@mastra/deployer-cloud 1.65.0-alpha.6 → 1.65.0-alpha.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.
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./core-B2OyzGRp.js","./engine-compile-BkERmzkH.js","./preload-helper-PPVm8Dsz.js","./engine-javascript-CSIo_1eZ.js","./html-C2L_23MC.js","./javascript-ySlJ1b_l.js","./css-BPhBrDlE.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./core-op51HA-s.js","./engine-compile-BkERmzkH.js","./preload-helper-PPVm8Dsz.js","./engine-javascript-CSIo_1eZ.js","./html-C2L_23MC.js","./javascript-ySlJ1b_l.js","./css-BPhBrDlE.js"])))=>i.map(i=>d[i]);
2
2
  import{_ as Va}from"./preload-helper-PPVm8Dsz.js";function SQt(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const s in r)if(s!=="default"&&!(s in e)){const a=Object.getOwnPropertyDescriptor(r,s);a&&Object.defineProperty(e,s,a.get?a:{enumerable:!0,get:()=>r[s]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}var jj=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Hl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var SX={exports:{}},fR={};var mMe;function kQt(){if(mMe)return fR;mMe=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,s,a){var i=null;if(a!==void 0&&(i=""+a),s.key!==void 0&&(i=""+s.key),"key"in s){a={};for(var l in s)l!=="key"&&(a[l]=s[l])}else a=s;return s=a.ref,{$$typeof:e,type:r,key:i,ref:s!==void 0?s:null,props:a}}return fR.Fragment=t,fR.jsx=n,fR.jsxs=n,fR}var gMe;function OQt(){return gMe||(gMe=1,SX.exports=kQt()),SX.exports}var o=OQt(),kX={exports:{}},Zr={},vMe;function CQt(){if(vMe)return Zr;vMe=1;var e={env:{}};var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),i=Symbol.for("react.consumer"),l=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),h=Symbol.for("react.activity"),p=Symbol.iterator;function m(F){return F===null||typeof F!="object"?null:(F=p&&F[p]||F["@@iterator"],typeof F=="function"?F:null)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y=Object.assign,b={};function x(F,R,U){this.props=F,this.context=R,this.refs=b,this.updater=U||v}x.prototype.isReactComponent={},x.prototype.setState=function(F,R){if(typeof F!="object"&&typeof F!="function"&&F!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,F,R,"setState")},x.prototype.forceUpdate=function(F){this.updater.enqueueForceUpdate(this,F,"forceUpdate")};function w(){}w.prototype=x.prototype;function k(F,R,U){this.props=F,this.context=R,this.refs=b,this.updater=U||v}var C=k.prototype=new w;C.constructor=k,y(C,x.prototype),C.isPureReactComponent=!0;var _=Array.isArray;function T(){}var E={H:null,A:null,T:null,S:null},N=Object.prototype.hasOwnProperty;function I(F,R,U){var Z=U.ref;return{$$typeof:t,type:F,key:R,ref:Z!==void 0?Z:null,props:U}}function A(F,R){return I(F.type,R,F.props)}function P(F){return typeof F=="object"&&F!==null&&F.$$typeof===t}function L(F){var R={"=":"=0",":":"=2"};return"$"+F.replace(/[=:]/g,function(U){return R[U]})}var D=/\/+/g;function B(F,R){return typeof F=="object"&&F!==null&&F.key!=null?L(""+F.key):R.toString(36)}function H(F){switch(F.status){case"fulfilled":return F.value;case"rejected":throw F.reason;default:switch(typeof F.status=="string"?F.then(T,T):(F.status="pending",F.then(function(R){F.status==="pending"&&(F.status="fulfilled",F.value=R)},function(R){F.status==="pending"&&(F.status="rejected",F.reason=R)})),F.status){case"fulfilled":return F.value;case"rejected":throw F.reason}}throw F}function q(F,R,U,Z,Y){var te=typeof F;(te==="undefined"||te==="boolean")&&(F=null);var J=!1;if(F===null)J=!0;else switch(te){case"bigint":case"string":case"number":J=!0;break;case"object":switch(F.$$typeof){case t:case n:J=!0;break;case f:return J=F._init,q(J(F._payload),R,U,Z,Y)}}if(J)return Y=Y(F),J=Z===""?"."+B(F,0):Z,_(Y)?(U="",J!=null&&(U=J.replace(D,"$&/")+"/"),q(Y,R,U,"",function(ae){return ae})):Y!=null&&(P(Y)&&(Y=A(Y,U+(Y.key==null||F&&F.key===Y.key?"":(""+Y.key).replace(D,"$&/")+"/")+J)),R.push(Y)),1;J=0;var ee=Z===""?".":Z+":";if(_(F))for(var re=0;re<F.length;re++)Z=F[re],te=ee+B(Z,re),J+=q(Z,R,U,te,Y);else if(re=m(F),typeof re=="function")for(F=re.call(F),re=0;!(Z=F.next()).done;)Z=Z.value,te=ee+B(Z,re++),J+=q(Z,R,U,te,Y);else if(te==="object"){if(typeof F.then=="function")return q(H(F),R,U,Z,Y);throw R=String(F),Error("Objects are not valid as a React child (found: "+(R==="[object Object]"?"object with keys {"+Object.keys(F).join(", ")+"}":R)+"). If you meant to render a collection of children, use an array instead.")}return J}function z(F,R,U){if(F==null)return F;var Z=[],Y=0;return q(F,Z,"","",function(te){return R.call(U,te,Y++)}),Z}function V(F){if(F._status===-1){var R=F._result;R=R(),R.then(function(U){(F._status===0||F._status===-1)&&(F._status=1,F._result=U)},function(U){(F._status===0||F._status===-1)&&(F._status=2,F._result=U)}),F._status===-1&&(F._status=0,F._result=R)}if(F._status===1)return F._result.default;throw F._result}var M=typeof reportError=="function"?reportError:function(F){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var R=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof F=="object"&&F!==null&&typeof F.message=="string"?String(F.message):String(F),error:F});if(!window.dispatchEvent(R))return}else if(typeof e=="object"&&typeof e.emit=="function"){e.emit("uncaughtException",F);return}console.error(F)},G={map:z,forEach:function(F,R,U){z(F,function(){R.apply(this,arguments)},U)},count:function(F){var R=0;return z(F,function(){R++}),R},toArray:function(F){return z(F,function(R){return R})||[]},only:function(F){if(!P(F))throw Error("React.Children.only expected to receive a single React element child.");return F}};return Zr.Activity=h,Zr.Children=G,Zr.Component=x,Zr.Fragment=r,Zr.Profiler=a,Zr.PureComponent=k,Zr.StrictMode=s,Zr.Suspense=u,Zr.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=E,Zr.__COMPILER_RUNTIME={__proto__:null,c:function(F){return E.H.useMemoCache(F)}},Zr.cache=function(F){return function(){return F.apply(null,arguments)}},Zr.cacheSignal=function(){return null},Zr.cloneElement=function(F,R,U){if(F==null)throw Error("The argument must be a React element, but you passed "+F+".");var Z=y({},F.props),Y=F.key;if(R!=null)for(te in R.key!==void 0&&(Y=""+R.key),R)!N.call(R,te)||te==="key"||te==="__self"||te==="__source"||te==="ref"&&R.ref===void 0||(Z[te]=R[te]);var te=arguments.length-2;if(te===1)Z.children=U;else if(1<te){for(var J=Array(te),ee=0;ee<te;ee++)J[ee]=arguments[ee+2];Z.children=J}return I(F.type,Y,Z)},Zr.createContext=function(F){return F={$$typeof:l,_currentValue:F,_currentValue2:F,_threadCount:0,Provider:null,Consumer:null},F.Provider=F,F.Consumer={$$typeof:i,_context:F},F},Zr.createElement=function(F,R,U){var Z,Y={},te=null;if(R!=null)for(Z in R.key!==void 0&&(te=""+R.key),R)N.call(R,Z)&&Z!=="key"&&Z!=="__self"&&Z!=="__source"&&(Y[Z]=R[Z]);var J=arguments.length-2;if(J===1)Y.children=U;else if(1<J){for(var ee=Array(J),re=0;re<J;re++)ee[re]=arguments[re+2];Y.children=ee}if(F&&F.defaultProps)for(Z in J=F.defaultProps,J)Y[Z]===void 0&&(Y[Z]=J[Z]);return I(F,te,Y)},Zr.createRef=function(){return{current:null}},Zr.forwardRef=function(F){return{$$typeof:c,render:F}},Zr.isValidElement=P,Zr.lazy=function(F){return{$$typeof:f,_payload:{_status:-1,_result:F},_init:V}},Zr.memo=function(F,R){return{$$typeof:d,type:F,compare:R===void 0?null:R}},Zr.startTransition=function(F){var R=E.T,U={};E.T=U;try{var Z=F(),Y=E.S;Y!==null&&Y(U,Z),typeof Z=="object"&&Z!==null&&typeof Z.then=="function"&&Z.then(T,M)}catch(te){M(te)}finally{R!==null&&U.types!==null&&(R.types=U.types),E.T=R}},Zr.unstable_useCacheRefresh=function(){return E.H.useCacheRefresh()},Zr.use=function(F){return E.H.use(F)},Zr.useActionState=function(F,R,U){return E.H.useActionState(F,R,U)},Zr.useCallback=function(F,R){return E.H.useCallback(F,R)},Zr.useContext=function(F){return E.H.useContext(F)},Zr.useDebugValue=function(){},Zr.useDeferredValue=function(F,R){return E.H.useDeferredValue(F,R)},Zr.useEffect=function(F,R){return E.H.useEffect(F,R)},Zr.useEffectEvent=function(F){return E.H.useEffectEvent(F)},Zr.useId=function(){return E.H.useId()},Zr.useImperativeHandle=function(F,R,U){return E.H.useImperativeHandle(F,R,U)},Zr.useInsertionEffect=function(F,R){return E.H.useInsertionEffect(F,R)},Zr.useLayoutEffect=function(F,R){return E.H.useLayoutEffect(F,R)},Zr.useMemo=function(F,R){return E.H.useMemo(F,R)},Zr.useOptimistic=function(F,R){return E.H.useOptimistic(F,R)},Zr.useReducer=function(F,R,U){return E.H.useReducer(F,R,U)},Zr.useRef=function(F){return E.H.useRef(F)},Zr.useState=function(F){return E.H.useState(F)},Zr.useSyncExternalStore=function(F,R,U){return E.H.useSyncExternalStore(F,R,U)},Zr.useTransition=function(){return E.H.useTransition()},Zr.version="19.2.7",Zr}var yMe;function nI(){return yMe||(yMe=1,kX.exports=CQt()),kX.exports}var g=nI();const qe=Hl(g),rI=SQt({__proto__:null,default:qe},[g]);var OX={exports:{}},hR={},CX={exports:{}},_X={};var bMe;function _Qt(){return bMe||(bMe=1,(function(e){function t(H,q){var z=H.length;H.push(q);e:for(;0<z;){var V=z-1>>>1,M=H[V];if(0<s(M,q))H[V]=q,H[z]=M,z=V;else break e}}function n(H){return H.length===0?null:H[0]}function r(H){if(H.length===0)return null;var q=H[0],z=H.pop();if(z!==q){H[0]=z;e:for(var V=0,M=H.length,G=M>>>1;V<G;){var F=2*(V+1)-1,R=H[F],U=F+1,Z=H[U];if(0>s(R,z))U<M&&0>s(Z,R)?(H[V]=Z,H[U]=z,V=U):(H[V]=R,H[F]=z,V=F);else if(U<M&&0>s(Z,z))H[V]=Z,H[U]=z,V=U;else break e}}return q}function s(H,q){var z=H.sortIndex-q.sortIndex;return z!==0?z:H.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var a=performance;e.unstable_now=function(){return a.now()}}else{var i=Date,l=i.now();e.unstable_now=function(){return i.now()-l}}var c=[],u=[],d=1,f=null,h=3,p=!1,m=!1,v=!1,y=!1,b=typeof setTimeout=="function"?setTimeout:null,x=typeof clearTimeout=="function"?clearTimeout:null,w=typeof setImmediate<"u"?setImmediate:null;function k(H){for(var q=n(u);q!==null;){if(q.callback===null)r(u);else if(q.startTime<=H)r(u),q.sortIndex=q.expirationTime,t(c,q);else break;q=n(u)}}function C(H){if(v=!1,k(H),!m)if(n(c)!==null)m=!0,_||(_=!0,P());else{var q=n(u);q!==null&&B(C,q.startTime-H)}}var _=!1,T=-1,E=5,N=-1;function I(){return y?!0:!(e.unstable_now()-N<E)}function A(){if(y=!1,_){var H=e.unstable_now();N=H;var q=!0;try{e:{m=!1,v&&(v=!1,x(T),T=-1),p=!0;var z=h;try{t:{for(k(H),f=n(c);f!==null&&!(f.expirationTime>H&&I());){var V=f.callback;if(typeof V=="function"){f.callback=null,h=f.priorityLevel;var M=V(f.expirationTime<=H);if(H=e.unstable_now(),typeof M=="function"){f.callback=M,k(H),q=!0;break t}f===n(c)&&r(c),k(H)}else r(c);f=n(c)}if(f!==null)q=!0;else{var G=n(u);G!==null&&B(C,G.startTime-H),q=!1}}break e}finally{f=null,h=z,p=!1}q=void 0}}finally{q?P():_=!1}}}var P;if(typeof w=="function")P=function(){w(A)};else if(typeof MessageChannel<"u"){var L=new MessageChannel,D=L.port2;L.port1.onmessage=A,P=function(){D.postMessage(null)}}else P=function(){b(A,0)};function B(H,q){T=b(function(){H(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(H){H.callback=null},e.unstable_forceFrameRate=function(H){0>H||125<H?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):E=0<H?Math.floor(1e3/H):5},e.unstable_getCurrentPriorityLevel=function(){return h},e.unstable_next=function(H){switch(h){case 1:case 2:case 3:var q=3;break;default:q=h}var z=h;h=q;try{return H()}finally{h=z}},e.unstable_requestPaint=function(){y=!0},e.unstable_runWithPriority=function(H,q){switch(H){case 1:case 2:case 3:case 4:case 5:break;default:H=3}var z=h;h=H;try{return q()}finally{h=z}},e.unstable_scheduleCallback=function(H,q,z){var V=e.unstable_now();switch(typeof z=="object"&&z!==null?(z=z.delay,z=typeof z=="number"&&0<z?V+z:V):z=V,H){case 1:var M=-1;break;case 2:M=250;break;case 5:M=1073741823;break;case 4:M=1e4;break;default:M=5e3}return M=z+M,H={id:d++,callback:q,priorityLevel:H,startTime:z,expirationTime:M,sortIndex:-1},z>V?(H.sortIndex=z,t(u,H),n(c)===null&&H===n(u)&&(v?(x(T),T=-1):v=!0,B(C,z-V))):(H.sortIndex=M,t(c,H),m||p||(m=!0,_||(_=!0,P()))),H},e.unstable_shouldYield=I,e.unstable_wrapCallback=function(H){var q=h;return function(){var z=h;h=q;try{return H.apply(this,arguments)}finally{h=z}}}})(_X)),_X}var xMe;function EQt(){return xMe||(xMe=1,CX.exports=_Qt()),CX.exports}var EX={exports:{}},Au={};var wMe;function TQt(){if(wMe)return Au;wMe=1;var e=nI();function t(c){var u="https://react.dev/errors/"+c;if(1<arguments.length){u+="?args[]="+encodeURIComponent(arguments[1]);for(var d=2;d<arguments.length;d++)u+="&args[]="+encodeURIComponent(arguments[d])}return"Minified React error #"+c+"; visit "+u+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function n(){}var r={d:{f:n,r:function(){throw Error(t(522))},D:n,C:n,L:n,m:n,X:n,S:n,M:n},p:0,findDOMNode:null},s=Symbol.for("react.portal");function a(c,u,d){var f=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:s,key:f==null?null:""+f,children:c,containerInfo:u,implementation:d}}var i=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function l(c,u){if(c==="font")return"";if(typeof u=="string")return u==="use-credentials"?u:""}return Au.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,Au.createPortal=function(c,u){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!u||u.nodeType!==1&&u.nodeType!==9&&u.nodeType!==11)throw Error(t(299));return a(c,u,null,d)},Au.flushSync=function(c){var u=i.T,d=r.p;try{if(i.T=null,r.p=2,c)return c()}finally{i.T=u,r.p=d,r.d.f()}},Au.preconnect=function(c,u){typeof c=="string"&&(u?(u=u.crossOrigin,u=typeof u=="string"?u==="use-credentials"?u:"":void 0):u=null,r.d.C(c,u))},Au.prefetchDNS=function(c){typeof c=="string"&&r.d.D(c)},Au.preinit=function(c,u){if(typeof c=="string"&&u&&typeof u.as=="string"){var d=u.as,f=l(d,u.crossOrigin),h=typeof u.integrity=="string"?u.integrity:void 0,p=typeof u.fetchPriority=="string"?u.fetchPriority:void 0;d==="style"?r.d.S(c,typeof u.precedence=="string"?u.precedence:void 0,{crossOrigin:f,integrity:h,fetchPriority:p}):d==="script"&&r.d.X(c,{crossOrigin:f,integrity:h,fetchPriority:p,nonce:typeof u.nonce=="string"?u.nonce:void 0})}},Au.preinitModule=function(c,u){if(typeof c=="string")if(typeof u=="object"&&u!==null){if(u.as==null||u.as==="script"){var d=l(u.as,u.crossOrigin);r.d.M(c,{crossOrigin:d,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0})}}else u==null&&r.d.M(c)},Au.preload=function(c,u){if(typeof c=="string"&&typeof u=="object"&&u!==null&&typeof u.as=="string"){var d=u.as,f=l(d,u.crossOrigin);r.d.L(c,d,{crossOrigin:f,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0,type:typeof u.type=="string"?u.type:void 0,fetchPriority:typeof u.fetchPriority=="string"?u.fetchPriority:void 0,referrerPolicy:typeof u.referrerPolicy=="string"?u.referrerPolicy:void 0,imageSrcSet:typeof u.imageSrcSet=="string"?u.imageSrcSet:void 0,imageSizes:typeof u.imageSizes=="string"?u.imageSizes:void 0,media:typeof u.media=="string"?u.media:void 0})}},Au.preloadModule=function(c,u){if(typeof c=="string")if(u){var d=l(u.as,u.crossOrigin);r.d.m(c,{as:typeof u.as=="string"&&u.as!=="script"?u.as:void 0,crossOrigin:d,integrity:typeof u.integrity=="string"?u.integrity:void 0})}else r.d.m(c)},Au.requestFormReset=function(c){r.d.r(c)},Au.unstable_batchedUpdates=function(c,u){return c(u)},Au.useFormState=function(c,u,d){return i.H.useFormState(c,u,d)},Au.useFormStatus=function(){return i.H.useHostTransitionStatus()},Au.version="19.2.7",Au}var SMe;function xct(){if(SMe)return EX.exports;SMe=1;function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),EX.exports=TQt(),EX.exports}var kMe;function jQt(){if(kMe)return hR;kMe=1;var e={env:{}};var t=EQt(),n=nI(),r=xct();function s(S){var O="https://react.dev/errors/"+S;if(1<arguments.length){O+="?args[]="+encodeURIComponent(arguments[1]);for(var j=2;j<arguments.length;j++)O+="&args[]="+encodeURIComponent(arguments[j])}return"Minified React error #"+S+"; visit "+O+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function a(S){return!(!S||S.nodeType!==1&&S.nodeType!==9&&S.nodeType!==11)}function i(S){var O=S,j=S;if(S.alternate)for(;O.return;)O=O.return;else{S=O;do O=S,(O.flags&4098)!==0&&(j=O.return),S=O.return;while(S)}return O.tag===3?j:null}function l(S){if(S.tag===13){var O=S.memoizedState;if(O===null&&(S=S.alternate,S!==null&&(O=S.memoizedState)),O!==null)return O.dehydrated}return null}function c(S){if(S.tag===31){var O=S.memoizedState;if(O===null&&(S=S.alternate,S!==null&&(O=S.memoizedState)),O!==null)return O.dehydrated}return null}function u(S){if(i(S)!==S)throw Error(s(188))}function d(S){var O=S.alternate;if(!O){if(O=i(S),O===null)throw Error(s(188));return O!==S?null:S}for(var j=S,$=O;;){var W=j.return;if(W===null)break;var Q=W.alternate;if(Q===null){if($=W.return,$!==null){j=$;continue}break}if(W.child===Q.child){for(Q=W.child;Q;){if(Q===j)return u(W),S;if(Q===$)return u(W),O;Q=Q.sibling}throw Error(s(188))}if(j.return!==$.return)j=W,$=Q;else{for(var oe=!1,we=W.child;we;){if(we===j){oe=!0,j=W,$=Q;break}if(we===$){oe=!0,$=W,j=Q;break}we=we.sibling}if(!oe){for(we=Q.child;we;){if(we===j){oe=!0,j=Q,$=W;break}if(we===$){oe=!0,$=Q,j=W;break}we=we.sibling}if(!oe)throw Error(s(189))}}if(j.alternate!==$)throw Error(s(190))}if(j.tag!==3)throw Error(s(188));return j.stateNode.current===j?S:O}function f(S){var O=S.tag;if(O===5||O===26||O===27||O===6)return S;for(S=S.child;S!==null;){if(O=f(S),O!==null)return O;S=S.sibling}return null}var h=Object.assign,p=Symbol.for("react.element"),m=Symbol.for("react.transitional.element"),v=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),b=Symbol.for("react.strict_mode"),x=Symbol.for("react.profiler"),w=Symbol.for("react.consumer"),k=Symbol.for("react.context"),C=Symbol.for("react.forward_ref"),_=Symbol.for("react.suspense"),T=Symbol.for("react.suspense_list"),E=Symbol.for("react.memo"),N=Symbol.for("react.lazy"),I=Symbol.for("react.activity"),A=Symbol.for("react.memo_cache_sentinel"),P=Symbol.iterator;function L(S){return S===null||typeof S!="object"?null:(S=P&&S[P]||S["@@iterator"],typeof S=="function"?S:null)}var D=Symbol.for("react.client.reference");function B(S){if(S==null)return null;if(typeof S=="function")return S.$$typeof===D?null:S.displayName||S.name||null;if(typeof S=="string")return S;switch(S){case y:return"Fragment";case x:return"Profiler";case b:return"StrictMode";case _:return"Suspense";case T:return"SuspenseList";case I:return"Activity"}if(typeof S=="object")switch(S.$$typeof){case v:return"Portal";case k:return S.displayName||"Context";case w:return(S._context.displayName||"Context")+".Consumer";case C:var O=S.render;return S=S.displayName,S||(S=O.displayName||O.name||"",S=S!==""?"ForwardRef("+S+")":"ForwardRef"),S;case E:return O=S.displayName||null,O!==null?O:B(S.type)||"Memo";case N:O=S._payload,S=S._init;try{return B(S(O))}catch{}}return null}var H=Array.isArray,q=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,z=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,V={pending:!1,data:null,method:null,action:null},M=[],G=-1;function F(S){return{current:S}}function R(S){0>G||(S.current=M[G],M[G]=null,G--)}function U(S,O){G++,M[G]=S.current,S.current=O}var Z=F(null),Y=F(null),te=F(null),J=F(null);function ee(S,O){switch(U(te,O),U(Y,S),U(Z,null),O.nodeType){case 9:case 11:S=(S=O.documentElement)&&(S=S.namespaceURI)?L2e(S):0;break;default:if(S=O.tagName,O=O.namespaceURI)O=L2e(O),S=F2e(O,S);else switch(S){case"svg":S=1;break;case"math":S=2;break;default:S=0}}R(Z),U(Z,S)}function re(){R(Z),R(Y),R(te)}function ae(S){S.memoizedState!==null&&U(J,S);var O=Z.current,j=F2e(O,S.type);O!==j&&(U(Y,S),U(Z,j))}function X(S){Y.current===S&&(R(Z),R(Y)),J.current===S&&(R(J),lR._currentValue=V)}var ne,se;function ce(S){if(ne===void 0)try{throw Error()}catch(j){var O=j.stack.trim().match(/\n( *(at )?)/);ne=O&&O[1]||"",se=-1<j.stack.indexOf(`
3
3
  at`)?" (<anonymous>)":-1<j.stack.indexOf("@")?"@unknown:0:0":""}return`
4
4
  `+ne+S+se}var le=!1;function be(S,O){if(!S||le)return"";le=!0;var j=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var $={DetermineComponentFrameRoot:function(){try{if(O){var At=function(){throw Error()};if(Object.defineProperty(At.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(At,[])}catch(gt){var ct=gt}Reflect.construct(S,[],At)}else{try{At.call()}catch(gt){ct=gt}S.call(At.prototype)}}else{try{throw Error()}catch(gt){ct=gt}(At=S())&&typeof At.catch=="function"&&At.catch(function(){})}}catch(gt){if(gt&&ct&&typeof gt.stack=="string")return[gt.stack,ct.stack]}return[null,null]}};$.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var W=Object.getOwnPropertyDescriptor($.DetermineComponentFrameRoot,"name");W&&W.configurable&&Object.defineProperty($.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var Q=$.DetermineComponentFrameRoot(),oe=Q[0],we=Q[1];if(oe&&we){var We=oe.split(`
@@ -231,7 +231,7 @@ attempted value: ${i}
231
231
  \${}
232
232
  }
233
233
  }`,{label:"class",detail:"definition",type:"keyword"}),df('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),df('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],ukt=hOe.concat([df("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),df("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),df("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),v9e=new pwt,dkt=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function FR(e){return(t,n)=>{let r=t.node.getChild("VariableDefinition");return r&&n(r,e),!0}}const $qn=["FunctionDeclaration"],Mqn={FunctionDeclaration:FR("function"),ClassDeclaration:FR("class"),ClassExpression:()=>!0,EnumDeclaration:FR("constant"),TypeAliasDeclaration:FR("type"),NamespaceDeclaration:FR("namespace"),VariableDefinition(e,t){e.matchContext($qn)||t(e,"variable")},TypeDefinition(e,t){t(e,"type")},__proto__:null};function fkt(e,t){let n=v9e.get(t);if(n)return n;let r=[],s=!0;function a(i,l){let c=e.sliceString(i.from,i.to);r.push({label:c,type:l})}return t.cursor(Ha.IncludeAnonymous).iterate(i=>{if(s)s=!1;else if(i.name){let l=Mqn[i.name];if(l&&l(i,a)||dkt.has(i.name))return!1}else if(i.to-i.from>8192){for(let l of fkt(e,i.node))r.push(l);return!1}}),v9e.set(t,r),r}const GB=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,pOe=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function hkt(e){let t=xi(e.state).resolveInner(e.pos,-1);if(pOe.indexOf(t.name)>-1)return null;let n=t.name=="VariableName"||t.to-t.from<20&&GB.test(e.state.sliceDoc(t.from,t.to));if(!n&&!e.explicit)return null;let r=[];for(let s=t;s;s=s.parent)dkt.has(s.name)&&(r=r.concat(fkt(e.state.doc,s)));return{options:r,from:n?t.from:e.pos,validFor:GB}}function dte(e,t,n){var r;let s=[];for(;;){let a=t.firstChild,i;if(a?.name=="VariableName")return s.push(e(a)),{path:s.reverse(),name:n};if(a?.name=="MemberExpression"&&((r=i=a.lastChild)===null||r===void 0?void 0:r.name)=="PropertyName")s.push(e(i)),t=a;else return null}}function pkt(e){let t=r=>e.state.doc.sliceString(r.from,r.to),n=xi(e.state).resolveInner(e.pos,-1);return n.name=="PropertyName"?dte(t,n.parent,t(n)):(n.name=="."||n.name=="?.")&&n.parent.name=="MemberExpression"?dte(t,n.parent,""):pOe.indexOf(n.name)>-1?null:n.name=="VariableName"||n.to-n.from<20&&GB.test(t(n))?{path:[],name:t(n)}:n.name=="MemberExpression"?dte(t,n,""):e.explicit?{path:[],name:""}:null}function Dqn(e,t){let n=e,r=[],s=new Set;for(let a=0;;a++){for(let l of(Object.getOwnPropertyNames||Object.keys)(e)){if(!/^[a-zA-Z_$\xaa-\uffdc][\w$\xaa-\uffdc]*$/.test(l)||s.has(l))continue;s.add(l);let c;try{c=n[l]}catch{continue}r.push({label:l,type:typeof c=="function"?/^[A-Z]/.test(l)?"class":t?"function":"method":t?"variable":"property",boost:-a})}let i=Object.getPrototypeOf(e);if(!i)return r;e=i}}function Lqn(e){let t=new Map;return n=>{let r=pkt(n);if(!r)return null;let s=e;for(let i of r.path)if(s=s[i],!s)return null;let a=t.get(s);return a||t.set(s,a=Dqn(s,!r.path.length)),{from:n.pos-r.name.length,options:a,validFor:GB}}}const im=XO.define({name:"javascript",parser:Pqn.configure({props:[o_.add({IfStatement:lj({except:/^\s*({|else\b)/}),TryStatement:lj({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:A9n,SwitchBody:e=>{let t=e.textAfter,n=/^\s*\}/.test(t),r=/^\s*(case|default)\b/.test(t);return e.baseIndent+(n?0:r?1:2)*e.unit},Block:I9n({closing:"}"}),ArrowFunction:e=>e.baseIndent+e.unit,"TemplateString BlockComment":()=>null,"Statement Property":lj({except:/^\s*{/}),JSXElement(e){let t=/^\s*<\//.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},JSXEscape(e){let t=/\s*\}/.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},"JSXOpenTag JSXSelfClosingTag"(e){return e.column(e.node.from)+e.unit}}),l_.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":Zke,BlockComment(e){return{from:e.from+2,to:e.to-2}},JSXElement(e){let t=e.firstChild;if(!t||t.name=="JSXSelfClosingTag")return null;let n=e.lastChild;return{from:t.to,to:n.type.isError?e.to:n.from}},"JSXSelfClosingTag JSXOpenTag"(e){var t;let n=(t=e.firstChild)===null||t===void 0?void 0:t.nextSibling,r=e.lastChild;return!n||n.type.isError?null:{from:n.to,to:r.type.isError?e.to:r.from}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),mkt={test:e=>/^JSX/.test(e.name),facet:uW({commentTokens:{block:{open:"{/*",close:"*/}"}}})},mOe=im.configure({dialect:"ts"},"typescript"),gOe=im.configure({dialect:"jsx",props:[Vke.add(e=>e.isTop?[mkt]:void 0)]}),vOe=im.configure({dialect:"jsx ts",props:[Vke.add(e=>e.isTop?[mkt]:void 0)]},"typescript");let gkt=e=>({label:e,type:"keyword"});const vkt="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(gkt),Fqn=vkt.concat(["declare","implements","private","protected","public"].map(gkt));function QB(e={}){let t=e.jsx?e.typescript?vOe:gOe:e.typescript?mOe:im,n=e.typescript?ukt.concat(Fqn):hOe.concat(vkt);return new eC(t,[im.data.of({autocomplete:v7n(pOe,mSt(n))}),im.data.of({autocomplete:hkt}),e.jsx?ykt:[]])}function zqn(e){for(;;){if(e.name=="JSXOpenTag"||e.name=="JSXSelfClosingTag"||e.name=="JSXFragmentTag")return e;if(e.name=="JSXEscape"||!e.parent)return null;e=e.parent}}function y9e(e,t,n=e.length){for(let r=t?.firstChild;r;r=r.nextSibling)if(r.name=="JSXIdentifier"||r.name=="JSXBuiltin"||r.name=="JSXNamespacedName"||r.name=="JSXMemberExpression")return e.sliceString(r.from,Math.min(r.to,n));return""}const Bqn=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),ykt=Pt.inputHandler.of((e,t,n,r,s)=>{if((Bqn?e.composing:e.compositionStarted)||e.state.readOnly||t!=n||r!=">"&&r!="/"||!im.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:i}=a,l=i.changeByRange(c=>{var u;let{head:d}=c,f=xi(i).resolveInner(d-1,-1),h;if(f.name=="JSXStartTag"&&(f=f.parent),!(i.doc.sliceString(d-1,d)!=r||f.name=="JSXAttributeValue"&&f.to>d)){if(r==">"&&f.name=="JSXFragmentTag")return{range:c,changes:{from:d,insert:"</>"}};if(r=="/"&&f.name=="JSXStartCloseTag"){let p=f.parent,m=p.parent;if(m&&p.from==d-2&&((h=y9e(i.doc,m.firstChild,d))||((u=m.firstChild)===null||u===void 0?void 0:u.name)=="JSXFragmentTag")){let v=`${h}>`;return{range:St.cursor(d+v.length,-1),changes:{from:d,insert:v}}}}else if(r==">"){let p=zqn(f);if(p&&p.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(i.doc.sliceString(d,d+2))&&(h=y9e(i.doc,p,d)))return{range:c,changes:{from:d,insert:`</${h}>`}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,i.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)});function Uqn(e,t){return t||(t={parserOptions:{ecmaVersion:2019,sourceType:"module"},env:{browser:!0,node:!0,es6:!0,es2015:!0,es2017:!0,es2020:!0},rules:{}},e.getRules().forEach((n,r)=>{var s;!((s=n.meta.docs)===null||s===void 0)&&s.recommended&&(t.rules[r]=2)})),n=>{let{state:r}=n,s=[];for(let{from:a,to:i}of im.findRegions(r)){let l=r.doc.lineAt(a),c={line:l.number-1,col:a-l.from,pos:a};for(let u of e.verify(r.sliceDoc(a,i),t))s.push(qqn(u,r.doc,c))}return s}}function b9e(e,t,n,r){return n.line(e+r.line).from+t+(e==1?r.col-1:-1)}function qqn(e,t,n){let r=b9e(e.line,e.column,t,n),s={from:r,to:e.endLine!=null&&e.endColumn!=1?b9e(e.endLine,e.endColumn,t,n):r,message:e.message,source:e.ruleId?"eslint:"+e.ruleId:"eslint",severity:e.severity==1?"warning":"error"};if(e.fix){let{range:a,text:i}=e.fix,l=a[0]+n.pos-r,c=a[1]+n.pos-r;s.actions=[{name:"fix",apply(u,d){u.dispatch({changes:{from:d+l,to:d+c,insert:i},scrollIntoView:!0})}}]}return s}const wF=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:ykt,completionPath:pkt,esLint:Uqn,javascript:QB,javascriptLanguage:im,jsxLanguage:gOe,localCompletionSource:hkt,scopeCompletionSource:Lqn,snippets:hOe,tsxLanguage:vOe,typescriptLanguage:mOe,typescriptSnippets:ukt},Symbol.toStringTag,{value:"Module"})),zR=["_blank","_self","_top","_parent"],fte=["ascii","utf-8","utf-16","latin1","latin1"],hte=["get","post","put","delete"],pte=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],dh=["true","false"],Jn={},Vqn={a:{attrs:{href:null,ping:null,type:null,media:null,target:zR,hreflang:null}},abbr:Jn,address:Jn,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:Jn,aside:Jn,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:Jn,base:{attrs:{href:null,target:zR}},bdi:Jn,bdo:Jn,blockquote:{attrs:{cite:null}},body:Jn,br:Jn,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:pte,formmethod:hte,formnovalidate:["novalidate"],formtarget:zR,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:Jn,center:Jn,cite:Jn,code:Jn,col:{attrs:{span:null}},colgroup:{attrs:{span:null}},command:{attrs:{type:["command","checkbox","radio"],label:null,icon:null,radiogroup:null,command:null,title:null,disabled:["disabled"],checked:["checked"]}},data:{attrs:{value:null}},datagrid:{attrs:{disabled:["disabled"],multiple:["multiple"]}},datalist:{attrs:{data:null}},dd:Jn,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:Jn,div:Jn,dl:Jn,dt:Jn,em:Jn,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:Jn,figure:Jn,footer:Jn,form:{attrs:{action:null,name:null,"accept-charset":fte,autocomplete:["on","off"],enctype:pte,method:hte,novalidate:["novalidate"],target:zR}},h1:Jn,h2:Jn,h3:Jn,h4:Jn,h5:Jn,h6:Jn,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:Jn,hgroup:Jn,hr:Jn,html:{attrs:{manifest:null}},i:Jn,iframe:{attrs:{src:null,srcdoc:null,name:null,width:null,height:null,sandbox:["allow-top-navigation","allow-same-origin","allow-forms","allow-scripts"],seamless:["seamless"]}},img:{attrs:{alt:null,src:null,ismap:null,usemap:null,width:null,height:null,crossorigin:["anonymous","use-credentials"]}},input:{attrs:{alt:null,dirname:null,form:null,formaction:null,height:null,list:null,max:null,maxlength:null,min:null,name:null,pattern:null,placeholder:null,size:null,src:null,step:null,value:null,width:null,accept:["audio/*","video/*","image/*"],autocomplete:["on","off"],autofocus:["autofocus"],checked:["checked"],disabled:["disabled"],formenctype:pte,formmethod:hte,formnovalidate:["novalidate"],formtarget:zR,multiple:["multiple"],readonly:["readonly"],required:["required"],type:["hidden","text","search","tel","url","email","password","datetime","date","month","week","time","datetime-local","number","range","color","checkbox","radio","file","submit","image","reset","button"]}},ins:{attrs:{cite:null,datetime:null}},kbd:Jn,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:Jn,li:{attrs:{value:null}},link:{attrs:{href:null,type:null,hreflang:null,media:null,sizes:["all","16x16","16x16 32x32","16x16 32x32 64x64"]}},map:{attrs:{name:null}},mark:Jn,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:fte,name:["viewport","application-name","author","description","generator","keywords"],"http-equiv":["content-language","content-type","default-style","refresh"]}},meter:{attrs:{value:null,min:null,low:null,high:null,max:null,optimum:null}},nav:Jn,noscript:Jn,object:{attrs:{data:null,type:null,name:null,usemap:null,form:null,width:null,height:null,typemustmatch:["typemustmatch"]}},ol:{attrs:{reversed:["reversed"],start:null,type:["1","a","A","i","I"]},children:["li","script","template","ul","ol"]},optgroup:{attrs:{disabled:["disabled"],label:null}},option:{attrs:{disabled:["disabled"],label:null,selected:["selected"],value:null}},output:{attrs:{for:null,form:null,name:null}},p:Jn,param:{attrs:{name:null,value:null}},pre:Jn,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:Jn,rt:Jn,ruby:Jn,samp:Jn,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:fte}},section:Jn,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:Jn,source:{attrs:{src:null,type:null,media:null}},span:Jn,strong:Jn,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:Jn,summary:Jn,sup:Jn,table:Jn,tbody:Jn,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:Jn,textarea:{attrs:{dirname:null,form:null,maxlength:null,name:null,placeholder:null,rows:null,cols:null,autofocus:["autofocus"],disabled:["disabled"],readonly:["readonly"],required:["required"],wrap:["soft","hard"]}},tfoot:Jn,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:Jn,time:{attrs:{datetime:null}},title:Jn,tr:Jn,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:Jn,video:{attrs:{src:null,poster:null,width:null,height:null,crossorigin:["anonymous","use-credentials"],preload:["auto","metadata","none"],autoplay:["autoplay"],mediagroup:["movie"],muted:["muted"],controls:["controls"]}},wbr:Jn},bkt={accesskey:null,class:null,contenteditable:dh,contextmenu:null,dir:["ltr","rtl","auto"],draggable:["true","false","auto"],dropzone:["copy","move","link","string:","file:"],hidden:["hidden"],id:null,inert:["inert"],itemid:null,itemprop:null,itemref:null,itemscope:["itemscope"],itemtype:null,lang:["ar","bn","de","en-GB","en-US","es","fr","hi","id","ja","pa","pt","ru","tr","zh"],spellcheck:dh,autocorrect:dh,autocapitalize:dh,style:null,tabindex:null,title:null,translate:["yes","no"],rel:["stylesheet","alternate","author","bookmark","help","license","next","nofollow","noreferrer","prefetch","prev","search","tag"],role:"alert application article banner button cell checkbox complementary contentinfo dialog document feed figure form grid gridcell heading img list listbox listitem main navigation region row rowgroup search switch tab table tabpanel textbox timer".split(" "),"aria-activedescendant":null,"aria-atomic":dh,"aria-autocomplete":["inline","list","both","none"],"aria-busy":dh,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":dh,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":dh,"aria-hidden":dh,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":dh,"aria-multiselectable":dh,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":dh,"aria-relevant":null,"aria-required":dh,"aria-selected":["true","false","undefined"],"aria-setsize":null,"aria-sort":["ascending","descending","none","other"],"aria-valuemax":null,"aria-valuemin":null,"aria-valuenow":null,"aria-valuetext":null},xkt="beforeunload copy cut dragstart dragover dragleave dragenter dragend drag paste focus blur change click load mousedown mouseenter mouseleave mouseup keydown keyup resize scroll unload".split(" ").map(e=>"on"+e);for(let e of xkt)bkt[e]=null;class DM{constructor(t,n){this.tags={...Vqn,...t},this.globalAttrs={...bkt,...n},this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}}DM.default=new DM;function sN(e,t,n=e.length){if(!t)return"";let r=t.firstChild,s=r&&r.getChild("TagName");return s?e.sliceString(s.from,Math.min(s.to,n)):""}function aN(e,t=!1){for(;e;e=e.parent)if(e.name=="Element")if(t)t=!1;else return e;return null}function wkt(e,t,n){let r=n.tags[sN(e,aN(t))];return r?.children||n.allTags}function yOe(e,t){let n=[];for(let r=aN(t);r&&!r.type.isTop;r=aN(r.parent)){let s=sN(e,r);if(s&&r.lastChild.name=="CloseTag")break;s&&n.indexOf(s)<0&&(t.name=="EndTag"||t.from>=r.firstChild.to)&&n.push(s)}return n}const Skt=/^[:\-\.\w\u00b7-\uffff]*$/;function x9e(e,t,n,r,s){let a=/\s*>/.test(e.sliceDoc(s,s+5))?"":">",i=aN(n,n.name=="StartTag"||n.name=="TagName");return{from:r,to:s,options:wkt(e.doc,i,t).map(l=>({label:l,type:"type"})).concat(yOe(e.doc,n).map((l,c)=>({label:"/"+l,apply:"/"+l+a,type:"type",boost:99-c}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function w9e(e,t,n,r){let s=/\s*>/.test(e.sliceDoc(r,r+5))?"":">";return{from:n,to:r,options:yOe(e.doc,t).map((a,i)=>({label:a,apply:a+s,type:"type",boost:99-i})),validFor:Skt}}function Hqn(e,t,n,r){let s=[],a=0;for(let i of wkt(e.doc,n,t))s.push({label:"<"+i,type:"type"});for(let i of yOe(e.doc,n))s.push({label:"</"+i+">",type:"type",boost:99-a++});return{from:r,to:r,options:s,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function Wqn(e,t,n,r,s){let a=aN(n),i=a?t.tags[sN(e.doc,a)]:null,l=i&&i.attrs?Object.keys(i.attrs):[],c=i&&i.globalAttrs===!1?l:l.length?l.concat(t.globalAttrNames):t.globalAttrNames;return{from:r,to:s,options:c.map(u=>({label:u,type:"property"})),validFor:Skt}}function Zqn(e,t,n,r,s){var a;let i=(a=n.parent)===null||a===void 0?void 0:a.getChild("AttributeName"),l=[],c;if(i){let u=e.sliceDoc(i.from,i.to),d=t.globalAttrs[u];if(!d){let f=aN(n),h=f?t.tags[sN(e.doc,f)]:null;d=h?.attrs&&h.attrs[u]}if(d){let f=e.sliceDoc(r,s).toLowerCase(),h='"',p='"';/^['"]/.test(f)?(c=f[0]=='"'?/^[^"]*$/:/^[^']*$/,h="",p=e.sliceDoc(s,s+1)==f[0]?"":f[0],f=f.slice(1),r++):c=/^[^\s<>='"]*$/;for(let m of d)l.push({label:m,apply:h+m+p,type:"constant"})}}return{from:r,to:s,options:l,validFor:c}}function kkt(e,t){let{state:n,pos:r}=t,s=xi(n).resolveInner(r,-1),a=s.resolve(r);for(let i=r,l;a==s&&(l=s.childBefore(i));){let c=l.lastChild;if(!c||!c.type.isError||c.from<c.to)break;a=s=l,i=c.from}return s.name=="TagName"?s.parent&&/CloseTag$/.test(s.parent.name)?w9e(n,s,s.from,r):x9e(n,e,s,s.from,r):s.name=="StartTag"||s.name=="IncompleteTag"?x9e(n,e,s,r,r):s.name=="StartCloseTag"||s.name=="IncompleteCloseTag"?w9e(n,s,r,r):s.name=="OpenTag"||s.name=="SelfClosingTag"||s.name=="AttributeName"?Wqn(n,e,s,s.name=="AttributeName"?s.from:r,r):s.name=="Is"||s.name=="AttributeValue"||s.name=="UnquotedAttributeValue"?Zqn(n,e,s,s.name=="Is"?r:s.from,r):t.explicit&&(a.name=="Element"||a.name=="Text"||a.name=="Document")?Hqn(n,e,s,r):null}function Gqn(e){return kkt(DM.default,e)}function Qqn(e){let{extraTags:t,extraGlobalAttributes:n}=e,r=n||t?new DM(t,n):DM.default;return s=>kkt(r,s)}const Yqn=im.parser.configure({top:"SingleExpression"}),Okt=[{tag:"script",attrs:e=>e.type=="text/typescript"||e.lang=="ts",parser:mOe.parser},{tag:"script",attrs:e=>e.type=="text/babel"||e.type=="text/jsx",parser:gOe.parser},{tag:"script",attrs:e=>e.type=="text/typescript-jsx",parser:vOe.parser},{tag:"script",attrs(e){return/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(e.type)},parser:Yqn},{tag:"script",attrs(e){return!e.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(e.type)},parser:im.parser},{tag:"style",attrs(e){return(!e.lang||e.lang=="css")&&(!e.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(e.type))},parser:ZB.parser}],Ckt=[{name:"style",parser:ZB.parser.configure({top:"Styles"})}].concat(xkt.map(e=>({name:e,parser:im.parser}))),_kt=XO.define({name:"html",parser:wUn.configure({props:[o_.add({Element(e){let t=/^(\s*)(<\/)?/.exec(e.textAfter);return e.node.to<=e.pos+t[0].length?e.continue():e.lineIndent(e.node.from)+(t[2]?0:e.unit)},"OpenTag CloseTag SelfClosingTag"(e){return e.column(e.node.from)+e.unit},Document(e){if(e.pos+/\s*/.exec(e.textAfter)[0].length<e.node.to)return e.continue();let t=null,n;for(let r=e.node;;){let s=r.lastChild;if(!s||s.name!="Element"||s.to!=r.to)break;t=r=s}return t&&!((n=t.lastChild)&&(n.name=="CloseTag"||n.name=="SelfClosingTag"))?e.lineIndent(t.from)+e.unit:null}}),l_.add({Element(e){let t=e.firstChild,n=e.lastChild;return!t||t.name!="OpenTag"?null:{from:t.to,to:n.name=="CloseTag"?n.from:e.to}}}),lSt.add({"OpenTag CloseTag":e=>e.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:"<!--",close:"-->"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-_"}}),e9=_kt.configure({wrap:rkt(Okt,Ckt)});function Kqn(e={}){let t="",n;e.matchClosingTags===!1&&(t="noMatch"),e.selfClosingTags===!0&&(t=(t?t+" ":"")+"selfClosing"),(e.nestedLanguages&&e.nestedLanguages.length||e.nestedAttributes&&e.nestedAttributes.length)&&(n=rkt((e.nestedLanguages||[]).concat(Okt),(e.nestedAttributes||[]).concat(Ckt)));let r=n?_kt.configure({wrap:n,dialect:t}):t?e9.configure({dialect:t}):e9;return new eC(r,[e9.data.of({autocomplete:Qqn(e)}),e.autoCloseTags!==!1?Xqn:[],QB().support,rqn().support])}const S9e=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" ")),Xqn=Pt.inputHandler.of((e,t,n,r,s)=>{if(e.composing||e.state.readOnly||t!=n||r!=">"&&r!="/"||!e9.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:i}=a,l=i.changeByRange(c=>{var u,d,f;let h=i.doc.sliceString(c.from-1,c.to)==r,{head:p}=c,m=xi(i).resolveInner(p,-1),v;if(h&&r==">"&&m.name=="EndTag"){let y=m.parent;if(((d=(u=y.parent)===null||u===void 0?void 0:u.lastChild)===null||d===void 0?void 0:d.name)!="CloseTag"&&(v=sN(i.doc,y.parent,p))&&!S9e.has(v)){let b=p+(i.doc.sliceString(p,p+1)===">"?1:0),x=`</${v}>`;return{range:c,changes:{from:p,to:b,insert:x}}}}else if(h&&r=="/"&&m.name=="IncompleteCloseTag"){let y=m.parent;if(m.from==p-2&&((f=y.lastChild)===null||f===void 0?void 0:f.name)!="CloseTag"&&(v=sN(i.doc,y,p))&&!S9e.has(v)){let b=p+(i.doc.sliceString(p,p+1)===">"?1:0),x=`${v}>`;return{range:St.cursor(p+x.length,-1),changes:{from:p,to:b,insert:x}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,i.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),Ekt=uW({commentTokens:{block:{open:"<!--",close:"-->"}}}),Tkt=new Mr,jkt=kBn.configure({props:[l_.add(e=>!e.is("Block")||e.is("Document")||_ve(e)!=null||Jqn(e)?void 0:(t,n)=>({from:n.doc.lineAt(t.from).to,to:t.to})),Tkt.add(_ve),o_.add({Document:()=>null}),Mw.add({Document:Ekt})]});function _ve(e){let t=/^(?:ATX|Setext)Heading(\d)$/.exec(e.name);return t?+t[1]:void 0}function Jqn(e){return e.name=="OrderedList"||e.name=="BulletList"}function eVn(e,t){let n=e;for(;;){let r=n.nextSibling,s;if(!r||(s=_ve(r.type))!=null&&s<=t)break;n=r}return n.to}const tVn=Y1t.of((e,t,n)=>{for(let r=xi(e).resolveInner(n,-1);r&&!(r.from<t);r=r.parent){let s=r.type.prop(Tkt);if(s==null)continue;let a=eVn(r,s);if(a>n)return{from:n,to:a}}return null});function bOe(e){return new Ih(Ekt,e,[],"markdown")}const Nkt=bOe(jkt),nVn=jkt.configure([PBn,MBn,$Bn,DBn,{props:[l_.add({Table:(e,t)=>({from:t.doc.lineAt(e.from).to,to:e.to})})]}]),rC=bOe(nVn);function rVn(e,t){return n=>{if(n&&e){let r=null;if(n=/\S*/.exec(n)[0],typeof e=="function"?r=e(n):r=gg.matchLanguageName(e,n,!0),r instanceof gg)return r.support?r.support.language.parser:JO.getSkippingParser(r.load());if(r)return r.parser}return t?t.parser:null}}class mte{constructor(t,n,r,s,a,i,l){this.node=t,this.from=n,this.to=r,this.spaceBefore=s,this.spaceAfter=a,this.type=i,this.item=l}blank(t,n=!0){let r=this.spaceBefore+(this.node.name=="Blockquote"?">":"");if(t!=null){for(;r.length<t;)r+=" ";return r}else{for(let s=this.to-this.from-r.length-this.spaceAfter.length;s>0;s--)r+=" ";return r+(n?this.spaceAfter:"")}}marker(t,n){let r=this.node.name=="OrderedList"?String(+Akt(this.item,t)[2]+n):"";return this.spaceBefore+r+this.type+this.spaceAfter}}function Ikt(e,t){let n=[],r=[];for(let s=e;s;s=s.parent){if(s.name=="FencedCode")return r;(s.name=="ListItem"||s.name=="Blockquote")&&n.push(s)}for(let s=n.length-1;s>=0;s--){let a=n[s],i,l=t.lineAt(a.from),c=a.from-l.from;if(a.name=="Blockquote"&&(i=/^ *>( ?)/.exec(l.text.slice(c))))r.push(new mte(a,c,c+i[0].length,"",i[1],">",null));else if(a.name=="ListItem"&&a.parent.name=="OrderedList"&&(i=/^( *)\d+([.)])( *)/.exec(l.text.slice(c)))){let u=i[3],d=i[0].length;u.length>=4&&(u=u.slice(0,u.length-4),d-=4),r.push(new mte(a.parent,c,c+d,i[1],u,i[2],a))}else if(a.name=="ListItem"&&a.parent.name=="BulletList"&&(i=/^( *)([-+*])( {1,4}\[[ xX]\])?( +)/.exec(l.text.slice(c)))){let u=i[4],d=i[0].length;u.length>4&&(u=u.slice(0,u.length-4),d-=4);let f=i[2];i[3]&&(f+=i[3].replace(/[xX]/," ")),r.push(new mte(a.parent,c,c+d,i[1],u,f,a))}}return r}function Akt(e,t){return/^(\s*)(\d+)(?=[.)])/.exec(t.sliceString(e.from,e.from+10))}function gte(e,t,n,r=0){for(let s=-1,a=e;;){if(a.name=="ListItem"){let l=Akt(a,t),c=+l[2];if(s>=0){if(c!=s+1)return;n.push({from:a.from+l[1].length,to:a.from+l[0].length,insert:String(s+2+r)})}s=c}let i=a.nextSibling;if(!i)break;a=i}}function xOe(e,t){let n=/^[ \t]*/.exec(e)[0].length;if(!n||t.facet(TI)!=" ")return e;let r=Vg(e,4,n),s="";for(let a=r;a>0;)a>=4?(s+=" ",a-=4):(s+=" ",a--);return s+e.slice(n)}const Rkt=(e={})=>({state:t,dispatch:n})=>{let r=xi(t),{doc:s}=t,a=null,i=t.changeByRange(l=>{if(!l.empty||!rC.isActiveAt(t,l.from,-1)&&!rC.isActiveAt(t,l.from,1))return a={range:l};let c=l.from,u=s.lineAt(c),d=Ikt(r.resolveInner(c,-1),s);for(;d.length&&d[d.length-1].from>c-u.from;)d.pop();if(!d.length)return a={range:l};let f=d[d.length-1];if(f.to-f.spaceAfter.length>c-u.from)return a={range:l};let h=c>=f.to-f.spaceAfter.length&&!/\S/.test(u.text.slice(f.to));if(f.item&&h){let b=f.node.firstChild,x=f.node.getChild("ListItem","ListItem");if(b.to>=c||x&&x.to<c||u.from>0&&!/[^\s>]/.test(s.lineAt(u.from-1).text)||e.nonTightLists===!1){let w=d.length>1?d[d.length-2]:null,k,C="";w&&w.item?(k=u.from+w.from,C=w.marker(s,1)):k=u.from+(w?w.to:0);let _=[{from:k,to:c,insert:C}];return f.node.name=="OrderedList"&&gte(f.item,s,_,-2),w&&w.node.name=="OrderedList"&&gte(w.item,s,_),{range:St.cursor(k+C.length),changes:_}}else{let w=O9e(d,t,u);return{range:St.cursor(c+w.length+1),changes:{from:u.from,insert:w+t.lineBreak}}}}if(f.node.name=="Blockquote"&&h&&u.from){let b=s.lineAt(u.from-1),x=/>\s*$/.exec(b.text);if(x&&x.index==f.from){let w=t.changes([{from:b.from+x.index,to:b.to},{from:u.from+f.from,to:u.to}]);return{range:l.map(w),changes:w}}}let p=[];f.node.name=="OrderedList"&&gte(f.item,s,p);let m=f.item&&f.item.from<u.from,v="";if(!m||/^[\s\d.)\-+*>]*/.exec(u.text)[0].length>=f.to)for(let b=0,x=d.length-1;b<=x;b++)v+=b==x&&!m?d[b].marker(s,1):d[b].blank(b<x?Vg(u.text,4,d[b+1].from)-v.length:null);let y=c;for(;y>u.from&&/\s/.test(u.text.charAt(y-u.from-1));)y--;return v=xOe(v,t),sVn(f.node,t.doc)&&(v=O9e(d,t,u)+t.lineBreak+v),p.push({from:y,to:c,insert:t.lineBreak+v}),{range:St.cursor(y+v.length+1),changes:p}});return a?!1:(n(t.update(i,{scrollIntoView:!0,userEvent:"input"})),!0)},Pkt=Rkt();function k9e(e){return e.name=="QuoteMark"||e.name=="ListMark"}function sVn(e,t){if(e.name!="OrderedList"&&e.name!="BulletList")return!1;let n=e.firstChild,r=e.getChild("ListItem","ListItem");if(!r)return!1;let s=t.lineAt(n.to),a=t.lineAt(r.from),i=/^[\s>]*$/.test(s.text);return s.number+(i?0:1)<a.number}function O9e(e,t,n){let r="";for(let s=0,a=e.length-2;s<=a;s++)r+=e[s].blank(s<a?Vg(n.text,4,e[s+1].from)-r.length:null,s<a);return xOe(r,t)}function aVn(e,t){let n=e.resolveInner(t,-1),r=t;k9e(n)&&(r=n.from,n=n.parent);for(let s;s=n.childBefore(r);)if(k9e(s))r=s.from;else if(s.name=="OrderedList"||s.name=="BulletList")n=s.lastChild,r=n.to;else break;return n}const $kt=({state:e,dispatch:t})=>{let n=xi(e),r=null,s=e.changeByRange(a=>{let i=a.from,{doc:l}=e;if(a.empty&&rC.isActiveAt(e,a.from)){let c=l.lineAt(i),u=Ikt(aVn(n,i),l);if(u.length){let d=u[u.length-1],f=d.to-d.spaceAfter.length+(d.spaceAfter?1:0);if(i-c.from>f&&!/\S/.test(c.text.slice(f,i-c.from)))return{range:St.cursor(c.from+f),changes:{from:c.from+f,to:i}};if(i-c.from==f&&(!d.item||c.from<=d.item.from||!/\S/.test(c.text.slice(0,d.to)))){let h=c.from+d.from;if(d.item&&d.node.from<d.item.from&&/\S/.test(c.text.slice(d.from,d.to))){let p=d.blank(Vg(c.text,4,d.to)-Vg(c.text,4,d.from));return h==c.from&&(p=xOe(p,e)),{range:St.cursor(h+p.length),changes:{from:h,to:c.from+d.to,insert:p}}}if(h<i)return{range:St.cursor(h),changes:{from:h,to:i}}}}}return r={range:a}});return r?!1:(t(e.update(s,{scrollIntoView:!0,userEvent:"delete"})),!0)},Mkt=[{key:"Enter",run:Pkt},{key:"Backspace",run:$kt}],Dkt=Kqn({matchClosingTags:!1});function wOe(e={}){let{codeLanguages:t,defaultCodeLanguage:n,addKeymap:r=!0,base:{parser:s}=Nkt,completeHTMLTags:a=!0,pasteURLAsLink:i=!0,htmlTagLanguage:l=Dkt}=e;if(!(s instanceof pW))throw new RangeError("Base parser provided to `markdown` should be a Markdown parser");let c=e.extensions?[e.extensions]:[],u=[l.support,tVn],d;i&&u.push(Lkt),n instanceof eC?(u.push(n.support),d=n.language):n&&(d=n);let f=t||d?rVn(t,d):void 0;c.push(CBn({codeParser:f,htmlParser:l.language.parser})),r&&u.push(ip.high(EI.of(Mkt)));let h=bOe(s.configure(c));return a&&u.push(h.data.of({autocomplete:iVn})),new eC(h,u)}function iVn(e){let{state:t,pos:n}=e,r=/<[:\-\.\w\u00b7-\uffff]*$/.exec(t.sliceDoc(n-25,n));if(!r)return null;let s=xi(t).resolveInner(n,-1);for(;s&&!s.type.isTop;){if(s.name=="CodeBlock"||s.name=="FencedCode"||s.name=="ProcessingInstructionBlock"||s.name=="CommentBlock"||s.name=="Link"||s.name=="Image")return null;s=s.parent}return{from:n-r[0].length,to:n,options:oVn(),validFor:/^<[:\-\.\w\u00b7-\uffff]*$/}}let vte=null;function oVn(){if(vte)return vte;let e=Gqn(new Kke(gs.create({extensions:Dkt}),0,!0));return vte=e?e.options:[]}const lVn=/code|horizontalrule|html|link|comment|processing|escape|entity|image|mark|url/i,Lkt=Pt.domEventHandlers({paste:(e,t)=>{var n;let{main:r}=t.state.selection;if(r.empty)return!1;let s=(n=e.clipboardData)===null||n===void 0?void 0:n.getData("text/plain");if(!s||!/^(https?:\/\/|mailto:|xmpp:|www\.)/.test(s)||(/^www\./.test(s)&&(s="https://"+s),!rC.isActiveAt(t.state,r.from,1)))return!1;let a=xi(t.state),i=!1;return a.iterate({from:r.from,to:r.to,enter:l=>{(l.from>r.from||lVn.test(l.name))&&(i=!0)},leave:l=>{l.to<r.to&&(i=!0)}}),i?!1:(t.dispatch({changes:[{from:r.from,insert:"["},{from:r.to,insert:`](${s})`}],userEvent:"input.paste",scrollIntoView:!0}),!0)}}),cVn=Object.freeze(Object.defineProperty({__proto__:null,commonmarkLanguage:Nkt,deleteMarkupBackward:$kt,insertNewlineContinueMarkup:Pkt,insertNewlineContinueMarkupCommand:Rkt,markdown:wOe,markdownKeymap:Mkt,markdownLanguage:rC,pasteURLAsLink:Lkt},Symbol.toStringTag,{value:"Module"}));function sC(){return sC=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},sC.apply(null,arguments)}var uVn=e=>{var t=e.theme,n=e.settings,r=n===void 0?{}:n,s=e.styles,a=s===void 0?[]:s,i={".cm-gutters":{}},l={};r.background&&(l.backgroundColor=r.background),r.backgroundImage&&(l.backgroundImage=r.backgroundImage),r.foreground&&(l.color=r.foreground),r.fontSize&&(l.fontSize=r.fontSize),(r.background||r.foreground)&&(i["&"]=l),r.fontFamily&&(i["&.cm-editor .cm-scroller"]={fontFamily:r.fontFamily}),r.gutterBackground&&(i[".cm-gutters"].backgroundColor=r.gutterBackground),r.gutterForeground&&(i[".cm-gutters"].color=r.gutterForeground),r.gutterBorder&&(i[".cm-gutters"].borderRightColor=r.gutterBorder),r.caret&&(i[".cm-content"]={caretColor:r.caret},i[".cm-cursor, .cm-dropCursor"]={borderLeftColor:r.caret});var c={};r.gutterActiveForeground&&(c.color=r.gutterActiveForeground),r.lineHighlight&&(i[".cm-activeLine"]={backgroundColor:r.lineHighlight},c.backgroundColor=r.lineHighlight),i[".cm-activeLineGutter"]=c,r.selection&&(i["&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection"]={background:r.selection+" !important"}),r.selectionMatch&&(i["& .cm-selectionMatch"]={backgroundColor:r.selectionMatch});var u=Pt.theme(i,{dark:t==="dark"}),d=Jg.define(a),f=[u,fS(d)];return f},dVn={background:"#282a36",foreground:"#f8f8f2",caret:"#f8f8f0",selection:"rgba(255, 255, 255, 0.1)",selectionMatch:"rgba(255, 255, 255, 0.2)",gutterBackground:"#282a36",gutterForeground:"#6D8A88",gutterBorder:"transparent",lineHighlight:"rgba(255, 255, 255, 0.1)"},fVn=[{tag:ue.comment,color:"#6272a4"},{tag:ue.string,color:"#f1fa8c"},{tag:ue.atom,color:"#bd93f9"},{tag:ue.meta,color:"#f8f8f2"},{tag:[ue.keyword,ue.operator,ue.tagName],color:"#ff79c6"},{tag:[ue.function(ue.propertyName),ue.propertyName],color:"#66d9ef"},{tag:[ue.definition(ue.variableName),ue.function(ue.variableName),ue.className,ue.attributeName],color:"#50fa7b"},{tag:ue.atom,color:"#bd93f9"}],NI=e=>{var t=e||{},n=t.theme,r=n===void 0?"dark":n,s=t.settings,a=s===void 0?{}:s,i=t.styles,l=i===void 0?[]:i;return uVn({theme:r,settings:sC({},dVn,a),styles:[...fVn,...l]})};NI();function Fkt(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}const hVn=e=>{let{state:t}=e,n=t.doc.lineAt(t.selection.main.from),r=kOe(e.state,n.from);return r.line?pVn(e):r.block?gVn(e):!1};function SOe(e,t){return({state:n,dispatch:r})=>{if(n.readOnly)return!1;let s=e(t,n);return s?(r(n.update(s)),!0):!1}}const pVn=SOe(bVn,0),mVn=SOe(zkt,0),gVn=SOe((e,t)=>zkt(e,t,yVn(t)),0);function kOe(e,t){let n=e.languageDataAt("commentTokens",t,1);return n.length?n[0]:{}}const BR=50;function vVn(e,{open:t,close:n},r,s){let a=e.sliceDoc(r-BR,r),i=e.sliceDoc(s,s+BR),l=/\s*$/.exec(a)[0].length,c=/^\s*/.exec(i)[0].length,u=a.length-l;if(a.slice(u-t.length,u)==t&&i.slice(c,c+n.length)==n)return{open:{pos:r-l,margin:l&&1},close:{pos:s+c,margin:c&&1}};let d,f;s-r<=2*BR?d=f=e.sliceDoc(r,s):(d=e.sliceDoc(r,r+BR),f=e.sliceDoc(s-BR,s));let h=/^\s*/.exec(d)[0].length,p=/\s*$/.exec(f)[0].length,m=f.length-p-n.length;return d.slice(h,h+t.length)==t&&f.slice(m,m+n.length)==n?{open:{pos:r+h+t.length,margin:/\s/.test(d.charAt(h+t.length))?1:0},close:{pos:s-p-n.length,margin:/\s/.test(f.charAt(m-1))?1:0}}:null}function yVn(e){let t=[];for(let n of e.selection.ranges){let r=e.doc.lineAt(n.from),s=n.to<=r.to?r:e.doc.lineAt(n.to);s.from>r.from&&s.from==n.to&&(s=n.to==r.to+1?r:e.doc.lineAt(n.to-1));let a=t.length-1;a>=0&&t[a].to>r.from?t[a].to=s.to:t.push({from:r.from+/^\s*/.exec(r.text)[0].length,to:s.to})}return t}function zkt(e,t,n=t.selection.ranges){let r=n.map(a=>kOe(t,a.from).block);if(!r.every(a=>a))return null;let s=n.map((a,i)=>vVn(t,r[i],a.from,a.to));if(e!=2&&!s.every(a=>a))return{changes:t.changes(n.map((a,i)=>s[i]?[]:[{from:a.from,insert:r[i].open+" "},{from:a.to,insert:" "+r[i].close}]))};if(e!=1&&s.some(a=>a)){let a=[];for(let i=0,l;i<s.length;i++)if(l=s[i]){let c=r[i],{open:u,close:d}=l;a.push({from:u.pos-c.open.length,to:u.pos+u.margin},{from:d.pos-d.margin,to:d.pos+c.close.length})}return{changes:a}}return null}function bVn(e,t,n=t.selection.ranges){let r=[],s=-1;e:for(let{from:a,to:i}of n){let l=r.length,c=1e9,u;for(let d=a;d<=i;){let f=t.doc.lineAt(d);if(u==null&&(u=kOe(t,f.from).line,!u))continue e;if(f.from>s&&(a==i||i>f.from)){s=f.from;let h=/^\s*/.exec(f.text)[0].length,p=h==f.length,m=f.text.slice(h,h+u.length)==u?h:-1;h<f.text.length&&h<c&&(c=h),r.push({line:f,comment:m,token:u,indent:h,empty:p,single:!1})}d=f.to+1}if(c<1e9)for(let d=l;d<r.length;d++)r[d].indent<r[d].line.text.length&&(r[d].indent=c);r.length==l+1&&(r[l].single=!0)}if(e!=2&&r.some(a=>a.comment<0&&(!a.empty||a.single))){let a=[];for(let{line:l,token:c,indent:u,empty:d,single:f}of r)(f||!d)&&a.push({from:l.from+u,insert:c+" "});let i=t.changes(a);return{changes:i,selection:t.selection.map(i,1)}}else if(e!=1&&r.some(a=>a.comment>=0)){let a=[];for(let{line:i,comment:l,token:c}of r)if(l>=0){let u=i.from+l,d=u+c.length;i.text[d-i.from]==" "&&d++,a.push({from:u,to:d})}return{changes:a}}return null}const Eve=Vy.define(),xVn=Vy.define(),wVn=kn.define(),Bkt=kn.define({combine(e){return Hy(e,{minDepth:100,newGroupDelay:500,joinToEvent:(t,n)=>n},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(t,n)=>(r,s)=>t(r,s)||n(r,s)})}}),Ukt=xl.define({create(){return ry.empty},update(e,t){let n=t.state.facet(Bkt),r=t.annotation(Eve);if(r){let c=Tf.fromTransaction(t,r.selection),u=r.side,d=u==0?e.undone:e.done;return c?d=YB(d,d.length,n.minDepth,c):d=Hkt(d,t.startState.selection),new ry(u==0?r.rest:d,u==0?d:r.rest)}let s=t.annotation(xVn);if((s=="full"||s=="before")&&(e=e.isolate()),t.annotation(Rl.addToHistory)===!1)return t.changes.empty?e:e.addMapping(t.changes.desc);let a=Tf.fromTransaction(t),i=t.annotation(Rl.time),l=t.annotation(Rl.userEvent);return a?e=e.addChanges(a,i,l,n,t):t.selection&&(e=e.addSelection(t.startState.selection,i,l,n.newGroupDelay)),(s=="full"||s=="after")&&(e=e.isolate()),e},toJSON(e){return{done:e.done.map(t=>t.toJSON()),undone:e.undone.map(t=>t.toJSON())}},fromJSON(e){return new ry(e.done.map(Tf.fromJSON),e.undone.map(Tf.fromJSON))}});function SVn(e={}){return[Ukt,Bkt.of(e),Pt.domEventHandlers({beforeinput(t,n){let r=t.inputType=="historyUndo"?qkt:t.inputType=="historyRedo"?Tve:null;return r?(t.preventDefault(),r(n)):!1}})]}function mW(e,t){return function({state:n,dispatch:r}){if(!t&&n.readOnly)return!1;let s=n.field(Ukt,!1);if(!s)return!1;let a=s.pop(e,n,t);return a?(r(a),!0):!1}}const qkt=mW(0,!1),Tve=mW(1,!1),kVn=mW(0,!0),OVn=mW(1,!0);class Tf{constructor(t,n,r,s,a){this.changes=t,this.effects=n,this.mapped=r,this.startSelection=s,this.selectionsAfter=a}setSelAfter(t){return new Tf(this.changes,this.effects,this.mapped,this.startSelection,t)}toJSON(){var t,n,r;return{changes:(t=this.changes)===null||t===void 0?void 0:t.toJSON(),mapped:(n=this.mapped)===null||n===void 0?void 0:n.toJSON(),startSelection:(r=this.startSelection)===null||r===void 0?void 0:r.toJSON(),selectionsAfter:this.selectionsAfter.map(s=>s.toJSON())}}static fromJSON(t){return new Tf(t.changes&&Il.fromJSON(t.changes),[],t.mapped&&py.fromJSON(t.mapped),t.startSelection&&St.fromJSON(t.startSelection),t.selectionsAfter.map(St.fromJSON))}static fromTransaction(t,n){let r=Qp;for(let s of t.startState.facet(wVn)){let a=s(t);a.length&&(r=r.concat(a))}return!r.length&&t.changes.empty?null:new Tf(t.changes.invert(t.startState.doc),r,void 0,n||t.startState.selection,Qp)}static selection(t){return new Tf(void 0,Qp,void 0,void 0,t)}}function YB(e,t,n,r){let s=t+1>n+20?t-n-1:0,a=e.slice(s,t);return a.push(r),a}function CVn(e,t){let n=[],r=!1;return e.iterChangedRanges((s,a)=>n.push(s,a)),t.iterChangedRanges((s,a,i,l)=>{for(let c=0;c<n.length;){let u=n[c++],d=n[c++];l>=u&&i<=d&&(r=!0)}}),r}function _Vn(e,t){return e.ranges.length==t.ranges.length&&e.ranges.filter((n,r)=>n.empty!=t.ranges[r].empty).length===0}function Vkt(e,t){return e.length?t.length?e.concat(t):e:t}const Qp=[],EVn=200;function Hkt(e,t){if(e.length){let n=e[e.length-1],r=n.selectionsAfter.slice(Math.max(0,n.selectionsAfter.length-EVn));return r.length&&r[r.length-1].eq(t)?e:(r.push(t),YB(e,e.length-1,1e9,n.setSelAfter(r)))}else return[Tf.selection([t])]}function TVn(e){let t=e[e.length-1],n=e.slice();return n[e.length-1]=t.setSelAfter(t.selectionsAfter.slice(0,t.selectionsAfter.length-1)),n}function yte(e,t){if(!e.length)return e;let n=e.length,r=Qp;for(;n;){let s=jVn(e[n-1],t,r);if(s.changes&&!s.changes.empty||s.effects.length){let a=e.slice(0,n);return a[n-1]=s,a}else t=s.mapped,n--,r=s.selectionsAfter}return r.length?[Tf.selection(r)]:Qp}function jVn(e,t,n){let r=Vkt(e.selectionsAfter.length?e.selectionsAfter.map(l=>l.map(t)):Qp,n);if(!e.changes)return Tf.selection(r);let s=e.changes.map(t),a=t.mapDesc(e.changes,!0),i=e.mapped?e.mapped.composeDesc(a):a;return new Tf(s,vr.mapEffects(e.effects,t),i,e.startSelection.map(a),r)}const NVn=/^(input\.type|delete)($|\.)/;class ry{constructor(t,n,r=0,s=void 0){this.done=t,this.undone=n,this.prevTime=r,this.prevUserEvent=s}isolate(){return this.prevTime?new ry(this.done,this.undone):this}addChanges(t,n,r,s,a){let i=this.done,l=i[i.length-1];return l&&l.changes&&!l.changes.empty&&t.changes&&(!r||NVn.test(r))&&(!l.selectionsAfter.length&&n-this.prevTime<s.newGroupDelay&&s.joinToEvent(a,CVn(l.changes,t.changes))||r=="input.type.compose")?i=YB(i,i.length-1,s.minDepth,new Tf(t.changes.compose(l.changes),Vkt(vr.mapEffects(t.effects,l.changes),l.effects),l.mapped,l.startSelection,Qp)):i=YB(i,i.length,s.minDepth,t),new ry(i,Qp,n,r)}addSelection(t,n,r,s){let a=this.done.length?this.done[this.done.length-1].selectionsAfter:Qp;return a.length>0&&n-this.prevTime<s&&r==this.prevUserEvent&&r&&/^select($|\.)/.test(r)&&_Vn(a[a.length-1],t)?this:new ry(Hkt(this.done,t),this.undone,n,r)}addMapping(t){return new ry(yte(this.done,t),yte(this.undone,t),this.prevTime,this.prevUserEvent)}pop(t,n,r){let s=t==0?this.done:this.undone;if(s.length==0)return null;let a=s[s.length-1],i=a.selectionsAfter[0]||(a.startSelection?a.startSelection.map(a.changes.invertedDesc,1):n.selection);if(r&&a.selectionsAfter.length)return n.update({selection:a.selectionsAfter[a.selectionsAfter.length-1],annotations:Eve.of({side:t,rest:TVn(s),selection:i}),userEvent:t==0?"select.undo":"select.redo",scrollIntoView:!0});if(a.changes){let l=s.length==1?Qp:s.slice(0,s.length-1);return a.mapped&&(l=yte(l,a.mapped)),n.update({changes:a.changes,selection:a.startSelection,effects:a.effects,annotations:Eve.of({side:t,rest:l,selection:i}),filter:!1,userEvent:t==0?"undo":"redo",scrollIntoView:!0})}else return null}}ry.empty=new ry(Qp,Qp);const IVn=[{key:"Mod-z",run:qkt,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:Tve,preventDefault:!0},{linux:"Ctrl-Shift-z",run:Tve,preventDefault:!0},{key:"Mod-u",run:kVn,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:OVn,preventDefault:!0}];function II(e,t){return St.create(e.ranges.map(t),e.mainIndex)}function ev(e,t){return e.update({selection:t,scrollIntoView:!0,userEvent:"select"})}function tv({state:e,dispatch:t},n){let r=II(e.selection,n);return r.eq(e.selection,!0)?!1:(t(ev(e,r)),!0)}function gW(e,t){return St.cursor(t?e.to:e.from)}function Wkt(e,t){return tv(e,n=>n.empty?e.moveByChar(n,t):gW(n,t))}function id(e){return e.textDirectionAt(e.state.selection.main.head)==Ei.LTR}const Zkt=e=>Wkt(e,!id(e)),Gkt=e=>Wkt(e,id(e));function Qkt(e,t){return tv(e,n=>n.empty?e.moveByGroup(n,t):gW(n,t))}const AVn=e=>Qkt(e,!id(e)),RVn=e=>Qkt(e,id(e));function PVn(e,t,n){if(t.type.prop(n))return!0;let r=t.to-t.from;return r&&(r>2||/[^\s,.;:]/.test(e.sliceDoc(t.from,t.to)))||t.firstChild}function vW(e,t,n){let r=xi(e).resolveInner(t.head),s=n?Mr.closedBy:Mr.openedBy;for(let c=t.head;;){let u=n?r.childAfter(c):r.childBefore(c);if(!u)break;PVn(e,u,s)?r=u:c=n?u.to:u.from}let a=r.type.prop(s),i,l;return a&&(i=n?ny(e,r.from,1):ny(e,r.to,-1))&&i.matched?l=n?i.end.to:i.end.from:l=n?r.to:r.from,St.cursor(l,n?-1:1)}const $Vn=e=>tv(e,t=>vW(e.state,t,!id(e))),MVn=e=>tv(e,t=>vW(e.state,t,id(e)));function Ykt(e,t){return tv(e,n=>{if(!n.empty)return gW(n,t);let r=e.moveVertically(n,t);return r.head!=n.head?r:e.moveToLineBoundary(n,t)})}const Kkt=e=>Ykt(e,!1),Xkt=e=>Ykt(e,!0);function Jkt(e){let t=e.scrollDOM.clientHeight<e.scrollDOM.scrollHeight-2,n=0,r=0,s;if(t){for(let a of e.state.facet(Pt.scrollMargins)){let i=a(e);i?.top&&(n=Math.max(i?.top,n)),i?.bottom&&(r=Math.max(i?.bottom,r))}s=e.scrollDOM.clientHeight-n-r}else s=(e.dom.ownerDocument.defaultView||window).innerHeight;return{marginTop:n,marginBottom:r,selfScroll:t,height:Math.max(e.defaultLineHeight,s-5)}}function eOt(e,t){let n=Jkt(e),{state:r}=e,s=II(r.selection,i=>i.empty?e.moveVertically(i,t,n.height):gW(i,t));if(s.eq(r.selection))return!1;let a;if(n.selfScroll){let i=e.coordsAtPos(r.selection.main.head),l=e.scrollDOM.getBoundingClientRect(),c=l.top+n.marginTop,u=l.bottom-n.marginBottom;i&&i.top>c&&i.bottom<u&&(a=Pt.scrollIntoView(s.main.head,{y:"start",yMargin:i.top-c}))}return e.dispatch(ev(r,s),{effects:a}),!0}const C9e=e=>eOt(e,!1),jve=e=>eOt(e,!0);function hS(e,t,n){let r=e.lineBlockAt(t.head),s=e.moveToLineBoundary(t,n);if(s.head==t.head&&s.head!=(n?r.to:r.from)&&(s=e.moveToLineBoundary(t,n,!1)),!n&&s.head==r.from&&r.length){let a=/^\s*/.exec(e.state.sliceDoc(r.from,Math.min(r.from+100,r.to)))[0].length;a&&t.head!=r.from+a&&(s=St.cursor(r.from+a))}return s}const DVn=e=>tv(e,t=>hS(e,t,!0)),LVn=e=>tv(e,t=>hS(e,t,!1)),FVn=e=>tv(e,t=>hS(e,t,!id(e))),zVn=e=>tv(e,t=>hS(e,t,id(e))),BVn=e=>tv(e,t=>St.cursor(e.lineBlockAt(t.head).from,1)),UVn=e=>tv(e,t=>St.cursor(e.lineBlockAt(t.head).to,-1));function qVn(e,t,n){let r=!1,s=II(e.selection,a=>{let i=ny(e,a.head,-1)||ny(e,a.head,1)||a.head>0&&ny(e,a.head-1,1)||a.head<e.doc.length&&ny(e,a.head+1,-1);if(!i||!i.end)return a;r=!0;let l=i.start.from==a.head?i.end.to:i.end.from;return St.cursor(l)});return r?(t(ev(e,s)),!0):!1}const VVn=({state:e,dispatch:t})=>qVn(e,t);function Dm(e,t,n){let r=II(e.state.selection,s=>{s.undirectional&&s.head>=s.anchor!=t&&(s=St.range(s.head,s.anchor));let a=n(s);return St.range(s.anchor,a.head,a.goalColumn,a.bidiLevel||void 0,a.assoc)});return r.eq(e.state.selection)?!1:(e.dispatch(ev(e.state,r)),!0)}function tOt(e,t){return Dm(e,t,n=>e.moveByChar(n,t))}const nOt=e=>tOt(e,!id(e)),rOt=e=>tOt(e,id(e));function sOt(e,t){return Dm(e,t,n=>e.moveByGroup(n,t))}const HVn=e=>sOt(e,!id(e)),WVn=e=>sOt(e,id(e)),ZVn=e=>{let t=!id(e);return Dm(e,t,n=>vW(e.state,n,t))},GVn=e=>{let t=id(e);return Dm(e,t,n=>vW(e.state,n,t))};function aOt(e,t){return Dm(e,t,n=>e.moveVertically(n,t))}const iOt=e=>aOt(e,!1),oOt=e=>aOt(e,!0);function lOt(e,t){return Dm(e,t,n=>e.moveVertically(n,t,Jkt(e).height))}const _9e=e=>lOt(e,!1),E9e=e=>lOt(e,!0),QVn=e=>Dm(e,!0,t=>hS(e,t,!0)),YVn=e=>Dm(e,!1,t=>hS(e,t,!1)),KVn=e=>{let t=!id(e);return Dm(e,t,n=>hS(e,n,t))},XVn=e=>{let t=id(e);return Dm(e,t,n=>hS(e,n,t))},JVn=e=>Dm(e,!1,t=>St.cursor(e.lineBlockAt(t.head).from)),eHn=e=>Dm(e,!0,t=>St.cursor(e.lineBlockAt(t.head).to)),T9e=({state:e,dispatch:t})=>(t(ev(e,{anchor:0})),!0),j9e=({state:e,dispatch:t})=>(t(ev(e,{anchor:e.doc.length})),!0),N9e=({state:e,dispatch:t})=>(t(ev(e,{anchor:e.selection.main.anchor,head:0})),!0),I9e=({state:e,dispatch:t})=>(t(ev(e,{anchor:e.selection.main.anchor,head:e.doc.length})),!0),tHn=({state:e,dispatch:t})=>(t(e.update({selection:{anchor:0,head:e.doc.length},userEvent:"select"})),!0),nHn=({state:e,dispatch:t})=>{let n=yW(e).map(({from:r,to:s})=>St.range(r,Math.min(s+1,e.doc.length)));return t(e.update({selection:St.create(n),userEvent:"select"})),!0},rHn=({state:e,dispatch:t})=>{let n=II(e.selection,r=>{let s=xi(e),a=s.resolveStack(r.from,1);if(r.empty){let i=s.resolveStack(r.from,-1);i.node.from>=a.node.from&&i.node.to<=a.node.to&&(a=i)}for(let i=a;i;i=i.next){let{node:l}=i;if((l.from<r.from&&l.to>=r.to||l.to>r.to&&l.from<=r.from)&&i.next)return St.range(l.to,l.from)}return r});return n.eq(e.selection)?!1:(t(ev(e,n)),!0)};function cOt(e,t){let{state:n}=e,r=n.selection,s=n.selection.ranges.slice();for(let a of n.selection.ranges){let i=n.doc.lineAt(a.head);if(t?i.to<e.state.doc.length:i.from>0)for(let l=a;;){let c=e.moveVertically(l,t);if(c.head<i.from||c.head>i.to){s.some(u=>u.head==c.head)||s.push(c);break}else{if(c.head==l.head)break;l=c}}}return s.length==r.ranges.length?!1:(e.dispatch(ev(n,St.create(s,s.length-1))),!0)}const sHn=e=>cOt(e,!1),aHn=e=>cOt(e,!0),iHn=({state:e,dispatch:t})=>{let n=e.selection,r=null;return n.ranges.length>1?r=St.create([n.main]):n.main.empty||(r=St.create([St.cursor(n.main.head)])),r?(t(ev(e,r)),!0):!1};function t4(e,t){if(e.state.readOnly)return!1;let n="delete.selection",{state:r}=e,s=r.changeByRange(a=>{let{from:i,to:l}=a;if(i==l){let c=t(a);c<i?(n="delete.backward",c=SF(e,c,!1)):c>i&&(n="delete.forward",c=SF(e,c,!0)),i=Math.min(i,c),l=Math.max(l,c)}else i=SF(e,i,!1),l=SF(e,l,!0);return i==l?{range:a}:{changes:{from:i,to:l},range:St.cursor(i,i<a.head?-1:1)}});return s.changes.empty?!1:(e.dispatch(r.update(s,{scrollIntoView:!0,userEvent:n,effects:n=="delete.selection"?Pt.announce.of(r.phrase("Selection deleted")):void 0})),!0)}function SF(e,t,n){if(e instanceof Pt)for(let r of e.state.facet(Pt.atomicRanges).map(s=>s(e)))r.between(t,t,(s,a)=>{s<t&&a>t&&(t=n?a:s)});return t}const uOt=(e,t,n)=>t4(e,r=>{let s=r.from,{state:a}=e,i=a.doc.lineAt(s),l,c;if(n&&!t&&s>i.from&&s<i.from+200&&!/[^ \t]/.test(l=i.text.slice(0,s-i.from))){if(l[l.length-1]==" ")return s-1;let u=Vg(l,a.tabSize),d=u%tC(a)||tC(a);for(let f=0;f<d&&l[l.length-1-f]==" ";f++)s--;c=s}else c=Ac(i.text,s-i.from,t,t)+i.from,c==s&&i.number!=(t?a.doc.lines:1)?c+=t?1:-1:!t&&/[\ufe00-\ufe0f]/.test(i.text.slice(c-i.from,s-i.from))&&(c=Ac(i.text,c-i.from,!1,!1)+i.from);return c}),Nve=e=>uOt(e,!1,!0),dOt=e=>uOt(e,!0,!1),fOt=(e,t)=>t4(e,n=>{let r=n.head,{state:s}=e,a=s.doc.lineAt(r),i=s.charCategorizer(r);for(let l=null;;){if(r==(t?a.to:a.from)){r==n.head&&a.number!=(t?s.doc.lines:1)&&(r+=t?1:-1);break}let c=Ac(a.text,r-a.from,t)+a.from,u=a.text.slice(Math.min(r,c)-a.from,Math.max(r,c)-a.from),d=i(u);if(l!=null&&d!=l)break;(u!=" "||r!=n.head)&&(l=d),r=c}return r}),hOt=e=>fOt(e,!1),oHn=e=>fOt(e,!0),lHn=e=>t4(e,t=>{let n=e.lineBlockAt(t.head).to;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),cHn=e=>t4(e,t=>{let n=e.moveToLineBoundary(t,!1).head;return t.head>n?n:Math.max(0,t.head-1)}),uHn=e=>t4(e,t=>{let n=e.moveToLineBoundary(t,!0).head;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),dHn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(r=>({changes:{from:r.from,to:r.to,insert:Oa.of(["",""])},range:St.cursor(r.from)}));return t(e.update(n,{scrollIntoView:!0,userEvent:"input"})),!0},fHn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(r=>{if(!r.empty||r.from==0||r.from==e.doc.length)return{range:r};let s=r.from,a=e.doc.lineAt(s),i=s==a.from?s-1:Ac(a.text,s-a.from,!1)+a.from,l=s==a.to?s+1:Ac(a.text,s-a.from,!0)+a.from;return{changes:{from:i,to:l,insert:e.doc.slice(s,l).append(e.doc.slice(i,s))},range:St.cursor(l)}});return n.changes.empty?!1:(t(e.update(n,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function yW(e){let t=[],n=-1;for(let r of e.selection.ranges){let s=e.doc.lineAt(r.from),a=e.doc.lineAt(r.to);if(!r.empty&&r.to==a.from&&(a=e.doc.lineAt(r.to-1)),n>=s.number){let i=t[t.length-1];i.to=a.to,i.ranges.push(r)}else t.push({from:s.from,to:a.to,ranges:[r]});n=a.number+1}return t}function pOt(e,t,n){if(e.readOnly)return!1;let r=[],s=[];for(let a of yW(e)){if(n?a.to==e.doc.length:a.from==0)continue;let i=e.doc.lineAt(n?a.to+1:a.from-1),l=i.length+1;if(n){r.push({from:a.to,to:i.to},{from:a.from,insert:i.text+e.lineBreak});for(let c of a.ranges)s.push(St.range(Math.min(e.doc.length,c.anchor+l),Math.min(e.doc.length,c.head+l)))}else{r.push({from:i.from,to:a.from},{from:a.to,insert:e.lineBreak+i.text});for(let c of a.ranges)s.push(St.range(c.anchor-l,c.head-l))}}return r.length?(t(e.update({changes:r,scrollIntoView:!0,selection:St.create(s,e.selection.mainIndex),userEvent:"move.line"})),!0):!1}const hHn=({state:e,dispatch:t})=>pOt(e,t,!1),pHn=({state:e,dispatch:t})=>pOt(e,t,!0);function mOt(e,t,n){if(e.readOnly)return!1;let r=[];for(let a of yW(e))n?r.push({from:a.from,insert:e.doc.slice(a.from,a.to)+e.lineBreak}):r.push({from:a.to,insert:e.lineBreak+e.doc.slice(a.from,a.to)});let s=e.changes(r);return t(e.update({changes:s,selection:e.selection.map(s,n?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}const mHn=({state:e,dispatch:t})=>mOt(e,t,!1),gHn=({state:e,dispatch:t})=>mOt(e,t,!0),vHn=e=>{if(e.state.readOnly)return!1;let{state:t}=e,n=t.changes(yW(t).map(({from:s,to:a})=>(s>0?s--:a<t.doc.length&&a++,{from:s,to:a}))),r=II(t.selection,s=>{let a;if(e.lineWrapping){let i=e.lineBlockAt(s.head),l=e.coordsAtPos(s.head,s.assoc||1);l&&(a=i.bottom+e.documentTop-l.bottom+e.defaultLineHeight/2)}return e.moveVertically(s,!0,a)}).map(n);return e.dispatch({changes:n,selection:r,scrollIntoView:!0,userEvent:"delete.line"}),!0};function yHn(e,t){if(/\(\)|\[\]|\{\}/.test(e.sliceDoc(t-1,t+1)))return{from:t,to:t};let n=xi(e).resolveInner(t),r=n.childBefore(t),s=n.childAfter(t),a;return r&&s&&r.to<=t&&s.from>=t&&(a=r.type.prop(Mr.closedBy))&&a.indexOf(s.name)>-1&&e.doc.lineAt(r.to).from==e.doc.lineAt(s.from).from&&!/\S/.test(e.sliceDoc(r.to,s.from))?{from:r.to,to:s.from}:null}const A9e=gOt(!1),bHn=gOt(!0);function gOt(e){return({state:t,dispatch:n})=>{if(t.readOnly)return!1;let r=t.changeByRange(s=>{let{from:a,to:i}=s,l=t.doc.lineAt(a),c=!e&&a==i&&yHn(t,a);e&&(a=i=(i<=l.to?l:t.doc.lineAt(i)).to);let u=new dW(t,{simulateBreak:a,simulateDoubleBreak:!!c}),d=Hke(u,a);for(d==null&&(d=Vg(/^\s*/.exec(t.doc.lineAt(a).text)[0],t.tabSize));i<l.to&&/\s/.test(l.text[i-l.from]);)i++;c?{from:a,to:i}=c:a>l.from&&a<l.from+100&&!/\S/.test(l.text.slice(0,a))&&(a=l.from);let f=["",jM(t,d)];return c&&f.push(jM(t,u.lineIndent(l.from,-1))),{changes:{from:a,to:i,insert:Oa.of(f)},range:St.cursor(a+1+f[1].length)}});return n(t.update(r,{scrollIntoView:!0,userEvent:"input"})),!0}}function OOe(e,t){let n=-1;return e.changeByRange(r=>{let s=[];for(let i=r.from;i<=r.to;){let l=e.doc.lineAt(i);l.number>n&&(r.empty||r.to>l.from)&&(t(l,s,r),n=l.number),i=l.to+1}let a=e.changes(s);return{changes:s,range:St.range(a.mapPos(r.anchor,1),a.mapPos(r.head,1))}})}const xHn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=Object.create(null),r=new dW(e,{overrideIndentation:a=>{let i=n[a];return i??-1}}),s=OOe(e,(a,i,l)=>{let c=Hke(r,a.from);if(c==null)return;/\S/.test(a.text)||(c=0);let u=/^\s*/.exec(a.text)[0],d=jM(e,c);(u!=d||l.from<a.from+u.length)&&(n[a.from]=c,i.push({from:a.from,to:a.from+u.length,insert:d}))});return s.changes.empty||t(e.update(s,{userEvent:"indent"})),!0},vOt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(OOe(e,(n,r)=>{r.push({from:n.from,insert:e.facet(TI)})}),{userEvent:"input.indent"})),!0),yOt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(OOe(e,(n,r)=>{let s=/^\s*/.exec(n.text)[0];if(!s)return;let a=Vg(s,e.tabSize),i=0,l=jM(e,Math.max(0,a-tC(e)));for(;i<s.length&&i<l.length&&s.charCodeAt(i)==l.charCodeAt(i);)i++;r.push({from:n.from+i,to:n.from+s.length,insert:l.slice(i)})}),{userEvent:"delete.dedent"})),!0),wHn=e=>(e.setTabFocusMode(),!0),SHn=[{key:"Ctrl-b",run:Zkt,shift:nOt,preventDefault:!0},{key:"Ctrl-f",run:Gkt,shift:rOt},{key:"Ctrl-p",run:Kkt,shift:iOt},{key:"Ctrl-n",run:Xkt,shift:oOt},{key:"Ctrl-a",run:BVn,shift:JVn},{key:"Ctrl-e",run:UVn,shift:eHn},{key:"Ctrl-d",run:dOt},{key:"Ctrl-h",run:Nve},{key:"Ctrl-k",run:lHn},{key:"Ctrl-Alt-h",run:hOt},{key:"Ctrl-o",run:dHn},{key:"Ctrl-t",run:fHn},{key:"Ctrl-v",run:jve}],kHn=[{key:"ArrowLeft",run:Zkt,shift:nOt,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:AVn,shift:HVn,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:FVn,shift:KVn,preventDefault:!0},{key:"ArrowRight",run:Gkt,shift:rOt,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:RVn,shift:WVn,preventDefault:!0},{mac:"Cmd-ArrowRight",run:zVn,shift:XVn,preventDefault:!0},{key:"ArrowUp",run:Kkt,shift:iOt,preventDefault:!0},{mac:"Cmd-ArrowUp",run:T9e,shift:N9e},{mac:"Ctrl-ArrowUp",run:C9e,shift:_9e},{key:"ArrowDown",run:Xkt,shift:oOt,preventDefault:!0},{mac:"Cmd-ArrowDown",run:j9e,shift:I9e},{mac:"Ctrl-ArrowDown",run:jve,shift:E9e},{key:"PageUp",run:C9e,shift:_9e},{key:"PageDown",run:jve,shift:E9e},{key:"Home",run:LVn,shift:YVn,preventDefault:!0},{key:"Mod-Home",run:T9e,shift:N9e},{key:"End",run:DVn,shift:QVn,preventDefault:!0},{key:"Mod-End",run:j9e,shift:I9e},{key:"Enter",run:A9e,shift:A9e},{key:"Mod-a",run:tHn},{key:"Backspace",run:Nve,shift:Nve,preventDefault:!0},{key:"Delete",run:dOt,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:hOt,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:oHn,preventDefault:!0},{mac:"Mod-Backspace",run:cHn,preventDefault:!0},{mac:"Mod-Delete",run:uHn,preventDefault:!0}].concat(SHn.map(e=>({mac:e.key,run:e.run,shift:e.shift}))),OHn=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:$Vn,shift:ZVn},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:MVn,shift:GVn},{key:"Alt-ArrowUp",run:hHn},{key:"Shift-Alt-ArrowUp",run:mHn},{key:"Alt-ArrowDown",run:pHn},{key:"Shift-Alt-ArrowDown",run:gHn},{key:"Mod-Alt-ArrowUp",run:sHn},{key:"Mod-Alt-ArrowDown",run:aHn},{key:"Escape",run:iHn},{key:"Mod-Enter",run:bHn},{key:"Alt-l",mac:"Ctrl-l",run:nHn},{key:"Mod-i",run:rHn,preventDefault:!0},{key:"Mod-[",run:yOt},{key:"Mod-]",run:vOt},{key:"Mod-Alt-\\",run:xHn},{key:"Shift-Mod-k",run:vHn},{key:"Shift-Mod-\\",run:VVn},{key:"Mod-/",run:hVn},{key:"Alt-A",run:mVn},{key:"Ctrl-m",mac:"Shift-Alt-m",run:wHn}].concat(kHn),CHn={key:"Tab",run:vOt,shift:yOt},R9e=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class Lx{constructor(t,n,r=0,s=t.length,a,i){this.test=i,this.value={from:0,to:0,precise:!1},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=t.iterRange(r,s),this.bufferStart=r,this.normalize=a?l=>a(R9e(l)):R9e,this.query=this.normalize(n)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return bf(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let t=this.peek();if(t<0)return this.done=!0,this;let n=_ke(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=Wv(t);let s=this.normalize(n);if(s.length)for(let a=0,i=r,l=!0;;a++){let c=s.charCodeAt(a),u=this.match(c,i,l,this.bufferPos+this.bufferStart,a==s.length-1);if(u)return this.value=u,this;if(a==s.length-1)break;l&&a<n.length&&n.charCodeAt(a)==c?i++:l=!1}}}match(t,n,r,s,a){let i=null;for(let l=0;l<this.matches.length;){let c=this.matches[l],u=!1;this.query.charCodeAt(c.index)==t&&(c.index==this.query.length-1?i={from:c.from,to:s,precise:a&&c.precise}:(c.index++,u=!0)),u?l++:this.matches.splice(l,1)}return this.query.charCodeAt(0)==t&&(this.query.length==1?i={from:n,to:s,precise:r&&a}:this.matches.push({from:n,index:1,precise:r})),i&&this.test&&!this.test(i.from,i.to,this.buffer,this.bufferStart)&&(i=null),i}}typeof Symbol<"u"&&(Lx.prototype[Symbol.iterator]=function(){return this});const bOt={from:-1,to:-1,match:/.*/.exec(""),precise:!0},COe="gm"+(/x/.unicode==null?"":"u");class xOt{constructor(t,n,r,s=0,a=t.length){if(this.text=t,this.to=a,this.curLine="",this.done=!1,this.value=bOt,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new wOt(t,n,r,s,a);this.re=new RegExp(n,COe+(r?.ignoreCase?"i":"")),this.test=r?.test,this.iter=t.iter();let i=t.lineAt(s);this.curLineStart=i.from,this.matchPos=KB(t,s),this.getLine(this.curLineStart)}getLine(t){this.iter.next(t),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let t=this.matchPos-this.curLineStart;;){this.re.lastIndex=t;let n=this.matchPos<=this.to&&this.re.exec(this.curLine);if(n){let r=this.curLineStart+n.index,s=r+n[0].length;if(this.matchPos=KB(this.text,s+(r==s?1:0)),r==this.curLineStart+this.curLine.length&&this.nextLine(),(r<s||r>this.value.to)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,precise:!0,match:n},this;t=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length<this.to)this.nextLine(),t=0;else return this.done=!0,this}}}const bte=new WeakMap;class uj{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let s=bte.get(t);if(!s||s.from>=r||s.to<=n){let l=new uj(n,t.sliceString(n,r));return bte.set(t,l),l}if(s.from==n&&s.to==r)return s;let{text:a,from:i}=s;return i>n&&(a=t.sliceString(n,i)+a,i=n),s.to<r&&(a+=t.sliceString(s.to,r)),bte.set(t,new uj(i,a)),new uj(n,a.slice(n-i,r-i))}}class wOt{constructor(t,n,r,s,a){this.text=t,this.to=a,this.done=!1,this.value=bOt,this.matchPos=KB(t,s),this.re=new RegExp(n,COe+(r?.ignoreCase?"i":"")),this.test=r?.test,this.flat=uj.get(t,s,this.chunkEnd(s+5e3))}chunkEnd(t){return t>=this.to?this.to:this.text.lineAt(t).to}next(){for(;;){let t=this.re.lastIndex=this.matchPos-this.flat.from,n=this.re.exec(this.flat.text);if(n&&!n[0]&&n.index==t&&(this.re.lastIndex=t+1,n=this.re.exec(this.flat.text)),n){let r=this.flat.from+n.index,s=r+n[0].length;if((this.flat.to>=this.to||n.index+n[0].length<=this.flat.text.length-10)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,precise:!0,match:n},this.matchPos=KB(this.text,s+(r==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=uj.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(xOt.prototype[Symbol.iterator]=wOt.prototype[Symbol.iterator]=function(){return this});function _Hn(e){try{return new RegExp(e,COe),!0}catch{return!1}}function KB(e,t){if(t>=e.length)return t;let n=e.lineAt(t),r;for(;t<n.to&&(r=n.text.charCodeAt(t-n.from))>=56320&&r<57344;)t++;return t}const EHn=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:s}=l9n(e,{label:t.phrase("Go to line"),input:{type:"text",name:"line",value:n},focus:!0,submitLabel:t.phrase("go")});return s.then(a=>{let i=a&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(a.elements.line.value);if(!i){e.dispatch({effects:r});return}let l=t.doc.lineAt(t.selection.main.head),[,c,u,d,f]=i,h=d?+d.slice(1):0,p=u?+u:l.number;if(u&&f){let y=p/100;c&&(y=y*(c=="-"?-1:1)+l.number/t.doc.lines),p=Math.round(t.doc.lines*y)}else u&&c&&(p=p*(c=="-"?-1:1)+l.number);let m=t.doc.line(Math.max(1,Math.min(t.doc.lines,p))),v=St.cursor(m.from+Math.max(0,Math.min(h,m.length)));e.dispatch({effects:[r,Pt.scrollIntoView(v.from,{y:"center"})],selection:v})}),!0},THn={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},jHn=kn.define({combine(e){return Hy(e,THn,{highlightWordAroundCursor:(t,n)=>t||n,minSelectionLength:Math.min,maxMatches:Math.min})}});function NHn(e){return[$Hn,PHn]}const IHn=Nn.mark({class:"cm-selectionMatch"}),AHn=Nn.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function P9e(e,t,n,r){return(n==0||e(t.sliceDoc(n-1,n))!=wo.Word)&&(r==t.doc.length||e(t.sliceDoc(r,r+1))!=wo.Word)}function RHn(e,t,n,r){return e(t.sliceDoc(n,n+1))==wo.Word&&e(t.sliceDoc(r-1,r))==wo.Word}const PHn=Co.fromClass(class{constructor(e){this.decorations=this.getDeco(e)}update(e){(e.selectionSet||e.docChanged||e.viewportChanged)&&(this.decorations=this.getDeco(e.view))}getDeco(e){let t=e.state.facet(jHn),{state:n}=e,r=n.selection;if(r.ranges.length>1)return Nn.none;let s=r.main,a,i=null;if(s.empty){if(!t.highlightWordAroundCursor)return Nn.none;let c=n.wordAt(s.head);if(!c)return Nn.none;i=n.charCategorizer(s.head),a=n.sliceDoc(c.from,c.to)}else{let c=s.to-s.from;if(c<t.minSelectionLength||c>200)return Nn.none;if(t.wholeWords){if(a=n.sliceDoc(s.from,s.to),i=n.charCategorizer(s.head),!(P9e(i,n,s.from,s.to)&&RHn(i,n,s.from,s.to)))return Nn.none}else if(a=n.sliceDoc(s.from,s.to),!a)return Nn.none}let l=[];for(let c of e.visibleRanges){let u=new Lx(n.doc,a,c.from,c.to);for(;!u.next().done;){let{from:d,to:f}=u.value;if((!i||P9e(i,n,d,f))&&(s.empty&&d<=s.from&&f>=s.to?l.push(AHn.range(d,f)):(d>=s.to||f<=s.from)&&l.push(IHn.range(d,f)),l.length>t.maxMatches))return Nn.none}}return Nn.set(l)}},{decorations:e=>e.decorations}),$Hn=Pt.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),MHn=({state:e,dispatch:t})=>{let{selection:n}=e,r=St.create(n.ranges.map(s=>e.wordAt(s.head)||St.cursor(s.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function DHn(e,t){let{main:n,ranges:r}=e.selection,s=e.wordAt(n.head),a=s&&s.from==n.from&&s.to==n.to;for(let i=!1,l=new Lx(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(i)return null;l=new Lx(e.doc,t,0,Math.max(0,r[r.length-1].from-1)),i=!0}else{if(i&&r.some(c=>c.from==l.value.from))continue;if(a){let c=e.wordAt(l.value.from);if(!c||c.from!=l.value.from||c.to!=l.value.to)continue}return l.value}}const LHn=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(a=>a.from===a.to))return MHn({state:e,dispatch:t});let r=e.sliceDoc(n[0].from,n[0].to);if(e.selection.ranges.some(a=>e.sliceDoc(a.from,a.to)!=r))return!1;let s=DHn(e,r);return s?(t(e.update({selection:e.selection.addRange(St.range(s.from,s.to),!1),effects:Pt.scrollIntoView(s.to)})),!0):!1},AI=kn.define({combine(e){return Hy(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new XHn(t),scrollToMatch:t=>Pt.scrollIntoView(t)})}});class SOt{constructor(t){this.search=t.search,this.caseSensitive=!!t.caseSensitive,this.literal=!!t.literal,this.regexp=!!t.regexp,this.replace=t.replace||"",this.valid=!!this.search&&(!this.regexp||_Hn(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!t.wholeWord,this.test=t.test}unquote(t){return this.literal?t:t.replace(/\\([nrt\\])/g,(n,r)=>r=="n"?`
234
- `:r=="r"?"\r":r=="t"?" ":"\\")}eq(t){return this.search==t.search&&this.replace==t.replace&&this.caseSensitive==t.caseSensitive&&this.regexp==t.regexp&&this.wholeWord==t.wholeWord&&this.test==t.test}create(){return this.regexp?new VHn(this):new BHn(this)}getCursor(t,n=0,r){let s=t.doc?t:gs.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?aT(this,s,n,r):sT(this,s,n,r)}}class kOt{constructor(t){this.spec=t}}function FHn(e,t,n){return(r,s,a,i)=>{if(n&&!n(r,s,a,i))return!1;let l=r>=i&&s<=i+a.length?a.slice(r-i,s-i):t.doc.sliceString(r,s);return e(l,t,r,s)}}function sT(e,t,n,r){let s;return e.wholeWord&&(s=zHn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=FHn(e.test,t,s)),new Lx(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function zHn(e,t){return(n,r,s,a)=>((a>n||a+s.length<r)&&(a=Math.max(0,n-2),s=e.sliceString(a,Math.min(e.length,r+2))),(t(XB(s,n-a))!=wo.Word||t(JB(s,n-a))!=wo.Word)&&(t(JB(s,r-a))!=wo.Word||t(XB(s,r-a))!=wo.Word))}class BHn extends kOt{constructor(t){super(t)}nextMatch(t,n,r){let s=sT(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=sT(this.spec,t,0,a).nextOverlapping()}return s.done||s.value.from==n&&s.value.to==r?null:s.value}prevMatchInRange(t,n,r){for(let s=r;;){let a=Math.max(n,s-1e4-this.spec.unquoted.length),i=sT(this.spec,t,a,s),l=null;for(;!i.nextOverlapping().done;)l=i.value;if(l)return l;if(a==n)return null;s-=1e4}}prevMatch(t,n,r){let s=this.prevMatchInRange(t,0,n);return s||(s=this.prevMatchInRange(t,Math.max(0,r-this.spec.unquoted.length),t.doc.length)),s&&(s.from!=n||s.to!=r)?s:null}getReplacement(t){return this.spec.unquote(this.spec.replace)}matchAll(t,n){let r=sT(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=sT(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}function UHn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function aT(e,t,n,r){let s;return e.wholeWord&&(s=qHn(t.charCategorizer(t.selection.main.head))),e.test&&(s=UHn(e.test,t,s)),new xOt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function XB(e,t){return e.slice(Ac(e,t,!1),t)}function JB(e,t){return e.slice(t,Ac(e,t))}function qHn(e){return(t,n,r)=>!r[0].length||(e(XB(r.input,r.index))!=wo.Word||e(JB(r.input,r.index))!=wo.Word)&&(e(JB(r.input,r.index+r[0].length))!=wo.Word||e(XB(r.input,r.index+r[0].length))!=wo.Word)}class VHn extends kOt{nextMatch(t,n,r){let s=aT(this.spec,t,r,t.doc.length).next();return s.done&&(s=aT(this.spec,t,0,n).next()),s.done?null:s.value}prevMatchInRange(t,n,r){for(let s=1;;s++){let a=Math.max(n,r-s*1e4),i=aT(this.spec,t,a,r),l=null;for(;!i.next().done;)l=i.value;if(l&&(a==n||l.from>a+10))return l;if(a==n)return null}}prevMatch(t,n,r){return this.prevMatchInRange(t,0,n)||this.prevMatchInRange(t,r,t.doc.length)}getReplacement(t){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(n,r)=>{if(r=="&")return t.match[0];if(r=="$")return"$";for(let s=r.length;s>0;s--){let a=+r.slice(0,s);if(a>0&&a<t.match.length)return t.match[a]+r.slice(s)}return n})}matchAll(t,n){let r=aT(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=aT(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}const LM=vr.define(),_Oe=vr.define(),e1=xl.define({create(e){return new xte(Ive(e).create(),null)},update(e,t){for(let n of t.effects)n.is(LM)?e=new xte(n.value.create(),e.panel):n.is(_Oe)&&(e=new xte(e.query,n.value?EOe:null));return e},provide:e=>TM.from(e,t=>t.panel)});class xte{constructor(t,n){this.query=t,this.panel=n}}const HHn=Nn.mark({class:"cm-searchMatch"}),WHn=Nn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),ZHn=Co.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(e1))}update(e){let t=e.state.field(e1);(t!=e.startState.field(e1)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return Nn.none;let{view:n}=this,r=new Hd;for(let s=0,a=n.visibleRanges,i=a.length;s<i;s++){let{from:l,to:c}=a[s];for(;s<i-1&&c>a[s+1].from-500;)c=a[++s].to;e.highlight(n.state,l,c,(u,d)=>{let f=n.state.selection.ranges.some(h=>h.from==u&&h.to==d);r.add(u,d,f?WHn:HHn)})}return r.finish()}},{decorations:e=>e.decorations});function n4(e){return t=>{let n=t.state.field(e1,!1);return n&&n.query.spec.valid?e(t,n):_Ot(t)}}const eU=n4((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=St.single(r.from,r.to),a=e.state.facet(AI);return e.dispatch({selection:s,effects:[TOe(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),COt(e),!0}),tU=n4((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let a=St.single(s.from,s.to),i=e.state.facet(AI);return e.dispatch({selection:a,effects:[TOe(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),COt(e),!0}),GHn=n4((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:St.create(n.map(r=>St.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),QHn=({state:e,dispatch:t})=>{let n=e.selection;if(n.ranges.length>1||n.main.empty)return!1;let{from:r,to:s}=n.main,a=[],i=0;for(let l=new Lx(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(i=a.length),a.push(St.range(l.value.from,l.value.to))}return t(e.update({selection:St.create(a,i),userEvent:"select.search.matches"})),!0},$9e=n4((e,{query:t})=>{let{state:n}=e,{from:r,to:s}=n.selection.main;if(n.readOnly)return!1;let a=t.nextMatch(n,r,r);if(!a)return!1;let i=a,l=[],c,u,d=[];i.precise?i.from==r&&i.to==s&&(u=n.toText(t.getReplacement(i)),l.push({from:i.from,to:i.to,insert:u}),i=t.nextMatch(n,i.from,i.to),d.push(Pt.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+"."))):i=t.nextMatch(n,i.from,i.to);let f=e.state.changes(l);return i&&(c=St.single(i.from,i.to).map(f),d.push(TOe(e,i)),d.push(n.facet(AI).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),YHn=n4((e,{query:t})=>{if(e.state.readOnly)return!1;let n=[];for(let s of t.matchAll(e.state,1e9)){let{from:a,to:i,precise:l}=s;l&&n.push({from:a,to:i,insert:t.getReplacement(s)})}if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:Pt.announce.of(r),userEvent:"input.replace.all"}),!0});function EOe(e){return e.state.facet(AI).createPanel(e)}function Ive(e,t){var n,r,s,a,i;let l=e.selection.main,c=l.empty||l.to>l.from+100?"":e.sliceDoc(l.from,l.to);if(t&&!c)return t;let u=e.facet(AI);return new SOt({search:((n=t?.literal)!==null&&n!==void 0?n:u.literal)?c:c.replace(/\n/g,"\\n"),caseSensitive:(r=t?.caseSensitive)!==null&&r!==void 0?r:u.caseSensitive,literal:(s=t?.literal)!==null&&s!==void 0?s:u.literal,regexp:(a=t?.regexp)!==null&&a!==void 0?a:u.regexp,wholeWord:(i=t?.wholeWord)!==null&&i!==void 0?i:u.wholeWord})}function OOt(e){let t=qke(e,EOe);return t&&t.dom.querySelector("[main-field]")}function COt(e){let t=OOt(e);t&&t==e.root.activeElement&&t.select()}const _Ot=e=>{let t=e.state.field(e1,!1);if(t&&t.panel){let n=OOt(e);if(n&&n!=e.root.activeElement){let r=Ive(e.state,t.query.spec);r.valid&&e.dispatch({effects:LM.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[_Oe.of(!0),t?LM.of(Ive(e.state,t.query.spec)):vr.appendConfig.of(eWn)]});return!0},EOt=e=>{let t=e.state.field(e1,!1);if(!t||!t.panel)return!1;let n=qke(e,EOe);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:_Oe.of(!1)}),!0},KHn=[{key:"Mod-f",run:_Ot,scope:"editor search-panel"},{key:"F3",run:eU,shift:tU,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:eU,shift:tU,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:EOt,scope:"editor search-panel"},{key:"Mod-Shift-l",run:QHn},{key:"Mod-Alt-g",run:EHn},{key:"Mod-d",run:LHn,preventDefault:!0}];class XHn{constructor(t){this.view=t;let n=this.query=t.state.field(e1).query.spec;this.commit=this.commit.bind(this),this.searchField=mi("input",{value:n.search,placeholder:fh(t,"Find"),"aria-label":fh(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=mi("input",{value:n.replace,placeholder:fh(t,"Replace"),"aria-label":fh(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=mi("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=mi("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=mi("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return mi("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=mi("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>eU(t),[fh(t,"next")]),r("prev",()=>tU(t),[fh(t,"previous")]),r("select",()=>GHn(t),[fh(t,"all")]),mi("label",null,[this.caseField,fh(t,"match case")]),mi("label",null,[this.reField,fh(t,"regexp")]),mi("label",null,[this.wordField,fh(t,"by word")]),...t.state.readOnly?[]:[mi("br"),this.replaceField,r("replace",()=>$9e(t),[fh(t,"replace")]),r("replaceAll",()=>YHn(t),[fh(t,"replace all")])],mi("button",{name:"close",onclick:()=>EOt(t),"aria-label":fh(t,"close"),type:"button"},["×"])])}commit(){let t=new SOt({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});t.eq(this.query)||(this.query=t,this.view.dispatch({effects:LM.of(t)}))}keydown(t){y8n(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?tU:eU)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),$9e(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(LM)&&!r.value.eq(this.query)&&this.setQuery(r.value)}setQuery(t){this.query=t,this.searchField.value=t.search,this.replaceField.value=t.replace,this.caseField.checked=t.caseSensitive,this.reField.checked=t.regexp,this.wordField.checked=t.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(AI).top}}function fh(e,t){return e.state.phrase(t)}const kF=30,OF=/[\s\.,:;?!]/;function TOe(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),s=e.state.doc.lineAt(n).to,a=Math.max(r.from,t-kF),i=Math.min(s,n+kF),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<kF;c++)if(!OF.test(l[c+1])&&OF.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-kF;c--)if(!OF.test(l[c-1])&&OF.test(l[c])){l=l.slice(0,c);break}}return Pt.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const JHn=Pt.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),eWn=[e1,ip.low(ZHn),JHn];class M9e{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class $k{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(FM).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new Hd,l=[],c=0;for(let d=0;;){let f=d==a.length?null:a[d];if(!f&&!l.length)break;let h,p;for(l.length?(h=c,p=l.reduce((v,y)=>Math.min(v,y.to),f&&f.from>h?f.from:1e8)):(h=f.from,p=f.to,l.push(f),d++);d<a.length;){let v=a[d];if(v.from==h&&(v.to>v.from||v.to==h))l.push(v),d++,p=Math.min(v.to,p);else{p=Math.min(v.from,p);break}}let m=hWn(l);if(l.some(v=>v.from==v.to||v.from==v.to-1&&r.doc.lineAt(v.from).to==v.from))i.add(h,h,Nn.widget({widget:new cWn(m),diagnostics:l.slice()}));else{let v=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(h,p,Nn.mark({class:"cm-lintRange cm-lintRange-"+m+v,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>p)}))}c=p;for(let v=0;v<l.length;v++)l[v].to<=c&&l.splice(v--,1)}let u=i.finish();return new $k(u,n,iN(u))}}function iN(e,t=null,n=0){let r=null;return e.between(n,1e9,(s,a,{spec:i})=>{if(!(t&&i.diagnostics.indexOf(t)<0))if(!r)r=new M9e(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new M9e(r.from,a,r.diagnostic)}}),r}function tWn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(FM).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(TOt))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function nWn(e,t){return e.field(Ah,!1)?t:t.concat(vr.appendConfig.of(pWn))}const TOt=vr.define(),jOe=vr.define(),jOt=vr.define(),Ah=xl.define({create(){return new $k(Nn.none,null,null)},update(e,t){if(t.docChanged&&e.diagnostics.size){let n=e.diagnostics.map(t.changes),r=null,s=e.panel;if(e.selected){let a=t.changes.mapPos(e.selected.from,1);r=iN(n,e.selected.diagnostic,a)||iN(n,null,a)}!n.size&&s&&t.state.facet(FM).autoPanel&&(s=null),e=new $k(n,s,r)}for(let n of t.effects)if(n.is(TOt)){let r=t.state.facet(FM).autoPanel?n.value.length?zM.open:null:e.panel;e=$k.init(n.value,r,t.state)}else n.is(jOe)?e=new $k(e.diagnostics,n.value?zM.open:null,e.selected):n.is(jOt)&&(e=new $k(e.diagnostics,e.panel,n.value));return e},provide:e=>[TM.from(e,t=>t.panel),Pt.decorations.from(e,t=>t.diagnostics)]}),rWn=Nn.mark({class:"cm-lintRange cm-lintRange-active"});function sWn(e,t,n){let{diagnostics:r}=e.state.field(Ah),s,a=-1,i=-1;r.between(t-(n<0?1:0),t+(n>0?1:0),(c,u,{spec:d})=>{if(t>=c&&t<=u&&(c==u||(t>c||n>0)&&(t<u||n<0)))return s=d.diagnostics,a=c,i=u,!1});let l=e.state.facet(FM).tooltipFilter;return s&&l&&(s=l(s,e.state)),s?{pos:a,end:i,above:e.state.doc.lineAt(a).to<i,create(){return{dom:aWn(e,s)}}}:null}function aWn(e,t){return mi("ul",{class:"cm-tooltip-lint"},t.map(n=>IOt(e,n,!1)))}const iWn=e=>{let t=e.state.field(Ah,!1);(!t||!t.panel)&&e.dispatch({effects:nWn(e.state,[jOe.of(!0)])});let n=qke(e,zM.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},D9e=e=>{let t=e.state.field(Ah,!1);return!t||!t.panel?!1:(e.dispatch({effects:jOe.of(!1)}),!0)},oWn=e=>{let t=e.state.field(Ah,!1);if(!t)return!1;let n=e.state.selection.main,r=t.diagnostics.iter(n.to+1);return!r.value&&(r=t.diagnostics.iter(0),!r.value||r.from==n.from&&r.to==n.to)?!1:(e.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0}),!0)},lWn=[{key:"Mod-Shift-m",run:iWn,preventDefault:!0},{key:"F8",run:oWn}],FM=kn.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...Hy(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:L9e,tooltipFilter:L9e,needsRefresh:(t,n)=>t?n?r=>t(r)||n(r):t:n,hideOn:(t,n)=>t?n?(r,s,a)=>t(r,s,a)||n(r,s,a):t:n,autoPanel:(t,n)=>t||n})}}});function L9e(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function NOt(e){let t=[];if(e)e:for(let{name:n}of e){for(let r=0;r<n.length;r++){let s=n[r];if(/[a-zA-Z]/.test(s)&&!t.some(a=>a.toLowerCase()==s.toLowerCase())){t.push(s);continue e}}t.push("")}return t}function IOt(e,t,n){var r;let s=n?NOt(t.actions):[];return mi("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},mi("span",{class:"cm-diagnosticText"},t.renderMessage?t.renderMessage(e):t.message),(r=t.actions)===null||r===void 0?void 0:r.map((a,i)=>{let l=!1,c=p=>{if(p.preventDefault(),l)return;l=!0;let m=iN(e.state.field(Ah).diagnostics,t);m&&a.apply(e,m.from,m.to)},{name:u}=a,d=s[i]?u.indexOf(s[i]):-1,f=d<0?u:[u.slice(0,d),mi("u",u.slice(d,d+1)),u.slice(d+1)],h=a.markClass?" "+a.markClass:"";return mi("button",{type:"button",class:"cm-diagnosticAction"+h,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&mi("div",{class:"cm-diagnosticSource"},t.source))}class cWn extends op{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return mi("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class F9e{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=IOt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class zM{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)D9e(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:a}=this.items[this.selectedIndex],i=NOt(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=iN(this.view.state.field(Ah).diagnostics,a);c&&a.actions[l].apply(t,c.from,c.to)}}else return;s.preventDefault()},r=s=>{for(let a=0;a<this.items.length;a++)this.items[a].dom.contains(s.target)&&this.moveSelection(a)};this.list=mi("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=mi("div",{class:"cm-panel-lint"},this.list,mi("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>D9e(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Ah).selected;if(!t)return-1;for(let n=0;n<this.items.length;n++)if(this.items[n].diagnostic==t.diagnostic)return n;return-1}update(){let{diagnostics:t,selected:n}=this.view.state.field(Ah),r=0,s=!1,a=null,i=new Set;for(t.between(0,this.view.state.doc.length,(l,c,{spec:u})=>{for(let d of u.diagnostics){if(i.has(d))continue;i.add(d);let f=-1,h;for(let p=r;p<this.items.length;p++)if(this.items[p].diagnostic==d){f=p;break}f<0?(h=new F9e(this.view,d),this.items.splice(r,0,h),s=!0):(h=this.items[f],f>r&&(this.items.splice(r,f-r),s=!0)),n&&h.diagnostic==n.diagnostic?h.dom.hasAttribute("aria-selected")||(h.dom.setAttribute("aria-selected","true"),a=h):h.dom.hasAttribute("aria-selected")&&h.dom.removeAttribute("aria-selected"),r++}});r<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0);)s=!0,this.items.pop();this.items.length==0&&(this.items.push(new F9e(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),s=!0),a?(this.list.setAttribute("aria-activedescendant",a.id),this.view.requestMeasure({key:this,read:()=>({sel:a.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:l,panel:c})=>{let u=c.height/this.list.offsetHeight;l.top<c.top?this.list.scrollTop-=(c.top-l.top)/u:l.bottom>c.bottom&&(this.list.scrollTop+=(l.bottom-c.bottom)/u)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let t=this.list.firstChild;function n(){let r=t;t=r.nextSibling,r.remove()}for(let r of this.items)if(r.dom.parentNode==this.list){for(;t!=r.dom;)n();t=r.dom.nextSibling}else this.list.insertBefore(r.dom,t);for(;t;)n()}moveSelection(t){if(this.selectedIndex<0)return;let n=this.view.state.field(Ah),r=iN(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:jOt.of(r)})}static open(t){return new zM(t)}}function uWn(e,t='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${t}>${encodeURIComponent(e)}</svg>')`}function CF(e){return uWn(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${e}" fill="none" stroke-width=".7"/>`,'width="6" height="3"')}const dWn=Pt.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:CF("#d11")},".cm-lintRange-warning":{backgroundImage:CF("orange")},".cm-lintRange-info":{backgroundImage:CF("#999")},".cm-lintRange-hint":{backgroundImage:CF("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}});function fWn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function hWn(e){let t="hint",n=1;for(let r of e){let s=fWn(r.severity);s>n&&(n=s,t=r.severity)}return t}const pWn=[Ah,Pt.decorations.compute([Ah],e=>{let{selected:t,panel:n}=e.field(Ah);return!t||!n||t.from==t.to?Nn.none:Nn.set([rWn.range(t.from,t.to)])}),i9n(sWn,{hideOn:tWn}),dWn];var z9e=function(t){t===void 0&&(t={});var n=t,r=n.crosshairCursor,s=r===void 0?!1:r,a=[];t.closeBracketsKeymap!==!1&&(a=a.concat(rBn)),t.defaultKeymap!==!1&&(a=a.concat(OHn)),t.searchKeymap!==!1&&(a=a.concat(KHn)),t.historyKeymap!==!1&&(a=a.concat(IVn)),t.foldKeymap!==!1&&(a=a.concat(U9n)),t.completionKeymap!==!1&&(a=a.concat(CSt)),t.lintKeymap!==!1&&(a=a.concat(lWn));var i=[];return t.lineNumbers!==!1&&i.push(y9n()),t.highlightActiveLineGutter!==!1&&i.push(w9n()),t.highlightSpecialChars!==!1&&i.push(P8n()),t.history!==!1&&i.push(SVn()),t.foldGutter!==!1&&i.push(W9n()),t.drawSelection!==!1&&i.push(O8n()),t.dropCursor!==!1&&i.push(j8n()),t.allowMultipleSelections!==!1&&i.push(gs.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(P9n()),t.syntaxHighlighting!==!1&&i.push(fS(Y9n,{fallback:!0})),t.bracketMatching!==!1&&i.push(r7n()),t.closeBrackets!==!1&&i.push(J7n()),t.autocompletion!==!1&&i.push(OSt()),t.rectangularSelection!==!1&&i.push(G8n()),s!==!1&&i.push(K8n()),t.highlightActiveLine!==!1&&i.push(z8n()),t.highlightSelectionMatches!==!1&&i.push(NHn()),t.tabSize&&typeof t.tabSize=="number"&&i.push(TI.of(" ".repeat(t.tabSize))),i.concat([EI.of(a.flat())]).filter(Boolean)};const mWn="#e5c07b",B9e="#e06c75",gWn="#56b6c2",vWn="#ffffff",t9="#abb2bf",Ave="#7d8799",yWn="#61afef",bWn="#98c379",U9e="#d19a66",xWn="#c678dd",wWn="#21252b",q9e="#2c313a",V9e="#282c34",wte="#353a42",SWn="#3E4451",H9e="#528bff",kWn=Pt.theme({"&":{color:t9,backgroundColor:V9e},".cm-content":{caretColor:H9e},".cm-cursor, .cm-dropCursor":{borderLeftColor:H9e},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:SWn},".cm-panels":{backgroundColor:wWn,color:t9},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:"1px solid #457dff"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:"#6199ff2f"},".cm-activeLine":{backgroundColor:"#6699ff0b"},".cm-selectionMatch":{backgroundColor:"#aafe661a"},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bad0f847"},".cm-gutters":{backgroundColor:V9e,color:Ave,border:"none"},".cm-activeLineGutter":{backgroundColor:q9e},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:wte},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:wte,borderBottomColor:wte},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:q9e,color:t9}}},{dark:!0}),OWn=Jg.define([{tag:ue.keyword,color:xWn},{tag:[ue.name,ue.deleted,ue.character,ue.propertyName,ue.macroName],color:B9e},{tag:[ue.function(ue.variableName),ue.labelName],color:yWn},{tag:[ue.color,ue.constant(ue.name),ue.standard(ue.name)],color:U9e},{tag:[ue.definition(ue.name),ue.separator],color:t9},{tag:[ue.typeName,ue.className,ue.number,ue.changed,ue.annotation,ue.modifier,ue.self,ue.namespace],color:mWn},{tag:[ue.operator,ue.operatorKeyword,ue.url,ue.escape,ue.regexp,ue.link,ue.special(ue.string)],color:gWn},{tag:[ue.meta,ue.comment],color:Ave},{tag:ue.strong,fontWeight:"bold"},{tag:ue.emphasis,fontStyle:"italic"},{tag:ue.strikethrough,textDecoration:"line-through"},{tag:ue.link,color:Ave,textDecoration:"underline"},{tag:ue.heading,fontWeight:"bold",color:B9e},{tag:[ue.atom,ue.bool,ue.special(ue.variableName)],color:U9e},{tag:[ue.processingInstruction,ue.string,ue.inserted],color:bWn},{tag:ue.invalid,color:vWn}]),CWn=[kWn,fS(OWn)];var _Wn=Pt.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),EWn=function(t){t===void 0&&(t={});var n=t,r=n.indentWithTab,s=r===void 0?!0:r,a=n.editable,i=a===void 0?!0:a,l=n.readOnly,c=l===void 0?!1:l,u=n.theme,d=u===void 0?"light":u,f=n.placeholder,h=f===void 0?"":f,p=n.basicSetup,m=p===void 0?!0:p,v=[];switch(s&&v.unshift(EI.of([CHn])),m&&(typeof m=="boolean"?v.unshift(z9e()):v.unshift(z9e(m))),h&&v.unshift(V8n(h)),d){case"light":v.push(_Wn);break;case"dark":v.push(CWn);break;case"none":break;default:v.push(d);break}return i===!1&&v.push(Pt.editable.of(!1)),c&&v.push(gs.readOnly.of(!0)),[...v]},TWn=e=>({line:e.state.doc.lineAt(e.state.selection.main.from),lineCount:e.state.doc.lines,lineBreak:e.state.lineBreak,length:e.state.doc.length,readOnly:e.state.readOnly,tabSize:e.state.tabSize,selection:e.state.selection,selectionAsSingle:e.state.selection.asSingle().main,ranges:e.state.selection.ranges,selectionCode:e.state.sliceDoc(e.state.selection.main.from,e.state.selection.main.to),selections:e.state.selection.ranges.map(t=>e.state.sliceDoc(t.from,t.to)),selectedText:e.state.selection.ranges.some(t=>!t.empty)});class jWn{constructor(t,n){this.timeLeftMS=void 0,this.timeoutMS=void 0,this.isCancelled=!1,this.isTimeExhausted=!1,this.callbacks=[],this.timeLeftMS=n,this.timeoutMS=n,this.callbacks.push(t)}tick(){if(!this.isCancelled&&!this.isTimeExhausted&&(this.timeLeftMS--,this.timeLeftMS<=0)){this.isTimeExhausted=!0;var t=this.callbacks.slice();this.callbacks.length=0,t.forEach(n=>{try{n()}catch(r){console.error("TimeoutLatch callback error:",r)}})}}cancel(){this.isCancelled=!0,this.callbacks.length=0}reset(){this.timeLeftMS=this.timeoutMS,this.isCancelled=!1,this.isTimeExhausted=!1}get isDone(){return this.isCancelled||this.isTimeExhausted}}class W9e{constructor(){this.interval=null,this.latches=new Set}add(t){this.latches.add(t),this.start()}remove(t){this.latches.delete(t),this.latches.size===0&&this.stop()}start(){this.interval===null&&(this.interval=setInterval(()=>{this.latches.forEach(t=>{t.tick(),t.isDone&&this.remove(t)})},1))}stop(){this.interval!==null&&(clearInterval(this.interval),this.interval=null)}}var Ste=null,NWn=()=>typeof window>"u"?new W9e:(Ste||(Ste=new W9e),Ste),IWn=Pt.theme({"& .cm-scroller":{height:"100% !important"}}),Z9e=null,kte=null;function AWn(e,t,n,r,s,a){if(!e&&!t&&!n&&!r&&!s&&!a)return null;var i=JSON.stringify({height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a});return i===Z9e||(Z9e=i,kte=Pt.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a}})),kte}var G9e=Vy.define(),RWn=200,PWn=[];function $Wn(e){var t=e.value,n=e.selection,r=e.onChange,s=e.onStatistics,a=e.onCreateEditor,i=e.onUpdate,l=e.extensions,c=l===void 0?PWn:l,u=e.autoFocus,d=e.theme,f=d===void 0?"light":d,h=e.height,p=h===void 0?null:h,m=e.minHeight,v=m===void 0?null:m,y=e.maxHeight,b=y===void 0?null:y,x=e.width,w=x===void 0?null:x,k=e.minWidth,C=k===void 0?null:k,_=e.maxWidth,T=_===void 0?null:_,E=e.placeholder,N=E===void 0?"":E,I=e.editable,A=I===void 0?!0:I,P=e.readOnly,L=P===void 0?!1:P,D=e.indentWithTab,B=D===void 0?!0:D,H=e.basicSetup,q=H===void 0?!0:H,z=e.root,V=e.initialState,M=g.useState(),G=M[0],F=M[1],R=g.useState(),U=R[0],Z=R[1],Y=g.useState(),te=Y[0],J=Y[1],ee=g.useState(()=>({current:null}))[0],re=g.useState(()=>({current:null}))[0],ae=AWn(p,v,b,w,C,T),X=Pt.updateListener.of(ce=>{if(ce.docChanged&&typeof r=="function"&&!ce.transactions.some(he=>he.annotation(G9e))){ee.current?ee.current.reset():(ee.current=new jWn(()=>{if(re.current){var he=re.current;re.current=null,he()}ee.current=null},RWn),NWn().add(ee.current));var le=ce.state.doc,be=le.toString();r(be,ce)}s&&s(TWn(ce))}),ne=EWn({theme:f,editable:A,readOnly:L,placeholder:N,indentWithTab:B,basicSetup:q}),se=[X,...ae?[ae]:[],IWn,...ne];return i&&typeof i=="function"&&se.push(Pt.updateListener.of(i)),se=se.concat(c),g.useLayoutEffect(()=>{if(G&&!te){var ce={doc:t,selection:n,extensions:se},le=V?gs.fromJSON(V.json,ce,V.fields):gs.create(ce);if(J(le),!U){var be=new Pt({state:le,parent:G,root:z});Z(be),a&&a(be,le)}}return()=>{U&&(J(void 0),Z(void 0))}},[G,te]),g.useEffect(()=>{e.container&&F(e.container)},[e.container]),g.useEffect(()=>()=>{U&&(U.destroy(),Z(void 0)),ee.current&&(ee.current.cancel(),ee.current=null)},[U]),g.useEffect(()=>{u&&U&&U.focus()},[u,U]),g.useEffect(()=>{U&&U.dispatch({effects:vr.reconfigure.of(se)})},[f,c,p,v,b,w,C,T,N,A,L,B,q,r,i]),g.useEffect(()=>{if(t!==void 0){var ce=U?U.state.doc.toString():"";if(U&&t!==ce){var le=ee.current&&!ee.current.isDone,be=()=>{U&&t!==U.state.doc.toString()&&U.dispatch({changes:{from:0,to:U.state.doc.toString().length,insert:t||""},annotations:[G9e.of(!0)]})};le?re.current=be:be()}}},[t,U]),{state:te,setState:J,view:U,setView:Z,container:G,setContainer:F}}var MWn=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],rd=g.forwardRef((e,t)=>{var n=e.className,r=e.value,s=r===void 0?"":r,a=e.selection,i=e.extensions,l=i===void 0?[]:i,c=e.onChange,u=e.onStatistics,d=e.onCreateEditor,f=e.onUpdate,h=e.autoFocus,p=e.theme,m=p===void 0?"light":p,v=e.height,y=e.minHeight,b=e.maxHeight,x=e.width,w=e.minWidth,k=e.maxWidth,C=e.basicSetup,_=e.placeholder,T=e.indentWithTab,E=e.editable,N=e.readOnly,I=e.root,A=e.initialState,P=Fkt(e,MWn),L=g.useRef(null),D=$Wn({root:I,value:s,autoFocus:h,theme:m,height:v,minHeight:y,maxHeight:b,width:x,minWidth:w,maxWidth:k,basicSetup:C,placeholder:_,indentWithTab:T,editable:E,readOnly:N,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),B=D.state,H=D.view,q=D.container,z=D.setContainer;g.useImperativeHandle(t,()=>({editor:L.current,state:B,view:H}),[L,q,B,H]);var V=g.useCallback(G=>{L.current=G,z(G)},[z]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var M=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",sC({ref:V,className:""+M+(n?" "+n:"")},P))});rd.displayName="CodeMirror";const DWn={js:"javascript",javascript:"javascript",mjs:"javascript",cjs:"javascript",node:"javascript",ts:"typescript",typescript:"typescript",mts:"typescript",cts:"typescript",tsx:"tsx",jsx:"jsx",json:"json",json5:"json",md:"markdown",markdown:"markdown",py:"python",python:"python",sh:"bash",bash:"bash",shell:"bash",zsh:"bash",yml:"yaml",yaml:"yaml",diff:"diff",patch:"diff",css:"css",scss:"css",html:"html",htm:"html",xml:"xml",svg:"xml",sql:"sql"};let Ote=null;function LWn(){return Ote||(Ote=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Va(()=>import("./core-B2OyzGRp.js"),__vite__mapDeps([0,1,2]),import.meta.url),Va(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[Va(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Va(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Va(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Va(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Va(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Va(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Va(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Va(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Va(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Va(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Va(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Va(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Va(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Va(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([4,5,6]),import.meta.url),Va(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Va(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),Ote}async function FWn(e,t){const n=DWn[t?.toLowerCase()];if(!n)return null;const r=await LWn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function zWn(e){return new eC(Gke.define(e))}const AOt=[gg.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return Va(()=>Promise.resolve().then(()=>wF),void 0,import.meta.url).then(e=>e.javascript())}}),gg.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return Va(()=>Promise.resolve().then(()=>m7n),void 0,import.meta.url).then(e=>e.json())}}),gg.of({name:"JSX",extensions:["jsx"],load(){return Va(()=>Promise.resolve().then(()=>wF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),gg.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return Va(()=>Promise.resolve().then(()=>cVn),void 0,import.meta.url).then(e=>e.markdown())}}),gg.of({name:"TSX",extensions:["tsx"],load(){return Va(()=>Promise.resolve().then(()=>wF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),gg.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return Va(()=>Promise.resolve().then(()=>wF),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),gg.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return Va(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>zWn(e.shell))}})];function BWn(e,t=5){if(!e?.properties)return[];const n=[];function r(s,a,i){if(i>t)return;const l=Array.isArray(s.type)?s.type.join(" | "):s.type;if(n.push({path:a,label:a,description:s.description??s.title,type:l}),s.properties)for(const[c,u]of Object.entries(s.properties))r(u,`${a}.${c}`,i+1);if(s.items?.properties)for(const[c,u]of Object.entries(s.items.properties))r(u,`${a}[].${c}`,i+1)}for(const[s,a]of Object.entries(e.properties))r(a,s,1);return n}function UWn(e){const t=BWn(e);return OSt({override:[qWn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function qWn(e){return t=>{const r=t.state.sliceDoc(Math.max(0,t.pos-50),t.pos).match(/\{\{([a-zA-Z0-9_.\[\]]*)?$/);if(!r)return null;const s=r[1]??"",a=t.pos-s.length,i=s?e.filter(c=>c.path.toLowerCase().startsWith(s.toLowerCase())):e;if(i.length===0)return null;const l=i.map(c=>({label:c.path,displayLabel:c.path,detail:c.type,info:c.description,apply:(u,d,f,h)=>{const v=u.state.sliceDoc(h,h+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:h,insert:v},selection:{anchor:f+v.length}})}}));return{from:a,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const VWn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,HWn=Nn.mark({class:"cm-variable-highlight"}),Q9e=new L1t({regexp:VWn,decoration:()=>HWn}),WWn=Co.fromClass(class{decorations;constructor(e){this.decorations=Q9e.createDeco(e)}update(e){this.decorations=Q9e.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),ZWn=WWn;function GWn(){const e=NI({settings:{fontFamily:"var(--font-mono)",fontSize:"0.8rem",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"var(--neutral2)",background:"transparent",foreground:"var(--neutral6)",caret:"var(--neutral6)"},styles:[{tag:[ue.className,ue.propertyName],color:"var(--neutral6)"},{tag:ue.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[ue.heading1,ue.heading2,ue.heading3,ue.heading4,ue.heading5,ue.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:ue.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:ue.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:ue.link,color:"var(--accent3)",textDecoration:"underline"},{tag:ue.url,color:"var(--accent3)"},{tag:ue.monospace,color:"var(--neutral6)"},{tag:ue.strikethrough,textDecoration:"line-through"},{tag:ue.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=Pt.theme({".cm-editor":{backgroundColor:"transparent"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{color:"var(--neutral3)"},".cm-cursor":{borderLeftColor:"var(--neutral6)"},".cm-selectionBackground, .cm-content ::selection":{backgroundColor:"color-mix(in srgb, var(--accent3) 22%, transparent)"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}});return[e,t]}function QWn(){const e=Pt.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"0.8rem"},"&.cm-editor .cm-scroller":{fontFamily:"var(--font-mono)"},".cm-gutters":{backgroundColor:"transparent",color:"var(--neutral2)",borderRight:"none"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-activeLine":{backgroundColor:"transparent"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{backgroundColor:"transparent",color:"var(--neutral3)"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"var(--neutral6)"},"&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection":{background:"color-mix(in srgb, var(--accent3) 22%, transparent) !important"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}}),t=Jg.define([{tag:[ue.comment,ue.bracket],color:"var(--neutral2)"},{tag:[ue.string,ue.meta,ue.regexp],color:"var(--accent1)"},{tag:[ue.atom,ue.bool,ue.special(ue.variableName)],color:"var(--accent6)"},{tag:[ue.keyword,ue.operator,ue.tagName],color:"var(--accent2)"},{tag:[ue.function(ue.propertyName),ue.propertyName],color:"var(--accent5)"},{tag:[ue.definition(ue.variableName),ue.function(ue.variableName),ue.className,ue.attributeName],color:"var(--accent3)"},{tag:[ue.variableName,ue.number],color:"var(--accent5)"},{tag:[ue.name,ue.quote],color:"var(--accent1)"},{tag:ue.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[ue.heading1,ue.heading2,ue.heading3,ue.heading4,ue.heading5,ue.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[ue.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[ue.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:ue.link,color:"var(--accent3)",textDecoration:"underline"},{tag:ue.url,color:"var(--accent3)"},{tag:ue.monospace,color:"var(--neutral6)"},{tag:ue.strikethrough,textDecoration:"line-through"},{tag:[ue.deleted],color:"var(--accent2)"},{tag:ue.invalid,color:"var(--error)"},{tag:[ue.standard(ue.tagName)],color:"var(--accent1)"}]);return[e,fS(t)]}const o0=()=>{const e=a_().resolvedTheme==="dark";return g.useMemo(()=>e?GWn():QWn(),[e])},YWn=uo(K("relative overflow-hidden font-mono outline-hidden focus-within:outline-hidden focus:outline-hidden","duration-normal transition-colors ease-out-custom"),{variants:{variant:{default:"rounded-md border border-border1 bg-surface3 p-1 focus-within:border-neutral6/20",embedded:"rounded-none border-none bg-transparent p-0"}},defaultVariants:{variant:"default"}}),KWn=ip.highest(Pt.editorAttributes.of({style:"outline: none"})),XWn=ip.highest(Pt.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),JWn=[KWn,XWn],Gr=g.forwardRef(({data:e,value:t,onChange:n,showCopyButton:r=!0,className:s,language:a="json",highlightVariables:i=!1,placeholder:l,schema:c,autoFocus:u,lineNumbers:d=!0,lineWrapping:f=!0,editable:h,variant:p,...m},v)=>{const y=o0(),b=e?JSON.stringify(e,null,2):t??"",x=g.useMemo(()=>{const w=[...JWn];return f&&w.push(Pt.lineWrapping),a==="json"?w.push(zh):a==="markdown"&&w.push(wOe({base:rC,codeLanguages:AOt})),i&&a==="markdown"&&w.push(ZWn),c&&a==="markdown"&&w.push(UWn(c)),h===!1&&w.push(gs.readOnly.of(!0)),w},[a,i,c,h,f]);return o.jsxs("div",{className:K(YWn({variant:p}),s),...m,children:[r&&o.jsx(_a,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(rd,{ref:v,value:b,theme:y,extensions:x,onChange:n,editable:h,"aria-label":"Code editor",placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),eZn=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},tZn=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=o0(),{settings:r,setSettings:s}=VH(),a=r?.tracingOptions,i=g.useMemo(()=>eZn(a),[a]),[l,c]=g.useState(()=>i),u=g.useRef(!1);g.useEffect(()=>{u.current||c(i)},[i]);const d=h=>{u.current=!0,c(h)},f=()=>{if(!l){s({...r,tracingOptions:void 0}),t?.();return}try{const h=JSON.parse(l);typeof h=="object"&&h!==null&&s({...r,tracingOptions:h})}catch{return}t?.()};return o.jsxs("div",{className:"space-y-2 px-5 py-2",children:[o.jsx(ve,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),o.jsx(rd,{value:l,onChange:d,theme:n,extensions:[zh],className:K("overflow-y-scroll bg-surface3 rounded-lg overflow-hidden p-3",e)}),o.jsx("div",{className:"flex items-center justify-end",children:o.jsx(ie,{type:"button",onClick:f,children:"Save"})})]})},nZn=()=>{const[e,t]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx(ie,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(Qe,{children:o.jsx(D0e,{})})})}),o.jsx(yn,{children:"Run Options"})]}),o.jsx(pr,{open:e,onOpenChange:t,children:o.jsxs(mr,{children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Run Options"}),o.jsx(Cs,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx(jr,{children:o.jsx(tZn,{onSaved:()=>t(!1)})})]})})]})};function rZn({status:e}){switch(e){case"running":return o.jsx(Vt,{});case"failed":return o.jsx(or,{className:"text-accent2"});case"canceled":return o.jsx(Mc,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(c1,{className:"text-neutral3"});case"suspended":return o.jsx(EV,{className:"text-accent3"});case"success":return o.jsx(Ur,{className:"text-accent1"});default:return o.jsx(c1,{className:"text-neutral3"})}}function ROt({status:e}){return o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx(Qe,{"aria-label":e,className:"shrink-0",children:o.jsx(rZn,{status:e})})}),o.jsx(yn,{children:e})]})}var Cte,Y9e;function NOe(){if(Y9e)return Cte;Y9e=1;var e="\0",t="\0",n="";class r{_isDirected=!0;_isMultigraph=!1;_isCompound=!1;_label;_defaultNodeLabelFn=()=>{};_defaultEdgeLabelFn=()=>{};_nodes={};_in={};_preds={};_out={};_sucs={};_edgeObjs={};_edgeLabels={};_nodeCount=0;_edgeCount=0;_parent;_children;constructor(d){d&&(this._isDirected=Object.hasOwn(d,"directed")?d.directed:!0,this._isMultigraph=Object.hasOwn(d,"multigraph")?d.multigraph:!1,this._isCompound=Object.hasOwn(d,"compound")?d.compound:!1),this._isCompound&&(this._parent={},this._children={},this._children[t]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(d){return this._label=d,this}graph(){return this._label}setDefaultNodeLabel(d){return this._defaultNodeLabelFn=d,typeof d!="function"&&(this._defaultNodeLabelFn=()=>d),this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){var d=this;return this.nodes().filter(f=>Object.keys(d._in[f]).length===0)}sinks(){var d=this;return this.nodes().filter(f=>Object.keys(d._out[f]).length===0)}setNodes(d,f){var h=arguments,p=this;return d.forEach(function(m){h.length>1?p.setNode(m,f):p.setNode(m)}),this}setNode(d,f){return Object.hasOwn(this._nodes,d)?(arguments.length>1&&(this._nodes[d]=f),this):(this._nodes[d]=arguments.length>1?f:this._defaultNodeLabelFn(d),this._isCompound&&(this._parent[d]=t,this._children[d]={},this._children[t][d]=!0),this._in[d]={},this._preds[d]={},this._out[d]={},this._sucs[d]={},++this._nodeCount,this)}node(d){return this._nodes[d]}hasNode(d){return Object.hasOwn(this._nodes,d)}removeNode(d){var f=this;if(Object.hasOwn(this._nodes,d)){var h=p=>f.removeEdge(f._edgeObjs[p]);delete this._nodes[d],this._isCompound&&(this._removeFromParentsChildList(d),delete this._parent[d],this.children(d).forEach(function(p){f.setParent(p)}),delete this._children[d]),Object.keys(this._in[d]).forEach(h),delete this._in[d],delete this._preds[d],Object.keys(this._out[d]).forEach(h),delete this._out[d],delete this._sucs[d],--this._nodeCount}return this}setParent(d,f){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(f===void 0)f=t;else{f+="";for(var h=f;h!==void 0;h=this.parent(h))if(h===d)throw new Error("Setting "+f+" as parent of "+d+" would create a cycle");this.setNode(f)}return this.setNode(d),this._removeFromParentsChildList(d),this._parent[d]=f,this._children[f][d]=!0,this}_removeFromParentsChildList(d){delete this._children[this._parent[d]][d]}parent(d){if(this._isCompound){var f=this._parent[d];if(f!==t)return f}}children(d=t){if(this._isCompound){var f=this._children[d];if(f)return Object.keys(f)}else{if(d===t)return this.nodes();if(this.hasNode(d))return[]}}predecessors(d){var f=this._preds[d];if(f)return Object.keys(f)}successors(d){var f=this._sucs[d];if(f)return Object.keys(f)}neighbors(d){var f=this.predecessors(d);if(f){const p=new Set(f);for(var h of this.successors(d))p.add(h);return Array.from(p.values())}}isLeaf(d){var f;return this.isDirected()?f=this.successors(d):f=this.neighbors(d),f.length===0}filterNodes(d){var f=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});f.setGraph(this.graph());var h=this;Object.entries(this._nodes).forEach(function([v,y]){d(v)&&f.setNode(v,y)}),Object.values(this._edgeObjs).forEach(function(v){f.hasNode(v.v)&&f.hasNode(v.w)&&f.setEdge(v,h.edge(v))});var p={};function m(v){var y=h.parent(v);return y===void 0||f.hasNode(y)?(p[v]=y,y):y in p?p[y]:m(y)}return this._isCompound&&f.nodes().forEach(v=>f.setParent(v,m(v))),f}setDefaultEdgeLabel(d){return this._defaultEdgeLabelFn=d,typeof d!="function"&&(this._defaultEdgeLabelFn=()=>d),this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(d,f){var h=this,p=arguments;return d.reduce(function(m,v){return p.length>1?h.setEdge(m,v,f):h.setEdge(m,v),v}),this}setEdge(){var d,f,h,p,m=!1,v=arguments[0];typeof v=="object"&&v!==null&&"v"in v?(d=v.v,f=v.w,h=v.name,arguments.length===2&&(p=arguments[1],m=!0)):(d=v,f=arguments[1],h=arguments[3],arguments.length>2&&(p=arguments[2],m=!0)),d=""+d,f=""+f,h!==void 0&&(h=""+h);var y=i(this._isDirected,d,f,h);if(Object.hasOwn(this._edgeLabels,y))return m&&(this._edgeLabels[y]=p),this;if(h!==void 0&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(d),this.setNode(f),this._edgeLabels[y]=m?p:this._defaultEdgeLabelFn(d,f,h);var b=l(this._isDirected,d,f,h);return d=b.v,f=b.w,Object.freeze(b),this._edgeObjs[y]=b,s(this._preds[f],d),s(this._sucs[d],f),this._in[f][y]=b,this._out[d][y]=b,this._edgeCount++,this}edge(d,f,h){var p=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,h);return this._edgeLabels[p]}edgeAsObj(){const d=this.edge(...arguments);return typeof d!="object"?{label:d}:d}hasEdge(d,f,h){var p=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,h);return Object.hasOwn(this._edgeLabels,p)}removeEdge(d,f,h){var p=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,h),m=this._edgeObjs[p];return m&&(d=m.v,f=m.w,delete this._edgeLabels[p],delete this._edgeObjs[p],a(this._preds[f],d),a(this._sucs[d],f),delete this._in[f][p],delete this._out[d][p],this._edgeCount--),this}inEdges(d,f){var h=this._in[d];if(h){var p=Object.values(h);return f?p.filter(m=>m.v===f):p}}outEdges(d,f){var h=this._out[d];if(h){var p=Object.values(h);return f?p.filter(m=>m.w===f):p}}nodeEdges(d,f){var h=this.inEdges(d,f);if(h)return h.concat(this.outEdges(d,f))}}function s(u,d){u[d]?u[d]++:u[d]=1}function a(u,d){--u[d]||delete u[d]}function i(u,d,f,h){var p=""+d,m=""+f;if(!u&&p>m){var v=p;p=m,m=v}return p+n+m+n+(h===void 0?e:h)}function l(u,d,f,h){var p=""+d,m=""+f;if(!u&&p>m){var v=p;p=m,m=v}var y={v:p,w:m};return h&&(y.name=h),y}function c(u,d){return i(u,d.v,d.w,d.name)}return Cte=r,Cte}var _te,K9e;function sZn(){return K9e||(K9e=1,_te="2.2.4"),_te}var Ete,X9e;function aZn(){return X9e||(X9e=1,Ete={Graph:NOe(),version:sZn()}),Ete}var Tte,J9e;function iZn(){if(J9e)return Tte;J9e=1;var e=NOe();Tte={write:t,read:s};function t(a){var i={options:{directed:a.isDirected(),multigraph:a.isMultigraph(),compound:a.isCompound()},nodes:n(a),edges:r(a)};return a.graph()!==void 0&&(i.value=structuredClone(a.graph())),i}function n(a){return a.nodes().map(function(i){var l=a.node(i),c=a.parent(i),u={v:i};return l!==void 0&&(u.value=l),c!==void 0&&(u.parent=c),u})}function r(a){return a.edges().map(function(i){var l=a.edge(i),c={v:i.v,w:i.w};return i.name!==void 0&&(c.name=i.name),l!==void 0&&(c.value=l),c})}function s(a){var i=new e(a.options).setGraph(a.value);return a.nodes.forEach(function(l){i.setNode(l.v,l.value),l.parent&&i.setParent(l.v,l.parent)}),a.edges.forEach(function(l){i.setEdge({v:l.v,w:l.w,name:l.name},l.value)}),i}return Tte}var jte,e7e;function oZn(){if(e7e)return jte;e7e=1,jte=e;function e(t){var n={},r=[],s;function a(i){Object.hasOwn(n,i)||(n[i]=!0,s.push(i),t.successors(i).forEach(a),t.predecessors(i).forEach(a))}return t.nodes().forEach(function(i){s=[],a(i),s.length&&r.push(s)}),r}return jte}var Nte,t7e;function POt(){if(t7e)return Nte;t7e=1;class e{_arr=[];_keyIndices={};size(){return this._arr.length}keys(){return this._arr.map(function(n){return n.key})}has(n){return Object.hasOwn(this._keyIndices,n)}priority(n){var r=this._keyIndices[n];if(r!==void 0)return this._arr[r].priority}min(){if(this.size()===0)throw new Error("Queue underflow");return this._arr[0].key}add(n,r){var s=this._keyIndices;if(n=String(n),!Object.hasOwn(s,n)){var a=this._arr,i=a.length;return s[n]=i,a.push({key:n,priority:r}),this._decrease(i),!0}return!1}removeMin(){this._swap(0,this._arr.length-1);var n=this._arr.pop();return delete this._keyIndices[n.key],this._heapify(0),n.key}decrease(n,r){var s=this._keyIndices[n];if(r>this._arr[s].priority)throw new Error("New priority is greater than current priority. Key: "+n+" Old: "+this._arr[s].priority+" New: "+r);this._arr[s].priority=r,this._decrease(s)}_heapify(n){var r=this._arr,s=2*n,a=s+1,i=n;s<r.length&&(i=r[s].priority<r[i].priority?s:i,a<r.length&&(i=r[a].priority<r[i].priority?a:i),i!==n&&(this._swap(n,i),this._heapify(i)))}_decrease(n){for(var r=this._arr,s=r[n].priority,a;n!==0&&(a=n>>1,!(r[a].priority<s));)this._swap(n,a),n=a}_swap(n,r){var s=this._arr,a=this._keyIndices,i=s[n],l=s[r];s[n]=l,s[r]=i,a[l.key]=n,a[i.key]=r}}return Nte=e,Nte}var Ite,n7e;function $Ot(){if(n7e)return Ite;n7e=1;var e=POt();Ite=n;var t=()=>1;function n(s,a,i,l){return r(s,String(a),i||t,l||function(c){return s.outEdges(c)})}function r(s,a,i,l){var c={},u=new e,d,f,h=function(p){var m=p.v!==d?p.v:p.w,v=c[m],y=i(p),b=f.distance+y;if(y<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+p+" Weight: "+y);b<v.distance&&(v.distance=b,v.predecessor=d,u.decrease(m,b))};for(s.nodes().forEach(function(p){var m=p===a?0:Number.POSITIVE_INFINITY;c[p]={distance:m},u.add(p,m)});u.size()>0&&(d=u.removeMin(),f=c[d],f.distance!==Number.POSITIVE_INFINITY);)l(d).forEach(h);return c}return Ite}var Ate,r7e;function lZn(){if(r7e)return Ate;r7e=1;var e=$Ot();Ate=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return Ate}var Rte,s7e;function MOt(){if(s7e)return Rte;s7e=1,Rte=e;function e(t){var n=0,r=[],s={},a=[];function i(l){var c=s[l]={onStack:!0,lowlink:n,index:n++};if(r.push(l),t.successors(l).forEach(function(f){Object.hasOwn(s,f)?s[f].onStack&&(c.lowlink=Math.min(c.lowlink,s[f].index)):(i(f),c.lowlink=Math.min(c.lowlink,s[f].lowlink))}),c.lowlink===c.index){var u=[],d;do d=r.pop(),s[d].onStack=!1,u.push(d);while(l!==d);a.push(u)}}return t.nodes().forEach(function(l){Object.hasOwn(s,l)||i(l)}),a}return Rte}var Pte,a7e;function cZn(){if(a7e)return Pte;a7e=1;var e=MOt();Pte=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return Pte}var $te,i7e;function uZn(){if(i7e)return $te;i7e=1,$te=t;var e=()=>1;function t(r,s,a){return n(r,s||e,a||function(i){return r.outEdges(i)})}function n(r,s,a){var i={},l=r.nodes();return l.forEach(function(c){i[c]={},i[c][c]={distance:0},l.forEach(function(u){c!==u&&(i[c][u]={distance:Number.POSITIVE_INFINITY})}),a(c).forEach(function(u){var d=u.v===c?u.w:u.v,f=s(u);i[c][d]={distance:f,predecessor:c}})}),l.forEach(function(c){var u=i[c];l.forEach(function(d){var f=i[d];l.forEach(function(h){var p=f[c],m=u[h],v=f[h],y=p.distance+m.distance;y<v.distance&&(v.distance=y,v.predecessor=m.predecessor)})})}),i}return $te}var Mte,o7e;function DOt(){if(o7e)return Mte;o7e=1;function e(n){var r={},s={},a=[];function i(l){if(Object.hasOwn(s,l))throw new t;Object.hasOwn(r,l)||(s[l]=!0,r[l]=!0,n.predecessors(l).forEach(i),delete s[l],a.push(l))}if(n.sinks().forEach(i),Object.keys(r).length!==n.nodeCount())throw new t;return a}class t extends Error{constructor(){super(...arguments)}}return Mte=e,e.CycleException=t,Mte}var Dte,l7e;function dZn(){if(l7e)return Dte;l7e=1;var e=DOt();Dte=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return Dte}var Lte,c7e;function LOt(){if(c7e)return Lte;c7e=1,Lte=e;function e(s,a,i){Array.isArray(a)||(a=[a]);var l=s.isDirected()?f=>s.successors(f):f=>s.neighbors(f),c=i==="post"?t:n,u=[],d={};return a.forEach(f=>{if(!s.hasNode(f))throw new Error("Graph does not have node: "+f);c(f,l,d,u)}),u}function t(s,a,i,l){for(var c=[[s,!1]];c.length>0;){var u=c.pop();u[1]?l.push(u[0]):Object.hasOwn(i,u[0])||(i[u[0]]=!0,c.push([u[0],!0]),r(a(u[0]),d=>c.push([d,!1])))}}function n(s,a,i,l){for(var c=[s];c.length>0;){var u=c.pop();Object.hasOwn(i,u)||(i[u]=!0,l.push(u),r(a(u),d=>c.push(d)))}}function r(s,a){for(var i=s.length;i--;)a(s[i],i,s);return s}return Lte}var Fte,u7e;function fZn(){if(u7e)return Fte;u7e=1;var e=LOt();Fte=t;function t(n,r){return e(n,r,"post")}return Fte}var zte,d7e;function hZn(){if(d7e)return zte;d7e=1;var e=LOt();zte=t;function t(n,r){return e(n,r,"pre")}return zte}var Bte,f7e;function pZn(){if(f7e)return Bte;f7e=1;var e=NOe(),t=POt();Bte=n;function n(r,s){var a=new e,i={},l=new t,c;function u(f){var h=f.v===c?f.w:f.v,p=l.priority(h);if(p!==void 0){var m=s(f);m<p&&(i[h]=c,l.decrease(h,m))}}if(r.nodeCount()===0)return a;r.nodes().forEach(function(f){l.add(f,Number.POSITIVE_INFINITY),a.setNode(f)}),l.decrease(r.nodes()[0],0);for(var d=!1;l.size()>0;){if(c=l.removeMin(),Object.hasOwn(i,c))a.setEdge(c,i[c]);else{if(d)throw new Error("Input graph is not connected: "+r);d=!0}r.nodeEdges(c).forEach(u)}return a}return Bte}var Ute,h7e;function mZn(){return h7e||(h7e=1,Ute={components:oZn(),dijkstra:$Ot(),dijkstraAll:lZn(),findCycles:cZn(),floydWarshall:uZn(),isAcyclic:dZn(),postorder:fZn(),preorder:hZn(),prim:pZn(),tarjan:MOt(),topsort:DOt()}),Ute}var qte,p7e;function Wg(){if(p7e)return qte;p7e=1;var e=aZn();return qte={Graph:e.Graph,json:iZn(),alg:mZn(),version:e.version},qte}var Vte,m7e;function gZn(){if(m7e)return Vte;m7e=1;class e{constructor(){let s={};s._next=s._prev=s,this._sentinel=s}dequeue(){let s=this._sentinel,a=s._prev;if(a!==s)return t(a),a}enqueue(s){let a=this._sentinel;s._prev&&s._next&&t(s),s._next=a._next,a._next._prev=s,a._next=s,s._prev=a}toString(){let s=[],a=this._sentinel,i=a._prev;for(;i!==a;)s.push(JSON.stringify(i,n)),i=i._prev;return"["+s.join(", ")+"]"}}function t(r){r._prev._next=r._next,r._next._prev=r._prev,delete r._next,delete r._prev}function n(r,s){if(r!=="_next"&&r!=="_prev")return s}return Vte=e,Vte}var Hte,g7e;function vZn(){if(g7e)return Hte;g7e=1;let e=Wg().Graph,t=gZn();Hte=r;let n=()=>1;function r(u,d){if(u.nodeCount()<=1)return[];let f=i(u,d||n);return s(f.graph,f.buckets,f.zeroIdx).flatMap(p=>u.outEdges(p.v,p.w))}function s(u,d,f){let h=[],p=d[d.length-1],m=d[0],v;for(;u.nodeCount();){for(;v=m.dequeue();)a(u,d,f,v);for(;v=p.dequeue();)a(u,d,f,v);if(u.nodeCount()){for(let y=d.length-2;y>0;--y)if(v=d[y].dequeue(),v){h=h.concat(a(u,d,f,v,!0));break}}}return h}function a(u,d,f,h,p){let m=p?[]:void 0;return u.inEdges(h.v).forEach(v=>{let y=u.edge(v),b=u.node(v.v);p&&m.push({v:v.v,w:v.w}),b.out-=y,l(d,f,b)}),u.outEdges(h.v).forEach(v=>{let y=u.edge(v),b=v.w,x=u.node(b);x.in-=y,l(d,f,x)}),u.removeNode(h.v),m}function i(u,d){let f=new e,h=0,p=0;u.nodes().forEach(y=>{f.setNode(y,{v:y,in:0,out:0})}),u.edges().forEach(y=>{let b=f.edge(y.v,y.w)||0,x=d(y),w=b+x;f.setEdge(y.v,y.w,w),p=Math.max(p,f.node(y.v).out+=x),h=Math.max(h,f.node(y.w).in+=x)});let m=c(p+h+3).map(()=>new t),v=h+1;return f.nodes().forEach(y=>{l(m,v,f.node(y))}),{graph:f,buckets:m,zeroIdx:v}}function l(u,d,f){f.out?f.in?u[f.out-f.in+d].enqueue(f):u[u.length-1].enqueue(f):u[0].enqueue(f)}function c(u){const d=[];for(let f=0;f<u;f++)d.push(f);return d}return Hte}var Wte,v7e;function $l(){if(v7e)return Wte;v7e=1;let e=Wg().Graph;Wte={addBorderNode:d,addDummyNode:t,applyWithChunking:p,asNonCompoundGraph:r,buildLayerMatrix:l,intersectRect:i,mapValues:_,maxRank:m,normalizeRanks:c,notime:b,partition:v,pick:C,predecessorWeights:a,range:k,removeEmptyRanks:u,simplify:n,successorWeights:s,time:y,uniqueId:w,zipObject:T};function t(E,N,I,A){for(var P=A;E.hasNode(P);)P=w(A);return I.dummy=N,E.setNode(P,I),P}function n(E){let N=new e().setGraph(E.graph());return E.nodes().forEach(I=>N.setNode(I,E.node(I))),E.edges().forEach(I=>{let A=N.edge(I.v,I.w)||{weight:0,minlen:1},P=E.edge(I);N.setEdge(I.v,I.w,{weight:A.weight+P.weight,minlen:Math.max(A.minlen,P.minlen)})}),N}function r(E){let N=new e({multigraph:E.isMultigraph()}).setGraph(E.graph());return E.nodes().forEach(I=>{E.children(I).length||N.setNode(I,E.node(I))}),E.edges().forEach(I=>{N.setEdge(I,E.edge(I))}),N}function s(E){let N=E.nodes().map(I=>{let A={};return E.outEdges(I).forEach(P=>{A[P.w]=(A[P.w]||0)+E.edge(P).weight}),A});return T(E.nodes(),N)}function a(E){let N=E.nodes().map(I=>{let A={};return E.inEdges(I).forEach(P=>{A[P.v]=(A[P.v]||0)+E.edge(P).weight}),A});return T(E.nodes(),N)}function i(E,N){let I=E.x,A=E.y,P=N.x-I,L=N.y-A,D=E.width/2,B=E.height/2;if(!P&&!L)throw new Error("Not possible to find intersection inside of the rectangle");let H,q;return Math.abs(L)*D>Math.abs(P)*B?(L<0&&(B=-B),H=B*P/L,q=B):(P<0&&(D=-D),H=D,q=D*L/P),{x:I+H,y:A+q}}function l(E){let N=k(m(E)+1).map(()=>[]);return E.nodes().forEach(I=>{let A=E.node(I),P=A.rank;P!==void 0&&(N[P][A.order]=I)}),N}function c(E){let N=E.nodes().map(A=>{let P=E.node(A).rank;return P===void 0?Number.MAX_VALUE:P}),I=p(Math.min,N);E.nodes().forEach(A=>{let P=E.node(A);Object.hasOwn(P,"rank")&&(P.rank-=I)})}function u(E){let N=E.nodes().map(D=>E.node(D).rank),I=p(Math.min,N),A=[];E.nodes().forEach(D=>{let B=E.node(D).rank-I;A[B]||(A[B]=[]),A[B].push(D)});let P=0,L=E.graph().nodeRankFactor;Array.from(A).forEach((D,B)=>{D===void 0&&B%L!==0?--P:D!==void 0&&P&&D.forEach(H=>E.node(H).rank+=P)})}function d(E,N,I,A){let P={width:0,height:0};return arguments.length>=4&&(P.rank=I,P.order=A),t(E,"border",P,N)}function f(E,N=h){const I=[];for(let A=0;A<E.length;A+=N){const P=E.slice(A,A+N);I.push(P)}return I}const h=65535;function p(E,N){if(N.length>h){const I=f(N);return E.apply(null,I.map(A=>E.apply(null,A)))}else return E.apply(null,N)}function m(E){const I=E.nodes().map(A=>{let P=E.node(A).rank;return P===void 0?Number.MIN_VALUE:P});return p(Math.max,I)}function v(E,N){let I={lhs:[],rhs:[]};return E.forEach(A=>{N(A)?I.lhs.push(A):I.rhs.push(A)}),I}function y(E,N){let I=Date.now();try{return N()}finally{console.log(E+" time: "+(Date.now()-I)+"ms")}}function b(E,N){return N()}let x=0;function w(E){var N=++x;return E+(""+N)}function k(E,N,I=1){N==null&&(N=E,E=0);let A=L=>L<N;I<0&&(A=L=>N<L);const P=[];for(let L=E;A(L);L+=I)P.push(L);return P}function C(E,N){const I={};for(const A of N)E[A]!==void 0&&(I[A]=E[A]);return I}function _(E,N){let I=N;return typeof N=="string"&&(I=A=>A[N]),Object.entries(E).reduce((A,[P,L])=>(A[P]=I(L,P),A),{})}function T(E,N){return E.reduce((I,A,P)=>(I[A]=N[P],I),{})}return Wte}var Zte,y7e;function yZn(){if(y7e)return Zte;y7e=1;let e=vZn(),t=$l().uniqueId;Zte={run:n,undo:s};function n(a){(a.graph().acyclicer==="greedy"?e(a,l(a)):r(a)).forEach(c=>{let u=a.edge(c);a.removeEdge(c),u.forwardName=c.name,u.reversed=!0,a.setEdge(c.w,c.v,u,t("rev"))});function l(c){return u=>c.edge(u).weight}}function r(a){let i=[],l={},c={};function u(d){Object.hasOwn(c,d)||(c[d]=!0,l[d]=!0,a.outEdges(d).forEach(f=>{Object.hasOwn(l,f.w)?i.push(f):u(f.w)}),delete l[d])}return a.nodes().forEach(u),i}function s(a){a.edges().forEach(i=>{let l=a.edge(i);if(l.reversed){a.removeEdge(i);let c=l.forwardName;delete l.reversed,delete l.forwardName,a.setEdge(i.w,i.v,l,c)}})}return Zte}var Gte,b7e;function bZn(){if(b7e)return Gte;b7e=1;let e=$l();Gte={run:t,undo:r};function t(s){s.graph().dummyChains=[],s.edges().forEach(a=>n(s,a))}function n(s,a){let i=a.v,l=s.node(i).rank,c=a.w,u=s.node(c).rank,d=a.name,f=s.edge(a),h=f.labelRank;if(u===l+1)return;s.removeEdge(a);let p,m,v;for(v=0,++l;l<u;++v,++l)f.points=[],m={width:0,height:0,edgeLabel:f,edgeObj:a,rank:l},p=e.addDummyNode(s,"edge",m,"_d"),l===h&&(m.width=f.width,m.height=f.height,m.dummy="edge-label",m.labelpos=f.labelpos),s.setEdge(i,p,{weight:f.weight},d),v===0&&s.graph().dummyChains.push(p),i=p;s.setEdge(i,c,{weight:f.weight},d)}function r(s){s.graph().dummyChains.forEach(a=>{let i=s.node(a),l=i.edgeLabel,c;for(s.setEdge(i.edgeObj,l);i.dummy;)c=s.successors(a)[0],s.removeNode(a),l.points.push({x:i.x,y:i.y}),i.dummy==="edge-label"&&(l.x=i.x,l.y=i.y,l.width=i.width,l.height=i.height),a=c,i=s.node(a)})}return Gte}var Qte,x7e;function nU(){if(x7e)return Qte;x7e=1;const{applyWithChunking:e}=$l();Qte={longestPath:t,slack:n};function t(r){var s={};function a(i){var l=r.node(i);if(Object.hasOwn(s,i))return l.rank;s[i]=!0;let c=r.outEdges(i).map(d=>d==null?Number.POSITIVE_INFINITY:a(d.w)-r.edge(d).minlen);var u=e(Math.min,c);return u===Number.POSITIVE_INFINITY&&(u=0),l.rank=u}r.sources().forEach(a)}function n(r,s){return r.node(s.w).rank-r.node(s.v).rank-r.edge(s).minlen}return Qte}var Yte,w7e;function FOt(){if(w7e)return Yte;w7e=1;var e=Wg().Graph,t=nU().slack;Yte=n;function n(i){var l=new e({directed:!1}),c=i.nodes()[0],u=i.nodeCount();l.setNode(c,{});for(var d,f;r(l,i)<u;)d=s(l,i),f=l.hasNode(d.v)?t(i,d):-t(i,d),a(l,i,f);return l}function r(i,l){function c(u){l.nodeEdges(u).forEach(d=>{var f=d.v,h=u===f?d.w:f;!i.hasNode(h)&&!t(l,d)&&(i.setNode(h,{}),i.setEdge(u,h,{}),c(h))})}return i.nodes().forEach(c),i.nodeCount()}function s(i,l){return l.edges().reduce((u,d)=>{let f=Number.POSITIVE_INFINITY;return i.hasNode(d.v)!==i.hasNode(d.w)&&(f=t(l,d)),f<u[0]?[f,d]:u},[Number.POSITIVE_INFINITY,null])[1]}function a(i,l,c){i.nodes().forEach(u=>l.node(u).rank+=c)}return Yte}var Kte,S7e;function xZn(){if(S7e)return Kte;S7e=1;var e=FOt(),t=nU().slack,n=nU().longestPath,r=Wg().alg.preorder,s=Wg().alg.postorder,a=$l().simplify;Kte=i,i.initLowLimValues=d,i.initCutValues=l,i.calcCutValue=u,i.leaveEdge=h,i.enterEdge=p,i.exchangeEdges=m;function i(x){x=a(x),n(x);var w=e(x);d(w),l(w,x);for(var k,C;k=h(w);)C=p(w,x,k),m(w,x,k,C)}function l(x,w){var k=s(x,x.nodes());k=k.slice(0,k.length-1),k.forEach(C=>c(x,w,C))}function c(x,w,k){var C=x.node(k),_=C.parent;x.edge(k,_).cutvalue=u(x,w,k)}function u(x,w,k){var C=x.node(k),_=C.parent,T=!0,E=w.edge(k,_),N=0;return E||(T=!1,E=w.edge(_,k)),N=E.weight,w.nodeEdges(k).forEach(I=>{var A=I.v===k,P=A?I.w:I.v;if(P!==_){var L=A===T,D=w.edge(I).weight;if(N+=L?D:-D,y(x,k,P)){var B=x.edge(k,P).cutvalue;N+=L?-B:B}}}),N}function d(x,w){arguments.length<2&&(w=x.nodes()[0]),f(x,{},1,w)}function f(x,w,k,C,_){var T=k,E=x.node(C);return w[C]=!0,x.neighbors(C).forEach(N=>{Object.hasOwn(w,N)||(k=f(x,w,k,N,C))}),E.low=T,E.lim=k++,_?E.parent=_:delete E.parent,k}function h(x){return x.edges().find(w=>x.edge(w).cutvalue<0)}function p(x,w,k){var C=k.v,_=k.w;w.hasEdge(C,_)||(C=k.w,_=k.v);var T=x.node(C),E=x.node(_),N=T,I=!1;T.lim>E.lim&&(N=E,I=!0);var A=w.edges().filter(P=>I===b(x,x.node(P.v),N)&&I!==b(x,x.node(P.w),N));return A.reduce((P,L)=>t(w,L)<t(w,P)?L:P)}function m(x,w,k,C){var _=k.v,T=k.w;x.removeEdge(_,T),x.setEdge(C.v,C.w,{}),d(x),l(x,w),v(x,w)}function v(x,w){var k=x.nodes().find(_=>!w.node(_).parent),C=r(x,k);C=C.slice(1),C.forEach(_=>{var T=x.node(_).parent,E=w.edge(_,T),N=!1;E||(E=w.edge(T,_),N=!0),w.node(_).rank=w.node(T).rank+(N?E.minlen:-E.minlen)})}function y(x,w,k){return x.hasEdge(w,k)}function b(x,w,k){return k.low<=w.lim&&w.lim<=k.lim}return Kte}var Xte,k7e;function wZn(){if(k7e)return Xte;k7e=1;var e=nU(),t=e.longestPath,n=FOt(),r=xZn();Xte=s;function s(c){var u=c.graph().ranker;if(u instanceof Function)return u(c);switch(c.graph().ranker){case"network-simplex":l(c);break;case"tight-tree":i(c);break;case"longest-path":a(c);break;case"none":break;default:l(c)}}var a=t;function i(c){t(c),n(c)}function l(c){r(c)}return Xte}var Jte,O7e;function SZn(){if(O7e)return Jte;O7e=1,Jte=e;function e(r){let s=n(r);r.graph().dummyChains.forEach(a=>{let i=r.node(a),l=i.edgeObj,c=t(r,s,l.v,l.w),u=c.path,d=c.lca,f=0,h=u[f],p=!0;for(;a!==l.w;){if(i=r.node(a),p){for(;(h=u[f])!==d&&r.node(h).maxRank<i.rank;)f++;h===d&&(p=!1)}if(!p){for(;f<u.length-1&&r.node(h=u[f+1]).minRank<=i.rank;)f++;h=u[f]}r.setParent(a,h),a=r.successors(a)[0]}})}function t(r,s,a,i){let l=[],c=[],u=Math.min(s[a].low,s[i].low),d=Math.max(s[a].lim,s[i].lim),f,h;f=a;do f=r.parent(f),l.push(f);while(f&&(s[f].low>u||d>s[f].lim));for(h=f,f=i;(f=r.parent(f))!==h;)c.push(f);return{path:l.concat(c.reverse()),lca:h}}function n(r){let s={},a=0;function i(l){let c=a;r.children(l).forEach(i),s[l]={low:c,lim:a++}}return r.children().forEach(i),s}return Jte}var ene,C7e;function kZn(){if(C7e)return ene;C7e=1;let e=$l();ene={run:t,cleanup:a};function t(i){let l=e.addDummyNode(i,"root",{},"_root"),c=r(i),u=Object.values(c),d=e.applyWithChunking(Math.max,u)-1,f=2*d+1;i.graph().nestingRoot=l,i.edges().forEach(p=>i.edge(p).minlen*=f);let h=s(i)+1;i.children().forEach(p=>n(i,l,f,h,d,c,p)),i.graph().nodeRankFactor=f}function n(i,l,c,u,d,f,h){let p=i.children(h);if(!p.length){h!==l&&i.setEdge(l,h,{weight:0,minlen:c});return}let m=e.addBorderNode(i,"_bt"),v=e.addBorderNode(i,"_bb"),y=i.node(h);i.setParent(m,h),y.borderTop=m,i.setParent(v,h),y.borderBottom=v,p.forEach(b=>{n(i,l,c,u,d,f,b);let x=i.node(b),w=x.borderTop?x.borderTop:b,k=x.borderBottom?x.borderBottom:b,C=x.borderTop?u:2*u,_=w!==k?1:d-f[h]+1;i.setEdge(m,w,{weight:C,minlen:_,nestingEdge:!0}),i.setEdge(k,v,{weight:C,minlen:_,nestingEdge:!0})}),i.parent(h)||i.setEdge(l,m,{weight:0,minlen:d+f[h]})}function r(i){var l={};function c(u,d){var f=i.children(u);f&&f.length&&f.forEach(h=>c(h,d+1)),l[u]=d}return i.children().forEach(u=>c(u,1)),l}function s(i){return i.edges().reduce((l,c)=>l+i.edge(c).weight,0)}function a(i){var l=i.graph();i.removeNode(l.nestingRoot),delete l.nestingRoot,i.edges().forEach(c=>{var u=i.edge(c);u.nestingEdge&&i.removeEdge(c)})}return ene}var tne,_7e;function OZn(){if(_7e)return tne;_7e=1;let e=$l();tne=t;function t(r){function s(a){let i=r.children(a),l=r.node(a);if(i.length&&i.forEach(s),Object.hasOwn(l,"minRank")){l.borderLeft=[],l.borderRight=[];for(let c=l.minRank,u=l.maxRank+1;c<u;++c)n(r,"borderLeft","_bl",a,l,c),n(r,"borderRight","_br",a,l,c)}}r.children().forEach(s)}function n(r,s,a,i,l,c){let u={width:0,height:0,rank:c,borderType:s},d=l[s][c-1],f=e.addDummyNode(r,"border",u,a);l[s][c]=f,r.setParent(f,i),d&&r.setEdge(d,f,{weight:1})}return tne}var nne,E7e;function CZn(){if(E7e)return nne;E7e=1,nne={adjust:e,undo:t};function e(c){let u=c.graph().rankdir.toLowerCase();(u==="lr"||u==="rl")&&n(c)}function t(c){let u=c.graph().rankdir.toLowerCase();(u==="bt"||u==="rl")&&s(c),(u==="lr"||u==="rl")&&(i(c),n(c))}function n(c){c.nodes().forEach(u=>r(c.node(u))),c.edges().forEach(u=>r(c.edge(u)))}function r(c){let u=c.width;c.width=c.height,c.height=u}function s(c){c.nodes().forEach(u=>a(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(a),Object.hasOwn(d,"y")&&a(d)})}function a(c){c.y=-c.y}function i(c){c.nodes().forEach(u=>l(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(l),Object.hasOwn(d,"x")&&l(d)})}function l(c){let u=c.x;c.x=c.y,c.y=u}return nne}var rne,T7e;function _Zn(){if(T7e)return rne;T7e=1;let e=$l();rne=t;function t(n){let r={},s=n.nodes().filter(d=>!n.children(d).length),a=s.map(d=>n.node(d).rank),i=e.applyWithChunking(Math.max,a),l=e.range(i+1).map(()=>[]);function c(d){if(r[d])return;r[d]=!0;let f=n.node(d);l[f.rank].push(d),n.successors(d).forEach(c)}return s.sort((d,f)=>n.node(d).rank-n.node(f).rank).forEach(c),l}return rne}var sne,j7e;function EZn(){if(j7e)return sne;j7e=1;let e=$l().zipObject;sne=t;function t(r,s){let a=0;for(let i=1;i<s.length;++i)a+=n(r,s[i-1],s[i]);return a}function n(r,s,a){let i=e(a,a.map((h,p)=>p)),l=s.flatMap(h=>r.outEdges(h).map(p=>({pos:i[p.w],weight:r.edge(p).weight})).sort((p,m)=>p.pos-m.pos)),c=1;for(;c<a.length;)c<<=1;let u=2*c-1;c-=1;let d=new Array(u).fill(0),f=0;return l.forEach(h=>{let p=h.pos+c;d[p]+=h.weight;let m=0;for(;p>0;)p%2&&(m+=d[p+1]),p=p-1>>1,d[p]+=h.weight;f+=h.weight*m}),f}return sne}var ane,N7e;function TZn(){if(N7e)return ane;N7e=1,ane=e;function e(t,n=[]){return n.map(r=>{let s=t.inEdges(r);if(s.length){let a=s.reduce((i,l)=>{let c=t.edge(l),u=t.node(l.v);return{sum:i.sum+c.weight*u.order,weight:i.weight+c.weight}},{sum:0,weight:0});return{v:r,barycenter:a.sum/a.weight,weight:a.weight}}else return{v:r}})}return ane}var ine,I7e;function jZn(){if(I7e)return ine;I7e=1;let e=$l();ine=t;function t(s,a){let i={};s.forEach((c,u)=>{let d=i[c.v]={indegree:0,in:[],out:[],vs:[c.v],i:u};c.barycenter!==void 0&&(d.barycenter=c.barycenter,d.weight=c.weight)}),a.edges().forEach(c=>{let u=i[c.v],d=i[c.w];u!==void 0&&d!==void 0&&(d.indegree++,u.out.push(i[c.w]))});let l=Object.values(i).filter(c=>!c.indegree);return n(l)}function n(s){let a=[];function i(c){return u=>{u.merged||(u.barycenter===void 0||c.barycenter===void 0||u.barycenter>=c.barycenter)&&r(c,u)}}function l(c){return u=>{u.in.push(c),--u.indegree===0&&s.push(u)}}for(;s.length;){let c=s.pop();a.push(c),c.in.reverse().forEach(i(c)),c.out.forEach(l(c))}return a.filter(c=>!c.merged).map(c=>e.pick(c,["vs","i","barycenter","weight"]))}function r(s,a){let i=0,l=0;s.weight&&(i+=s.barycenter*s.weight,l+=s.weight),a.weight&&(i+=a.barycenter*a.weight,l+=a.weight),s.vs=a.vs.concat(s.vs),s.barycenter=i/l,s.weight=l,s.i=Math.min(a.i,s.i),a.merged=!0}return ine}var one,A7e;function NZn(){if(A7e)return one;A7e=1;let e=$l();one=t;function t(s,a){let i=e.partition(s,m=>Object.hasOwn(m,"barycenter")),l=i.lhs,c=i.rhs.sort((m,v)=>v.i-m.i),u=[],d=0,f=0,h=0;l.sort(r(!!a)),h=n(u,c,h),l.forEach(m=>{h+=m.vs.length,u.push(m.vs),d+=m.barycenter*m.weight,f+=m.weight,h=n(u,c,h)});let p={vs:u.flat(!0)};return f&&(p.barycenter=d/f,p.weight=f),p}function n(s,a,i){let l;for(;a.length&&(l=a[a.length-1]).i<=i;)a.pop(),s.push(l.vs),i++;return i}function r(s){return(a,i)=>a.barycenter<i.barycenter?-1:a.barycenter>i.barycenter?1:s?i.i-a.i:a.i-i.i}return one}var lne,R7e;function IZn(){if(R7e)return lne;R7e=1;let e=TZn(),t=jZn(),n=NZn();lne=r;function r(i,l,c,u){let d=i.children(l),f=i.node(l),h=f?f.borderLeft:void 0,p=f?f.borderRight:void 0,m={};h&&(d=d.filter(x=>x!==h&&x!==p));let v=e(i,d);v.forEach(x=>{if(i.children(x.v).length){let w=r(i,x.v,c,u);m[x.v]=w,Object.hasOwn(w,"barycenter")&&a(x,w)}});let y=t(v,c);s(y,m);let b=n(y,u);if(h&&(b.vs=[h,b.vs,p].flat(!0),i.predecessors(h).length)){let x=i.node(i.predecessors(h)[0]),w=i.node(i.predecessors(p)[0]);Object.hasOwn(b,"barycenter")||(b.barycenter=0,b.weight=0),b.barycenter=(b.barycenter*b.weight+x.order+w.order)/(b.weight+2),b.weight+=2}return b}function s(i,l){i.forEach(c=>{c.vs=c.vs.flatMap(u=>l[u]?l[u].vs:u)})}function a(i,l){i.barycenter!==void 0?(i.barycenter=(i.barycenter*i.weight+l.barycenter*l.weight)/(i.weight+l.weight),i.weight+=l.weight):(i.barycenter=l.barycenter,i.weight=l.weight)}return lne}var cne,P7e;function AZn(){if(P7e)return cne;P7e=1;let e=Wg().Graph,t=$l();cne=n;function n(s,a,i,l){l||(l=s.nodes());let c=r(s),u=new e({compound:!0}).setGraph({root:c}).setDefaultNodeLabel(d=>s.node(d));return l.forEach(d=>{let f=s.node(d),h=s.parent(d);(f.rank===a||f.minRank<=a&&a<=f.maxRank)&&(u.setNode(d),u.setParent(d,h||c),s[i](d).forEach(p=>{let m=p.v===d?p.w:p.v,v=u.edge(m,d),y=v!==void 0?v.weight:0;u.setEdge(m,d,{weight:s.edge(p).weight+y})}),Object.hasOwn(f,"minRank")&&u.setNode(d,{borderLeft:f.borderLeft[a],borderRight:f.borderRight[a]}))}),u}function r(s){for(var a;s.hasNode(a=t.uniqueId("_root")););return a}return cne}var une,$7e;function RZn(){if($7e)return une;$7e=1,une=e;function e(t,n,r){let s={},a;r.forEach(i=>{let l=t.parent(i),c,u;for(;l;){if(c=t.parent(l),c?(u=s[c],s[c]=l):(u=a,a=l),u&&u!==l){n.setEdge(u,l);return}l=c}})}return une}var dne,M7e;function PZn(){if(M7e)return dne;M7e=1;let e=_Zn(),t=EZn(),n=IZn(),r=AZn(),s=RZn(),a=Wg().Graph,i=$l();dne=l;function l(f,h){if(h&&typeof h.customOrder=="function"){h.customOrder(f,l);return}let p=i.maxRank(f),m=c(f,i.range(1,p+1),"inEdges"),v=c(f,i.range(p-1,-1,-1),"outEdges"),y=e(f);if(d(f,y),h&&h.disableOptimalOrderHeuristic)return;let b=Number.POSITIVE_INFINITY,x;for(let w=0,k=0;k<4;++w,++k){u(w%2?m:v,w%4>=2),y=i.buildLayerMatrix(f);let C=t(f,y);C<b&&(k=0,x=Object.assign({},y),b=C)}d(f,x)}function c(f,h,p){const m=new Map,v=(y,b)=>{m.has(y)||m.set(y,[]),m.get(y).push(b)};for(const y of f.nodes()){const b=f.node(y);if(typeof b.rank=="number"&&v(b.rank,y),typeof b.minRank=="number"&&typeof b.maxRank=="number")for(let x=b.minRank;x<=b.maxRank;x++)x!==b.rank&&v(x,y)}return h.map(function(y){return r(f,y,p,m.get(y)||[])})}function u(f,h){let p=new a;f.forEach(function(m){let v=m.graph().root,y=n(m,v,p,h);y.vs.forEach((b,x)=>m.node(b).order=x),s(m,p,y.vs)})}function d(f,h){Object.values(h).forEach(p=>p.forEach((m,v)=>f.node(m).order=v))}return dne}var fne,D7e;function $Zn(){if(D7e)return fne;D7e=1;let e=Wg().Graph,t=$l();fne={positionX:p,findType1Conflicts:n,findType2Conflicts:r,addConflict:a,hasConflict:i,verticalAlignment:l,horizontalCompaction:c,alignCoordinates:f,findSmallestWidthAlignment:d,balance:h};function n(y,b){let x={};function w(k,C){let _=0,T=0,E=k.length,N=C[C.length-1];return C.forEach((I,A)=>{let P=s(y,I),L=P?y.node(P).order:E;(P||I===N)&&(C.slice(T,A+1).forEach(D=>{y.predecessors(D).forEach(B=>{let H=y.node(B),q=H.order;(q<_||L<q)&&!(H.dummy&&y.node(D).dummy)&&a(x,B,D)})}),T=A+1,_=L)}),C}return b.length&&b.reduce(w),x}function r(y,b){let x={};function w(C,_,T,E,N){let I;t.range(_,T).forEach(A=>{I=C[A],y.node(I).dummy&&y.predecessors(I).forEach(P=>{let L=y.node(P);L.dummy&&(L.order<E||L.order>N)&&a(x,P,I)})})}function k(C,_){let T=-1,E,N=0;return _.forEach((I,A)=>{if(y.node(I).dummy==="border"){let P=y.predecessors(I);P.length&&(E=y.node(P[0]).order,w(_,N,A,T,E),N=A,T=E)}w(_,N,_.length,E,C.length)}),_}return b.length&&b.reduce(k),x}function s(y,b){if(y.node(b).dummy)return y.predecessors(b).find(x=>y.node(x).dummy)}function a(y,b,x){if(b>x){let k=b;b=x,x=k}let w=y[b];w||(y[b]=w={}),w[x]=!0}function i(y,b,x){if(b>x){let w=b;b=x,x=w}return!!y[b]&&Object.hasOwn(y[b],x)}function l(y,b,x,w){let k={},C={},_={};return b.forEach(T=>{T.forEach((E,N)=>{k[E]=E,C[E]=E,_[E]=N})}),b.forEach(T=>{let E=-1;T.forEach(N=>{let I=w(N);if(I.length){I=I.sort((P,L)=>_[P]-_[L]);let A=(I.length-1)/2;for(let P=Math.floor(A),L=Math.ceil(A);P<=L;++P){let D=I[P];C[N]===N&&E<_[D]&&!i(x,N,D)&&(C[D]=N,C[N]=k[N]=k[D],E=_[D])}}})}),{root:k,align:C}}function c(y,b,x,w,k){let C={},_=u(y,b,x,k),T=k?"borderLeft":"borderRight";function E(A,P){let L=_.nodes(),D=L.pop(),B={};for(;D;)B[D]?A(D):(B[D]=!0,L.push(D),L=L.concat(P(D))),D=L.pop()}function N(A){C[A]=_.inEdges(A).reduce((P,L)=>Math.max(P,C[L.v]+_.edge(L)),0)}function I(A){let P=_.outEdges(A).reduce((D,B)=>Math.min(D,C[B.w]-_.edge(B)),Number.POSITIVE_INFINITY),L=y.node(A);P!==Number.POSITIVE_INFINITY&&L.borderType!==T&&(C[A]=Math.max(C[A],P))}return E(N,_.predecessors.bind(_)),E(I,_.successors.bind(_)),Object.keys(w).forEach(A=>C[A]=C[x[A]]),C}function u(y,b,x,w){let k=new e,C=y.graph(),_=m(C.nodesep,C.edgesep,w);return b.forEach(T=>{let E;T.forEach(N=>{let I=x[N];if(k.setNode(I),E){var A=x[E],P=k.edge(A,I);k.setEdge(A,I,Math.max(_(y,N,E),P||0))}E=N})}),k}function d(y,b){return Object.values(b).reduce((x,w)=>{let k=Number.NEGATIVE_INFINITY,C=Number.POSITIVE_INFINITY;Object.entries(w).forEach(([T,E])=>{let N=v(y,T)/2;k=Math.max(E+N,k),C=Math.min(E-N,C)});const _=k-C;return _<x[0]&&(x=[_,w]),x},[Number.POSITIVE_INFINITY,null])[1]}function f(y,b){let x=Object.values(b),w=t.applyWithChunking(Math.min,x),k=t.applyWithChunking(Math.max,x);["u","d"].forEach(C=>{["l","r"].forEach(_=>{let T=C+_,E=y[T];if(E===b)return;let N=Object.values(E),I=w-t.applyWithChunking(Math.min,N);_!=="l"&&(I=k-t.applyWithChunking(Math.max,N)),I&&(y[T]=t.mapValues(E,A=>A+I))})})}function h(y,b){return t.mapValues(y.ul,(x,w)=>{if(b)return y[b.toLowerCase()][w];{let k=Object.values(y).map(C=>C[w]).sort((C,_)=>C-_);return(k[1]+k[2])/2}})}function p(y){let b=t.buildLayerMatrix(y),x=Object.assign(n(y,b),r(y,b)),w={},k;["u","d"].forEach(_=>{k=_==="u"?b:Object.values(b).reverse(),["l","r"].forEach(T=>{T==="r"&&(k=k.map(A=>Object.values(A).reverse()));let E=(_==="u"?y.predecessors:y.successors).bind(y),N=l(y,k,x,E),I=c(y,k,N.root,N.align,T==="r");T==="r"&&(I=t.mapValues(I,A=>-A)),w[_+T]=I})});let C=d(y,w);return f(w,C),h(w,y.graph().align)}function m(y,b,x){return(w,k,C)=>{let _=w.node(k),T=w.node(C),E=0,N;if(E+=_.width/2,Object.hasOwn(_,"labelpos"))switch(_.labelpos.toLowerCase()){case"l":N=-_.width/2;break;case"r":N=_.width/2;break}if(N&&(E+=x?N:-N),N=0,E+=(_.dummy?b:y)/2,E+=(T.dummy?b:y)/2,E+=T.width/2,Object.hasOwn(T,"labelpos"))switch(T.labelpos.toLowerCase()){case"l":N=T.width/2;break;case"r":N=-T.width/2;break}return N&&(E+=x?N:-N),N=0,E}}function v(y,b){return y.node(b).width}return fne}var hne,L7e;function MZn(){if(L7e)return hne;L7e=1;let e=$l(),t=$Zn().positionX;hne=n;function n(s){s=e.asNonCompoundGraph(s),r(s),Object.entries(t(s)).forEach(([a,i])=>s.node(a).x=i)}function r(s){let a=e.buildLayerMatrix(s),i=s.graph().ranksep,l=0;a.forEach(c=>{const u=c.reduce((d,f)=>{const h=s.node(f).height;return d>h?d:h},0);c.forEach(d=>s.node(d).y=l+u/2),l+=u+i})}return hne}var pne,F7e;function DZn(){if(F7e)return pne;F7e=1;let e=yZn(),t=bZn(),n=wZn(),r=$l().normalizeRanks,s=SZn(),a=$l().removeEmptyRanks,i=kZn(),l=OZn(),c=CZn(),u=PZn(),d=MZn(),f=$l(),h=Wg().Graph;pne=p;function p(R,U){let Z=U&&U.debugTiming?f.time:f.notime;Z("layout",()=>{let Y=Z(" buildLayoutGraph",()=>E(R));Z(" runLayout",()=>m(Y,Z,U)),Z(" updateInputGraph",()=>v(R,Y))})}function m(R,U,Z){U(" makeSpaceForEdgeLabels",()=>N(R)),U(" removeSelfEdges",()=>z(R)),U(" acyclic",()=>e.run(R)),U(" nestingGraph.run",()=>i.run(R)),U(" rank",()=>n(f.asNonCompoundGraph(R))),U(" injectEdgeLabelProxies",()=>I(R)),U(" removeEmptyRanks",()=>a(R)),U(" nestingGraph.cleanup",()=>i.cleanup(R)),U(" normalizeRanks",()=>r(R)),U(" assignRankMinMax",()=>A(R)),U(" removeEdgeLabelProxies",()=>P(R)),U(" normalize.run",()=>t.run(R)),U(" parentDummyChains",()=>s(R)),U(" addBorderSegments",()=>l(R)),U(" order",()=>u(R,Z)),U(" insertSelfEdges",()=>V(R)),U(" adjustCoordinateSystem",()=>c.adjust(R)),U(" position",()=>d(R)),U(" positionSelfEdges",()=>M(R)),U(" removeBorderNodes",()=>q(R)),U(" normalize.undo",()=>t.undo(R)),U(" fixupEdgeLabelCoords",()=>B(R)),U(" undoCoordinateSystem",()=>c.undo(R)),U(" translateGraph",()=>L(R)),U(" assignNodeIntersects",()=>D(R)),U(" reversePoints",()=>H(R)),U(" acyclic.undo",()=>e.undo(R))}function v(R,U){R.nodes().forEach(Z=>{let Y=R.node(Z),te=U.node(Z);Y&&(Y.x=te.x,Y.y=te.y,Y.rank=te.rank,U.children(Z).length&&(Y.width=te.width,Y.height=te.height))}),R.edges().forEach(Z=>{let Y=R.edge(Z),te=U.edge(Z);Y.points=te.points,Object.hasOwn(te,"x")&&(Y.x=te.x,Y.y=te.y)}),R.graph().width=U.graph().width,R.graph().height=U.graph().height}let y=["nodesep","edgesep","ranksep","marginx","marginy"],b={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},x=["acyclicer","ranker","rankdir","align"],w=["width","height","rank"],k={width:0,height:0},C=["minlen","weight","width","height","labeloffset"],_={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},T=["labelpos"];function E(R){let U=new h({multigraph:!0,compound:!0}),Z=F(R.graph());return U.setGraph(Object.assign({},b,G(Z,y),f.pick(Z,x))),R.nodes().forEach(Y=>{let te=F(R.node(Y));const J=G(te,w);Object.keys(k).forEach(ee=>{J[ee]===void 0&&(J[ee]=k[ee])}),U.setNode(Y,J),U.setParent(Y,R.parent(Y))}),R.edges().forEach(Y=>{let te=F(R.edge(Y));U.setEdge(Y,Object.assign({},_,G(te,C),f.pick(te,T)))}),U}function N(R){let U=R.graph();U.ranksep/=2,R.edges().forEach(Z=>{let Y=R.edge(Z);Y.minlen*=2,Y.labelpos.toLowerCase()!=="c"&&(U.rankdir==="TB"||U.rankdir==="BT"?Y.width+=Y.labeloffset:Y.height+=Y.labeloffset)})}function I(R){R.edges().forEach(U=>{let Z=R.edge(U);if(Z.width&&Z.height){let Y=R.node(U.v),J={rank:(R.node(U.w).rank-Y.rank)/2+Y.rank,e:U};f.addDummyNode(R,"edge-proxy",J,"_ep")}})}function A(R){let U=0;R.nodes().forEach(Z=>{let Y=R.node(Z);Y.borderTop&&(Y.minRank=R.node(Y.borderTop).rank,Y.maxRank=R.node(Y.borderBottom).rank,U=Math.max(U,Y.maxRank))}),R.graph().maxRank=U}function P(R){R.nodes().forEach(U=>{let Z=R.node(U);Z.dummy==="edge-proxy"&&(R.edge(Z.e).labelRank=Z.rank,R.removeNode(U))})}function L(R){let U=Number.POSITIVE_INFINITY,Z=0,Y=Number.POSITIVE_INFINITY,te=0,J=R.graph(),ee=J.marginx||0,re=J.marginy||0;function ae(X){let ne=X.x,se=X.y,ce=X.width,le=X.height;U=Math.min(U,ne-ce/2),Z=Math.max(Z,ne+ce/2),Y=Math.min(Y,se-le/2),te=Math.max(te,se+le/2)}R.nodes().forEach(X=>ae(R.node(X))),R.edges().forEach(X=>{let ne=R.edge(X);Object.hasOwn(ne,"x")&&ae(ne)}),U-=ee,Y-=re,R.nodes().forEach(X=>{let ne=R.node(X);ne.x-=U,ne.y-=Y}),R.edges().forEach(X=>{let ne=R.edge(X);ne.points.forEach(se=>{se.x-=U,se.y-=Y}),Object.hasOwn(ne,"x")&&(ne.x-=U),Object.hasOwn(ne,"y")&&(ne.y-=Y)}),J.width=Z-U+ee,J.height=te-Y+re}function D(R){R.edges().forEach(U=>{let Z=R.edge(U),Y=R.node(U.v),te=R.node(U.w),J,ee;Z.points?(J=Z.points[0],ee=Z.points[Z.points.length-1]):(Z.points=[],J=te,ee=Y),Z.points.unshift(f.intersectRect(Y,J)),Z.points.push(f.intersectRect(te,ee))})}function B(R){R.edges().forEach(U=>{let Z=R.edge(U);if(Object.hasOwn(Z,"x"))switch((Z.labelpos==="l"||Z.labelpos==="r")&&(Z.width-=Z.labeloffset),Z.labelpos){case"l":Z.x-=Z.width/2+Z.labeloffset;break;case"r":Z.x+=Z.width/2+Z.labeloffset;break}})}function H(R){R.edges().forEach(U=>{let Z=R.edge(U);Z.reversed&&Z.points.reverse()})}function q(R){R.nodes().forEach(U=>{if(R.children(U).length){let Z=R.node(U),Y=R.node(Z.borderTop),te=R.node(Z.borderBottom),J=R.node(Z.borderLeft[Z.borderLeft.length-1]),ee=R.node(Z.borderRight[Z.borderRight.length-1]);Z.width=Math.abs(ee.x-J.x),Z.height=Math.abs(te.y-Y.y),Z.x=J.x+Z.width/2,Z.y=Y.y+Z.height/2}}),R.nodes().forEach(U=>{R.node(U).dummy==="border"&&R.removeNode(U)})}function z(R){R.edges().forEach(U=>{if(U.v===U.w){var Z=R.node(U.v);Z.selfEdges||(Z.selfEdges=[]),Z.selfEdges.push({e:U,label:R.edge(U)}),R.removeEdge(U)}})}function V(R){var U=f.buildLayerMatrix(R);U.forEach(Z=>{var Y=0;Z.forEach((te,J)=>{var ee=R.node(te);ee.order=J+Y,(ee.selfEdges||[]).forEach(re=>{f.addDummyNode(R,"selfedge",{width:re.label.width,height:re.label.height,rank:ee.rank,order:J+ ++Y,e:re.e,label:re.label},"_se")}),delete ee.selfEdges})})}function M(R){R.nodes().forEach(U=>{var Z=R.node(U);if(Z.dummy==="selfedge"){var Y=R.node(Z.e.v),te=Y.x+Y.width/2,J=Y.y,ee=Z.x-te,re=Y.height/2;R.setEdge(Z.e,Z.label),R.removeNode(U),Z.label.points=[{x:te+2*ee/3,y:J-re},{x:te+5*ee/6,y:J-re},{x:te+ee,y:J},{x:te+5*ee/6,y:J+re},{x:te+2*ee/3,y:J+re}],Z.label.x=Z.x,Z.label.y=Z.y}})}function G(R,U){return f.mapValues(f.pick(R,U),Number)}function F(R){var U={};return R&&Object.entries(R).forEach(([Z,Y])=>{typeof Z=="string"&&(Z=Z.toLowerCase()),U[Z]=Y}),U}return pne}var mne,z7e;function LZn(){if(z7e)return mne;z7e=1;let e=$l(),t=Wg().Graph;mne={debugOrdering:n};function n(r){let s=e.buildLayerMatrix(r),a=new t({compound:!0,multigraph:!0}).setGraph({});return r.nodes().forEach(i=>{a.setNode(i,{label:i}),a.setParent(i,"layer"+r.node(i).rank)}),r.edges().forEach(i=>a.setEdge(i.v,i.w,{},i.name)),s.forEach((i,l)=>{let c="layer"+l;a.setNode(c,{rank:"same"}),i.reduce((u,d)=>(a.setEdge(u,d,{style:"invis"}),d))}),a}return mne}var gne,B7e;function FZn(){return B7e||(B7e=1,gne="1.1.8"),gne}var vne,U7e;function zZn(){return U7e||(U7e=1,vne={graphlib:Wg(),layout:DZn(),debug:LZn(),util:{time:$l().time,notime:$l().notime},version:FZn()}),vne}var BZn=zZn();const q7e=Hl(BZn);function Ql(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,r;n<e.length;n++)(r=Ql(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var UZn={value:()=>{}};function bW(){for(var e=0,t=arguments.length,n={},r;e<t;++e){if(!(r=arguments[e]+"")||r in n||/[\s.]/.test(r))throw new Error("illegal type: "+r);n[r]=[]}return new n9(n)}function n9(e){this._=e}function qZn(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",s=n.indexOf(".");if(s>=0&&(r=n.slice(s+1),n=n.slice(0,s)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}n9.prototype=bW.prototype={constructor:n9,on:function(e,t){var n=this._,r=qZn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=VZn(n[s],e.name)))return s;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++a<i;)if(s=(e=r[a]).type)n[s]=V7e(n[s],e.name,t);else if(t==null)for(s in n)n[s]=V7e(n[s],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new n9(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),r=0,s,a;r<s;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(a=this._[e],r=0,s=a.length;r<s;++r)a[r].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],s=0,a=r.length;s<a;++s)r[s].value.apply(t,n)}};function VZn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function V7e(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=UZn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Rve="http://www.w3.org/1999/xhtml";const H7e={svg:"http://www.w3.org/2000/svg",xhtml:Rve,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function xW(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),H7e.hasOwnProperty(t)?{space:H7e[t],local:e}:e}function HZn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Rve&&t.documentElement.namespaceURI===Rve?t.createElement(e):t.createElementNS(n,e)}}function WZn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function zOt(e){var t=xW(e);return(t.local?WZn:HZn)(t)}function ZZn(){}function IOe(e){return e==null?ZZn:function(){return this.querySelector(e)}}function GZn(e){typeof e!="function"&&(e=IOe(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=new Array(i),c,u,d=0;d<i;++d)(c=a[d])&&(u=e.call(c,c.__data__,d,a))&&("__data__"in c&&(u.__data__=c.__data__),l[d]=u);return new tp(r,this._parents)}function QZn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function YZn(){return[]}function BOt(e){return e==null?YZn:function(){return this.querySelectorAll(e)}}function KZn(e){return function(){return QZn(e.apply(this,arguments))}}function XZn(e){typeof e=="function"?e=KZn(e):e=BOt(e);for(var t=this._groups,n=t.length,r=[],s=[],a=0;a<n;++a)for(var i=t[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&(r.push(e.call(c,c.__data__,u,i)),s.push(c));return new tp(r,s)}function UOt(e){return function(){return this.matches(e)}}function qOt(e){return function(t){return t.matches(e)}}var JZn=Array.prototype.find;function eGn(e){return function(){return JZn.call(this.children,e)}}function tGn(){return this.firstElementChild}function nGn(e){return this.select(e==null?tGn:eGn(typeof e=="function"?e:qOt(e)))}var rGn=Array.prototype.filter;function sGn(){return Array.from(this.children)}function aGn(e){return function(){return rGn.call(this.children,e)}}function iGn(e){return this.selectAll(e==null?sGn:aGn(typeof e=="function"?e:qOt(e)))}function oGn(e){typeof e!="function"&&(e=UOt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new tp(r,this._parents)}function VOt(e){return new Array(e.length)}function lGn(){return new tp(this._enter||this._groups.map(VOt),this._parents)}function rU(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}rU.prototype={constructor:rU,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}};function cGn(e){return function(){return e}}function uGn(e,t,n,r,s,a){for(var i=0,l,c=t.length,u=a.length;i<u;++i)(l=t[i])?(l.__data__=a[i],r[i]=l):n[i]=new rU(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function dGn(e,t,n,r,s,a,i){var l,c,u=new Map,d=t.length,f=a.length,h=new Array(d),p;for(l=0;l<d;++l)(c=t[l])&&(h[l]=p=i.call(c,c.__data__,l,t)+"",u.has(p)?s[l]=c:u.set(p,c));for(l=0;l<f;++l)p=i.call(e,a[l],l,a)+"",(c=u.get(p))?(r[l]=c,c.__data__=a[l],u.delete(p)):n[l]=new rU(e,a[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(h[l])===c&&(s[l]=c)}function fGn(e){return e.__data__}function hGn(e,t){if(!arguments.length)return Array.from(this,fGn);var n=t?dGn:uGn,r=this._parents,s=this._groups;typeof e!="function"&&(e=cGn(e));for(var a=s.length,i=new Array(a),l=new Array(a),c=new Array(a),u=0;u<a;++u){var d=r[u],f=s[u],h=f.length,p=pGn(e.call(d,d&&d.__data__,u,r)),m=p.length,v=l[u]=new Array(m),y=i[u]=new Array(m),b=c[u]=new Array(h);n(d,f,v,y,b,p,t);for(var x=0,w=0,k,C;x<m;++x)if(k=v[x]){for(x>=w&&(w=x+1);!(C=y[w])&&++w<m;);k._next=C||null}}return i=new tp(i,r),i._enter=l,i._exit=c,i}function pGn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function mGn(){return new tp(this._exit||this._groups.map(VOt),this._parents)}function gGn(e,t,n){var r=this.enter(),s=this,a=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(s=t(s),s&&(s=s.selection())),n==null?a.remove():n(a),r&&s?r.merge(s).order():s}function vGn(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,s=n.length,a=r.length,i=Math.min(s,a),l=new Array(s),c=0;c<i;++c)for(var u=n[c],d=r[c],f=u.length,h=l[c]=new Array(f),p,m=0;m<f;++m)(p=u[m]||d[m])&&(h[m]=p);for(;c<s;++c)l[c]=n[c];return new tp(l,this._parents)}function yGn(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],s=r.length-1,a=r[s],i;--s>=0;)(i=r[s])&&(a&&i.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(i,a),a=i);return this}function bGn(e){e||(e=xGn);function t(f,h){return f&&h?e(f.__data__,h.__data__):!f-!h}for(var n=this._groups,r=n.length,s=new Array(r),a=0;a<r;++a){for(var i=n[a],l=i.length,c=s[a]=new Array(l),u,d=0;d<l;++d)(u=i[d])&&(c[d]=u);c.sort(t)}return new tp(s,this._parents).order()}function xGn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function wGn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function SGn(){return Array.from(this)}function kGn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length;s<a;++s){var i=r[s];if(i)return i}return null}function OGn(){let e=0;for(const t of this)++e;return e}function CGn(){return!this.node()}function _Gn(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var s=t[n],a=0,i=s.length,l;a<i;++a)(l=s[a])&&e.call(l,l.__data__,a,s);return this}function EGn(e){return function(){this.removeAttribute(e)}}function TGn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function jGn(e,t){return function(){this.setAttribute(e,t)}}function NGn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function IGn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function AGn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function RGn(e,t){var n=xW(e);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((t==null?n.local?TGn:EGn:typeof t=="function"?n.local?AGn:IGn:n.local?NGn:jGn)(n,t))}function HOt(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function PGn(e){return function(){this.style.removeProperty(e)}}function $Gn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function MGn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function DGn(e,t,n){return arguments.length>1?this.each((t==null?PGn:typeof t=="function"?MGn:$Gn)(e,t,n??"")):oN(this.node(),e)}function oN(e,t){return e.style.getPropertyValue(t)||HOt(e).getComputedStyle(e,null).getPropertyValue(t)}function LGn(e){return function(){delete this[e]}}function FGn(e,t){return function(){this[e]=t}}function zGn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function BGn(e,t){return arguments.length>1?this.each((t==null?LGn:typeof t=="function"?zGn:FGn)(e,t)):this.node()[e]}function WOt(e){return e.trim().split(/^|\s+/)}function AOe(e){return e.classList||new ZOt(e)}function ZOt(e){this._node=e,this._names=WOt(e.getAttribute("class")||"")}ZOt.prototype={add:function(e){var t=this._names.indexOf(e);t<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};function GOt(e,t){for(var n=AOe(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function QOt(e,t){for(var n=AOe(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function UGn(e){return function(){GOt(this,e)}}function qGn(e){return function(){QOt(this,e)}}function VGn(e,t){return function(){(t.apply(this,arguments)?GOt:QOt)(this,e)}}function HGn(e,t){var n=WOt(e+"");if(arguments.length<2){for(var r=AOe(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?VGn:t?UGn:qGn)(n,t))}function WGn(){this.textContent=""}function ZGn(e){return function(){this.textContent=e}}function GGn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function QGn(e){return arguments.length?this.each(e==null?WGn:(typeof e=="function"?GGn:ZGn)(e)):this.node().textContent}function YGn(){this.innerHTML=""}function KGn(e){return function(){this.innerHTML=e}}function XGn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function JGn(e){return arguments.length?this.each(e==null?YGn:(typeof e=="function"?XGn:KGn)(e)):this.node().innerHTML}function eQn(){this.nextSibling&&this.parentNode.appendChild(this)}function tQn(){return this.each(eQn)}function nQn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function rQn(){return this.each(nQn)}function sQn(e){var t=typeof e=="function"?e:zOt(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function aQn(){return null}function iQn(e,t){var n=typeof e=="function"?e:zOt(e),r=t==null?aQn:typeof t=="function"?t:IOe(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function oQn(){var e=this.parentNode;e&&e.removeChild(this)}function lQn(){return this.each(oQn)}function cQn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function uQn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function dQn(e){return this.select(e?uQn:cQn)}function fQn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function hQn(e){return function(t){e.call(this,t,this.__data__)}}function pQn(e){return e.trim().split(/^|\s+/).map(function(t){var n="",r=t.indexOf(".");return r>=0&&(n=t.slice(r+1),t=t.slice(0,r)),{type:t,name:n}})}function mQn(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,s=t.length,a;n<s;++n)a=t[n],(!e.type||a.type===e.type)&&a.name===e.name?this.removeEventListener(a.type,a.listener,a.options):t[++r]=a;++r?t.length=r:delete this.__on}}}function gQn(e,t,n){return function(){var r=this.__on,s,a=hQn(t);if(r){for(var i=0,l=r.length;i<l;++i)if((s=r[i]).type===e.type&&s.name===e.name){this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=a,s.options=n),s.value=t;return}}this.addEventListener(e.type,a,n),s={type:e.type,name:e.name,value:t,listener:a,options:n},r?r.push(s):this.__on=[s]}}function vQn(e,t,n){var r=pQn(e+""),s,a=r.length,i;if(arguments.length<2){var l=this.node().__on;if(l){for(var c=0,u=l.length,d;c<u;++c)for(s=0,d=l[c];s<a;++s)if((i=r[s]).type===d.type&&i.name===d.name)return d.value}return}for(l=t?gQn:mQn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function YOt(e,t,n){var r=HOt(e),s=r.CustomEvent;typeof s=="function"?s=new s(t,n):(s=r.document.createEvent("Event"),n?(s.initEvent(t,n.bubbles,n.cancelable),s.detail=n.detail):s.initEvent(t,!1,!1)),e.dispatchEvent(s)}function yQn(e,t){return function(){return YOt(this,e,t)}}function bQn(e,t){return function(){return YOt(this,e,t.apply(this,arguments))}}function xQn(e,t){return this.each((typeof t=="function"?bQn:yQn)(e,t))}function*wQn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length,i;s<a;++s)(i=r[s])&&(yield i)}var KOt=[null];function tp(e,t){this._groups=e,this._parents=t}function r4(){return new tp([[document.documentElement]],KOt)}function SQn(){return this}tp.prototype=r4.prototype={constructor:tp,select:GZn,selectAll:XZn,selectChild:nGn,selectChildren:iGn,filter:oGn,data:hGn,enter:lGn,exit:mGn,join:gGn,merge:vGn,selection:SQn,order:yGn,sort:bGn,call:wGn,nodes:SGn,node:kGn,size:OGn,empty:CGn,each:_Gn,attr:RGn,style:DGn,property:BGn,classed:HGn,text:QGn,html:JGn,raise:tQn,lower:rQn,append:sQn,insert:iQn,remove:lQn,clone:dQn,datum:fQn,on:vQn,dispatch:xQn,[Symbol.iterator]:wQn};function Eh(e){return typeof e=="string"?new tp([[document.querySelector(e)]],[document.documentElement]):new tp([[e]],KOt)}function kQn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function vg(e,t){if(e=kQn(e),t===void 0&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,r=r.matrixTransform(t.getScreenCTM().inverse()),[r.x,r.y]}if(t.getBoundingClientRect){var s=t.getBoundingClientRect();return[e.clientX-s.left-t.clientLeft,e.clientY-s.top-t.clientTop]}}return[e.pageX,e.pageY]}const OQn={passive:!1},BM={capture:!0,passive:!1};function yne(e){e.stopImmediatePropagation()}function dj(e){e.preventDefault(),e.stopImmediatePropagation()}function XOt(e){var t=e.document.documentElement,n=Eh(e).on("dragstart.drag",dj,BM);"onselectstart"in t?n.on("selectstart.drag",dj,BM):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function JOt(e,t){var n=e.document.documentElement,r=Eh(e).on("dragstart.drag",null);t&&(r.on("click.drag",dj,BM),setTimeout(function(){r.on("click.drag",null)},0)),"onselectstart"in n?r.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}const _F=e=>()=>e;function Pve(e,{sourceEvent:t,subject:n,target:r,identifier:s,active:a,x:i,y:l,dx:c,dy:u,dispatch:d}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:s,enumerable:!0,configurable:!0},active:{value:a,enumerable:!0,configurable:!0},x:{value:i,enumerable:!0,configurable:!0},y:{value:l,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:u,enumerable:!0,configurable:!0},_:{value:d}})}Pve.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function CQn(e){return!e.ctrlKey&&!e.button}function _Qn(){return this.parentNode}function EQn(e,t){return t??{x:e.x,y:e.y}}function TQn(){return navigator.maxTouchPoints||"ontouchstart"in this}function eCt(){var e=CQn,t=_Qn,n=EQn,r=TQn,s={},a=bW("start","drag","end"),i=0,l,c,u,d,f=0;function h(k){k.on("mousedown.drag",p).filter(r).on("touchstart.drag",y).on("touchmove.drag",b,OQn).on("touchend.drag touchcancel.drag",x).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function p(k,C){if(!(d||!e.call(this,k,C))){var _=w(this,t.call(this,k,C),k,C,"mouse");_&&(Eh(k.view).on("mousemove.drag",m,BM).on("mouseup.drag",v,BM),XOt(k.view),yne(k),u=!1,l=k.clientX,c=k.clientY,_("start",k))}}function m(k){if(dj(k),!u){var C=k.clientX-l,_=k.clientY-c;u=C*C+_*_>f}s.mouse("drag",k)}function v(k){Eh(k.view).on("mousemove.drag mouseup.drag",null),JOt(k.view,u),dj(k),s.mouse("end",k)}function y(k,C){if(e.call(this,k,C)){var _=k.changedTouches,T=t.call(this,k,C),E=_.length,N,I;for(N=0;N<E;++N)(I=w(this,T,k,C,_[N].identifier,_[N]))&&(yne(k),I("start",k,_[N]))}}function b(k){var C=k.changedTouches,_=C.length,T,E;for(T=0;T<_;++T)(E=s[C[T].identifier])&&(dj(k),E("drag",k,C[T]))}function x(k){var C=k.changedTouches,_=C.length,T,E;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),T=0;T<_;++T)(E=s[C[T].identifier])&&(yne(k),E("end",k,C[T]))}function w(k,C,_,T,E,N){var I=a.copy(),A=vg(N||_,C),P,L,D;if((D=n.call(k,new Pve("beforestart",{sourceEvent:_,target:h,identifier:E,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),T))!=null)return P=D.x-A[0]||0,L=D.y-A[1]||0,function B(H,q,z){var V=A,M;switch(H){case"start":s[E]=B,M=i++;break;case"end":delete s[E],--i;case"drag":A=vg(z||q,C),M=i;break}I.call(H,k,new Pve(H,{sourceEvent:q,subject:D,target:h,identifier:E,active:M,x:A[0]+P,y:A[1]+L,dx:A[0]-V[0],dy:A[1]-V[1],dispatch:I}),T)}}return h.filter=function(k){return arguments.length?(e=typeof k=="function"?k:_F(!!k),h):e},h.container=function(k){return arguments.length?(t=typeof k=="function"?k:_F(k),h):t},h.subject=function(k){return arguments.length?(n=typeof k=="function"?k:_F(k),h):n},h.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:_F(!!k),h):r},h.on=function(){var k=a.on.apply(a,arguments);return k===a?h:k},h.clickDistance=function(k){return arguments.length?(f=(k=+k)*k,h):Math.sqrt(f)},h}function ROe(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function tCt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function s4(){}var UM=.7,sU=1/UM,fj="\\s*([+-]?\\d+)\\s*",qM="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",my="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",jQn=/^#([0-9a-f]{3,8})$/,NQn=new RegExp(`^rgb\\(${fj},${fj},${fj}\\)$`),IQn=new RegExp(`^rgb\\(${my},${my},${my}\\)$`),AQn=new RegExp(`^rgba\\(${fj},${fj},${fj},${qM}\\)$`),RQn=new RegExp(`^rgba\\(${my},${my},${my},${qM}\\)$`),PQn=new RegExp(`^hsl\\(${qM},${my},${my}\\)$`),$Qn=new RegExp(`^hsla\\(${qM},${my},${my},${qM}\\)$`),W7e={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};ROe(s4,aC,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Z7e,formatHex:Z7e,formatHex8:MQn,formatHsl:DQn,formatRgb:G7e,toString:G7e});function Z7e(){return this.rgb().formatHex()}function MQn(){return this.rgb().formatHex8()}function DQn(){return nCt(this).formatHsl()}function G7e(){return this.rgb().formatRgb()}function aC(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=jQn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?Q7e(t):n===3?new jf(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?EF(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?EF(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=NQn.exec(e))?new jf(t[1],t[2],t[3],1):(t=IQn.exec(e))?new jf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=AQn.exec(e))?EF(t[1],t[2],t[3],t[4]):(t=RQn.exec(e))?EF(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=PQn.exec(e))?X7e(t[1],t[2]/100,t[3]/100,1):(t=$Qn.exec(e))?X7e(t[1],t[2]/100,t[3]/100,t[4]):W7e.hasOwnProperty(e)?Q7e(W7e[e]):e==="transparent"?new jf(NaN,NaN,NaN,0):null}function Q7e(e){return new jf(e>>16&255,e>>8&255,e&255,1)}function EF(e,t,n,r){return r<=0&&(e=t=n=NaN),new jf(e,t,n,r)}function LQn(e){return e instanceof s4||(e=aC(e)),e?(e=e.rgb(),new jf(e.r,e.g,e.b,e.opacity)):new jf}function $ve(e,t,n,r){return arguments.length===1?LQn(e):new jf(e,t,n,r??1)}function jf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}ROe(jf,$ve,tCt(s4,{brighter(e){return e=e==null?sU:Math.pow(sU,e),new jf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?UM:Math.pow(UM,e),new jf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new jf(dO(this.r),dO(this.g),dO(this.b),aU(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Y7e,formatHex:Y7e,formatHex8:FQn,formatRgb:K7e,toString:K7e}));function Y7e(){return`#${Hk(this.r)}${Hk(this.g)}${Hk(this.b)}`}function FQn(){return`#${Hk(this.r)}${Hk(this.g)}${Hk(this.b)}${Hk((isNaN(this.opacity)?1:this.opacity)*255)}`}function K7e(){const e=aU(this.opacity);return`${e===1?"rgb(":"rgba("}${dO(this.r)}, ${dO(this.g)}, ${dO(this.b)}${e===1?")":`, ${e})`}`}function aU(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function dO(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Hk(e){return e=dO(e),(e<16?"0":"")+e.toString(16)}function X7e(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Og(e,t,n,r)}function nCt(e){if(e instanceof Og)return new Og(e.h,e.s,e.l,e.opacity);if(e instanceof s4||(e=aC(e)),!e)return new Og;if(e instanceof Og)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,s=Math.min(t,n,r),a=Math.max(t,n,r),i=NaN,l=a-s,c=(a+s)/2;return l?(t===a?i=(n-r)/l+(n<r)*6:n===a?i=(r-t)/l+2:i=(t-n)/l+4,l/=c<.5?a+s:2-a-s,i*=60):l=c>0&&c<1?0:i,new Og(i,l,c,e.opacity)}function zQn(e,t,n,r){return arguments.length===1?nCt(e):new Og(e,t,n,r??1)}function Og(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}ROe(Og,zQn,tCt(s4,{brighter(e){return e=e==null?sU:Math.pow(sU,e),new Og(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?UM:Math.pow(UM,e),new Og(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,s=2*n-r;return new jf(bne(e>=240?e-240:e+120,s,r),bne(e,s,r),bne(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new Og(J7e(this.h),TF(this.s),TF(this.l),aU(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=aU(this.opacity);return`${e===1?"hsl(":"hsla("}${J7e(this.h)}, ${TF(this.s)*100}%, ${TF(this.l)*100}%${e===1?")":`, ${e})`}`}}));function J7e(e){return e=(e||0)%360,e<0?e+360:e}function TF(e){return Math.max(0,Math.min(1,e||0))}function bne(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}const POe=e=>()=>e;function BQn(e,t){return function(n){return e+n*t}}function UQn(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(r){return Math.pow(e+r*t,n)}}function qQn(e){return(e=+e)==1?rCt:function(t,n){return n-t?UQn(t,n,e):POe(isNaN(t)?n:t)}}function rCt(e,t){var n=t-e;return n?BQn(e,n):POe(isNaN(e)?t:e)}const iU=(function e(t){var n=qQn(t);function r(s,a){var i=n((s=$ve(s)).r,(a=$ve(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=rCt(s.opacity,a.opacity);return function(d){return s.r=i(d),s.g=l(d),s.b=c(d),s.opacity=u(d),s+""}}return r.gamma=e,r})(1);function VQn(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),s;return function(a){for(s=0;s<n;++s)r[s]=e[s]*(1-a)+t[s]*a;return r}}function HQn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function WQn(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,s=new Array(r),a=new Array(n),i;for(i=0;i<r;++i)s[i]=bx(e[i],t[i]);for(;i<n;++i)a[i]=t[i];return function(l){for(i=0;i<r;++i)a[i]=s[i](l);return a}}function ZQn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function bg(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function GQn(e,t){var n={},r={},s;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(s in t)s in e?n[s]=bx(e[s],t[s]):r[s]=t[s];return function(a){for(s in n)r[s]=n[s](a);return r}}var Mve=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,xne=new RegExp(Mve.source,"g");function QQn(e){return function(){return e}}function YQn(e){return function(t){return e(t)+""}}function sCt(e,t){var n=Mve.lastIndex=xne.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Mve.exec(e))&&(s=xne.exec(t));)(a=s.index)>n&&(a=t.slice(n,a),l[i]?l[i]+=a:l[++i]=a),(r=r[0])===(s=s[0])?l[i]?l[i]+=s:l[++i]=s:(l[++i]=null,c.push({i,x:bg(r,s)})),n=xne.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?YQn(c[0].x):QQn(t):(t=c.length,function(u){for(var d=0,f;d<t;++d)l[(f=c[d]).i]=f.x(u);return l.join("")})}function bx(e,t){var n=typeof t,r;return t==null||n==="boolean"?POe(t):(n==="number"?bg:n==="string"?(r=aC(t))?(t=r,iU):sCt:t instanceof aC?iU:t instanceof Date?ZQn:HQn(t)?VQn:Array.isArray(t)?WQn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?GQn:bg)(e,t)}function $Oe(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var eBe=180/Math.PI,Dve={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function aCt(e,t,n,r,s,a){var i,l,c;return(i=Math.sqrt(e*e+t*t))&&(e/=i,t/=i),(c=e*n+t*r)&&(n-=e*c,r-=t*c),(l=Math.sqrt(n*n+r*r))&&(n/=l,r/=l,c/=l),e*r<t*n&&(e=-e,t=-t,c=-c,i=-i),{translateX:s,translateY:a,rotate:Math.atan2(t,e)*eBe,skewX:Math.atan(c)*eBe,scaleX:i,scaleY:l}}var jF;function KQn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Dve:aCt(t.a,t.b,t.c,t.d,t.e,t.f)}function XQn(e){return e==null||(jF||(jF=document.createElementNS("http://www.w3.org/2000/svg","g")),jF.setAttribute("transform",e),!(e=jF.transform.baseVal.consolidate()))?Dve:(e=e.matrix,aCt(e.a,e.b,e.c,e.d,e.e,e.f))}function iCt(e,t,n,r){function s(u){return u.length?u.pop()+" ":""}function a(u,d,f,h,p,m){if(u!==f||d!==h){var v=p.push("translate(",null,t,null,n);m.push({i:v-4,x:bg(u,f)},{i:v-2,x:bg(d,h)})}else(f||h)&&p.push("translate("+f+t+h+n)}function i(u,d,f,h){u!==d?(u-d>180?d+=360:d-u>180&&(u+=360),h.push({i:f.push(s(f)+"rotate(",null,r)-2,x:bg(u,d)})):d&&f.push(s(f)+"rotate("+d+r)}function l(u,d,f,h){u!==d?h.push({i:f.push(s(f)+"skewX(",null,r)-2,x:bg(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,h,p,m){if(u!==f||d!==h){var v=p.push(s(p)+"scale(",null,",",null,")");m.push({i:v-4,x:bg(u,f)},{i:v-2,x:bg(d,h)})}else(f!==1||h!==1)&&p.push(s(p)+"scale("+f+","+h+")")}return function(u,d){var f=[],h=[];return u=e(u),d=e(d),a(u.translateX,u.translateY,d.translateX,d.translateY,f,h),i(u.rotate,d.rotate,f,h),l(u.skewX,d.skewX,f,h),c(u.scaleX,u.scaleY,d.scaleX,d.scaleY,f,h),u=d=null,function(p){for(var m=-1,v=h.length,y;++m<v;)f[(y=h[m]).i]=y.x(p);return f.join("")}}}var JQn=iCt(KQn,"px, ","px)","deg)"),eYn=iCt(XQn,", ",")",")"),tYn=1e-12;function tBe(e){return((e=Math.exp(e))+1/e)/2}function nYn(e){return((e=Math.exp(e))-1/e)/2}function rYn(e){return((e=Math.exp(2*e))-1)/(e+1)}const r9=(function e(t,n,r){function s(a,i){var l=a[0],c=a[1],u=a[2],d=i[0],f=i[1],h=i[2],p=d-l,m=f-c,v=p*p+m*m,y,b;if(v<tYn)b=Math.log(h/u)/t,y=function(T){return[l+T*p,c+T*m,u*Math.exp(t*T*b)]};else{var x=Math.sqrt(v),w=(h*h-u*u+r*v)/(2*u*n*x),k=(h*h-u*u-r*v)/(2*h*n*x),C=Math.log(Math.sqrt(w*w+1)-w),_=Math.log(Math.sqrt(k*k+1)-k);b=(_-C)/t,y=function(T){var E=T*b,N=tBe(C),I=u/(n*x)*(N*rYn(t*E+C)-nYn(C));return[l+I*p,c+I*m,u*N/tBe(t*E+C)]}}return y.duration=b*1e3*t/Math.SQRT2,y}return s.rho=function(a){var i=Math.max(.001,+a),l=i*i,c=l*l;return e(i,l,c)},s})(Math.SQRT2,2,4);function sYn(e,t){t===void 0&&(t=e,e=bx);for(var n=0,r=t.length-1,s=t[0],a=new Array(r<0?0:r);n<r;)a[n]=e(s,s=t[++n]);return function(i){var l=Math.max(0,Math.min(r-1,Math.floor(i*=r)));return a[l](i-l)}}var lN=0,r$=0,UR=0,oCt=1e3,oU,s$,lU=0,iC=0,wW=0,VM=typeof performance=="object"&&performance.now?performance:Date,lCt=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function MOe(){return iC||(lCt(aYn),iC=VM.now()+wW)}function aYn(){iC=0}function cU(){this._call=this._time=this._next=null}cU.prototype=cCt.prototype={constructor:cU,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?MOe():+n)+(t==null?0:+t),!this._next&&s$!==this&&(s$?s$._next=this:oU=this,s$=this),this._call=e,this._time=n,Lve()},stop:function(){this._call&&(this._call=null,this._time=1/0,Lve())}};function cCt(e,t,n){var r=new cU;return r.restart(e,t,n),r}function iYn(){MOe(),++lN;for(var e=oU,t;e;)(t=iC-e._time)>=0&&e._call.call(void 0,t),e=e._next;--lN}function nBe(){iC=(lU=VM.now())+wW,lN=r$=0;try{iYn()}finally{lN=0,lYn(),iC=0}}function oYn(){var e=VM.now(),t=e-lU;t>oCt&&(wW-=t,lU=e)}function lYn(){for(var e,t=oU,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:oU=n);s$=e,Lve(r)}function Lve(e){if(!lN){r$&&(r$=clearTimeout(r$));var t=e-iC;t>24?(e<1/0&&(r$=setTimeout(nBe,e-VM.now()-wW)),UR&&(UR=clearInterval(UR))):(UR||(lU=VM.now(),UR=setInterval(oYn,oCt)),lN=1,lCt(nBe))}}function rBe(e,t,n){var r=new cU;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var cYn=bW("start","end","cancel","interrupt"),uYn=[],uCt=0,sBe=1,Fve=2,s9=3,aBe=4,zve=5,a9=6;function SW(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;dYn(e,n,{name:t,index:r,group:s,on:cYn,tween:uYn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:uCt})}function DOe(e,t){var n=nv(e,t);if(n.state>uCt)throw new Error("too late; already scheduled");return n}function Wy(e,t){var n=nv(e,t);if(n.state>s9)throw new Error("too late; already running");return n}function nv(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function dYn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=cCt(a,0,n.time);function a(u){n.state=sBe,n.timer.restart(i,n.delay,n.time),n.delay<=u&&i(u-n.delay)}function i(u){var d,f,h,p;if(n.state!==sBe)return c();for(d in r)if(p=r[d],p.name===n.name){if(p.state===s9)return rBe(i);p.state===aBe?(p.state=a9,p.timer.stop(),p.on.call("interrupt",e,e.__data__,p.index,p.group),delete r[d]):+d<t&&(p.state=a9,p.timer.stop(),p.on.call("cancel",e,e.__data__,p.index,p.group),delete r[d])}if(rBe(function(){n.state===s9&&(n.state=aBe,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Fve,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Fve){for(n.state=s9,s=new Array(h=n.tween.length),d=0,f=-1;d<h;++d)(p=n.tween[d].value.call(e,e.__data__,n.index,n.group))&&(s[++f]=p);s.length=f+1}}function l(u){for(var d=u<n.duration?n.ease.call(null,u/n.duration):(n.timer.restart(c),n.state=zve,1),f=-1,h=s.length;++f<h;)s[f].call(e,d);n.state===zve&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=a9,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function i9(e,t){var n=e.__transition,r,s,a=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((r=n[i]).name!==t){a=!1;continue}s=r.state>Fve&&r.state<zve,r.state=a9,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function fYn(e){return this.each(function(){i9(this,e)})}function hYn(e,t){var n,r;return function(){var s=Wy(this,e),a=s.tween;if(a!==n){r=n=a;for(var i=0,l=r.length;i<l;++i)if(r[i].name===t){r=r.slice(),r.splice(i,1);break}}s.tween=r}}function pYn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=Wy(this,e),i=a.tween;if(i!==r){s=(r=i).slice();for(var l={name:t,value:n},c=0,u=s.length;c<u;++c)if(s[c].name===t){s[c]=l;break}c===u&&s.push(l)}a.tween=s}}function mYn(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=nv(this.node(),n).tween,s=0,a=r.length,i;s<a;++s)if((i=r[s]).name===e)return i.value;return null}return this.each((t==null?hYn:pYn)(n,e,t))}function LOe(e,t,n){var r=e._id;return e.each(function(){var s=Wy(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return nv(s,r).value[t]}}function dCt(e,t){var n;return(typeof t=="number"?bg:t instanceof aC?iU:(n=aC(t))?(t=n,iU):sCt)(e,t)}function gYn(e){return function(){this.removeAttribute(e)}}function vYn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function yYn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttribute(e);return i===s?null:i===r?a:a=t(r=i,n)}}function bYn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttributeNS(e.space,e.local);return i===s?null:i===r?a:a=t(r=i,n)}}function xYn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttribute(e):(i=this.getAttribute(e),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function wYn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttributeNS(e.space,e.local):(i=this.getAttributeNS(e.space,e.local),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function SYn(e,t){var n=xW(e),r=n==="transform"?eYn:dCt;return this.attrTween(e,typeof t=="function"?(n.local?wYn:xYn)(n,r,LOe(this,"attr."+e,t)):t==null?(n.local?vYn:gYn)(n):(n.local?bYn:yYn)(n,r,t))}function kYn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function OYn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function CYn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&OYn(e,a)),n}return s._value=t,s}function _Yn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&kYn(e,a)),n}return s._value=t,s}function EYn(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(t==null)return this.tween(n,null);if(typeof t!="function")throw new Error;var r=xW(e);return this.tween(n,(r.local?CYn:_Yn)(r,t))}function TYn(e,t){return function(){DOe(this,e).delay=+t.apply(this,arguments)}}function jYn(e,t){return t=+t,function(){DOe(this,e).delay=t}}function NYn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?TYn:jYn)(t,e)):nv(this.node(),t).delay}function IYn(e,t){return function(){Wy(this,e).duration=+t.apply(this,arguments)}}function AYn(e,t){return t=+t,function(){Wy(this,e).duration=t}}function RYn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?IYn:AYn)(t,e)):nv(this.node(),t).duration}function PYn(e,t){if(typeof t!="function")throw new Error;return function(){Wy(this,e).ease=t}}function $Yn(e){var t=this._id;return arguments.length?this.each(PYn(t,e)):nv(this.node(),t).ease}function MYn(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Wy(this,e).ease=n}}function DYn(e){if(typeof e!="function")throw new Error;return this.each(MYn(this._id,e))}function LYn(e){typeof e!="function"&&(e=UOt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new Fx(r,this._parents,this._name,this._id)}function FYn(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,s=n.length,a=Math.min(r,s),i=new Array(r),l=0;l<a;++l)for(var c=t[l],u=n[l],d=c.length,f=i[l]=new Array(d),h,p=0;p<d;++p)(h=c[p]||u[p])&&(f[p]=h);for(;l<r;++l)i[l]=t[l];return new Fx(i,this._parents,this._name,this._id)}function zYn(e){return(e+"").trim().split(/^|\s+/).every(function(t){var n=t.indexOf(".");return n>=0&&(t=t.slice(0,n)),!t||t==="start"})}function BYn(e,t,n){var r,s,a=zYn(t)?DOe:Wy;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function UYn(e,t){var n=this._id;return arguments.length<2?nv(this.node(),n).on.on(e):this.each(BYn(n,e,t))}function qYn(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function VYn(){return this.on("end.remove",qYn(this._id))}function HYn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=IOe(e));for(var r=this._groups,s=r.length,a=new Array(s),i=0;i<s;++i)for(var l=r[i],c=l.length,u=a[i]=new Array(c),d,f,h=0;h<c;++h)(d=l[h])&&(f=e.call(d,d.__data__,h,l))&&("__data__"in d&&(f.__data__=d.__data__),u[h]=f,SW(u[h],t,n,h,u,nv(d,n)));return new Fx(a,this._parents,t,n)}function WYn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=BOt(e));for(var r=this._groups,s=r.length,a=[],i=[],l=0;l<s;++l)for(var c=r[l],u=c.length,d,f=0;f<u;++f)if(d=c[f]){for(var h=e.call(d,d.__data__,f,c),p,m=nv(d,n),v=0,y=h.length;v<y;++v)(p=h[v])&&SW(p,t,n,v,h,m);a.push(h),i.push(d)}return new Fx(a,i,t,n)}var ZYn=r4.prototype.constructor;function GYn(){return new ZYn(this._groups,this._parents)}function QYn(e,t){var n,r,s;return function(){var a=oN(this,e),i=(this.style.removeProperty(e),oN(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function fCt(e){return function(){this.style.removeProperty(e)}}function YYn(e,t,n){var r,s=n+"",a;return function(){var i=oN(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function KYn(e,t,n){var r,s,a;return function(){var i=oN(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),oN(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function XYn(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=Wy(this,e),u=c.on,d=c.value[a]==null?l||(l=fCt(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function JYn(e,t,n){var r=(e+="")=="transform"?JQn:dCt;return t==null?this.styleTween(e,QYn(e,r)).on("end.style."+e,fCt(e)):typeof t=="function"?this.styleTween(e,KYn(e,r,LOe(this,"style."+e,t))).each(XYn(this._id,e)):this.styleTween(e,YYn(e,r,t),n).on("end.style."+e,null)}function eKn(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function tKn(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&eKn(e,i,n)),r}return a._value=t,a}function nKn(e,t,n){var r="style."+(e+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(t==null)return this.tween(r,null);if(typeof t!="function")throw new Error;return this.tween(r,tKn(e,t,n??""))}function rKn(e){return function(){this.textContent=e}}function sKn(e){return function(){var t=e(this);this.textContent=t??""}}function aKn(e){return this.tween("text",typeof e=="function"?sKn(LOe(this,"text",e)):rKn(e==null?"":e+""))}function iKn(e){return function(t){this.textContent=e.call(this,t)}}function oKn(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&iKn(s)),t}return r._value=e,r}function lKn(e){var t="text";if(arguments.length<1)return(t=this.tween(t))&&t._value;if(e==null)return this.tween(t,null);if(typeof e!="function")throw new Error;return this.tween(t,oKn(e))}function cKn(){for(var e=this._name,t=this._id,n=hCt(),r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)if(c=i[u]){var d=nv(c,t);SW(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new Fx(r,this._parents,e,n)}function uKn(){var e,t,n=this,r=n._id,s=n.size();return new Promise(function(a,i){var l={value:i},c={value:function(){--s===0&&a()}};n.each(function(){var u=Wy(this,r),d=u.on;d!==e&&(t=(e=d).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(c)),u.on=t}),s===0&&a()})}var dKn=0;function Fx(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function hCt(){return++dKn}var Tb=r4.prototype;Fx.prototype={constructor:Fx,select:HYn,selectAll:WYn,selectChild:Tb.selectChild,selectChildren:Tb.selectChildren,filter:LYn,merge:FYn,selection:GYn,transition:cKn,call:Tb.call,nodes:Tb.nodes,node:Tb.node,size:Tb.size,empty:Tb.empty,each:Tb.each,on:UYn,attr:SYn,attrTween:EYn,style:JYn,styleTween:nKn,text:aKn,textTween:lKn,remove:VYn,tween:mYn,delay:NYn,duration:RYn,ease:$Yn,easeVarying:DYn,end:uKn,[Symbol.iterator]:Tb[Symbol.iterator]};function fKn(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var hKn={time:null,delay:0,duration:250,ease:fKn};function pKn(e,t){for(var n;!(n=e.__transition)||!(n=n[t]);)if(!(e=e.parentNode))throw new Error(`transition ${t} not found`);return n}function mKn(e){var t,n;e instanceof Fx?(t=e._id,e=e._name):(t=hCt(),(n=hKn).time=MOe(),e=e==null?null:e+"");for(var r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&SW(c,e,t,u,i,n||pKn(c,t));return new Fx(r,this._parents,e,t)}r4.prototype.interrupt=fYn;r4.prototype.transition=mKn;const NF=e=>()=>e;function gKn(e,{sourceEvent:t,target:n,transform:r,dispatch:s}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:s}})}function ix(e,t,n){this.k=e,this.x=t,this.y=n}ix.prototype={constructor:ix,scale:function(e){return e===1?this:new ix(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new ix(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var kW=new ix(1,0,0);pCt.prototype=ix.prototype;function pCt(e){for(;!e.__zoom;)if(!(e=e.parentNode))return kW;return e.__zoom}function wne(e){e.stopImmediatePropagation()}function qR(e){e.preventDefault(),e.stopImmediatePropagation()}function vKn(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function yKn(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e,e.hasAttribute("viewBox")?(e=e.viewBox.baseVal,[[e.x,e.y],[e.x+e.width,e.y+e.height]]):[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]):[[0,0],[e.clientWidth,e.clientHeight]]}function iBe(){return this.__zoom||kW}function bKn(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function xKn(){return navigator.maxTouchPoints||"ontouchstart"in this}function wKn(e,t,n){var r=e.invertX(t[0][0])-n[0][0],s=e.invertX(t[1][0])-n[1][0],a=e.invertY(t[0][1])-n[0][1],i=e.invertY(t[1][1])-n[1][1];return e.translate(s>r?(r+s)/2:Math.min(0,r)||Math.max(0,s),i>a?(a+i)/2:Math.min(0,a)||Math.max(0,i))}function mCt(){var e=vKn,t=yKn,n=wKn,r=bKn,s=xKn,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=r9,u=bW("start","zoom","end"),d,f,h,p=500,m=150,v=0,y=10;function b(D){D.property("__zoom",iBe).on("wheel.zoom",E,{passive:!1}).on("mousedown.zoom",N).on("dblclick.zoom",I).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",P).on("touchend.zoom touchcancel.zoom",L).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(D,B,H,q){var z=D.selection?D.selection():D;z.property("__zoom",iBe),D!==z?C(D,B,H,q):z.interrupt().each(function(){_(this,arguments).event(q).start().zoom(null,typeof B=="function"?B.apply(this,arguments):B).end()})},b.scaleBy=function(D,B,H,q){b.scaleTo(D,function(){var z=this.__zoom.k,V=typeof B=="function"?B.apply(this,arguments):B;return z*V},H,q)},b.scaleTo=function(D,B,H,q){b.transform(D,function(){var z=t.apply(this,arguments),V=this.__zoom,M=H==null?k(z):typeof H=="function"?H.apply(this,arguments):H,G=V.invert(M),F=typeof B=="function"?B.apply(this,arguments):B;return n(w(x(V,F),M,G),z,i)},H,q)},b.translateBy=function(D,B,H,q){b.transform(D,function(){return n(this.__zoom.translate(typeof B=="function"?B.apply(this,arguments):B,typeof H=="function"?H.apply(this,arguments):H),t.apply(this,arguments),i)},null,q)},b.translateTo=function(D,B,H,q,z){b.transform(D,function(){var V=t.apply(this,arguments),M=this.__zoom,G=q==null?k(V):typeof q=="function"?q.apply(this,arguments):q;return n(kW.translate(G[0],G[1]).scale(M.k).translate(typeof B=="function"?-B.apply(this,arguments):-B,typeof H=="function"?-H.apply(this,arguments):-H),V,i)},q,z)};function x(D,B){return B=Math.max(a[0],Math.min(a[1],B)),B===D.k?D:new ix(B,D.x,D.y)}function w(D,B,H){var q=B[0]-H[0]*D.k,z=B[1]-H[1]*D.k;return q===D.x&&z===D.y?D:new ix(D.k,q,z)}function k(D){return[(+D[0][0]+ +D[1][0])/2,(+D[0][1]+ +D[1][1])/2]}function C(D,B,H,q){D.on("start.zoom",function(){_(this,arguments).event(q).start()}).on("interrupt.zoom end.zoom",function(){_(this,arguments).event(q).end()}).tween("zoom",function(){var z=this,V=arguments,M=_(z,V).event(q),G=t.apply(z,V),F=H==null?k(G):typeof H=="function"?H.apply(z,V):H,R=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),U=z.__zoom,Z=typeof B=="function"?B.apply(z,V):B,Y=c(U.invert(F).concat(R/U.k),Z.invert(F).concat(R/Z.k));return function(te){if(te===1)te=Z;else{var J=Y(te),ee=R/J[2];te=new ix(ee,F[0]-J[0]*ee,F[1]-J[1]*ee)}M.zoom(null,te)}})}function _(D,B,H){return!H&&D.__zooming||new T(D,B)}function T(D,B){this.that=D,this.args=B,this.active=0,this.sourceEvent=null,this.extent=t.apply(D,B),this.taps=0}T.prototype={event:function(D){return D&&(this.sourceEvent=D),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(D,B){return this.mouse&&D!=="mouse"&&(this.mouse[1]=B.invert(this.mouse[0])),this.touch0&&D!=="touch"&&(this.touch0[1]=B.invert(this.touch0[0])),this.touch1&&D!=="touch"&&(this.touch1[1]=B.invert(this.touch1[0])),this.that.__zoom=B,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(D){var B=Eh(this.that).datum();u.call(D,this.that,new gKn(D,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),B)}};function E(D,...B){if(!e.apply(this,arguments))return;var H=_(this,B).event(D),q=this.__zoom,z=Math.max(a[0],Math.min(a[1],q.k*Math.pow(2,r.apply(this,arguments)))),V=vg(D);if(H.wheel)(H.mouse[0][0]!==V[0]||H.mouse[0][1]!==V[1])&&(H.mouse[1]=q.invert(H.mouse[0]=V)),clearTimeout(H.wheel);else{if(q.k===z)return;H.mouse=[V,q.invert(V)],i9(this),H.start()}qR(D),H.wheel=setTimeout(M,m),H.zoom("mouse",n(w(x(q,z),H.mouse[0],H.mouse[1]),H.extent,i));function M(){H.wheel=null,H.end()}}function N(D,...B){if(h||!e.apply(this,arguments))return;var H=D.currentTarget,q=_(this,B,!0).event(D),z=Eh(D.view).on("mousemove.zoom",F,!0).on("mouseup.zoom",R,!0),V=vg(D,H),M=D.clientX,G=D.clientY;XOt(D.view),wne(D),q.mouse=[V,this.__zoom.invert(V)],i9(this),q.start();function F(U){if(qR(U),!q.moved){var Z=U.clientX-M,Y=U.clientY-G;q.moved=Z*Z+Y*Y>v}q.event(U).zoom("mouse",n(w(q.that.__zoom,q.mouse[0]=vg(U,H),q.mouse[1]),q.extent,i))}function R(U){z.on("mousemove.zoom mouseup.zoom",null),JOt(U.view,q.moved),qR(U),q.event(U).end()}}function I(D,...B){if(e.apply(this,arguments)){var H=this.__zoom,q=vg(D.changedTouches?D.changedTouches[0]:D,this),z=H.invert(q),V=H.k*(D.shiftKey?.5:2),M=n(w(x(H,V),q,z),t.apply(this,B),i);qR(D),l>0?Eh(this).transition().duration(l).call(C,M,q,D):Eh(this).call(b.transform,M,q,D)}}function A(D,...B){if(e.apply(this,arguments)){var H=D.touches,q=H.length,z=_(this,B,D.changedTouches.length===q).event(D),V,M,G,F;for(wne(D),M=0;M<q;++M)G=H[M],F=vg(G,this),F=[F,this.__zoom.invert(F),G.identifier],z.touch0?!z.touch1&&z.touch0[2]!==F[2]&&(z.touch1=F,z.taps=0):(z.touch0=F,V=!0,z.taps=1+!!d);d&&(d=clearTimeout(d)),V&&(z.taps<2&&(f=F[0],d=setTimeout(function(){d=null},p)),i9(this),z.start())}}function P(D,...B){if(this.__zooming){var H=_(this,B).event(D),q=D.changedTouches,z=q.length,V,M,G,F;for(qR(D),V=0;V<z;++V)M=q[V],G=vg(M,this),H.touch0&&H.touch0[2]===M.identifier?H.touch0[0]=G:H.touch1&&H.touch1[2]===M.identifier&&(H.touch1[0]=G);if(M=H.that.__zoom,H.touch1){var R=H.touch0[0],U=H.touch0[1],Z=H.touch1[0],Y=H.touch1[1],te=(te=Z[0]-R[0])*te+(te=Z[1]-R[1])*te,J=(J=Y[0]-U[0])*J+(J=Y[1]-U[1])*J;M=x(M,Math.sqrt(te/J)),G=[(R[0]+Z[0])/2,(R[1]+Z[1])/2],F=[(U[0]+Y[0])/2,(U[1]+Y[1])/2]}else if(H.touch0)G=H.touch0[0],F=H.touch0[1];else return;H.zoom("touch",n(w(M,G,F),H.extent,i))}}function L(D,...B){if(this.__zooming){var H=_(this,B).event(D),q=D.changedTouches,z=q.length,V,M;for(wne(D),h&&clearTimeout(h),h=setTimeout(function(){h=null},p),V=0;V<z;++V)M=q[V],H.touch0&&H.touch0[2]===M.identifier?delete H.touch0:H.touch1&&H.touch1[2]===M.identifier&&delete H.touch1;if(H.touch1&&!H.touch0&&(H.touch0=H.touch1,delete H.touch1),H.touch0)H.touch0[1]=this.__zoom.invert(H.touch0[0]);else if(H.end(),H.taps===2&&(M=vg(M,this),Math.hypot(f[0]-M[0],f[1]-M[1])<y)){var G=Eh(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(D){return arguments.length?(r=typeof D=="function"?D:NF(+D),b):r},b.filter=function(D){return arguments.length?(e=typeof D=="function"?D:NF(!!D),b):e},b.touchable=function(D){return arguments.length?(s=typeof D=="function"?D:NF(!!D),b):s},b.extent=function(D){return arguments.length?(t=typeof D=="function"?D:NF([[+D[0][0],+D[0][1]],[+D[1][0],+D[1][1]]]),b):t},b.scaleExtent=function(D){return arguments.length?(a[0]=+D[0],a[1]=+D[1],b):[a[0],a[1]]},b.translateExtent=function(D){return arguments.length?(i[0][0]=+D[0][0],i[1][0]=+D[1][0],i[0][1]=+D[0][1],i[1][1]=+D[1][1],b):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},b.constrain=function(D){return arguments.length?(n=D,b):n},b.duration=function(D){return arguments.length?(l=+D,b):l},b.interpolate=function(D){return arguments.length?(c=D,b):c},b.on=function(){var D=u.on.apply(u,arguments);return D===u?b:D},b.clickDistance=function(D){return arguments.length?(v=(D=+D)*D,b):Math.sqrt(v)},b.tapDistance=function(D){return arguments.length?(y=+D,b):y},b}const Ty={error001:()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>"The React Flow parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,{id:t,sourceHandle:n,targetHandle:r})=>`Couldn't create edge for ${e} handle id: "${e==="source"?n:r}", edge id: ${t}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(e="react")=>`It seems that you haven't loaded the styles. Please import '@xyflow/${e}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>"useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.",error015:()=>"It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs."},HM=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],gCt=["Enter"," ","Escape"],vCt={"node.a11yDescription.default":"Press enter or space to select a node. Press delete to remove it and escape to cancel.","node.a11yDescription.keyboardDisabled":"Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.","node.a11yDescription.ariaLiveMessage":({direction:e,x:t,y:n})=>`Moved selected node ${e}. New position, x: ${t}, y: ${n}`,"edge.a11yDescription.default":"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.","controls.ariaLabel":"Control Panel","controls.zoomIn.ariaLabel":"Zoom In","controls.zoomOut.ariaLabel":"Zoom Out","controls.fitView.ariaLabel":"Fit View","controls.interactive.ariaLabel":"Toggle Interactivity","minimap.ariaLabel":"Mini Map","handle.ariaLabel":"Handle"};var cN;(function(e){e.Strict="strict",e.Loose="loose"})(cN||(cN={}));var fO;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(fO||(fO={}));var WM;(function(e){e.Partial="partial",e.Full="full"})(WM||(WM={}));const yCt={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var Ew;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(Ew||(Ew={}));var ZM;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(ZM||(ZM={}));var nr;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(nr||(nr={}));const oBe={[nr.Left]:nr.Right,[nr.Right]:nr.Left,[nr.Top]:nr.Bottom,[nr.Bottom]:nr.Top};function bCt(e){return e===null?null:e?"valid":"invalid"}const xCt=e=>"id"in e&&"source"in e&&"target"in e,SKn=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),FOe=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),a4=(e,t=[0,0])=>{const{width:n,height:r}=l0(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},kKn=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,s)=>{const a=typeof s=="string";let i=!t.nodeLookup&&!a?s:void 0;t.nodeLookup&&(i=a?t.nodeLookup.get(s):FOe(s)?s:t.nodeLookup.get(s.id));const l=i?uU(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return OW(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return CW(n)},i4=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},r=!1;return e.forEach(s=>{(t.filter===void 0||t.filter(s))&&(n=OW(n,uU(s)),r=!0)}),r?CW(n):{x:0,y:0,width:0,height:0}},zOe=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...l4(t,[n,r,s]),width:t.width/s,height:t.height/s},c=[];for(const u of e.values()){const{measured:d,selectable:f=!0,hidden:h=!1}=u;if(i&&!f||h)continue;const p=d.width??u.width??u.initialWidth??null,m=d.height??u.height??u.initialHeight??null,v=GM(l,dN(u)),y=(p??0)*(m??0),b=a&&v>0;(!u.internals.handleBounds||b||v>=y||u.dragging)&&c.push(u)}return c},OKn=(e,t)=>{const n=new Set;return e.forEach(r=>{n.add(r.id)}),t.filter(r=>n.has(r.source)||n.has(r.target))};function CKn(e,t){const n=new Map,r=t?.nodes?new Set(t.nodes.map(s=>s.id)):null;return e.forEach(s=>{s.measured.width&&s.measured.height&&(t?.includeHiddenNodes||!s.hidden)&&(!r||r.has(s.id))&&n.set(s.id,s)}),n}async function _Kn({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=CKn(e,i),c=i4(l),u=BOe(c,t,n,i?.minZoom??s,i?.maxZoom??a,i?.padding??.1);return await r.setViewport(u,{duration:i?.duration,ease:i?.ease,interpolate:i?.interpolate}),Promise.resolve(!0)}function wCt({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:s,onError:a}){const i=n.get(e),l=i.parentId?n.get(i.parentId):void 0,{x:c,y:u}=l?l.internals.positionAbsolute:{x:0,y:0},d=i.origin??r;let f=i.extent||s;if(i.extent==="parent"&&!i.expandParent)if(!l)a?.("005",Ty.error005());else{const p=l.measured.width,m=l.measured.height;p&&m&&(f=[[c,u],[c+p,u+m]])}else l&&fN(i.extent)&&(f=[[i.extent[0][0]+c,i.extent[0][1]+u],[i.extent[1][0]+c,i.extent[1][1]+u]]);const h=fN(f)?oC(t,f,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&a?.("015",Ty.error015()),{position:{x:h.x-c+(i.measured.width??0)*d[0],y:h.y-u+(i.measured.height??0)*d[1]},positionAbsolute:h}}async function EKn({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const a=new Set(e.map(h=>h.id)),i=[];for(const h of n){if(h.deletable===!1)continue;const p=a.has(h.id),m=!p&&h.parentId&&i.find(v=>v.id===h.parentId);(p||m)&&i.push(h)}const l=new Set(t.map(h=>h.id)),c=r.filter(h=>h.deletable!==!1),d=OKn(i,c);for(const h of c)l.has(h.id)&&!d.find(m=>m.id===h.id)&&d.push(h);if(!s)return{edges:d,nodes:i};const f=await s({nodes:i,edges:d});return typeof f=="boolean"?f?{edges:d,nodes:i}:{edges:[],nodes:[]}:f}const uN=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),oC=(e={x:0,y:0},t,n)=>({x:uN(e.x,t[0][0],t[1][0]-(n?.width??0)),y:uN(e.y,t[0][1],t[1][1]-(n?.height??0))});function SCt(e,t,n){const{width:r,height:s}=l0(n),{x:a,y:i}=n.internals.positionAbsolute;return oC(e,[[a,i],[a+r,i+s]],t)}const lBe=(e,t,n)=>e<t?uN(Math.abs(e-t),1,t)/t:e>n?-uN(Math.abs(e-n),1,t)/t:0,kCt=(e,t,n=15,r=40)=>{const s=lBe(e.x,r,t.width-r)*n,a=lBe(e.y,r,t.height-r)*n;return[s,a]},OW=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),Bve=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),CW=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),dN=(e,t=[0,0])=>{const{x:n,y:r}=FOe(e)?e.internals.positionAbsolute:a4(e,t);return{x:n,y:r,width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}},uU=(e,t=[0,0])=>{const{x:n,y:r}=FOe(e)?e.internals.positionAbsolute:a4(e,t);return{x:n,y:r,x2:n+(e.measured?.width??e.width??e.initialWidth??0),y2:r+(e.measured?.height??e.height??e.initialHeight??0)}},OCt=(e,t)=>CW(OW(Bve(e),Bve(t))),GM=(e,t)=>{const n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*r)},cBe=e=>jg(e.width)&&jg(e.height)&&jg(e.x)&&jg(e.y),jg=e=>!isNaN(e)&&isFinite(e),TKn=(e,t)=>{},o4=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),l4=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?o4(l,i):l},dU=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function SE(e,t){if(typeof e=="number")return Math.floor((t-t/(1+e))*.5);if(typeof e=="string"&&e.endsWith("px")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(n)}if(typeof e=="string"&&e.endsWith("%")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(t*n*.01)}return console.error(`[React Flow] The padding value "${e}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}function jKn(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=SE(e,n),s=SE(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=SE(e.top??e.y??0,n),s=SE(e.bottom??e.y??0,n),a=SE(e.left??e.x??0,t),i=SE(e.right??e.x??0,t);return{top:r,right:i,bottom:s,left:a,x:a+i,y:r+s}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function NKn(e,t,n,r,s,a){const{x:i,y:l}=dU(e,[t,n,r]),{x:c,y:u}=dU({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=s-c,f=a-u;return{left:Math.floor(i),top:Math.floor(l),right:Math.floor(d),bottom:Math.floor(f)}}const BOe=(e,t,n,r,s,a)=>{const i=jKn(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=uN(u,r,s),f=e.x+e.width/2,h=e.y+e.height/2,p=t/2-f*d,m=n/2-h*d,v=NKn(e,p,m,d,t,n),y={left:Math.min(v.left-i.left,0),top:Math.min(v.top-i.top,0),right:Math.min(v.right-i.right,0),bottom:Math.min(v.bottom-i.bottom,0)};return{x:p-y.left+y.right,y:m-y.top+y.bottom,zoom:d}},QM=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function fN(e){return e!=null&&e!=="parent"}function l0(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function CCt(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function _Ct(e,t={width:0,height:0},n,r,s){const a={...e},i=r.get(n);if(i){const l=i.origin||s;a.x+=i.internals.positionAbsolute.x-(t.width??0)*l[0],a.y+=i.internals.positionAbsolute.y-(t.height??0)*l[1]}return a}function uBe(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function IKn(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function AKn(e){return{...vCt,...e||{}}}function V$(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=Ng(e),l=l4({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?o4(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const UOe=e=>({width:e.offsetWidth,height:e.offsetHeight}),ECt=e=>e?.getRootNode?.()||window?.document,RKn=["INPUT","SELECT","TEXTAREA"];function TCt(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:RKn.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const jCt=e=>"clientX"in e,Ng=(e,t)=>{const n=jCt(e),r=n?e.clientX:e.touches?.[0].clientX,s=n?e.clientY:e.touches?.[0].clientY;return{x:r-(t?.left??0),y:s-(t?.top??0)}},dBe=(e,t,n,r,s)=>{const a=t.querySelectorAll(`.${e}`);return!a||!a.length?null:Array.from(a).map(i=>{const l=i.getBoundingClientRect();return{id:i.getAttribute("data-handleid"),type:e,nodeId:s,position:i.getAttribute("data-handlepos"),x:(l.left-n.left)/r,y:(l.top-n.top)/r,...UOe(i)}})};function NCt({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:s,sourceControlY:a,targetControlX:i,targetControlY:l}){const c=e*.125+s*.375+i*.375+n*.125,u=t*.125+a*.375+l*.375+r*.125,d=Math.abs(c-e),f=Math.abs(u-t);return[c,u,d,f]}function IF(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function fBe({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case nr.Left:return[t-IF(t-r,a),n];case nr.Right:return[t+IF(r-t,a),n];case nr.Top:return[t,n-IF(n-s,a)];case nr.Bottom:return[t,n+IF(s-n,a)]}}function qOe({sourceX:e,sourceY:t,sourcePosition:n=nr.Bottom,targetX:r,targetY:s,targetPosition:a=nr.Top,curvature:i=.25}){const[l,c]=fBe({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=fBe({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,h,p,m]=NCt({sourceX:e,sourceY:t,targetX:r,targetY:s,sourceControlX:l,sourceControlY:c,targetControlX:u,targetControlY:d});return[`M${e},${t} C${l},${c} ${u},${d} ${r},${s}`,f,h,p,m]}function ICt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const s=Math.abs(n-e)/2,a=n<e?n+s:n-s,i=Math.abs(r-t)/2,l=r<t?r+i:r-i;return[a,l,s,i]}function PKn({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:s=!1,zIndexMode:a="basic"}){if(a==="manual")return r;const i=s&&n?r+1e3:r,l=Math.max(e.parentId||s&&e.selected?e.internals.z:0,t.parentId||s&&t.selected?t.internals.z:0);return i+l}function $Kn({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=OW(uU(e),uU(t));a.x===a.x2&&(a.x2+=1),a.y===a.y2&&(a.y2+=1);const i={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:r/s[2]};return GM(i,CW(a))>0}const MKn=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,DKn=(e,t)=>t.some(n=>n.source===e.source&&n.target===e.target&&(n.sourceHandle===e.sourceHandle||!n.sourceHandle&&!e.sourceHandle)&&(n.targetHandle===e.targetHandle||!n.targetHandle&&!e.targetHandle)),LKn=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||MKn;let s;return xCt(e)?s={...e}:s={...e,id:r(e)},DKn(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function ACt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=ICt({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const hBe={[nr.Left]:{x:-1,y:0},[nr.Right]:{x:1,y:0},[nr.Top]:{x:0,y:-1},[nr.Bottom]:{x:0,y:1}},FKn=({source:e,sourcePosition:t=nr.Bottom,target:n})=>t===nr.Left||t===nr.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},pBe=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function zKn({source:e,sourcePosition:t=nr.Bottom,target:n,targetPosition:r=nr.Top,center:s,offset:a,stepPosition:i}){const l=hBe[t],c=hBe[r],u={x:e.x+l.x*a,y:e.y+l.y*a},d={x:n.x+c.x*a,y:n.y+c.y*a},f=FKn({source:u,sourcePosition:t,target:d}),h=f.x!==0?"x":"y",p=f[h];let m=[],v,y;const b={x:0,y:0},x={x:0,y:0},[,,w,k]=ICt({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[h]*c[h]===-1){h==="x"?(v=s.x??u.x+(d.x-u.x)*i,y=s.y??(u.y+d.y)/2):(v=s.x??(u.x+d.x)/2,y=s.y??u.y+(d.y-u.y)*i);const E=[{x:v,y:u.y},{x:v,y:d.y}],N=[{x:u.x,y},{x:d.x,y}];l[h]===p?m=h==="x"?E:N:m=h==="x"?N:E}else{const E=[{x:u.x,y:d.y}],N=[{x:d.x,y:u.y}];if(h==="x"?m=l.x===p?N:E:m=l.y===p?E:N,t===r){const D=Math.abs(e[h]-n[h]);if(D<=a){const B=Math.min(a-1,a-D);l[h]===p?b[h]=(u[h]>e[h]?-1:1)*B:x[h]=(d[h]>n[h]?-1:1)*B}}if(t!==r){const D=h==="x"?"y":"x",B=l[h]===c[D],H=u[D]>d[D],q=u[D]<d[D];(l[h]===1&&(!B&&H||B&&q)||l[h]!==1&&(!B&&q||B&&H))&&(m=h==="x"?E:N)}const I={x:u.x+b.x,y:u.y+b.y},A={x:d.x+x.x,y:d.y+x.y},P=Math.max(Math.abs(I.x-m[0].x),Math.abs(A.x-m[0].x)),L=Math.max(Math.abs(I.y-m[0].y),Math.abs(A.y-m[0].y));P>=L?(v=(I.x+A.x)/2,y=m[0].y):(v=m[0].x,y=(I.y+A.y)/2)}const C={x:u.x+b.x,y:u.y+b.y},_={x:d.x+x.x,y:d.y+x.y};return[[e,...C.x!==m[0].x||C.y!==m[0].y?[C]:[],...m,..._.x!==m[m.length-1].x||_.y!==m[m.length-1].y?[_]:[],n],v,y,w,k]}function BKn(e,t,n,r){const s=Math.min(pBe(e,t)/2,pBe(t,n)/2,r),{x:a,y:i}=t;if(e.x===a&&a===n.x||e.y===i&&i===n.y)return`L${a} ${i}`;if(e.y===i){const u=e.x<n.x?-1:1,d=e.y<n.y?1:-1;return`L ${a+s*u},${i}Q ${a},${i} ${a},${i+s*d}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${a},${i+s*c}Q ${a},${i} ${a+s*l},${i}`}function Uve({sourceX:e,sourceY:t,sourcePosition:n=nr.Bottom,targetX:r,targetY:s,targetPosition:a=nr.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,h,p,m,v]=zKn({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:s},targetPosition:a,center:{x:l,y:c},offset:u,stepPosition:d});let y=`M${f[0].x} ${f[0].y}`;for(let b=1;b<f.length-1;b++)y+=BKn(f[b-1],f[b],f[b+1],i);return y+=`L${f[f.length-1].x} ${f[f.length-1].y}`,[y,h,p,m,v]}function mBe(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function UKn(e){const{sourceNode:t,targetNode:n}=e;if(!mBe(t)||!mBe(n))return null;const r=t.internals.handleBounds||gBe(t.handles),s=n.internals.handleBounds||gBe(n.handles),a=vBe(r?.source??[],e.sourceHandle),i=vBe(e.connectionMode===cN.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!a||!i)return e.onError?.("008",Ty.error008(a?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=a?.position||nr.Bottom,c=i?.position||nr.Top,u=lC(t,a,l),d=lC(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function gBe(e){if(!e)return null;const t=[],n=[];for(const r of e)r.width=r.width??1,r.height=r.height??1,r.type==="source"?t.push(r):r.type==="target"&&n.push(r);return{source:t,target:n}}function lC(e,t,n=nr.Left,r=!1){const s=(t?.x??0)+e.internals.positionAbsolute.x,a=(t?.y??0)+e.internals.positionAbsolute.y,{width:i,height:l}=t??l0(e);if(r)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case nr.Top:return{x:s+i/2,y:a};case nr.Right:return{x:s+i,y:a+l/2};case nr.Bottom:return{x:s+i/2,y:a+l};case nr.Left:return{x:s,y:a+l/2}}}function vBe(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function qve(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function qKn(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:s}){const a=new Set;return e.reduce((i,l)=>([l.markerStart||r,l.markerEnd||s].forEach(c=>{if(c&&typeof c=="object"){const u=qve(c,t);a.has(u)||(i.push({id:u,color:c.color||n,...c}),a.add(u))}}),i),[]).sort((i,l)=>i.id.localeCompare(l.id))}const RCt=1e3,VKn=10,VOe={nodeOrigin:[0,0],nodeExtent:HM,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},HKn={...VOe,checkEquality:!0};function HOe(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function WKn(e,t,n){const r=HOe(VOe,n);for(const s of e.values())if(s.parentId)ZOe(s,e,t,r);else{const a=a4(s,r.nodeOrigin),i=fN(s.extent)?s.extent:r.nodeExtent,l=oC(a,i,l0(s));s.internals.positionAbsolute=l}}function ZKn(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;const n=[],r=[];for(const s of e.handles){const a={id:s.id,width:s.width??1,height:s.height??1,nodeId:e.id,x:s.x,y:s.y,position:s.position,type:s.type};s.type==="source"?n.push(a):s.type==="target"&&r.push(a)}return{source:n,target:r}}function WOe(e){return e==="manual"}function Vve(e,t,n,r={}){const s=HOe(HKn,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!WOe(s.zIndexMode)?RCt:0;let c=e.length>0,u=!1;t.clear(),n.clear();for(const d of e){let f=i.get(d.id);if(s.checkEquality&&d===f?.internals.userNode)t.set(d.id,f);else{const h=a4(d,s.nodeOrigin),p=fN(d.extent)?d.extent:s.nodeExtent,m=oC(h,p,l0(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:ZKn(d,f),z:PCt(d,l,s.zIndexMode),userNode:d}},t.set(d.id,f)}(f.measured===void 0||f.measured.width===void 0||f.measured.height===void 0)&&!f.hidden&&(c=!1),d.parentId&&ZOe(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function GKn(e,t){if(!e.parentId)return;const n=t.get(e.parentId);n?n.set(e.id,e):t.set(e.parentId,new Map([[e.id,e]]))}function ZOe(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=HOe(VOe,r),u=e.parentId,d=t.get(u);if(!d){console.warn(`Parent node ${u} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}GKn(e,n),s&&!d.parentId&&d.internals.rootParentIndex===void 0&&c==="auto"&&(d.internals.rootParentIndex=++s.i,d.internals.z=d.internals.z+s.i*VKn),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!WOe(c)?RCt:0,{x:h,y:p,z:m}=QKn(e,d,i,l,f,c),{positionAbsolute:v}=e.internals,y=h!==v.x||p!==v.y;(y||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:h,y:p}:v,z:m}})}function PCt(e,t,n){const r=jg(e.zIndex)?e.zIndex:0;return WOe(n)?r:r+(e.selected?t:0)}function QKn(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=l0(e),u=a4(e,n),d=fN(e.extent)?oC(u,e.extent,c):u;let f=oC({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=SCt(f,c,t));const h=PCt(e,s,a),p=t.internals.z??0;return{x:f.x,y:f.y,z:p>=h?p+1:h}}function GOe(e,t,n,r=[0,0]){const s=[],a=new Map;for(const i of e){const l=t.get(i.parentId);if(!l)continue;const c=a.get(i.parentId)?.expandedRect??dN(l),u=OCt(c,i.rect);a.set(i.parentId,{expandedRect:u,parent:l})}return a.size>0&&a.forEach(({expandedRect:i,parent:l},c)=>{const u=l.internals.positionAbsolute,d=l0(l),f=l.origin??r,h=i.x<u.x?Math.round(Math.abs(u.x-i.x)):0,p=i.y<u.y?Math.round(Math.abs(u.y-i.y)):0,m=Math.max(d.width,Math.round(i.width)),v=Math.max(d.height,Math.round(i.height)),y=(m-d.width)*f[0],b=(v-d.height)*f[1];(h>0||p>0||y||b)&&(s.push({id:c,type:"position",position:{x:l.position.x-h+y,y:l.position.y-p+b}}),n.get(c)?.forEach(x=>{e.some(w=>w.id===x.id)||s.push({id:x.id,type:"position",position:{x:x.position.x+h,y:x.position.y+p}})})),(d.width<i.width||d.height<i.height||h||p)&&s.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:m+(h?f[0]*h-y:0),height:v+(p?f[1]*p-b:0)}})}),s}function YKn(e,t,n,r,s,a,i){const l=r?.querySelector(".xyflow__viewport");let c=!1;if(!l)return{changes:[],updatedInternals:c};const u=[],d=window.getComputedStyle(l),{m22:f}=new window.DOMMatrixReadOnly(d.transform),h=[];for(const p of e.values()){const m=t.get(p.id);if(!m)continue;if(m.hidden){t.set(m.id,{...m,internals:{...m.internals,handleBounds:void 0}}),c=!0;continue}const v=UOe(p.nodeElement),y=m.measured.width!==v.width||m.measured.height!==v.height;if(!!(v.width&&v.height&&(y||!m.internals.handleBounds||p.force))){const x=p.nodeElement.getBoundingClientRect(),w=fN(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=SCt(k,v,t.get(m.parentId)):w&&(k=oC(k,w,v));const C={...m,measured:v,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:dBe("source",p.nodeElement,x,f,m.id),target:dBe("target",p.nodeElement,x,f,m.id)}}};t.set(m.id,C),m.parentId&&ZOe(C,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,y&&(u.push({id:m.id,type:"dimensions",dimensions:v}),m.expandParent&&m.parentId&&h.push({id:m.id,parentId:m.parentId,rect:dN(C,s)}))}}if(h.length>0){const p=GOe(h,t,n,s);u.push(...p)}return{changes:u,updatedInternals:c}}async function KKn({delta:e,panZoom:t,transform:n,translateExtent:r,width:s,height:a}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const i=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[s,a]],r),l=!!i&&(i.x!==n[0]||i.y!==n[1]||i.k!==n[2]);return Promise.resolve(l)}function yBe(e,t,n,r,s,a){let i=s;const l=r.get(i)||new Map;r.set(i,l.set(n,t)),i=`${s}-${e}`;const c=r.get(i)||new Map;if(r.set(i,c.set(n,t)),a){i=`${s}-${e}-${a}`;const u=r.get(i)||new Map;r.set(i,u.set(n,t))}}function $Ct(e,t,n){e.clear(),t.clear();for(const r of n){const{source:s,target:a,sourceHandle:i=null,targetHandle:l=null}=r,c={edgeId:r.id,source:s,target:a,sourceHandle:i,targetHandle:l},u=`${s}-${i}--${a}-${l}`,d=`${a}-${l}--${s}-${i}`;yBe("source",c,d,e,s,i),yBe("target",c,u,e,a,l),t.set(r.id,r)}}function MCt(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:MCt(n,t):!1}function bBe(e,t,n){let r=e;do{if(r?.matches?.(t))return!0;if(r===n)return!1;r=r?.parentElement}while(r);return!1}function XKn(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!MCt(i,e))&&(i.draggable||t&&typeof i.draggable>"u")){const l=e.get(a);l&&s.set(a,{id:a,position:l.position||{x:0,y:0},distance:{x:n.x-l.internals.positionAbsolute.x,y:n.y-l.internals.positionAbsolute.y},extent:l.extent,parentId:l.parentId,origin:l.origin,expandParent:l.expandParent,internals:{positionAbsolute:l.internals.positionAbsolute||{x:0,y:0}},measured:{width:l.measured.width??0,height:l.measured.height??0}})}return s}function Sne({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){const s=[];for(const[i,l]of t){const c=n.get(i)?.internals.userNode;c&&s.push({...c,position:l.position,dragging:r})}if(!e)return[s[0],s];const a=n.get(e)?.internals.userNode;return[a?{...a,position:t.get(e)?.position||a.position,dragging:r}:s[0],s]}function JKn({dragItems:e,snapGrid:t,x:n,y:r}){const s=e.values().next().value;if(!s)return null;const a={x:n-s.distance.x,y:r-s.distance.y},i=o4(a,t);return{x:i.x-a.x,y:i.y-a.y}}function eXn({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:s}){let a={x:null,y:null},i=0,l=new Map,c=!1,u={x:0,y:0},d=null,f=!1,h=null,p=!1,m=!1,v=null;function y({noDragClassName:x,handleSelector:w,domNode:k,isSelectable:C,nodeId:_,nodeClickDistance:T=0}){h=Eh(k);function E({x:P,y:L}){const{nodeLookup:D,nodeExtent:B,snapGrid:H,snapToGrid:q,nodeOrigin:z,onNodeDrag:V,onSelectionDrag:M,onError:G,updateNodePositions:F}=t();a={x:P,y:L};let R=!1;const U=l.size>1,Z=U&&B?Bve(i4(l)):null,Y=U&&q?JKn({dragItems:l,snapGrid:H,x:P,y:L}):null;for(const[te,J]of l){if(!D.has(te))continue;let ee={x:P-J.distance.x,y:L-J.distance.y};q&&(ee=Y?{x:Math.round(ee.x+Y.x),y:Math.round(ee.y+Y.y)}:o4(ee,H));let re=null;if(U&&B&&!J.extent&&Z){const{positionAbsolute:ne}=J.internals,se=ne.x-Z.x+B[0][0],ce=ne.x+J.measured.width-Z.x2+B[1][0],le=ne.y-Z.y+B[0][1],be=ne.y+J.measured.height-Z.y2+B[1][1];re=[[se,le],[ce,be]]}const{position:ae,positionAbsolute:X}=wCt({nodeId:te,nextPosition:ee,nodeLookup:D,nodeExtent:re||B,nodeOrigin:z,onError:G});R=R||J.position.x!==ae.x||J.position.y!==ae.y,J.position=ae,J.internals.positionAbsolute=X}if(m=m||R,!!R&&(F(l,!0),v&&(r||V||!_&&M))){const[te,J]=Sne({nodeId:_,dragItems:l,nodeLookup:D});r?.(v,l,te,J),V?.(v,te,J),_||M?.(v,J)}}async function N(){if(!d)return;const{transform:P,panBy:L,autoPanSpeed:D,autoPanOnNodeDrag:B}=t();if(!B){c=!1,cancelAnimationFrame(i);return}const[H,q]=kCt(u,d,D);(H!==0||q!==0)&&(a.x=(a.x??0)-H/P[2],a.y=(a.y??0)-q/P[2],await L({x:H,y:q})&&E(a)),i=requestAnimationFrame(N)}function I(P){const{nodeLookup:L,multiSelectionActive:D,nodesDraggable:B,transform:H,snapGrid:q,snapToGrid:z,selectNodesOnDrag:V,onNodeDragStart:M,onSelectionDragStart:G,unselectNodesAndEdges:F}=t();f=!0,(!V||!C)&&!D&&_&&(L.get(_)?.selected||F()),C&&V&&_&&e?.(_);const R=V$(P.sourceEvent,{transform:H,snapGrid:q,snapToGrid:z,containerBounds:d});if(a=R,l=XKn(L,B,R,_),l.size>0&&(n||M||!_&&G)){const[U,Z]=Sne({nodeId:_,dragItems:l,nodeLookup:L});n?.(P.sourceEvent,l,U,Z),M?.(P.sourceEvent,U,Z),_||G?.(P.sourceEvent,Z)}}const A=eCt().clickDistance(T).on("start",P=>{const{domNode:L,nodeDragThreshold:D,transform:B,snapGrid:H,snapToGrid:q}=t();d=L?.getBoundingClientRect()||null,p=!1,m=!1,v=P.sourceEvent,D===0&&I(P),a=V$(P.sourceEvent,{transform:B,snapGrid:H,snapToGrid:q,containerBounds:d}),u=Ng(P.sourceEvent,d)}).on("drag",P=>{const{autoPanOnNodeDrag:L,transform:D,snapGrid:B,snapToGrid:H,nodeDragThreshold:q,nodeLookup:z}=t(),V=V$(P.sourceEvent,{transform:D,snapGrid:B,snapToGrid:H,containerBounds:d});if(v=P.sourceEvent,(P.sourceEvent.type==="touchmove"&&P.sourceEvent.touches.length>1||_&&!z.has(_))&&(p=!0),!p){if(!c&&L&&f&&(c=!0,N()),!f){const M=Ng(P.sourceEvent,d),G=M.x-u.x,F=M.y-u.y;Math.sqrt(G*G+F*F)>q&&I(P)}(a.x!==V.xSnapped||a.y!==V.ySnapped)&&l&&f&&(u=Ng(P.sourceEvent,d),E(V))}}).on("end",P=>{if(!(!f||p)&&(c=!1,f=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:L,updateNodePositions:D,onNodeDragStop:B,onSelectionDragStop:H}=t();if(m&&(D(l,!1),m=!1),s||B||!_&&H){const[q,z]=Sne({nodeId:_,dragItems:l,nodeLookup:L,dragging:!1});s?.(P.sourceEvent,l,q,z),B?.(P.sourceEvent,q,z),_||H?.(P.sourceEvent,z)}}}).filter(P=>{const L=P.target;return!P.button&&(!x||!bBe(L,`.${x}`,k))&&(!w||bBe(L,w,k))});h.call(A)}function b(){h?.on(".drag",null)}return{update:y,destroy:b}}function tXn(e,t,n){const r=[],s={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const a of t.values())GM(s,dN(a))>0&&r.push(a);return r}const nXn=250;function rXn(e,t,n,r){let s=[],a=1/0;const i=tXn(e,n,t+nXn);for(const l of i){const c=[...l.internals.handleBounds?.source??[],...l.internals.handleBounds?.target??[]];for(const u of c){if(r.nodeId===u.nodeId&&r.type===u.type&&r.id===u.id)continue;const{x:d,y:f}=lC(l,u,u.position,!0),h=Math.sqrt(Math.pow(d-e.x,2)+Math.pow(f-e.y,2));h>t||(h<a?(s=[{...u,x:d,y:f}],a=h):h===a&&s.push({...u,x:d,y:f}))}}if(!s.length)return null;if(s.length>1){const l=r.type==="source"?"target":"source";return s.find(c=>c.type===l)??s[0]}return s[0]}function DCt(e,t,n,r,s,a=!1){const i=r.get(e);if(!i)return null;const l=s==="strict"?i.internals.handleBounds?.[t]:[...i.internals.handleBounds?.source??[],...i.internals.handleBounds?.target??[]],c=(n?l?.find(u=>u.id===n):l?.[0])??null;return c&&a?{...c,...lC(i,c,c.position,!0)}:c}function LCt(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function sXn(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const FCt=()=>!0;function aXn(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:a,isTarget:i,domNode:l,nodeLookup:c,lib:u,autoPanOnConnect:d,flowId:f,panBy:h,cancelConnection:p,onConnectStart:m,onConnect:v,onConnectEnd:y,isValidConnection:b=FCt,onReconnectEnd:x,updateConnection:w,getTransform:k,getFromHandle:C,autoPanSpeed:_,dragThreshold:T=1,handleDomNode:E}){const N=ECt(e.target);let I=0,A;const{x:P,y:L}=Ng(e),D=LCt(a,E),B=l?.getBoundingClientRect();let H=!1;if(!B||!D)return;const q=DCt(s,D,r,c,t);if(!q)return;let z=Ng(e,B),V=!1,M=null,G=!1,F=null;function R(){if(!d||!B)return;const[ae,X]=kCt(z,B,_);h({x:ae,y:X}),I=requestAnimationFrame(R)}const U={...q,nodeId:s,type:D,position:q.position},Z=c.get(s);let te={inProgress:!0,isValid:null,from:lC(Z,U,nr.Left,!0),fromHandle:U,fromPosition:U.position,fromNode:Z,to:z,toHandle:null,toPosition:oBe[U.position],toNode:null,pointer:z};function J(){H=!0,w(te),m?.(e,{nodeId:s,handleId:r,handleType:D})}T===0&&J();function ee(ae){if(!H){const{x:be,y:he}=Ng(ae),xe=be-P,Ae=he-L;if(!(xe*xe+Ae*Ae>T*T))return;J()}if(!C()||!U){re(ae);return}const X=k();z=Ng(ae,B),A=rXn(l4(z,X,!1,[1,1]),n,c,U),V||(R(),V=!0);const ne=zCt(ae,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});F=ne.handleDomNode,M=ne.connection,G=sXn(!!A,ne.isValid);const se=c.get(s),ce=se?lC(se,U,nr.Left,!0):te.from,le={...te,from:ce,isValid:G,to:ne.toHandle&&G?dU({x:ne.toHandle.x,y:ne.toHandle.y},X):z,toHandle:ne.toHandle,toPosition:G&&ne.toHandle?ne.toHandle.position:oBe[U.position],toNode:ne.toHandle?c.get(ne.toHandle.nodeId):null,pointer:z};w(le),te=le}function re(ae){if(!("touches"in ae&&ae.touches.length>0)){if(H){(A||F)&&M&&G&&v?.(M);const{inProgress:X,...ne}=te,se={...ne,toPosition:te.toHandle?te.toPosition:null};y?.(ae,se),a&&x?.(ae,se)}p(),cancelAnimationFrame(I),V=!1,G=!1,M=null,F=null,N.removeEventListener("mousemove",ee),N.removeEventListener("mouseup",re),N.removeEventListener("touchmove",ee),N.removeEventListener("touchend",re)}}N.addEventListener("mousemove",ee),N.addEventListener("mouseup",re),N.addEventListener("touchmove",ee),N.addEventListener("touchend",re)}function zCt(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=FCt,nodeLookup:d}){const f=a==="target",h=t?i.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:p,y:m}=Ng(e),v=i.elementFromPoint(p,m),y=v?.classList.contains(`${l}-flow__handle`)?v:h,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){const x=LCt(void 0,y),w=y.getAttribute("data-nodeid"),k=y.getAttribute("data-handleid"),C=y.classList.contains("connectable"),_=y.classList.contains("connectableend");if(!w||!x)return b;const T={source:f?w:r,sourceHandle:f?k:s,target:f?r:w,targetHandle:f?s:k};b.connection=T;const N=C&&_&&(n===cN.Strict?f&&x==="source"||!f&&x==="target":w!==r||k!==s);b.isValid=N&&u(T),b.toHandle=DCt(w,x,k,d,n,!0)}return b}const Hve={onPointerDown:aXn,isValid:zCt};function iXn({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Eh(e);function a({translateExtent:l,width:c,height:u,zoomStep:d=1,pannable:f=!0,zoomable:h=!0,inversePan:p=!1}){const m=w=>{if(w.sourceEvent.type!=="wheel"||!t)return;const k=n(),C=w.sourceEvent.ctrlKey&&QM()?10:1,_=-w.sourceEvent.deltaY*(w.sourceEvent.deltaMode===1?.05:w.sourceEvent.deltaMode?1:.002)*d,T=k[2]*Math.pow(2,_*C);t.scaleTo(T)};let v=[0,0];const y=w=>{(w.sourceEvent.type==="mousedown"||w.sourceEvent.type==="touchstart")&&(v=[w.sourceEvent.clientX??w.sourceEvent.touches[0].clientX,w.sourceEvent.clientY??w.sourceEvent.touches[0].clientY])},b=w=>{const k=n();if(w.sourceEvent.type!=="mousemove"&&w.sourceEvent.type!=="touchmove"||!t)return;const C=[w.sourceEvent.clientX??w.sourceEvent.touches[0].clientX,w.sourceEvent.clientY??w.sourceEvent.touches[0].clientY],_=[C[0]-v[0],C[1]-v[1]];v=C;const T=r()*Math.max(k[2],Math.log(k[2]))*(p?-1:1),E={x:k[0]-_[0]*T,y:k[1]-_[1]*T},N=[[0,0],[c,u]];t.setViewportConstrained({x:E.x,y:E.y,zoom:k[2]},N,l)},x=mCt().on("start",y).on("zoom",f?b:null).on("zoom.wheel",h?m:null);s.call(x,{})}function i(){s.on("zoom",null)}return{update:a,destroy:i,pointer:vg}}const _W=e=>({x:e.x,y:e.y,zoom:e.k}),kne=({x:e,y:t,zoom:n})=>kW.translate(e,t).scale(n),ET=(e,t)=>e.target.closest(`.${t}`),BCt=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),oXn=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,One=(e,t=0,n=oXn,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},UCt=e=>{const t=e.ctrlKey&&QM()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function lXn({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(ET(d,t))return d.ctrlKey&&d.preventDefault(),!1;d.preventDefault(),d.stopImmediatePropagation();const f=n.property("__zoom").k||1;if(d.ctrlKey&&i){const y=vg(d),b=UCt(d),x=f*Math.pow(2,b);r.scaleTo(n,x,y,d);return}const h=d.deltaMode===1?20:1;let p=s===fO.Vertical?0:d.deltaX*h,m=s===fO.Horizontal?0:d.deltaY*h;!QM()&&d.shiftKey&&s!==fO.Vertical&&(p=d.deltaY*h,m=0),r.translateBy(n,-(p/f)*a,-(m/f)*a,{internal:!0});const v=_W(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(d,v),e.panScrollTimeout=setTimeout(()=>{u?.(d,v),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l?.(d,v))}}function cXn({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=ET(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function uXn({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=_W(r.transform);e.mouseButton=r.sourceEvent?.button||0,e.isZoomingOrPanning=!0,e.prevViewport=s,r.sourceEvent?.type==="mousedown"&&t(!0),n&&n?.(r.sourceEvent,s)}}function dXn({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&BCt(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,_W(a.transform))}}function fXn({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&BCt(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=_W(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function hXn({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:s,zoomOnDoubleClick:a,userSelectionActive:i,noWheelClassName:l,noPanClassName:c,lib:u,connectionInProgress:d}){return f=>{const h=e||t,p=n&&f.ctrlKey,m=f.type==="wheel";if(f.button===1&&f.type==="mousedown"&&(ET(f,`${u}-flow__node`)||ET(f,`${u}-flow__edge`)))return!0;if(!r&&!h&&!s&&!a&&!n||i||d&&!m||ET(f,l)&&m||ET(f,c)&&(!m||s&&m&&!e)||!n&&f.ctrlKey&&m)return!1;if(!n&&f.type==="touchstart"&&f.touches?.length>1)return f.preventDefault(),!1;if(!h&&!s&&!p&&m||!r&&(f.type==="mousedown"||f.type==="touchstart")||Array.isArray(r)&&!r.includes(f.button)&&f.type==="mousedown")return!1;const v=Array.isArray(r)&&r.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||m)&&v}}function pXn({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:s,onPanZoom:a,onPanZoomStart:i,onPanZoomEnd:l,onDraggingChange:c}){const u={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},d=e.getBoundingClientRect(),f=mCt().scaleExtent([t,n]).translateExtent(r),h=Eh(e).call(f);x({x:s.x,y:s.y,zoom:uN(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const p=h.on("wheel.zoom"),m=h.on("dblclick.zoom");f.wheelDelta(UCt);function v(A,P){return h?new Promise(L=>{f?.interpolate(P?.interpolate==="linear"?bx:r9).transform(One(h,P?.duration,P?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:P,onPaneContextMenu:L,userSelectionActive:D,panOnScroll:B,panOnDrag:H,panOnScrollMode:q,panOnScrollSpeed:z,preventScrolling:V,zoomOnPinch:M,zoomOnScroll:G,zoomOnDoubleClick:F,zoomActivationKeyPressed:R,lib:U,onTransformChange:Z,connectionInProgress:Y,paneClickDistance:te,selectionOnDrag:J}){D&&!u.isZoomingOrPanning&&b();const ee=B&&!R&&!D;f.clickDistance(J?1/0:!jg(te)||te<0?0:te);const re=ee?lXn({zoomPanValues:u,noWheelClassName:A,d3Selection:h,d3Zoom:f,panOnScrollMode:q,panOnScrollSpeed:z,zoomOnPinch:M,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):cXn({noWheelClassName:A,preventScrolling:V,d3ZoomHandler:p});if(h.on("wheel.zoom",re,{passive:!1}),!D){const X=uXn({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",X);const ne=dXn({zoomPanValues:u,panOnDrag:H,onPaneContextMenu:!!L,onPanZoom:a,onTransformChange:Z});f.on("zoom",ne);const se=fXn({zoomPanValues:u,panOnDrag:H,panOnScroll:B,onPaneContextMenu:L,onPanZoomEnd:l,onDraggingChange:c});f.on("end",se)}const ae=hXn({zoomActivationKeyPressed:R,panOnDrag:H,zoomOnScroll:G,panOnScroll:B,zoomOnDoubleClick:F,zoomOnPinch:M,userSelectionActive:D,noPanClassName:P,noWheelClassName:A,lib:U,connectionInProgress:Y});f.filter(ae),F?h.on("dblclick.zoom",m):h.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,P,L){const D=kne(A),B=f?.constrain()(D,P,L);return B&&await v(B),new Promise(H=>H(B))}async function w(A,P){const L=kne(A);return await v(L,P),new Promise(D=>D(L))}function k(A){if(h){const P=kne(A),L=h.property("__zoom");(L.k!==A.zoom||L.x!==A.x||L.y!==A.y)&&f?.transform(h,P,null,{sync:!0})}}function C(){const A=h?pCt(h.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function _(A,P){return h?new Promise(L=>{f?.interpolate(P?.interpolate==="linear"?bx:r9).scaleTo(One(h,P?.duration,P?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function T(A,P){return h?new Promise(L=>{f?.interpolate(P?.interpolate==="linear"?bx:r9).scaleBy(One(h,P?.duration,P?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function E(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const P=!jg(A)||A<0?0:A;f?.clickDistance(P)}return{update:y,destroy:b,setViewport:w,setViewportConstrained:x,getViewport:C,scaleTo:_,scaleBy:T,setScaleExtent:E,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var hN;(function(e){e.Line="line",e.Handle="handle"})(hN||(hN={}));function mXn({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:s,affectsY:a}){const i=e-t,l=n-r,c=[i>0?1:i<0?-1:0,l>0?1:l<0?-1:0];return i&&s&&(c[0]=c[0]*-1),l&&a&&(c[1]=c[1]*-1),c}function xBe(e){const t=e.includes("right")||e.includes("left"),n=e.includes("bottom")||e.includes("top"),r=e.includes("left"),s=e.includes("top");return{isHorizontal:t,isVertical:n,affectsX:r,affectsY:s}}function nw(e,t){return Math.max(0,t-e)}function rw(e,t){return Math.max(0,e-t)}function AF(e,t,n){return Math.max(0,t-e,e-n)}function wBe(e,t){return e?!t:t}function gXn(e,t,n,r,s,a,i,l){let{affectsX:c,affectsY:u}=t;const{isHorizontal:d,isVertical:f}=t,h=d&&f,{xSnapped:p,ySnapped:m}=n,{minWidth:v,maxWidth:y,minHeight:b,maxHeight:x}=r,{x:w,y:k,width:C,height:_,aspectRatio:T}=e;let E=Math.floor(d?p-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=C+(c?-E:E),A=_+(u?-N:N),P=-a[0]*C,L=-a[1]*_;let D=AF(I,v,y),B=AF(A,b,x);if(i){let z=0,V=0;c&&E<0?z=nw(w+E+P,i[0][0]):!c&&E>0&&(z=rw(w+I+P,i[1][0])),u&&N<0?V=nw(k+N+L,i[0][1]):!u&&N>0&&(V=rw(k+A+L,i[1][1])),D=Math.max(D,z),B=Math.max(B,V)}if(l){let z=0,V=0;c&&E>0?z=rw(w+E,l[0][0]):!c&&E<0&&(z=nw(w+I,l[1][0])),u&&N>0?V=rw(k+N,l[0][1]):!u&&N<0&&(V=nw(k+A,l[1][1])),D=Math.max(D,z),B=Math.max(B,V)}if(s){if(d){const z=AF(I/T,b,x)*T;if(D=Math.max(D,z),i){let V=0;!c&&!u||c&&!u&&h?V=rw(k+L+I/T,i[1][1])*T:V=nw(k+L+(c?E:-E)/T,i[0][1])*T,D=Math.max(D,V)}if(l){let V=0;!c&&!u||c&&!u&&h?V=nw(k+I/T,l[1][1])*T:V=rw(k+(c?E:-E)/T,l[0][1])*T,D=Math.max(D,V)}}if(f){const z=AF(A*T,v,y)/T;if(B=Math.max(B,z),i){let V=0;!c&&!u||u&&!c&&h?V=rw(w+A*T+P,i[1][0])/T:V=nw(w+(u?N:-N)*T+P,i[0][0])/T,B=Math.max(B,V)}if(l){let V=0;!c&&!u||u&&!c&&h?V=nw(w+A*T,l[1][0])/T:V=rw(w+(u?N:-N)*T,l[0][0])/T,B=Math.max(B,V)}}}N=N+(N<0?B:-B),E=E+(E<0?D:-D),s&&(h?I>A*T?N=(wBe(c,u)?-E:E)/T:E=(wBe(c,u)?-N:N)*T:d?(N=E/T,u=c):(E=N*T,c=u));const H=c?w+E:w,q=u?k+N:k;return{width:C+(c?-E:E),height:_+(u?-N:N),x:a[0]*E*(c?-1:1)+H,y:a[1]*N*(u?-1:1)+q}}const qCt={width:0,height:0,x:0,y:0},vXn={...qCt,pointerX:0,pointerY:0,aspectRatio:1};function yXn(e){return[[0,0],[e.measured.width,e.measured.height]]}function bXn(e,t,n){const r=t.position.x+e.position.x,s=t.position.y+e.position.y,a=e.measured.width??0,i=e.measured.height??0,l=n[0]*a,c=n[1]*i;return[[r-l,s-c],[r+a-l,s+i-c]]}function xXn({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=Eh(e);let i={controlDirection:xBe("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:u,boundaries:d,keepAspectRatio:f,resizeDirection:h,onResizeStart:p,onResize:m,onResizeEnd:v,shouldResize:y}){let b={...qCt},x={...vXn};i={boundaries:d,resizeDirection:h,keepAspectRatio:f,controlDirection:xBe(u)};let w,k=null,C=[],_,T,E,N=!1;const I=eCt().on("start",A=>{const{nodeLookup:P,transform:L,snapGrid:D,snapToGrid:B,nodeOrigin:H,paneDomNode:q}=n();if(w=P.get(t),!w)return;k=q?.getBoundingClientRect()??null;const{xSnapped:z,ySnapped:V}=V$(A.sourceEvent,{transform:L,snapGrid:D,snapToGrid:B,containerBounds:k});b={width:w.measured.width??0,height:w.measured.height??0,x:w.position.x??0,y:w.position.y??0},x={...b,pointerX:z,pointerY:V,aspectRatio:b.width/b.height},_=void 0,w.parentId&&(w.extent==="parent"||w.expandParent)&&(_=P.get(w.parentId),T=_&&w.extent==="parent"?yXn(_):void 0),C=[],E=void 0;for(const[M,G]of P)if(G.parentId===t&&(C.push({id:M,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const F=bXn(G,w,G.origin??H);E?E=[[Math.min(F[0][0],E[0][0]),Math.min(F[0][1],E[0][1])],[Math.max(F[1][0],E[1][0]),Math.max(F[1][1],E[1][1])]]:E=F}p?.(A,{...b})}).on("drag",A=>{const{transform:P,snapGrid:L,snapToGrid:D,nodeOrigin:B}=n(),H=V$(A.sourceEvent,{transform:P,snapGrid:L,snapToGrid:D,containerBounds:k}),q=[];if(!w)return;const{x:z,y:V,width:M,height:G}=b,F={},R=w.origin??B,{width:U,height:Z,x:Y,y:te}=gXn(x,i.controlDirection,H,i.boundaries,i.keepAspectRatio,R,T,E),J=U!==M,ee=Z!==G,re=Y!==z&&J,ae=te!==V&&ee;if(!re&&!ae&&!J&&!ee)return;if((re||ae||R[0]===1||R[1]===1)&&(F.x=re?Y:b.x,F.y=ae?te:b.y,b.x=F.x,b.y=F.y,C.length>0)){const ce=Y-z,le=te-V;for(const be of C)be.position={x:be.position.x-ce+R[0]*(U-M),y:be.position.y-le+R[1]*(Z-G)},q.push(be)}if((J||ee)&&(F.width=J&&(!i.resizeDirection||i.resizeDirection==="horizontal")?U:b.width,F.height=ee&&(!i.resizeDirection||i.resizeDirection==="vertical")?Z:b.height,b.width=F.width,b.height=F.height),_&&w.expandParent){const ce=R[0]*(F.width??0);F.x&&F.x<ce&&(b.x=ce,x.x=x.x-(F.x-ce));const le=R[1]*(F.height??0);F.y&&F.y<le&&(b.y=le,x.y=x.y-(F.y-le))}const X=mXn({width:b.width,prevWidth:M,height:b.height,prevHeight:G,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),ne={...b,direction:X};y?.(A,ne)!==!1&&(N=!0,m?.(A,ne),r(F,q))}).on("end",A=>{N&&(v?.(A,{...b}),s?.({...b}),N=!1)});a.call(I)}function c(){a.on(".drag",null)}return{update:l,destroy:c}}const wXn={},SBe=e=>{let t;const n=new Set,r=(d,f)=>{const h=typeof d=="function"?d(t):d;if(!Object.is(h,t)){const p=t;t=f??(typeof h!="object"||h===null)?h:Object.assign({},t,h),n.forEach(m=>m(t,p))}},s=()=>t,c={setState:r,getState:s,getInitialState:()=>u,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(wXn?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},u=t=e(r,s,c);return c},SXn=e=>e?SBe(e):SBe,{useDebugValue:kXn}=qe,{useSyncExternalStoreWithSelector:OXn}=zNn,CXn=e=>e;function VCt(e,t=CXn,n){const r=OXn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return kXn(r),r}const kBe=(e,t)=>{const n=SXn(e),r=(s,a=t)=>VCt(n,s,a);return Object.assign(r,n),r},_Xn=(e,t)=>e?kBe(e,t):kBe;function oo(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,s]of e)if(!Object.is(s,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}const EW=g.createContext(null),EXn=EW.Provider,HCt=Ty.error001();function Ws(e,t){const n=g.useContext(EW);if(n===null)throw new Error(HCt);return VCt(n,e,t)}function To(){const e=g.useContext(EW);if(e===null)throw new Error(HCt);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const OBe={display:"none"},TXn={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},WCt="react-flow__node-desc",ZCt="react-flow__edge-desc",jXn="react-flow__aria-live",NXn=e=>e.ariaLiveMessage,IXn=e=>e.ariaLabelConfig;function AXn({rfId:e}){const t=Ws(NXn);return o.jsx("div",{id:`${jXn}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:TXn,children:t})}function RXn({rfId:e,disableKeyboardA11y:t}){const n=Ws(IXn);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${WCt}-${e}`,style:OBe,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${ZCt}-${e}`,style:OBe,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(AXn,{rfId:e})]})}const c4=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:Ql(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});c4.displayName="Panel";function PXn({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(c4,{position:t,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev",children:o.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const $Xn=e=>{const t=[],n=[];for(const[,r]of e.nodeLookup)r.selected&&t.push(r.internals.userNode);for(const[,r]of e.edgeLookup)r.selected&&n.push(r);return{selectedNodes:t,selectedEdges:n}},RF=e=>e.id;function MXn(e,t){return oo(e.selectedNodes.map(RF),t.selectedNodes.map(RF))&&oo(e.selectedEdges.map(RF),t.selectedEdges.map(RF))}function DXn({onSelectionChange:e}){const t=To(),{selectedNodes:n,selectedEdges:r}=Ws($Xn,MXn);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const LXn=e=>!!e.onSelectionChangeHandlers;function FXn({onSelectionChange:e}){const t=Ws(LXn);return e||t?o.jsx(DXn,{onSelectionChange:e}):null}const Wve=typeof window<"u"?g.useLayoutEffect:g.useEffect,GCt=[0,0],zXn={x:0,y:0,zoom:1},BXn=["nodes","edges","defaultNodes","defaultEdges","onConnect","onConnectStart","onConnectEnd","onClickConnectStart","onClickConnectEnd","nodesDraggable","autoPanOnNodeFocus","nodesConnectable","nodesFocusable","edgesFocusable","edgesReconnectable","elevateNodesOnSelect","elevateEdgesOnSelect","minZoom","maxZoom","nodeExtent","onNodesChange","onEdgesChange","elementsSelectable","connectionMode","snapGrid","snapToGrid","translateExtent","connectOnClick","defaultEdgeOptions","fitView","fitViewOptions","onNodesDelete","onEdgesDelete","onDelete","onNodeDrag","onNodeDragStart","onNodeDragStop","onSelectionDrag","onSelectionDragStart","onSelectionDragStop","onMoveStart","onMove","onMoveEnd","noPanClassName","nodeOrigin","autoPanOnConnect","autoPanOnNodeDrag","onError","connectionRadius","isValidConnection","selectNodesOnDrag","nodeDragThreshold","connectionDragThreshold","onBeforeDelete","debug","autoPanSpeed","ariaLabelConfig","zIndexMode"],CBe=[...BXn,"rfId"],UXn=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges}),_Be={translateExtent:HM,nodeOrigin:GCt,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function qXn(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Ws(UXn,oo),u=To();Wve(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=_Be,l()}),[]);const d=g.useRef(_Be);return Wve(()=>{for(const f of CBe){const h=e[f],p=d.current[f];h!==p&&(typeof e[f]>"u"||(f==="nodes"?t(h):f==="edges"?n(h):f==="minZoom"?r(h):f==="maxZoom"?s(h):f==="translateExtent"?a(h):f==="nodeExtent"?i(h):f==="ariaLabelConfig"?u.setState({ariaLabelConfig:AKn(h)}):f==="fitView"?u.setState({fitViewQueued:h}):f==="fitViewOptions"?u.setState({fitViewOptions:h}):u.setState({[f]:h})))}d.current=e},CBe.map(f=>e[f])),null}function EBe(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function VXn(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=EBe(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:EBe()?.matches?"dark":"light"}const TBe=typeof document<"u"?document:null;function YM(e=null,t={target:TBe,actInsideInputWithModifier:!0}){const[n,r]=g.useState(!1),s=g.useRef(!1),a=g.useRef(new Set([])),[i,l]=g.useMemo(()=>{if(e!==null){const u=(Array.isArray(e)?e:[e]).filter(f=>typeof f=="string").map(f=>f.replace("+",`
234
+ `:r=="r"?"\r":r=="t"?" ":"\\")}eq(t){return this.search==t.search&&this.replace==t.replace&&this.caseSensitive==t.caseSensitive&&this.regexp==t.regexp&&this.wholeWord==t.wholeWord&&this.test==t.test}create(){return this.regexp?new VHn(this):new BHn(this)}getCursor(t,n=0,r){let s=t.doc?t:gs.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?aT(this,s,n,r):sT(this,s,n,r)}}class kOt{constructor(t){this.spec=t}}function FHn(e,t,n){return(r,s,a,i)=>{if(n&&!n(r,s,a,i))return!1;let l=r>=i&&s<=i+a.length?a.slice(r-i,s-i):t.doc.sliceString(r,s);return e(l,t,r,s)}}function sT(e,t,n,r){let s;return e.wholeWord&&(s=zHn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=FHn(e.test,t,s)),new Lx(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function zHn(e,t){return(n,r,s,a)=>((a>n||a+s.length<r)&&(a=Math.max(0,n-2),s=e.sliceString(a,Math.min(e.length,r+2))),(t(XB(s,n-a))!=wo.Word||t(JB(s,n-a))!=wo.Word)&&(t(JB(s,r-a))!=wo.Word||t(XB(s,r-a))!=wo.Word))}class BHn extends kOt{constructor(t){super(t)}nextMatch(t,n,r){let s=sT(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=sT(this.spec,t,0,a).nextOverlapping()}return s.done||s.value.from==n&&s.value.to==r?null:s.value}prevMatchInRange(t,n,r){for(let s=r;;){let a=Math.max(n,s-1e4-this.spec.unquoted.length),i=sT(this.spec,t,a,s),l=null;for(;!i.nextOverlapping().done;)l=i.value;if(l)return l;if(a==n)return null;s-=1e4}}prevMatch(t,n,r){let s=this.prevMatchInRange(t,0,n);return s||(s=this.prevMatchInRange(t,Math.max(0,r-this.spec.unquoted.length),t.doc.length)),s&&(s.from!=n||s.to!=r)?s:null}getReplacement(t){return this.spec.unquote(this.spec.replace)}matchAll(t,n){let r=sT(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=sT(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}function UHn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function aT(e,t,n,r){let s;return e.wholeWord&&(s=qHn(t.charCategorizer(t.selection.main.head))),e.test&&(s=UHn(e.test,t,s)),new xOt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function XB(e,t){return e.slice(Ac(e,t,!1),t)}function JB(e,t){return e.slice(t,Ac(e,t))}function qHn(e){return(t,n,r)=>!r[0].length||(e(XB(r.input,r.index))!=wo.Word||e(JB(r.input,r.index))!=wo.Word)&&(e(JB(r.input,r.index+r[0].length))!=wo.Word||e(XB(r.input,r.index+r[0].length))!=wo.Word)}class VHn extends kOt{nextMatch(t,n,r){let s=aT(this.spec,t,r,t.doc.length).next();return s.done&&(s=aT(this.spec,t,0,n).next()),s.done?null:s.value}prevMatchInRange(t,n,r){for(let s=1;;s++){let a=Math.max(n,r-s*1e4),i=aT(this.spec,t,a,r),l=null;for(;!i.next().done;)l=i.value;if(l&&(a==n||l.from>a+10))return l;if(a==n)return null}}prevMatch(t,n,r){return this.prevMatchInRange(t,0,n)||this.prevMatchInRange(t,r,t.doc.length)}getReplacement(t){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(n,r)=>{if(r=="&")return t.match[0];if(r=="$")return"$";for(let s=r.length;s>0;s--){let a=+r.slice(0,s);if(a>0&&a<t.match.length)return t.match[a]+r.slice(s)}return n})}matchAll(t,n){let r=aT(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=aT(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}const LM=vr.define(),_Oe=vr.define(),e1=xl.define({create(e){return new xte(Ive(e).create(),null)},update(e,t){for(let n of t.effects)n.is(LM)?e=new xte(n.value.create(),e.panel):n.is(_Oe)&&(e=new xte(e.query,n.value?EOe:null));return e},provide:e=>TM.from(e,t=>t.panel)});class xte{constructor(t,n){this.query=t,this.panel=n}}const HHn=Nn.mark({class:"cm-searchMatch"}),WHn=Nn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),ZHn=Co.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(e1))}update(e){let t=e.state.field(e1);(t!=e.startState.field(e1)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return Nn.none;let{view:n}=this,r=new Hd;for(let s=0,a=n.visibleRanges,i=a.length;s<i;s++){let{from:l,to:c}=a[s];for(;s<i-1&&c>a[s+1].from-500;)c=a[++s].to;e.highlight(n.state,l,c,(u,d)=>{let f=n.state.selection.ranges.some(h=>h.from==u&&h.to==d);r.add(u,d,f?WHn:HHn)})}return r.finish()}},{decorations:e=>e.decorations});function n4(e){return t=>{let n=t.state.field(e1,!1);return n&&n.query.spec.valid?e(t,n):_Ot(t)}}const eU=n4((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=St.single(r.from,r.to),a=e.state.facet(AI);return e.dispatch({selection:s,effects:[TOe(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),COt(e),!0}),tU=n4((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let a=St.single(s.from,s.to),i=e.state.facet(AI);return e.dispatch({selection:a,effects:[TOe(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),COt(e),!0}),GHn=n4((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:St.create(n.map(r=>St.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),QHn=({state:e,dispatch:t})=>{let n=e.selection;if(n.ranges.length>1||n.main.empty)return!1;let{from:r,to:s}=n.main,a=[],i=0;for(let l=new Lx(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(i=a.length),a.push(St.range(l.value.from,l.value.to))}return t(e.update({selection:St.create(a,i),userEvent:"select.search.matches"})),!0},$9e=n4((e,{query:t})=>{let{state:n}=e,{from:r,to:s}=n.selection.main;if(n.readOnly)return!1;let a=t.nextMatch(n,r,r);if(!a)return!1;let i=a,l=[],c,u,d=[];i.precise?i.from==r&&i.to==s&&(u=n.toText(t.getReplacement(i)),l.push({from:i.from,to:i.to,insert:u}),i=t.nextMatch(n,i.from,i.to),d.push(Pt.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+"."))):i=t.nextMatch(n,i.from,i.to);let f=e.state.changes(l);return i&&(c=St.single(i.from,i.to).map(f),d.push(TOe(e,i)),d.push(n.facet(AI).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),YHn=n4((e,{query:t})=>{if(e.state.readOnly)return!1;let n=[];for(let s of t.matchAll(e.state,1e9)){let{from:a,to:i,precise:l}=s;l&&n.push({from:a,to:i,insert:t.getReplacement(s)})}if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:Pt.announce.of(r),userEvent:"input.replace.all"}),!0});function EOe(e){return e.state.facet(AI).createPanel(e)}function Ive(e,t){var n,r,s,a,i;let l=e.selection.main,c=l.empty||l.to>l.from+100?"":e.sliceDoc(l.from,l.to);if(t&&!c)return t;let u=e.facet(AI);return new SOt({search:((n=t?.literal)!==null&&n!==void 0?n:u.literal)?c:c.replace(/\n/g,"\\n"),caseSensitive:(r=t?.caseSensitive)!==null&&r!==void 0?r:u.caseSensitive,literal:(s=t?.literal)!==null&&s!==void 0?s:u.literal,regexp:(a=t?.regexp)!==null&&a!==void 0?a:u.regexp,wholeWord:(i=t?.wholeWord)!==null&&i!==void 0?i:u.wholeWord})}function OOt(e){let t=qke(e,EOe);return t&&t.dom.querySelector("[main-field]")}function COt(e){let t=OOt(e);t&&t==e.root.activeElement&&t.select()}const _Ot=e=>{let t=e.state.field(e1,!1);if(t&&t.panel){let n=OOt(e);if(n&&n!=e.root.activeElement){let r=Ive(e.state,t.query.spec);r.valid&&e.dispatch({effects:LM.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[_Oe.of(!0),t?LM.of(Ive(e.state,t.query.spec)):vr.appendConfig.of(eWn)]});return!0},EOt=e=>{let t=e.state.field(e1,!1);if(!t||!t.panel)return!1;let n=qke(e,EOe);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:_Oe.of(!1)}),!0},KHn=[{key:"Mod-f",run:_Ot,scope:"editor search-panel"},{key:"F3",run:eU,shift:tU,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:eU,shift:tU,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:EOt,scope:"editor search-panel"},{key:"Mod-Shift-l",run:QHn},{key:"Mod-Alt-g",run:EHn},{key:"Mod-d",run:LHn,preventDefault:!0}];class XHn{constructor(t){this.view=t;let n=this.query=t.state.field(e1).query.spec;this.commit=this.commit.bind(this),this.searchField=mi("input",{value:n.search,placeholder:fh(t,"Find"),"aria-label":fh(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=mi("input",{value:n.replace,placeholder:fh(t,"Replace"),"aria-label":fh(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=mi("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=mi("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=mi("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return mi("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=mi("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>eU(t),[fh(t,"next")]),r("prev",()=>tU(t),[fh(t,"previous")]),r("select",()=>GHn(t),[fh(t,"all")]),mi("label",null,[this.caseField,fh(t,"match case")]),mi("label",null,[this.reField,fh(t,"regexp")]),mi("label",null,[this.wordField,fh(t,"by word")]),...t.state.readOnly?[]:[mi("br"),this.replaceField,r("replace",()=>$9e(t),[fh(t,"replace")]),r("replaceAll",()=>YHn(t),[fh(t,"replace all")])],mi("button",{name:"close",onclick:()=>EOt(t),"aria-label":fh(t,"close"),type:"button"},["×"])])}commit(){let t=new SOt({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});t.eq(this.query)||(this.query=t,this.view.dispatch({effects:LM.of(t)}))}keydown(t){y8n(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?tU:eU)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),$9e(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(LM)&&!r.value.eq(this.query)&&this.setQuery(r.value)}setQuery(t){this.query=t,this.searchField.value=t.search,this.replaceField.value=t.replace,this.caseField.checked=t.caseSensitive,this.reField.checked=t.regexp,this.wordField.checked=t.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(AI).top}}function fh(e,t){return e.state.phrase(t)}const kF=30,OF=/[\s\.,:;?!]/;function TOe(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),s=e.state.doc.lineAt(n).to,a=Math.max(r.from,t-kF),i=Math.min(s,n+kF),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<kF;c++)if(!OF.test(l[c+1])&&OF.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-kF;c--)if(!OF.test(l[c-1])&&OF.test(l[c])){l=l.slice(0,c);break}}return Pt.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const JHn=Pt.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),eWn=[e1,ip.low(ZHn),JHn];class M9e{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class $k{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(FM).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new Hd,l=[],c=0;for(let d=0;;){let f=d==a.length?null:a[d];if(!f&&!l.length)break;let h,p;for(l.length?(h=c,p=l.reduce((v,y)=>Math.min(v,y.to),f&&f.from>h?f.from:1e8)):(h=f.from,p=f.to,l.push(f),d++);d<a.length;){let v=a[d];if(v.from==h&&(v.to>v.from||v.to==h))l.push(v),d++,p=Math.min(v.to,p);else{p=Math.min(v.from,p);break}}let m=hWn(l);if(l.some(v=>v.from==v.to||v.from==v.to-1&&r.doc.lineAt(v.from).to==v.from))i.add(h,h,Nn.widget({widget:new cWn(m),diagnostics:l.slice()}));else{let v=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(h,p,Nn.mark({class:"cm-lintRange cm-lintRange-"+m+v,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>p)}))}c=p;for(let v=0;v<l.length;v++)l[v].to<=c&&l.splice(v--,1)}let u=i.finish();return new $k(u,n,iN(u))}}function iN(e,t=null,n=0){let r=null;return e.between(n,1e9,(s,a,{spec:i})=>{if(!(t&&i.diagnostics.indexOf(t)<0))if(!r)r=new M9e(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new M9e(r.from,a,r.diagnostic)}}),r}function tWn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(FM).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(TOt))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function nWn(e,t){return e.field(Ah,!1)?t:t.concat(vr.appendConfig.of(pWn))}const TOt=vr.define(),jOe=vr.define(),jOt=vr.define(),Ah=xl.define({create(){return new $k(Nn.none,null,null)},update(e,t){if(t.docChanged&&e.diagnostics.size){let n=e.diagnostics.map(t.changes),r=null,s=e.panel;if(e.selected){let a=t.changes.mapPos(e.selected.from,1);r=iN(n,e.selected.diagnostic,a)||iN(n,null,a)}!n.size&&s&&t.state.facet(FM).autoPanel&&(s=null),e=new $k(n,s,r)}for(let n of t.effects)if(n.is(TOt)){let r=t.state.facet(FM).autoPanel?n.value.length?zM.open:null:e.panel;e=$k.init(n.value,r,t.state)}else n.is(jOe)?e=new $k(e.diagnostics,n.value?zM.open:null,e.selected):n.is(jOt)&&(e=new $k(e.diagnostics,e.panel,n.value));return e},provide:e=>[TM.from(e,t=>t.panel),Pt.decorations.from(e,t=>t.diagnostics)]}),rWn=Nn.mark({class:"cm-lintRange cm-lintRange-active"});function sWn(e,t,n){let{diagnostics:r}=e.state.field(Ah),s,a=-1,i=-1;r.between(t-(n<0?1:0),t+(n>0?1:0),(c,u,{spec:d})=>{if(t>=c&&t<=u&&(c==u||(t>c||n>0)&&(t<u||n<0)))return s=d.diagnostics,a=c,i=u,!1});let l=e.state.facet(FM).tooltipFilter;return s&&l&&(s=l(s,e.state)),s?{pos:a,end:i,above:e.state.doc.lineAt(a).to<i,create(){return{dom:aWn(e,s)}}}:null}function aWn(e,t){return mi("ul",{class:"cm-tooltip-lint"},t.map(n=>IOt(e,n,!1)))}const iWn=e=>{let t=e.state.field(Ah,!1);(!t||!t.panel)&&e.dispatch({effects:nWn(e.state,[jOe.of(!0)])});let n=qke(e,zM.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},D9e=e=>{let t=e.state.field(Ah,!1);return!t||!t.panel?!1:(e.dispatch({effects:jOe.of(!1)}),!0)},oWn=e=>{let t=e.state.field(Ah,!1);if(!t)return!1;let n=e.state.selection.main,r=t.diagnostics.iter(n.to+1);return!r.value&&(r=t.diagnostics.iter(0),!r.value||r.from==n.from&&r.to==n.to)?!1:(e.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0}),!0)},lWn=[{key:"Mod-Shift-m",run:iWn,preventDefault:!0},{key:"F8",run:oWn}],FM=kn.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...Hy(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:L9e,tooltipFilter:L9e,needsRefresh:(t,n)=>t?n?r=>t(r)||n(r):t:n,hideOn:(t,n)=>t?n?(r,s,a)=>t(r,s,a)||n(r,s,a):t:n,autoPanel:(t,n)=>t||n})}}});function L9e(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function NOt(e){let t=[];if(e)e:for(let{name:n}of e){for(let r=0;r<n.length;r++){let s=n[r];if(/[a-zA-Z]/.test(s)&&!t.some(a=>a.toLowerCase()==s.toLowerCase())){t.push(s);continue e}}t.push("")}return t}function IOt(e,t,n){var r;let s=n?NOt(t.actions):[];return mi("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},mi("span",{class:"cm-diagnosticText"},t.renderMessage?t.renderMessage(e):t.message),(r=t.actions)===null||r===void 0?void 0:r.map((a,i)=>{let l=!1,c=p=>{if(p.preventDefault(),l)return;l=!0;let m=iN(e.state.field(Ah).diagnostics,t);m&&a.apply(e,m.from,m.to)},{name:u}=a,d=s[i]?u.indexOf(s[i]):-1,f=d<0?u:[u.slice(0,d),mi("u",u.slice(d,d+1)),u.slice(d+1)],h=a.markClass?" "+a.markClass:"";return mi("button",{type:"button",class:"cm-diagnosticAction"+h,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&mi("div",{class:"cm-diagnosticSource"},t.source))}class cWn extends op{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return mi("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class F9e{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=IOt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class zM{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)D9e(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:a}=this.items[this.selectedIndex],i=NOt(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=iN(this.view.state.field(Ah).diagnostics,a);c&&a.actions[l].apply(t,c.from,c.to)}}else return;s.preventDefault()},r=s=>{for(let a=0;a<this.items.length;a++)this.items[a].dom.contains(s.target)&&this.moveSelection(a)};this.list=mi("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=mi("div",{class:"cm-panel-lint"},this.list,mi("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>D9e(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Ah).selected;if(!t)return-1;for(let n=0;n<this.items.length;n++)if(this.items[n].diagnostic==t.diagnostic)return n;return-1}update(){let{diagnostics:t,selected:n}=this.view.state.field(Ah),r=0,s=!1,a=null,i=new Set;for(t.between(0,this.view.state.doc.length,(l,c,{spec:u})=>{for(let d of u.diagnostics){if(i.has(d))continue;i.add(d);let f=-1,h;for(let p=r;p<this.items.length;p++)if(this.items[p].diagnostic==d){f=p;break}f<0?(h=new F9e(this.view,d),this.items.splice(r,0,h),s=!0):(h=this.items[f],f>r&&(this.items.splice(r,f-r),s=!0)),n&&h.diagnostic==n.diagnostic?h.dom.hasAttribute("aria-selected")||(h.dom.setAttribute("aria-selected","true"),a=h):h.dom.hasAttribute("aria-selected")&&h.dom.removeAttribute("aria-selected"),r++}});r<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0);)s=!0,this.items.pop();this.items.length==0&&(this.items.push(new F9e(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),s=!0),a?(this.list.setAttribute("aria-activedescendant",a.id),this.view.requestMeasure({key:this,read:()=>({sel:a.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:l,panel:c})=>{let u=c.height/this.list.offsetHeight;l.top<c.top?this.list.scrollTop-=(c.top-l.top)/u:l.bottom>c.bottom&&(this.list.scrollTop+=(l.bottom-c.bottom)/u)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let t=this.list.firstChild;function n(){let r=t;t=r.nextSibling,r.remove()}for(let r of this.items)if(r.dom.parentNode==this.list){for(;t!=r.dom;)n();t=r.dom.nextSibling}else this.list.insertBefore(r.dom,t);for(;t;)n()}moveSelection(t){if(this.selectedIndex<0)return;let n=this.view.state.field(Ah),r=iN(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:jOt.of(r)})}static open(t){return new zM(t)}}function uWn(e,t='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${t}>${encodeURIComponent(e)}</svg>')`}function CF(e){return uWn(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${e}" fill="none" stroke-width=".7"/>`,'width="6" height="3"')}const dWn=Pt.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:CF("#d11")},".cm-lintRange-warning":{backgroundImage:CF("orange")},".cm-lintRange-info":{backgroundImage:CF("#999")},".cm-lintRange-hint":{backgroundImage:CF("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}});function fWn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function hWn(e){let t="hint",n=1;for(let r of e){let s=fWn(r.severity);s>n&&(n=s,t=r.severity)}return t}const pWn=[Ah,Pt.decorations.compute([Ah],e=>{let{selected:t,panel:n}=e.field(Ah);return!t||!n||t.from==t.to?Nn.none:Nn.set([rWn.range(t.from,t.to)])}),i9n(sWn,{hideOn:tWn}),dWn];var z9e=function(t){t===void 0&&(t={});var n=t,r=n.crosshairCursor,s=r===void 0?!1:r,a=[];t.closeBracketsKeymap!==!1&&(a=a.concat(rBn)),t.defaultKeymap!==!1&&(a=a.concat(OHn)),t.searchKeymap!==!1&&(a=a.concat(KHn)),t.historyKeymap!==!1&&(a=a.concat(IVn)),t.foldKeymap!==!1&&(a=a.concat(U9n)),t.completionKeymap!==!1&&(a=a.concat(CSt)),t.lintKeymap!==!1&&(a=a.concat(lWn));var i=[];return t.lineNumbers!==!1&&i.push(y9n()),t.highlightActiveLineGutter!==!1&&i.push(w9n()),t.highlightSpecialChars!==!1&&i.push(P8n()),t.history!==!1&&i.push(SVn()),t.foldGutter!==!1&&i.push(W9n()),t.drawSelection!==!1&&i.push(O8n()),t.dropCursor!==!1&&i.push(j8n()),t.allowMultipleSelections!==!1&&i.push(gs.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(P9n()),t.syntaxHighlighting!==!1&&i.push(fS(Y9n,{fallback:!0})),t.bracketMatching!==!1&&i.push(r7n()),t.closeBrackets!==!1&&i.push(J7n()),t.autocompletion!==!1&&i.push(OSt()),t.rectangularSelection!==!1&&i.push(G8n()),s!==!1&&i.push(K8n()),t.highlightActiveLine!==!1&&i.push(z8n()),t.highlightSelectionMatches!==!1&&i.push(NHn()),t.tabSize&&typeof t.tabSize=="number"&&i.push(TI.of(" ".repeat(t.tabSize))),i.concat([EI.of(a.flat())]).filter(Boolean)};const mWn="#e5c07b",B9e="#e06c75",gWn="#56b6c2",vWn="#ffffff",t9="#abb2bf",Ave="#7d8799",yWn="#61afef",bWn="#98c379",U9e="#d19a66",xWn="#c678dd",wWn="#21252b",q9e="#2c313a",V9e="#282c34",wte="#353a42",SWn="#3E4451",H9e="#528bff",kWn=Pt.theme({"&":{color:t9,backgroundColor:V9e},".cm-content":{caretColor:H9e},".cm-cursor, .cm-dropCursor":{borderLeftColor:H9e},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:SWn},".cm-panels":{backgroundColor:wWn,color:t9},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:"1px solid #457dff"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:"#6199ff2f"},".cm-activeLine":{backgroundColor:"#6699ff0b"},".cm-selectionMatch":{backgroundColor:"#aafe661a"},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bad0f847"},".cm-gutters":{backgroundColor:V9e,color:Ave,border:"none"},".cm-activeLineGutter":{backgroundColor:q9e},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:wte},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:wte,borderBottomColor:wte},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:q9e,color:t9}}},{dark:!0}),OWn=Jg.define([{tag:ue.keyword,color:xWn},{tag:[ue.name,ue.deleted,ue.character,ue.propertyName,ue.macroName],color:B9e},{tag:[ue.function(ue.variableName),ue.labelName],color:yWn},{tag:[ue.color,ue.constant(ue.name),ue.standard(ue.name)],color:U9e},{tag:[ue.definition(ue.name),ue.separator],color:t9},{tag:[ue.typeName,ue.className,ue.number,ue.changed,ue.annotation,ue.modifier,ue.self,ue.namespace],color:mWn},{tag:[ue.operator,ue.operatorKeyword,ue.url,ue.escape,ue.regexp,ue.link,ue.special(ue.string)],color:gWn},{tag:[ue.meta,ue.comment],color:Ave},{tag:ue.strong,fontWeight:"bold"},{tag:ue.emphasis,fontStyle:"italic"},{tag:ue.strikethrough,textDecoration:"line-through"},{tag:ue.link,color:Ave,textDecoration:"underline"},{tag:ue.heading,fontWeight:"bold",color:B9e},{tag:[ue.atom,ue.bool,ue.special(ue.variableName)],color:U9e},{tag:[ue.processingInstruction,ue.string,ue.inserted],color:bWn},{tag:ue.invalid,color:vWn}]),CWn=[kWn,fS(OWn)];var _Wn=Pt.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),EWn=function(t){t===void 0&&(t={});var n=t,r=n.indentWithTab,s=r===void 0?!0:r,a=n.editable,i=a===void 0?!0:a,l=n.readOnly,c=l===void 0?!1:l,u=n.theme,d=u===void 0?"light":u,f=n.placeholder,h=f===void 0?"":f,p=n.basicSetup,m=p===void 0?!0:p,v=[];switch(s&&v.unshift(EI.of([CHn])),m&&(typeof m=="boolean"?v.unshift(z9e()):v.unshift(z9e(m))),h&&v.unshift(V8n(h)),d){case"light":v.push(_Wn);break;case"dark":v.push(CWn);break;case"none":break;default:v.push(d);break}return i===!1&&v.push(Pt.editable.of(!1)),c&&v.push(gs.readOnly.of(!0)),[...v]},TWn=e=>({line:e.state.doc.lineAt(e.state.selection.main.from),lineCount:e.state.doc.lines,lineBreak:e.state.lineBreak,length:e.state.doc.length,readOnly:e.state.readOnly,tabSize:e.state.tabSize,selection:e.state.selection,selectionAsSingle:e.state.selection.asSingle().main,ranges:e.state.selection.ranges,selectionCode:e.state.sliceDoc(e.state.selection.main.from,e.state.selection.main.to),selections:e.state.selection.ranges.map(t=>e.state.sliceDoc(t.from,t.to)),selectedText:e.state.selection.ranges.some(t=>!t.empty)});class jWn{constructor(t,n){this.timeLeftMS=void 0,this.timeoutMS=void 0,this.isCancelled=!1,this.isTimeExhausted=!1,this.callbacks=[],this.timeLeftMS=n,this.timeoutMS=n,this.callbacks.push(t)}tick(){if(!this.isCancelled&&!this.isTimeExhausted&&(this.timeLeftMS--,this.timeLeftMS<=0)){this.isTimeExhausted=!0;var t=this.callbacks.slice();this.callbacks.length=0,t.forEach(n=>{try{n()}catch(r){console.error("TimeoutLatch callback error:",r)}})}}cancel(){this.isCancelled=!0,this.callbacks.length=0}reset(){this.timeLeftMS=this.timeoutMS,this.isCancelled=!1,this.isTimeExhausted=!1}get isDone(){return this.isCancelled||this.isTimeExhausted}}class W9e{constructor(){this.interval=null,this.latches=new Set}add(t){this.latches.add(t),this.start()}remove(t){this.latches.delete(t),this.latches.size===0&&this.stop()}start(){this.interval===null&&(this.interval=setInterval(()=>{this.latches.forEach(t=>{t.tick(),t.isDone&&this.remove(t)})},1))}stop(){this.interval!==null&&(clearInterval(this.interval),this.interval=null)}}var Ste=null,NWn=()=>typeof window>"u"?new W9e:(Ste||(Ste=new W9e),Ste),IWn=Pt.theme({"& .cm-scroller":{height:"100% !important"}}),Z9e=null,kte=null;function AWn(e,t,n,r,s,a){if(!e&&!t&&!n&&!r&&!s&&!a)return null;var i=JSON.stringify({height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a});return i===Z9e||(Z9e=i,kte=Pt.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a}})),kte}var G9e=Vy.define(),RWn=200,PWn=[];function $Wn(e){var t=e.value,n=e.selection,r=e.onChange,s=e.onStatistics,a=e.onCreateEditor,i=e.onUpdate,l=e.extensions,c=l===void 0?PWn:l,u=e.autoFocus,d=e.theme,f=d===void 0?"light":d,h=e.height,p=h===void 0?null:h,m=e.minHeight,v=m===void 0?null:m,y=e.maxHeight,b=y===void 0?null:y,x=e.width,w=x===void 0?null:x,k=e.minWidth,C=k===void 0?null:k,_=e.maxWidth,T=_===void 0?null:_,E=e.placeholder,N=E===void 0?"":E,I=e.editable,A=I===void 0?!0:I,P=e.readOnly,L=P===void 0?!1:P,D=e.indentWithTab,B=D===void 0?!0:D,H=e.basicSetup,q=H===void 0?!0:H,z=e.root,V=e.initialState,M=g.useState(),G=M[0],F=M[1],R=g.useState(),U=R[0],Z=R[1],Y=g.useState(),te=Y[0],J=Y[1],ee=g.useState(()=>({current:null}))[0],re=g.useState(()=>({current:null}))[0],ae=AWn(p,v,b,w,C,T),X=Pt.updateListener.of(ce=>{if(ce.docChanged&&typeof r=="function"&&!ce.transactions.some(he=>he.annotation(G9e))){ee.current?ee.current.reset():(ee.current=new jWn(()=>{if(re.current){var he=re.current;re.current=null,he()}ee.current=null},RWn),NWn().add(ee.current));var le=ce.state.doc,be=le.toString();r(be,ce)}s&&s(TWn(ce))}),ne=EWn({theme:f,editable:A,readOnly:L,placeholder:N,indentWithTab:B,basicSetup:q}),se=[X,...ae?[ae]:[],IWn,...ne];return i&&typeof i=="function"&&se.push(Pt.updateListener.of(i)),se=se.concat(c),g.useLayoutEffect(()=>{if(G&&!te){var ce={doc:t,selection:n,extensions:se},le=V?gs.fromJSON(V.json,ce,V.fields):gs.create(ce);if(J(le),!U){var be=new Pt({state:le,parent:G,root:z});Z(be),a&&a(be,le)}}return()=>{U&&(J(void 0),Z(void 0))}},[G,te]),g.useEffect(()=>{e.container&&F(e.container)},[e.container]),g.useEffect(()=>()=>{U&&(U.destroy(),Z(void 0)),ee.current&&(ee.current.cancel(),ee.current=null)},[U]),g.useEffect(()=>{u&&U&&U.focus()},[u,U]),g.useEffect(()=>{U&&U.dispatch({effects:vr.reconfigure.of(se)})},[f,c,p,v,b,w,C,T,N,A,L,B,q,r,i]),g.useEffect(()=>{if(t!==void 0){var ce=U?U.state.doc.toString():"";if(U&&t!==ce){var le=ee.current&&!ee.current.isDone,be=()=>{U&&t!==U.state.doc.toString()&&U.dispatch({changes:{from:0,to:U.state.doc.toString().length,insert:t||""},annotations:[G9e.of(!0)]})};le?re.current=be:be()}}},[t,U]),{state:te,setState:J,view:U,setView:Z,container:G,setContainer:F}}var MWn=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],rd=g.forwardRef((e,t)=>{var n=e.className,r=e.value,s=r===void 0?"":r,a=e.selection,i=e.extensions,l=i===void 0?[]:i,c=e.onChange,u=e.onStatistics,d=e.onCreateEditor,f=e.onUpdate,h=e.autoFocus,p=e.theme,m=p===void 0?"light":p,v=e.height,y=e.minHeight,b=e.maxHeight,x=e.width,w=e.minWidth,k=e.maxWidth,C=e.basicSetup,_=e.placeholder,T=e.indentWithTab,E=e.editable,N=e.readOnly,I=e.root,A=e.initialState,P=Fkt(e,MWn),L=g.useRef(null),D=$Wn({root:I,value:s,autoFocus:h,theme:m,height:v,minHeight:y,maxHeight:b,width:x,minWidth:w,maxWidth:k,basicSetup:C,placeholder:_,indentWithTab:T,editable:E,readOnly:N,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),B=D.state,H=D.view,q=D.container,z=D.setContainer;g.useImperativeHandle(t,()=>({editor:L.current,state:B,view:H}),[L,q,B,H]);var V=g.useCallback(G=>{L.current=G,z(G)},[z]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var M=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",sC({ref:V,className:""+M+(n?" "+n:"")},P))});rd.displayName="CodeMirror";const DWn={js:"javascript",javascript:"javascript",mjs:"javascript",cjs:"javascript",node:"javascript",ts:"typescript",typescript:"typescript",mts:"typescript",cts:"typescript",tsx:"tsx",jsx:"jsx",json:"json",json5:"json",md:"markdown",markdown:"markdown",py:"python",python:"python",sh:"bash",bash:"bash",shell:"bash",zsh:"bash",yml:"yaml",yaml:"yaml",diff:"diff",patch:"diff",css:"css",scss:"css",html:"html",htm:"html",xml:"xml",svg:"xml",sql:"sql"};let Ote=null;function LWn(){return Ote||(Ote=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Va(()=>import("./core-op51HA-s.js"),__vite__mapDeps([0,1,2]),import.meta.url),Va(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[Va(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Va(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Va(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Va(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Va(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Va(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Va(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Va(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Va(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Va(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Va(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Va(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Va(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Va(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([4,5,6]),import.meta.url),Va(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Va(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),Ote}async function FWn(e,t){const n=DWn[t?.toLowerCase()];if(!n)return null;const r=await LWn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function zWn(e){return new eC(Gke.define(e))}const AOt=[gg.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return Va(()=>Promise.resolve().then(()=>wF),void 0,import.meta.url).then(e=>e.javascript())}}),gg.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return Va(()=>Promise.resolve().then(()=>m7n),void 0,import.meta.url).then(e=>e.json())}}),gg.of({name:"JSX",extensions:["jsx"],load(){return Va(()=>Promise.resolve().then(()=>wF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),gg.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return Va(()=>Promise.resolve().then(()=>cVn),void 0,import.meta.url).then(e=>e.markdown())}}),gg.of({name:"TSX",extensions:["tsx"],load(){return Va(()=>Promise.resolve().then(()=>wF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),gg.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return Va(()=>Promise.resolve().then(()=>wF),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),gg.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return Va(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>zWn(e.shell))}})];function BWn(e,t=5){if(!e?.properties)return[];const n=[];function r(s,a,i){if(i>t)return;const l=Array.isArray(s.type)?s.type.join(" | "):s.type;if(n.push({path:a,label:a,description:s.description??s.title,type:l}),s.properties)for(const[c,u]of Object.entries(s.properties))r(u,`${a}.${c}`,i+1);if(s.items?.properties)for(const[c,u]of Object.entries(s.items.properties))r(u,`${a}[].${c}`,i+1)}for(const[s,a]of Object.entries(e.properties))r(a,s,1);return n}function UWn(e){const t=BWn(e);return OSt({override:[qWn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function qWn(e){return t=>{const r=t.state.sliceDoc(Math.max(0,t.pos-50),t.pos).match(/\{\{([a-zA-Z0-9_.\[\]]*)?$/);if(!r)return null;const s=r[1]??"",a=t.pos-s.length,i=s?e.filter(c=>c.path.toLowerCase().startsWith(s.toLowerCase())):e;if(i.length===0)return null;const l=i.map(c=>({label:c.path,displayLabel:c.path,detail:c.type,info:c.description,apply:(u,d,f,h)=>{const v=u.state.sliceDoc(h,h+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:h,insert:v},selection:{anchor:f+v.length}})}}));return{from:a,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const VWn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,HWn=Nn.mark({class:"cm-variable-highlight"}),Q9e=new L1t({regexp:VWn,decoration:()=>HWn}),WWn=Co.fromClass(class{decorations;constructor(e){this.decorations=Q9e.createDeco(e)}update(e){this.decorations=Q9e.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),ZWn=WWn;function GWn(){const e=NI({settings:{fontFamily:"var(--font-mono)",fontSize:"0.8rem",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"var(--neutral2)",background:"transparent",foreground:"var(--neutral6)",caret:"var(--neutral6)"},styles:[{tag:[ue.className,ue.propertyName],color:"var(--neutral6)"},{tag:ue.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[ue.heading1,ue.heading2,ue.heading3,ue.heading4,ue.heading5,ue.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:ue.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:ue.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:ue.link,color:"var(--accent3)",textDecoration:"underline"},{tag:ue.url,color:"var(--accent3)"},{tag:ue.monospace,color:"var(--neutral6)"},{tag:ue.strikethrough,textDecoration:"line-through"},{tag:ue.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=Pt.theme({".cm-editor":{backgroundColor:"transparent"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{color:"var(--neutral3)"},".cm-cursor":{borderLeftColor:"var(--neutral6)"},".cm-selectionBackground, .cm-content ::selection":{backgroundColor:"color-mix(in srgb, var(--accent3) 22%, transparent)"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}});return[e,t]}function QWn(){const e=Pt.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"0.8rem"},"&.cm-editor .cm-scroller":{fontFamily:"var(--font-mono)"},".cm-gutters":{backgroundColor:"transparent",color:"var(--neutral2)",borderRight:"none"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-activeLine":{backgroundColor:"transparent"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{backgroundColor:"transparent",color:"var(--neutral3)"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"var(--neutral6)"},"&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection":{background:"color-mix(in srgb, var(--accent3) 22%, transparent) !important"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}}),t=Jg.define([{tag:[ue.comment,ue.bracket],color:"var(--neutral2)"},{tag:[ue.string,ue.meta,ue.regexp],color:"var(--accent1)"},{tag:[ue.atom,ue.bool,ue.special(ue.variableName)],color:"var(--accent6)"},{tag:[ue.keyword,ue.operator,ue.tagName],color:"var(--accent2)"},{tag:[ue.function(ue.propertyName),ue.propertyName],color:"var(--accent5)"},{tag:[ue.definition(ue.variableName),ue.function(ue.variableName),ue.className,ue.attributeName],color:"var(--accent3)"},{tag:[ue.variableName,ue.number],color:"var(--accent5)"},{tag:[ue.name,ue.quote],color:"var(--accent1)"},{tag:ue.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[ue.heading1,ue.heading2,ue.heading3,ue.heading4,ue.heading5,ue.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[ue.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[ue.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:ue.link,color:"var(--accent3)",textDecoration:"underline"},{tag:ue.url,color:"var(--accent3)"},{tag:ue.monospace,color:"var(--neutral6)"},{tag:ue.strikethrough,textDecoration:"line-through"},{tag:[ue.deleted],color:"var(--accent2)"},{tag:ue.invalid,color:"var(--error)"},{tag:[ue.standard(ue.tagName)],color:"var(--accent1)"}]);return[e,fS(t)]}const o0=()=>{const e=a_().resolvedTheme==="dark";return g.useMemo(()=>e?GWn():QWn(),[e])},YWn=uo(K("relative overflow-hidden font-mono outline-hidden focus-within:outline-hidden focus:outline-hidden","duration-normal transition-colors ease-out-custom"),{variants:{variant:{default:"rounded-md border border-border1 bg-surface3 p-1 focus-within:border-neutral6/20",embedded:"rounded-none border-none bg-transparent p-0"}},defaultVariants:{variant:"default"}}),KWn=ip.highest(Pt.editorAttributes.of({style:"outline: none"})),XWn=ip.highest(Pt.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),JWn=[KWn,XWn],Gr=g.forwardRef(({data:e,value:t,onChange:n,showCopyButton:r=!0,className:s,language:a="json",highlightVariables:i=!1,placeholder:l,schema:c,autoFocus:u,lineNumbers:d=!0,lineWrapping:f=!0,editable:h,variant:p,...m},v)=>{const y=o0(),b=e?JSON.stringify(e,null,2):t??"",x=g.useMemo(()=>{const w=[...JWn];return f&&w.push(Pt.lineWrapping),a==="json"?w.push(zh):a==="markdown"&&w.push(wOe({base:rC,codeLanguages:AOt})),i&&a==="markdown"&&w.push(ZWn),c&&a==="markdown"&&w.push(UWn(c)),h===!1&&w.push(gs.readOnly.of(!0)),w},[a,i,c,h,f]);return o.jsxs("div",{className:K(YWn({variant:p}),s),...m,children:[r&&o.jsx(_a,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(rd,{ref:v,value:b,theme:y,extensions:x,onChange:n,editable:h,"aria-label":"Code editor",placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),eZn=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},tZn=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=o0(),{settings:r,setSettings:s}=VH(),a=r?.tracingOptions,i=g.useMemo(()=>eZn(a),[a]),[l,c]=g.useState(()=>i),u=g.useRef(!1);g.useEffect(()=>{u.current||c(i)},[i]);const d=h=>{u.current=!0,c(h)},f=()=>{if(!l){s({...r,tracingOptions:void 0}),t?.();return}try{const h=JSON.parse(l);typeof h=="object"&&h!==null&&s({...r,tracingOptions:h})}catch{return}t?.()};return o.jsxs("div",{className:"space-y-2 px-5 py-2",children:[o.jsx(ve,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),o.jsx(rd,{value:l,onChange:d,theme:n,extensions:[zh],className:K("overflow-y-scroll bg-surface3 rounded-lg overflow-hidden p-3",e)}),o.jsx("div",{className:"flex items-center justify-end",children:o.jsx(ie,{type:"button",onClick:f,children:"Save"})})]})},nZn=()=>{const[e,t]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx(ie,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(Qe,{children:o.jsx(D0e,{})})})}),o.jsx(yn,{children:"Run Options"})]}),o.jsx(pr,{open:e,onOpenChange:t,children:o.jsxs(mr,{children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Run Options"}),o.jsx(Cs,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx(jr,{children:o.jsx(tZn,{onSaved:()=>t(!1)})})]})})]})};function rZn({status:e}){switch(e){case"running":return o.jsx(Vt,{});case"failed":return o.jsx(or,{className:"text-accent2"});case"canceled":return o.jsx(Mc,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(c1,{className:"text-neutral3"});case"suspended":return o.jsx(EV,{className:"text-accent3"});case"success":return o.jsx(Ur,{className:"text-accent1"});default:return o.jsx(c1,{className:"text-neutral3"})}}function ROt({status:e}){return o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx(Qe,{"aria-label":e,className:"shrink-0",children:o.jsx(rZn,{status:e})})}),o.jsx(yn,{children:e})]})}var Cte,Y9e;function NOe(){if(Y9e)return Cte;Y9e=1;var e="\0",t="\0",n="";class r{_isDirected=!0;_isMultigraph=!1;_isCompound=!1;_label;_defaultNodeLabelFn=()=>{};_defaultEdgeLabelFn=()=>{};_nodes={};_in={};_preds={};_out={};_sucs={};_edgeObjs={};_edgeLabels={};_nodeCount=0;_edgeCount=0;_parent;_children;constructor(d){d&&(this._isDirected=Object.hasOwn(d,"directed")?d.directed:!0,this._isMultigraph=Object.hasOwn(d,"multigraph")?d.multigraph:!1,this._isCompound=Object.hasOwn(d,"compound")?d.compound:!1),this._isCompound&&(this._parent={},this._children={},this._children[t]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(d){return this._label=d,this}graph(){return this._label}setDefaultNodeLabel(d){return this._defaultNodeLabelFn=d,typeof d!="function"&&(this._defaultNodeLabelFn=()=>d),this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){var d=this;return this.nodes().filter(f=>Object.keys(d._in[f]).length===0)}sinks(){var d=this;return this.nodes().filter(f=>Object.keys(d._out[f]).length===0)}setNodes(d,f){var h=arguments,p=this;return d.forEach(function(m){h.length>1?p.setNode(m,f):p.setNode(m)}),this}setNode(d,f){return Object.hasOwn(this._nodes,d)?(arguments.length>1&&(this._nodes[d]=f),this):(this._nodes[d]=arguments.length>1?f:this._defaultNodeLabelFn(d),this._isCompound&&(this._parent[d]=t,this._children[d]={},this._children[t][d]=!0),this._in[d]={},this._preds[d]={},this._out[d]={},this._sucs[d]={},++this._nodeCount,this)}node(d){return this._nodes[d]}hasNode(d){return Object.hasOwn(this._nodes,d)}removeNode(d){var f=this;if(Object.hasOwn(this._nodes,d)){var h=p=>f.removeEdge(f._edgeObjs[p]);delete this._nodes[d],this._isCompound&&(this._removeFromParentsChildList(d),delete this._parent[d],this.children(d).forEach(function(p){f.setParent(p)}),delete this._children[d]),Object.keys(this._in[d]).forEach(h),delete this._in[d],delete this._preds[d],Object.keys(this._out[d]).forEach(h),delete this._out[d],delete this._sucs[d],--this._nodeCount}return this}setParent(d,f){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(f===void 0)f=t;else{f+="";for(var h=f;h!==void 0;h=this.parent(h))if(h===d)throw new Error("Setting "+f+" as parent of "+d+" would create a cycle");this.setNode(f)}return this.setNode(d),this._removeFromParentsChildList(d),this._parent[d]=f,this._children[f][d]=!0,this}_removeFromParentsChildList(d){delete this._children[this._parent[d]][d]}parent(d){if(this._isCompound){var f=this._parent[d];if(f!==t)return f}}children(d=t){if(this._isCompound){var f=this._children[d];if(f)return Object.keys(f)}else{if(d===t)return this.nodes();if(this.hasNode(d))return[]}}predecessors(d){var f=this._preds[d];if(f)return Object.keys(f)}successors(d){var f=this._sucs[d];if(f)return Object.keys(f)}neighbors(d){var f=this.predecessors(d);if(f){const p=new Set(f);for(var h of this.successors(d))p.add(h);return Array.from(p.values())}}isLeaf(d){var f;return this.isDirected()?f=this.successors(d):f=this.neighbors(d),f.length===0}filterNodes(d){var f=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});f.setGraph(this.graph());var h=this;Object.entries(this._nodes).forEach(function([v,y]){d(v)&&f.setNode(v,y)}),Object.values(this._edgeObjs).forEach(function(v){f.hasNode(v.v)&&f.hasNode(v.w)&&f.setEdge(v,h.edge(v))});var p={};function m(v){var y=h.parent(v);return y===void 0||f.hasNode(y)?(p[v]=y,y):y in p?p[y]:m(y)}return this._isCompound&&f.nodes().forEach(v=>f.setParent(v,m(v))),f}setDefaultEdgeLabel(d){return this._defaultEdgeLabelFn=d,typeof d!="function"&&(this._defaultEdgeLabelFn=()=>d),this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(d,f){var h=this,p=arguments;return d.reduce(function(m,v){return p.length>1?h.setEdge(m,v,f):h.setEdge(m,v),v}),this}setEdge(){var d,f,h,p,m=!1,v=arguments[0];typeof v=="object"&&v!==null&&"v"in v?(d=v.v,f=v.w,h=v.name,arguments.length===2&&(p=arguments[1],m=!0)):(d=v,f=arguments[1],h=arguments[3],arguments.length>2&&(p=arguments[2],m=!0)),d=""+d,f=""+f,h!==void 0&&(h=""+h);var y=i(this._isDirected,d,f,h);if(Object.hasOwn(this._edgeLabels,y))return m&&(this._edgeLabels[y]=p),this;if(h!==void 0&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(d),this.setNode(f),this._edgeLabels[y]=m?p:this._defaultEdgeLabelFn(d,f,h);var b=l(this._isDirected,d,f,h);return d=b.v,f=b.w,Object.freeze(b),this._edgeObjs[y]=b,s(this._preds[f],d),s(this._sucs[d],f),this._in[f][y]=b,this._out[d][y]=b,this._edgeCount++,this}edge(d,f,h){var p=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,h);return this._edgeLabels[p]}edgeAsObj(){const d=this.edge(...arguments);return typeof d!="object"?{label:d}:d}hasEdge(d,f,h){var p=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,h);return Object.hasOwn(this._edgeLabels,p)}removeEdge(d,f,h){var p=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,h),m=this._edgeObjs[p];return m&&(d=m.v,f=m.w,delete this._edgeLabels[p],delete this._edgeObjs[p],a(this._preds[f],d),a(this._sucs[d],f),delete this._in[f][p],delete this._out[d][p],this._edgeCount--),this}inEdges(d,f){var h=this._in[d];if(h){var p=Object.values(h);return f?p.filter(m=>m.v===f):p}}outEdges(d,f){var h=this._out[d];if(h){var p=Object.values(h);return f?p.filter(m=>m.w===f):p}}nodeEdges(d,f){var h=this.inEdges(d,f);if(h)return h.concat(this.outEdges(d,f))}}function s(u,d){u[d]?u[d]++:u[d]=1}function a(u,d){--u[d]||delete u[d]}function i(u,d,f,h){var p=""+d,m=""+f;if(!u&&p>m){var v=p;p=m,m=v}return p+n+m+n+(h===void 0?e:h)}function l(u,d,f,h){var p=""+d,m=""+f;if(!u&&p>m){var v=p;p=m,m=v}var y={v:p,w:m};return h&&(y.name=h),y}function c(u,d){return i(u,d.v,d.w,d.name)}return Cte=r,Cte}var _te,K9e;function sZn(){return K9e||(K9e=1,_te="2.2.4"),_te}var Ete,X9e;function aZn(){return X9e||(X9e=1,Ete={Graph:NOe(),version:sZn()}),Ete}var Tte,J9e;function iZn(){if(J9e)return Tte;J9e=1;var e=NOe();Tte={write:t,read:s};function t(a){var i={options:{directed:a.isDirected(),multigraph:a.isMultigraph(),compound:a.isCompound()},nodes:n(a),edges:r(a)};return a.graph()!==void 0&&(i.value=structuredClone(a.graph())),i}function n(a){return a.nodes().map(function(i){var l=a.node(i),c=a.parent(i),u={v:i};return l!==void 0&&(u.value=l),c!==void 0&&(u.parent=c),u})}function r(a){return a.edges().map(function(i){var l=a.edge(i),c={v:i.v,w:i.w};return i.name!==void 0&&(c.name=i.name),l!==void 0&&(c.value=l),c})}function s(a){var i=new e(a.options).setGraph(a.value);return a.nodes.forEach(function(l){i.setNode(l.v,l.value),l.parent&&i.setParent(l.v,l.parent)}),a.edges.forEach(function(l){i.setEdge({v:l.v,w:l.w,name:l.name},l.value)}),i}return Tte}var jte,e7e;function oZn(){if(e7e)return jte;e7e=1,jte=e;function e(t){var n={},r=[],s;function a(i){Object.hasOwn(n,i)||(n[i]=!0,s.push(i),t.successors(i).forEach(a),t.predecessors(i).forEach(a))}return t.nodes().forEach(function(i){s=[],a(i),s.length&&r.push(s)}),r}return jte}var Nte,t7e;function POt(){if(t7e)return Nte;t7e=1;class e{_arr=[];_keyIndices={};size(){return this._arr.length}keys(){return this._arr.map(function(n){return n.key})}has(n){return Object.hasOwn(this._keyIndices,n)}priority(n){var r=this._keyIndices[n];if(r!==void 0)return this._arr[r].priority}min(){if(this.size()===0)throw new Error("Queue underflow");return this._arr[0].key}add(n,r){var s=this._keyIndices;if(n=String(n),!Object.hasOwn(s,n)){var a=this._arr,i=a.length;return s[n]=i,a.push({key:n,priority:r}),this._decrease(i),!0}return!1}removeMin(){this._swap(0,this._arr.length-1);var n=this._arr.pop();return delete this._keyIndices[n.key],this._heapify(0),n.key}decrease(n,r){var s=this._keyIndices[n];if(r>this._arr[s].priority)throw new Error("New priority is greater than current priority. Key: "+n+" Old: "+this._arr[s].priority+" New: "+r);this._arr[s].priority=r,this._decrease(s)}_heapify(n){var r=this._arr,s=2*n,a=s+1,i=n;s<r.length&&(i=r[s].priority<r[i].priority?s:i,a<r.length&&(i=r[a].priority<r[i].priority?a:i),i!==n&&(this._swap(n,i),this._heapify(i)))}_decrease(n){for(var r=this._arr,s=r[n].priority,a;n!==0&&(a=n>>1,!(r[a].priority<s));)this._swap(n,a),n=a}_swap(n,r){var s=this._arr,a=this._keyIndices,i=s[n],l=s[r];s[n]=l,s[r]=i,a[l.key]=n,a[i.key]=r}}return Nte=e,Nte}var Ite,n7e;function $Ot(){if(n7e)return Ite;n7e=1;var e=POt();Ite=n;var t=()=>1;function n(s,a,i,l){return r(s,String(a),i||t,l||function(c){return s.outEdges(c)})}function r(s,a,i,l){var c={},u=new e,d,f,h=function(p){var m=p.v!==d?p.v:p.w,v=c[m],y=i(p),b=f.distance+y;if(y<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+p+" Weight: "+y);b<v.distance&&(v.distance=b,v.predecessor=d,u.decrease(m,b))};for(s.nodes().forEach(function(p){var m=p===a?0:Number.POSITIVE_INFINITY;c[p]={distance:m},u.add(p,m)});u.size()>0&&(d=u.removeMin(),f=c[d],f.distance!==Number.POSITIVE_INFINITY);)l(d).forEach(h);return c}return Ite}var Ate,r7e;function lZn(){if(r7e)return Ate;r7e=1;var e=$Ot();Ate=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return Ate}var Rte,s7e;function MOt(){if(s7e)return Rte;s7e=1,Rte=e;function e(t){var n=0,r=[],s={},a=[];function i(l){var c=s[l]={onStack:!0,lowlink:n,index:n++};if(r.push(l),t.successors(l).forEach(function(f){Object.hasOwn(s,f)?s[f].onStack&&(c.lowlink=Math.min(c.lowlink,s[f].index)):(i(f),c.lowlink=Math.min(c.lowlink,s[f].lowlink))}),c.lowlink===c.index){var u=[],d;do d=r.pop(),s[d].onStack=!1,u.push(d);while(l!==d);a.push(u)}}return t.nodes().forEach(function(l){Object.hasOwn(s,l)||i(l)}),a}return Rte}var Pte,a7e;function cZn(){if(a7e)return Pte;a7e=1;var e=MOt();Pte=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return Pte}var $te,i7e;function uZn(){if(i7e)return $te;i7e=1,$te=t;var e=()=>1;function t(r,s,a){return n(r,s||e,a||function(i){return r.outEdges(i)})}function n(r,s,a){var i={},l=r.nodes();return l.forEach(function(c){i[c]={},i[c][c]={distance:0},l.forEach(function(u){c!==u&&(i[c][u]={distance:Number.POSITIVE_INFINITY})}),a(c).forEach(function(u){var d=u.v===c?u.w:u.v,f=s(u);i[c][d]={distance:f,predecessor:c}})}),l.forEach(function(c){var u=i[c];l.forEach(function(d){var f=i[d];l.forEach(function(h){var p=f[c],m=u[h],v=f[h],y=p.distance+m.distance;y<v.distance&&(v.distance=y,v.predecessor=m.predecessor)})})}),i}return $te}var Mte,o7e;function DOt(){if(o7e)return Mte;o7e=1;function e(n){var r={},s={},a=[];function i(l){if(Object.hasOwn(s,l))throw new t;Object.hasOwn(r,l)||(s[l]=!0,r[l]=!0,n.predecessors(l).forEach(i),delete s[l],a.push(l))}if(n.sinks().forEach(i),Object.keys(r).length!==n.nodeCount())throw new t;return a}class t extends Error{constructor(){super(...arguments)}}return Mte=e,e.CycleException=t,Mte}var Dte,l7e;function dZn(){if(l7e)return Dte;l7e=1;var e=DOt();Dte=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return Dte}var Lte,c7e;function LOt(){if(c7e)return Lte;c7e=1,Lte=e;function e(s,a,i){Array.isArray(a)||(a=[a]);var l=s.isDirected()?f=>s.successors(f):f=>s.neighbors(f),c=i==="post"?t:n,u=[],d={};return a.forEach(f=>{if(!s.hasNode(f))throw new Error("Graph does not have node: "+f);c(f,l,d,u)}),u}function t(s,a,i,l){for(var c=[[s,!1]];c.length>0;){var u=c.pop();u[1]?l.push(u[0]):Object.hasOwn(i,u[0])||(i[u[0]]=!0,c.push([u[0],!0]),r(a(u[0]),d=>c.push([d,!1])))}}function n(s,a,i,l){for(var c=[s];c.length>0;){var u=c.pop();Object.hasOwn(i,u)||(i[u]=!0,l.push(u),r(a(u),d=>c.push(d)))}}function r(s,a){for(var i=s.length;i--;)a(s[i],i,s);return s}return Lte}var Fte,u7e;function fZn(){if(u7e)return Fte;u7e=1;var e=LOt();Fte=t;function t(n,r){return e(n,r,"post")}return Fte}var zte,d7e;function hZn(){if(d7e)return zte;d7e=1;var e=LOt();zte=t;function t(n,r){return e(n,r,"pre")}return zte}var Bte,f7e;function pZn(){if(f7e)return Bte;f7e=1;var e=NOe(),t=POt();Bte=n;function n(r,s){var a=new e,i={},l=new t,c;function u(f){var h=f.v===c?f.w:f.v,p=l.priority(h);if(p!==void 0){var m=s(f);m<p&&(i[h]=c,l.decrease(h,m))}}if(r.nodeCount()===0)return a;r.nodes().forEach(function(f){l.add(f,Number.POSITIVE_INFINITY),a.setNode(f)}),l.decrease(r.nodes()[0],0);for(var d=!1;l.size()>0;){if(c=l.removeMin(),Object.hasOwn(i,c))a.setEdge(c,i[c]);else{if(d)throw new Error("Input graph is not connected: "+r);d=!0}r.nodeEdges(c).forEach(u)}return a}return Bte}var Ute,h7e;function mZn(){return h7e||(h7e=1,Ute={components:oZn(),dijkstra:$Ot(),dijkstraAll:lZn(),findCycles:cZn(),floydWarshall:uZn(),isAcyclic:dZn(),postorder:fZn(),preorder:hZn(),prim:pZn(),tarjan:MOt(),topsort:DOt()}),Ute}var qte,p7e;function Wg(){if(p7e)return qte;p7e=1;var e=aZn();return qte={Graph:e.Graph,json:iZn(),alg:mZn(),version:e.version},qte}var Vte,m7e;function gZn(){if(m7e)return Vte;m7e=1;class e{constructor(){let s={};s._next=s._prev=s,this._sentinel=s}dequeue(){let s=this._sentinel,a=s._prev;if(a!==s)return t(a),a}enqueue(s){let a=this._sentinel;s._prev&&s._next&&t(s),s._next=a._next,a._next._prev=s,a._next=s,s._prev=a}toString(){let s=[],a=this._sentinel,i=a._prev;for(;i!==a;)s.push(JSON.stringify(i,n)),i=i._prev;return"["+s.join(", ")+"]"}}function t(r){r._prev._next=r._next,r._next._prev=r._prev,delete r._next,delete r._prev}function n(r,s){if(r!=="_next"&&r!=="_prev")return s}return Vte=e,Vte}var Hte,g7e;function vZn(){if(g7e)return Hte;g7e=1;let e=Wg().Graph,t=gZn();Hte=r;let n=()=>1;function r(u,d){if(u.nodeCount()<=1)return[];let f=i(u,d||n);return s(f.graph,f.buckets,f.zeroIdx).flatMap(p=>u.outEdges(p.v,p.w))}function s(u,d,f){let h=[],p=d[d.length-1],m=d[0],v;for(;u.nodeCount();){for(;v=m.dequeue();)a(u,d,f,v);for(;v=p.dequeue();)a(u,d,f,v);if(u.nodeCount()){for(let y=d.length-2;y>0;--y)if(v=d[y].dequeue(),v){h=h.concat(a(u,d,f,v,!0));break}}}return h}function a(u,d,f,h,p){let m=p?[]:void 0;return u.inEdges(h.v).forEach(v=>{let y=u.edge(v),b=u.node(v.v);p&&m.push({v:v.v,w:v.w}),b.out-=y,l(d,f,b)}),u.outEdges(h.v).forEach(v=>{let y=u.edge(v),b=v.w,x=u.node(b);x.in-=y,l(d,f,x)}),u.removeNode(h.v),m}function i(u,d){let f=new e,h=0,p=0;u.nodes().forEach(y=>{f.setNode(y,{v:y,in:0,out:0})}),u.edges().forEach(y=>{let b=f.edge(y.v,y.w)||0,x=d(y),w=b+x;f.setEdge(y.v,y.w,w),p=Math.max(p,f.node(y.v).out+=x),h=Math.max(h,f.node(y.w).in+=x)});let m=c(p+h+3).map(()=>new t),v=h+1;return f.nodes().forEach(y=>{l(m,v,f.node(y))}),{graph:f,buckets:m,zeroIdx:v}}function l(u,d,f){f.out?f.in?u[f.out-f.in+d].enqueue(f):u[u.length-1].enqueue(f):u[0].enqueue(f)}function c(u){const d=[];for(let f=0;f<u;f++)d.push(f);return d}return Hte}var Wte,v7e;function $l(){if(v7e)return Wte;v7e=1;let e=Wg().Graph;Wte={addBorderNode:d,addDummyNode:t,applyWithChunking:p,asNonCompoundGraph:r,buildLayerMatrix:l,intersectRect:i,mapValues:_,maxRank:m,normalizeRanks:c,notime:b,partition:v,pick:C,predecessorWeights:a,range:k,removeEmptyRanks:u,simplify:n,successorWeights:s,time:y,uniqueId:w,zipObject:T};function t(E,N,I,A){for(var P=A;E.hasNode(P);)P=w(A);return I.dummy=N,E.setNode(P,I),P}function n(E){let N=new e().setGraph(E.graph());return E.nodes().forEach(I=>N.setNode(I,E.node(I))),E.edges().forEach(I=>{let A=N.edge(I.v,I.w)||{weight:0,minlen:1},P=E.edge(I);N.setEdge(I.v,I.w,{weight:A.weight+P.weight,minlen:Math.max(A.minlen,P.minlen)})}),N}function r(E){let N=new e({multigraph:E.isMultigraph()}).setGraph(E.graph());return E.nodes().forEach(I=>{E.children(I).length||N.setNode(I,E.node(I))}),E.edges().forEach(I=>{N.setEdge(I,E.edge(I))}),N}function s(E){let N=E.nodes().map(I=>{let A={};return E.outEdges(I).forEach(P=>{A[P.w]=(A[P.w]||0)+E.edge(P).weight}),A});return T(E.nodes(),N)}function a(E){let N=E.nodes().map(I=>{let A={};return E.inEdges(I).forEach(P=>{A[P.v]=(A[P.v]||0)+E.edge(P).weight}),A});return T(E.nodes(),N)}function i(E,N){let I=E.x,A=E.y,P=N.x-I,L=N.y-A,D=E.width/2,B=E.height/2;if(!P&&!L)throw new Error("Not possible to find intersection inside of the rectangle");let H,q;return Math.abs(L)*D>Math.abs(P)*B?(L<0&&(B=-B),H=B*P/L,q=B):(P<0&&(D=-D),H=D,q=D*L/P),{x:I+H,y:A+q}}function l(E){let N=k(m(E)+1).map(()=>[]);return E.nodes().forEach(I=>{let A=E.node(I),P=A.rank;P!==void 0&&(N[P][A.order]=I)}),N}function c(E){let N=E.nodes().map(A=>{let P=E.node(A).rank;return P===void 0?Number.MAX_VALUE:P}),I=p(Math.min,N);E.nodes().forEach(A=>{let P=E.node(A);Object.hasOwn(P,"rank")&&(P.rank-=I)})}function u(E){let N=E.nodes().map(D=>E.node(D).rank),I=p(Math.min,N),A=[];E.nodes().forEach(D=>{let B=E.node(D).rank-I;A[B]||(A[B]=[]),A[B].push(D)});let P=0,L=E.graph().nodeRankFactor;Array.from(A).forEach((D,B)=>{D===void 0&&B%L!==0?--P:D!==void 0&&P&&D.forEach(H=>E.node(H).rank+=P)})}function d(E,N,I,A){let P={width:0,height:0};return arguments.length>=4&&(P.rank=I,P.order=A),t(E,"border",P,N)}function f(E,N=h){const I=[];for(let A=0;A<E.length;A+=N){const P=E.slice(A,A+N);I.push(P)}return I}const h=65535;function p(E,N){if(N.length>h){const I=f(N);return E.apply(null,I.map(A=>E.apply(null,A)))}else return E.apply(null,N)}function m(E){const I=E.nodes().map(A=>{let P=E.node(A).rank;return P===void 0?Number.MIN_VALUE:P});return p(Math.max,I)}function v(E,N){let I={lhs:[],rhs:[]};return E.forEach(A=>{N(A)?I.lhs.push(A):I.rhs.push(A)}),I}function y(E,N){let I=Date.now();try{return N()}finally{console.log(E+" time: "+(Date.now()-I)+"ms")}}function b(E,N){return N()}let x=0;function w(E){var N=++x;return E+(""+N)}function k(E,N,I=1){N==null&&(N=E,E=0);let A=L=>L<N;I<0&&(A=L=>N<L);const P=[];for(let L=E;A(L);L+=I)P.push(L);return P}function C(E,N){const I={};for(const A of N)E[A]!==void 0&&(I[A]=E[A]);return I}function _(E,N){let I=N;return typeof N=="string"&&(I=A=>A[N]),Object.entries(E).reduce((A,[P,L])=>(A[P]=I(L,P),A),{})}function T(E,N){return E.reduce((I,A,P)=>(I[A]=N[P],I),{})}return Wte}var Zte,y7e;function yZn(){if(y7e)return Zte;y7e=1;let e=vZn(),t=$l().uniqueId;Zte={run:n,undo:s};function n(a){(a.graph().acyclicer==="greedy"?e(a,l(a)):r(a)).forEach(c=>{let u=a.edge(c);a.removeEdge(c),u.forwardName=c.name,u.reversed=!0,a.setEdge(c.w,c.v,u,t("rev"))});function l(c){return u=>c.edge(u).weight}}function r(a){let i=[],l={},c={};function u(d){Object.hasOwn(c,d)||(c[d]=!0,l[d]=!0,a.outEdges(d).forEach(f=>{Object.hasOwn(l,f.w)?i.push(f):u(f.w)}),delete l[d])}return a.nodes().forEach(u),i}function s(a){a.edges().forEach(i=>{let l=a.edge(i);if(l.reversed){a.removeEdge(i);let c=l.forwardName;delete l.reversed,delete l.forwardName,a.setEdge(i.w,i.v,l,c)}})}return Zte}var Gte,b7e;function bZn(){if(b7e)return Gte;b7e=1;let e=$l();Gte={run:t,undo:r};function t(s){s.graph().dummyChains=[],s.edges().forEach(a=>n(s,a))}function n(s,a){let i=a.v,l=s.node(i).rank,c=a.w,u=s.node(c).rank,d=a.name,f=s.edge(a),h=f.labelRank;if(u===l+1)return;s.removeEdge(a);let p,m,v;for(v=0,++l;l<u;++v,++l)f.points=[],m={width:0,height:0,edgeLabel:f,edgeObj:a,rank:l},p=e.addDummyNode(s,"edge",m,"_d"),l===h&&(m.width=f.width,m.height=f.height,m.dummy="edge-label",m.labelpos=f.labelpos),s.setEdge(i,p,{weight:f.weight},d),v===0&&s.graph().dummyChains.push(p),i=p;s.setEdge(i,c,{weight:f.weight},d)}function r(s){s.graph().dummyChains.forEach(a=>{let i=s.node(a),l=i.edgeLabel,c;for(s.setEdge(i.edgeObj,l);i.dummy;)c=s.successors(a)[0],s.removeNode(a),l.points.push({x:i.x,y:i.y}),i.dummy==="edge-label"&&(l.x=i.x,l.y=i.y,l.width=i.width,l.height=i.height),a=c,i=s.node(a)})}return Gte}var Qte,x7e;function nU(){if(x7e)return Qte;x7e=1;const{applyWithChunking:e}=$l();Qte={longestPath:t,slack:n};function t(r){var s={};function a(i){var l=r.node(i);if(Object.hasOwn(s,i))return l.rank;s[i]=!0;let c=r.outEdges(i).map(d=>d==null?Number.POSITIVE_INFINITY:a(d.w)-r.edge(d).minlen);var u=e(Math.min,c);return u===Number.POSITIVE_INFINITY&&(u=0),l.rank=u}r.sources().forEach(a)}function n(r,s){return r.node(s.w).rank-r.node(s.v).rank-r.edge(s).minlen}return Qte}var Yte,w7e;function FOt(){if(w7e)return Yte;w7e=1;var e=Wg().Graph,t=nU().slack;Yte=n;function n(i){var l=new e({directed:!1}),c=i.nodes()[0],u=i.nodeCount();l.setNode(c,{});for(var d,f;r(l,i)<u;)d=s(l,i),f=l.hasNode(d.v)?t(i,d):-t(i,d),a(l,i,f);return l}function r(i,l){function c(u){l.nodeEdges(u).forEach(d=>{var f=d.v,h=u===f?d.w:f;!i.hasNode(h)&&!t(l,d)&&(i.setNode(h,{}),i.setEdge(u,h,{}),c(h))})}return i.nodes().forEach(c),i.nodeCount()}function s(i,l){return l.edges().reduce((u,d)=>{let f=Number.POSITIVE_INFINITY;return i.hasNode(d.v)!==i.hasNode(d.w)&&(f=t(l,d)),f<u[0]?[f,d]:u},[Number.POSITIVE_INFINITY,null])[1]}function a(i,l,c){i.nodes().forEach(u=>l.node(u).rank+=c)}return Yte}var Kte,S7e;function xZn(){if(S7e)return Kte;S7e=1;var e=FOt(),t=nU().slack,n=nU().longestPath,r=Wg().alg.preorder,s=Wg().alg.postorder,a=$l().simplify;Kte=i,i.initLowLimValues=d,i.initCutValues=l,i.calcCutValue=u,i.leaveEdge=h,i.enterEdge=p,i.exchangeEdges=m;function i(x){x=a(x),n(x);var w=e(x);d(w),l(w,x);for(var k,C;k=h(w);)C=p(w,x,k),m(w,x,k,C)}function l(x,w){var k=s(x,x.nodes());k=k.slice(0,k.length-1),k.forEach(C=>c(x,w,C))}function c(x,w,k){var C=x.node(k),_=C.parent;x.edge(k,_).cutvalue=u(x,w,k)}function u(x,w,k){var C=x.node(k),_=C.parent,T=!0,E=w.edge(k,_),N=0;return E||(T=!1,E=w.edge(_,k)),N=E.weight,w.nodeEdges(k).forEach(I=>{var A=I.v===k,P=A?I.w:I.v;if(P!==_){var L=A===T,D=w.edge(I).weight;if(N+=L?D:-D,y(x,k,P)){var B=x.edge(k,P).cutvalue;N+=L?-B:B}}}),N}function d(x,w){arguments.length<2&&(w=x.nodes()[0]),f(x,{},1,w)}function f(x,w,k,C,_){var T=k,E=x.node(C);return w[C]=!0,x.neighbors(C).forEach(N=>{Object.hasOwn(w,N)||(k=f(x,w,k,N,C))}),E.low=T,E.lim=k++,_?E.parent=_:delete E.parent,k}function h(x){return x.edges().find(w=>x.edge(w).cutvalue<0)}function p(x,w,k){var C=k.v,_=k.w;w.hasEdge(C,_)||(C=k.w,_=k.v);var T=x.node(C),E=x.node(_),N=T,I=!1;T.lim>E.lim&&(N=E,I=!0);var A=w.edges().filter(P=>I===b(x,x.node(P.v),N)&&I!==b(x,x.node(P.w),N));return A.reduce((P,L)=>t(w,L)<t(w,P)?L:P)}function m(x,w,k,C){var _=k.v,T=k.w;x.removeEdge(_,T),x.setEdge(C.v,C.w,{}),d(x),l(x,w),v(x,w)}function v(x,w){var k=x.nodes().find(_=>!w.node(_).parent),C=r(x,k);C=C.slice(1),C.forEach(_=>{var T=x.node(_).parent,E=w.edge(_,T),N=!1;E||(E=w.edge(T,_),N=!0),w.node(_).rank=w.node(T).rank+(N?E.minlen:-E.minlen)})}function y(x,w,k){return x.hasEdge(w,k)}function b(x,w,k){return k.low<=w.lim&&w.lim<=k.lim}return Kte}var Xte,k7e;function wZn(){if(k7e)return Xte;k7e=1;var e=nU(),t=e.longestPath,n=FOt(),r=xZn();Xte=s;function s(c){var u=c.graph().ranker;if(u instanceof Function)return u(c);switch(c.graph().ranker){case"network-simplex":l(c);break;case"tight-tree":i(c);break;case"longest-path":a(c);break;case"none":break;default:l(c)}}var a=t;function i(c){t(c),n(c)}function l(c){r(c)}return Xte}var Jte,O7e;function SZn(){if(O7e)return Jte;O7e=1,Jte=e;function e(r){let s=n(r);r.graph().dummyChains.forEach(a=>{let i=r.node(a),l=i.edgeObj,c=t(r,s,l.v,l.w),u=c.path,d=c.lca,f=0,h=u[f],p=!0;for(;a!==l.w;){if(i=r.node(a),p){for(;(h=u[f])!==d&&r.node(h).maxRank<i.rank;)f++;h===d&&(p=!1)}if(!p){for(;f<u.length-1&&r.node(h=u[f+1]).minRank<=i.rank;)f++;h=u[f]}r.setParent(a,h),a=r.successors(a)[0]}})}function t(r,s,a,i){let l=[],c=[],u=Math.min(s[a].low,s[i].low),d=Math.max(s[a].lim,s[i].lim),f,h;f=a;do f=r.parent(f),l.push(f);while(f&&(s[f].low>u||d>s[f].lim));for(h=f,f=i;(f=r.parent(f))!==h;)c.push(f);return{path:l.concat(c.reverse()),lca:h}}function n(r){let s={},a=0;function i(l){let c=a;r.children(l).forEach(i),s[l]={low:c,lim:a++}}return r.children().forEach(i),s}return Jte}var ene,C7e;function kZn(){if(C7e)return ene;C7e=1;let e=$l();ene={run:t,cleanup:a};function t(i){let l=e.addDummyNode(i,"root",{},"_root"),c=r(i),u=Object.values(c),d=e.applyWithChunking(Math.max,u)-1,f=2*d+1;i.graph().nestingRoot=l,i.edges().forEach(p=>i.edge(p).minlen*=f);let h=s(i)+1;i.children().forEach(p=>n(i,l,f,h,d,c,p)),i.graph().nodeRankFactor=f}function n(i,l,c,u,d,f,h){let p=i.children(h);if(!p.length){h!==l&&i.setEdge(l,h,{weight:0,minlen:c});return}let m=e.addBorderNode(i,"_bt"),v=e.addBorderNode(i,"_bb"),y=i.node(h);i.setParent(m,h),y.borderTop=m,i.setParent(v,h),y.borderBottom=v,p.forEach(b=>{n(i,l,c,u,d,f,b);let x=i.node(b),w=x.borderTop?x.borderTop:b,k=x.borderBottom?x.borderBottom:b,C=x.borderTop?u:2*u,_=w!==k?1:d-f[h]+1;i.setEdge(m,w,{weight:C,minlen:_,nestingEdge:!0}),i.setEdge(k,v,{weight:C,minlen:_,nestingEdge:!0})}),i.parent(h)||i.setEdge(l,m,{weight:0,minlen:d+f[h]})}function r(i){var l={};function c(u,d){var f=i.children(u);f&&f.length&&f.forEach(h=>c(h,d+1)),l[u]=d}return i.children().forEach(u=>c(u,1)),l}function s(i){return i.edges().reduce((l,c)=>l+i.edge(c).weight,0)}function a(i){var l=i.graph();i.removeNode(l.nestingRoot),delete l.nestingRoot,i.edges().forEach(c=>{var u=i.edge(c);u.nestingEdge&&i.removeEdge(c)})}return ene}var tne,_7e;function OZn(){if(_7e)return tne;_7e=1;let e=$l();tne=t;function t(r){function s(a){let i=r.children(a),l=r.node(a);if(i.length&&i.forEach(s),Object.hasOwn(l,"minRank")){l.borderLeft=[],l.borderRight=[];for(let c=l.minRank,u=l.maxRank+1;c<u;++c)n(r,"borderLeft","_bl",a,l,c),n(r,"borderRight","_br",a,l,c)}}r.children().forEach(s)}function n(r,s,a,i,l,c){let u={width:0,height:0,rank:c,borderType:s},d=l[s][c-1],f=e.addDummyNode(r,"border",u,a);l[s][c]=f,r.setParent(f,i),d&&r.setEdge(d,f,{weight:1})}return tne}var nne,E7e;function CZn(){if(E7e)return nne;E7e=1,nne={adjust:e,undo:t};function e(c){let u=c.graph().rankdir.toLowerCase();(u==="lr"||u==="rl")&&n(c)}function t(c){let u=c.graph().rankdir.toLowerCase();(u==="bt"||u==="rl")&&s(c),(u==="lr"||u==="rl")&&(i(c),n(c))}function n(c){c.nodes().forEach(u=>r(c.node(u))),c.edges().forEach(u=>r(c.edge(u)))}function r(c){let u=c.width;c.width=c.height,c.height=u}function s(c){c.nodes().forEach(u=>a(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(a),Object.hasOwn(d,"y")&&a(d)})}function a(c){c.y=-c.y}function i(c){c.nodes().forEach(u=>l(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(l),Object.hasOwn(d,"x")&&l(d)})}function l(c){let u=c.x;c.x=c.y,c.y=u}return nne}var rne,T7e;function _Zn(){if(T7e)return rne;T7e=1;let e=$l();rne=t;function t(n){let r={},s=n.nodes().filter(d=>!n.children(d).length),a=s.map(d=>n.node(d).rank),i=e.applyWithChunking(Math.max,a),l=e.range(i+1).map(()=>[]);function c(d){if(r[d])return;r[d]=!0;let f=n.node(d);l[f.rank].push(d),n.successors(d).forEach(c)}return s.sort((d,f)=>n.node(d).rank-n.node(f).rank).forEach(c),l}return rne}var sne,j7e;function EZn(){if(j7e)return sne;j7e=1;let e=$l().zipObject;sne=t;function t(r,s){let a=0;for(let i=1;i<s.length;++i)a+=n(r,s[i-1],s[i]);return a}function n(r,s,a){let i=e(a,a.map((h,p)=>p)),l=s.flatMap(h=>r.outEdges(h).map(p=>({pos:i[p.w],weight:r.edge(p).weight})).sort((p,m)=>p.pos-m.pos)),c=1;for(;c<a.length;)c<<=1;let u=2*c-1;c-=1;let d=new Array(u).fill(0),f=0;return l.forEach(h=>{let p=h.pos+c;d[p]+=h.weight;let m=0;for(;p>0;)p%2&&(m+=d[p+1]),p=p-1>>1,d[p]+=h.weight;f+=h.weight*m}),f}return sne}var ane,N7e;function TZn(){if(N7e)return ane;N7e=1,ane=e;function e(t,n=[]){return n.map(r=>{let s=t.inEdges(r);if(s.length){let a=s.reduce((i,l)=>{let c=t.edge(l),u=t.node(l.v);return{sum:i.sum+c.weight*u.order,weight:i.weight+c.weight}},{sum:0,weight:0});return{v:r,barycenter:a.sum/a.weight,weight:a.weight}}else return{v:r}})}return ane}var ine,I7e;function jZn(){if(I7e)return ine;I7e=1;let e=$l();ine=t;function t(s,a){let i={};s.forEach((c,u)=>{let d=i[c.v]={indegree:0,in:[],out:[],vs:[c.v],i:u};c.barycenter!==void 0&&(d.barycenter=c.barycenter,d.weight=c.weight)}),a.edges().forEach(c=>{let u=i[c.v],d=i[c.w];u!==void 0&&d!==void 0&&(d.indegree++,u.out.push(i[c.w]))});let l=Object.values(i).filter(c=>!c.indegree);return n(l)}function n(s){let a=[];function i(c){return u=>{u.merged||(u.barycenter===void 0||c.barycenter===void 0||u.barycenter>=c.barycenter)&&r(c,u)}}function l(c){return u=>{u.in.push(c),--u.indegree===0&&s.push(u)}}for(;s.length;){let c=s.pop();a.push(c),c.in.reverse().forEach(i(c)),c.out.forEach(l(c))}return a.filter(c=>!c.merged).map(c=>e.pick(c,["vs","i","barycenter","weight"]))}function r(s,a){let i=0,l=0;s.weight&&(i+=s.barycenter*s.weight,l+=s.weight),a.weight&&(i+=a.barycenter*a.weight,l+=a.weight),s.vs=a.vs.concat(s.vs),s.barycenter=i/l,s.weight=l,s.i=Math.min(a.i,s.i),a.merged=!0}return ine}var one,A7e;function NZn(){if(A7e)return one;A7e=1;let e=$l();one=t;function t(s,a){let i=e.partition(s,m=>Object.hasOwn(m,"barycenter")),l=i.lhs,c=i.rhs.sort((m,v)=>v.i-m.i),u=[],d=0,f=0,h=0;l.sort(r(!!a)),h=n(u,c,h),l.forEach(m=>{h+=m.vs.length,u.push(m.vs),d+=m.barycenter*m.weight,f+=m.weight,h=n(u,c,h)});let p={vs:u.flat(!0)};return f&&(p.barycenter=d/f,p.weight=f),p}function n(s,a,i){let l;for(;a.length&&(l=a[a.length-1]).i<=i;)a.pop(),s.push(l.vs),i++;return i}function r(s){return(a,i)=>a.barycenter<i.barycenter?-1:a.barycenter>i.barycenter?1:s?i.i-a.i:a.i-i.i}return one}var lne,R7e;function IZn(){if(R7e)return lne;R7e=1;let e=TZn(),t=jZn(),n=NZn();lne=r;function r(i,l,c,u){let d=i.children(l),f=i.node(l),h=f?f.borderLeft:void 0,p=f?f.borderRight:void 0,m={};h&&(d=d.filter(x=>x!==h&&x!==p));let v=e(i,d);v.forEach(x=>{if(i.children(x.v).length){let w=r(i,x.v,c,u);m[x.v]=w,Object.hasOwn(w,"barycenter")&&a(x,w)}});let y=t(v,c);s(y,m);let b=n(y,u);if(h&&(b.vs=[h,b.vs,p].flat(!0),i.predecessors(h).length)){let x=i.node(i.predecessors(h)[0]),w=i.node(i.predecessors(p)[0]);Object.hasOwn(b,"barycenter")||(b.barycenter=0,b.weight=0),b.barycenter=(b.barycenter*b.weight+x.order+w.order)/(b.weight+2),b.weight+=2}return b}function s(i,l){i.forEach(c=>{c.vs=c.vs.flatMap(u=>l[u]?l[u].vs:u)})}function a(i,l){i.barycenter!==void 0?(i.barycenter=(i.barycenter*i.weight+l.barycenter*l.weight)/(i.weight+l.weight),i.weight+=l.weight):(i.barycenter=l.barycenter,i.weight=l.weight)}return lne}var cne,P7e;function AZn(){if(P7e)return cne;P7e=1;let e=Wg().Graph,t=$l();cne=n;function n(s,a,i,l){l||(l=s.nodes());let c=r(s),u=new e({compound:!0}).setGraph({root:c}).setDefaultNodeLabel(d=>s.node(d));return l.forEach(d=>{let f=s.node(d),h=s.parent(d);(f.rank===a||f.minRank<=a&&a<=f.maxRank)&&(u.setNode(d),u.setParent(d,h||c),s[i](d).forEach(p=>{let m=p.v===d?p.w:p.v,v=u.edge(m,d),y=v!==void 0?v.weight:0;u.setEdge(m,d,{weight:s.edge(p).weight+y})}),Object.hasOwn(f,"minRank")&&u.setNode(d,{borderLeft:f.borderLeft[a],borderRight:f.borderRight[a]}))}),u}function r(s){for(var a;s.hasNode(a=t.uniqueId("_root")););return a}return cne}var une,$7e;function RZn(){if($7e)return une;$7e=1,une=e;function e(t,n,r){let s={},a;r.forEach(i=>{let l=t.parent(i),c,u;for(;l;){if(c=t.parent(l),c?(u=s[c],s[c]=l):(u=a,a=l),u&&u!==l){n.setEdge(u,l);return}l=c}})}return une}var dne,M7e;function PZn(){if(M7e)return dne;M7e=1;let e=_Zn(),t=EZn(),n=IZn(),r=AZn(),s=RZn(),a=Wg().Graph,i=$l();dne=l;function l(f,h){if(h&&typeof h.customOrder=="function"){h.customOrder(f,l);return}let p=i.maxRank(f),m=c(f,i.range(1,p+1),"inEdges"),v=c(f,i.range(p-1,-1,-1),"outEdges"),y=e(f);if(d(f,y),h&&h.disableOptimalOrderHeuristic)return;let b=Number.POSITIVE_INFINITY,x;for(let w=0,k=0;k<4;++w,++k){u(w%2?m:v,w%4>=2),y=i.buildLayerMatrix(f);let C=t(f,y);C<b&&(k=0,x=Object.assign({},y),b=C)}d(f,x)}function c(f,h,p){const m=new Map,v=(y,b)=>{m.has(y)||m.set(y,[]),m.get(y).push(b)};for(const y of f.nodes()){const b=f.node(y);if(typeof b.rank=="number"&&v(b.rank,y),typeof b.minRank=="number"&&typeof b.maxRank=="number")for(let x=b.minRank;x<=b.maxRank;x++)x!==b.rank&&v(x,y)}return h.map(function(y){return r(f,y,p,m.get(y)||[])})}function u(f,h){let p=new a;f.forEach(function(m){let v=m.graph().root,y=n(m,v,p,h);y.vs.forEach((b,x)=>m.node(b).order=x),s(m,p,y.vs)})}function d(f,h){Object.values(h).forEach(p=>p.forEach((m,v)=>f.node(m).order=v))}return dne}var fne,D7e;function $Zn(){if(D7e)return fne;D7e=1;let e=Wg().Graph,t=$l();fne={positionX:p,findType1Conflicts:n,findType2Conflicts:r,addConflict:a,hasConflict:i,verticalAlignment:l,horizontalCompaction:c,alignCoordinates:f,findSmallestWidthAlignment:d,balance:h};function n(y,b){let x={};function w(k,C){let _=0,T=0,E=k.length,N=C[C.length-1];return C.forEach((I,A)=>{let P=s(y,I),L=P?y.node(P).order:E;(P||I===N)&&(C.slice(T,A+1).forEach(D=>{y.predecessors(D).forEach(B=>{let H=y.node(B),q=H.order;(q<_||L<q)&&!(H.dummy&&y.node(D).dummy)&&a(x,B,D)})}),T=A+1,_=L)}),C}return b.length&&b.reduce(w),x}function r(y,b){let x={};function w(C,_,T,E,N){let I;t.range(_,T).forEach(A=>{I=C[A],y.node(I).dummy&&y.predecessors(I).forEach(P=>{let L=y.node(P);L.dummy&&(L.order<E||L.order>N)&&a(x,P,I)})})}function k(C,_){let T=-1,E,N=0;return _.forEach((I,A)=>{if(y.node(I).dummy==="border"){let P=y.predecessors(I);P.length&&(E=y.node(P[0]).order,w(_,N,A,T,E),N=A,T=E)}w(_,N,_.length,E,C.length)}),_}return b.length&&b.reduce(k),x}function s(y,b){if(y.node(b).dummy)return y.predecessors(b).find(x=>y.node(x).dummy)}function a(y,b,x){if(b>x){let k=b;b=x,x=k}let w=y[b];w||(y[b]=w={}),w[x]=!0}function i(y,b,x){if(b>x){let w=b;b=x,x=w}return!!y[b]&&Object.hasOwn(y[b],x)}function l(y,b,x,w){let k={},C={},_={};return b.forEach(T=>{T.forEach((E,N)=>{k[E]=E,C[E]=E,_[E]=N})}),b.forEach(T=>{let E=-1;T.forEach(N=>{let I=w(N);if(I.length){I=I.sort((P,L)=>_[P]-_[L]);let A=(I.length-1)/2;for(let P=Math.floor(A),L=Math.ceil(A);P<=L;++P){let D=I[P];C[N]===N&&E<_[D]&&!i(x,N,D)&&(C[D]=N,C[N]=k[N]=k[D],E=_[D])}}})}),{root:k,align:C}}function c(y,b,x,w,k){let C={},_=u(y,b,x,k),T=k?"borderLeft":"borderRight";function E(A,P){let L=_.nodes(),D=L.pop(),B={};for(;D;)B[D]?A(D):(B[D]=!0,L.push(D),L=L.concat(P(D))),D=L.pop()}function N(A){C[A]=_.inEdges(A).reduce((P,L)=>Math.max(P,C[L.v]+_.edge(L)),0)}function I(A){let P=_.outEdges(A).reduce((D,B)=>Math.min(D,C[B.w]-_.edge(B)),Number.POSITIVE_INFINITY),L=y.node(A);P!==Number.POSITIVE_INFINITY&&L.borderType!==T&&(C[A]=Math.max(C[A],P))}return E(N,_.predecessors.bind(_)),E(I,_.successors.bind(_)),Object.keys(w).forEach(A=>C[A]=C[x[A]]),C}function u(y,b,x,w){let k=new e,C=y.graph(),_=m(C.nodesep,C.edgesep,w);return b.forEach(T=>{let E;T.forEach(N=>{let I=x[N];if(k.setNode(I),E){var A=x[E],P=k.edge(A,I);k.setEdge(A,I,Math.max(_(y,N,E),P||0))}E=N})}),k}function d(y,b){return Object.values(b).reduce((x,w)=>{let k=Number.NEGATIVE_INFINITY,C=Number.POSITIVE_INFINITY;Object.entries(w).forEach(([T,E])=>{let N=v(y,T)/2;k=Math.max(E+N,k),C=Math.min(E-N,C)});const _=k-C;return _<x[0]&&(x=[_,w]),x},[Number.POSITIVE_INFINITY,null])[1]}function f(y,b){let x=Object.values(b),w=t.applyWithChunking(Math.min,x),k=t.applyWithChunking(Math.max,x);["u","d"].forEach(C=>{["l","r"].forEach(_=>{let T=C+_,E=y[T];if(E===b)return;let N=Object.values(E),I=w-t.applyWithChunking(Math.min,N);_!=="l"&&(I=k-t.applyWithChunking(Math.max,N)),I&&(y[T]=t.mapValues(E,A=>A+I))})})}function h(y,b){return t.mapValues(y.ul,(x,w)=>{if(b)return y[b.toLowerCase()][w];{let k=Object.values(y).map(C=>C[w]).sort((C,_)=>C-_);return(k[1]+k[2])/2}})}function p(y){let b=t.buildLayerMatrix(y),x=Object.assign(n(y,b),r(y,b)),w={},k;["u","d"].forEach(_=>{k=_==="u"?b:Object.values(b).reverse(),["l","r"].forEach(T=>{T==="r"&&(k=k.map(A=>Object.values(A).reverse()));let E=(_==="u"?y.predecessors:y.successors).bind(y),N=l(y,k,x,E),I=c(y,k,N.root,N.align,T==="r");T==="r"&&(I=t.mapValues(I,A=>-A)),w[_+T]=I})});let C=d(y,w);return f(w,C),h(w,y.graph().align)}function m(y,b,x){return(w,k,C)=>{let _=w.node(k),T=w.node(C),E=0,N;if(E+=_.width/2,Object.hasOwn(_,"labelpos"))switch(_.labelpos.toLowerCase()){case"l":N=-_.width/2;break;case"r":N=_.width/2;break}if(N&&(E+=x?N:-N),N=0,E+=(_.dummy?b:y)/2,E+=(T.dummy?b:y)/2,E+=T.width/2,Object.hasOwn(T,"labelpos"))switch(T.labelpos.toLowerCase()){case"l":N=T.width/2;break;case"r":N=-T.width/2;break}return N&&(E+=x?N:-N),N=0,E}}function v(y,b){return y.node(b).width}return fne}var hne,L7e;function MZn(){if(L7e)return hne;L7e=1;let e=$l(),t=$Zn().positionX;hne=n;function n(s){s=e.asNonCompoundGraph(s),r(s),Object.entries(t(s)).forEach(([a,i])=>s.node(a).x=i)}function r(s){let a=e.buildLayerMatrix(s),i=s.graph().ranksep,l=0;a.forEach(c=>{const u=c.reduce((d,f)=>{const h=s.node(f).height;return d>h?d:h},0);c.forEach(d=>s.node(d).y=l+u/2),l+=u+i})}return hne}var pne,F7e;function DZn(){if(F7e)return pne;F7e=1;let e=yZn(),t=bZn(),n=wZn(),r=$l().normalizeRanks,s=SZn(),a=$l().removeEmptyRanks,i=kZn(),l=OZn(),c=CZn(),u=PZn(),d=MZn(),f=$l(),h=Wg().Graph;pne=p;function p(R,U){let Z=U&&U.debugTiming?f.time:f.notime;Z("layout",()=>{let Y=Z(" buildLayoutGraph",()=>E(R));Z(" runLayout",()=>m(Y,Z,U)),Z(" updateInputGraph",()=>v(R,Y))})}function m(R,U,Z){U(" makeSpaceForEdgeLabels",()=>N(R)),U(" removeSelfEdges",()=>z(R)),U(" acyclic",()=>e.run(R)),U(" nestingGraph.run",()=>i.run(R)),U(" rank",()=>n(f.asNonCompoundGraph(R))),U(" injectEdgeLabelProxies",()=>I(R)),U(" removeEmptyRanks",()=>a(R)),U(" nestingGraph.cleanup",()=>i.cleanup(R)),U(" normalizeRanks",()=>r(R)),U(" assignRankMinMax",()=>A(R)),U(" removeEdgeLabelProxies",()=>P(R)),U(" normalize.run",()=>t.run(R)),U(" parentDummyChains",()=>s(R)),U(" addBorderSegments",()=>l(R)),U(" order",()=>u(R,Z)),U(" insertSelfEdges",()=>V(R)),U(" adjustCoordinateSystem",()=>c.adjust(R)),U(" position",()=>d(R)),U(" positionSelfEdges",()=>M(R)),U(" removeBorderNodes",()=>q(R)),U(" normalize.undo",()=>t.undo(R)),U(" fixupEdgeLabelCoords",()=>B(R)),U(" undoCoordinateSystem",()=>c.undo(R)),U(" translateGraph",()=>L(R)),U(" assignNodeIntersects",()=>D(R)),U(" reversePoints",()=>H(R)),U(" acyclic.undo",()=>e.undo(R))}function v(R,U){R.nodes().forEach(Z=>{let Y=R.node(Z),te=U.node(Z);Y&&(Y.x=te.x,Y.y=te.y,Y.rank=te.rank,U.children(Z).length&&(Y.width=te.width,Y.height=te.height))}),R.edges().forEach(Z=>{let Y=R.edge(Z),te=U.edge(Z);Y.points=te.points,Object.hasOwn(te,"x")&&(Y.x=te.x,Y.y=te.y)}),R.graph().width=U.graph().width,R.graph().height=U.graph().height}let y=["nodesep","edgesep","ranksep","marginx","marginy"],b={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},x=["acyclicer","ranker","rankdir","align"],w=["width","height","rank"],k={width:0,height:0},C=["minlen","weight","width","height","labeloffset"],_={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},T=["labelpos"];function E(R){let U=new h({multigraph:!0,compound:!0}),Z=F(R.graph());return U.setGraph(Object.assign({},b,G(Z,y),f.pick(Z,x))),R.nodes().forEach(Y=>{let te=F(R.node(Y));const J=G(te,w);Object.keys(k).forEach(ee=>{J[ee]===void 0&&(J[ee]=k[ee])}),U.setNode(Y,J),U.setParent(Y,R.parent(Y))}),R.edges().forEach(Y=>{let te=F(R.edge(Y));U.setEdge(Y,Object.assign({},_,G(te,C),f.pick(te,T)))}),U}function N(R){let U=R.graph();U.ranksep/=2,R.edges().forEach(Z=>{let Y=R.edge(Z);Y.minlen*=2,Y.labelpos.toLowerCase()!=="c"&&(U.rankdir==="TB"||U.rankdir==="BT"?Y.width+=Y.labeloffset:Y.height+=Y.labeloffset)})}function I(R){R.edges().forEach(U=>{let Z=R.edge(U);if(Z.width&&Z.height){let Y=R.node(U.v),J={rank:(R.node(U.w).rank-Y.rank)/2+Y.rank,e:U};f.addDummyNode(R,"edge-proxy",J,"_ep")}})}function A(R){let U=0;R.nodes().forEach(Z=>{let Y=R.node(Z);Y.borderTop&&(Y.minRank=R.node(Y.borderTop).rank,Y.maxRank=R.node(Y.borderBottom).rank,U=Math.max(U,Y.maxRank))}),R.graph().maxRank=U}function P(R){R.nodes().forEach(U=>{let Z=R.node(U);Z.dummy==="edge-proxy"&&(R.edge(Z.e).labelRank=Z.rank,R.removeNode(U))})}function L(R){let U=Number.POSITIVE_INFINITY,Z=0,Y=Number.POSITIVE_INFINITY,te=0,J=R.graph(),ee=J.marginx||0,re=J.marginy||0;function ae(X){let ne=X.x,se=X.y,ce=X.width,le=X.height;U=Math.min(U,ne-ce/2),Z=Math.max(Z,ne+ce/2),Y=Math.min(Y,se-le/2),te=Math.max(te,se+le/2)}R.nodes().forEach(X=>ae(R.node(X))),R.edges().forEach(X=>{let ne=R.edge(X);Object.hasOwn(ne,"x")&&ae(ne)}),U-=ee,Y-=re,R.nodes().forEach(X=>{let ne=R.node(X);ne.x-=U,ne.y-=Y}),R.edges().forEach(X=>{let ne=R.edge(X);ne.points.forEach(se=>{se.x-=U,se.y-=Y}),Object.hasOwn(ne,"x")&&(ne.x-=U),Object.hasOwn(ne,"y")&&(ne.y-=Y)}),J.width=Z-U+ee,J.height=te-Y+re}function D(R){R.edges().forEach(U=>{let Z=R.edge(U),Y=R.node(U.v),te=R.node(U.w),J,ee;Z.points?(J=Z.points[0],ee=Z.points[Z.points.length-1]):(Z.points=[],J=te,ee=Y),Z.points.unshift(f.intersectRect(Y,J)),Z.points.push(f.intersectRect(te,ee))})}function B(R){R.edges().forEach(U=>{let Z=R.edge(U);if(Object.hasOwn(Z,"x"))switch((Z.labelpos==="l"||Z.labelpos==="r")&&(Z.width-=Z.labeloffset),Z.labelpos){case"l":Z.x-=Z.width/2+Z.labeloffset;break;case"r":Z.x+=Z.width/2+Z.labeloffset;break}})}function H(R){R.edges().forEach(U=>{let Z=R.edge(U);Z.reversed&&Z.points.reverse()})}function q(R){R.nodes().forEach(U=>{if(R.children(U).length){let Z=R.node(U),Y=R.node(Z.borderTop),te=R.node(Z.borderBottom),J=R.node(Z.borderLeft[Z.borderLeft.length-1]),ee=R.node(Z.borderRight[Z.borderRight.length-1]);Z.width=Math.abs(ee.x-J.x),Z.height=Math.abs(te.y-Y.y),Z.x=J.x+Z.width/2,Z.y=Y.y+Z.height/2}}),R.nodes().forEach(U=>{R.node(U).dummy==="border"&&R.removeNode(U)})}function z(R){R.edges().forEach(U=>{if(U.v===U.w){var Z=R.node(U.v);Z.selfEdges||(Z.selfEdges=[]),Z.selfEdges.push({e:U,label:R.edge(U)}),R.removeEdge(U)}})}function V(R){var U=f.buildLayerMatrix(R);U.forEach(Z=>{var Y=0;Z.forEach((te,J)=>{var ee=R.node(te);ee.order=J+Y,(ee.selfEdges||[]).forEach(re=>{f.addDummyNode(R,"selfedge",{width:re.label.width,height:re.label.height,rank:ee.rank,order:J+ ++Y,e:re.e,label:re.label},"_se")}),delete ee.selfEdges})})}function M(R){R.nodes().forEach(U=>{var Z=R.node(U);if(Z.dummy==="selfedge"){var Y=R.node(Z.e.v),te=Y.x+Y.width/2,J=Y.y,ee=Z.x-te,re=Y.height/2;R.setEdge(Z.e,Z.label),R.removeNode(U),Z.label.points=[{x:te+2*ee/3,y:J-re},{x:te+5*ee/6,y:J-re},{x:te+ee,y:J},{x:te+5*ee/6,y:J+re},{x:te+2*ee/3,y:J+re}],Z.label.x=Z.x,Z.label.y=Z.y}})}function G(R,U){return f.mapValues(f.pick(R,U),Number)}function F(R){var U={};return R&&Object.entries(R).forEach(([Z,Y])=>{typeof Z=="string"&&(Z=Z.toLowerCase()),U[Z]=Y}),U}return pne}var mne,z7e;function LZn(){if(z7e)return mne;z7e=1;let e=$l(),t=Wg().Graph;mne={debugOrdering:n};function n(r){let s=e.buildLayerMatrix(r),a=new t({compound:!0,multigraph:!0}).setGraph({});return r.nodes().forEach(i=>{a.setNode(i,{label:i}),a.setParent(i,"layer"+r.node(i).rank)}),r.edges().forEach(i=>a.setEdge(i.v,i.w,{},i.name)),s.forEach((i,l)=>{let c="layer"+l;a.setNode(c,{rank:"same"}),i.reduce((u,d)=>(a.setEdge(u,d,{style:"invis"}),d))}),a}return mne}var gne,B7e;function FZn(){return B7e||(B7e=1,gne="1.1.8"),gne}var vne,U7e;function zZn(){return U7e||(U7e=1,vne={graphlib:Wg(),layout:DZn(),debug:LZn(),util:{time:$l().time,notime:$l().notime},version:FZn()}),vne}var BZn=zZn();const q7e=Hl(BZn);function Ql(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,r;n<e.length;n++)(r=Ql(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var UZn={value:()=>{}};function bW(){for(var e=0,t=arguments.length,n={},r;e<t;++e){if(!(r=arguments[e]+"")||r in n||/[\s.]/.test(r))throw new Error("illegal type: "+r);n[r]=[]}return new n9(n)}function n9(e){this._=e}function qZn(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",s=n.indexOf(".");if(s>=0&&(r=n.slice(s+1),n=n.slice(0,s)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}n9.prototype=bW.prototype={constructor:n9,on:function(e,t){var n=this._,r=qZn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=VZn(n[s],e.name)))return s;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++a<i;)if(s=(e=r[a]).type)n[s]=V7e(n[s],e.name,t);else if(t==null)for(s in n)n[s]=V7e(n[s],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new n9(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),r=0,s,a;r<s;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(a=this._[e],r=0,s=a.length;r<s;++r)a[r].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],s=0,a=r.length;s<a;++s)r[s].value.apply(t,n)}};function VZn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function V7e(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=UZn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Rve="http://www.w3.org/1999/xhtml";const H7e={svg:"http://www.w3.org/2000/svg",xhtml:Rve,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function xW(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),H7e.hasOwnProperty(t)?{space:H7e[t],local:e}:e}function HZn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Rve&&t.documentElement.namespaceURI===Rve?t.createElement(e):t.createElementNS(n,e)}}function WZn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function zOt(e){var t=xW(e);return(t.local?WZn:HZn)(t)}function ZZn(){}function IOe(e){return e==null?ZZn:function(){return this.querySelector(e)}}function GZn(e){typeof e!="function"&&(e=IOe(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=new Array(i),c,u,d=0;d<i;++d)(c=a[d])&&(u=e.call(c,c.__data__,d,a))&&("__data__"in c&&(u.__data__=c.__data__),l[d]=u);return new tp(r,this._parents)}function QZn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function YZn(){return[]}function BOt(e){return e==null?YZn:function(){return this.querySelectorAll(e)}}function KZn(e){return function(){return QZn(e.apply(this,arguments))}}function XZn(e){typeof e=="function"?e=KZn(e):e=BOt(e);for(var t=this._groups,n=t.length,r=[],s=[],a=0;a<n;++a)for(var i=t[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&(r.push(e.call(c,c.__data__,u,i)),s.push(c));return new tp(r,s)}function UOt(e){return function(){return this.matches(e)}}function qOt(e){return function(t){return t.matches(e)}}var JZn=Array.prototype.find;function eGn(e){return function(){return JZn.call(this.children,e)}}function tGn(){return this.firstElementChild}function nGn(e){return this.select(e==null?tGn:eGn(typeof e=="function"?e:qOt(e)))}var rGn=Array.prototype.filter;function sGn(){return Array.from(this.children)}function aGn(e){return function(){return rGn.call(this.children,e)}}function iGn(e){return this.selectAll(e==null?sGn:aGn(typeof e=="function"?e:qOt(e)))}function oGn(e){typeof e!="function"&&(e=UOt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new tp(r,this._parents)}function VOt(e){return new Array(e.length)}function lGn(){return new tp(this._enter||this._groups.map(VOt),this._parents)}function rU(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}rU.prototype={constructor:rU,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}};function cGn(e){return function(){return e}}function uGn(e,t,n,r,s,a){for(var i=0,l,c=t.length,u=a.length;i<u;++i)(l=t[i])?(l.__data__=a[i],r[i]=l):n[i]=new rU(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function dGn(e,t,n,r,s,a,i){var l,c,u=new Map,d=t.length,f=a.length,h=new Array(d),p;for(l=0;l<d;++l)(c=t[l])&&(h[l]=p=i.call(c,c.__data__,l,t)+"",u.has(p)?s[l]=c:u.set(p,c));for(l=0;l<f;++l)p=i.call(e,a[l],l,a)+"",(c=u.get(p))?(r[l]=c,c.__data__=a[l],u.delete(p)):n[l]=new rU(e,a[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(h[l])===c&&(s[l]=c)}function fGn(e){return e.__data__}function hGn(e,t){if(!arguments.length)return Array.from(this,fGn);var n=t?dGn:uGn,r=this._parents,s=this._groups;typeof e!="function"&&(e=cGn(e));for(var a=s.length,i=new Array(a),l=new Array(a),c=new Array(a),u=0;u<a;++u){var d=r[u],f=s[u],h=f.length,p=pGn(e.call(d,d&&d.__data__,u,r)),m=p.length,v=l[u]=new Array(m),y=i[u]=new Array(m),b=c[u]=new Array(h);n(d,f,v,y,b,p,t);for(var x=0,w=0,k,C;x<m;++x)if(k=v[x]){for(x>=w&&(w=x+1);!(C=y[w])&&++w<m;);k._next=C||null}}return i=new tp(i,r),i._enter=l,i._exit=c,i}function pGn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function mGn(){return new tp(this._exit||this._groups.map(VOt),this._parents)}function gGn(e,t,n){var r=this.enter(),s=this,a=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(s=t(s),s&&(s=s.selection())),n==null?a.remove():n(a),r&&s?r.merge(s).order():s}function vGn(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,s=n.length,a=r.length,i=Math.min(s,a),l=new Array(s),c=0;c<i;++c)for(var u=n[c],d=r[c],f=u.length,h=l[c]=new Array(f),p,m=0;m<f;++m)(p=u[m]||d[m])&&(h[m]=p);for(;c<s;++c)l[c]=n[c];return new tp(l,this._parents)}function yGn(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],s=r.length-1,a=r[s],i;--s>=0;)(i=r[s])&&(a&&i.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(i,a),a=i);return this}function bGn(e){e||(e=xGn);function t(f,h){return f&&h?e(f.__data__,h.__data__):!f-!h}for(var n=this._groups,r=n.length,s=new Array(r),a=0;a<r;++a){for(var i=n[a],l=i.length,c=s[a]=new Array(l),u,d=0;d<l;++d)(u=i[d])&&(c[d]=u);c.sort(t)}return new tp(s,this._parents).order()}function xGn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function wGn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function SGn(){return Array.from(this)}function kGn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length;s<a;++s){var i=r[s];if(i)return i}return null}function OGn(){let e=0;for(const t of this)++e;return e}function CGn(){return!this.node()}function _Gn(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var s=t[n],a=0,i=s.length,l;a<i;++a)(l=s[a])&&e.call(l,l.__data__,a,s);return this}function EGn(e){return function(){this.removeAttribute(e)}}function TGn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function jGn(e,t){return function(){this.setAttribute(e,t)}}function NGn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function IGn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function AGn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function RGn(e,t){var n=xW(e);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((t==null?n.local?TGn:EGn:typeof t=="function"?n.local?AGn:IGn:n.local?NGn:jGn)(n,t))}function HOt(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function PGn(e){return function(){this.style.removeProperty(e)}}function $Gn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function MGn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function DGn(e,t,n){return arguments.length>1?this.each((t==null?PGn:typeof t=="function"?MGn:$Gn)(e,t,n??"")):oN(this.node(),e)}function oN(e,t){return e.style.getPropertyValue(t)||HOt(e).getComputedStyle(e,null).getPropertyValue(t)}function LGn(e){return function(){delete this[e]}}function FGn(e,t){return function(){this[e]=t}}function zGn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function BGn(e,t){return arguments.length>1?this.each((t==null?LGn:typeof t=="function"?zGn:FGn)(e,t)):this.node()[e]}function WOt(e){return e.trim().split(/^|\s+/)}function AOe(e){return e.classList||new ZOt(e)}function ZOt(e){this._node=e,this._names=WOt(e.getAttribute("class")||"")}ZOt.prototype={add:function(e){var t=this._names.indexOf(e);t<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};function GOt(e,t){for(var n=AOe(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function QOt(e,t){for(var n=AOe(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function UGn(e){return function(){GOt(this,e)}}function qGn(e){return function(){QOt(this,e)}}function VGn(e,t){return function(){(t.apply(this,arguments)?GOt:QOt)(this,e)}}function HGn(e,t){var n=WOt(e+"");if(arguments.length<2){for(var r=AOe(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?VGn:t?UGn:qGn)(n,t))}function WGn(){this.textContent=""}function ZGn(e){return function(){this.textContent=e}}function GGn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function QGn(e){return arguments.length?this.each(e==null?WGn:(typeof e=="function"?GGn:ZGn)(e)):this.node().textContent}function YGn(){this.innerHTML=""}function KGn(e){return function(){this.innerHTML=e}}function XGn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function JGn(e){return arguments.length?this.each(e==null?YGn:(typeof e=="function"?XGn:KGn)(e)):this.node().innerHTML}function eQn(){this.nextSibling&&this.parentNode.appendChild(this)}function tQn(){return this.each(eQn)}function nQn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function rQn(){return this.each(nQn)}function sQn(e){var t=typeof e=="function"?e:zOt(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function aQn(){return null}function iQn(e,t){var n=typeof e=="function"?e:zOt(e),r=t==null?aQn:typeof t=="function"?t:IOe(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function oQn(){var e=this.parentNode;e&&e.removeChild(this)}function lQn(){return this.each(oQn)}function cQn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function uQn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function dQn(e){return this.select(e?uQn:cQn)}function fQn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function hQn(e){return function(t){e.call(this,t,this.__data__)}}function pQn(e){return e.trim().split(/^|\s+/).map(function(t){var n="",r=t.indexOf(".");return r>=0&&(n=t.slice(r+1),t=t.slice(0,r)),{type:t,name:n}})}function mQn(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,s=t.length,a;n<s;++n)a=t[n],(!e.type||a.type===e.type)&&a.name===e.name?this.removeEventListener(a.type,a.listener,a.options):t[++r]=a;++r?t.length=r:delete this.__on}}}function gQn(e,t,n){return function(){var r=this.__on,s,a=hQn(t);if(r){for(var i=0,l=r.length;i<l;++i)if((s=r[i]).type===e.type&&s.name===e.name){this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=a,s.options=n),s.value=t;return}}this.addEventListener(e.type,a,n),s={type:e.type,name:e.name,value:t,listener:a,options:n},r?r.push(s):this.__on=[s]}}function vQn(e,t,n){var r=pQn(e+""),s,a=r.length,i;if(arguments.length<2){var l=this.node().__on;if(l){for(var c=0,u=l.length,d;c<u;++c)for(s=0,d=l[c];s<a;++s)if((i=r[s]).type===d.type&&i.name===d.name)return d.value}return}for(l=t?gQn:mQn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function YOt(e,t,n){var r=HOt(e),s=r.CustomEvent;typeof s=="function"?s=new s(t,n):(s=r.document.createEvent("Event"),n?(s.initEvent(t,n.bubbles,n.cancelable),s.detail=n.detail):s.initEvent(t,!1,!1)),e.dispatchEvent(s)}function yQn(e,t){return function(){return YOt(this,e,t)}}function bQn(e,t){return function(){return YOt(this,e,t.apply(this,arguments))}}function xQn(e,t){return this.each((typeof t=="function"?bQn:yQn)(e,t))}function*wQn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length,i;s<a;++s)(i=r[s])&&(yield i)}var KOt=[null];function tp(e,t){this._groups=e,this._parents=t}function r4(){return new tp([[document.documentElement]],KOt)}function SQn(){return this}tp.prototype=r4.prototype={constructor:tp,select:GZn,selectAll:XZn,selectChild:nGn,selectChildren:iGn,filter:oGn,data:hGn,enter:lGn,exit:mGn,join:gGn,merge:vGn,selection:SQn,order:yGn,sort:bGn,call:wGn,nodes:SGn,node:kGn,size:OGn,empty:CGn,each:_Gn,attr:RGn,style:DGn,property:BGn,classed:HGn,text:QGn,html:JGn,raise:tQn,lower:rQn,append:sQn,insert:iQn,remove:lQn,clone:dQn,datum:fQn,on:vQn,dispatch:xQn,[Symbol.iterator]:wQn};function Eh(e){return typeof e=="string"?new tp([[document.querySelector(e)]],[document.documentElement]):new tp([[e]],KOt)}function kQn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function vg(e,t){if(e=kQn(e),t===void 0&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,r=r.matrixTransform(t.getScreenCTM().inverse()),[r.x,r.y]}if(t.getBoundingClientRect){var s=t.getBoundingClientRect();return[e.clientX-s.left-t.clientLeft,e.clientY-s.top-t.clientTop]}}return[e.pageX,e.pageY]}const OQn={passive:!1},BM={capture:!0,passive:!1};function yne(e){e.stopImmediatePropagation()}function dj(e){e.preventDefault(),e.stopImmediatePropagation()}function XOt(e){var t=e.document.documentElement,n=Eh(e).on("dragstart.drag",dj,BM);"onselectstart"in t?n.on("selectstart.drag",dj,BM):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function JOt(e,t){var n=e.document.documentElement,r=Eh(e).on("dragstart.drag",null);t&&(r.on("click.drag",dj,BM),setTimeout(function(){r.on("click.drag",null)},0)),"onselectstart"in n?r.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}const _F=e=>()=>e;function Pve(e,{sourceEvent:t,subject:n,target:r,identifier:s,active:a,x:i,y:l,dx:c,dy:u,dispatch:d}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:s,enumerable:!0,configurable:!0},active:{value:a,enumerable:!0,configurable:!0},x:{value:i,enumerable:!0,configurable:!0},y:{value:l,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:u,enumerable:!0,configurable:!0},_:{value:d}})}Pve.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function CQn(e){return!e.ctrlKey&&!e.button}function _Qn(){return this.parentNode}function EQn(e,t){return t??{x:e.x,y:e.y}}function TQn(){return navigator.maxTouchPoints||"ontouchstart"in this}function eCt(){var e=CQn,t=_Qn,n=EQn,r=TQn,s={},a=bW("start","drag","end"),i=0,l,c,u,d,f=0;function h(k){k.on("mousedown.drag",p).filter(r).on("touchstart.drag",y).on("touchmove.drag",b,OQn).on("touchend.drag touchcancel.drag",x).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function p(k,C){if(!(d||!e.call(this,k,C))){var _=w(this,t.call(this,k,C),k,C,"mouse");_&&(Eh(k.view).on("mousemove.drag",m,BM).on("mouseup.drag",v,BM),XOt(k.view),yne(k),u=!1,l=k.clientX,c=k.clientY,_("start",k))}}function m(k){if(dj(k),!u){var C=k.clientX-l,_=k.clientY-c;u=C*C+_*_>f}s.mouse("drag",k)}function v(k){Eh(k.view).on("mousemove.drag mouseup.drag",null),JOt(k.view,u),dj(k),s.mouse("end",k)}function y(k,C){if(e.call(this,k,C)){var _=k.changedTouches,T=t.call(this,k,C),E=_.length,N,I;for(N=0;N<E;++N)(I=w(this,T,k,C,_[N].identifier,_[N]))&&(yne(k),I("start",k,_[N]))}}function b(k){var C=k.changedTouches,_=C.length,T,E;for(T=0;T<_;++T)(E=s[C[T].identifier])&&(dj(k),E("drag",k,C[T]))}function x(k){var C=k.changedTouches,_=C.length,T,E;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),T=0;T<_;++T)(E=s[C[T].identifier])&&(yne(k),E("end",k,C[T]))}function w(k,C,_,T,E,N){var I=a.copy(),A=vg(N||_,C),P,L,D;if((D=n.call(k,new Pve("beforestart",{sourceEvent:_,target:h,identifier:E,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),T))!=null)return P=D.x-A[0]||0,L=D.y-A[1]||0,function B(H,q,z){var V=A,M;switch(H){case"start":s[E]=B,M=i++;break;case"end":delete s[E],--i;case"drag":A=vg(z||q,C),M=i;break}I.call(H,k,new Pve(H,{sourceEvent:q,subject:D,target:h,identifier:E,active:M,x:A[0]+P,y:A[1]+L,dx:A[0]-V[0],dy:A[1]-V[1],dispatch:I}),T)}}return h.filter=function(k){return arguments.length?(e=typeof k=="function"?k:_F(!!k),h):e},h.container=function(k){return arguments.length?(t=typeof k=="function"?k:_F(k),h):t},h.subject=function(k){return arguments.length?(n=typeof k=="function"?k:_F(k),h):n},h.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:_F(!!k),h):r},h.on=function(){var k=a.on.apply(a,arguments);return k===a?h:k},h.clickDistance=function(k){return arguments.length?(f=(k=+k)*k,h):Math.sqrt(f)},h}function ROe(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function tCt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function s4(){}var UM=.7,sU=1/UM,fj="\\s*([+-]?\\d+)\\s*",qM="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",my="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",jQn=/^#([0-9a-f]{3,8})$/,NQn=new RegExp(`^rgb\\(${fj},${fj},${fj}\\)$`),IQn=new RegExp(`^rgb\\(${my},${my},${my}\\)$`),AQn=new RegExp(`^rgba\\(${fj},${fj},${fj},${qM}\\)$`),RQn=new RegExp(`^rgba\\(${my},${my},${my},${qM}\\)$`),PQn=new RegExp(`^hsl\\(${qM},${my},${my}\\)$`),$Qn=new RegExp(`^hsla\\(${qM},${my},${my},${qM}\\)$`),W7e={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};ROe(s4,aC,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Z7e,formatHex:Z7e,formatHex8:MQn,formatHsl:DQn,formatRgb:G7e,toString:G7e});function Z7e(){return this.rgb().formatHex()}function MQn(){return this.rgb().formatHex8()}function DQn(){return nCt(this).formatHsl()}function G7e(){return this.rgb().formatRgb()}function aC(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=jQn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?Q7e(t):n===3?new jf(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?EF(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?EF(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=NQn.exec(e))?new jf(t[1],t[2],t[3],1):(t=IQn.exec(e))?new jf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=AQn.exec(e))?EF(t[1],t[2],t[3],t[4]):(t=RQn.exec(e))?EF(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=PQn.exec(e))?X7e(t[1],t[2]/100,t[3]/100,1):(t=$Qn.exec(e))?X7e(t[1],t[2]/100,t[3]/100,t[4]):W7e.hasOwnProperty(e)?Q7e(W7e[e]):e==="transparent"?new jf(NaN,NaN,NaN,0):null}function Q7e(e){return new jf(e>>16&255,e>>8&255,e&255,1)}function EF(e,t,n,r){return r<=0&&(e=t=n=NaN),new jf(e,t,n,r)}function LQn(e){return e instanceof s4||(e=aC(e)),e?(e=e.rgb(),new jf(e.r,e.g,e.b,e.opacity)):new jf}function $ve(e,t,n,r){return arguments.length===1?LQn(e):new jf(e,t,n,r??1)}function jf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}ROe(jf,$ve,tCt(s4,{brighter(e){return e=e==null?sU:Math.pow(sU,e),new jf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?UM:Math.pow(UM,e),new jf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new jf(dO(this.r),dO(this.g),dO(this.b),aU(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Y7e,formatHex:Y7e,formatHex8:FQn,formatRgb:K7e,toString:K7e}));function Y7e(){return`#${Hk(this.r)}${Hk(this.g)}${Hk(this.b)}`}function FQn(){return`#${Hk(this.r)}${Hk(this.g)}${Hk(this.b)}${Hk((isNaN(this.opacity)?1:this.opacity)*255)}`}function K7e(){const e=aU(this.opacity);return`${e===1?"rgb(":"rgba("}${dO(this.r)}, ${dO(this.g)}, ${dO(this.b)}${e===1?")":`, ${e})`}`}function aU(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function dO(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Hk(e){return e=dO(e),(e<16?"0":"")+e.toString(16)}function X7e(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Og(e,t,n,r)}function nCt(e){if(e instanceof Og)return new Og(e.h,e.s,e.l,e.opacity);if(e instanceof s4||(e=aC(e)),!e)return new Og;if(e instanceof Og)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,s=Math.min(t,n,r),a=Math.max(t,n,r),i=NaN,l=a-s,c=(a+s)/2;return l?(t===a?i=(n-r)/l+(n<r)*6:n===a?i=(r-t)/l+2:i=(t-n)/l+4,l/=c<.5?a+s:2-a-s,i*=60):l=c>0&&c<1?0:i,new Og(i,l,c,e.opacity)}function zQn(e,t,n,r){return arguments.length===1?nCt(e):new Og(e,t,n,r??1)}function Og(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}ROe(Og,zQn,tCt(s4,{brighter(e){return e=e==null?sU:Math.pow(sU,e),new Og(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?UM:Math.pow(UM,e),new Og(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,s=2*n-r;return new jf(bne(e>=240?e-240:e+120,s,r),bne(e,s,r),bne(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new Og(J7e(this.h),TF(this.s),TF(this.l),aU(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=aU(this.opacity);return`${e===1?"hsl(":"hsla("}${J7e(this.h)}, ${TF(this.s)*100}%, ${TF(this.l)*100}%${e===1?")":`, ${e})`}`}}));function J7e(e){return e=(e||0)%360,e<0?e+360:e}function TF(e){return Math.max(0,Math.min(1,e||0))}function bne(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}const POe=e=>()=>e;function BQn(e,t){return function(n){return e+n*t}}function UQn(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(r){return Math.pow(e+r*t,n)}}function qQn(e){return(e=+e)==1?rCt:function(t,n){return n-t?UQn(t,n,e):POe(isNaN(t)?n:t)}}function rCt(e,t){var n=t-e;return n?BQn(e,n):POe(isNaN(e)?t:e)}const iU=(function e(t){var n=qQn(t);function r(s,a){var i=n((s=$ve(s)).r,(a=$ve(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=rCt(s.opacity,a.opacity);return function(d){return s.r=i(d),s.g=l(d),s.b=c(d),s.opacity=u(d),s+""}}return r.gamma=e,r})(1);function VQn(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),s;return function(a){for(s=0;s<n;++s)r[s]=e[s]*(1-a)+t[s]*a;return r}}function HQn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function WQn(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,s=new Array(r),a=new Array(n),i;for(i=0;i<r;++i)s[i]=bx(e[i],t[i]);for(;i<n;++i)a[i]=t[i];return function(l){for(i=0;i<r;++i)a[i]=s[i](l);return a}}function ZQn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function bg(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function GQn(e,t){var n={},r={},s;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(s in t)s in e?n[s]=bx(e[s],t[s]):r[s]=t[s];return function(a){for(s in n)r[s]=n[s](a);return r}}var Mve=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,xne=new RegExp(Mve.source,"g");function QQn(e){return function(){return e}}function YQn(e){return function(t){return e(t)+""}}function sCt(e,t){var n=Mve.lastIndex=xne.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Mve.exec(e))&&(s=xne.exec(t));)(a=s.index)>n&&(a=t.slice(n,a),l[i]?l[i]+=a:l[++i]=a),(r=r[0])===(s=s[0])?l[i]?l[i]+=s:l[++i]=s:(l[++i]=null,c.push({i,x:bg(r,s)})),n=xne.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?YQn(c[0].x):QQn(t):(t=c.length,function(u){for(var d=0,f;d<t;++d)l[(f=c[d]).i]=f.x(u);return l.join("")})}function bx(e,t){var n=typeof t,r;return t==null||n==="boolean"?POe(t):(n==="number"?bg:n==="string"?(r=aC(t))?(t=r,iU):sCt:t instanceof aC?iU:t instanceof Date?ZQn:HQn(t)?VQn:Array.isArray(t)?WQn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?GQn:bg)(e,t)}function $Oe(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var eBe=180/Math.PI,Dve={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function aCt(e,t,n,r,s,a){var i,l,c;return(i=Math.sqrt(e*e+t*t))&&(e/=i,t/=i),(c=e*n+t*r)&&(n-=e*c,r-=t*c),(l=Math.sqrt(n*n+r*r))&&(n/=l,r/=l,c/=l),e*r<t*n&&(e=-e,t=-t,c=-c,i=-i),{translateX:s,translateY:a,rotate:Math.atan2(t,e)*eBe,skewX:Math.atan(c)*eBe,scaleX:i,scaleY:l}}var jF;function KQn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Dve:aCt(t.a,t.b,t.c,t.d,t.e,t.f)}function XQn(e){return e==null||(jF||(jF=document.createElementNS("http://www.w3.org/2000/svg","g")),jF.setAttribute("transform",e),!(e=jF.transform.baseVal.consolidate()))?Dve:(e=e.matrix,aCt(e.a,e.b,e.c,e.d,e.e,e.f))}function iCt(e,t,n,r){function s(u){return u.length?u.pop()+" ":""}function a(u,d,f,h,p,m){if(u!==f||d!==h){var v=p.push("translate(",null,t,null,n);m.push({i:v-4,x:bg(u,f)},{i:v-2,x:bg(d,h)})}else(f||h)&&p.push("translate("+f+t+h+n)}function i(u,d,f,h){u!==d?(u-d>180?d+=360:d-u>180&&(u+=360),h.push({i:f.push(s(f)+"rotate(",null,r)-2,x:bg(u,d)})):d&&f.push(s(f)+"rotate("+d+r)}function l(u,d,f,h){u!==d?h.push({i:f.push(s(f)+"skewX(",null,r)-2,x:bg(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,h,p,m){if(u!==f||d!==h){var v=p.push(s(p)+"scale(",null,",",null,")");m.push({i:v-4,x:bg(u,f)},{i:v-2,x:bg(d,h)})}else(f!==1||h!==1)&&p.push(s(p)+"scale("+f+","+h+")")}return function(u,d){var f=[],h=[];return u=e(u),d=e(d),a(u.translateX,u.translateY,d.translateX,d.translateY,f,h),i(u.rotate,d.rotate,f,h),l(u.skewX,d.skewX,f,h),c(u.scaleX,u.scaleY,d.scaleX,d.scaleY,f,h),u=d=null,function(p){for(var m=-1,v=h.length,y;++m<v;)f[(y=h[m]).i]=y.x(p);return f.join("")}}}var JQn=iCt(KQn,"px, ","px)","deg)"),eYn=iCt(XQn,", ",")",")"),tYn=1e-12;function tBe(e){return((e=Math.exp(e))+1/e)/2}function nYn(e){return((e=Math.exp(e))-1/e)/2}function rYn(e){return((e=Math.exp(2*e))-1)/(e+1)}const r9=(function e(t,n,r){function s(a,i){var l=a[0],c=a[1],u=a[2],d=i[0],f=i[1],h=i[2],p=d-l,m=f-c,v=p*p+m*m,y,b;if(v<tYn)b=Math.log(h/u)/t,y=function(T){return[l+T*p,c+T*m,u*Math.exp(t*T*b)]};else{var x=Math.sqrt(v),w=(h*h-u*u+r*v)/(2*u*n*x),k=(h*h-u*u-r*v)/(2*h*n*x),C=Math.log(Math.sqrt(w*w+1)-w),_=Math.log(Math.sqrt(k*k+1)-k);b=(_-C)/t,y=function(T){var E=T*b,N=tBe(C),I=u/(n*x)*(N*rYn(t*E+C)-nYn(C));return[l+I*p,c+I*m,u*N/tBe(t*E+C)]}}return y.duration=b*1e3*t/Math.SQRT2,y}return s.rho=function(a){var i=Math.max(.001,+a),l=i*i,c=l*l;return e(i,l,c)},s})(Math.SQRT2,2,4);function sYn(e,t){t===void 0&&(t=e,e=bx);for(var n=0,r=t.length-1,s=t[0],a=new Array(r<0?0:r);n<r;)a[n]=e(s,s=t[++n]);return function(i){var l=Math.max(0,Math.min(r-1,Math.floor(i*=r)));return a[l](i-l)}}var lN=0,r$=0,UR=0,oCt=1e3,oU,s$,lU=0,iC=0,wW=0,VM=typeof performance=="object"&&performance.now?performance:Date,lCt=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function MOe(){return iC||(lCt(aYn),iC=VM.now()+wW)}function aYn(){iC=0}function cU(){this._call=this._time=this._next=null}cU.prototype=cCt.prototype={constructor:cU,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?MOe():+n)+(t==null?0:+t),!this._next&&s$!==this&&(s$?s$._next=this:oU=this,s$=this),this._call=e,this._time=n,Lve()},stop:function(){this._call&&(this._call=null,this._time=1/0,Lve())}};function cCt(e,t,n){var r=new cU;return r.restart(e,t,n),r}function iYn(){MOe(),++lN;for(var e=oU,t;e;)(t=iC-e._time)>=0&&e._call.call(void 0,t),e=e._next;--lN}function nBe(){iC=(lU=VM.now())+wW,lN=r$=0;try{iYn()}finally{lN=0,lYn(),iC=0}}function oYn(){var e=VM.now(),t=e-lU;t>oCt&&(wW-=t,lU=e)}function lYn(){for(var e,t=oU,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:oU=n);s$=e,Lve(r)}function Lve(e){if(!lN){r$&&(r$=clearTimeout(r$));var t=e-iC;t>24?(e<1/0&&(r$=setTimeout(nBe,e-VM.now()-wW)),UR&&(UR=clearInterval(UR))):(UR||(lU=VM.now(),UR=setInterval(oYn,oCt)),lN=1,lCt(nBe))}}function rBe(e,t,n){var r=new cU;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var cYn=bW("start","end","cancel","interrupt"),uYn=[],uCt=0,sBe=1,Fve=2,s9=3,aBe=4,zve=5,a9=6;function SW(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;dYn(e,n,{name:t,index:r,group:s,on:cYn,tween:uYn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:uCt})}function DOe(e,t){var n=nv(e,t);if(n.state>uCt)throw new Error("too late; already scheduled");return n}function Wy(e,t){var n=nv(e,t);if(n.state>s9)throw new Error("too late; already running");return n}function nv(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function dYn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=cCt(a,0,n.time);function a(u){n.state=sBe,n.timer.restart(i,n.delay,n.time),n.delay<=u&&i(u-n.delay)}function i(u){var d,f,h,p;if(n.state!==sBe)return c();for(d in r)if(p=r[d],p.name===n.name){if(p.state===s9)return rBe(i);p.state===aBe?(p.state=a9,p.timer.stop(),p.on.call("interrupt",e,e.__data__,p.index,p.group),delete r[d]):+d<t&&(p.state=a9,p.timer.stop(),p.on.call("cancel",e,e.__data__,p.index,p.group),delete r[d])}if(rBe(function(){n.state===s9&&(n.state=aBe,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Fve,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Fve){for(n.state=s9,s=new Array(h=n.tween.length),d=0,f=-1;d<h;++d)(p=n.tween[d].value.call(e,e.__data__,n.index,n.group))&&(s[++f]=p);s.length=f+1}}function l(u){for(var d=u<n.duration?n.ease.call(null,u/n.duration):(n.timer.restart(c),n.state=zve,1),f=-1,h=s.length;++f<h;)s[f].call(e,d);n.state===zve&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=a9,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function i9(e,t){var n=e.__transition,r,s,a=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((r=n[i]).name!==t){a=!1;continue}s=r.state>Fve&&r.state<zve,r.state=a9,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function fYn(e){return this.each(function(){i9(this,e)})}function hYn(e,t){var n,r;return function(){var s=Wy(this,e),a=s.tween;if(a!==n){r=n=a;for(var i=0,l=r.length;i<l;++i)if(r[i].name===t){r=r.slice(),r.splice(i,1);break}}s.tween=r}}function pYn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=Wy(this,e),i=a.tween;if(i!==r){s=(r=i).slice();for(var l={name:t,value:n},c=0,u=s.length;c<u;++c)if(s[c].name===t){s[c]=l;break}c===u&&s.push(l)}a.tween=s}}function mYn(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=nv(this.node(),n).tween,s=0,a=r.length,i;s<a;++s)if((i=r[s]).name===e)return i.value;return null}return this.each((t==null?hYn:pYn)(n,e,t))}function LOe(e,t,n){var r=e._id;return e.each(function(){var s=Wy(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return nv(s,r).value[t]}}function dCt(e,t){var n;return(typeof t=="number"?bg:t instanceof aC?iU:(n=aC(t))?(t=n,iU):sCt)(e,t)}function gYn(e){return function(){this.removeAttribute(e)}}function vYn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function yYn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttribute(e);return i===s?null:i===r?a:a=t(r=i,n)}}function bYn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttributeNS(e.space,e.local);return i===s?null:i===r?a:a=t(r=i,n)}}function xYn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttribute(e):(i=this.getAttribute(e),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function wYn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttributeNS(e.space,e.local):(i=this.getAttributeNS(e.space,e.local),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function SYn(e,t){var n=xW(e),r=n==="transform"?eYn:dCt;return this.attrTween(e,typeof t=="function"?(n.local?wYn:xYn)(n,r,LOe(this,"attr."+e,t)):t==null?(n.local?vYn:gYn)(n):(n.local?bYn:yYn)(n,r,t))}function kYn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function OYn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function CYn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&OYn(e,a)),n}return s._value=t,s}function _Yn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&kYn(e,a)),n}return s._value=t,s}function EYn(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(t==null)return this.tween(n,null);if(typeof t!="function")throw new Error;var r=xW(e);return this.tween(n,(r.local?CYn:_Yn)(r,t))}function TYn(e,t){return function(){DOe(this,e).delay=+t.apply(this,arguments)}}function jYn(e,t){return t=+t,function(){DOe(this,e).delay=t}}function NYn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?TYn:jYn)(t,e)):nv(this.node(),t).delay}function IYn(e,t){return function(){Wy(this,e).duration=+t.apply(this,arguments)}}function AYn(e,t){return t=+t,function(){Wy(this,e).duration=t}}function RYn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?IYn:AYn)(t,e)):nv(this.node(),t).duration}function PYn(e,t){if(typeof t!="function")throw new Error;return function(){Wy(this,e).ease=t}}function $Yn(e){var t=this._id;return arguments.length?this.each(PYn(t,e)):nv(this.node(),t).ease}function MYn(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Wy(this,e).ease=n}}function DYn(e){if(typeof e!="function")throw new Error;return this.each(MYn(this._id,e))}function LYn(e){typeof e!="function"&&(e=UOt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new Fx(r,this._parents,this._name,this._id)}function FYn(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,s=n.length,a=Math.min(r,s),i=new Array(r),l=0;l<a;++l)for(var c=t[l],u=n[l],d=c.length,f=i[l]=new Array(d),h,p=0;p<d;++p)(h=c[p]||u[p])&&(f[p]=h);for(;l<r;++l)i[l]=t[l];return new Fx(i,this._parents,this._name,this._id)}function zYn(e){return(e+"").trim().split(/^|\s+/).every(function(t){var n=t.indexOf(".");return n>=0&&(t=t.slice(0,n)),!t||t==="start"})}function BYn(e,t,n){var r,s,a=zYn(t)?DOe:Wy;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function UYn(e,t){var n=this._id;return arguments.length<2?nv(this.node(),n).on.on(e):this.each(BYn(n,e,t))}function qYn(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function VYn(){return this.on("end.remove",qYn(this._id))}function HYn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=IOe(e));for(var r=this._groups,s=r.length,a=new Array(s),i=0;i<s;++i)for(var l=r[i],c=l.length,u=a[i]=new Array(c),d,f,h=0;h<c;++h)(d=l[h])&&(f=e.call(d,d.__data__,h,l))&&("__data__"in d&&(f.__data__=d.__data__),u[h]=f,SW(u[h],t,n,h,u,nv(d,n)));return new Fx(a,this._parents,t,n)}function WYn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=BOt(e));for(var r=this._groups,s=r.length,a=[],i=[],l=0;l<s;++l)for(var c=r[l],u=c.length,d,f=0;f<u;++f)if(d=c[f]){for(var h=e.call(d,d.__data__,f,c),p,m=nv(d,n),v=0,y=h.length;v<y;++v)(p=h[v])&&SW(p,t,n,v,h,m);a.push(h),i.push(d)}return new Fx(a,i,t,n)}var ZYn=r4.prototype.constructor;function GYn(){return new ZYn(this._groups,this._parents)}function QYn(e,t){var n,r,s;return function(){var a=oN(this,e),i=(this.style.removeProperty(e),oN(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function fCt(e){return function(){this.style.removeProperty(e)}}function YYn(e,t,n){var r,s=n+"",a;return function(){var i=oN(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function KYn(e,t,n){var r,s,a;return function(){var i=oN(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),oN(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function XYn(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=Wy(this,e),u=c.on,d=c.value[a]==null?l||(l=fCt(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function JYn(e,t,n){var r=(e+="")=="transform"?JQn:dCt;return t==null?this.styleTween(e,QYn(e,r)).on("end.style."+e,fCt(e)):typeof t=="function"?this.styleTween(e,KYn(e,r,LOe(this,"style."+e,t))).each(XYn(this._id,e)):this.styleTween(e,YYn(e,r,t),n).on("end.style."+e,null)}function eKn(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function tKn(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&eKn(e,i,n)),r}return a._value=t,a}function nKn(e,t,n){var r="style."+(e+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(t==null)return this.tween(r,null);if(typeof t!="function")throw new Error;return this.tween(r,tKn(e,t,n??""))}function rKn(e){return function(){this.textContent=e}}function sKn(e){return function(){var t=e(this);this.textContent=t??""}}function aKn(e){return this.tween("text",typeof e=="function"?sKn(LOe(this,"text",e)):rKn(e==null?"":e+""))}function iKn(e){return function(t){this.textContent=e.call(this,t)}}function oKn(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&iKn(s)),t}return r._value=e,r}function lKn(e){var t="text";if(arguments.length<1)return(t=this.tween(t))&&t._value;if(e==null)return this.tween(t,null);if(typeof e!="function")throw new Error;return this.tween(t,oKn(e))}function cKn(){for(var e=this._name,t=this._id,n=hCt(),r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)if(c=i[u]){var d=nv(c,t);SW(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new Fx(r,this._parents,e,n)}function uKn(){var e,t,n=this,r=n._id,s=n.size();return new Promise(function(a,i){var l={value:i},c={value:function(){--s===0&&a()}};n.each(function(){var u=Wy(this,r),d=u.on;d!==e&&(t=(e=d).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(c)),u.on=t}),s===0&&a()})}var dKn=0;function Fx(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function hCt(){return++dKn}var Tb=r4.prototype;Fx.prototype={constructor:Fx,select:HYn,selectAll:WYn,selectChild:Tb.selectChild,selectChildren:Tb.selectChildren,filter:LYn,merge:FYn,selection:GYn,transition:cKn,call:Tb.call,nodes:Tb.nodes,node:Tb.node,size:Tb.size,empty:Tb.empty,each:Tb.each,on:UYn,attr:SYn,attrTween:EYn,style:JYn,styleTween:nKn,text:aKn,textTween:lKn,remove:VYn,tween:mYn,delay:NYn,duration:RYn,ease:$Yn,easeVarying:DYn,end:uKn,[Symbol.iterator]:Tb[Symbol.iterator]};function fKn(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var hKn={time:null,delay:0,duration:250,ease:fKn};function pKn(e,t){for(var n;!(n=e.__transition)||!(n=n[t]);)if(!(e=e.parentNode))throw new Error(`transition ${t} not found`);return n}function mKn(e){var t,n;e instanceof Fx?(t=e._id,e=e._name):(t=hCt(),(n=hKn).time=MOe(),e=e==null?null:e+"");for(var r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&SW(c,e,t,u,i,n||pKn(c,t));return new Fx(r,this._parents,e,t)}r4.prototype.interrupt=fYn;r4.prototype.transition=mKn;const NF=e=>()=>e;function gKn(e,{sourceEvent:t,target:n,transform:r,dispatch:s}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:s}})}function ix(e,t,n){this.k=e,this.x=t,this.y=n}ix.prototype={constructor:ix,scale:function(e){return e===1?this:new ix(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new ix(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var kW=new ix(1,0,0);pCt.prototype=ix.prototype;function pCt(e){for(;!e.__zoom;)if(!(e=e.parentNode))return kW;return e.__zoom}function wne(e){e.stopImmediatePropagation()}function qR(e){e.preventDefault(),e.stopImmediatePropagation()}function vKn(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function yKn(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e,e.hasAttribute("viewBox")?(e=e.viewBox.baseVal,[[e.x,e.y],[e.x+e.width,e.y+e.height]]):[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]):[[0,0],[e.clientWidth,e.clientHeight]]}function iBe(){return this.__zoom||kW}function bKn(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function xKn(){return navigator.maxTouchPoints||"ontouchstart"in this}function wKn(e,t,n){var r=e.invertX(t[0][0])-n[0][0],s=e.invertX(t[1][0])-n[1][0],a=e.invertY(t[0][1])-n[0][1],i=e.invertY(t[1][1])-n[1][1];return e.translate(s>r?(r+s)/2:Math.min(0,r)||Math.max(0,s),i>a?(a+i)/2:Math.min(0,a)||Math.max(0,i))}function mCt(){var e=vKn,t=yKn,n=wKn,r=bKn,s=xKn,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=r9,u=bW("start","zoom","end"),d,f,h,p=500,m=150,v=0,y=10;function b(D){D.property("__zoom",iBe).on("wheel.zoom",E,{passive:!1}).on("mousedown.zoom",N).on("dblclick.zoom",I).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",P).on("touchend.zoom touchcancel.zoom",L).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(D,B,H,q){var z=D.selection?D.selection():D;z.property("__zoom",iBe),D!==z?C(D,B,H,q):z.interrupt().each(function(){_(this,arguments).event(q).start().zoom(null,typeof B=="function"?B.apply(this,arguments):B).end()})},b.scaleBy=function(D,B,H,q){b.scaleTo(D,function(){var z=this.__zoom.k,V=typeof B=="function"?B.apply(this,arguments):B;return z*V},H,q)},b.scaleTo=function(D,B,H,q){b.transform(D,function(){var z=t.apply(this,arguments),V=this.__zoom,M=H==null?k(z):typeof H=="function"?H.apply(this,arguments):H,G=V.invert(M),F=typeof B=="function"?B.apply(this,arguments):B;return n(w(x(V,F),M,G),z,i)},H,q)},b.translateBy=function(D,B,H,q){b.transform(D,function(){return n(this.__zoom.translate(typeof B=="function"?B.apply(this,arguments):B,typeof H=="function"?H.apply(this,arguments):H),t.apply(this,arguments),i)},null,q)},b.translateTo=function(D,B,H,q,z){b.transform(D,function(){var V=t.apply(this,arguments),M=this.__zoom,G=q==null?k(V):typeof q=="function"?q.apply(this,arguments):q;return n(kW.translate(G[0],G[1]).scale(M.k).translate(typeof B=="function"?-B.apply(this,arguments):-B,typeof H=="function"?-H.apply(this,arguments):-H),V,i)},q,z)};function x(D,B){return B=Math.max(a[0],Math.min(a[1],B)),B===D.k?D:new ix(B,D.x,D.y)}function w(D,B,H){var q=B[0]-H[0]*D.k,z=B[1]-H[1]*D.k;return q===D.x&&z===D.y?D:new ix(D.k,q,z)}function k(D){return[(+D[0][0]+ +D[1][0])/2,(+D[0][1]+ +D[1][1])/2]}function C(D,B,H,q){D.on("start.zoom",function(){_(this,arguments).event(q).start()}).on("interrupt.zoom end.zoom",function(){_(this,arguments).event(q).end()}).tween("zoom",function(){var z=this,V=arguments,M=_(z,V).event(q),G=t.apply(z,V),F=H==null?k(G):typeof H=="function"?H.apply(z,V):H,R=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),U=z.__zoom,Z=typeof B=="function"?B.apply(z,V):B,Y=c(U.invert(F).concat(R/U.k),Z.invert(F).concat(R/Z.k));return function(te){if(te===1)te=Z;else{var J=Y(te),ee=R/J[2];te=new ix(ee,F[0]-J[0]*ee,F[1]-J[1]*ee)}M.zoom(null,te)}})}function _(D,B,H){return!H&&D.__zooming||new T(D,B)}function T(D,B){this.that=D,this.args=B,this.active=0,this.sourceEvent=null,this.extent=t.apply(D,B),this.taps=0}T.prototype={event:function(D){return D&&(this.sourceEvent=D),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(D,B){return this.mouse&&D!=="mouse"&&(this.mouse[1]=B.invert(this.mouse[0])),this.touch0&&D!=="touch"&&(this.touch0[1]=B.invert(this.touch0[0])),this.touch1&&D!=="touch"&&(this.touch1[1]=B.invert(this.touch1[0])),this.that.__zoom=B,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(D){var B=Eh(this.that).datum();u.call(D,this.that,new gKn(D,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),B)}};function E(D,...B){if(!e.apply(this,arguments))return;var H=_(this,B).event(D),q=this.__zoom,z=Math.max(a[0],Math.min(a[1],q.k*Math.pow(2,r.apply(this,arguments)))),V=vg(D);if(H.wheel)(H.mouse[0][0]!==V[0]||H.mouse[0][1]!==V[1])&&(H.mouse[1]=q.invert(H.mouse[0]=V)),clearTimeout(H.wheel);else{if(q.k===z)return;H.mouse=[V,q.invert(V)],i9(this),H.start()}qR(D),H.wheel=setTimeout(M,m),H.zoom("mouse",n(w(x(q,z),H.mouse[0],H.mouse[1]),H.extent,i));function M(){H.wheel=null,H.end()}}function N(D,...B){if(h||!e.apply(this,arguments))return;var H=D.currentTarget,q=_(this,B,!0).event(D),z=Eh(D.view).on("mousemove.zoom",F,!0).on("mouseup.zoom",R,!0),V=vg(D,H),M=D.clientX,G=D.clientY;XOt(D.view),wne(D),q.mouse=[V,this.__zoom.invert(V)],i9(this),q.start();function F(U){if(qR(U),!q.moved){var Z=U.clientX-M,Y=U.clientY-G;q.moved=Z*Z+Y*Y>v}q.event(U).zoom("mouse",n(w(q.that.__zoom,q.mouse[0]=vg(U,H),q.mouse[1]),q.extent,i))}function R(U){z.on("mousemove.zoom mouseup.zoom",null),JOt(U.view,q.moved),qR(U),q.event(U).end()}}function I(D,...B){if(e.apply(this,arguments)){var H=this.__zoom,q=vg(D.changedTouches?D.changedTouches[0]:D,this),z=H.invert(q),V=H.k*(D.shiftKey?.5:2),M=n(w(x(H,V),q,z),t.apply(this,B),i);qR(D),l>0?Eh(this).transition().duration(l).call(C,M,q,D):Eh(this).call(b.transform,M,q,D)}}function A(D,...B){if(e.apply(this,arguments)){var H=D.touches,q=H.length,z=_(this,B,D.changedTouches.length===q).event(D),V,M,G,F;for(wne(D),M=0;M<q;++M)G=H[M],F=vg(G,this),F=[F,this.__zoom.invert(F),G.identifier],z.touch0?!z.touch1&&z.touch0[2]!==F[2]&&(z.touch1=F,z.taps=0):(z.touch0=F,V=!0,z.taps=1+!!d);d&&(d=clearTimeout(d)),V&&(z.taps<2&&(f=F[0],d=setTimeout(function(){d=null},p)),i9(this),z.start())}}function P(D,...B){if(this.__zooming){var H=_(this,B).event(D),q=D.changedTouches,z=q.length,V,M,G,F;for(qR(D),V=0;V<z;++V)M=q[V],G=vg(M,this),H.touch0&&H.touch0[2]===M.identifier?H.touch0[0]=G:H.touch1&&H.touch1[2]===M.identifier&&(H.touch1[0]=G);if(M=H.that.__zoom,H.touch1){var R=H.touch0[0],U=H.touch0[1],Z=H.touch1[0],Y=H.touch1[1],te=(te=Z[0]-R[0])*te+(te=Z[1]-R[1])*te,J=(J=Y[0]-U[0])*J+(J=Y[1]-U[1])*J;M=x(M,Math.sqrt(te/J)),G=[(R[0]+Z[0])/2,(R[1]+Z[1])/2],F=[(U[0]+Y[0])/2,(U[1]+Y[1])/2]}else if(H.touch0)G=H.touch0[0],F=H.touch0[1];else return;H.zoom("touch",n(w(M,G,F),H.extent,i))}}function L(D,...B){if(this.__zooming){var H=_(this,B).event(D),q=D.changedTouches,z=q.length,V,M;for(wne(D),h&&clearTimeout(h),h=setTimeout(function(){h=null},p),V=0;V<z;++V)M=q[V],H.touch0&&H.touch0[2]===M.identifier?delete H.touch0:H.touch1&&H.touch1[2]===M.identifier&&delete H.touch1;if(H.touch1&&!H.touch0&&(H.touch0=H.touch1,delete H.touch1),H.touch0)H.touch0[1]=this.__zoom.invert(H.touch0[0]);else if(H.end(),H.taps===2&&(M=vg(M,this),Math.hypot(f[0]-M[0],f[1]-M[1])<y)){var G=Eh(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(D){return arguments.length?(r=typeof D=="function"?D:NF(+D),b):r},b.filter=function(D){return arguments.length?(e=typeof D=="function"?D:NF(!!D),b):e},b.touchable=function(D){return arguments.length?(s=typeof D=="function"?D:NF(!!D),b):s},b.extent=function(D){return arguments.length?(t=typeof D=="function"?D:NF([[+D[0][0],+D[0][1]],[+D[1][0],+D[1][1]]]),b):t},b.scaleExtent=function(D){return arguments.length?(a[0]=+D[0],a[1]=+D[1],b):[a[0],a[1]]},b.translateExtent=function(D){return arguments.length?(i[0][0]=+D[0][0],i[1][0]=+D[1][0],i[0][1]=+D[0][1],i[1][1]=+D[1][1],b):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},b.constrain=function(D){return arguments.length?(n=D,b):n},b.duration=function(D){return arguments.length?(l=+D,b):l},b.interpolate=function(D){return arguments.length?(c=D,b):c},b.on=function(){var D=u.on.apply(u,arguments);return D===u?b:D},b.clickDistance=function(D){return arguments.length?(v=(D=+D)*D,b):Math.sqrt(v)},b.tapDistance=function(D){return arguments.length?(y=+D,b):y},b}const Ty={error001:()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>"The React Flow parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,{id:t,sourceHandle:n,targetHandle:r})=>`Couldn't create edge for ${e} handle id: "${e==="source"?n:r}", edge id: ${t}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(e="react")=>`It seems that you haven't loaded the styles. Please import '@xyflow/${e}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>"useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.",error015:()=>"It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs."},HM=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],gCt=["Enter"," ","Escape"],vCt={"node.a11yDescription.default":"Press enter or space to select a node. Press delete to remove it and escape to cancel.","node.a11yDescription.keyboardDisabled":"Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.","node.a11yDescription.ariaLiveMessage":({direction:e,x:t,y:n})=>`Moved selected node ${e}. New position, x: ${t}, y: ${n}`,"edge.a11yDescription.default":"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.","controls.ariaLabel":"Control Panel","controls.zoomIn.ariaLabel":"Zoom In","controls.zoomOut.ariaLabel":"Zoom Out","controls.fitView.ariaLabel":"Fit View","controls.interactive.ariaLabel":"Toggle Interactivity","minimap.ariaLabel":"Mini Map","handle.ariaLabel":"Handle"};var cN;(function(e){e.Strict="strict",e.Loose="loose"})(cN||(cN={}));var fO;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(fO||(fO={}));var WM;(function(e){e.Partial="partial",e.Full="full"})(WM||(WM={}));const yCt={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var Ew;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(Ew||(Ew={}));var ZM;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(ZM||(ZM={}));var nr;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(nr||(nr={}));const oBe={[nr.Left]:nr.Right,[nr.Right]:nr.Left,[nr.Top]:nr.Bottom,[nr.Bottom]:nr.Top};function bCt(e){return e===null?null:e?"valid":"invalid"}const xCt=e=>"id"in e&&"source"in e&&"target"in e,SKn=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),FOe=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),a4=(e,t=[0,0])=>{const{width:n,height:r}=l0(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},kKn=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,s)=>{const a=typeof s=="string";let i=!t.nodeLookup&&!a?s:void 0;t.nodeLookup&&(i=a?t.nodeLookup.get(s):FOe(s)?s:t.nodeLookup.get(s.id));const l=i?uU(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return OW(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return CW(n)},i4=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},r=!1;return e.forEach(s=>{(t.filter===void 0||t.filter(s))&&(n=OW(n,uU(s)),r=!0)}),r?CW(n):{x:0,y:0,width:0,height:0}},zOe=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...l4(t,[n,r,s]),width:t.width/s,height:t.height/s},c=[];for(const u of e.values()){const{measured:d,selectable:f=!0,hidden:h=!1}=u;if(i&&!f||h)continue;const p=d.width??u.width??u.initialWidth??null,m=d.height??u.height??u.initialHeight??null,v=GM(l,dN(u)),y=(p??0)*(m??0),b=a&&v>0;(!u.internals.handleBounds||b||v>=y||u.dragging)&&c.push(u)}return c},OKn=(e,t)=>{const n=new Set;return e.forEach(r=>{n.add(r.id)}),t.filter(r=>n.has(r.source)||n.has(r.target))};function CKn(e,t){const n=new Map,r=t?.nodes?new Set(t.nodes.map(s=>s.id)):null;return e.forEach(s=>{s.measured.width&&s.measured.height&&(t?.includeHiddenNodes||!s.hidden)&&(!r||r.has(s.id))&&n.set(s.id,s)}),n}async function _Kn({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=CKn(e,i),c=i4(l),u=BOe(c,t,n,i?.minZoom??s,i?.maxZoom??a,i?.padding??.1);return await r.setViewport(u,{duration:i?.duration,ease:i?.ease,interpolate:i?.interpolate}),Promise.resolve(!0)}function wCt({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:s,onError:a}){const i=n.get(e),l=i.parentId?n.get(i.parentId):void 0,{x:c,y:u}=l?l.internals.positionAbsolute:{x:0,y:0},d=i.origin??r;let f=i.extent||s;if(i.extent==="parent"&&!i.expandParent)if(!l)a?.("005",Ty.error005());else{const p=l.measured.width,m=l.measured.height;p&&m&&(f=[[c,u],[c+p,u+m]])}else l&&fN(i.extent)&&(f=[[i.extent[0][0]+c,i.extent[0][1]+u],[i.extent[1][0]+c,i.extent[1][1]+u]]);const h=fN(f)?oC(t,f,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&a?.("015",Ty.error015()),{position:{x:h.x-c+(i.measured.width??0)*d[0],y:h.y-u+(i.measured.height??0)*d[1]},positionAbsolute:h}}async function EKn({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const a=new Set(e.map(h=>h.id)),i=[];for(const h of n){if(h.deletable===!1)continue;const p=a.has(h.id),m=!p&&h.parentId&&i.find(v=>v.id===h.parentId);(p||m)&&i.push(h)}const l=new Set(t.map(h=>h.id)),c=r.filter(h=>h.deletable!==!1),d=OKn(i,c);for(const h of c)l.has(h.id)&&!d.find(m=>m.id===h.id)&&d.push(h);if(!s)return{edges:d,nodes:i};const f=await s({nodes:i,edges:d});return typeof f=="boolean"?f?{edges:d,nodes:i}:{edges:[],nodes:[]}:f}const uN=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),oC=(e={x:0,y:0},t,n)=>({x:uN(e.x,t[0][0],t[1][0]-(n?.width??0)),y:uN(e.y,t[0][1],t[1][1]-(n?.height??0))});function SCt(e,t,n){const{width:r,height:s}=l0(n),{x:a,y:i}=n.internals.positionAbsolute;return oC(e,[[a,i],[a+r,i+s]],t)}const lBe=(e,t,n)=>e<t?uN(Math.abs(e-t),1,t)/t:e>n?-uN(Math.abs(e-n),1,t)/t:0,kCt=(e,t,n=15,r=40)=>{const s=lBe(e.x,r,t.width-r)*n,a=lBe(e.y,r,t.height-r)*n;return[s,a]},OW=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),Bve=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),CW=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),dN=(e,t=[0,0])=>{const{x:n,y:r}=FOe(e)?e.internals.positionAbsolute:a4(e,t);return{x:n,y:r,width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}},uU=(e,t=[0,0])=>{const{x:n,y:r}=FOe(e)?e.internals.positionAbsolute:a4(e,t);return{x:n,y:r,x2:n+(e.measured?.width??e.width??e.initialWidth??0),y2:r+(e.measured?.height??e.height??e.initialHeight??0)}},OCt=(e,t)=>CW(OW(Bve(e),Bve(t))),GM=(e,t)=>{const n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*r)},cBe=e=>jg(e.width)&&jg(e.height)&&jg(e.x)&&jg(e.y),jg=e=>!isNaN(e)&&isFinite(e),TKn=(e,t)=>{},o4=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),l4=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?o4(l,i):l},dU=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function SE(e,t){if(typeof e=="number")return Math.floor((t-t/(1+e))*.5);if(typeof e=="string"&&e.endsWith("px")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(n)}if(typeof e=="string"&&e.endsWith("%")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(t*n*.01)}return console.error(`[React Flow] The padding value "${e}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}function jKn(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=SE(e,n),s=SE(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=SE(e.top??e.y??0,n),s=SE(e.bottom??e.y??0,n),a=SE(e.left??e.x??0,t),i=SE(e.right??e.x??0,t);return{top:r,right:i,bottom:s,left:a,x:a+i,y:r+s}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function NKn(e,t,n,r,s,a){const{x:i,y:l}=dU(e,[t,n,r]),{x:c,y:u}=dU({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=s-c,f=a-u;return{left:Math.floor(i),top:Math.floor(l),right:Math.floor(d),bottom:Math.floor(f)}}const BOe=(e,t,n,r,s,a)=>{const i=jKn(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=uN(u,r,s),f=e.x+e.width/2,h=e.y+e.height/2,p=t/2-f*d,m=n/2-h*d,v=NKn(e,p,m,d,t,n),y={left:Math.min(v.left-i.left,0),top:Math.min(v.top-i.top,0),right:Math.min(v.right-i.right,0),bottom:Math.min(v.bottom-i.bottom,0)};return{x:p-y.left+y.right,y:m-y.top+y.bottom,zoom:d}},QM=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function fN(e){return e!=null&&e!=="parent"}function l0(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function CCt(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function _Ct(e,t={width:0,height:0},n,r,s){const a={...e},i=r.get(n);if(i){const l=i.origin||s;a.x+=i.internals.positionAbsolute.x-(t.width??0)*l[0],a.y+=i.internals.positionAbsolute.y-(t.height??0)*l[1]}return a}function uBe(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function IKn(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function AKn(e){return{...vCt,...e||{}}}function V$(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=Ng(e),l=l4({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?o4(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const UOe=e=>({width:e.offsetWidth,height:e.offsetHeight}),ECt=e=>e?.getRootNode?.()||window?.document,RKn=["INPUT","SELECT","TEXTAREA"];function TCt(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:RKn.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const jCt=e=>"clientX"in e,Ng=(e,t)=>{const n=jCt(e),r=n?e.clientX:e.touches?.[0].clientX,s=n?e.clientY:e.touches?.[0].clientY;return{x:r-(t?.left??0),y:s-(t?.top??0)}},dBe=(e,t,n,r,s)=>{const a=t.querySelectorAll(`.${e}`);return!a||!a.length?null:Array.from(a).map(i=>{const l=i.getBoundingClientRect();return{id:i.getAttribute("data-handleid"),type:e,nodeId:s,position:i.getAttribute("data-handlepos"),x:(l.left-n.left)/r,y:(l.top-n.top)/r,...UOe(i)}})};function NCt({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:s,sourceControlY:a,targetControlX:i,targetControlY:l}){const c=e*.125+s*.375+i*.375+n*.125,u=t*.125+a*.375+l*.375+r*.125,d=Math.abs(c-e),f=Math.abs(u-t);return[c,u,d,f]}function IF(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function fBe({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case nr.Left:return[t-IF(t-r,a),n];case nr.Right:return[t+IF(r-t,a),n];case nr.Top:return[t,n-IF(n-s,a)];case nr.Bottom:return[t,n+IF(s-n,a)]}}function qOe({sourceX:e,sourceY:t,sourcePosition:n=nr.Bottom,targetX:r,targetY:s,targetPosition:a=nr.Top,curvature:i=.25}){const[l,c]=fBe({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=fBe({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,h,p,m]=NCt({sourceX:e,sourceY:t,targetX:r,targetY:s,sourceControlX:l,sourceControlY:c,targetControlX:u,targetControlY:d});return[`M${e},${t} C${l},${c} ${u},${d} ${r},${s}`,f,h,p,m]}function ICt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const s=Math.abs(n-e)/2,a=n<e?n+s:n-s,i=Math.abs(r-t)/2,l=r<t?r+i:r-i;return[a,l,s,i]}function PKn({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:s=!1,zIndexMode:a="basic"}){if(a==="manual")return r;const i=s&&n?r+1e3:r,l=Math.max(e.parentId||s&&e.selected?e.internals.z:0,t.parentId||s&&t.selected?t.internals.z:0);return i+l}function $Kn({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=OW(uU(e),uU(t));a.x===a.x2&&(a.x2+=1),a.y===a.y2&&(a.y2+=1);const i={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:r/s[2]};return GM(i,CW(a))>0}const MKn=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,DKn=(e,t)=>t.some(n=>n.source===e.source&&n.target===e.target&&(n.sourceHandle===e.sourceHandle||!n.sourceHandle&&!e.sourceHandle)&&(n.targetHandle===e.targetHandle||!n.targetHandle&&!e.targetHandle)),LKn=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||MKn;let s;return xCt(e)?s={...e}:s={...e,id:r(e)},DKn(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function ACt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=ICt({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const hBe={[nr.Left]:{x:-1,y:0},[nr.Right]:{x:1,y:0},[nr.Top]:{x:0,y:-1},[nr.Bottom]:{x:0,y:1}},FKn=({source:e,sourcePosition:t=nr.Bottom,target:n})=>t===nr.Left||t===nr.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},pBe=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function zKn({source:e,sourcePosition:t=nr.Bottom,target:n,targetPosition:r=nr.Top,center:s,offset:a,stepPosition:i}){const l=hBe[t],c=hBe[r],u={x:e.x+l.x*a,y:e.y+l.y*a},d={x:n.x+c.x*a,y:n.y+c.y*a},f=FKn({source:u,sourcePosition:t,target:d}),h=f.x!==0?"x":"y",p=f[h];let m=[],v,y;const b={x:0,y:0},x={x:0,y:0},[,,w,k]=ICt({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[h]*c[h]===-1){h==="x"?(v=s.x??u.x+(d.x-u.x)*i,y=s.y??(u.y+d.y)/2):(v=s.x??(u.x+d.x)/2,y=s.y??u.y+(d.y-u.y)*i);const E=[{x:v,y:u.y},{x:v,y:d.y}],N=[{x:u.x,y},{x:d.x,y}];l[h]===p?m=h==="x"?E:N:m=h==="x"?N:E}else{const E=[{x:u.x,y:d.y}],N=[{x:d.x,y:u.y}];if(h==="x"?m=l.x===p?N:E:m=l.y===p?E:N,t===r){const D=Math.abs(e[h]-n[h]);if(D<=a){const B=Math.min(a-1,a-D);l[h]===p?b[h]=(u[h]>e[h]?-1:1)*B:x[h]=(d[h]>n[h]?-1:1)*B}}if(t!==r){const D=h==="x"?"y":"x",B=l[h]===c[D],H=u[D]>d[D],q=u[D]<d[D];(l[h]===1&&(!B&&H||B&&q)||l[h]!==1&&(!B&&q||B&&H))&&(m=h==="x"?E:N)}const I={x:u.x+b.x,y:u.y+b.y},A={x:d.x+x.x,y:d.y+x.y},P=Math.max(Math.abs(I.x-m[0].x),Math.abs(A.x-m[0].x)),L=Math.max(Math.abs(I.y-m[0].y),Math.abs(A.y-m[0].y));P>=L?(v=(I.x+A.x)/2,y=m[0].y):(v=m[0].x,y=(I.y+A.y)/2)}const C={x:u.x+b.x,y:u.y+b.y},_={x:d.x+x.x,y:d.y+x.y};return[[e,...C.x!==m[0].x||C.y!==m[0].y?[C]:[],...m,..._.x!==m[m.length-1].x||_.y!==m[m.length-1].y?[_]:[],n],v,y,w,k]}function BKn(e,t,n,r){const s=Math.min(pBe(e,t)/2,pBe(t,n)/2,r),{x:a,y:i}=t;if(e.x===a&&a===n.x||e.y===i&&i===n.y)return`L${a} ${i}`;if(e.y===i){const u=e.x<n.x?-1:1,d=e.y<n.y?1:-1;return`L ${a+s*u},${i}Q ${a},${i} ${a},${i+s*d}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${a},${i+s*c}Q ${a},${i} ${a+s*l},${i}`}function Uve({sourceX:e,sourceY:t,sourcePosition:n=nr.Bottom,targetX:r,targetY:s,targetPosition:a=nr.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,h,p,m,v]=zKn({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:s},targetPosition:a,center:{x:l,y:c},offset:u,stepPosition:d});let y=`M${f[0].x} ${f[0].y}`;for(let b=1;b<f.length-1;b++)y+=BKn(f[b-1],f[b],f[b+1],i);return y+=`L${f[f.length-1].x} ${f[f.length-1].y}`,[y,h,p,m,v]}function mBe(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function UKn(e){const{sourceNode:t,targetNode:n}=e;if(!mBe(t)||!mBe(n))return null;const r=t.internals.handleBounds||gBe(t.handles),s=n.internals.handleBounds||gBe(n.handles),a=vBe(r?.source??[],e.sourceHandle),i=vBe(e.connectionMode===cN.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!a||!i)return e.onError?.("008",Ty.error008(a?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=a?.position||nr.Bottom,c=i?.position||nr.Top,u=lC(t,a,l),d=lC(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function gBe(e){if(!e)return null;const t=[],n=[];for(const r of e)r.width=r.width??1,r.height=r.height??1,r.type==="source"?t.push(r):r.type==="target"&&n.push(r);return{source:t,target:n}}function lC(e,t,n=nr.Left,r=!1){const s=(t?.x??0)+e.internals.positionAbsolute.x,a=(t?.y??0)+e.internals.positionAbsolute.y,{width:i,height:l}=t??l0(e);if(r)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case nr.Top:return{x:s+i/2,y:a};case nr.Right:return{x:s+i,y:a+l/2};case nr.Bottom:return{x:s+i/2,y:a+l};case nr.Left:return{x:s,y:a+l/2}}}function vBe(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function qve(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function qKn(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:s}){const a=new Set;return e.reduce((i,l)=>([l.markerStart||r,l.markerEnd||s].forEach(c=>{if(c&&typeof c=="object"){const u=qve(c,t);a.has(u)||(i.push({id:u,color:c.color||n,...c}),a.add(u))}}),i),[]).sort((i,l)=>i.id.localeCompare(l.id))}const RCt=1e3,VKn=10,VOe={nodeOrigin:[0,0],nodeExtent:HM,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},HKn={...VOe,checkEquality:!0};function HOe(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function WKn(e,t,n){const r=HOe(VOe,n);for(const s of e.values())if(s.parentId)ZOe(s,e,t,r);else{const a=a4(s,r.nodeOrigin),i=fN(s.extent)?s.extent:r.nodeExtent,l=oC(a,i,l0(s));s.internals.positionAbsolute=l}}function ZKn(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;const n=[],r=[];for(const s of e.handles){const a={id:s.id,width:s.width??1,height:s.height??1,nodeId:e.id,x:s.x,y:s.y,position:s.position,type:s.type};s.type==="source"?n.push(a):s.type==="target"&&r.push(a)}return{source:n,target:r}}function WOe(e){return e==="manual"}function Vve(e,t,n,r={}){const s=HOe(HKn,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!WOe(s.zIndexMode)?RCt:0;let c=e.length>0,u=!1;t.clear(),n.clear();for(const d of e){let f=i.get(d.id);if(s.checkEquality&&d===f?.internals.userNode)t.set(d.id,f);else{const h=a4(d,s.nodeOrigin),p=fN(d.extent)?d.extent:s.nodeExtent,m=oC(h,p,l0(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:ZKn(d,f),z:PCt(d,l,s.zIndexMode),userNode:d}},t.set(d.id,f)}(f.measured===void 0||f.measured.width===void 0||f.measured.height===void 0)&&!f.hidden&&(c=!1),d.parentId&&ZOe(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function GKn(e,t){if(!e.parentId)return;const n=t.get(e.parentId);n?n.set(e.id,e):t.set(e.parentId,new Map([[e.id,e]]))}function ZOe(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=HOe(VOe,r),u=e.parentId,d=t.get(u);if(!d){console.warn(`Parent node ${u} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}GKn(e,n),s&&!d.parentId&&d.internals.rootParentIndex===void 0&&c==="auto"&&(d.internals.rootParentIndex=++s.i,d.internals.z=d.internals.z+s.i*VKn),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!WOe(c)?RCt:0,{x:h,y:p,z:m}=QKn(e,d,i,l,f,c),{positionAbsolute:v}=e.internals,y=h!==v.x||p!==v.y;(y||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:h,y:p}:v,z:m}})}function PCt(e,t,n){const r=jg(e.zIndex)?e.zIndex:0;return WOe(n)?r:r+(e.selected?t:0)}function QKn(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=l0(e),u=a4(e,n),d=fN(e.extent)?oC(u,e.extent,c):u;let f=oC({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=SCt(f,c,t));const h=PCt(e,s,a),p=t.internals.z??0;return{x:f.x,y:f.y,z:p>=h?p+1:h}}function GOe(e,t,n,r=[0,0]){const s=[],a=new Map;for(const i of e){const l=t.get(i.parentId);if(!l)continue;const c=a.get(i.parentId)?.expandedRect??dN(l),u=OCt(c,i.rect);a.set(i.parentId,{expandedRect:u,parent:l})}return a.size>0&&a.forEach(({expandedRect:i,parent:l},c)=>{const u=l.internals.positionAbsolute,d=l0(l),f=l.origin??r,h=i.x<u.x?Math.round(Math.abs(u.x-i.x)):0,p=i.y<u.y?Math.round(Math.abs(u.y-i.y)):0,m=Math.max(d.width,Math.round(i.width)),v=Math.max(d.height,Math.round(i.height)),y=(m-d.width)*f[0],b=(v-d.height)*f[1];(h>0||p>0||y||b)&&(s.push({id:c,type:"position",position:{x:l.position.x-h+y,y:l.position.y-p+b}}),n.get(c)?.forEach(x=>{e.some(w=>w.id===x.id)||s.push({id:x.id,type:"position",position:{x:x.position.x+h,y:x.position.y+p}})})),(d.width<i.width||d.height<i.height||h||p)&&s.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:m+(h?f[0]*h-y:0),height:v+(p?f[1]*p-b:0)}})}),s}function YKn(e,t,n,r,s,a,i){const l=r?.querySelector(".xyflow__viewport");let c=!1;if(!l)return{changes:[],updatedInternals:c};const u=[],d=window.getComputedStyle(l),{m22:f}=new window.DOMMatrixReadOnly(d.transform),h=[];for(const p of e.values()){const m=t.get(p.id);if(!m)continue;if(m.hidden){t.set(m.id,{...m,internals:{...m.internals,handleBounds:void 0}}),c=!0;continue}const v=UOe(p.nodeElement),y=m.measured.width!==v.width||m.measured.height!==v.height;if(!!(v.width&&v.height&&(y||!m.internals.handleBounds||p.force))){const x=p.nodeElement.getBoundingClientRect(),w=fN(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=SCt(k,v,t.get(m.parentId)):w&&(k=oC(k,w,v));const C={...m,measured:v,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:dBe("source",p.nodeElement,x,f,m.id),target:dBe("target",p.nodeElement,x,f,m.id)}}};t.set(m.id,C),m.parentId&&ZOe(C,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,y&&(u.push({id:m.id,type:"dimensions",dimensions:v}),m.expandParent&&m.parentId&&h.push({id:m.id,parentId:m.parentId,rect:dN(C,s)}))}}if(h.length>0){const p=GOe(h,t,n,s);u.push(...p)}return{changes:u,updatedInternals:c}}async function KKn({delta:e,panZoom:t,transform:n,translateExtent:r,width:s,height:a}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const i=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[s,a]],r),l=!!i&&(i.x!==n[0]||i.y!==n[1]||i.k!==n[2]);return Promise.resolve(l)}function yBe(e,t,n,r,s,a){let i=s;const l=r.get(i)||new Map;r.set(i,l.set(n,t)),i=`${s}-${e}`;const c=r.get(i)||new Map;if(r.set(i,c.set(n,t)),a){i=`${s}-${e}-${a}`;const u=r.get(i)||new Map;r.set(i,u.set(n,t))}}function $Ct(e,t,n){e.clear(),t.clear();for(const r of n){const{source:s,target:a,sourceHandle:i=null,targetHandle:l=null}=r,c={edgeId:r.id,source:s,target:a,sourceHandle:i,targetHandle:l},u=`${s}-${i}--${a}-${l}`,d=`${a}-${l}--${s}-${i}`;yBe("source",c,d,e,s,i),yBe("target",c,u,e,a,l),t.set(r.id,r)}}function MCt(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:MCt(n,t):!1}function bBe(e,t,n){let r=e;do{if(r?.matches?.(t))return!0;if(r===n)return!1;r=r?.parentElement}while(r);return!1}function XKn(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!MCt(i,e))&&(i.draggable||t&&typeof i.draggable>"u")){const l=e.get(a);l&&s.set(a,{id:a,position:l.position||{x:0,y:0},distance:{x:n.x-l.internals.positionAbsolute.x,y:n.y-l.internals.positionAbsolute.y},extent:l.extent,parentId:l.parentId,origin:l.origin,expandParent:l.expandParent,internals:{positionAbsolute:l.internals.positionAbsolute||{x:0,y:0}},measured:{width:l.measured.width??0,height:l.measured.height??0}})}return s}function Sne({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){const s=[];for(const[i,l]of t){const c=n.get(i)?.internals.userNode;c&&s.push({...c,position:l.position,dragging:r})}if(!e)return[s[0],s];const a=n.get(e)?.internals.userNode;return[a?{...a,position:t.get(e)?.position||a.position,dragging:r}:s[0],s]}function JKn({dragItems:e,snapGrid:t,x:n,y:r}){const s=e.values().next().value;if(!s)return null;const a={x:n-s.distance.x,y:r-s.distance.y},i=o4(a,t);return{x:i.x-a.x,y:i.y-a.y}}function eXn({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:s}){let a={x:null,y:null},i=0,l=new Map,c=!1,u={x:0,y:0},d=null,f=!1,h=null,p=!1,m=!1,v=null;function y({noDragClassName:x,handleSelector:w,domNode:k,isSelectable:C,nodeId:_,nodeClickDistance:T=0}){h=Eh(k);function E({x:P,y:L}){const{nodeLookup:D,nodeExtent:B,snapGrid:H,snapToGrid:q,nodeOrigin:z,onNodeDrag:V,onSelectionDrag:M,onError:G,updateNodePositions:F}=t();a={x:P,y:L};let R=!1;const U=l.size>1,Z=U&&B?Bve(i4(l)):null,Y=U&&q?JKn({dragItems:l,snapGrid:H,x:P,y:L}):null;for(const[te,J]of l){if(!D.has(te))continue;let ee={x:P-J.distance.x,y:L-J.distance.y};q&&(ee=Y?{x:Math.round(ee.x+Y.x),y:Math.round(ee.y+Y.y)}:o4(ee,H));let re=null;if(U&&B&&!J.extent&&Z){const{positionAbsolute:ne}=J.internals,se=ne.x-Z.x+B[0][0],ce=ne.x+J.measured.width-Z.x2+B[1][0],le=ne.y-Z.y+B[0][1],be=ne.y+J.measured.height-Z.y2+B[1][1];re=[[se,le],[ce,be]]}const{position:ae,positionAbsolute:X}=wCt({nodeId:te,nextPosition:ee,nodeLookup:D,nodeExtent:re||B,nodeOrigin:z,onError:G});R=R||J.position.x!==ae.x||J.position.y!==ae.y,J.position=ae,J.internals.positionAbsolute=X}if(m=m||R,!!R&&(F(l,!0),v&&(r||V||!_&&M))){const[te,J]=Sne({nodeId:_,dragItems:l,nodeLookup:D});r?.(v,l,te,J),V?.(v,te,J),_||M?.(v,J)}}async function N(){if(!d)return;const{transform:P,panBy:L,autoPanSpeed:D,autoPanOnNodeDrag:B}=t();if(!B){c=!1,cancelAnimationFrame(i);return}const[H,q]=kCt(u,d,D);(H!==0||q!==0)&&(a.x=(a.x??0)-H/P[2],a.y=(a.y??0)-q/P[2],await L({x:H,y:q})&&E(a)),i=requestAnimationFrame(N)}function I(P){const{nodeLookup:L,multiSelectionActive:D,nodesDraggable:B,transform:H,snapGrid:q,snapToGrid:z,selectNodesOnDrag:V,onNodeDragStart:M,onSelectionDragStart:G,unselectNodesAndEdges:F}=t();f=!0,(!V||!C)&&!D&&_&&(L.get(_)?.selected||F()),C&&V&&_&&e?.(_);const R=V$(P.sourceEvent,{transform:H,snapGrid:q,snapToGrid:z,containerBounds:d});if(a=R,l=XKn(L,B,R,_),l.size>0&&(n||M||!_&&G)){const[U,Z]=Sne({nodeId:_,dragItems:l,nodeLookup:L});n?.(P.sourceEvent,l,U,Z),M?.(P.sourceEvent,U,Z),_||G?.(P.sourceEvent,Z)}}const A=eCt().clickDistance(T).on("start",P=>{const{domNode:L,nodeDragThreshold:D,transform:B,snapGrid:H,snapToGrid:q}=t();d=L?.getBoundingClientRect()||null,p=!1,m=!1,v=P.sourceEvent,D===0&&I(P),a=V$(P.sourceEvent,{transform:B,snapGrid:H,snapToGrid:q,containerBounds:d}),u=Ng(P.sourceEvent,d)}).on("drag",P=>{const{autoPanOnNodeDrag:L,transform:D,snapGrid:B,snapToGrid:H,nodeDragThreshold:q,nodeLookup:z}=t(),V=V$(P.sourceEvent,{transform:D,snapGrid:B,snapToGrid:H,containerBounds:d});if(v=P.sourceEvent,(P.sourceEvent.type==="touchmove"&&P.sourceEvent.touches.length>1||_&&!z.has(_))&&(p=!0),!p){if(!c&&L&&f&&(c=!0,N()),!f){const M=Ng(P.sourceEvent,d),G=M.x-u.x,F=M.y-u.y;Math.sqrt(G*G+F*F)>q&&I(P)}(a.x!==V.xSnapped||a.y!==V.ySnapped)&&l&&f&&(u=Ng(P.sourceEvent,d),E(V))}}).on("end",P=>{if(!(!f||p)&&(c=!1,f=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:L,updateNodePositions:D,onNodeDragStop:B,onSelectionDragStop:H}=t();if(m&&(D(l,!1),m=!1),s||B||!_&&H){const[q,z]=Sne({nodeId:_,dragItems:l,nodeLookup:L,dragging:!1});s?.(P.sourceEvent,l,q,z),B?.(P.sourceEvent,q,z),_||H?.(P.sourceEvent,z)}}}).filter(P=>{const L=P.target;return!P.button&&(!x||!bBe(L,`.${x}`,k))&&(!w||bBe(L,w,k))});h.call(A)}function b(){h?.on(".drag",null)}return{update:y,destroy:b}}function tXn(e,t,n){const r=[],s={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const a of t.values())GM(s,dN(a))>0&&r.push(a);return r}const nXn=250;function rXn(e,t,n,r){let s=[],a=1/0;const i=tXn(e,n,t+nXn);for(const l of i){const c=[...l.internals.handleBounds?.source??[],...l.internals.handleBounds?.target??[]];for(const u of c){if(r.nodeId===u.nodeId&&r.type===u.type&&r.id===u.id)continue;const{x:d,y:f}=lC(l,u,u.position,!0),h=Math.sqrt(Math.pow(d-e.x,2)+Math.pow(f-e.y,2));h>t||(h<a?(s=[{...u,x:d,y:f}],a=h):h===a&&s.push({...u,x:d,y:f}))}}if(!s.length)return null;if(s.length>1){const l=r.type==="source"?"target":"source";return s.find(c=>c.type===l)??s[0]}return s[0]}function DCt(e,t,n,r,s,a=!1){const i=r.get(e);if(!i)return null;const l=s==="strict"?i.internals.handleBounds?.[t]:[...i.internals.handleBounds?.source??[],...i.internals.handleBounds?.target??[]],c=(n?l?.find(u=>u.id===n):l?.[0])??null;return c&&a?{...c,...lC(i,c,c.position,!0)}:c}function LCt(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function sXn(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const FCt=()=>!0;function aXn(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:a,isTarget:i,domNode:l,nodeLookup:c,lib:u,autoPanOnConnect:d,flowId:f,panBy:h,cancelConnection:p,onConnectStart:m,onConnect:v,onConnectEnd:y,isValidConnection:b=FCt,onReconnectEnd:x,updateConnection:w,getTransform:k,getFromHandle:C,autoPanSpeed:_,dragThreshold:T=1,handleDomNode:E}){const N=ECt(e.target);let I=0,A;const{x:P,y:L}=Ng(e),D=LCt(a,E),B=l?.getBoundingClientRect();let H=!1;if(!B||!D)return;const q=DCt(s,D,r,c,t);if(!q)return;let z=Ng(e,B),V=!1,M=null,G=!1,F=null;function R(){if(!d||!B)return;const[ae,X]=kCt(z,B,_);h({x:ae,y:X}),I=requestAnimationFrame(R)}const U={...q,nodeId:s,type:D,position:q.position},Z=c.get(s);let te={inProgress:!0,isValid:null,from:lC(Z,U,nr.Left,!0),fromHandle:U,fromPosition:U.position,fromNode:Z,to:z,toHandle:null,toPosition:oBe[U.position],toNode:null,pointer:z};function J(){H=!0,w(te),m?.(e,{nodeId:s,handleId:r,handleType:D})}T===0&&J();function ee(ae){if(!H){const{x:be,y:he}=Ng(ae),xe=be-P,Ae=he-L;if(!(xe*xe+Ae*Ae>T*T))return;J()}if(!C()||!U){re(ae);return}const X=k();z=Ng(ae,B),A=rXn(l4(z,X,!1,[1,1]),n,c,U),V||(R(),V=!0);const ne=zCt(ae,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});F=ne.handleDomNode,M=ne.connection,G=sXn(!!A,ne.isValid);const se=c.get(s),ce=se?lC(se,U,nr.Left,!0):te.from,le={...te,from:ce,isValid:G,to:ne.toHandle&&G?dU({x:ne.toHandle.x,y:ne.toHandle.y},X):z,toHandle:ne.toHandle,toPosition:G&&ne.toHandle?ne.toHandle.position:oBe[U.position],toNode:ne.toHandle?c.get(ne.toHandle.nodeId):null,pointer:z};w(le),te=le}function re(ae){if(!("touches"in ae&&ae.touches.length>0)){if(H){(A||F)&&M&&G&&v?.(M);const{inProgress:X,...ne}=te,se={...ne,toPosition:te.toHandle?te.toPosition:null};y?.(ae,se),a&&x?.(ae,se)}p(),cancelAnimationFrame(I),V=!1,G=!1,M=null,F=null,N.removeEventListener("mousemove",ee),N.removeEventListener("mouseup",re),N.removeEventListener("touchmove",ee),N.removeEventListener("touchend",re)}}N.addEventListener("mousemove",ee),N.addEventListener("mouseup",re),N.addEventListener("touchmove",ee),N.addEventListener("touchend",re)}function zCt(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=FCt,nodeLookup:d}){const f=a==="target",h=t?i.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:p,y:m}=Ng(e),v=i.elementFromPoint(p,m),y=v?.classList.contains(`${l}-flow__handle`)?v:h,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){const x=LCt(void 0,y),w=y.getAttribute("data-nodeid"),k=y.getAttribute("data-handleid"),C=y.classList.contains("connectable"),_=y.classList.contains("connectableend");if(!w||!x)return b;const T={source:f?w:r,sourceHandle:f?k:s,target:f?r:w,targetHandle:f?s:k};b.connection=T;const N=C&&_&&(n===cN.Strict?f&&x==="source"||!f&&x==="target":w!==r||k!==s);b.isValid=N&&u(T),b.toHandle=DCt(w,x,k,d,n,!0)}return b}const Hve={onPointerDown:aXn,isValid:zCt};function iXn({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Eh(e);function a({translateExtent:l,width:c,height:u,zoomStep:d=1,pannable:f=!0,zoomable:h=!0,inversePan:p=!1}){const m=w=>{if(w.sourceEvent.type!=="wheel"||!t)return;const k=n(),C=w.sourceEvent.ctrlKey&&QM()?10:1,_=-w.sourceEvent.deltaY*(w.sourceEvent.deltaMode===1?.05:w.sourceEvent.deltaMode?1:.002)*d,T=k[2]*Math.pow(2,_*C);t.scaleTo(T)};let v=[0,0];const y=w=>{(w.sourceEvent.type==="mousedown"||w.sourceEvent.type==="touchstart")&&(v=[w.sourceEvent.clientX??w.sourceEvent.touches[0].clientX,w.sourceEvent.clientY??w.sourceEvent.touches[0].clientY])},b=w=>{const k=n();if(w.sourceEvent.type!=="mousemove"&&w.sourceEvent.type!=="touchmove"||!t)return;const C=[w.sourceEvent.clientX??w.sourceEvent.touches[0].clientX,w.sourceEvent.clientY??w.sourceEvent.touches[0].clientY],_=[C[0]-v[0],C[1]-v[1]];v=C;const T=r()*Math.max(k[2],Math.log(k[2]))*(p?-1:1),E={x:k[0]-_[0]*T,y:k[1]-_[1]*T},N=[[0,0],[c,u]];t.setViewportConstrained({x:E.x,y:E.y,zoom:k[2]},N,l)},x=mCt().on("start",y).on("zoom",f?b:null).on("zoom.wheel",h?m:null);s.call(x,{})}function i(){s.on("zoom",null)}return{update:a,destroy:i,pointer:vg}}const _W=e=>({x:e.x,y:e.y,zoom:e.k}),kne=({x:e,y:t,zoom:n})=>kW.translate(e,t).scale(n),ET=(e,t)=>e.target.closest(`.${t}`),BCt=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),oXn=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,One=(e,t=0,n=oXn,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},UCt=e=>{const t=e.ctrlKey&&QM()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function lXn({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(ET(d,t))return d.ctrlKey&&d.preventDefault(),!1;d.preventDefault(),d.stopImmediatePropagation();const f=n.property("__zoom").k||1;if(d.ctrlKey&&i){const y=vg(d),b=UCt(d),x=f*Math.pow(2,b);r.scaleTo(n,x,y,d);return}const h=d.deltaMode===1?20:1;let p=s===fO.Vertical?0:d.deltaX*h,m=s===fO.Horizontal?0:d.deltaY*h;!QM()&&d.shiftKey&&s!==fO.Vertical&&(p=d.deltaY*h,m=0),r.translateBy(n,-(p/f)*a,-(m/f)*a,{internal:!0});const v=_W(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(d,v),e.panScrollTimeout=setTimeout(()=>{u?.(d,v),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l?.(d,v))}}function cXn({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=ET(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function uXn({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=_W(r.transform);e.mouseButton=r.sourceEvent?.button||0,e.isZoomingOrPanning=!0,e.prevViewport=s,r.sourceEvent?.type==="mousedown"&&t(!0),n&&n?.(r.sourceEvent,s)}}function dXn({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&BCt(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,_W(a.transform))}}function fXn({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&BCt(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=_W(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function hXn({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:s,zoomOnDoubleClick:a,userSelectionActive:i,noWheelClassName:l,noPanClassName:c,lib:u,connectionInProgress:d}){return f=>{const h=e||t,p=n&&f.ctrlKey,m=f.type==="wheel";if(f.button===1&&f.type==="mousedown"&&(ET(f,`${u}-flow__node`)||ET(f,`${u}-flow__edge`)))return!0;if(!r&&!h&&!s&&!a&&!n||i||d&&!m||ET(f,l)&&m||ET(f,c)&&(!m||s&&m&&!e)||!n&&f.ctrlKey&&m)return!1;if(!n&&f.type==="touchstart"&&f.touches?.length>1)return f.preventDefault(),!1;if(!h&&!s&&!p&&m||!r&&(f.type==="mousedown"||f.type==="touchstart")||Array.isArray(r)&&!r.includes(f.button)&&f.type==="mousedown")return!1;const v=Array.isArray(r)&&r.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||m)&&v}}function pXn({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:s,onPanZoom:a,onPanZoomStart:i,onPanZoomEnd:l,onDraggingChange:c}){const u={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},d=e.getBoundingClientRect(),f=mCt().scaleExtent([t,n]).translateExtent(r),h=Eh(e).call(f);x({x:s.x,y:s.y,zoom:uN(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const p=h.on("wheel.zoom"),m=h.on("dblclick.zoom");f.wheelDelta(UCt);function v(A,P){return h?new Promise(L=>{f?.interpolate(P?.interpolate==="linear"?bx:r9).transform(One(h,P?.duration,P?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:P,onPaneContextMenu:L,userSelectionActive:D,panOnScroll:B,panOnDrag:H,panOnScrollMode:q,panOnScrollSpeed:z,preventScrolling:V,zoomOnPinch:M,zoomOnScroll:G,zoomOnDoubleClick:F,zoomActivationKeyPressed:R,lib:U,onTransformChange:Z,connectionInProgress:Y,paneClickDistance:te,selectionOnDrag:J}){D&&!u.isZoomingOrPanning&&b();const ee=B&&!R&&!D;f.clickDistance(J?1/0:!jg(te)||te<0?0:te);const re=ee?lXn({zoomPanValues:u,noWheelClassName:A,d3Selection:h,d3Zoom:f,panOnScrollMode:q,panOnScrollSpeed:z,zoomOnPinch:M,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):cXn({noWheelClassName:A,preventScrolling:V,d3ZoomHandler:p});if(h.on("wheel.zoom",re,{passive:!1}),!D){const X=uXn({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",X);const ne=dXn({zoomPanValues:u,panOnDrag:H,onPaneContextMenu:!!L,onPanZoom:a,onTransformChange:Z});f.on("zoom",ne);const se=fXn({zoomPanValues:u,panOnDrag:H,panOnScroll:B,onPaneContextMenu:L,onPanZoomEnd:l,onDraggingChange:c});f.on("end",se)}const ae=hXn({zoomActivationKeyPressed:R,panOnDrag:H,zoomOnScroll:G,panOnScroll:B,zoomOnDoubleClick:F,zoomOnPinch:M,userSelectionActive:D,noPanClassName:P,noWheelClassName:A,lib:U,connectionInProgress:Y});f.filter(ae),F?h.on("dblclick.zoom",m):h.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,P,L){const D=kne(A),B=f?.constrain()(D,P,L);return B&&await v(B),new Promise(H=>H(B))}async function w(A,P){const L=kne(A);return await v(L,P),new Promise(D=>D(L))}function k(A){if(h){const P=kne(A),L=h.property("__zoom");(L.k!==A.zoom||L.x!==A.x||L.y!==A.y)&&f?.transform(h,P,null,{sync:!0})}}function C(){const A=h?pCt(h.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function _(A,P){return h?new Promise(L=>{f?.interpolate(P?.interpolate==="linear"?bx:r9).scaleTo(One(h,P?.duration,P?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function T(A,P){return h?new Promise(L=>{f?.interpolate(P?.interpolate==="linear"?bx:r9).scaleBy(One(h,P?.duration,P?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function E(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const P=!jg(A)||A<0?0:A;f?.clickDistance(P)}return{update:y,destroy:b,setViewport:w,setViewportConstrained:x,getViewport:C,scaleTo:_,scaleBy:T,setScaleExtent:E,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var hN;(function(e){e.Line="line",e.Handle="handle"})(hN||(hN={}));function mXn({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:s,affectsY:a}){const i=e-t,l=n-r,c=[i>0?1:i<0?-1:0,l>0?1:l<0?-1:0];return i&&s&&(c[0]=c[0]*-1),l&&a&&(c[1]=c[1]*-1),c}function xBe(e){const t=e.includes("right")||e.includes("left"),n=e.includes("bottom")||e.includes("top"),r=e.includes("left"),s=e.includes("top");return{isHorizontal:t,isVertical:n,affectsX:r,affectsY:s}}function nw(e,t){return Math.max(0,t-e)}function rw(e,t){return Math.max(0,e-t)}function AF(e,t,n){return Math.max(0,t-e,e-n)}function wBe(e,t){return e?!t:t}function gXn(e,t,n,r,s,a,i,l){let{affectsX:c,affectsY:u}=t;const{isHorizontal:d,isVertical:f}=t,h=d&&f,{xSnapped:p,ySnapped:m}=n,{minWidth:v,maxWidth:y,minHeight:b,maxHeight:x}=r,{x:w,y:k,width:C,height:_,aspectRatio:T}=e;let E=Math.floor(d?p-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=C+(c?-E:E),A=_+(u?-N:N),P=-a[0]*C,L=-a[1]*_;let D=AF(I,v,y),B=AF(A,b,x);if(i){let z=0,V=0;c&&E<0?z=nw(w+E+P,i[0][0]):!c&&E>0&&(z=rw(w+I+P,i[1][0])),u&&N<0?V=nw(k+N+L,i[0][1]):!u&&N>0&&(V=rw(k+A+L,i[1][1])),D=Math.max(D,z),B=Math.max(B,V)}if(l){let z=0,V=0;c&&E>0?z=rw(w+E,l[0][0]):!c&&E<0&&(z=nw(w+I,l[1][0])),u&&N>0?V=rw(k+N,l[0][1]):!u&&N<0&&(V=nw(k+A,l[1][1])),D=Math.max(D,z),B=Math.max(B,V)}if(s){if(d){const z=AF(I/T,b,x)*T;if(D=Math.max(D,z),i){let V=0;!c&&!u||c&&!u&&h?V=rw(k+L+I/T,i[1][1])*T:V=nw(k+L+(c?E:-E)/T,i[0][1])*T,D=Math.max(D,V)}if(l){let V=0;!c&&!u||c&&!u&&h?V=nw(k+I/T,l[1][1])*T:V=rw(k+(c?E:-E)/T,l[0][1])*T,D=Math.max(D,V)}}if(f){const z=AF(A*T,v,y)/T;if(B=Math.max(B,z),i){let V=0;!c&&!u||u&&!c&&h?V=rw(w+A*T+P,i[1][0])/T:V=nw(w+(u?N:-N)*T+P,i[0][0])/T,B=Math.max(B,V)}if(l){let V=0;!c&&!u||u&&!c&&h?V=nw(w+A*T,l[1][0])/T:V=rw(w+(u?N:-N)*T,l[0][0])/T,B=Math.max(B,V)}}}N=N+(N<0?B:-B),E=E+(E<0?D:-D),s&&(h?I>A*T?N=(wBe(c,u)?-E:E)/T:E=(wBe(c,u)?-N:N)*T:d?(N=E/T,u=c):(E=N*T,c=u));const H=c?w+E:w,q=u?k+N:k;return{width:C+(c?-E:E),height:_+(u?-N:N),x:a[0]*E*(c?-1:1)+H,y:a[1]*N*(u?-1:1)+q}}const qCt={width:0,height:0,x:0,y:0},vXn={...qCt,pointerX:0,pointerY:0,aspectRatio:1};function yXn(e){return[[0,0],[e.measured.width,e.measured.height]]}function bXn(e,t,n){const r=t.position.x+e.position.x,s=t.position.y+e.position.y,a=e.measured.width??0,i=e.measured.height??0,l=n[0]*a,c=n[1]*i;return[[r-l,s-c],[r+a-l,s+i-c]]}function xXn({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=Eh(e);let i={controlDirection:xBe("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:u,boundaries:d,keepAspectRatio:f,resizeDirection:h,onResizeStart:p,onResize:m,onResizeEnd:v,shouldResize:y}){let b={...qCt},x={...vXn};i={boundaries:d,resizeDirection:h,keepAspectRatio:f,controlDirection:xBe(u)};let w,k=null,C=[],_,T,E,N=!1;const I=eCt().on("start",A=>{const{nodeLookup:P,transform:L,snapGrid:D,snapToGrid:B,nodeOrigin:H,paneDomNode:q}=n();if(w=P.get(t),!w)return;k=q?.getBoundingClientRect()??null;const{xSnapped:z,ySnapped:V}=V$(A.sourceEvent,{transform:L,snapGrid:D,snapToGrid:B,containerBounds:k});b={width:w.measured.width??0,height:w.measured.height??0,x:w.position.x??0,y:w.position.y??0},x={...b,pointerX:z,pointerY:V,aspectRatio:b.width/b.height},_=void 0,w.parentId&&(w.extent==="parent"||w.expandParent)&&(_=P.get(w.parentId),T=_&&w.extent==="parent"?yXn(_):void 0),C=[],E=void 0;for(const[M,G]of P)if(G.parentId===t&&(C.push({id:M,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const F=bXn(G,w,G.origin??H);E?E=[[Math.min(F[0][0],E[0][0]),Math.min(F[0][1],E[0][1])],[Math.max(F[1][0],E[1][0]),Math.max(F[1][1],E[1][1])]]:E=F}p?.(A,{...b})}).on("drag",A=>{const{transform:P,snapGrid:L,snapToGrid:D,nodeOrigin:B}=n(),H=V$(A.sourceEvent,{transform:P,snapGrid:L,snapToGrid:D,containerBounds:k}),q=[];if(!w)return;const{x:z,y:V,width:M,height:G}=b,F={},R=w.origin??B,{width:U,height:Z,x:Y,y:te}=gXn(x,i.controlDirection,H,i.boundaries,i.keepAspectRatio,R,T,E),J=U!==M,ee=Z!==G,re=Y!==z&&J,ae=te!==V&&ee;if(!re&&!ae&&!J&&!ee)return;if((re||ae||R[0]===1||R[1]===1)&&(F.x=re?Y:b.x,F.y=ae?te:b.y,b.x=F.x,b.y=F.y,C.length>0)){const ce=Y-z,le=te-V;for(const be of C)be.position={x:be.position.x-ce+R[0]*(U-M),y:be.position.y-le+R[1]*(Z-G)},q.push(be)}if((J||ee)&&(F.width=J&&(!i.resizeDirection||i.resizeDirection==="horizontal")?U:b.width,F.height=ee&&(!i.resizeDirection||i.resizeDirection==="vertical")?Z:b.height,b.width=F.width,b.height=F.height),_&&w.expandParent){const ce=R[0]*(F.width??0);F.x&&F.x<ce&&(b.x=ce,x.x=x.x-(F.x-ce));const le=R[1]*(F.height??0);F.y&&F.y<le&&(b.y=le,x.y=x.y-(F.y-le))}const X=mXn({width:b.width,prevWidth:M,height:b.height,prevHeight:G,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),ne={...b,direction:X};y?.(A,ne)!==!1&&(N=!0,m?.(A,ne),r(F,q))}).on("end",A=>{N&&(v?.(A,{...b}),s?.({...b}),N=!1)});a.call(I)}function c(){a.on(".drag",null)}return{update:l,destroy:c}}const wXn={},SBe=e=>{let t;const n=new Set,r=(d,f)=>{const h=typeof d=="function"?d(t):d;if(!Object.is(h,t)){const p=t;t=f??(typeof h!="object"||h===null)?h:Object.assign({},t,h),n.forEach(m=>m(t,p))}},s=()=>t,c={setState:r,getState:s,getInitialState:()=>u,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(wXn?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},u=t=e(r,s,c);return c},SXn=e=>e?SBe(e):SBe,{useDebugValue:kXn}=qe,{useSyncExternalStoreWithSelector:OXn}=zNn,CXn=e=>e;function VCt(e,t=CXn,n){const r=OXn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return kXn(r),r}const kBe=(e,t)=>{const n=SXn(e),r=(s,a=t)=>VCt(n,s,a);return Object.assign(r,n),r},_Xn=(e,t)=>e?kBe(e,t):kBe;function oo(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,s]of e)if(!Object.is(s,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}const EW=g.createContext(null),EXn=EW.Provider,HCt=Ty.error001();function Ws(e,t){const n=g.useContext(EW);if(n===null)throw new Error(HCt);return VCt(n,e,t)}function To(){const e=g.useContext(EW);if(e===null)throw new Error(HCt);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const OBe={display:"none"},TXn={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},WCt="react-flow__node-desc",ZCt="react-flow__edge-desc",jXn="react-flow__aria-live",NXn=e=>e.ariaLiveMessage,IXn=e=>e.ariaLabelConfig;function AXn({rfId:e}){const t=Ws(NXn);return o.jsx("div",{id:`${jXn}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:TXn,children:t})}function RXn({rfId:e,disableKeyboardA11y:t}){const n=Ws(IXn);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${WCt}-${e}`,style:OBe,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${ZCt}-${e}`,style:OBe,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(AXn,{rfId:e})]})}const c4=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:Ql(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});c4.displayName="Panel";function PXn({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(c4,{position:t,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev",children:o.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const $Xn=e=>{const t=[],n=[];for(const[,r]of e.nodeLookup)r.selected&&t.push(r.internals.userNode);for(const[,r]of e.edgeLookup)r.selected&&n.push(r);return{selectedNodes:t,selectedEdges:n}},RF=e=>e.id;function MXn(e,t){return oo(e.selectedNodes.map(RF),t.selectedNodes.map(RF))&&oo(e.selectedEdges.map(RF),t.selectedEdges.map(RF))}function DXn({onSelectionChange:e}){const t=To(),{selectedNodes:n,selectedEdges:r}=Ws($Xn,MXn);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const LXn=e=>!!e.onSelectionChangeHandlers;function FXn({onSelectionChange:e}){const t=Ws(LXn);return e||t?o.jsx(DXn,{onSelectionChange:e}):null}const Wve=typeof window<"u"?g.useLayoutEffect:g.useEffect,GCt=[0,0],zXn={x:0,y:0,zoom:1},BXn=["nodes","edges","defaultNodes","defaultEdges","onConnect","onConnectStart","onConnectEnd","onClickConnectStart","onClickConnectEnd","nodesDraggable","autoPanOnNodeFocus","nodesConnectable","nodesFocusable","edgesFocusable","edgesReconnectable","elevateNodesOnSelect","elevateEdgesOnSelect","minZoom","maxZoom","nodeExtent","onNodesChange","onEdgesChange","elementsSelectable","connectionMode","snapGrid","snapToGrid","translateExtent","connectOnClick","defaultEdgeOptions","fitView","fitViewOptions","onNodesDelete","onEdgesDelete","onDelete","onNodeDrag","onNodeDragStart","onNodeDragStop","onSelectionDrag","onSelectionDragStart","onSelectionDragStop","onMoveStart","onMove","onMoveEnd","noPanClassName","nodeOrigin","autoPanOnConnect","autoPanOnNodeDrag","onError","connectionRadius","isValidConnection","selectNodesOnDrag","nodeDragThreshold","connectionDragThreshold","onBeforeDelete","debug","autoPanSpeed","ariaLabelConfig","zIndexMode"],CBe=[...BXn,"rfId"],UXn=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges}),_Be={translateExtent:HM,nodeOrigin:GCt,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function qXn(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Ws(UXn,oo),u=To();Wve(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=_Be,l()}),[]);const d=g.useRef(_Be);return Wve(()=>{for(const f of CBe){const h=e[f],p=d.current[f];h!==p&&(typeof e[f]>"u"||(f==="nodes"?t(h):f==="edges"?n(h):f==="minZoom"?r(h):f==="maxZoom"?s(h):f==="translateExtent"?a(h):f==="nodeExtent"?i(h):f==="ariaLabelConfig"?u.setState({ariaLabelConfig:AKn(h)}):f==="fitView"?u.setState({fitViewQueued:h}):f==="fitViewOptions"?u.setState({fitViewOptions:h}):u.setState({[f]:h})))}d.current=e},CBe.map(f=>e[f])),null}function EBe(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function VXn(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=EBe(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:EBe()?.matches?"dark":"light"}const TBe=typeof document<"u"?document:null;function YM(e=null,t={target:TBe,actInsideInputWithModifier:!0}){const[n,r]=g.useState(!1),s=g.useRef(!1),a=g.useRef(new Set([])),[i,l]=g.useMemo(()=>{if(e!==null){const u=(Array.isArray(e)?e:[e]).filter(f=>typeof f=="string").map(f=>f.replace("+",`
235
235
  `).replace(`
236
236
 
237
237
  `,`
@@ -511,7 +511,7 @@ Ask one simple question at a time.`;function z7r(e,t){const n=g.useRef(e);n.curr
511
511
  `):e,D=s||l;return!e||e==="null"?null:o.jsxs("div",{className:K("flex flex-col gap-2",a),children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx(Q4t,{icon:r,children:t}),o.jsxs("div",{className:"flex items-center gap-2",children:[!D&&o.jsx(wC,{name:"code-section-search",label:"Search code",labelIsHidden:!0,placeholder:"Search...",value:f,onChange:T,onReset:E,size:"sm",isMinimized:u,onMinimizedChange:d}),o.jsxs(es,{children:[o.jsx(_a,{content:e||"No content",size:"sm"}),C&&o.jsx(ie,{size:"sm","aria-label":l?"Show escaped newlines":"Show multiline text",tooltip:l?"Show escaped newlines":"Show multiline text",onClick:()=>c(B=>!B),children:l?o.jsx(d1,{}):o.jsx(U9,{})}),o.jsx(ie,{size:"sm","aria-label":"Expand",tooltip:"Expand",onClick:()=>m(!0),children:o.jsx(IKt,{})})]})]})]}),o.jsx("div",{className:"border-border1 bg-surface3 text-ui-sm text-neutral4 max-h-[30vh] overflow-hidden overflow-y-auto rounded-lg border p-3 break-all dark:border-white/10 dark:bg-black/20",children:D?o.jsx("div",{className:"text-neutral4 font-mono break-all",children:o.jsx("pre",{className:"text-wrap",children:P})}):o.jsx(rd,{ref:w,extensions:[nN(),Pt.lineWrapping,rXe()],theme:i,value:e,editable:!1})}),o.jsx(pr,{open:p,onOpenChange:m,children:o.jsxs(mr,{className:"grid h-[calc(100vh-6rem)]! max-w-[90vw]! grid-rows-[auto_1fr] [&>.absolute]:hidden",children:[o.jsxs(gr,{className:"flex-row items-center justify-between",children:[o.jsx(ur,{className:"text-ui-sm flex min-w-0 items-center gap-1.5 truncate [&>svg]:size-3.5",children:n??o.jsxs(o.Fragment,{children:[r,t]})}),o.jsx(Cs,{children:"Expanded code view"}),o.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[!b&&o.jsx(wC,{name:"expanded-code-search",label:"Search code",labelIsHidden:!0,placeholder:"Search...",value:v,onChange:I,onReset:A,size:"sm"}),o.jsxs(es,{children:[o.jsx(_a,{content:e||"No content",size:"sm"}),C&&o.jsx(ie,{size:"sm","aria-label":b?"Show escaped newlines":"Show multiline text",tooltip:b?"Show escaped newlines":"Show multiline text",onClick:()=>x(B=>!B),children:b?o.jsx(d1,{}):o.jsx(U9,{})}),o.jsx(Sxt,{asChild:!0,children:o.jsx(ie,{size:"sm","aria-label":"Close",tooltip:"Close",children:o.jsx(or,{})})})]})]})]}),o.jsx("div",{className:"overflow-auto px-6 pb-6",children:b?o.jsx("div",{className:"border-border1 bg-surface3 text-ui-sm text-neutral4 overflow-hidden overflow-y-auto rounded-lg border p-3 break-all dark:border-white/10 dark:bg-black/20",children:o.jsx("div",{className:"text-neutral4 font-mono break-all",children:o.jsx("pre",{className:"text-wrap",children:L})})}):o.jsx(rd,{ref:k,extensions:[nN(),Pt.lineWrapping,rXe()],theme:i,value:e,editable:!1})})]})})]})}function hxe(e){if(typeof e=="string"){const t=e.indexOf(`
512
512
  `);return t!==-1&&t!==e.length-1}else{if(Array.isArray(e))return e.some(t=>hxe(t));if(e&&typeof e=="object")return Object.values(e).some(t=>hxe(t))}return!1}function rqr({onClick:e,tooltip:t="Close panel",className:n}){return o.jsx(ie,{size:"md",onClick:e,"aria-label":"Close Panel",tooltip:t,className:n,children:o.jsx(or,{})})}function sqr({children:e,ref:t}){return o.jsx("div",{ref:t,className:"min-h-0 flex-1 overflow-y-auto p-4",children:e})}function aqr({className:e,children:t}){return o.jsx("div",{className:K("flex min-h-14 items-center justify-between gap-2 px-4 py-3","not-last:border-b not-last:border-border1",e),children:t})}function iqr({className:e,children:t}){return o.jsx("h3",{className:K("flex gap-2 text-ui-md text-neutral3 [&>b]:font-normal [&>b]:text-neutral2",e),children:t})}function oqr({children:e}){return o.jsxs("div",{className:"text-ui-sm text-neutral2 flex min-h-32 items-center justify-center gap-2 px-4 py-6",children:[o.jsx(Vt,{size:"sm",variant:"pulse",className:"text-neutral1"})," ",e??"Loading..."]})}function lqr({onPrevious:e,onNext:t,previousLabel:n="Previous",nextLabel:r="Next"}){return o.jsxs(es,{spacing:"close",children:[o.jsx(ie,{size:"md",tooltip:n,onClick:e,disabled:!e,children:o.jsx(K1,{})}),o.jsx(ie,{size:"md",tooltip:r,onClick:t,disabled:!t,children:o.jsx(CV,{})})]})}function cqr({children:e}){return o.jsx("p",{className:"text-ui-sm text-neutral2 px-4 py-6",children:e??"No data found."})}function uqr({collapsed:e,children:t,className:n}){return o.jsx("section",{className:K("flex flex-col overflow-hidden rounded-xl border border-border1 bg-surface2",e?"h-auto":"max-h-full",n),children:t})}const Gt=Object.assign(uqr,{Header:aqr,Heading:iqr,CloseButton:rqr,NextPrevNav:lqr,LoadingData:oqr,NoData:cqr,Content:sqr,CodeSection:nqr,SectionHeading:Q4t});function yO(e,t){const n=[];return JSON.stringify(e,function(r,s){if(typeof s=="bigint")return s.toString();if(s!==null&&typeof s=="object"){for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(s))return"[Circular]";n.push(s)}return s},t)??"null"}function dqr({className:e,...t}){return o.jsx("div",{"data-slot":"section-content",className:K("group-data-[variant=factory]/section:overflow-hidden group-data-[variant=factory]/section:rounded-xl group-data-[variant=factory]/section:border group-data-[variant=factory]/section:border-border1 group-data-[variant=factory]/section:bg-surface3",e),...t})}function fqr({className:e,...t}){return o.jsx("p",{"data-slot":"section-description",className:K("max-w-[62ch] text-ui-md leading-ui-md text-pretty text-neutral3",e),...t})}function hqr({className:e,...t}){return o.jsx("div",{role:"separator","aria-orientation":"horizontal",className:K("h-px bg-border1",e),...t})}function pqr({children:e,className:t,inset:n=!1,...r}){return o.jsx("header",{"data-slot":"section-header",className:K("group-data-[variant=default]/section:grid group-data-[variant=default]/section:grid-cols-[1fr_auto] group-data-[variant=default]/section:items-center","group-data-[variant=flat]/section:flex group-data-[variant=flat]/section:min-w-0 group-data-[variant=flat]/section:flex-col group-data-[variant=flat]/section:gap-4 group-data-[variant=flat]/section:pb-4 sm:group-data-[variant=flat]/section:flex-row sm:group-data-[variant=flat]/section:items-start sm:group-data-[variant=flat]/section:justify-between sm:group-data-[variant=flat]/section:gap-6","group-data-[variant=factory]/section:flex group-data-[variant=factory]/section:min-w-0 group-data-[variant=factory]/section:flex-col group-data-[variant=factory]/section:gap-2 sm:group-data-[variant=factory]/section:flex-row sm:group-data-[variant=factory]/section:items-start sm:group-data-[variant=factory]/section:justify-between sm:group-data-[variant=factory]/section:gap-4",n&&"px-4",t),...r,children:e})}function mqr({className:e,...t}){return o.jsx("div",{"data-slot":"section-header-text",className:K("flex min-w-0 flex-col gap-1.5",e),...t})}function gqr({headingLevel:e="h2",children:t,className:n,...r}){const s=e;return o.jsx(s,{"data-slot":"section-heading",className:K("group-data-[variant=default]/section:flex group-data-[variant=default]/section:items-center group-data-[variant=default]/section:gap-2 group-data-[variant=default]/section:text-ui-lg group-data-[variant=default]/section:font-bold group-data-[variant=default]/section:text-neutral4 group-data-[variant=default]/section:[&>svg]:size-[1.2em] group-data-[variant=default]/section:[&>svg]:opacity-50","group-data-[variant=flat]/section:text-ui-lg group-data-[variant=flat]/section:leading-ui-lg group-data-[variant=flat]/section:font-medium group-data-[variant=flat]/section:text-balance group-data-[variant=flat]/section:text-neutral5","group-data-[variant=factory]/section:text-ui-lg group-data-[variant=factory]/section:leading-ui-lg group-data-[variant=factory]/section:font-medium group-data-[variant=factory]/section:text-balance group-data-[variant=factory]/section:text-neutral5",n),...r,children:t})}function Y4t({variant:e="default",children:t,className:n,...r}){return o.jsx("section",{"data-slot":"section","data-variant":e,className:K("group/section",e==="default"&&"grid gap-4",e==="flat"&&"w-full min-w-0",e==="factory"&&"flex w-full min-w-0 flex-col gap-2",n),...r,children:t})}function k_({children:e,className:t,...n}){return o.jsx("section",{className:K("grid gap-2",t),...n,children:e})}function bje({label:e,description:t,htmlFor:n,children:r,className:s,tone:a="default",viewOnly:i=!1,...l}){const u=K("text-ui-md leading-ui-md",a==="destructive"?"text-accent2":i?"text-neutral3":"text-neutral5","group-data-[variant=factory]/section:font-medium group-data-[variant=flat]/section:font-medium");return o.jsxs("div",{"data-slot":"section-row",className:K("grid min-w-0 gap-3 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-center","sm:group-data-[variant=default]/section:gap-4","group-data-[variant=flat]/section:p-4 sm:group-data-[variant=flat]/section:gap-8","group-data-[variant=factory]/section:px-4 group-data-[variant=factory]/section:py-3 sm:group-data-[variant=factory]/section:gap-4",s),...l,children:[o.jsxs("div",{className:"min-w-0",children:[n?o.jsx(Dt,{htmlFor:n,className:u,children:e}):o.jsx("p",{className:u,children:e}),t!=null?o.jsx("p",{className:"text-ui-md leading-ui-md text-neutral3 mt-1 max-w-[62ch] text-pretty",children:t}):null]}),r!=null?o.jsxs("div",{"data-slot":"section-control",className:K("min-w-0 sm:justify-self-end",i&&"flex items-center gap-2 text-ui-md text-neutral3"),children:[i?o.jsxs(o.Fragment,{children:[o.jsx(KXt,{className:"size-4 shrink-0","aria-hidden":!0}),o.jsx("span",{className:"sr-only",children:"View only: "})]}):null,r]}):null]})}function vqr(e){return o.jsx(bje,{...e})}function yqr(e){return o.jsx(bje,{viewOnly:!0,...e})}function bqr(e){return o.jsx(bje,{tone:"destructive",...e})}function $c(e){return o.jsx(Y4t,{...e})}$c.Header=pqr;$c.HeaderText=mqr;$c.Heading=gqr;$c.Description=fqr;$c.Content=dqr;$c.Row=vqr;$c.ViewOnlyRow=yqr;$c.DestructiveRow=bqr;$c.Divider=hqr;function xqr(){return NI({settings:{fontFamily:"var(--font-mono)",fontSize:"0.8125rem",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"#939393",background:"transparent"},styles:[{tag:[ue.className,ue.propertyName]}]})}function wqr(){const e=Pt.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"0.8125rem"},"&.cm-editor .cm-scroller":{fontFamily:"var(--font-mono)"},".cm-gutters":{backgroundColor:"transparent",color:"var(--neutral2)",borderRight:"none"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-activeLine":{backgroundColor:"transparent"},".cm-activeLineGutter":{backgroundColor:"transparent"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"var(--neutral6)"}}),t=Jg.define([{tag:[ue.comment,ue.bracket],color:"var(--neutral2)"},{tag:[ue.string,ue.meta,ue.regexp],color:"var(--accent1)"},{tag:[ue.atom,ue.bool,ue.special(ue.variableName)],color:"var(--accent6)"},{tag:[ue.keyword,ue.operator,ue.tagName],color:"var(--accent2)"},{tag:[ue.function(ue.propertyName),ue.propertyName],color:"var(--accent5)"},{tag:[ue.definition(ue.variableName),ue.function(ue.variableName),ue.className,ue.attributeName],color:"var(--accent3)"},{tag:[ue.variableName,ue.number],color:"var(--accent5)"},{tag:[ue.name,ue.quote],color:"var(--accent1)"}]);return[e,fS(t)]}const Sqr=()=>{const e=a_().resolvedTheme==="dark";return g.useMemo(()=>e?xqr():wqr(),[e])};function kqr({codeStr:e="",title:t,icon:n,simplified:r=!1}){const s=Sqr(),[a,i]=g.useState(!1),l=g.useMemo(()=>{try{const u=JSON.parse(e);return pxe(u||"")}catch{return!1}},[e]),c=a?e?.replace(/\\n/g,`
513
513
  `):e;return o.jsxs($c,{children:[o.jsxs($c.Header,{children:[o.jsxs($c.Heading,{children:[n,t]}),o.jsxs(es,{children:[o.jsx(_a,{content:e||"No content"}),l&&o.jsx(ie,{onClick:()=>i(!a),children:a?o.jsx(d1,{}):o.jsx(U9,{})})]})]}),e&&o.jsx("div",{className:"border-border1 bg-surface3 text-ui-md text-neutral4 max-h-[30vh] overflow-hidden overflow-y-auto rounded-xl border p-4 break-all dark:border-white/10 dark:bg-black/20",children:r?o.jsx("div",{className:"text-neutral4 px-2 font-mono break-all",children:o.jsx("pre",{className:"text-wrap",children:e})}):o.jsx(rd,{extensions:[nN(),Pt.lineWrapping],theme:s,value:c})})]})}function pxe(e){if(typeof e=="string"){const t=e.indexOf(`
514
- `);return t!==-1&&t!==e.length-1}else{if(Array.isArray(e))return e.some(t=>pxe(t));if(e&&typeof e=="object")return Object.values(e).some(t=>pxe(t))}return!1}function Oqr({children:e,className:t}){return o.jsx(DEt,{render:o.jsx("div",{className:K("grid content-start gap-6 overflow-y-scroll p-6 pb-8 pl-9",t),children:e})})}function Cqr({children:e,className:t}){return o.jsx("div",{className:K("flex items-center justify-between pb-4",t),children:e})}function _qr({children:e,className:t,as:n="h1"}){const r=n;return o.jsx(r,{className:K("flex items-start gap-2 text-header-sm font-semibold text-neutral4","[&>svg]:mt-0.5 [&>svg]:size-[1.25em] [&>svg]:shrink-0 [&>svg]:opacity-70",{"text-header-sm":n==="h1","text-ui-lg":n==="h2"},t),children:e})}function Eqr({onNext:e,onPrevious:t,className:n}){const r=()=>{e?.()},s=()=>{t?.()};return o.jsx("div",{className:K("flex items-center gap-4","[&_svg]:size-[1.1em] [&_svg]:text-neutral3",n),children:(e||t)&&o.jsxs("div",{className:K("flex items-baseline gap-4"),children:[o.jsxs(ie,{onClick:s,disabled:!t,children:["Previous",o.jsx(K1,{})]}),o.jsxs(ie,{onClick:r,disabled:!e,children:["Next",o.jsx(CV,{})]})]})})}function Tqr({dialogTitle:e,dialogDescription:t,isOpen:n,onClose:r,children:s,variant:a="default",level:i=1,className:l}){const c=a==="confirmation",[u,d]=g.useState(null);return o.jsx(RI,{side:"right",open:n,onOpenChange:f=>{f||r?.()},children:o.jsxs(dCe,{children:[!c&&o.jsx(IW,{className:"backdrop-blur-sm"}),o.jsx(AW,{className:c?"pointer-events-none":void 0,children:o.jsxs(RW,{className:K("max-w-none overflow-visible rounded-none border-y-0 border-r-0 border-l border-border2 bg-surface2",{"w-[75vw] 2xl:w-[65vw] 4xl:w-[55vw]":i===1,"w-[70vw] 2xl:w-[59vw] 4xl:w-[48vw]":i===2,"w-[65vw] 2xl:w-[53vw] 4xl:w-[41vw]":i===3,"pointer-events-auto bg-surface2/70 backdrop-blur-sm shadow-none":c},l),children:[o.jsx(PI,{className:"sr-only",children:e}),o.jsx(h4,{className:"sr-only",children:t}),!c&&o.jsx(uCe,{render:o.jsx("button",{type:"button",className:K("absolute top-0 -left-14 flex size-14 appearance-none items-center justify-center rounded-bl-lg border-b border-l border-border2 bg-surface2 text-neutral3",Yr.all,"hover:bg-surface4 hover:text-neutral5"),"aria-label":"Close",children:o.jsx(Ect,{})})}),o.jsx(DEt,{render:o.jsx("div",{ref:d,className:"absolute"})}),o.jsx(iPn,{container:u,children:o.jsx("div",{className:K("grid h-full",{"grid-rows-[auto_1fr]":!c}),children:s})})]})})]})})}function jqr({children:e,className:t}){return o.jsx("div",{className:K("text-ui-md text-neutral5 relative flex h-14 items-center gap-4 pl-6",'[&:after]:absolute [&:after]:inset-x-6 [&:after]:bottom-0 [&:after]:border-b [&:after]:border-border1 [&:after]:content-[""]',t),children:e})}const Ca=Object.assign(Tqr,{Top:jqr,Header:Cqr,Heading:_qr,Content:Oqr,CodeSection:kqr,Nav:Eqr}),wi=()=>{const e=Ye(),t=Ar(),n=Sn({mutationFn:v=>e.createDataset(v),onSuccess:()=>{t.invalidateQueries({queryKey:["datasets"]})}}),r=Sn({mutationFn:v=>e.updateDataset(v),onSuccess:(v,y)=>{t.invalidateQueries({queryKey:["datasets"]}),t.invalidateQueries({queryKey:["dataset",y.datasetId]})}}),s=Sn({mutationFn:v=>e.deleteDataset(v),onSuccess:()=>{t.invalidateQueries({queryKey:["datasets"]})}}),a=Sn({mutationFn:v=>e.addDatasetItem(v),onSuccess:(v,y)=>{t.invalidateQueries({queryKey:["dataset-items",y.datasetId]}),t.invalidateQueries({queryKey:["dataset",y.datasetId]}),t.invalidateQueries({queryKey:["dataset-versions",y.datasetId]})}}),i=Sn({mutationFn:v=>e.updateDatasetItem(v),onSuccess:(v,y)=>{t.invalidateQueries({queryKey:["dataset-items",y.datasetId]}),t.invalidateQueries({queryKey:["dataset-item",y.datasetId,y.itemId]}),t.invalidateQueries({queryKey:["dataset-item-versions",y.datasetId,y.itemId]}),t.invalidateQueries({queryKey:["dataset-versions",y.datasetId]})}}),l=Sn({mutationFn:({datasetId:v,itemId:y})=>e.deleteDatasetItem(v,y),onSuccess:(v,y)=>{t.invalidateQueries({queryKey:["dataset-items",y.datasetId]}),t.invalidateQueries({queryKey:["dataset",y.datasetId]}),t.invalidateQueries({queryKey:["dataset-versions",y.datasetId]})}}),c=Sn({mutationFn:v=>e.batchInsertDatasetItems(v),onSuccess:(v,y)=>{t.invalidateQueries({queryKey:["dataset-items",y.datasetId]}),t.invalidateQueries({queryKey:["dataset",y.datasetId]}),t.invalidateQueries({queryKey:["dataset-versions",y.datasetId]})}}),u=Sn({mutationFn:v=>e.batchDeleteDatasetItems(v),onSuccess:(v,y)=>{t.invalidateQueries({queryKey:["dataset-items",y.datasetId]}),t.invalidateQueries({queryKey:["dataset",y.datasetId]}),t.invalidateQueries({queryKey:["dataset-versions",y.datasetId]})}}),d=Sn({mutationFn:async({datasetId:v,itemIds:y})=>e.batchDeleteDatasetItems({datasetId:v,itemIds:y}),onSuccess:(v,y)=>{t.invalidateQueries({queryKey:["dataset-items",y.datasetId]}),t.invalidateQueries({queryKey:["dataset",y.datasetId]}),t.invalidateQueries({queryKey:["dataset-versions",y.datasetId]})}}),f=Sn({mutationFn:v=>e.generateDatasetItems(v)}),h=Sn({mutationFn:v=>e.triggerDatasetExperiment(v),onSuccess:(v,y)=>{t.invalidateQueries({queryKey:["dataset-experiments",y.datasetId]})}}),p=Sn({mutationFn:v=>e.updateDatasetExperiment(v),onSuccess:(v,y)=>{t.invalidateQueries({queryKey:["experiments"]}),t.invalidateQueries({queryKey:["dataset-experiments",y.datasetId]}),t.invalidateQueries({queryKey:["dataset-experiment",y.datasetId,y.experimentId]})}}),m=Sn({mutationFn:v=>e.updateDatasetExperimentResult(v),onSuccess:(v,y)=>{t.invalidateQueries({queryKey:["experiment-results",y.experimentId]}),t.invalidateQueries({queryKey:["dataset-experiment-results"]}),t.invalidateQueries({queryKey:["review-items"]}),t.invalidateQueries({queryKey:["dataset-review-items"]}),t.invalidateQueries({queryKey:["dataset-completed-items"]}),t.invalidateQueries({queryKey:["experiment-review-summary"]})}});return{createDataset:n,updateDataset:r,deleteDataset:s,addItem:a,updateItem:i,deleteItem:l,deleteItems:d,batchInsertItems:c,batchDeleteItems:u,generateItems:f,triggerExperiment:h,updateExperiment:p,updateExperimentResult:m}};function K4t({initialInput:e,initialGroundTruth:t,initialTrajectory:n,trajectoryLoading:r,initialToolMocks:s,breadcrumb:a,isOpen:i,onClose:l,level:c=2,source:u}){const[d,f]=g.useState(""),[h,p]=g.useState(""),[m,v]=g.useState(""),[y,b]=g.useState(""),[x,w]=g.useState(""),{data:k,isLoading:C}=Xg(),{addItem:_}=wi(),T=k?.datasets??[],E=g.useRef(!1),N=g.useRef(!1),I=g.useRef(!1),A=g.useRef(!1);g.useEffect(()=>{i&&!E.current&&(p(e),v(t),b(n??""),w(s??""),N.current=!!n,I.current=e!=="{}",A.current=!!t),E.current=i,i||(N.current=!1,I.current=!1,A.current=!1)},[i,e,t,n,s]);const P=z=>{I.current=!0,p(z)},L=z=>{A.current=!0,v(z)},D=z=>{N.current=!0,b(z)},B=z=>{w(z)};g.useEffect(()=>{i&&e!=="{}"&&!I.current&&(p(e),I.current=!0)},[i,e]),g.useEffect(()=>{i&&t&&!A.current&&(v(t),A.current=!0)},[i,t]),g.useEffect(()=>{i&&n&&!N.current&&(b(n),N.current=!0)},[i,n]);const H=async z=>{if(z.preventDefault(),!d){Ve.error("Please select a dataset");return}let V;try{V=JSON.parse(h)}catch{Ve.error("Input must be valid JSON");return}let M;if(m.trim())try{M=JSON.parse(m)}catch{Ve.error("Ground Truth must be valid JSON");return}let G;if(y.trim())try{G=JSON.parse(y)}catch{Ve.error("Expected Trajectory must be valid JSON");return}let F;if(x.trim())try{const R=JSON.parse(x);if(!Array.isArray(R)){Ve.error("Tool Mocks must be a JSON array");return}F=R}catch{Ve.error("Tool Mocks must be valid JSON");return}try{await _.mutateAsync({datasetId:d,input:V,groundTruth:M,expectedTrajectory:G,toolMocks:F,...u?{source:u}:{}});const R=T.find(U=>U.id===d);Ve.success(`Item saved to "${R?.name}"`),f(""),p("{}"),v(""),b(""),w(""),l()}catch(R){Ve.error(`Failed to save item: ${R instanceof Error?R.message:"Unknown error"}`)}},q=()=>{f(""),l()};return o.jsxs(Ca,{dialogTitle:"Save as Dataset Item",dialogDescription:"Save data as a dataset item",isOpen:i,onClose:l,level:c,children:[o.jsxs(Ca.Top,{children:[a,"›",o.jsxs(Pl,{children:[o.jsx(hm,{})," Save as Dataset Item"]})]}),o.jsxs(Ca.Content,{children:[o.jsx(Ca.Header,{children:o.jsxs(Ca.Heading,{children:[o.jsx(hm,{})," Save as Dataset Item"]})}),o.jsxs("form",{onSubmit:H,className:"grid gap-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"target-dataset",children:"Dataset *"}),o.jsxs(la,{value:d,onValueChange:f,disabled:_.isPending||C,children:[o.jsx(ua,{id:"target-dataset",children:o.jsx(ca,{placeholder:C?"Loading datasets...":"Select a dataset"})}),o.jsx(da,{children:T.length===0?o.jsx("div",{className:"text-neutral4 px-2 py-4 text-center text-sm",children:"No datasets available"}):T.map(z=>o.jsx(xr,{value:z.id,children:z.name},z.id))})]})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Gr,{value:h,onChange:P,showCopyButton:!1,className:"min-h-[120px]"})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),o.jsx(Gr,{value:m,onChange:L,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),o.jsx(Gr,{value:y,onChange:D,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-tool-mocks",children:"Tool Mocks (JSON, optional)"}),o.jsx(Gr,{value:x,onChange:B,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ie,{type:"button",variant:"outline",onClick:q,children:"Cancel"}),o.jsx(ie,{type:"submit",variant:"default",disabled:_.isPending||r||!d||T.length===0,children:_.isPending?"Saving...":r?"Loading...":"Save Item"})]})]})]})]})}function Nqr(e){return e?yO({input:e.input,output:e.output,groundTruth:null},2):"{}"}function Iqr(e){return e?yO({score:e.score,reason:e.reason??null},2):""}function Aqr({score:e,isOpen:t,onClose:n,level:r=2}){return o.jsx(K4t,{initialInput:Nqr(e),initialGroundTruth:Iqr(e),breadcrumb:o.jsxs(Pl,{children:[o.jsx(gYt,{})," ",y0(e?.id)]}),isOpen:t,onClose:n,level:r,source:e?.traceId?{type:"trace",referenceId:e.traceId}:void 0})}function Rqr(e){if(!e)return!1;const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function LE(e,t,n){return o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"text-neutral2 flex items-center gap-1.5 tracking-widest uppercase [&>svg]:size-3.5",children:[t,e]}),o.jsxs("span",{children:["› Score ",o.jsxs("b",{className:"text-neutral3",children:["#",n.id]})]})]})}function X4t({score:e,onClose:t,onPrevious:n,onNext:r}){const{Link:s}=dn(),[a,i]=g.useState(!1),l=Rqr(e),c=l?"N/A — code-based scorer does not use prompts":"N/A — step not configured";return o.jsxs(o.Fragment,{children:[o.jsxs(Gt,{children:[o.jsxs(Gt.Header,{children:[o.jsxs(Gt.Heading,{children:["Score ",o.jsxs("b",{children:["# ",e.id]})]}),o.jsxs(es,{className:"ml-auto shrink-0",children:[o.jsx(Gt.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Previous score",nextLabel:"Next score"}),o.jsx(Gt.CloseButton,{onClick:t})]})]}),o.jsxs(Gt.Content,{children:[o.jsxs(En,{children:[e.scorer?.name!=null&&o.jsxs(o.Fragment,{children:[o.jsx(En.Key,{children:"Scorer"}),o.jsx(En.Value,{children:String(e.scorer.name)})]}),e.createdAt&&o.jsxs(o.Fragment,{children:[o.jsx(En.Key,{children:"Created"}),o.jsx(En.Value,{children:dr(new Date(e.createdAt),"MMM dd, HH:mm:ss.SSS")})]}),e.traceId&&o.jsxs(o.Fragment,{children:[o.jsx(En.Key,{children:"Trace Id"}),o.jsx(En.ValueLink,{href:`/traces?traceId=${encodeURIComponent(e.traceId)}`,as:s,children:e.traceId})]}),e.spanId&&e.traceId&&o.jsxs(o.Fragment,{children:[o.jsx(En.Key,{children:"Span Id"}),o.jsx(En.ValueLink,{href:`/traces?traceId=${encodeURIComponent(e.traceId)}&spanId=${encodeURIComponent(e.spanId)}`,as:s,children:e.spanId})]})]}),o.jsx("div",{className:"mt-6 mb-6 flex justify-end",children:o.jsxs(ie,{size:"sm",onClick:()=>i(!0),children:[o.jsx(Qe,{children:o.jsx(Qu,{})}),"Save as Dataset Item"]})}),o.jsxs("div",{className:"text-neutral4 mb-6",children:[o.jsxs("div",{className:K("text-neutral2 text-ui-lg flex gap-2 items-baseline","[&>svg]:w-5 [&>svg]:h-5 [&>svg]:translate-y-1"),children:[o.jsx(Qh,{}),o.jsx("span",{className:"",children:"Score:"}),o.jsx("b",{className:"text-neutral3 font-mono",children:`${e.score==null||Number.isNaN(e.score)?"n/a":e.score}`})]}),o.jsx("div",{className:"text-ui-smd mt-2 font-mono",children:e.reason||(l?"N/A — code-based scorer does not generate a reason":"N/A — step not configured")})]}),o.jsxs("div",{className:"grid gap-4",children:[o.jsx(Gt.CodeSection,{title:"Input",dialogTitle:LE("Input",o.jsx(Ox,{}),e),icon:o.jsx(Ox,{}),codeStr:JSON.stringify(e.input??null,null,2)}),o.jsx(Gt.CodeSection,{title:"Output",dialogTitle:LE("Output",o.jsx(nm,{}),e),icon:o.jsx(nm,{}),codeStr:JSON.stringify(e.output??null,null,2)}),o.jsx(Gt.CodeSection,{title:"Preprocess Prompt",dialogTitle:LE("Preprocess Prompt",o.jsx($p,{}),e),icon:o.jsx($p,{}),codeStr:e.preprocessPrompt||c,simplified:!0}),o.jsx(Gt.CodeSection,{title:"Analyze Prompt",dialogTitle:LE("Analyze Prompt",o.jsx($p,{}),e),icon:o.jsx($p,{}),codeStr:e.analyzePrompt||c,simplified:!0}),o.jsx(Gt.CodeSection,{title:"Generate Score Prompt",dialogTitle:LE("Generate Score Prompt",o.jsx($p,{}),e),icon:o.jsx($p,{}),codeStr:e.generateScorePrompt||c,simplified:!0}),o.jsx(Gt.CodeSection,{title:"Generate Reason Prompt",dialogTitle:LE("Generate Reason Prompt",o.jsx($p,{}),e),icon:o.jsx($p,{}),codeStr:e.generateReasonPrompt||c,simplified:!0})]})]})]}),o.jsx(Aqr,{score:e,isOpen:a,onClose:()=>i(!1)})]})}const sXe=["input","entity"],Pqr={input:"Input",entity:"Entity"};function $qr(e){const t=["auto","auto","minmax(0, 10rem)"];return e.has("entity")&&t.push("minmax(0, 14rem)"),e.has("input")&&t.push("minmax(0, 40rem)"),t.join(" ")}function Mqr(e){return{...e,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt)}}function Dqr({scores:e,onScoreClick:t,errorMsg:n,isLoading:r,isFetchingNextPage:s,hasNextPage:a,setEndOfListElement:i,selectedScoreId:l}){const[c,u]=g.useState(l),d=l??c,[f,h]=g.useState(new Set),p=g.useMemo(()=>new Set(sXe.filter(I=>!f.has(I))),[f]),m=g.useMemo(()=>$qr(p),[p]),v=g.useCallback(I=>{h(A=>{const P=new Set(A);return P.has(I)?P.delete(I):P.add(I),P})},[]);g.useEffect(()=>{u(l)},[l]);const y=g.useCallback(I=>{const A=d===I?void 0:I;u(A),t?.(A??"")},[d,t]),b=g.useMemo(()=>d?e?.find(I=>I.id===d):void 0,[e,d]),x=b?e?.indexOf(b)??-1:-1,w=x>0?()=>{const I=e[x-1];u(I.id),t?.(I.id)}:void 0,k=e&&x>=0&&x<e.length-1?()=>{const I=e[x+1];u(I.id),t?.(I.id)}:void 0,{containerRef:C,getRowProps:_}=ao({count:e?.length??0}),T=g.useCallback(()=>{u(void 0),t?.("")},[t]);if(r)return o.jsx(Bo,{columns:m});if(!e)return null;const E=o.jsxs(Ru.Top,{children:[o.jsx(Ru.TopCell,{children:"Date"}),o.jsx(Ru.TopCell,{children:"Time"}),o.jsx(Ru.TopCell,{children:"Score"}),p.has("entity")&&o.jsx(Ru.TopCell,{children:"Entity"}),p.has("input")&&o.jsx(Ru.TopCell,{children:"Input"})]});if(n)return o.jsxs(Ru,{columns:m,children:[E,o.jsx(Ru.NoMatch,{message:n})]});if(e.length===0)return null;const N=!!b;return o.jsxs("div",{className:K("grid h-full max-h-full min-h-0 gap-4",N?"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[o.jsxs("div",{className:"flex h-full min-h-0 min-w-0 flex-col gap-0",children:[o.jsx("div",{className:"flex shrink-0 items-center justify-end pb-2",children:o.jsxs(at,{children:[o.jsx(at.Trigger,{asChild:!0,children:o.jsxs(ie,{variant:"outline",size:"sm",children:[o.jsx(Ict,{className:"size-3.5"}),"Columns"]})}),o.jsxs(at.Content,{align:"end",children:[o.jsx(at.Label,{children:"Toggle columns"}),sXe.map(I=>o.jsx(at.CheckboxItem,{checked:p.has(I),onClick:()=>v(I),children:Pqr[I]},I))]})]})}),o.jsxs(Ru,{columns:m,className:"min-h-0 flex-1",scrollRef:C,children:[E,e.map((I,A)=>o.jsxs(Ru.RowButton,{onClick:()=>y(I.id),className:d===I.id?"bg-surface4":"",..._(A),children:[o.jsx(Ru.DateCell,{timestamp:I.createdAt}),o.jsx(Ru.TimeCell,{timestamp:I.createdAt}),o.jsx(Ru.ScoreCell,{score:I.score}),p.has("entity")&&o.jsx(Ru.EntityCell,{entityId:I.entityId}),p.has("input")&&o.jsx(Ru.InputCell,{input:I.input})]},I.id)),o.jsx(Ru.NextPageLoading,{isLoading:s,hasMore:a,setEndOfListElement:i})]})]}),b&&o.jsx("div",{className:"grid h-full max-h-full min-h-0 grid-rows-[1fr] overflow-hidden",children:o.jsx(X4t,{score:Mqr(b),onClose:T,onPrevious:w,onNext:k})})]})}const Lqr=({onRunExperiment:e})=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx(Mc,{}),titleSlot:"No scores yet",descriptionSlot:"Scores will appear here once a scorer evaluates agents or workflows. More info in the documentation.",actionSlot:o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e&&o.jsxs(ie,{variant:"primary",onClick:e,children:[o.jsx(Dc,{}),"Run Experiment"]}),o.jsxs(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/evals/overview",target:"_blank",rel:"noopener noreferrer",children:["Scorers Documentation ",o.jsx(ta,{})]})]})})});function xje({data:e,className:t,labelsAreHidden:n,isLoading:r,LinkComponent:s}){const a=({children:i})=>n?o.jsx(T1,{children:i}):i;return!e||e.length===0?null:o.jsx("dl",{className:K("grid grid-cols-[auto_1fr] content-start items-start gap-x-4",t),children:e.map(({key:i,label:l,value:c,icon:u,separator:d},f)=>{const h=Array.isArray(c);return o.jsxs(qe.Fragment,{children:[o.jsxs("dt",{className:K("flex min-h-9 items-center justify-between gap-8 text-ui-md text-neutral3"),children:[o.jsxs("span",{className:K("flex items-center gap-2","[&>svg]:size-[1.4em] [&>svg]:text-neutral3 [&>svg]:opacity-50",{"[&>svg]:opacity-20":r}),children:[u," ",o.jsx(a,{children:l})]}),!n&&o.jsx("span",{className:K("text-neutral3","[&>svg]:size-[1em] [&>svg]:text-neutral3"),children:d})]}),o.jsx("dd",{className:K("flex min-h-9 flex-wrap items-center gap-2 py-1 text-ui-md text-wrap text-neutral5","truncate [&>a]:flex [&>a]:min-h-7 [&>a]:w-auto [&>a]:max-w-full [&>a]:items-center [&>a]:gap-2 [&>a]:rounded-md [&>a]:bg-surface4 [&>a]:px-2 [&>a]:py-0.5 [&>a]:text-ui-md [&>a]:leading-none [&>a]:text-neutral5 [&>a]:transition-colors","[&>a:hover]:bg-surface6 [&>a:hover]:text-neutral6","[&>a>svg]:ml-[-0.5em] [&>a>svg]:size-[1em] [&>a>svg]:text-neutral3"),children:r?o.jsx("span",{className:K("w-full rounded-e-lg bg-surface4"),style:{width:`${Math.floor(Math.random()*61)+50}%`},children:" "}):h?c?.map(p=>p.path&&s?o.jsx(aXe,{description:p.description,children:o.jsxs(s,{href:p.path,children:[p?.name," ",o.jsx(Lr,{})]})},p.id):p.path?o.jsx(aXe,{description:p.description,children:o.jsxs("a",{href:p.path,children:[p?.name," ",o.jsx(Lr,{})]})},p.id):o.jsx("span",{children:p?.name},p.id)):o.jsx(o.Fragment,{children:c||o.jsx("span",{className:"text-ui-sm text-neutral3",children:"n/a"})})})]},i??f)})})}function aXe({description:e,children:t}){return e?o.jsxs(iA,{children:[o.jsx(x_,{render:qe.isValidElement(t)?t:void 0}),o.jsx(w_,{className:"max-w-60 text-center",children:e})]}):t}function Fqr({children:e,className:t}){return o.jsx("div",{className:K("grid gap-12",t),children:e})}function zqr({onEntityChange:e,onReset:t,selectedEntity:n,entityOptions:r,isLoading:s}){return o.jsxs(es,{children:[o.jsx(Cm,{label:"Filter by Entity",labelIsHidden:!0,name:"select-entity",placeholder:"Select...",size:"md",options:r||[],onValueChange:a=>{const i=r?.find(l=>l.value===a);i&&e(i)},value:n?.value||"",className:"min-w-56",disabled:s}),n&&n.value!=="all"&&o.jsxs(ie,{onClick:t,disabled:s,size:"md",children:["Reset",o.jsx(Qe,{children:o.jsx(or,{})})]})]})}const Bqr=25,Uqr=5e3;function qqr(e){return z4(e.state.error,"scores")||B4(e.state.error)?!1:Uqr}function Vqr(e,t,n){if(e?.pagination?.hasMore)return n+1}function Hqr(e){const t=new Set;return e.pages.flatMap(r=>r.scores??[]).filter(r=>t.has(r.id)?!1:(t.add(r.id),!0))}const Wqr=({scorerId:e,entityId:t,entityType:n})=>{const r=Ye(),{inView:s,setRef:a}=a0(),i=Ly({queryKey:["scores",e,t,n],queryFn:({pageParam:d})=>r.listScoresByScorerId({scorerId:e,page:d,perPage:Bqr,entityId:t,entityType:n}),initialPageParam:0,getNextPageParam:Vqr,select:Hqr,refetchInterval:qqr}),{hasNextPage:l,isFetchingNextPage:c,fetchNextPage:u}=i;return g.useEffect(()=>{s&&l&&!c&&u()},[s,l,c,u]),{...i,setEndOfListElement:a}},Zqr=e=>{const t=Ye(),[n,r]=g.useState(null),[s,a]=g.useState(!0),[i,l]=g.useState(null);return g.useEffect(()=>{(async()=>{a(!0),l(null);try{const u=await t.getScorer(e);r(u)}catch(u){r(null);const d=u instanceof Error?u:new Error("Error fetching scorer");l(d),console.error("Error fetching scorer",u),Ve.error("Error fetching scorer")}finally{a(!1)}})()},[e,t]),{scorer:n,isLoading:s,error:i}},up=()=>{const e=Ye(),t=Zl();return mt({queryKey:["scorers",t],queryFn:()=>e.listScorers(t),staleTime:0,gcTime:0})};function Gqr({value:e,onValueChange:t,placeholder:n="Select a scorer...",searchPlaceholder:r="Search scorers...",emptyText:s="No scorers found.",className:a,disabled:i=!1,variant:l,size:c}){const{data:u={},isLoading:d,isError:f,error:h}=up(),{navigate:p,paths:m}=dn();g.useEffect(()=>{if(f){const b=h instanceof Error?h.message:"Failed to load scorers";Ve.error(`Error loading scorers: ${b}`)}},[f,h]);const v=Object.keys(u).map(b=>({label:u[b]?.scorer.config.name||b,value:b})),y=b=>{t?t(b):b&&b!==e&&p(m.scorerLink(b))};return o.jsx(vl,{options:v,value:e,onValueChange:y,placeholder:d?"Loading scorers...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||d||f,variant:l,size:c})}function J4t({children:e,className:t}){return o.jsx("div",{className:K("rounded-xl border border-border1 bg-surface-overlay-soft px-4 py-3",t),children:e})}function Qqr({changePct:e,prevValue:t,lowerIsBetter:n,className:r}){const s=n?e<0:e>=0;return o.jsxs("div",{className:K("flex flex-wrap items-center gap-1 text-sm text-neutral1",r),children:[o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("span",{className:K("[&>svg]:size-4",s?"text-green-600":"text-red-600"),children:e>=0?o.jsx(otn,{}):o.jsx(atn,{})}),o.jsx("span",{className:K(s?"text-green-600":"text-red-600"),children:`${e>=0?"+":"-"}${Math.abs(e).toFixed(1)}%`})]}),t&&o.jsxs("div",{children:["vs previous ",o.jsx("b",{className:"text-neutral2 font-semibold",children:t})]})]})}function Yqr({message:e="Failed to load data",className:t}){return o.jsx("span",{className:K("text-ui-sm text-accent2",t),children:e})}function Kqr({children:e,className:t}){return o.jsx("span",{className:K("text-ui-md leading-relaxed text-neutral3",t),children:e})}function Xqr({className:e}){return o.jsx("span",{className:K("text-sm",e),children:o.jsx(Vt,{size:"md",variant:"pulse",className:"text-neutral1"})})}function Jqr({message:e="No previous value to compare",className:t}){return o.jsx("span",{className:K("text-sm text-neutral1",t),children:e})}function eVr({message:e="No data yet",className:t}){return o.jsx("span",{className:K("text-sm text-neutral1",t),children:e})}function tVr({children:e,className:t}){return o.jsx(J4t,{className:K("min-w-72 flex-1",t),children:o.jsx("div",{className:"grid gap-1",children:e})})}function nVr({children:e,className:t}){return o.jsx("strong",{className:K("text-header-lg font-semibold text-neutral4",t),children:e})}const Xr=Object.assign(tVr,{Label:Kqr,Value:nVr,Change:Qqr,NoChange:Jqr,NoData:eVr,Error:Yqr,Loading:Xqr});function rVr({children:e,className:t}){return o.jsx("div",{className:K("flex shrink-0 items-center gap-1",t),children:e})}function sVr({children:e,className:t}){return o.jsx("div",{className:K("overflow-x-auto ",t),children:e})}function eLt({children:e,className:t}){return o.jsx("p",{className:K("mt-0.5 text-ui-md leading-tight text-neutral2",t),children:e})}function aVr({message:e="Failed to load data",className:t}){return o.jsx("div",{className:K("flex flex-col items-center justify-center gap-3",t),children:o.jsx("p",{className:"text-ui-sm text-accent2",children:e})})}function iVr({className:e}){return o.jsx("div",{className:K("flex items-center justify-center",e),children:o.jsx(Vt,{size:"md",variant:"pulse",className:"text-neutral1"})})}function oVr({message:e="No data yet",className:t}){return o.jsx("div",{className:K("flex h-full items-center justify-center",t),children:o.jsx("p",{className:"text-neutral1 text-sm",children:e})})}function iXe({children:e,className:t}){return o.jsx(J4t,{className:K("2xl:min-w-120 md:min-w-88 xl:min-w-104 grid min-h-72 min-w-80 flex-1 grid-rows-[4rem_1fr] gap-2 lg:min-w-sm",t),children:e})}function lVr({value:e,label:t,className:n}){return o.jsxs("div",{className:K("grid content-start justify-end gap-1 text-right",n),children:[o.jsx("span",{className:"text-ui-lg text-neutral4 leading-none font-semibold",children:e}),t&&o.jsx("span",{className:"text-ui-md text-neutral2",children:t})]})}function tLt({children:e,className:t,as:n="h2"}){return o.jsx(n,{className:K("text-ui-md font-normal text-neutral4",t),children:e})}function cVr(e){if("children"in e)return o.jsx("div",{className:e.className,children:e.children});const{title:t,description:n,titleAs:r}=e;return o.jsxs("div",{className:e.className,children:[o.jsx(tLt,{as:r,children:t}),n&&o.jsx(eLt,{children:n})]})}function uVr({children:e,className:t}){return o.jsx("div",{className:K("flex items-start gap-4 [&>:first-child]:min-w-0 [&>:first-child]:flex-1",t),children:e})}const Ht=Object.assign(iXe,{Root:iXe,Kpi:Xr,TopBar:uVr,Actions:rVr,TitleAndDescription:cVr,Title:tLt,Description:eLt,Summary:lVr,Loading:iVr,Error:aVr,Content:sVr,NoData:oVr});function dVr({active:e,payload:t,label:n,suffix:r}){return!e||!t?.length?null:o.jsxs("div",{className:"border-border1 bg-surface2 rounded-md border px-3 py-2 text-xs shadow-lg",children:[o.jsx("p",{className:"text-icon6 mb-1 font-medium",children:n}),t.map(s=>o.jsxs("p",{className:"text-icon2",children:[o.jsx("span",{className:"mr-2 inline-block size-2 rounded-full",style:{backgroundColor:s.color}}),s.name,":"," ",o.jsxs("span",{className:"font-mono",children:[s.value,r]})]},s.name))]})}const oXe="#a1a1aa";function ID({data:e,series:t,height:n=210,yDomain:r,onPointClick:s,xAxisInterval:a=5,xAxisMinTickGap:i,showDots:l=!1}){const c=typeof s=="function";return o.jsxs("div",{children:[o.jsx("div",{className:"mb-4 flex w-full flex-wrap items-end gap-4 gap-y-1",children:t.map(u=>{const d=u.aggregate?.(e);return o.jsxs("div",{className:"inline-flex items-baseline gap-2",children:[o.jsx("div",{className:"size-2 shrink-0 -translate-y-px rounded-full",style:{backgroundColor:u.color}}),o.jsx("span",{className:"text-ui-sm text-neutral3 max-w-24 truncate",children:u.label}),d&&o.jsxs("span",{className:"text-ui-sm text-neutral4",children:[d.value,d.suffix&&o.jsxs("span",{className:"text-ui-sm text-neutral2",children:[" ",d.suffix]})]})]},u.dataKey)})}),o.jsx("div",{style:{height:n},children:o.jsx(S4,{width:"100%",height:"100%",children:o.jsxs(QEr,{data:e,children:[o.jsx(WRt,{stroke:"currentColor",strokeOpacity:.08,vertical:!1,className:"text-black dark:text-white"}),o.jsx(P4,{dataKey:"time",tick:{fontSize:10,fill:oXe,fontFamily:"var(--font-mono)"},tickLine:!1,axisLine:!1,interval:a,minTickGap:i}),o.jsx($4,{tick:{fontSize:10,fill:oXe,fontFamily:"var(--font-mono)"},tickLine:!1,axisLine:!1,width:30,domain:r}),o.jsx(RZ,{content:o.jsx(dVr,{})}),t.map(u=>o.jsx(tPt,{type:"linear",dataKey:u.dataKey,stroke:u.color,strokeWidth:2,dot:l?{r:3,fill:u.color,strokeWidth:0}:!1,activeDot:c?{r:4,style:{cursor:"pointer"},onClick:(d,f)=>{const h=f?.payload;h&&s(h,u.dataKey)}}:void 0,name:u.label},u.dataKey))]})})})]})}const lXe=["#22c55e","#4f83f1","#8b5cf6","#fb923c","#f472b6","#facc15"];function fVr({summaryData:e,overTimeData:t,scorerNames:n,avgScore:r,isLoading:s,isError:a}){const i=e.length>0,l=g.useMemo(()=>n.map((c,u)=>({dataKey:c,label:c,color:lXe[u%lXe.length],aggregate:d=>({value:d.length>0?(d.reduce((f,h)=>f+(h[c]??0),0)/d.length).toFixed(2):"0",suffix:"avg"})})),[n]);return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Scores",description:"Evaluation scorer performance across all scorers."}),i&&o.jsx(Ht.Summary,{value:r!=null?`avg ${r}`:"—",label:"Across all scorers"})]}),s?o.jsx(Ht.Loading,{}):a?o.jsx(Ht.Error,{message:"Failed to load scores data"}):o.jsx(Ht.Content,{children:i?o.jsxs(Zc,{defaultTab:"over-time",className:"overflow-visible",children:[o.jsxs(Wc,{children:[o.jsx(Qr,{value:"over-time",children:"Over Time"}),o.jsx(Qr,{value:"summary",children:"Summary"})]}),o.jsx(_s,{value:"over-time",children:t.length>0?o.jsx(ID,{data:t,series:l,yDomain:[0,1]}):o.jsx(Ht.NoData,{message:"No time series data yet"})}),o.jsx(_s,{value:"summary",children:o.jsxs(pe,{columns:"auto auto auto auto auto",className:"max-h-80",mask:{left:!1},children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{sticky:"start",children:"Scorer"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Avg"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Min"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Max"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Count"})]}),e.map(c=>o.jsxs(pe.RowStatic,{children:[o.jsx(pe.RowHeaderCell,{className:"text-ui-sm",children:c.scorer}),o.jsx(pe.NumberCell,{highlight:!0,children:c.avg.toFixed(2)}),o.jsx(pe.NumberCell,{children:c.min.toFixed(2)}),o.jsx(pe.NumberCell,{children:c.max.toFixed(2)}),o.jsx(pe.NumberCell,{children:c.count.toLocaleString()})]},c.scorer))]})})]}):o.jsx(Ht.NoData,{message:"No scores data yet"})})]})}const cXe="minmax(0,1fr) minmax(0,1.5fr) auto auto auto";function hVr({scorers:e,isLoading:t,search:n="",sourceFilter:r="all"}){const{paths:s,Link:a}=dn(),i=g.useMemo(()=>Object.entries(e).map(([d,f])=>({...f,id:d})),[e]),l=g.useMemo(()=>{const d=n.toLowerCase();return i.filter(f=>{const h=!d||f.scorer.config?.id?.toLowerCase().includes(d)||f.scorer.config?.name?.toLowerCase().includes(d),p=r==="all"||f.source===r;return h&&p})},[i,n,r]),{containerRef:c,getRowProps:u}=ao({count:l.length});return t?o.jsx(Bo,{columns:cXe}):o.jsxs(pe,{columns:cXe,scrollRef:c,children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{children:"Name"}),o.jsx(pe.TopCell,{children:"Description"}),o.jsx(pe.TopCell,{children:"Source"}),o.jsx(pe.TopCellSmart,{long:"Agents",short:o.jsx(Ri,{}),tooltip:"Number of attached Agents",className:"text-center"}),o.jsx(pe.TopCellSmart,{long:"Workflows",short:o.jsx(fI,{}),tooltip:"Number of attached Workflows",className:"text-center"})]}),l.map((d,f)=>{const h=d.scorer.config?.name||d.id,p=d.scorer.config?.description||"",m=d.agentIds?.length??0,v=d.workflowIds?.length??0,y=d.scorer.config?.type==="trajectory";return o.jsxs(pe.RowLink,{to:s.scorerLink(d.id),LinkComponent:a,...u(f),children:[o.jsx(pe.NameCell,{children:o.jsxs("span",{className:"flex max-w-full min-w-0 items-center gap-1.5",children:[o.jsx("span",{className:"min-w-0 truncate",children:h}),y&&o.jsx(bt,{size:"xs",variant:"purple",className:"shrink-0",children:"trajectory"})]})}),o.jsx(pe.DescriptionCell,{children:p}),o.jsx(pe.Cell,{children:o.jsx(bt,{size:"xs",variant:d.source==="code"?"blue":"neutral",children:d.source})}),o.jsx(pe.TextCell,{className:"text-center",children:m||""}),o.jsx(pe.TextCell,{className:"text-center",children:v||""})]},d.id)})]})}const pVr=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx(Mc,{}),titleSlot:"No Scorers yet",descriptionSlot:"Configure scorers in code to get started. More info in the documentation.",actionSlot:o.jsxs(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/evals/overview",target:"_blank",rel:"noopener noreferrer",children:["Scorers Documentation ",o.jsx(ta,{})]})})}),mVr=[{value:"all",label:"All sources"},{value:"code",label:"Code"},{value:"stored",label:"Stored"}];function gVr({search:e,onSearchChange:t,sourceFilter:n,onSourceFilterChange:r,onReset:s,hasActiveFilters:a}){const[i,l]=g.useState(e),c=g.useRef(e),u=Uy(p=>{c.current=p,t(p)},300);g.useEffect(()=>{e!==c.current&&(c.current=e,u.cancel(),l(e))},[e,u]),g.useEffect(()=>()=>u.cancel(),[u]);const d=g.useCallback(p=>{l(p.target.value),u(p.target.value)},[u]),f=g.useCallback(()=>{c.current="",u.cancel(),l(""),t("")},[t,u]),h=g.useCallback(()=>{c.current="",u.cancel(),l(""),s?.()},[s,u]);return o.jsxs("div",{className:"flex w-full max-w-[40rem] items-center gap-2",children:[o.jsxs(es,{spacing:"close",className:"min-w-0 flex-1",children:[o.jsxs(du,{variant:"outline",size:"default",children:[o.jsx(Ic,{align:"inline-start",children:o.jsx(Ds,{})}),o.jsx(fu,{name:"scorer-search",type:"search","aria-label":"Search scorers",placeholder:"Filter by scorer name",value:i,onChange:d}),i&&o.jsx(Ic,{align:"inline-end",children:o.jsx(ije,{"aria-label":"Clear search",onClick:f,children:o.jsx(or,{})})})]}),o.jsxs(la,{value:n,onValueChange:r,children:[o.jsx(ua,{"aria-label":"Filter by source",className:"rounded-full",children:o.jsx(ca,{placeholder:"All sources"})}),o.jsx(da,{align:"end",children:mVr.map(p=>o.jsx(xr,{value:p.value,children:p.label},p.value))})]})]}),s&&a&&o.jsxs(ie,{onClick:h,variant:"outline",children:[o.jsx(or,{})," Reset"]})]})}const mxe={checked(e){return e?{"data-checked":""}:{"data-unchecked":""}},...Im,...r_},nLt=g.createContext(void 0);function vVr(){return g.useContext(nLt)}const rLt=g.createContext(void 0);function yVr(){const e=g.useContext(rLt);if(e===void 0)throw new Error(Ir(52));return e}const bVr=g.forwardRef(function(t,n){const{render:r,className:s,disabled:a=!1,readOnly:i=!1,required:l=!1,"aria-labelledby":c,value:u,inputRef:d,nativeButton:f=!1,id:h,style:p,...m}=t,v=vVr(),{disabled:y,readOnly:b,required:x,form:w,checkedValue:k,touched:C=!1,validation:_,name:T,setCheckedValue:E=ra,setTouched:N=ra,registerInputRef:I=ra}=v??{},{setTouched:A,setFilled:P,state:L,disabled:D}=Pm(),B=zxt(),{labelId:H,getDescriptionProps:q}=r0(),z=D||B.disabled||y||a,V=b||i,M=x||l,G=w,F=v?k===u:u==="",R=g.useRef(null),U=g.useRef(null),Z=_?.registerInput,Y=g.useCallback(Me=>Z?.(Me,{controlRef:R,value:void 0}),[Z]),te=qd(d,U,I,Y);Tt(()=>{U.current?.checked&&P(!0)},[P]),Tt(()=>{if(U.current){if(z&&F){I(null);return}I(U.current)}},[F,z,I]);const J=Vi(),ee=s_({id:h,implicit:!1,controlRef:R}),re=f?void 0:ee,ae=RSe(c,H,U,!f,re),X={role:"radio","aria-checked":F,"aria-labelledby":ae,[VEe]:F?"":void 0,id:f?ee:J,onKeyDown(Me){Me.key==="Enter"&&Me.preventDefault()},onClick(Me){if(Me.defaultPrevented||z||V)return;Me.preventDefault();const Pe=U.current;Pe&&iO(Pe,Me)},onFocus(Me){Me.defaultPrevented||z||V||!C||(U.current?.click(),N(!1))}},{getButtonProps:ne,buttonRef:se}=Yd({disabled:z,native:f,composite:!1}),ce={type:"radio",ref:te,form:G,id:re,name:T,tabIndex:-1,style:T?gI:k1,"aria-hidden":!0,...u!==void 0?{value:K7(u)}:ya,disabled:z,checked:F,required:M,readOnly:V,onChange(Me){if(Me.nativeEvent.defaultPrevented||z||V||u===void 0)return;const Pe=nn(Ji,Me.nativeEvent);E(u,Pe),!Pe.isCanceled&&A(!0)},onClick(Me){Me.stopPropagation()},onFocus(){R.current?.focus()}},le=g.useMemo(()=>({...L,required:M,disabled:z,readOnly:V,checked:F}),[L,z,V,F,M]),be=le,he=v!==void 0,xe=[n,R,se],Ae=[X,m,ne,q,_?Me=>_.getValidationProps(z,Me):ya],De=In("span",t,{enabled:!he,state:le,ref:xe,props:Ae,stateAttributesMapping:mxe});return o.jsxs(rLt.Provider,{value:be,children:[he?o.jsx(T$t,{tag:"span",render:r,className:s,style:p,state:le,refs:xe,props:Ae,stateAttributesMapping:mxe}):De,o.jsx("input",{...ce,suppressHydrationWarning:!0})]})}),xVr=g.forwardRef(function(t,n){const{render:r,className:s,style:a,keepMounted:i=!1,...l}=t,c=yVr(),u=c.checked,{mounted:d,transitionStatus:f,setMounted:h}=Kg(u),p={...c,transitionStatus:f},m=g.useRef(null),v=i||d,y=In("span",t,{ref:[n,m],state:p,props:l,stateAttributesMapping:mxe});return hc({open:u,ref:m,onComplete(){u||h(!1)}}),v?y:null});function wVr(e,t){return e.matches(":disabled")?!1:!t||e.form===t?!0:e.form===null&&!e.hasAttribute("form")}const SVr=g.createContext(void 0);function kVr(e=!1){const t=g.useContext(SVr);if(!t&&!e)throw new Error(Ir(86));return t}const OVr=[bxt],CVr=g.forwardRef(function(t,n){const{render:r,className:s,disabled:a,readOnly:i,required:l,onValueChange:c,value:u,defaultValue:d,form:f,name:h,inputRef:p,id:m,style:v,...y}=t,{setTouched:b,setFocused:x,validationMode:w,name:k,disabled:C,state:_,validation:T,setDirty:E,setFilled:N,validityData:I}=Pm(),{labelId:A}=r0(),{clearErrors:P,elementRef:L}=kI(),D=kVr(!0),B=C||a,H=k??h,q=Vi(m),[z,V]=Rf({controlled:u,default:d,name:"RadioGroup",state:"value"}),[M,G]=g.useState(!1),F=yt((se,ce)=>{c?.(se,ce),!ce.isCanceled&&V(se)}),R=T.getInputControl,U=g.useMemo(()=>({get current(){return R()}}),[R]),Z=g.useRef(null),Y=g.useRef(null);function te(se){let ce;return p&&(typeof p=="function"?ce=p(se):p.current=se),Z.current=se,ce}const J=yt(se=>{if(!se||se.disabled)return;Y.current||(Y.current=se);const ce=Z.current,le=se.checked||ce==null||ce.disabled?te(se):void 0;return()=>{Y.current===se&&(Y.current=null),Z.current===se?le?(le(),Z.current=null):te(null):le?.()}}),ee=yt(()=>{const se=L.current;if(!se)return z??null;for(const ce of T.registeredInputs.keys())if(ce.checked&&wVr(ce,se))return z??null;return null});SI(U,q,z??null,ee,!B,h),Xv(z,()=>{P(H),E(z!==I.initialValue),N(z!=null),T.change(z);const se=Y.current;z==null&&se&&!se.disabled&&te(se)});const re=A??D?.legendId,ae={..._,disabled:B??!1,required:l??!1,readOnly:i??!1},X=g.useMemo(()=>({checkedValue:z,disabled:B,form:f,validation:T,name:H,readOnly:i,registerInputRef:J,required:l,setCheckedValue:F,setTouched:G,touched:M}),[z,B,f,T,H,i,J,l,F,G,M]),ne={id:m,role:"radiogroup","aria-required":l||void 0,"aria-disabled":B||void 0,"aria-readonly":i||void 0,"aria-labelledby":re,onFocus(){x(!0)},onBlur(se){cn(se.currentTarget,se.relatedTarget)||(b(!0),x(!1),w==="onBlur"&&T.commit(z))},onKeyDownCapture(se){se.key.startsWith("Arrow")&&(G(!0),x(!0))}};return o.jsx(nLt.Provider,{value:X,children:o.jsx(QPt,{render:r,className:s,style:v,state:ae,props:[ne,y,se=>T.getValidationProps(B??!1,se)],refs:[n],stateAttributesMapping:r_,enableHomeAndEndKeys:!1,modifierKeys:OVr})})}),nL=g.forwardRef(({className:e,...t},n)=>o.jsx(CVr,{ref:n,"data-slot":"radio-group",className:K("grid gap-2",e),...t}));nL.displayName="RadioGroup";const Mh=g.forwardRef(({className:e,...t},n)=>o.jsx(bVr,{ref:n,"data-slot":"radio-group-item",className:K("flex size-4 shrink-0 cursor-pointer items-center justify-center rounded-full","border border-neutral6/[0.06] bg-neutral6/[0.12] text-surface1 outline-hidden",Yr.all,"hover:border-neutral6/[0.12] hover:bg-neutral6/[0.16]","active:scale-95 active:border-neutral6/[0.18] active:bg-neutral6/[0.18]","focus-visible:border-neutral5/50 focus-visible:outline-1 focus-visible:outline-offset-2 focus-visible:outline-neutral5/55 focus-visible:outline-solid","data-[checked]:border-neutral6 data-[checked]:bg-neutral6 data-[checked]:text-surface1","data-[checked]:hover:border-neutral5 data-[checked]:hover:bg-neutral5","data-[checked]:active:border-neutral4 data-[checked]:active:bg-neutral4","data-[disabled]:cursor-not-allowed data-[disabled]:border-neutral6/[0.38] data-[disabled]:bg-neutral6/[0.38] data-[disabled]:hover:border-neutral6/[0.38] data-[disabled]:hover:bg-neutral6/[0.38] data-[disabled]:active:scale-100","data-[disabled]:data-[checked]:border-neutral6/[0.38] data-[disabled]:data-[checked]:bg-neutral6/[0.38] data-[disabled]:data-[checked]:text-neutral6",e),...t,children:o.jsx(xVr,{keepMounted:!0,className:K("flex items-center justify-center text-current","scale-50 opacity-0 transition-[opacity,scale] duration-200 ease-out-custom","data-[checked]:scale-100 data-[checked]:opacity-100","data-[starting-style]:scale-50 data-[starting-style]:opacity-0","data-[ending-style]:scale-50 data-[ending-style]:opacity-0"),children:o.jsx("span",{className:"size-1.5 rounded-full bg-current"})})}));Mh.displayName="RadioGroupItem";function Ld({title:e,subtitle:t,icon:n,className:r}){return o.jsxs("header",{className:K("flex flex-col w-fit",r),children:[o.jsxs(ve,{as:"h2",variant:"header-md",className:"flex items-center gap-2",children:[n&&o.jsx(Qe,{size:"lg",className:"text-accent1",children:n}),e]}),t&&o.jsx(ve,{className:"text-ui-md text-neutral3 !font-light",children:t})]})}function b0({title:e,icon:t}){return o.jsxs(ve,{as:"h4",variant:"ui-sm",className:"text-neutral2 flex items-center gap-1 uppercase",children:[t&&o.jsx(Qe,{size:"sm",className:"text-neutral1",children:t}),e]})}const gxe=e=>"field"in e,sLt=e=>e?e.conditions.reduce((t,n)=>gxe(n)?t+1:t+sLt(n),0):0,wje=()=>({field:"",operator:"equals",value:""}),_Vr=(e="AND")=>({operator:e,conditions:[wje()]}),AD=e=>Array.isArray(e.type)?e.type.find(t=>t!=="null")||"string":e.type||"string",aLt=e=>{const t=AD(e);return t==="object"&&e.properties?Object.keys(e.properties).length>0:t==="array"&&e.items?AD(e.items)==="object"&&!!e.items.properties:!1},vxe=(e,t="")=>e?Object.entries(e).map(([n,r])=>{const s=t?`${t}.${n}`:n,a=AD(r),i=aLt(r);return{path:s,label:r.title||n,type:a,hasChildren:i,children:a==="object"?r.properties:void 0,items:a==="array"?r.items:void 0}}):[],EVr=e=>vxe(e.properties),TVr=(e,t)=>e.type==="object"&&e.children?vxe(e.children,t):e.type==="array"&&e.items&&AD(e.items)==="object"&&e.items.properties?vxe(e.items.properties,t):[],iLt=e=>e.split(".").filter(Boolean),oLt=(e,t)=>{const n=iLt(t);if(n.length===0)return;let r=e.properties,s="",a;for(let i=0;i<n.length;i++){const l=n[i];if(l===void 0)return;const c=r?.[l];if(!c)return;s=s?`${s}.${l}`:l;const u=AD(c),d=aLt(c);a={path:s,label:c.title||l,type:u,hasChildren:d,children:u==="object"?c.properties:void 0,items:u==="array"?c.items:void 0},u==="object"&&c.properties?r=c.properties:u==="array"&&c.items?.properties?r=c.items.properties:r=void 0}return a},jVr=e=>{switch(e){case"object":return o.jsx(sc,{});case"array":return o.jsx(u1,{});case"number":case"integer":return o.jsx(AV,{});case"boolean":return o.jsx(z0e,{});default:return o.jsx(U0e,{})}},NVr=({options:e,value:t,onChange:n,placeholder:r="Select field",className:s})=>o.jsx("div",{className:K("relative",s),children:o.jsxs(la,{value:t,onValueChange:n,children:[o.jsx(ua,{className:"bg-surface4 text-neutral6 min-w-35",size:"sm",children:o.jsx(ca,{placeholder:r})}),o.jsx(da,{children:e.map(a=>o.jsx(xr,{value:a.path,children:o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(Qe,{size:"sm",className:"text-neutral3",children:jVr(a.type)}),a.label,a.hasChildren&&o.jsx("span",{className:"text-neutral3",children:"..."})]})},a.path))})]})}),IVr=({schema:e,value:t,onChange:n,className:r})=>{const s=g.useMemo(()=>iLt(t),[t]),a=g.useMemo(()=>{const l=[],c=EVr(e);if(c.length===0)return l;l.push({options:c,value:s[0]||"",basePath:""});let u="";for(let d=0;d<s.length;d++){const f=s[d];if(f===void 0)break;u=u?`${u}.${f}`:f;const h=oLt(e,u);if(!h||!h.hasChildren)break;const p=TVr(h,u);if(p.length===0)break;const m=s[d+1],v=m?`${u}.${m}`:"";l.push({options:p,value:v,basePath:u})}return l},[e,s]),i=g.useCallback((l,c)=>{n(c)},[n]);return a.length===0?o.jsx("div",{className:K("text-sm text-neutral3",r),children:"No fields available"}):o.jsx("div",{className:K("flex items-center gap-1",r),children:a.map((l,c)=>o.jsxs(g.Fragment,{children:[c>0&&o.jsx("span",{className:"text-neutral3",children:"."}),o.jsx(NVr,{options:l.options,value:l.value,onChange:u=>i(c,u),placeholder:c===0?"Select field":"Select property"})]},`${l.basePath}-${c}`))})},AVr={equals:"equals",not_equals:"not equals",contains:"contains",not_contains:"not contains",greater_than:"greater than",less_than:"less than",greater_than_or_equal:"greater than or equal",less_than_or_equal:"less than or equal",in:"in",not_in:"not in",exists:"exists",not_exists:"not exists"},RVr=["equals","not_equals","contains","not_contains","greater_than","less_than","greater_than_or_equal","less_than_or_equal","in","not_in","exists","not_exists"],PVr={equals:o.jsx(Rct,{}),not_equals:o.jsx(EKt,{}),contains:o.jsx(Ken,{}),not_contains:o.jsx(d1,{}),greater_than:o.jsx(Lr,{}),less_than:o.jsx(KD,{}),greater_than_or_equal:o.jsx(Ect,{}),less_than_or_equal:o.jsx(IYt,{}),in:o.jsx(u1,{}),not_in:o.jsx(ZXt,{}),exists:o.jsx(Ur,{}),not_exists:o.jsx(k0e,{})},$Vr=({value:e,onChange:t,operators:n,className:r})=>{const s=n??RVr;return o.jsx("div",{className:K("relative",r),children:o.jsxs(la,{value:e,onValueChange:t,children:[o.jsx(ua,{className:"bg-surface4 text-neutral6 min-w-[150px]",size:"sm",children:o.jsx(ca,{placeholder:"Select operator"})}),o.jsx(da,{children:s.map(a=>o.jsx(xr,{value:a,children:o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(Qe,{size:"sm",className:"text-neutral3",children:PVr[a]}),AVr[a]]})},a))})]})})},lLt=e=>{const t=e.trim();if(t==="")return"";if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;const n=t.toLowerCase();if(n==="infinity"||n==="-infinity"||n==="nan")return t;const r=Number(t);return Number.isNaN(r)?e:r},MVr=e=>e.trim()===""?[]:e.split(",").map(t=>lLt(t.trim())),Qq=e=>e===null?"null":e===void 0?"":Array.isArray(e)?e.map(Qq).join(", "):String(e),DVr=e=>e===!0?"true":e===!1?"false":"",LVr=({value:e,onChange:t,className:n})=>{const r=DVr(e),s=g.useCallback(a=>{t(a==="true")},[t]);return o.jsxs("div",{className:K("relative",n),children:[o.jsx(Qe,{size:"sm",className:"text-neutral3 pointer-events-none absolute top-1/2 left-2 z-10 -translate-y-1/2",children:o.jsx(z0e,{})}),o.jsxs(la,{value:r,onValueChange:s,children:[o.jsx(ua,{className:"bg-surface4 min-w-35 pl-7",size:"sm",children:o.jsx(ca,{placeholder:"Select value"})}),o.jsxs(da,{children:[o.jsx(xr,{value:"true",children:"true"}),o.jsx(xr,{value:"false",children:"false"})]})]})]})},FVr=({value:e,onChange:t,placeholder:n,className:r})=>{const s=e===void 0||e===""?"":String(e),a=g.useCallback(i=>{const l=i.target.value;if(l==="")t("");else{const c=Number(l);t(Number.isNaN(c)?l:c)}},[t]);return o.jsxs("div",{className:K("relative",r),children:[o.jsx(Qe,{size:"sm",className:"text-neutral3 pointer-events-none absolute top-1/2 left-2 -translate-y-1/2",children:o.jsx(AV,{})}),o.jsx(jn,{type:"number",value:s,onChange:a,placeholder:n||"Enter number",className:"bg-surface4 min-w-35 pl-7",size:"sm"})]})},zVr=({value:e,onChange:t,placeholder:n,className:r})=>{const s=Qq(e),a=g.useCallback(i=>{t(lLt(i.target.value))},[t]);return o.jsxs("div",{className:K("relative",r),children:[o.jsx(Qe,{size:"sm",className:"text-neutral3 pointer-events-none absolute top-1/2 left-2 -translate-y-1/2",children:o.jsx(U0e,{})}),o.jsx(jn,{value:s,onChange:a,placeholder:n||"Enter value",className:"bg-surface4 min-w-35 pl-7",size:"sm"})]})},BVr=({value:e,onChange:t,placeholder:n,className:r})=>{const s=g.useMemo(()=>Array.isArray(e)?e.map(Qq).join(", "):Qq(e),[e]),a=g.useCallback(i=>{t(MVr(i.target.value))},[t]);return o.jsx(jn,{value:s,onChange:a,placeholder:n||"Enter values (comma-separated)",className:K("min-w-40 bg-surface4",r),size:"sm"})},UVr=({value:e,onChange:t,operator:n,fieldType:r,placeholder:s,className:a})=>n==="in"||n==="not_in"?o.jsx(BVr,{value:e,onChange:t,placeholder:s,className:a}):r==="boolean"?o.jsx(LVr,{value:e,onChange:t,placeholder:s,className:a}):r==="number"||r==="integer"?o.jsx(FVr,{value:e,onChange:t,placeholder:s,className:a}):o.jsx(zVr,{value:e,onChange:t,placeholder:s,className:a}),qVr=new Set(["string","number","boolean","integer"]),VVr=({schema:e,rule:t,onChange:n,onRemove:r,className:s})=>{const a=g.useMemo(()=>oLt(e,t.field)?.type,[e,t.field]),i=a!==void 0&&qVr.has(a),l=a==="array",c=t.operator==="in"||t.operator==="not_in",u=t.operator==="exists"||t.operator==="not_exists",d=i||l,f=!u&&(i||l&&c),h=g.useCallback(v=>{n({...t,field:v})},[t,n]),p=g.useCallback(v=>{if(v==="exists"||v==="not_exists"){n({...t,operator:v,value:void 0});return}const b=v==="in"||v==="not_in",x=t.operator==="in"||t.operator==="not_in";let w=t.value;b&&!x?w=t.value!==void 0?[t.value]:[]:!b&&x&&(w=Array.isArray(t.value)?t.value[0]:t.value),n({...t,operator:v,value:w})},[t,n]),m=g.useCallback(v=>{n({...t,value:v})},[t,n]);return o.jsxs("div",{className:"flex justify-between gap-2",children:[o.jsxs("div",{className:K("flex flex-wrap items-center gap-2",s),children:[o.jsx(IVr,{schema:e,value:t.field,onChange:h}),d&&o.jsxs(o.Fragment,{children:[o.jsx($Vr,{value:t.operator,onChange:p,operators:l?["in","not_in"]:void 0}),f&&o.jsx(UVr,{value:t.value,onChange:m,operator:t.operator,fieldType:a})]})]}),o.jsx(ie,{type:"button",onClick:r,tooltip:"Remove rule",size:"icon-sm",variant:"ghost",children:o.jsx(or,{})})]})},HVr=3,cLt=({schema:e,group:t,onChange:n,onRemove:r,depth:s,maxDepth:a})=>{const i=s===0,l=()=>{n({...t,operator:t.operator==="AND"?"OR":"AND"})},c=(h,p)=>{n({...t,conditions:t.conditions.map((m,v)=>v===h?p:m)})},u=h=>{const p=t.conditions.filter((m,v)=>v!==h);p.length===0&&r?r():n({...t,conditions:p})},d=()=>{n({...t,conditions:[...t.conditions,wje()]})},f=()=>{n({...t,conditions:[...t.conditions,_Vr(t.operator==="AND"?"OR":"AND")]})};return o.jsxs("div",{className:K(i?"bg-surface2":"bg-surface3 pl-6"),children:[!i&&o.jsxs("div",{className:"border-border1 flex items-center justify-between border-b border-dashed py-1.5 pr-4 pl-3",children:[o.jsx("span",{className:"text-ui-xs text-neutral3",children:"Group"}),r&&o.jsx(ie,{type:"button",onClick:r,tooltip:"Remove group",size:"icon-sm",variant:"ghost",children:o.jsx(or,{})})]}),t.conditions.map((h,p)=>o.jsx("div",{className:"border-border1 border-b border-dashed last:border-b-0",children:o.jsxs("div",{className:K("relative",gxe(h)&&"border-l-4 border-border1 p-4"),children:[p>0&&o.jsx("button",{type:"button",onClick:l,className:K("absolute top-0 left-1/2 z-10 -translate-1/2 cursor-pointer rounded-full px-3 py-0.5 text-ui-xs",t.operator==="OR"?"bg-accent6Dark text-accent6 hover:bg-accent6Dark/70":"bg-accent3Dark text-accent3 hover:bg-accent3Dark/70"),children:t.operator.toLowerCase()}),gxe(h)?o.jsx(VVr,{schema:e,rule:h,onChange:m=>c(p,m),onRemove:()=>u(p)}):o.jsx(cLt,{schema:e,group:h,onChange:m=>c(p,m),onRemove:()=>u(p),depth:s+1,maxDepth:a})]})},p)),o.jsxs("div",{className:"flex gap-1 p-2",children:[o.jsxs(ie,{type:"button",onClick:d,variant:"ghost",size:"sm",children:[o.jsx(Qe,{children:o.jsx(_r,{})}),"Add rule"]}),s<a-1&&o.jsxs(ie,{type:"button",onClick:f,variant:"ghost",size:"sm",children:[o.jsx(Qe,{children:o.jsx(dKt,{})}),"Add group"]})]})]})},WVr=({schema:e,ruleGroup:t,onChange:n,maxDepth:r=HVr,className:s})=>{const a=g.useCallback(l=>{n(l)},[n]),i=g.useCallback(()=>{n({operator:"AND",conditions:[wje()]})},[n]);return t?o.jsx("div",{className:s,children:o.jsx(cLt,{schema:e,group:t,onChange:a,depth:0,maxDepth:r})}):o.jsxs("button",{type:"button",onClick:i,className:"border-border1 text-ui-sm text-neutral3 hover:text-neutral6 flex w-full items-center justify-center gap-2 rounded-md border border-dashed p-2",children:[o.jsx(Qe,{children:o.jsx(_r,{})}),"Add conditional rule"]})};function oA({entityName:e,schema:t,rules:n,onRulesChange:r}){const s=Object.keys(t?.properties??{}).length>0;if(!t||!s)return null;const a=sLt(n);return o.jsxs(pr,{children:[o.jsx(zSe,{asChild:!0,children:o.jsxs(ie,{tooltip:a>0?`${a} rules`:"Display Conditions",size:"icon-sm",variant:"ghost",className:"relative",children:[o.jsx(ven,{className:"text-accent6"}),a>0&&o.jsx("span",{className:"bg-accent1 absolute -top-0.5 -right-0.5 size-2 rounded-full"})]})}),o.jsxs(mr,{className:"w-full max-w-5xl",children:[o.jsxs(gr,{children:[o.jsxs(ur,{children:["Display Conditions for ",e]}),o.jsx(Cs,{children:"Configure when this entity should be displayed based on variable values."})]}),o.jsx(jr,{children:o.jsx(WVr,{schema:t,ruleGroup:n,onChange:r})})]})]})}function uLt({form:e,onPublish:t,onSaveDraft:n,isSubmitting:r=!1,isSavingDraft:s=!1,formRef:a,mode:i="create"}){const{register:l,control:c,formState:{errors:u}}=e,d=Mn({control:c,name:"defaultSampling.type"}),f=Mn({control:c,name:"model.provider"});return o.jsxs("div",{className:"flex h-full flex-col",children:[o.jsx(Nr,{className:"min-h-0 flex-1",children:o.jsxs("div",{className:"flex flex-col gap-6 p-4",children:[o.jsx(Ld,{title:"Configuration",subtitle:"Define your scorer's name, type, and settings."}),o.jsxs("div",{className:"flex flex-col gap-1.5",children:[o.jsxs(Dt,{htmlFor:"scorer-name",className:"text-neutral5 text-xs",children:["Name ",o.jsx("span",{className:"text-accent2",children:"*"})]}),o.jsx(jn,{id:"scorer-name",placeholder:"My Scorer",variant:"outline",...l("name"),error:!!u.name}),u.name&&o.jsx("span",{className:"text-accent2 text-xs",children:u.name.message})]}),o.jsxs("div",{className:"flex flex-col gap-1.5",children:[o.jsxs(Dt,{htmlFor:"scorer-description",className:"text-neutral5 text-xs",children:["Description ",o.jsx("span",{className:"text-accent2",children:"*"})]}),o.jsx(zo,{id:"scorer-description",placeholder:"Describe what this scorer does",variant:"outline",...l("description"),error:!!u.description}),u.description&&o.jsx("span",{className:"text-accent2 text-xs",children:u.description.message})]}),o.jsxs("div",{className:"flex flex-col gap-1.5",children:[o.jsxs(Dt,{className:"text-neutral5 text-xs",children:["Provider ",o.jsx("span",{className:"text-accent2",children:"*"})]}),o.jsx($s,{name:"model.provider",control:c,render:({field:h})=>o.jsx(Yy,{value:h.value,onValueChange:h.onChange,container:a})}),u.model?.provider&&o.jsx("span",{className:"text-accent2 text-xs",children:u.model.provider.message})]}),o.jsxs("div",{className:"flex flex-col gap-1.5",children:[o.jsxs(Dt,{className:"text-neutral5 text-xs",children:["Model ",o.jsx("span",{className:"text-accent2",children:"*"})]}),o.jsx($s,{name:"model.name",control:c,render:({field:h})=>o.jsx(Ky,{value:h.value,onValueChange:h.onChange,llmId:f||"",container:a})}),u.model?.name&&o.jsx("span",{className:"text-accent2 text-xs",children:u.model.name.message})]}),o.jsxs("div",{className:"flex flex-col gap-1.5",children:[o.jsx(Dt,{className:"text-neutral5 text-xs",children:"Score Range"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx($s,{name:"scoreRange.min",control:c,render:({field:h})=>o.jsx(jn,{type:"number",placeholder:"Min",variant:"outline",value:h.value,onChange:p=>h.onChange(parseFloat(p.target.value)||0)})}),o.jsx("span",{className:"text-neutral3 text-xs",children:"to"}),o.jsx($s,{name:"scoreRange.max",control:c,render:({field:h})=>o.jsx(jn,{type:"number",placeholder:"Max",variant:"outline",value:h.value,onChange:p=>h.onChange(parseFloat(p.target.value)||0)})})]})]}),o.jsxs("div",{className:"flex flex-col gap-1.5",children:[o.jsx(Dt,{className:"text-neutral5 text-xs",children:"Default Sampling"}),o.jsx($s,{name:"defaultSampling.type",control:c,render:({field:h})=>o.jsxs(nL,{value:h.value??"none",onValueChange:h.onChange,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Mh,{value:"none",id:"sampling-none"}),o.jsx(Dt,{htmlFor:"sampling-none",className:"text-neutral5 text-xs",children:"None"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Mh,{value:"ratio",id:"sampling-ratio"}),o.jsx(Dt,{htmlFor:"sampling-ratio",className:"text-neutral5 text-xs",children:"Ratio"})]})]})}),d==="ratio"&&o.jsx($s,{name:"defaultSampling.rate",control:c,render:({field:h})=>o.jsx(jn,{type:"number",step:"0.1",min:"0",max:"1",placeholder:"Rate (0-1)",variant:"outline",value:h.value??"",onChange:p=>h.onChange(parseFloat(p.target.value)||0)})})]})]})}),o.jsx("div",{className:"shrink-0 p-4",children:i==="edit"&&n?o.jsxs("div",{className:"flex gap-2",children:[o.jsx(ie,{variant:"outline",onClick:n,disabled:s||r,className:"flex-1",children:s?o.jsxs(o.Fragment,{children:[o.jsx(Vt,{className:"h-4 w-4"}),"Saving..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Qe,{children:o.jsx(Qu,{})}),"Save"]})}),o.jsx(ie,{variant:"primary",onClick:t,disabled:r||s,className:"flex-1",children:r?o.jsxs(o.Fragment,{children:[o.jsx(Vt,{className:"h-4 w-4"}),"Publishing..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Qe,{children:o.jsx(Ur,{})}),"Publish"]})})]}):o.jsx(ie,{variant:"primary",onClick:t,disabled:r,className:"w-full",children:r?o.jsxs(o.Fragment,{children:[o.jsx(Vt,{className:"h-4 w-4"}),"Creating..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Qe,{children:o.jsx(Ur,{})}),"Create scorer"]})})})]})}function dLt({form:e}){const{control:t}=e;return o.jsxs("div",{className:"flex h-full flex-col gap-3 px-4",children:[o.jsx(Ld,{title:"Instructions",subtitle:"Write your scorer's system prompt."}),o.jsx($s,{name:"instructions",control:t,render:({field:n})=>o.jsx("div",{className:"flex flex-1 flex-col",children:o.jsx(Gr,{value:n.value??"",onChange:n.onChange,language:"markdown",showCopyButton:!1,placeholder:"Enter scorer instructions...",className:"min-h-[200px] flex-1"})})})]})}const ZVr=async e=>{const t={};return!e.name||e.name.trim()===""?t.name={type:"required",message:"Name is required"}:e.name.length>100&&(t.name={type:"maxLength",message:"Name must be 100 characters or less"}),e.description&&e.description.length>500&&(t.description={type:"maxLength",message:"Description must be 500 characters or less"}),(!e.model?.provider||e.model.provider.trim()==="")&&(t["model.provider"]={type:"required",message:"Provider is required"}),(!e.model?.name||e.model.name.trim()==="")&&(t["model.name"]={type:"required",message:"Model is required"}),(!e.instructions||e.instructions.trim()==="")&&(t.instructions={type:"required",message:"Instructions are required"}),{values:Object.keys(t).length===0?e:{},errors:Object.keys(t).length>0?t:{}}};function fLt(e={}){const{initialValues:t}=e;return{form:dS({resolver:ZVr,defaultValues:{name:t?.name??"",description:t?.description??"",type:t?.type??"llm-judge",model:t?.model??{provider:"",name:""},instructions:t?.instructions??"",scoreRange:t?.scoreRange??{min:0,max:1},defaultSampling:t?.defaultSampling}})}}const GVr=["llm-judge"],QVr=wke("type",[ws({type:$x("none")}),ws({type:$x("ratio"),rate:pf().min(0).max(1)})]);ws({name:cr().min(1,"Name is required").max(100,"Name must be 100 characters or less"),description:cr().max(500,"Description must be 500 characters or less"),type:qy(GVr),model:ws({provider:cr(),name:cr()}),instructions:cr(),scoreRange:ws({min:pf(),max:pf()}),defaultSampling:QVr.optional()});const hLt=(e,t)=>{const n=Ye(),{requestContext:r}=ys();return mt({queryKey:["stored-scorer",e,t?.status,r],queryFn:()=>e?n.getStoredScorer(e).details(r,t):null,enabled:!!e})},Sje=e=>{const t=Ye(),n=Ar(),{requestContext:r}=ys(),s=Sn({mutationFn:l=>t.createStoredScorer(l),onSuccess:()=>{n.invalidateQueries({queryKey:["stored-scorers"]}),n.invalidateQueries({queryKey:["scorers"]})}}),a=Sn({mutationFn:l=>{if(!e)throw new Error("scorerId is required for update");return t.getStoredScorer(e).update(l,r)},onSuccess:()=>{n.invalidateQueries({queryKey:["stored-scorers"]}),n.invalidateQueries({queryKey:["scorers"]}),e&&n.invalidateQueries({queryKey:["stored-scorer",e]})}}),i=Sn({mutationFn:()=>{if(!e)throw new Error("scorerId is required for delete");return t.getStoredScorer(e).delete(r)},onSuccess:()=>{n.invalidateQueries({queryKey:["stored-scorers"]}),n.invalidateQueries({queryKey:["scorers"]}),e&&n.invalidateQueries({queryKey:["stored-scorer",e]})}});return{createStoredScorer:s,updateStoredScorer:a,deleteStoredScorer:i}},V1=({children:e,leftSlot:t})=>o.jsxs("div",{className:"grid h-full grid-cols-[auto_1fr] overflow-y-auto",children:[o.jsx("div",{className:"border-border1 bg-surface3 h-full overflow-y-auto border-r",children:t}),o.jsx("div",{className:"h-full overflow-y-auto py-4",children:e})]});function YVr({onSuccess:e}){const{createStoredScorer:t}=Sje(),n=g.useRef(null),{form:r}=fLt(),s=async()=>{if(!await r.trigger()){Ve.error("Please fill in all required fields");return}const i=r.getValues();try{const l={name:i.name,description:i.description||void 0,type:i.type,model:i.model,instructions:i.instructions||void 0,scoreRange:i.scoreRange,defaultSampling:i.defaultSampling?.type==="ratio"&&typeof i.defaultSampling.rate=="number"?i.defaultSampling:{type:"none"}},c=await t.mutateAsync(l);Ve.success("Scorer created successfully"),e?.(c)}catch(l){Ve.error(`Failed to create scorer: ${l instanceof Error?l.message:"Unknown error"}`)}};return o.jsx(V1,{leftSlot:o.jsx(uLt,{form:r,onPublish:s,isSubmitting:t.isPending,formRef:n}),children:o.jsx("form",{ref:n,className:"h-full",children:o.jsx(dLt,{form:r})})})}const KVr=3e3;function XVr(e){return z4(e.state.error,"scores")||B4(e.state.error)?!1:KVr}const kje=({traceId:e="",spanId:t="",page:n})=>{const r=Ye();return mt({queryKey:["trace-span-scores",e,t,n],queryFn:()=>r.listScoresBySpan({traceId:e,spanId:t,page:n||0,perPage:10}),enabled:!!e&&!!t,refetchInterval:XVr,gcTime:0,staleTime:0})},pLt=({scorerId:e,params:t})=>{const n=Ye(),{requestContext:r}=ys();return mt({queryKey:["scorer-versions",e,t,r],queryFn:()=>n.getStoredScorer(e).listVersions(t,r),enabled:!!e})},JVr=({scorerId:e,versionId:t})=>{const n=Ye(),{requestContext:r}=ys();return mt({queryKey:["scorer-version",e,t,r],queryFn:()=>n.getStoredScorer(e).getVersion(t,r),enabled:!!e&&!!t})};function eHr(e){const t=Ye(),n=Zl(),r=e?.start||e?.end?e:void 0;return mt({queryKey:["score-metrics",n,r?.start?.toISOString(),r?.end?.toISOString()],queryFn:async()=>{const s=await t.listScorers(n),a=Object.keys(s??{});if(a.length===0)return{summaryData:[],overTimeData:[],scorerNames:[],avgScore:null,prevAvgScore:null};const i=await Promise.all(a.map(async N=>{const I=[];let A=0;for(;;){const P=await t.listScores({filters:{scorerId:N,timestamp:r},pagination:{page:A,perPage:100},orderBy:{field:"timestamp",direction:"DESC"}});if(I.push(...P.scores),!P.pagination?.hasMore)break;A++}return I})),l=[];for(const N of i)for(const I of N)l.push({scorerId:I.scorerId,score:I.score,timestamp:typeof I.timestamp=="string"?I.timestamp:new Date(I.timestamp).toISOString()});if(l.length===0)return{summaryData:[],overTimeData:[],scorerNames:[],avgScore:null,prevAvgScore:null};const c=[...l].sort((N,I)=>new Date(N.timestamp).getTime()-new Date(I.timestamp).getTime()),u=Math.floor(c.length/2),d=c.slice(0,u),f=new Map;for(const N of l)f.has(N.scorerId)||f.set(N.scorerId,[]),f.get(N.scorerId).push(N.score);const h=Array.from(f.entries()).map(([N,I])=>({scorer:N,avg:I.reduce((A,P)=>A+P,0)/I.length,min:Math.min(...I),max:Math.max(...I),count:I.length})),p=h.map(N=>N.scorer),m=h.reduce((N,I)=>N+I.avg,0)/h.length;let v=null;if(d.length>0){const N=new Map;for(const A of d)N.has(A.scorerId)||N.set(A.scorerId,[]),N.get(A.scorerId).push(A.score);const I=Array.from(N.values()).map(A=>A.reduce((P,L)=>P+L,0)/A.length);v=I.reduce((A,P)=>A+P,0)/I.length,v=Math.round(v*100)/100}const y=l.map(N=>new Date(N.timestamp).getTime()),b=Math.max(...y)-Math.min(...y);let x;b<36e5?x=6e4:b<864e5?x=36e5:x=864e5;const w=new Map;for(const N of l){const I=new Date(N.timestamp),A=Math.floor(I.getTime()/x)*x;w.has(A)||w.set(A,new Map);const P=w.get(A);P.has(N.scorerId)||P.set(N.scorerId,[]),P.get(N.scorerId).push(N.score)}const k=Array.from(w.entries()).sort(([N],[I])=>N-I),C=k.length>0?k[0][0]:0,T=((k.length>0?k[k.length-1][0]:0)-C)/864e5,E=k.map(([N,I])=>{const A=new Date(N);let P;T>1?P=A.toLocaleDateString("en-US",{month:"short",day:"numeric"})+" "+A.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}):P=A.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1});const L={time:P};for(const D of p){const B=I.get(D);B&&B.length>0&&(L[D]=+(B.reduce((H,q)=>H+q,0)/B.length).toFixed(2))}return L});return{summaryData:h,overTimeData:E,scorerNames:p,avgScore:Math.round(m*100)/100,prevAvgScore:v}}})}function tHr(e){return new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})}function nHr({scorerId:e,value:t,onValueChange:n,className:r,disabled:s=!1,variant:a,activeVersionId:i}){const{data:l,isLoading:c}=pLt({scorerId:e,params:{orderBy:{direction:"DESC"}}}),u=l?.versions??[],f=(i?u.find(p=>p.id===i):void 0)?.versionNumber,h=[{label:"Latest",value:""},...u.map(p=>{const m=p.id===i,v=f!==void 0&&p.versionNumber>f;return{label:`v${p.versionNumber}`,value:p.id,description:tHr(p.createdAt),end:m?o.jsx(bt,{variant:"green",children:"Published"}):v?o.jsx(bt,{variant:"blue",children:"Draft"}):void 0}})];return o.jsx(vl,{options:h,value:t,onValueChange:n,placeholder:c?"Loading versions...":"Versions",searchPlaceholder:"Search versions...",emptyText:"No versions found.",className:r,disabled:s||c,variant:a})}const yh="mastra_workspace",Uv={FILESYSTEM:{READ_FILE:`${yh}_read_file`,WRITE_FILE:`${yh}_write_file`,EDIT_FILE:`${yh}_edit_file`,LIST_FILES:`${yh}_list_files`,DELETE:`${yh}_delete`,FILE_STAT:`${yh}_file_stat`,MKDIR:`${yh}_mkdir`},SANDBOX:{EXECUTE_COMMAND:`${yh}_execute_command`,GET_PROCESS_OUTPUT:`${yh}_get_process_output`,KILL_PROCESS:`${yh}_kill_process`},SEARCH:{SEARCH:`${yh}_search`,INDEX:`${yh}_index`}},mLt=g.createContext(void 0),rHr=()=>{};function Oje(){const e=g.useContext(mLt);if(!e)throw new Error("ToolCall compounds must be rendered within ToolCall");return e}function sHr({open:e,defaultOpen:t=!1,onOpenChange:n=rHr,status:r="idle",className:s,children:a,...i}){const[l,c]=g.useState(t),u=e??l,d=g.useId(),f=h=>{e===void 0&&c(h),n(h)};return o.jsx(mLt.Provider,{value:{open:u,status:r},children:o.jsxs(fc,{open:u,onOpenChange:f,className:K("max-w-full min-w-0",s),role:"group","aria-busy":r==="running","aria-invalid":r==="error"||void 0,"aria-describedby":r==="idle"?void 0:d,"data-status":r,...i,children:[a,r!=="idle"&&o.jsx("span",{id:d,className:"sr-only",children:r==="running"?"Tool call running":"Tool call failed"})]})})}const aHr=({className:e,...t})=>o.jsx(ql,{className:K("group/row w-full cursor-pointer rounded-md text-left transition-colors hover:bg-neutral6/5 focus-visible:ring-1 focus-visible:ring-accent1 focus-visible:outline-hidden motion-reduce:transition-none",e),...t}),gLt=({className:e,children:t,...n})=>{const{status:r}=Oje();return o.jsx(I3t,{active:r==="running",className:K("flex w-full min-w-0 items-center gap-2 px-1.5 py-1",e),...n,children:t})},vLt=({className:e,...t})=>o.jsx("span",{className:K("flex size-4 shrink-0 items-center justify-center",e),...t}),yLt=({className:e,...t})=>o.jsx(ve,{as:"span",variant:"ui-sm",className:K("text-icon3 max-w-[55%] shrink-0 truncate",e),...t}),bLt=({className:e,...t})=>{const n=y3t();return o.jsx(ve,{as:"span",variant:"ui-xs",font:"mono",className:K("text-icon3 min-w-0 truncate",n,e),...t})},xLt=({rule:e,className:t,...n})=>o.jsx("span",{"aria-hidden":!0,className:K("min-w-2 flex-1",e&&"h-px bg-border1 mask-r-from-[calc(100%-min(100%,160px))]",t),...n}),yxe=({className:e,...t})=>o.jsx("span",{className:K("flex shrink-0 items-center",e),...t}),wLt=({className:e,children:t,...n})=>{const{open:r}=Oje();return o.jsx("span",{className:K("flex size-4 shrink-0 items-center justify-center",e),...n,children:o.jsx("span",{"aria-hidden":!0,className:K("text-icon3 flex shrink-0 items-center opacity-0 transition duration-150 motion-reduce:transition-none","group-hover/row:opacity-100 group-focus-visible/row:opacity-100",r&&"rotate-90 opacity-100"),children:t??o.jsx(Lr,{size:13})})})},iHr=({icon:e,label:t,detail:n,disclosure:r=!0,...s})=>{const{status:a}=Oje();return o.jsxs(gLt,{...s,children:[o.jsx(vLt,{children:o.jsx(e,{size:14,strokeWidth:1.75,"aria-hidden":!0,className:a==="error"?"text-error/80":"text-icon2"})}),o.jsx(yLt,{children:t}),n&&o.jsx(bLt,{children:n}),o.jsx(xLt,{}),a==="error"&&o.jsx(yxe,{children:o.jsx(or,{size:13,role:"img","aria-label":"Failed",className:"text-error shrink-0"})}),r&&o.jsx(wLt,{})]})},oHr=({className:e,children:t,...n})=>o.jsx(Vl,{className:"max-w-full min-w-0",...n,children:o.jsx("div",{className:K("relative ml-[14px] flex max-w-full min-w-0 flex-col gap-1.5 py-1.5 pr-1 pl-4 before:absolute before:inset-y-0 before:left-0 before:w-px before:bg-border1 before:mask-b-from-[calc(100%-min(40%,80px))] before:content-['']",e),children:t})}),l2=({copyText:e,className:t,children:n,...r})=>o.jsxs("div",{className:"group/block relative max-w-full min-w-0",children:[o.jsx("pre",{className:K("m-0 max-h-60 max-w-full overflow-auto rounded-md bg-neutral6/5 px-3 py-2 font-mono text-xs leading-normal break-words whitespace-pre-wrap",t),...r,children:n}),o.jsx(_a,{content:e,size:"sm",variant:"ghost",className:"absolute top-1 right-1 opacity-0 transition-opacity group-hover/block:opacity-100 focus-visible:opacity-100"})]});function bxe(e){if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}function lHr(e,t){return t in e}function cHr(e,t){if(!e||typeof e!="object"||!lHr(e,t))return;const n=e[t];return typeof n=="number"?String(n):typeof n=="string"&&n.length>0?n:void 0}function uHr(e,t){for(const n of t){const r=cHr(e,n);if(r)return r}}const dHr={view:{icon:ac,label:"Read",detailKeys:["path"]},read_file:{icon:ac,label:"Read",detailKeys:["path"]},write_file:{icon:fE,label:"Write",detailKeys:["path"]},create_file:{icon:fE,label:"Write",detailKeys:["path"]},edit_file:{icon:fE,label:"Edit",detailKeys:["path"]},string_replace:{icon:fE,label:"Edit",detailKeys:["path"]},str_replace:{icon:fE,label:"Edit",detailKeys:["path"]},ast_edit:{icon:fE,label:"Edit",detailKeys:["path"]},execute_command:{icon:Qct,label:"Run",detailKeys:["command"],isCommand:!0},get_process_output:{icon:Sen,label:"Process output",detailKeys:["pid"]},kill_process:{icon:C0e,label:"Stop process",detailKeys:["pid"]},find_files:{icon:_Me,label:"Find files",detailKeys:["pattern","path"]},list_files:{icon:_Me,label:"List files",detailKeys:["pattern","path"]},grep:{icon:Ds,label:"Search",detailKeys:["pattern","path"]},search_content:{icon:Ds,label:"Search",detailKeys:["pattern","query"]},search:{icon:Ds,label:"Search",detailKeys:["query"]},web_search:{icon:Ry,label:"Search the web",detailKeys:["query"]},lsp_inspect:{icon:sc,label:"Inspect code",detailKeys:["path"]},file_stat:{icon:GKt,label:"File info",detailKeys:["path"]},delete:{icon:Fl,label:"Delete",detailKeys:["path"]},delete_file:{icon:Fl,label:"Delete",detailKeys:["path"]},mkdir:{icon:JD,label:"New folder",detailKeys:["path"]},skill:{icon:k$,label:"Skill",detailKeys:["name"]},skill_search:{icon:k$,label:"Search skills",detailKeys:["query"]},skill_read:{icon:k$,label:"Skill file",detailKeys:["path"]}};function fHr(e){const t=e.replace(/[_-]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function hHr(e){return e.replace(/^\s*cd\s+(?:'[^']*'|"[^"]*"|[^\s&|;]+)\s*&&\s*/,"")||e}function pHr(e,t){const n=dHr[e.replace(/^mastra_workspace_/,"")];if(!n)return{icon:Ud,label:fHr(e)};const r=n.detailKeys?uHr(t,n.detailKeys):void 0;return r?n.isCommand?{icon:n.icon,label:n.label,detail:hHr(r),command:r}:{icon:n.icon,label:n.label,detail:r}:{icon:n.icon,label:n.label}}const SLt=g.createContext({messages:[]}),kLt=g.createContext({isRunning:!1,cancelRun:()=>{},canSendWhileStreaming:!1}),OLt=g.createContext({send:()=>{}}),CLt=g.createContext({tasks:[]}),_Lt=g.createContext(void 0),mHr=()=>g.useContext(SLt).messages,rL=()=>g.useContext(kLt),Cje=()=>g.useContext(OLt).send,gHr=()=>g.useContext(CLt).tasks,sL=({children:e,initialCollapsed:t=!0,icon:n,title:r,detail:s,collapsible:a=!0,extraInfo:i,header:l,status:c="idle","data-testid":u})=>{const[d,f]=g.useState(!t),{isRunning:h}=rL(),[p]=g.useState(()=>h);g.useEffect(()=>{f(!t)},[t]);const m=l??o.jsxs(gLt,{children:[o.jsx(vLt,{children:n}),o.jsx(yLt,{children:r}),s&&o.jsx(bLt,{children:s}),o.jsx(xLt,{}),c==="error"&&o.jsx(yxe,{children:o.jsx(or,{size:13,role:"img","aria-label":"Failed",className:"text-error shrink-0"})}),a&&o.jsx(wLt,{})]}),v=!a||d;return o.jsxs(sHr,{open:v,onOpenChange:f,status:c,className:K(p&&"motion-safe:animate-in fade-in-0 slide-in-from-bottom-1"),"data-testid":u,children:[o.jsxs("span",{className:"flex w-full min-w-0 items-center",children:[a?o.jsx(aHr,{className:"min-w-0 flex-1",children:m}):o.jsx("span",{className:"min-w-0 flex-1",children:m}),i&&o.jsx(yxe,{className:"gap-1 pr-1",children:i})]}),o.jsx(oHr,{children:e})]})},_je=()=>o.jsx(sL,{icon:o.jsx(Vt,{className:"text-neutral3"}),title:o.jsx(Et,{className:"ml-2 h-2 w-12"}),collapsible:!1}),vHr=({agents:e})=>{const{Link:t,paths:n}=dn();return e.length===0?o.jsx(SS,{children:"No agents"}):o.jsx(wS,{children:e.map(r=>o.jsx(Zx,{children:o.jsx(t,{href:n.agentLink(r.id),"data-testid":"agent-badge",children:o.jsx(bt,{variant:"green",icon:o.jsx(Ri,{}),children:r.name})})},r.id))})},yHr=({agentId:e})=>{const{data:t,isLoading:n}=Yl(e),{mutate:r}=n2r(e),{mutateAsync:s}=r2r(e),a=o0(),{isCmsAvailable:i,isLoading:l}=kS();if(n)return o.jsx(Et,{className:"h-full"});if(!t)return o.jsx("div",{children:"Agent not found"});const c=t.agents??{},u=Object.keys(c).map(k=>({...c[k],id:k})),d=t.tools??{},f=Object.keys(d).map(k=>d[k]),h=t.workflows??{},p=Object.keys(h).map(k=>({id:k,...h[k]})),m=t.skills??[],v=t.workspaceTools??[],y=t.browserTools??[],b=t.workspaceId,x=t.inputProcessors??[],w=t.outputProcessors??[];return o.jsxs("div",{className:"flex flex-col gap-4","data-testid":"agent-metadata",children:[t.modelList&&o.jsxs(Ku,{className:"bg-surface3",children:[o.jsx(gj,{children:o.jsx(om,{children:"Models"})}),o.jsx(lm,{children:o.jsx(XBr,{modelList:t.modelList,updateModelInModelList:s,reorderModelList:r})})]}),o.jsxs(Ku,{className:"bg-surface3",children:[o.jsxs(gj,{className:"flex-row items-baseline gap-2 space-y-0",children:[o.jsx(om,{children:"Capabilities"}),o.jsx(n1,{children:"Everything this agent can call at runtime"})]}),o.jsxs(lm,{children:[u.length>0&&o.jsx(iw,{title:o.jsx(FE,{title:"Agents",count:u.length}),hint:{link:"https://mastra.ai/en/docs/agents/overview",title:"Agents documentation"},children:o.jsx(vHr,{agents:u})}),o.jsx(iw,{title:o.jsx(FE,{title:"Tools",count:f.length}),hint:{link:"https://mastra.ai/en/docs/agents/using-tools-and-mcp",title:"Using Tools and MCP documentation"},children:o.jsx(bHr,{tools:f,agentId:e})}),o.jsx(iw,{title:o.jsx(FE,{title:"Workflows",count:p.length}),hint:{link:"https://mastra.ai/en/docs/workflows/overview",title:"Workflows documentation"},children:o.jsx(xHr,{workflows:p})}),v.length>0&&o.jsx(iw,{title:o.jsx(FE,{title:"Workspace Tools",count:v.length}),hint:{link:"https://mastra.ai/en/reference/workspace/workspace-class#agent-tools",title:"Workspace tools documentation"},children:o.jsx(OHr,{tools:v})}),y.length>0&&o.jsx(iw,{title:o.jsx(FE,{title:"Browser Tools",count:y.length}),hint:{link:"https://mastra.ai/en/docs/agents/adding-browser-control",title:"Browser tools documentation"},children:o.jsx(CHr,{tools:y})}),(x.length>0||w.length>0)&&o.jsx(iw,{title:"Processors",hint:{link:"https://mastra.ai/docs/agents/processors",title:"Processors documentation"},children:o.jsx(_Hr,{inputProcessors:x,outputProcessors:w})}),o.jsx(iw,{title:o.jsx(FE,{title:"Skills",count:m.length}),hint:{link:"https://mastra.ai/en/docs/workspace/skills",title:"Skills documentation"},children:o.jsx(SHr,{skills:m,agentId:e,workspaceId:b})}),o.jsx(iw,{title:"Scorers",children:o.jsx(wHr,{entityId:t.name,entityType:"AGENT"})})]})]}),o.jsxs(Ku,{className:"bg-surface3",children:[o.jsx(gj,{children:o.jsx(om,{children:"System Prompt"})}),o.jsxs(lm,{className:"space-y-3",children:[o.jsx(rd,{className:"border-border1 rounded-md border",value:X4(t.instructions),editable:!1,extensions:[wOe({base:rC,codeLanguages:AOt}),Pt.lineWrapping],theme:a}),!l&&!i&&o.jsx(Rn,{variant:"warning",title:"Read-only",children:o.jsxs(Rn.Message,{children:["To edit the system prompt in Studio, add ",o.jsx("code",{className:"font-medium",children:"@mastra/editor"})," to your project. See the"," ",o.jsx("a",{href:"https://mastra.ai/docs/editor/overview",target:"_blank",rel:"noopener noreferrer",className:"underline",children:"documentation"}),"."]})})]})]})]})},FE=({title:e,count:t})=>o.jsxs("span",{className:"flex items-center gap-1.5",children:[e,o.jsx(bt,{variant:"neutral",children:t})]}),bHr=({tools:e,agentId:t})=>{const{Link:n,paths:r}=dn();return e.length===0?o.jsx(SS,{children:"No tools"}):o.jsx(wS,{children:e.map(s=>o.jsx(Zx,{children:o.jsx(n,{href:r.agentToolLink(t,s.id),"data-testid":"tool-badge",children:o.jsx(bt,{icon:o.jsx(Bf,{className:"text-accent6"}),children:s.id})})},s.id))})},xHr=({workflows:e})=>{const{Link:t,paths:n}=dn();return e.length===0?o.jsx(SS,{children:"No workflows"}):o.jsx(wS,{children:e.map(r=>o.jsx(Zx,{children:o.jsx(t,{href:n.workflowLink(r.id),"data-testid":"workflow-badge",children:o.jsx(bt,{icon:o.jsx(Bc,{className:"text-accent3"}),children:r.name})})},r.id))})},wHr=({entityId:e,entityType:t})=>{const{Link:n,paths:r}=dn(),{data:s={},isLoading:a}=up(),i=Object.keys(s).filter(l=>{const c=s[l];return t==="AGENT"?c.agentNames?.includes?.(e):c.workflowIds.includes(e)}).map(l=>({...s[l],id:l}));return a?o.jsx(_je,{}):i.length===0?o.jsx(SS,{children:"No Scorers"}):o.jsx(wS,{children:i.map(l=>o.jsx(Zx,{children:o.jsx(n,{href:r.scorerLink(l.id),"data-testid":"scorer-badge",children:o.jsx(bt,{icon:o.jsx(Qh,{className:"text-neutral3"}),children:l.scorer.config.name})})},l.id))})},SHr=({skills:e,agentId:t,workspaceId:n})=>{const{Link:r,paths:s}=dn(),{isSkillActivated:a}=U4t();return e.length===0?o.jsx(SS,{children:"No skills"}):o.jsx(wS,{children:e.map(i=>{const l=a(i.name),c=o.jsxs(bt,{icon:o.jsx(b_,{className:`h-3 w-3 ${l?"text-green-400":"text-accent2"}`}),variant:l?"green":"neutral",children:[i.name,l&&o.jsx("span",{className:"sr-only",children:"Active"})]});return o.jsx(Zx,{children:l?o.jsx(Wl,{children:o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx(r,{href:s.agentSkillLink(t,i.name,i.path,n),"data-testid":"skill-badge",children:c})}),o.jsx(yn,{className:"bg-surface3 text-neutral6 border-border1 border",children:"Active"})]})}):o.jsx(r,{href:s.agentSkillLink(t,i.name,i.path,n),"data-testid":"skill-badge",children:c})},i.path)})})};function kHr(e){const t=`${yh}_`;return e.startsWith(t)?e.slice(t.length):e}const OHr=({tools:e})=>e.length===0?o.jsx(SS,{children:"No workspace tools"}):o.jsx(wS,{children:e.map(t=>o.jsx(Zx,{children:o.jsx(bt,{icon:o.jsx(cI,{className:"text-accent1 h-3 w-3"}),children:kHr(t)})},t))}),CHr=({tools:e})=>e.length===0?o.jsx(SS,{children:"No browser tools"}):o.jsx(wS,{children:e.map(t=>o.jsx(Zx,{children:o.jsx(bt,{icon:o.jsx(Ry,{className:"h-3 w-3 text-cyan-500"}),children:t})},t))}),_Hr=({inputProcessors:e,outputProcessors:t})=>{const{Link:n,paths:r}=dn();if(e.length===0&&t.length===0)return o.jsx(SS,{children:"No processors"});const s=e[0]?.id,a=t[0]?.id;return o.jsxs(wS,{children:[e.length>0&&s&&o.jsx(Zx,{children:o.jsx(n,{href:`${r.workflowLink(s)}/graph`,"data-testid":"processor-badge",children:o.jsx(bt,{icon:o.jsx(jD,{className:"text-accent4"}),children:"input"})})}),t.length>0&&a&&o.jsx(Zx,{children:o.jsx(n,{href:`${r.workflowLink(a)}/graph`,"data-testid":"processor-badge",children:o.jsx(bt,{icon:o.jsx(jD,{className:"text-accent5"}),children:"output"})})})]})},O_=e=>{const t=Ye(),n=Zl();return mt({queryKey:["memory",e,n],queryFn:()=>e?t.getMemoryStatus(e,n):null,enabled:!!e,staleTime:300*1e3,gcTime:600*1e3,retry:!1})},OS=e=>{const t=Ye(),n=Zl();return mt({queryKey:["memory","config",e,n],queryFn:()=>e?t.getMemoryConfig({agentId:e,requestContext:n}):null,enabled:!!e,staleTime:300*1e3,gcTime:600*1e3,retry:!1,refetchOnWindowFocus:!1})},Eje=({threadId:e,agentId:t})=>{const n=Ye(),r=Zl();return mt({queryKey:["memory","thread",e,t,r],queryFn:()=>n.getMemoryThread({threadId:e,agentId:t}).get({requestContext:r}),enabled:!!e&&e!=="new"&&!!t,staleTime:300*1e3,gcTime:600*1e3,retry:!1,refetchOnWindowFocus:!1})},ELt=({resourceId:e,agentId:t,isMemoryEnabled:n})=>{const r=Ye(),s=Zl();return mt({queryKey:["memory","threads",e,t,s],queryFn:async()=>n?(await r.listMemoryThreads({resourceId:e,agentId:t,requestContext:s})).threads:null,enabled:!!n,staleTime:0,gcTime:0,retry:!1,refetchOnWindowFocus:!1})},EHr=()=>{const e=Ye(),t=Ar(),n=Zl();return Sn({mutationFn:({threadId:r,agentId:s})=>e.getMemoryThread({threadId:r,agentId:s}).delete({requestContext:n}),onSuccess:(r,s)=>{const{agentId:a}=s;a&&t.invalidateQueries({queryKey:["memory","threads",a,a]}),Ve.success("Chat deleted successfully")},onError:()=>{Ve.error("Failed to delete chat")}})},THr=({agentId:e,resourceId:t,threadId:n})=>{const r=Zl(),s=Ye();return Sn({mutationFn:async({searchQuery:a,memoryConfig:i})=>s.searchMemory({agentId:e,resourceId:t,threadId:n,searchQuery:a,memoryConfig:i,requestContext:r})})},jHr=()=>{const e=Ye(),t=Ar(),n=Zl();return Sn({mutationFn:async({threadId:r,agentId:s,title:a})=>e.getMemoryThread({threadId:r,agentId:s}).clone({title:a,requestContext:n}),onSuccess:(r,s)=>{const{agentId:a}=s;a&&t.invalidateQueries({queryKey:["memory","threads",a,a]}),Ve.success("Thread cloned successfully")},onError:()=>{Ve.error("Failed to clone thread")}})},NHr=({agentId:e,resourceId:t,threadId:n,enabled:r=!0,isActive:s=!1})=>{const a=Ye(),i=Zl();return mt({queryKey:["observational-memory",e,t,n,i],queryFn:async()=>!t&&!n?null:a.getObservationalMemory({agentId:e,resourceId:t,threadId:n,requestContext:i}),enabled:r&&!!e&&(!!t||!!n),staleTime:s?1e3:30*1e3,gcTime:300*1e3,retry:!1,refetchOnWindowFocus:!1,refetchInterval:s?2e3:!1,placeholderData:l=>l})},TLt=({agentId:e,resourceId:t,threadId:n,pollWhenActive:r=!0})=>{const s=Ye(),a=Zl(),[i,l]=g.useState(!1),c=mt({queryKey:["memory-status",e,t,n,a],queryFn:()=>e?s.getMemoryStatus(e,a,{resourceId:t,threadId:n}):null,enabled:!!e,staleTime:i&&r?1e3:30*1e3,gcTime:300*1e3,retry:!1,refetchOnWindowFocus:!1,refetchInterval:i&&r?2e3:!1,placeholderData:f=>f}),u=c.data?.observationalMemory?.isObserving,d=c.data?.observationalMemory?.isReflecting;return g.useEffect(()=>{l(u||d||!1)},[u,d]),c},uXe=e=>e===void 0?"Default":typeof e=="number"?`${e.toLocaleString()} tokens`:`${e.min.toLocaleString()}-${e.max.toLocaleString()} tokens`,dXe={success:"green",info:"blue",warning:"yellow"};function IHr({value:e,badge:t}){return typeof e=="boolean"?o.jsx(bt,{size:"xs",indicator:"dot",variant:e?t?dXe[t]:"green":"red",children:e?"Yes":"No"}):t?o.jsx(bt,{size:"xs",variant:dXe[t],children:e}):o.jsx(o.Fragment,{children:e})}const AHr=({agentId:e})=>{const{data:t,isLoading:n}=OS(e),r=t?.config,s=g.useMemo(()=>{if(!r)return[];const a=!!r,i=[{title:"General",items:[{label:"Memory Enabled",value:a,badge:a?"success":void 0},{label:"Last Messages",value:r.lastMessages||0},{label:"Auto-generate Titles",value:!!r.generateTitle,badge:r.generateTitle?"info":void 0}]}];if(r.semanticRecall){const d=!!r.semanticRecall,f=typeof r.semanticRecall=="object"?r.semanticRecall:{};i.push({title:"Semantic Recall",items:[{label:"Enabled",value:d,badge:d?"success":void 0},...d?[{label:"Scope",value:f.scope||"resource"},{label:"Top K Results",value:f.topK||4},{label:"Message Range",value:typeof f.messageRange=="object"?`${f.messageRange.before||1} before, ${f.messageRange.after||1} after`:f.messageRange!==void 0?`${f.messageRange} before, ${f.messageRange} after`:"1 before, 1 after"}]:[]]})}const l=r.observationalMemory,c=l!==null&&typeof l=="object";if(l===!0||c&&l.enabled!==!1){const d=c?l.observationModel||l.model||l.observation?.model:void 0,f=c?l.reflectionModel||l.model||l.reflection?.model:void 0;i.push({title:"Observational Memory",items:[{label:"Enabled",value:!0,badge:"success"},{label:"Scope",value:c&&l.scope||"thread"},{label:"Message Tokens",value:uXe(c?l.observation?.messageTokens:void 0)},{label:"Observation Tokens",value:uXe(c?l.reflection?.observationTokens:void 0)},...d?[{label:"Observation Model",value:String(d)}]:[],...f?[{label:"Reflection Model",value:String(f)}]:[]]})}return i},[r]);return n?o.jsx("div",{className:"p-4",children:o.jsx(Et,{className:"h-32 w-full"})}):!r||s.length===0?o.jsx("div",{className:"p-4",children:o.jsx(ve,{variant:"ui-xs",className:"text-neutral3",children:"No memory configuration available"})}):o.jsx("div",{className:"divide-border1 divide-y pt-1.5 pb-2",children:s.map(a=>o.jsxs(fc,{defaultOpen:a.title!=="Observational Memory",children:[o.jsxs(ql,{className:"text-neutral5 flex w-full items-center justify-between px-4 py-2.5",children:[o.jsx(ve,{as:"span",variant:"ui-md",className:"font-medium text-inherit",children:a.title}),o.jsx(Lr,{className:"text-neutral3 size-4"})]}),o.jsx(Vl,{className:"px-4 pb-3",children:o.jsx(xje,{data:a.items.map(i=>({key:`${a.title}-${i.label}`,label:i.label,value:o.jsx(IHr,{value:i.value??"",badge:i.badge})}))})})]},a.title))})};function RHr({agentId:e}){const{data:t}=nG(),n=!!t?.length;return o.jsx("div",{className:"h-full w-full min-w-0","data-testid":"agent-settings-view",children:o.jsx(Nr,{className:"h-full w-full",viewPortClassName:"h-full",mask:{top:!1},children:o.jsxs("div",{className:"grid grid-cols-1 items-start gap-4 px-5 py-4 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]",children:[o.jsx(yHr,{agentId:e}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs(Ku,{className:"bg-surface3",children:[o.jsx(gj,{children:o.jsx(om,{children:"Memory"})}),o.jsx(lm,{className:"p-0",children:o.jsx(AHr,{agentId:e})})]}),n&&o.jsxs(Ku,{className:"bg-surface3",children:[o.jsx(gj,{children:o.jsx(om,{children:"Channels"})}),o.jsx(lm,{children:o.jsx(ZBr,{agentId:e})})]})]})]})})})}const PHr=({agentId:e})=>{const{data:t,isLoading:n}=Yl(e),{handleCopy:r,isCopied:s}=Ff({text:e}),a=t?.name||"";return o.jsx(Wl,{children:o.jsx("div",{className:"min-w-0 overflow-x-hidden p-3",children:o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsxs("button",{type:"button",onClick:r,"aria-label":"Copy Agent ID for use in code",className:"group/agent-title text-neutral6 flex max-w-full min-w-0 cursor-pointer items-center gap-2","data-testid":"agent-entity-header-copy-id",children:[o.jsx("span",{className:"flex size-7 shrink-0 items-center justify-center",children:o.jsx(Qe,{size:"lg",children:o.jsx(Ri,{})})}),n?o.jsx(Et,{className:"h-3 w-32"}):o.jsx(ve,{variant:"header-md",as:"h2",className:"truncate font-medium",children:a}),s?o.jsx(Ur,{className:"text-neutral3 h-4 w-4 shrink-0"}):o.jsx(zd,{className:"text-neutral3 h-4 w-4 shrink-0"})]})}),o.jsx(yn,{children:"Copy Agent ID for use in code"})]})})})};function bG(e){const t=(window.MASTRA_STUDIO_BASE_PATH??"").replace(/\/$/,"");if(!t)return e;const n=new URL(e,window.location.origin);if(n.origin!==window.location.origin)return e;const r=`${n.pathname}${n.search}${n.hash}`;return n.pathname===t||n.pathname.startsWith(`${t}/`)?r:`${t}${n.pathname}${n.search}${n.hash}`}function $Hr({agentId:e}){const{data:t}=Yl(e),{canCreateAgent:n}=EMt(),{Link:r,paths:s}=dn(),a=`${window.location.origin}${bG(`/agents/${encodeURIComponent(e)}/session`)}`,{handleCopy:i,isCopied:l}=Ff({text:a,copyMessage:"Session URL copied to clipboard!"}),c=t?.source==="stored",u=s.cmsAgentEditLink(e),d=n&&c&&!!u;return o.jsx(Wl,{children:o.jsxs("div",{className:"flex items-start justify-between gap-2 pr-3 max-lg:py-2",children:[o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col max-lg:hidden",children:[o.jsx(PHr,{agentId:e}),t?.description&&o.jsx("p",{className:"text-neutral4 -mt-2 max-w-prose pr-3 pb-1 pl-12 text-sm",children:t.description})]}),o.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-2 py-2",children:[d&&o.jsxs(ie,{variant:"outline",size:"sm",as:r,to:u,children:[o.jsx(Qe,{size:"sm",children:o.jsx(Yh,{})}),"Edit"]}),o.jsxs(ie,{variant:"ghost",size:"sm",type:"button",onClick:i,tooltip:"Copy session URL to share with your team","data-testid":"agent-entity-header-share",children:[o.jsx(Qe,{size:"sm",children:l?o.jsx(Ur,{}):o.jsx(Dct,{})}),"Share"]}),o.jsxs(ie,{variant:"primary",size:"sm",as:r,to:s.agentNewThreadLink(e),"data-testid":"agent-view-header-new-chat",children:[o.jsx(Qe,{size:"sm",children:o.jsx(dJt,{})}),"Open chat"]})]})]})})}function MHr(){const{agentId:e}=fr(),{data:t,isLoading:n,error:r}=Yl(e);return r&&hs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{})}):r&&ps(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ks,{resource:"agents"})}):n?o.jsx(VBr,{}):t?o.jsx(pG,{children:o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[o.jsx($Hr,{agentId:e}),o.jsx("div",{className:"min-h-0 overflow-hidden",children:o.jsx(RHr,{agentId:e})})]})},e):o.jsx("div",{className:"py-4 text-center",children:"Agent not found"})}function vs({children:e,className:t,style:n}){const r=jLt("MainContentLayout"),s=KPt();return o.jsxs("main",{className:K("grid h-full grid-rows-[auto_1fr] content-start items-start",t),style:{...n,...r?{border:"3px dotted red"}:{}},children:[s&&o.jsx("h1",{className:"sr-only",children:s}),e]})}function by({children:e,className:t,isCentered:n=!1,isDivided:r=!1,hasLeftServiceColumn:s=!1,style:a}){const i=jLt("MainContentContent"),l=DHr({isCentered:n,isDivided:r,hasLeftServiceColumn:s,className:t});return o.jsx("div",{className:l,style:{...a,...i?{border:"3px dotted orange"}:{}},children:e})}const DHr=({isCentered:e,isDivided:t,hasLeftServiceColumn:n,className:r})=>K("grid h-full overflow-y-auto ","min-w-min overflow-x-auto",{"items-start content-start":!e&&!t&&!n,"grid place-items-center":e,"grid-cols-[1fr_1fr]":t&&!n,"grid-cols-[12rem_1fr_1fr]":t&&n,"grid-cols-[auto_1fr]":!t&&n},r);function jLt(e){try{const t=localStorage.getItem("add-dev-style-to-components");return t?t.split(",").map(r=>r.trim()).filter(Boolean).includes(e):!1}catch(t){return console.error("Error reading or parsing localStorage:",t),!1}}function NLt({config:e,redirectUri:t,className:n,loginUrl:r="/login"}){const{mutate:s,isPending:a}=rDt();if(!e)return null;if(e.type==="sso"||e.type==="both"&&e.sso){const l=e.sso,c=()=>{s({redirectUri:t},{onSuccess:u=>{window.location.href=u.url}})};return o.jsxs(ie,{onClick:c,disabled:a,className:n,children:[l?.icon&&o.jsx("span",{className:"mr-2",children:l.icon}),l?.text||"Sign in"]})}const i=()=>{const l=new URL(bG(r),window.location.origin);t&&l.searchParams.set("redirect",t),window.location.href=l.toString()};return o.jsx(ie,{onClick:i,className:n,children:"Sign in"})}function fXe({user:e,size:t="sm"}){if(!e)return null;const n=e.name||e.email||"User";return o.jsx(OC,{src:e.avatarUrl,name:n,size:t})}function LHr({user:e}){const[t,n]=g.useState(!1),{mutate:r,isPending:s}=U2r(),{data:a}=pc(),{isImpersonating:i,impersonatedRole:l,startImpersonation:c,stopImpersonation:u,isSwitching:d}=RH();if(!e)return null;const f=()=>{r(void 0,{onSuccess:m=>{m.redirectTo?window.location.href=m.redirectTo:window.location.reload()}})},h=a&&Am(a)?a.availableRoles:void 0,p=e.name||e.email||"User";return o.jsxs(Vf,{open:t,onOpenChange:n,children:[o.jsx(Xd,{asChild:!0,children:o.jsx("button",{type:"button",className:"hover:bg-surface2 flex items-center gap-2 rounded-md p-1 transition-colors",children:o.jsx(fXe,{user:e,size:"sm"})})}),o.jsxs(Jd,{align:"end",className:"w-64 p-0",children:[o.jsx("div",{className:"border-border1 border-b p-3",children:o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(fXe,{user:e,size:"md"}),o.jsxs("div",{className:"flex flex-col overflow-hidden",children:[o.jsx(ve,{variant:"ui-md",className:"truncate font-medium",children:p}),e.email&&o.jsx(ve,{variant:"ui-sm",className:"text-neutral3 truncate",children:e.email})]})]})}),h&&h.length>0&&o.jsxs("div",{className:"border-border1 border-b p-2",children:[o.jsx(ve,{variant:"ui-xs",className:"text-neutral3 px-2 py-1 tracking-wider uppercase",children:"Preview as role"}),h.map(m=>{const v=i&&l?.id===m.id;return o.jsxs("button",{type:"button",disabled:d,onClick:()=>{v?u():c(m),n(!1)},className:`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors ${v?"bg-surface2":"hover:bg-surface2"} ${d?"cursor-not-allowed opacity-50":""}`,children:[d&&o.jsx(Vs,{className:"h-3.5 w-3.5 animate-spin"}),o.jsx("span",{className:"flex-1 capitalize",children:m.name}),v&&o.jsx(or,{className:"text-neutral3 hover:text-neutral1 h-3.5 w-3.5"})]},m.id)})]}),o.jsxs("div",{className:"flex flex-col gap-1 p-2",children:[o.jsxs(ie,{as:Da,to:"/settings",variant:"ghost",className:"w-full justify-start",onClick:()=>n(!1),children:[o.jsx(Ij,{className:"h-4 w-4"}),"Settings"]}),o.jsx(ie,{variant:"ghost",onClick:f,disabled:s,className:"w-full justify-start",children:s?"Signing out...":"Sign out"})]})]})]})}function RD({className:e}){const{data:t,isLoading:n,error:r}=pc();return n||r||!t?.enabled?null:Am(t)?o.jsx(LHr,{user:t.user}):o.jsx(NLt,{config:t.login,redirectUri:typeof window<"u"?window.location.href:void 0,className:e})}const Ez="__custom__",ILt=()=>{const e=cwt(),{requestContext:t,setRequestContext:n}=ys(),r=g.useMemo(()=>{if(!e)return Ez;const a=JSON.stringify(t??{});for(const[i,l]of Object.entries(e))if(JSON.stringify(l)===a)return i;return Ez},[e,t]),s=a=>{if(a===Ez){n({});return}if(!e)return;const i=e[a];i&&n(i)};return o.jsxs(UH,{children:[o.jsxs(ESe,{children:[o.jsx(Wh,{className:"h-5 w-8 shrink-0"}),"Mastra Studio",o.jsx(RD,{})]}),e&&Object.keys(e).length>0&&o.jsx(Kbt,{children:o.jsxs(la,{value:r,onValueChange:s,children:[o.jsx(ua,{size:"sm",className:"w-[200px]",children:o.jsx(ca,{placeholder:"Select a preset..."})}),o.jsxs(da,{children:[o.jsx(xr,{value:Ez,children:"Custom"}),Object.keys(e).map(a=>o.jsx(xr,{value:a,children:a},a))]})]})})]})},hXe={modelSettings:{maxRetries:2,maxSteps:15,chatWithGenerateLegacy:!1,chatWithGenerate:!1,chatWithLegacyStream:!1}};function FHr({agentId:e,defaultSettings:t}){const[n,r]=g.useState(t),s=`mastra-agent-store-${e}`;return g.useEffect(()=>{try{const l=localStorage.getItem(s),c=l?JSON.parse(l):{},u={...c,modelSettings:{...hXe.modelSettings,...c?.modelSettings??{},...t?.modelSettings??{}}};r(u)}catch{}},[s,t]),{settings:n,setSettings:l=>{r(c=>({...c,...l})),localStorage.setItem(s,JSON.stringify({...l,agentId:e}))},resetAll:()=>{const l={modelSettings:{...hXe.modelSettings,...t?.modelSettings??{}}};r(l),localStorage.removeItem(s)}}}const ALt=g.createContext({});function Tje({children:e,agentId:t,defaultSettings:n}){const{settings:r,setSettings:s,resetAll:a}=FHr({agentId:t,defaultSettings:n});return o.jsx(ALt.Provider,{value:{settings:r,setSettings:s,resetAll:a},children:e})}const jje=()=>g.useContext(ALt),xxe=(e,t)=>["memory","status",e,t],Yq=(e,t)=>["memory","thread",e,"messages",t??0];function zHr(e,t){const n=Ye(),r=0,s=100;return mt({queryKey:Yq(e,r),queryFn:e?()=>n.getMemoryThread({threadId:e}).listMessages({page:r,perPage:s}):n_})}const Kq=(e,t)=>["memory","observational-memory",e,t];function RLt(e,t,n){const r=Ye();return mt({queryKey:Kq(e,t),queryFn:e&&t?()=>r.getObservationalMemory({agentId:e,threadId:t,resourceId:n}):n_,staleTime:5e3})}const PLt="mastra-memory-om-observation",pXe={"data-om-observation-start":"start","data-om-observation-end":"end","data-om-observation-failed":"failed","data-om-buffering-start":"bufferingStart","data-om-buffering-end":"bufferingEnd","data-om-buffering-failed":"bufferingFailed","data-om-activation":"activation"},$Lt=(e,t)=>{for(const n of e){if(!(n.type in pXe))continue;const r=n,s=r.data?.cycleId;if(!s)continue;const a=pXe[r.type],i=t.get(s)||{};i[a]=r,t.set(s,i)}return t},Nje=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0,Ije=e=>Array.isArray(e)&&e.length>0,Xk=e=>({...Nje(e?.extractedValues)?{extractedValues:e.extractedValues}:{},...Ije(e?.extractionFailures)?{extractionFailures:e.extractionFailures}:{}}),MT=e=>Object.keys(Xk(e)).length>0,Tz=(e,t)=>{if(!e?.data||!t)return e;const n=Xk(e.data),r=Xk(t);if(!Object.keys(r).length)return e;const s={...n.extractedValues??r.extractedValues?{extractedValues:n.extractedValues??r.extractedValues}:{},...n.extractionFailures??r.extractionFailures?{extractionFailures:n.extractionFailures??r.extractionFailures}:{}};return{...e,data:{...e.data,...s}}},BHr=(e,t)=>{for(const[n,r]of e){const s=t.get(n);s&&(r.end=Tz(r.end,s.end),r.failed=Tz(r.failed,s.failed),r.bufferingEnd=Tz(r.bufferingEnd,s.bufferingEnd),r.bufferingFailed=Tz(r.bufferingFailed,s.bufferingFailed));const a={...s??{}};MT(r.end?.data)&&(a.end=Xk(r.end?.data)),MT(r.failed?.data)&&(a.failed=Xk(r.failed?.data)),MT(r.bufferingEnd?.data)&&(a.bufferingEnd=Xk(r.bufferingEnd?.data)),MT(r.bufferingFailed?.data)&&(a.bufferingFailed=Xk(r.bufferingFailed?.data)),Object.keys(a).length>0&&t.set(n,a)}return e},UHr=(e,t)=>{const n=new Map;for(const r of e){const s=r?.content?.parts;Array.isArray(s)&&$Lt(s,n)}return t?BHr(n,t):n},qHr=(e,t)=>{const n=t.start?.data;if(!n)return;const r=t.end?.data,s=t.failed?.data,a=!!t.failed,i=!!t.end,l=!!n.disconnectedAt||i&&!!r?.disconnectedAt,c=a?"failed":l?"disconnected":i?"observed":"observing",u={...n,...i?r:{},...a?s:{},_state:a?"failed":l?"disconnected":i?"complete":"loading"};return{cycleId:e,recordId:typeof u.recordId=="string"?u.recordId:void 0,status:c,operationType:u.operationType,observations:u.observations,extractedValues:Nje(u.extractedValues)?u.extractedValues:void 0,extractionFailures:Ije(u.extractionFailures)?u.extractionFailures:void 0,omData:u,isLoading:c==="observing"}},VHr=(e,t)=>{const n=t.bufferingStart?.data;if(!n)return;const r=t.bufferingEnd?.data,s=t.bufferingFailed?.data,a=t.activation?.data,i=!!t.bufferingFailed,l=!!t.activation,c=!!t.bufferingEnd,u=!!n.disconnectedAt,d=i?"buffering-failed":u?"disconnected":c?"buffering-complete":l?"activated":"buffering",f={...n,...c?r:{},...i?s:{},...l?a:{},_state:d};return!f.tokensObserved&&f.tokensActivated&&(f.tokensObserved=f.tokensActivated),{cycleId:e,recordId:typeof f.recordId=="string"?f.recordId:void 0,status:d,operationType:f.operationType,observations:f.observations,extractedValues:Nje(f.extractedValues)?f.extractedValues:void 0,extractionFailures:Ije(f.extractionFailures)?f.extractionFailures:void 0,omData:f,isLoading:d==="buffering"}},jz=(e,t,n)=>n==="observation"?qHr(e,t):VHr(e,t),Nz=(e,t,n)=>({type:"dynamic-tool",toolCallId:`om-${t}-${e}`,toolName:PLt,input:n.omData,output:n.isLoading?void 0:{status:t==="observation"?n.status==="failed"?"failed":n.status==="disconnected"?"disconnected":"complete":n.status,omData:n.omData},state:n.isLoading?"input-available":"output-available"}),mXe=(e,t)=>t==="observation"?!!e?.end||!!e?.failed:!!e?.bufferingEnd||!!e?.bufferingFailed,gXe=(e,t)=>t==="observation"?e==="data-om-observation-end"||e==="data-om-observation-failed":e==="data-om-buffering-end"||e==="data-om-buffering-failed"||e==="data-om-activation",HHr=(e,t)=>{if(!e||!Array.isArray(e.content?.parts))return e;const n=$Lt(e.content.parts,new Map),r=[];for(const s of e.content.parts){const a=s.data?.cycleId,i=s.type;if(i==="data-om-observation-start"&&a){const l=n.get(a),c=t.get(a);if(!l)continue;const u=mXe(c,"observation")?c??l:{start:l.start},d=jz(a,u,"observation");if(!d)continue;r.push(Nz(a,"observation",d))}else if(i==="data-om-buffering-start"&&a){const l=n.get(a),c=t.get(a);if(!l)continue;const u=mXe(c,"buffering")?c??l:{bufferingStart:l.bufferingStart},d=jz(a,u,"buffering");if(!d)continue;r.push(Nz(a,"buffering",d))}else if(a&&gXe(i,"observation")){const l=n.get(a),c=t.get(a);if(l?.start||c?.start||!c)continue;const u=jz(a,c,"observation");if(!u)continue;r.push(Nz(a,"observation",u))}else if(a&&gXe(i,"buffering")){const l=n.get(a),c=t.get(a);if(l?.bufferingStart||c?.bufferingStart||i==="data-om-activation"&&(l?.bufferingEnd||l?.bufferingFailed)||!c)continue;const u=jz(a,c,"buffering");if(!u)continue;r.push(Nz(a,"buffering",u))}else{if(i?.startsWith("data-om-"))continue;r.push(s)}}return{...e,content:{...e.content,parts:r}}},MLt=(e,t)=>e.map(n=>{if(n.role!=="assistant")return n;const r=n.content?.parts;if(!Array.isArray(r))return n;const{parts:s,changed:a}=t(r);return a?{...n,content:{...n.content,parts:s}}:n}),Aje=e=>{const t=new Set,n=new Set,r=new Set;for(const s of e){const a=s.content?.parts;if(Array.isArray(a))for(const i of a){const l=i?.data?.cycleId;l&&((i.type==="data-om-observation-end"||i.type==="data-om-observation-failed")&&t.add(l),(i.type==="data-om-buffering-end"||i.type==="data-om-buffering-failed")&&n.add(l),i.type==="data-om-activation"&&r.add(l))}}return{observation:t,buffering:n,activatedBuffering:r}},vXe=e=>{const t=Aje(e),n=new Set([...t.buffering,...t.activatedBuffering]);return MLt(e,r=>{let s=!1;return{parts:r.map(i=>{if(i.type==="data-om-observation-start"){const l=i.data?.cycleId;return!l||i.data?.disconnectedAt||t.observation.has(l)?i:(s=!0,{...i,data:{...i.data,disconnectedAt:new Date().toISOString(),_state:"disconnected"}})}if(i.type==="data-om-buffering-start"){const l=i.data?.cycleId;return!l||i.data?.disconnectedAt||n.has(l)?i:(s=!0,{...i,data:{...i.data,disconnectedAt:new Date().toISOString(),_state:"disconnected"}})}if(i.type==="tool-call"&&i.toolName===PLt){const l=i.metadata?.omData||i.args;if(!l?.completedAt&&!l?.failedAt&&!l?.disconnectedAt)return s=!0,{...i,metadata:{...i.metadata,omData:{...l,disconnectedAt:new Date().toISOString(),_state:"disconnected"}}}}return i}),changed:s}})},WHr=e=>{const{buffering:t,activatedBuffering:n}=Aje(e),r=new Set([...t,...n]);for(const s of e){const a=s.content?.parts;if(Array.isArray(a))for(const i of a){const l=i?.data?.cycleId;if(i.type==="data-om-buffering-start"&&l&&!i.data?.disconnectedAt&&!r.has(l)||i.type==="data-om-buffering-end"&&l&&i.data?.operationType==="observation"&&!MT(i.data))return!0}}return!1},DLt=(e,t)=>{const n=new Map,r=Aje(e).buffering;if(t?.bufferedObservationChunks)for(const s of t.bufferedObservationChunks)s.cycleId&&n.set(s.cycleId,s);return MLt(e,s=>{const a=[];let i=!1;for(const l of s){if(l.type==="data-om-buffering-end"&&l.data?.cycleId&&l.data?.operationType==="observation"){const c=n.get(l.data.cycleId);if(c&&!MT(l.data)){a.push({...l,data:{...l.data,observations:l.data.observations??c.observations,extractedValues:c.extractedValues,extractionFailures:c.extractionFailures}}),i=!0;continue}}if(a.push(l),l.type==="data-om-buffering-start"&&l.data?.cycleId&&!l.data?.disconnectedAt&&!r.has(l.data.cycleId)){const c=l.data.cycleId,u=l.data.operationType,d={cycleId:c,operationType:u,completedAt:new Date().toISOString()};if(u==="observation"){const f=n.get(c);f&&(d.tokensBuffered=f.messageTokens,d.bufferedTokens=f.tokenCount,d.observations=f.observations,d.extractedValues=f.extractedValues,d.extractionFailures=f.extractionFailures)}else u==="reflection"&&t&&(d.tokensBuffered=t.bufferedReflectionInputTokens,d.bufferedTokens=t.bufferedReflectionTokens,d.observations=t.bufferedReflection);a.push({type:"data-om-buffering-end",data:d}),r.add(c),i=!0}}return{parts:a,changed:i}})},ZHr=e=>{const t=[];let n=null;for(const r of e){const s=r?.content?.parts;if(Array.isArray(s))for(const a of s)a?.type==="data-om-activation"&&a?.data?.cycleId&&t.push(a.data.cycleId),a?.type==="data-om-status"&&a?.data&&(n=a.data)}return{activatedCycleIds:t,lastProgress:n}},GHr="tool-calls",QHr=e=>`Agent stopped because it reached maxSteps${typeof e=="number"?` (${e})`:""} while tool calls were still pending. Increase maxSteps in advanced settings and try again.`,YHr=e=>{if(e.type!=="finish")return;const t=e.payload?.stepResult?.reason;return typeof t=="string"?t:void 0},KHr=e=>YHr(e)===GHr,wxe=e=>{const t=e.payload?.error;let n;if(typeof t=="string")n=t;else if(t instanceof Error)n=t.message;else if(t&&typeof t=="object"&&typeof t.message=="string")n=t.message;else if(t==null)n="Unknown error";else try{n=JSON.stringify(t)??String(t)}catch{try{n=String(t)}catch{n="Unknown error"}}return{id:`error-${e.runId??"unknown"}-${Date.now()}`,role:"assistant",createdAt:new Date,content:{format:2,parts:[{type:"text",text:n}],metadata:{status:"error"}}}},XHr=(e,t)=>wxe({runId:e.runId,payload:{error:QHr(t)}}),yXe=e=>{const t=e.type;if(t==="error"||t==="data-om-observation-start"||t==="data-om-observation-end"||t==="data-om-observation-failed"||t==="data-om-status"||t==="data-om-activation")return e},JHr=e=>{const t=new zC;return Object.entries(e.requestContext??{}).forEach(([n,r])=>{t.set(n,r)}),e.agentVersionId&&t.set("agentVersionId",e.agentVersionId),t},bXe=e=>(e.type==="tool-result"||e.type==="tool-execution-end")&&e.payload?.toolName==="updateWorkingMemory"&&typeof e.payload.result=="object"&&"success"in e.payload.result&&e.payload.result?.success,eWr=({agentId:e,requestContext:t,agentVersionId:n,threadId:r,modelSettingsArgs:s,model:a,chatWithNetwork:i,chatWithGenerate:l,maxSteps:c,isOMEnabled:u,tracingOptions:d,threadSignalsUnsupportedRef:f,isRunningStream:h,sendMessage:p,cancelRun:m,setMessages:v,setStreamErrors:y,refreshThreadList:b,refreshWorkingMemory:x,handleObservationStart:w,handleProgressUpdate:k,refreshObservationalMemory:C,handleActivation:_,resetObservationalMemoryStreamState:T,signalTimelineRefresh:E})=>{const N=Ye(),I=Ar(),A=g.useRef(null),P=g.useRef({requestContext:t,agentVersionId:n,threadId:r,modelSettingsArgs:s,model:a,chatWithNetwork:i,chatWithGenerate:l,maxSteps:c,isOMEnabled:u,tracingOptions:d});P.current={requestContext:t,agentVersionId:n,threadId:r,modelSettingsArgs:s,model:a,chatWithNetwork:i,chatWithGenerate:l,maxSteps:c,isOMEnabled:u,tracingOptions:d};const L=g.useCallback(z=>{z&&(I.refetchQueries({queryKey:Kq(e,z)}),I.refetchQueries({queryKey:Yq(z)}),I.refetchQueries({queryKey:xxe(e,z)}),E())},[e,I,E]),D=g.useCallback(z=>{!z||!P.current.isOMEnabled||N.awaitBufferStatus({agentId:e,resourceId:e,threadId:z}).then(V=>{v(M=>DLt(M,V?.record)),I.invalidateQueries({queryKey:["observational-memory",e]}),I.invalidateQueries({queryKey:["memory-status",e]}),L(z)}).catch(()=>{})},[e,N,I,L,v]),B=g.useCallback(z=>{z?.type==="error"&&y(V=>[...V,wxe(z)]),z?.type==="data-om-observation-start"&&w(z.data?.operationType),z?.type==="data-om-status"&&k(z.data),(z?.type==="data-om-observation-end"||z?.type==="data-om-observation-failed"||z?.type==="data-om-activation")&&C(z.data?.operationType),z?.type==="data-om-activation"&&_(z.data)},[_,w,k,C,y]),H=g.useCallback(async({message:z,attachments:V=[]})=>{const M=P.current;if(f.current&&(h||A.current))return;y([]);const G=new AbortController;A.current=G;const F=JHr(M);try{if(M.chatWithNetwork)await p({message:z,mode:"network",coreUserMessages:V,requestContext:F,threadId:M.threadId,modelSettings:M.modelSettingsArgs,model:M.model,signal:G.signal,tracingOptions:M.tracingOptions,onNetworkChunk:async R=>{bXe(R)&&x?.(),R.type==="network-execution-event-step-finish"&&b?.(),B(yXe(R))}});else if(M.chatWithGenerate){await p({message:z,mode:"generate",coreUserMessages:V,requestContext:F,threadId:M.threadId,modelSettings:M.modelSettingsArgs,model:M.model,signal:G.signal,tracingOptions:M.tracingOptions}),await b?.(),L(M.threadId);return}else{await p({message:z,mode:"stream",coreUserMessages:V,requestContext:F,threadId:M.threadId,modelSettings:M.modelSettingsArgs,model:M.model,tracingOptions:M.tracingOptions,onChunk:async R=>{R.type==="finish"&&(KHr(R)&&y(U=>[...U,XHr(R,M.maxSteps)]),await b?.()),bXe(R)&&x?.(),B(yXe(R))},signal:G.signal}),L(M.threadId),D(M.threadId);return}setTimeout(()=>{b?.()},500),L(M.threadId),D(M.threadId)}catch(R){if(console.error("Error occurred in ChatProvider",R),R.name==="AbortError")return;y(U=>[...U,wxe({runId:"thrown",payload:{error:R}})]),T()}finally{A.current=null}},[D,B,h,b,L,x,T,p,y,f]),q=g.useCallback(async()=>{A.current?.abort(),A.current=null,T(),m?.(),D(P.current.threadId)},[m,D,T]);return{send:H,cancel:q}};function xXe(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function tWr(e,t,n){const r=Ye(),[s,a]=g.useState(!1),[i,l]=g.useState(null),[c,u]=g.useState("thread"),[d,f]=g.useState("markdown"),[h,p]=g.useState(!0),[m,v]=g.useState(!1),{requestContext:y}=ys(),b=g.useCallback(async()=>{p(!0);try{if(!e||!t){l(null),p(!1);return}const w=await r.getWorkingMemory({agentId:e,threadId:t,resourceId:n,requestContext:y}),{workingMemory:k,source:C,workingMemoryTemplate:_,threadExists:T}=w;if(a(T),l(k),u(C),f(_?.format||"markdown"),_?.format==="json"){let E="";k?E=xXe(k):_?.content?E=xXe(_.content):E="",l(E)}else l(k||_?.content||"")}catch(w){l(null),console.error("Error fetching working memory",w)}finally{p(!1)}},[e,t,n]);return g.useEffect(()=>{b()},[b]),{threadExists:s,workingMemoryData:i,workingMemorySource:c,workingMemoryFormat:d,isLoading:h,isUpdating:m,refetch:b,updateWorkingMemory:async w=>{v(!0);try{if(d==="json")try{JSON.parse(w)}catch{throw new Error("Invalid JSON working memory")}await r.updateWorkingMemory({agentId:e,threadId:t,workingMemory:w,resourceId:n,requestContext:y}),b()}catch(k){throw console.error("Error updating working memory",k),k}finally{v(!1)}}}}const LLt=g.createContext({threadExists:!1,workingMemoryData:null,workingMemorySource:"thread",isLoading:!1,isUpdating:!1,updateWorkingMemory:()=>Promise.resolve(),refetch:()=>Promise.resolve()});function FLt({agentId:e,threadId:t,resourceId:n,children:r}){const s=tWr(e,t,n);return o.jsx(LLt.Provider,{value:s,children:r})}function zLt(){const e=g.useContext(LLt);if(!e)throw new Error("useWorkingMemory must be used within a WorkingMemoryProvider");return e}const BLt=g.createContext(null);function ULt({children:e}){const[t,n]=g.useState(!1),[r,s]=g.useState(!1),[a,i]=g.useState(0),[l,c]=g.useState(null),[u,d]=g.useState(new Set),f=g.useCallback(()=>{i(Date.now())},[]),h=g.useCallback(m=>{d(v=>new Set([...v,m]))},[]),p=g.useCallback(()=>{n(!1),s(!1),d(new Set)},[]);return o.jsx(BLt.Provider,{value:{isObservingFromStream:t,setIsObservingFromStream:n,isReflectingFromStream:r,setIsReflectingFromStream:s,observationsUpdatedAt:a,signalObservationsUpdated:f,streamProgress:l,setStreamProgress:c,activatedCycleIds:u,markCycleIdActivated:h,clearProgress:p},children:e})}function xG(){const e=g.useContext(BLt);return e||{isObservingFromStream:!1,setIsObservingFromStream:()=>{},isReflectingFromStream:!1,setIsReflectingFromStream:()=>{},observationsUpdatedAt:0,signalObservationsUpdated:()=>{},streamProgress:null,setStreamProgress:()=>{},activatedCycleIds:new Set,markCycleIdActivated:()=>{},clearProgress:()=>{}}}const qLt=g.createContext(null),nWr={isPanelOpen:!1,openPanel:()=>{},closePanel:()=>{},selectedTimestamp:null,setSelectedTimestamp:()=>{}};function rWr({children:e}){const[t,n]=g.useState(!1),[r,s]=g.useState(null),a=g.useCallback(()=>n(!0),[]),i=g.useCallback(()=>n(!1),[]),l=g.useMemo(()=>({isPanelOpen:t,openPanel:a,closePanel:i,selectedTimestamp:r,setSelectedTimestamp:s}),[t,a,i,r]);return o.jsx(qLt.Provider,{value:l,children:e})}function wG(){return g.useContext(qLt)??nWr}const Rje=g.createContext(null);function Pje({children:e,...t}){return o.jsx(Rje.Provider,{value:t,children:e})}function Wo(){const e=g.useContext(Rje);if(!e)throw new Error("useAgentEditFormContext must be used within an AgentEditFormProvider");return e}function VLt(){return g.useContext(Rje)}const $je=g.createContext(null);function HLt({children:e,defaultProvider:t="",defaultModel:n=""}){const[r,s]=g.useState({provider:t,model:n,explicit:!1}),a=f=>{s({provider:f,model:"",explicit:!1})},i=(f,h)=>{s({provider:f,model:h,explicit:!0})},{provider:l,model:c,explicit:u}=r,d=u?`${l}/${c}`:void 0;return o.jsx($je.Provider,{value:{provider:l,model:c,modelOverride:d,setProvider:a,setModel:i},children:e})}function Mje(){const e=g.useContext($je);if(!e)throw new Error("usePlaygroundModel must be used within a PlaygroundModelProvider");return e}function Dje(){return g.useContext($je)??void 0}const WLt=g.createContext(null);function sWr({children:e}){const[t,n]=g.useState([]),[r,s]=g.useState([]),[a,i]=g.useState(null),{updateExperimentResult:l}=wi(),c=Ye(),u=g.useCallback(x=>{n(w=>{const k=new Set(w.map(_=>_.itemId)),C=x.filter(_=>!k.has(_.itemId));return[...w,...C.map((_,T)=>({..._,id:_.id||`review-${Date.now()}-${T}`,tags:_.tags??[]}))]})},[]),d=g.useCallback(x=>{n(w=>{const k=new Map(x.map(_=>[_.id,_])),C=w.filter(_=>!k.has(_.id));return[...x,...C]})},[]),f=g.useCallback(x=>{const w=t.find(k=>k.id===x);w?.experimentId&&w?.datasetId&&l.mutate({datasetId:w.datasetId,experimentId:w.experimentId,resultId:w.id,status:null}),n(k=>k.filter(C=>C.id!==x))},[t,l]),h=g.useCallback(async x=>{const w=t.find(k=>k.id===x);w?.experimentId&&w?.datasetId&&await l.mutateAsync({datasetId:w.datasetId,experimentId:w.experimentId,resultId:w.id,status:"complete"}),n(k=>k.filter(C=>C.id!==x))},[t,l]),p=g.useCallback((x,w)=>{const k=t.find(C=>C.id===x);k?.experimentId&&k?.datasetId&&l.mutate({datasetId:k.datasetId,experimentId:k.experimentId,resultId:k.id,tags:w}),n(C=>C.map(_=>_.id===x?{..._,tags:w}:_))},[t,l]),m=g.useCallback((x,w)=>{const k=t.find(C=>C.id===x);k?.traceId&&w!==void 0&&c.createFeedback({feedback:{traceId:k.traceId,source:"studio",feedbackSource:"studio",feedbackType:"rating",value:w==="positive"?1:-1,reviewStatus:"reviewed",experimentId:k.experimentId??void 0,sourceId:k.id}}).catch(()=>{}),n(C=>C.map(_=>_.id===x?{..._,rating:w}:_))},[t,c]),v=g.useCallback((x,w)=>{const k=t.find(C=>C.id===x);k?.experimentId&&k?.datasetId&&l.mutate({datasetId:k.datasetId,experimentId:k.experimentId,resultId:k.id,comment:w}),k?.traceId&&c.createFeedback({feedback:{traceId:k.traceId,source:"studio",feedbackSource:"studio",feedbackType:"comment",value:w,comment:w,reviewStatus:"reviewed",experimentId:k.experimentId??void 0,sourceId:k.id}}).catch(()=>{}),n(C=>C.map(_=>_.id===x?{..._,comment:w}:_))},[t,c,l]),y=g.useCallback((x,w)=>{n(k=>k.map(C=>C.id===x?{...C,clusterId:w}:C))},[]),b=g.useCallback(()=>{n([]),s([]),i(null)},[]);return o.jsx(WLt.Provider,{value:{items:t,clusters:r,activeClusterId:a,addItems:u,removeItem:f,completeItem:h,setItemTags:p,rateItem:m,commentItem:v,setClusters:s,setActiveClusterId:i,assignCluster:y,clearAll:b,loadPersistedItems:d},children:e})}function ZLt(){const e=g.useContext(WLt);if(!e)throw new Error("useReviewQueue must be used within ReviewQueueProvider");return e}function aWr({isSupportedModel:e,threadSignalsEnabled:t,threadId:n,threadSignalsUnsupported:r}){return e&&t&&!!n&&!r}const GLt=g.createContext(void 0);function QLt({children:e,approveToolcall:t,declineToolcall:n,approveToolcallGenerate:r,declineToolcallGenerate:s,approveNetworkToolcall:a,declineNetworkToolcall:i,isRunning:l,toolCallApprovals:c,networkToolCallApprovals:u}){return o.jsx(GLt.Provider,{value:{approveToolcall:t,declineToolcall:n,approveToolcallGenerate:r,declineToolcallGenerate:s,approveNetworkToolcall:a,declineNetworkToolcall:i,isRunning:l,toolCallApprovals:c,networkToolCallApprovals:u},children:e})}function Lje(){const e=g.useContext(GLt);if(!e)throw new Error("useToolCall must be used within a ToolCallProvider");return e}function iWr({children:e,agentId:t,initialMessages:n,threadId:r,refreshThreadList:s,settings:a,requestContext:i,modelVersion:l,agentVersionId:c,supportsMemory:u}){const{settings:d}=VH(),f=Dje()?.modelOverride,[h,p]=g.useState([]),[m,v]=g.useState(!1),y=g.useRef(!1),b=a?.modelSettings??{},x=window.MASTRA_AGENT_SIGNALS!=="false"&&u!==!1&&!b.chatWithLegacyStream;g.useEffect(()=>{p([]),y.current=!1,v(!1)},[t,r]);const w=g.useMemo(()=>{if(!c&&!i)return;const _e=new zC;return Object.entries(i??{}).forEach(([et,dt])=>{_e.set(et,dt)}),c&&_e.set("agentVersionId",c),_e},[c,i]),{messages:k,tasks:C,sendMessage:_,cancelRun:T,isRunning:E,isAwaitingToolApproval:N,setMessages:I,approveToolCall:A,declineToolCall:P,approveToolCallGenerate:L,declineToolCallGenerate:D,toolCallApprovals:B,approveNetworkToolCall:H,declineNetworkToolCall:q,networkToolCallApprovals:z}=m1e({agentId:t,threadId:r,initialMessages:n,requestContext:w,enableThreadSignals:x,onThreadSignalsUnsupported:()=>{y.current=!0,v(!0)}}),{refetch:V}=zLt(),M=Ar(),G=Ye(),{data:F}=OS(t),R=F?.config?.observationalMemory,U=R===!0||typeof R=="object"&&R!==null&&(!("enabled"in R)||R.enabled!==!1),{setIsObservingFromStream:Z,setIsReflectingFromStream:Y,signalObservationsUpdated:te,setStreamProgress:J,markCycleIdActivated:ee}=xG(),re=g.useCallback(_e=>{_e==="reflection"?Y(!0):Z(!0)},[Z,Y]),ae=g.useCallback(_e=>{_e.threadId&&_e.threadId!==r||J({windows:_e.windows,recordId:_e.recordId,threadId:_e.threadId,stepNumber:_e.stepNumber,generationCount:_e.generationCount})},[J,r]),X=g.useCallback(_e=>{_e==="reflection"?Y(!1):Z(!1),te(),M.invalidateQueries({queryKey:["observational-memory",t]}),M.invalidateQueries({queryKey:["memory-status",t]}),M.refetchQueries({queryKey:Kq(t,r)}),M.refetchQueries({queryKey:Yq(r)}),M.refetchQueries({queryKey:xxe(t,r)})},[t,M,Z,Y,te,r]),ne=g.useCallback(_e=>{const et=_e?.cycleId;et&&ee(et)},[ee]),se=g.useCallback(()=>{Z(!1),Y(!1),I(_e=>vXe(_e)),M.invalidateQueries({queryKey:["observational-memory",t]}),M.invalidateQueries({queryKey:["memory-status",t]}),M.refetchQueries({queryKey:Kq(t,r)}),M.refetchQueries({queryKey:Yq(r)}),M.refetchQueries({queryKey:xxe(t,r)})},[t,M,Z,Y,I,r]);g.useEffect(()=>{const{activatedCycleIds:_e,lastProgress:et}=ZHr(n||[]);for(const dt of _e)ee(dt);et&&ae(et)},[ae,n,ee]),g.useEffect(()=>{if(!r||!WHr(n||[]))return;let _e=!1;return G.awaitBufferStatus({agentId:t,resourceId:t,threadId:r}).then(et=>{_e||I(dt=>DLt(dt,et?.record))}).catch(()=>{_e||I(et=>vXe(et))}),()=>{_e=!0}},[t,G,n,I,r]);const{frequencyPenalty:ce,presencePenalty:le,maxRetries:be,maxSteps:he,maxTokens:xe,temperature:Ae,topK:De,topP:Me,seed:Pe,chatWithGenerate:Re,chatWithNetwork:Le,chatWithLegacyStream:Ee,providerOptions:Te,requireToolApproval:ze}=b,Ce={frequencyPenalty:ce,presencePenalty:le,maxRetries:be,temperature:Ae,topK:De,topP:Me,seed:Pe,maxTokens:xe,providerOptions:Te,maxSteps:he,requireToolApproval:ze},{send:Fe,cancel:tt}=eWr({agentId:t,requestContext:i,agentVersionId:c,threadId:r,modelSettingsArgs:Ce,model:f,chatWithNetwork:Le,chatWithGenerate:Re,maxSteps:he,isOMEnabled:U,tracingOptions:d?.tracingOptions,threadSignalsUnsupportedRef:y,isRunningStream:E,sendMessage:_,cancelRun:T,setMessages:I,setStreamErrors:p,refreshThreadList:s,refreshWorkingMemory:V,handleObservationStart:re,handleProgressUpdate:ae,refreshObservationalMemory:X,handleActivation:ne,resetObservationalMemoryStreamState:se,signalTimelineRefresh:te}),Ge=l==="v2"||l==="v3",ge=g.useRef(new Map),Se=g.useMemo(()=>UHr(k,ge.current),[k]),de=g.useMemo(()=>[...k.filter(_e=>_e.content?.metadata?.status!=="error"),...h].map(_e=>HHr(_e,Se)),[k,h,Se]),ke=E||N,fe=aWr({isSupportedModel:Ge,threadSignalsEnabled:x&&(!Re&&!Le&&!Ee),threadId:r,threadSignalsUnsupported:m}),ye=g.useMemo(()=>({messages:de}),[de]),je=g.useMemo(()=>({isRunning:ke,cancelRun:tt,canSendWhileStreaming:fe}),[ke,tt,fe]),$e=g.useMemo(()=>({send:Fe}),[Fe]),He=g.useMemo(()=>({tasks:C}),[C]),vt=g.useMemo(()=>({agentId:t,agentVersionId:c,requestContext:i}),[t,c,i]);return o.jsx(_Lt.Provider,{value:vt,children:o.jsx(kLt.Provider,{value:je,children:o.jsx(SLt.Provider,{value:ye,children:o.jsx(CLt.Provider,{value:He,children:o.jsx(OLt.Provider,{value:$e,children:o.jsx(QLt,{approveToolcall:A,declineToolcall:P,approveToolcallGenerate:L,declineToolcallGenerate:D,approveNetworkToolcall:H,declineNetworkToolcall:q,isRunning:E,toolCallApprovals:B,networkToolCallApprovals:z,children:e})})})})})})}function YLt({children:e}){const t=g.useRef(!1);return g.useEffect(()=>{t.current=!0},[]),o.jsx(g3t,{value:t,children:e})}function gie({children:e,className:t}){const n=y3t();return o.jsx("div",{className:K(n,t),children:o.jsx(YLt,{children:e})})}function oWr(e){const t=g.useRef(null);return g.useEffect(()=>{const n=t.current;if(!n||!e)return;let r,s=0,a=0;const i=()=>{r=void 0;const c=n.getBoundingClientRect(),u=Math.atan2(a-(c.top+c.height/2),s-(c.left+c.width/2));n.style.setProperty("--composer-ring-angle",`${u*180/Math.PI+90}deg`)},l=c=>{s=c.clientX,a=c.clientY,r??=requestAnimationFrame(i)};return window.addEventListener("pointermove",l,{passive:!0}),()=>{window.removeEventListener("pointermove",l),r!==void 0&&cancelAnimationFrame(r)}},[e]),t}const KLt=g.forwardRef(({children:e,...t},n)=>o.jsx("form",{ref:n,"data-slot":"composer",...t,children:e}));KLt.displayName="Composer";const XLt=g.forwardRef(({children:e,className:t,sendingPulseKey:n=0,...r},s)=>o.jsxs("div",{ref:s,"data-slot":"composer-box",className:K("@container relative mx-auto mt-auto w-full max-w-3xl overflow-hidden rounded-[22px] border border-border2/40 bg-surface3 transition-colors duration-normal focus-within:border-border2",t),...r,children:[o.jsx(lWr,{pulseKey:n}),o.jsx("div",{className:"relative z-10",children:e})]}));XLt.displayName="ComposerBox";const JLt=({busy:e=!1,className:t,...n})=>{const r=oWr(!e);return o.jsx("div",{ref:r,"data-slot":"composer-ring","data-busy":e?"true":"false",className:K("composer-ring relative mx-auto w-full max-w-3xl rounded-[23px] p-px",t),...n})};JLt.displayName="ComposerRing";const e5t=g.forwardRef(({className:e,...t},n)=>o.jsx("div",{ref:n,role:"region","data-slot":"composer-attachments",className:K("mx-auto w-full max-w-3xl pb-2",e),...t}));e5t.displayName="ComposerAttachments";const t5t=g.forwardRef(({className:e,maxHeight:t="212px",...n},r)=>o.jsx(Nr,{maxHeight:t,children:o.jsx("textarea",{ref:r,"data-slot":"composer-input",className:K("min-h-17 field-sizing-content w-full resize-none overflow-hidden bg-transparent px-3 pt-3 pb-2 text-ui-lg leading-ui-lg text-neutral6 outline-hidden placeholder:text-neutral3 focus:outline-hidden disabled:cursor-not-allowed disabled:opacity-50",e),...n})}));t5t.displayName="ComposerInput";const n5t=g.forwardRef(({className:e,...t},n)=>o.jsx("div",{ref:n,role:"region","data-slot":"composer-actions",className:K("flex flex-wrap-reverse items-center justify-between gap-2 px-1.5 pb-1.5",e),...t}));n5t.displayName="ComposerActions";const vie=({className:e})=>o.jsxs("div",{className:K("flex size-full flex-col -space-y-3",e),children:[o.jsx("div",{className:"bg-accent1 w-full flex-1 blur-xl"}),o.jsx("div",{className:"bg-accent1Dark w-full flex-1 blur-xl"}),o.jsx("div",{className:"bg-accent1 w-full flex-1 blur-xl"}),o.jsx("div",{className:"bg-accent1Darker w-full flex-1 blur-xl"})]}),lWr=({pulseKey:e})=>e===0?null:o.jsxs("div",{"aria-hidden":"true","data-slot":"composer-sending-pulse",className:"composer-sending pointer-events-none absolute top-0 left-[-10%] z-0 flex h-10 w-[120%] transform-gpu",children:[o.jsx(vie,{}),o.jsx(vie,{className:"-translate-y-2"}),o.jsx(vie,{})]},e),wXe={start:!1,end:!1},SXe={currentAnchorId:void 0,visibleMessageIds:[]},cWr=8,uWr=0,dWr=64,fWr=160,hWr=160,SG=g.createContext(null),r5t=g.createContext(null),s5t=g.createContext(null),a5t=(e,t)=>{const n=g.useContext(e);if(!n)throw new Error(`${t} must be used within MessageScrollerProvider.`);return n},kG=e=>a5t(SG,e),pWr=e=>a5t(r5t,e),DT=.5,mWr=e=>{if(!e)return{start:0,end:0};const t=window.getComputedStyle(e);return{start:Number.parseFloat(t.paddingBlockStart||t.paddingTop)||0,end:Number.parseFloat(t.paddingBlockEnd||t.paddingBottom)||0}},i5t=e=>Math.max(0,e.scrollHeight-e.clientHeight),Sxe=(e,t)=>{const n=e.getBoundingClientRect(),r=t.getBoundingClientRect();return n.top-r.top+t.scrollTop},kXe=({align:e,contentElement:t,element:n,scrollMargin:r,viewportElement:s})=>{const a=mWr(t),i=Sxe(n,s),l=n.getBoundingClientRect().height,c=Math.max(0,s.clientHeight-a.start-a.end);if(e==="center")return i-a.start-(c-l)/2-r;if(e==="end")return i-s.clientHeight+l+a.end+r;if(e==="nearest"){const u=i+l,d=s.scrollTop+a.start,f=s.scrollTop+s.clientHeight-a.end;return i>=d&&u<=f?s.scrollTop:i<d?i-a.start-r:u-s.clientHeight+a.end+r}return i-a.start-r},gWr=({contentElement:e,items:t,viewportElement:n})=>{const r=i5t(n),s=t.at(-1)?.[1].element;if(!s||!e)return r;const a=Sxe(e,n)+e.getBoundingClientRect().height,i=Math.max(0,n.scrollHeight-a),l=Sxe(s,n)+s.getBoundingClientRect().height;return Math.min(r,Math.max(0,l+i-n.clientHeight))},vWr=({fallbackAnchorId:e,items:t,scrollMargin:n,scrollPreviousItemPeek:r,visibleMessageIds:s,viewportElement:a})=>{const i=a.getBoundingClientRect().top+n+r,l=t.filter(([,u])=>u.scrollAnchor);let c;for(const[u,d]of l)d.element.getBoundingClientRect().top<=i+DT&&(c=u);return c||(l.find(([u])=>s.has(u))?.[0]??e)},yWr=240,bWr=220,xWr="cubic-bezier(0.33, 1, 0.68, 1)";function OXe(e){if(typeof DOMMatrixReadOnly>"u")return 0;const{transform:t}=getComputedStyle(e);return!t||t==="none"?0:new DOMMatrixReadOnly(t).m42}const Xq=new WeakMap;function CXe(e){Xq.get(e)?.abort(),Xq.delete(e),e.style.transition="",e.style.transform=""}function wWr(){return typeof window>"u"||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function SWr(e,t){if(!e||t<=0||wWr())return;const n=OXe(e)+t;if(n>yWr){CXe(e);return}e.style.transition="none",e.style.transform=`translateY(${n}px)`,e.offsetHeight,e.style.transition=`transform ${bWr}ms ${xWr}`,e.style.transform="translateY(0)",Xq.get(e)?.abort();const r=new AbortController;Xq.set(e,r);const s=a=>{a.target===e&&OXe(e)===0&&CXe(e)};e.addEventListener("transitionend",s,{signal:r.signal}),e.addEventListener("transitioncancel",s,{signal:r.signal})}const kWr=560,OWr=240,CWr=e=>1-(1-e)**5;function _Wr(e,t,n){const s=typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches?0:kWr,a=performance.now(),i=e.scrollTop;let l=i,c=0,u=!1;const d=h=>{u=!0,n(h)},f=()=>{if(Math.abs(e.scrollTop-l)>1)return d("interrupted");const h=t();if(h===void 0)return d("expired");const p=performance.now()-a,m=s===0?1:Math.min(1,p/s);if(e.scrollTop=i+(h-i)*CWr(m),l=e.scrollTop,m===1&&Math.abs(l-h)<=DT)return d("arrived");if(p>=s+OWr)return d("expired");c=window.requestAnimationFrame(f)};return c=window.requestAnimationFrame(f),{cancel:()=>{u||(u=!0,window.cancelAnimationFrame(c))}}}const OG=(...e)=>t=>{e.forEach(n=>{if(n){if(typeof n=="function"){n(t);return}n.current=t}})},EWr=(e,t)=>e.start===t.start&&e.end===t.end,TWr=(e,t)=>e.currentAnchorId===t.currentAnchorId&&e.visibleMessageIds.length===t.visibleMessageIds.length&&e.visibleMessageIds.every((n,r)=>n===t.visibleMessageIds[r]),jWr=e=>e.sort(([,t],[,n])=>{const r=t.element.compareDocumentPosition(n.element);return r&Node.DOCUMENT_POSITION_FOLLOWING?-1:r&Node.DOCUMENT_POSITION_PRECEDING?1:0}),bP=(e,t,n)=>{if(typeof e.scrollTo=="function"){e.scrollTo({top:t,behavior:n});return}e.scrollTop=t},xP=e=>{if(typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(e);return}window.setTimeout(e,0)};function NWr({autoScroll:e=!1,children:t,defaultScrollPosition:n="end",onReachStart:r,preserveScrollOnPrepend:s=!1,reachStartThreshold:a=fWr,scrollEdgeThreshold:i=cWr,scrollMargin:l=uWr,scrollPreviousItemPeek:c=dWr}){const u=g.useRef(null);u.current??=new Map;const d=u.current,f=g.useRef(null),h=g.useRef(null);h.current??=new Set;const p=h.current,[m,v]=g.useState(0),[y,b]=g.useState(null),[x,w]=g.useState(null),[k,C]=g.useState(null),_=g.useRef(!1),T=g.useRef(!1),E=g.useRef(!1),N=g.useRef(null);N.current??=new Set;const I=N.current,A=g.useRef(null);A.current??=new WeakSet;const P=A.current,L=g.useRef(!1),[D,B]=g.useState(wXe),[H,q]=g.useState(SXe),z=g.useRef(!0),V=g.useRef(!0),M=g.useRef(null),G=g.useRef(null),F=g.useRef(0),R=g.useRef(!1),U=g.useRef(!1),Z=g.useRef(null),Y=g.useRef(void 0),te=g.useRef(r);g.useEffect(()=>{te.current=r},[r]);const J=g.useCallback(Ce=>{const Fe=[Ce.start&&"start",Ce.end&&"end"].filter(Boolean).join(" ");for(const tt of[y,x])tt&&(Fe?tt.setAttribute("data-scrollable",Fe):tt.removeAttribute("data-scrollable"));B(tt=>EWr(tt,Ce)?tt:Ce)},[y,x]),ee=g.useCallback(Ce=>{q(Fe=>TWr(Fe,Ce)?Fe:Ce)},[]),re=g.useCallback(()=>(f.current??=jWr(Array.from(d.entries())),f.current),[d]),ae=g.useCallback(()=>x?gWr({contentElement:k,items:re(),viewportElement:x}):0,[k,re,x]),X=g.useCallback(Ce=>{const Fe=d.get(Ce);if(!(!Fe||!x))return Math.max(0,kXe({align:"start",contentElement:k,element:Fe.element,scrollMargin:l,viewportElement:x}))},[k,d,l,x]),ne=g.useCallback(Ce=>{const Fe=X(Ce);return Fe===void 0||!x?Fe:Math.min(Fe,i5t(x))},[X,x]),se=g.useCallback(()=>{G.current?.cancel(),G.current=null},[]),ce=g.useCallback(({fromScroll:Ce=!1}={})=>{if(!x){z.current=!0,J(wXe);return}const{scrollTop:Fe}=x,tt=ae()-Fe,Ge=Fe<F.current;z.current=tt<hWr,M.current==="end"&&(Ge||z.current)&&(M.current=null),F.current=Fe,Ce&&M.current===null&&(Ge||z.current)&&(V.current=z.current),J({start:Fe>i,end:tt>i&&!(e&&V.current)})},[e,ae,J,i,x]),le=g.useCallback(()=>re().filter(([,Ce])=>Ce.scrollAnchor).at(-1)?.[0],[re]),be=g.useCallback(()=>{const Ce=re(),Fe=le()??Ce.at(-1)?.[0];if(Ce.length===0){ee(SXe);return}if(!x){ee({currentAnchorId:Fe,visibleMessageIds:Fe?[Fe]:[]});return}const tt=x.getBoundingClientRect(),Ge=new Set;if(typeof IntersectionObserver>"u"){const Se=tt.top+l+c;Ce.forEach(([de,ke])=>{const Ne=ke.element.getBoundingClientRect();Ne.bottom>Se&&Ne.top<tt.bottom&&Ge.add(de)})}else p.forEach(Se=>Ge.add(Se));const ge=Ce.flatMap(([Se])=>Ge.has(Se)?[Se]:[]);ee({currentAnchorId:vWr({fallbackAnchorId:Fe,items:Ce,scrollMargin:l,scrollPreviousItemPeek:c,visibleMessageIds:Ge,viewportElement:x}),visibleMessageIds:ge.length>0?ge:Fe?[Fe]:[]})},[le,re,p,ee,l,c,x]),he=g.useCallback(()=>{ce(),be()},[ce,be]),xe=g.useCallback(()=>{const Ce=!!(x&&x.scrollHeight>x.clientHeight);if(ce({fromScroll:!0}),be(),!!x&&(z.current&&Ce&&(R.current=!0),!!R.current&&Ce)){if(x.scrollTop>a){U.current=!1;return}U.current||te.current&&(U.current=!0,s&&(Z.current={scrollHeight:x.scrollHeight,scrollTop:x.scrollTop}),te.current())}},[s,a,ce,be,x]),Ae=g.useCallback((Ce,{align:Fe="start",behavior:tt="auto",scrollMargin:Ge=l}={})=>{if(!x||!k?.contains(Ce))return!1;const ge=Math.max(0,kXe({align:Fe,contentElement:k,element:Ce,scrollMargin:Ge,viewportElement:x}));return Math.abs(x.scrollTop-ge)<=DT?(bP(x,ge,"auto"),he(),!0):(bP(x,ge,tt),xP(he),!0)},[k,l,he,x]),De=g.useCallback(({behavior:Ce="auto"}={})=>x?(se(),M.current=null,bP(x,0,Ce),xP(he),!0):!1,[se,he,x]),Me=g.useCallback(({behavior:Ce="auto"}={})=>x?(se(),V.current=!0,M.current=Ce==="smooth"?"end":null,bP(x,ae(),Ce),he(),xP(he),!0):!1,[se,ae,he,x]),Pe=g.useCallback((Ce,Fe)=>{const tt=d.get(Ce);return tt?Ae(tt.element,Fe):!1},[d,Ae]),Re=g.useCallback(()=>{const Ce=M.current;if(!(Ce!==null&&Ce!=="end")&&e&&_.current&&V.current&&x){const tt=ae()-x.scrollTop;if(tt>DT){const Ge=Ce==="end";bP(x,ae(),Ge?"smooth":"auto"),Ge||SWr(k,tt)}}he()},[e,k,ae,he,x]),Le=g.useCallback((Ce,Fe,tt)=>(d.set(Ce,{element:Fe,scrollAnchor:tt}),f.current=null,v(Ge=>Ge+1),()=>{d.get(Ce)?.element===Fe&&(d.delete(Ce),p.delete(Ce),f.current=null,v(ge=>ge+1))}),[p,d]);g.useEffect(()=>{if(!k||!x||typeof IntersectionObserver>"u"){be();return}const Ce=new Map;for(const[tt,Ge]of d)Ce.set(Ge.element,tt);const Fe=new IntersectionObserver(tt=>{for(const Ge of tt){const ge=Ce.get(Ge.target);ge&&(Ge.isIntersecting?p.add(ge):p.delete(ge))}be()},{root:x,rootMargin:`${-(l+c)}px 0px 0px 0px`,threshold:[0,.01,.5,1]});for(const[,tt]of d)Fe.observe(tt.element);return be(),()=>Fe.disconnect()},[k,p,d,m,l,c,be,x]),g.useEffect(()=>{if(!x||typeof ResizeObserver>"u")return;const Ce=new ResizeObserver(he);return Ce.observe(x),()=>Ce.disconnect()},[he,x]),g.useLayoutEffect(()=>{ce(),be()},[m,ce,be]),g.useLayoutEffect(()=>{if(_.current||!x)return;if(d.size===0){T.current=!0;return}const Ce=()=>{const tt=le();V.current=!1;let Ge=!1;if(n==="start"?Ge=De({behavior:"auto"}):n==="last-anchor"?Ge=tt?Pe(tt,{align:"start",behavior:"auto"}):Me({behavior:"auto"}):Ge=Me({behavior:"auto"}),!!Ge){_.current=!0;for(const[ge,Se]of re())Se.scrollAnchor&&(I.add(ge),P.add(Se.element));L.current=!0}};if(!T.current){Ce();return}if(E.current)return;E.current=!0;let Fe=!1;return xP(()=>{xP(()=>{E.current=!1,!Fe&&!_.current&&Ce()})}),()=>{Fe=!0,E.current=!1}},[n,le,re,d,m,Me,Pe,De,P,I,x]),g.useLayoutEffect(()=>{const Ce=le(),Fe=Ce?d.get(Ce):void 0,tt=L.current&&Ce!==void 0&&Fe!==void 0&&!I.has(Ce)&&!P.has(Fe.element);for(const[Ge,ge]of re())ge.scrollAnchor&&(I.add(Ge),P.add(ge.element));if(L.current=_.current,tt&&Ce){e&&(V.current=!0),se();const Ge=x?X(Ce):void 0;Ge===void 0||!x||Math.abs(Ge-x.scrollTop)<=DT?M.current=null:(M.current={anchorId:Ce},G.current=_Wr(x,()=>ne(Ce),ge=>{G.current=null,M.current=null,ge==="interrupted"&&(V.current=z.current),he()})),he();return}!e||!_.current||!V.current||M.current!==null&&M.current!=="end"||x&&ae()-x.scrollTop<=DT||Me({behavior:M.current==="end"?"smooth":"auto"})},[X,e,se,ae,le,re,d,m,ne,Me,P,I,he,x]),g.useEffect(()=>()=>{se(),M.current=null},[se,x]),g.useLayoutEffect(()=>{const Ce=Y.current,Fe=k?.querySelector('[data-slot="message-scroller-item"]')?.dataset.messageId;Y.current=Fe;const tt=Z.current;if(Z.current=null,!tt||!x||Fe===Ce)return;U.current=!1;const Ge=x.scrollHeight-tt.scrollHeight;Ge>0&&(x.scrollTop=tt.scrollTop+Ge)},[k,m,x]);const Ee=g.useMemo(()=>({notifyContentResize:Re,notifyScroll:xe,registerItem:Le,scrollToEnd:Me,scrollToMessage:Pe,scrollToStart:De,setContentElement:C,setRootElement:b,setViewportElement:w,syncAfterScroll:he}),[Re,xe,Le,Me,Pe,De,he]),Te=g.useMemo(()=>({end:D.end,start:D.start}),[D.end,D.start]),ze=g.useMemo(()=>({currentAnchorId:H.currentAnchorId,visibleMessageIds:H.visibleMessageIds}),[H.currentAnchorId,H.visibleMessageIds]);return o.jsx(SG.Provider,{value:Ee,children:o.jsx(r5t.Provider,{value:Te,children:o.jsx(s5t.Provider,{value:ze,children:t})})})}const o5t=g.forwardRef(({className:e,...t},n)=>{const{setRootElement:r}=kG("MessageScroller");return o.jsx("div",{ref:OG(r,n),"data-slot":"message-scroller",className:K("group/message-scroller relative flex size-full min-h-0 flex-col overflow-hidden",e),...t})});o5t.displayName="MessageScroller";const l5t=g.forwardRef(({className:e,onScroll:t,role:n,tabIndex:r,...s},a)=>{const{setViewportElement:i,notifyScroll:l}=kG("MessageScrollerViewport"),c=g.useMemo(()=>OG(i,a),[a,i]);return o.jsx("div",{ref:c,role:n??"region",tabIndex:r??0,"data-slot":"message-scroller-viewport",className:K("[container-type:size] size-full min-h-0 min-w-0 overflow-y-auto overscroll-contain","data-autoscrolling:scrollbar-thumb-transparent data-autoscrolling:scrollbar-track-transparent",e),onScroll:u=>{l(),t?.(u)},...s})});l5t.displayName="MessageScrollerViewport";const c5t=g.forwardRef(({children:e,className:t,spacerClassName:n,role:r,"aria-relevant":s="additions",...a},i)=>{const{setContentElement:l,notifyContentResize:c,syncAfterScroll:u}=kG("MessageScrollerContent"),[d,f]=g.useState(null),h=g.useMemo(()=>OG(l,f,i),[i,l]);return g.useLayoutEffect(()=>{u()},[u]),g.useEffect(()=>{if(!d||typeof MutationObserver>"u")return;const p=new MutationObserver(c);return p.observe(d,{childList:!0,subtree:!1}),()=>p.disconnect()},[d,c]),g.useEffect(()=>{if(!d||typeof ResizeObserver>"u")return;const p=new ResizeObserver(c);return p.observe(d),()=>p.disconnect()},[d,c]),o.jsxs("div",{ref:h,role:r??"log","aria-relevant":s,"data-slot":"message-scroller-content",className:K("flex h-max min-h-full flex-col gap-6",t),...a,children:[e,o.jsx("div",{"aria-hidden":"true","data-message-scroller-spacer":"",hidden:!0,className:n})]})});c5t.displayName="MessageScrollerContent";const u5t=g.forwardRef(({className:e,messageId:t,scrollAnchor:n=!1,...r},s)=>{const a=g.useContext(SG)?.registerItem,i=g.useRef(void 0),l=g.useCallback(c=>{i.current?.(),i.current=void 0,OG(s)(c),!(!c||!t||!a)&&(i.current=a(t,c,n))},[t,s,a,n]);return o.jsx("div",{ref:l,"data-slot":"message-scroller-item","data-message-id":t,"data-scroll-anchor":n?"true":"false",className:K("min-w-0 shrink-0 [contain-intrinsic-size:auto_10rem] [content-visibility:auto]",e),...r})});u5t.displayName="MessageScrollerItem";const d5t=g.forwardRef(({behavior:e="smooth",direction:t="end",className:n,children:r,onClick:s,tabIndex:a,type:i="button",...l},c)=>{const{scrollToEnd:u,scrollToStart:d}=kG("MessageScrollerButton"),{start:f,end:h}=pWr("MessageScrollerButton"),p=t==="start"?f:h;return o.jsx("button",{ref:c,type:i,...l,"data-slot":"message-scroller-button","data-active":p?"true":"false","data-direction":t,tabIndex:p?a:-1,className:K("absolute inset-s-1/2 inline-flex min-h-5 min-w-7 -translate-x-1/2 items-center justify-center rounded-full border border-border1 bg-surface3 text-neutral6 shadow-[0_1px_2px_-1px_oklch(0%_0_0deg/10%),0_8px_20px_-12px_oklch(0%_0_0deg/25%)] transition-[translate,scale,opacity] duration-200 hover:bg-surface4 data-[active=false]:pointer-events-none data-[active=false]:scale-95 data-[active=false]:opacity-0 data-[active=false]:duration-400 data-[active=false]:ease-[cubic-bezier(0.7,0,0.84,0)] data-[active=true]:translate-y-0 data-[active=true]:scale-100 data-[active=true]:opacity-100 data-[active=true]:ease-[cubic-bezier(0.23,1,0.32,1)] data-[direction=end]:bottom-4 data-[direction=end]:data-[active=false]:translate-y-full data-[direction=start]:top-4 data-[direction=start]:data-[active=false]:-translate-y-full rtl:translate-x-1/2 data-[direction=start]:[&_svg]:rotate-180",n),onClick:m=>{p&&(s?.(m),!m.defaultPrevented&&(m.currentTarget.blur(),t==="start"?d({behavior:e}):u({behavior:e})))},children:r??o.jsxs(o.Fragment,{children:[o.jsx(CV,{className:"size-4","aria-hidden":!0}),o.jsx("span",{className:"sr-only",children:t==="end"?"Scroll to end":"Scroll to start"})]})})});d5t.displayName="MessageScrollerButton";const IWr=()=>{const e=g.useContext(SG);return g.useMemo(()=>{if(e)return{scrollToEnd:e.scrollToEnd,scrollToMessage:e.scrollToMessage,scrollToStart:e.scrollToStart}},[e])},AWr=()=>{const e=g.useContext(s5t);return g.useMemo(()=>e?{currentAnchorId:e.currentAnchorId,visibleMessageIds:e.visibleMessageIds}:void 0,[e])},CG=typeof window>"u"?g.useEffect:g.useLayoutEffect,RWr=e=>{const t=e.getBoundingClientRect().height,n=t>0?t:e.scrollHeight;return Math.ceil(n)};function PWr(){const[e,t]=g.useState(null),[n,r]=g.useState(null),s=g.useRef(null),a=g.useCallback(()=>{if(!e)return null;const l=RWr(e);return r(c=>c===l?c:l),l},[e]);CG(()=>{if(!e||(a(),typeof ResizeObserver>"u"))return;const l=()=>{s.current!==null&&window.cancelAnimationFrame(s.current),s.current=window.requestAnimationFrame(()=>{s.current=null,a()})},c=new ResizeObserver(l);return c.observe(e),()=>{c.disconnect(),s.current!==null&&(window.cancelAnimationFrame(s.current),s.current=null)}},[e,a]);const i=g.useMemo(()=>n===null?{}:{height:n},[n]);return{ref:t,height:n,heightStyle:i,measure:a}}const $Wr=360,_Xe=$Wr+80,EXe={currentTurn:void 0,previousTurn:void 0,index:null,phase:"hidden",top:0,transitionKey:0};function f5t({turns:e,currentAnchorId:t,visibleMessageIds:n,label:r="Conversation timeline",className:s,maxHeight:a="calc(100dvh - 12rem)",scrollAreaClassName:i,onSelect:l}){const c=g.useRef(null),u=g.useId(),[d,f]=g.useState(EXe),h=IWr(),p=AWr(),m=e.at(-1)?.messageId,v=t??p?.currentAnchorId??m,y=n??p?.visibleMessageIds??(v?[v]:[]),b=new Set(y),w=d.phase==="entering"||d.phase==="visible"?d.index:null,k=g.useCallback(T=>{if(l){l(T);return}h?.scrollToMessage(T.messageId,{behavior:"smooth",align:"start"})},[h,l]),C=(T,E)=>{const N=c.current?.getBoundingClientRect().top??0,I=E.getBoundingClientRect(),A=e[T];A&&f(P=>{const L=I.top+I.height/2-N;if(P.index===T&&P.phase!=="hidden"&&P.phase!=="exiting")return{...P,top:L};const D=P.currentTurn&&P.currentTurn.key!==A.key&&P.phase!=="hidden"?P.currentTurn:void 0;return{currentTurn:A,previousTurn:D,index:T,phase:"entering",top:L,transitionKey:P.transitionKey+1}})},_=()=>{f(T=>!T.currentTurn||T.phase==="hidden"||T.phase==="exiting"?{...T,index:null}:{...T,index:null,previousTurn:void 0,phase:"exiting",transitionKey:T.transitionKey+1})};return g.useEffect(()=>{if(d.phase!=="entering")return;const T=window.requestAnimationFrame??window.setTimeout,E=window.cancelAnimationFrame??window.clearTimeout;let N;const I=T(()=>{N=T(()=>{f(A=>A.transitionKey===d.transitionKey&&A.phase==="entering"?{...A,phase:"visible"}:A)})});return()=>{E(I),N!==void 0&&E(N)}},[d.phase,d.transitionKey]),g.useEffect(()=>{if(d.phase!=="visible"||!d.previousTurn)return;const T=window.setTimeout(()=>{f(E=>E.transitionKey===d.transitionKey?{...E,previousTurn:void 0}:E)},_Xe);return()=>window.clearTimeout(T)},[d.phase,d.previousTurn,d.transitionKey]),g.useEffect(()=>{if(d.phase!=="exiting")return;const T=window.setTimeout(()=>{f(E=>E.transitionKey===d.transitionKey?EXe:E)},_Xe);return()=>window.clearTimeout(T)},[d.phase,d.transitionKey]),e.length===0?null:o.jsxs("nav",{ref:c,"aria-label":r,"data-testid":"thread-rail",className:K("relative w-8 py-2",s),onMouseLeave:_,onBlur:T=>{const E=T.relatedTarget;(!(E instanceof Node)||!T.currentTarget.contains(E))&&_()},children:[o.jsx(Nr,{"data-testid":"thread-rail-scroll-area",maxHeight:a,className:K("w-8",i),viewPortClassName:"pr-3",children:o.jsx("div",{className:"flex w-4 flex-col items-start gap-2 py-2",children:e.map((T,E)=>{const N=w===null?null:Math.abs(E-w),I=T.messageId===v,A=b.has(T.messageId),P=w===E;return o.jsx(LWr,{turn:T,index:E,distance:N,active:I,inView:A,previewId:P?u:void 0,onHoverChange:C,onSelect:k},T.key)})})}),d.currentTurn&&o.jsx(FWr,{id:u,currentTurn:d.currentTurn,previousTurn:d.previousTurn,phase:d.phase,top:d.top})]})}const MWr=e=>e===0?"w-4":e===1?"w-3":"w-2",DWr=({distance:e,active:t,inView:n})=>e===0||t?"bg-neutral6":n?"bg-neutral5":e===1?"bg-neutral4":"bg-neutral3/60";function LWr({turn:e,index:t,distance:n,active:r,inView:s,previewId:a,onHoverChange:i,onSelect:l}){const c=MWr(n),u=DWr({distance:n,active:r,inView:s});return o.jsx("div",{"data-in-view":s?"true":void 0,"data-active":r?"true":void 0,className:"group/thread-rail-item relative flex items-center",children:o.jsx("button",{type:"button","aria-label":`Jump to ${e.prompt}`,"aria-current":r?"location":void 0,"aria-describedby":a,"data-in-view":s?"true":void 0,"data-active":r?"true":void 0,onClick:()=>l(e),onMouseEnter:d=>i(t,d.currentTarget),onFocus:d=>i(t,d.currentTarget),className:K("relative block h-px cursor-pointer rounded-full transition-[width,background-color] duration-normal ease-out","before:absolute before:inset-x-0 before:-inset-y-1 before:content-['']","focus-visible:ring-2 focus-visible:ring-accent1/40 focus-visible:outline-hidden",c,u)})})}function FWr({id:e,currentTurn:t,previousTurn:n,phase:r,top:s}){const{ref:a,heightStyle:i,measure:l}=PWr(),c=r==="visible"||r==="entering"&&!!n,u="scale-95 opacity-0 blur-xs",d="scale-100 opacity-100 blur-none",f="absolute inset-x-0 top-0 h-full origin-left transition-[opacity,filter,scale] duration-150 ease-in-out will-change-[opacity,filter,scale] motion-reduce:scale-100 motion-reduce:blur-none motion-reduce:transition-none";return g.useLayoutEffect(()=>{l()},[t.key,r,l]),o.jsxs("div",{id:e,"data-testid":"thread-rail-preview","data-visible":c?"true":void 0,className:K("pointer-events-none absolute top-0 left-full z-30 ml-3 w-72 overflow-hidden rounded-xl border border-border1 bg-surface3 text-left shadow-dialog transition-[height,translate,opacity] duration-360 ease-out-custom will-change-[height,translate,opacity] motion-reduce:transition-none",c?"opacity-100":"opacity-0"),style:{...i,translate:`0 calc(${s}px - 50%)`},children:[o.jsx("div",{ref:a,"data-testid":"thread-rail-preview-sizer","aria-hidden":!0,className:"invisible",children:o.jsx(yie,{turn:t,className:"p-3.5"})}),o.jsx("div",{"data-testid":"thread-rail-preview-viewport",className:"absolute inset-0",children:o.jsxs("div",{className:"relative h-full",children:[n&&o.jsx("div",{"data-testid":"thread-rail-preview-previous","aria-hidden":!0,className:K(f,r==="entering"?d:u),children:o.jsx(yie,{turn:n,className:"p-3.5"})},n.key),o.jsx("div",{"data-testid":"thread-rail-preview-current",className:K(f,r==="visible"?d:u),children:o.jsx(yie,{turn:t,className:"p-3.5"})},t.key)]})})]})}function yie({turn:e,className:t,...n}){return o.jsxs("div",{className:t,...n,children:[o.jsx("div",{className:"text-ui-md leading-ui-md text-neutral6 truncate font-medium",children:e.prompt}),e.reply&&o.jsx("p",{className:"text-ui-sm leading-ui-sm text-neutral4 mt-1.5 line-clamp-3",children:e.reply}),(e.files.length>0||e.hiddenFileCount>0)&&o.jsxs("div",{className:"border-border1/60 mt-3 flex flex-wrap items-center gap-2 border-t pt-2.5",children:[e.files.map(r=>o.jsxs("span",{className:"text-ui-sm text-neutral4 inline-flex max-w-44 items-center gap-1.5 truncate",children:[o.jsx(Ll,{className:"size-3.5 shrink-0 opacity-70","aria-hidden":!0}),r]},r)),e.hiddenFileCount>0&&o.jsxs("span",{className:"text-ui-sm text-neutral4 font-medium",children:["+",e.hiddenFileCount]})]})]})}const TXe=120,zWr=2,BWr="clientMessageId",_G=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),kxe=e=>{const t=e.content.metadata,n=_G(t)?t[BWr]:void 0;return typeof n=="string"&&n.length>0?n:e.id},h5t=(e,t)=>{const n=e.replace(/\s+/g," ").trim();return n.length===0?t:n.length<=TXe?n:`${n.slice(0,TXe-3).trimEnd()}...`},p5t=e=>e.content.parts.flatMap(t=>!_G(t)||t.type!=="text"||typeof t.text!="string"?[]:[t.text]).join(`
514
+ `);return t!==-1&&t!==e.length-1}else{if(Array.isArray(e))return e.some(t=>pxe(t));if(e&&typeof e=="object")return Object.values(e).some(t=>pxe(t))}return!1}function Oqr({children:e,className:t}){return o.jsx(DEt,{render:o.jsx("div",{className:K("grid content-start gap-6 overflow-y-scroll p-6 pb-8 pl-9",t),children:e})})}function Cqr({children:e,className:t}){return o.jsx("div",{className:K("flex items-center justify-between pb-4",t),children:e})}function _qr({children:e,className:t,as:n="h1"}){const r=n;return o.jsx(r,{className:K("flex items-start gap-2 text-header-sm font-semibold text-neutral4","[&>svg]:mt-0.5 [&>svg]:size-[1.25em] [&>svg]:shrink-0 [&>svg]:opacity-70",{"text-header-sm":n==="h1","text-ui-lg":n==="h2"},t),children:e})}function Eqr({onNext:e,onPrevious:t,className:n}){const r=()=>{e?.()},s=()=>{t?.()};return o.jsx("div",{className:K("flex items-center gap-4","[&_svg]:size-[1.1em] [&_svg]:text-neutral3",n),children:(e||t)&&o.jsxs("div",{className:K("flex items-baseline gap-4"),children:[o.jsxs(ie,{onClick:s,disabled:!t,children:["Previous",o.jsx(K1,{})]}),o.jsxs(ie,{onClick:r,disabled:!e,children:["Next",o.jsx(CV,{})]})]})})}function Tqr({dialogTitle:e,dialogDescription:t,isOpen:n,onClose:r,children:s,variant:a="default",level:i=1,className:l}){const c=a==="confirmation",[u,d]=g.useState(null);return o.jsx(RI,{side:"right",open:n,onOpenChange:f=>{f||r?.()},children:o.jsxs(dCe,{children:[!c&&o.jsx(IW,{className:"backdrop-blur-sm"}),o.jsx(AW,{className:c?"pointer-events-none":void 0,children:o.jsxs(RW,{className:K("max-w-none overflow-visible rounded-none border-y-0 border-r-0 border-l border-border2 bg-surface2",{"w-[75vw] 2xl:w-[65vw] 4xl:w-[55vw]":i===1,"w-[70vw] 2xl:w-[59vw] 4xl:w-[48vw]":i===2,"w-[65vw] 2xl:w-[53vw] 4xl:w-[41vw]":i===3,"pointer-events-auto bg-surface2/70 backdrop-blur-sm shadow-none":c},l),children:[o.jsx(PI,{className:"sr-only",children:e}),o.jsx(h4,{className:"sr-only",children:t}),!c&&o.jsx(uCe,{render:o.jsx("button",{type:"button",className:K("absolute top-0 -left-14 flex size-14 appearance-none items-center justify-center rounded-bl-lg border-b border-l border-border2 bg-surface2 text-neutral3",Yr.all,"hover:bg-surface4 hover:text-neutral5"),"aria-label":"Close",children:o.jsx(Ect,{})})}),o.jsx(DEt,{render:o.jsx("div",{ref:d,className:"absolute"})}),o.jsx(iPn,{container:u,children:o.jsx("div",{className:K("grid h-full",{"grid-rows-[auto_1fr]":!c}),children:s})})]})})]})})}function jqr({children:e,className:t}){return o.jsx("div",{className:K("text-ui-md text-neutral5 relative flex h-14 items-center gap-4 pl-6",'[&:after]:absolute [&:after]:inset-x-6 [&:after]:bottom-0 [&:after]:border-b [&:after]:border-border1 [&:after]:content-[""]',t),children:e})}const Ca=Object.assign(Tqr,{Top:jqr,Header:Cqr,Heading:_qr,Content:Oqr,CodeSection:kqr,Nav:Eqr}),wi=()=>{const e=Ye(),t=Ar(),n=Sn({mutationFn:v=>e.createDataset(v),onSuccess:()=>{t.invalidateQueries({queryKey:["datasets"]})}}),r=Sn({mutationFn:v=>e.updateDataset(v),onSuccess:(v,y)=>{t.invalidateQueries({queryKey:["datasets"]}),t.invalidateQueries({queryKey:["dataset",y.datasetId]})}}),s=Sn({mutationFn:v=>e.deleteDataset(v),onSuccess:()=>{t.invalidateQueries({queryKey:["datasets"]})}}),a=Sn({mutationFn:v=>e.addDatasetItem(v),onSuccess:(v,y)=>{t.invalidateQueries({queryKey:["dataset-items",y.datasetId]}),t.invalidateQueries({queryKey:["dataset",y.datasetId]}),t.invalidateQueries({queryKey:["dataset-versions",y.datasetId]})}}),i=Sn({mutationFn:v=>e.updateDatasetItem(v),onSuccess:(v,y)=>{t.invalidateQueries({queryKey:["dataset-items",y.datasetId]}),t.invalidateQueries({queryKey:["dataset-item",y.datasetId,y.itemId]}),t.invalidateQueries({queryKey:["dataset-item-versions",y.datasetId,y.itemId]}),t.invalidateQueries({queryKey:["dataset-versions",y.datasetId]})}}),l=Sn({mutationFn:({datasetId:v,itemId:y})=>e.deleteDatasetItem(v,y),onSuccess:(v,y)=>{t.invalidateQueries({queryKey:["dataset-items",y.datasetId]}),t.invalidateQueries({queryKey:["dataset",y.datasetId]}),t.invalidateQueries({queryKey:["dataset-versions",y.datasetId]})}}),c=Sn({mutationFn:v=>e.batchInsertDatasetItems(v),onSuccess:(v,y)=>{t.invalidateQueries({queryKey:["dataset-items",y.datasetId]}),t.invalidateQueries({queryKey:["dataset",y.datasetId]}),t.invalidateQueries({queryKey:["dataset-versions",y.datasetId]})}}),u=Sn({mutationFn:v=>e.batchDeleteDatasetItems(v),onSuccess:(v,y)=>{t.invalidateQueries({queryKey:["dataset-items",y.datasetId]}),t.invalidateQueries({queryKey:["dataset",y.datasetId]}),t.invalidateQueries({queryKey:["dataset-versions",y.datasetId]})}}),d=Sn({mutationFn:async({datasetId:v,itemIds:y})=>e.batchDeleteDatasetItems({datasetId:v,itemIds:y}),onSuccess:(v,y)=>{t.invalidateQueries({queryKey:["dataset-items",y.datasetId]}),t.invalidateQueries({queryKey:["dataset",y.datasetId]}),t.invalidateQueries({queryKey:["dataset-versions",y.datasetId]})}}),f=Sn({mutationFn:v=>e.generateDatasetItems(v)}),h=Sn({mutationFn:v=>e.triggerDatasetExperiment(v),onSuccess:(v,y)=>{t.invalidateQueries({queryKey:["dataset-experiments",y.datasetId]})}}),p=Sn({mutationFn:v=>e.updateDatasetExperiment(v),onSuccess:(v,y)=>{t.invalidateQueries({queryKey:["experiments"]}),t.invalidateQueries({queryKey:["dataset-experiments",y.datasetId]}),t.invalidateQueries({queryKey:["dataset-experiment",y.datasetId,y.experimentId]})}}),m=Sn({mutationFn:v=>e.updateDatasetExperimentResult(v),onSuccess:(v,y)=>{t.invalidateQueries({queryKey:["experiment-results",y.experimentId]}),t.invalidateQueries({queryKey:["dataset-experiment-results"]}),t.invalidateQueries({queryKey:["review-items"]}),t.invalidateQueries({queryKey:["dataset-review-items"]}),t.invalidateQueries({queryKey:["dataset-completed-items"]}),t.invalidateQueries({queryKey:["experiment-review-summary"]})}});return{createDataset:n,updateDataset:r,deleteDataset:s,addItem:a,updateItem:i,deleteItem:l,deleteItems:d,batchInsertItems:c,batchDeleteItems:u,generateItems:f,triggerExperiment:h,updateExperiment:p,updateExperimentResult:m}};function K4t({initialInput:e,initialGroundTruth:t,initialTrajectory:n,trajectoryLoading:r,initialToolMocks:s,breadcrumb:a,isOpen:i,onClose:l,level:c=2,source:u}){const[d,f]=g.useState(""),[h,p]=g.useState(""),[m,v]=g.useState(""),[y,b]=g.useState(""),[x,w]=g.useState(""),{data:k,isLoading:C}=Xg(),{addItem:_}=wi(),T=k?.datasets??[],E=g.useRef(!1),N=g.useRef(!1),I=g.useRef(!1),A=g.useRef(!1);g.useEffect(()=>{i&&!E.current&&(p(e),v(t),b(n??""),w(s??""),N.current=!!n,I.current=e!=="{}",A.current=!!t),E.current=i,i||(N.current=!1,I.current=!1,A.current=!1)},[i,e,t,n,s]);const P=z=>{I.current=!0,p(z)},L=z=>{A.current=!0,v(z)},D=z=>{N.current=!0,b(z)},B=z=>{w(z)};g.useEffect(()=>{i&&e!=="{}"&&!I.current&&(p(e),I.current=!0)},[i,e]),g.useEffect(()=>{i&&t&&!A.current&&(v(t),A.current=!0)},[i,t]),g.useEffect(()=>{i&&n&&!N.current&&(b(n),N.current=!0)},[i,n]);const H=async z=>{if(z.preventDefault(),!d){Ve.error("Please select a dataset");return}let V;try{V=JSON.parse(h)}catch{Ve.error("Input must be valid JSON");return}let M;if(m.trim())try{M=JSON.parse(m)}catch{Ve.error("Ground Truth must be valid JSON");return}let G;if(y.trim())try{G=JSON.parse(y)}catch{Ve.error("Expected Trajectory must be valid JSON");return}let F;if(x.trim())try{const R=JSON.parse(x);if(!Array.isArray(R)){Ve.error("Tool Mocks must be a JSON array");return}F=R}catch{Ve.error("Tool Mocks must be valid JSON");return}try{await _.mutateAsync({datasetId:d,input:V,groundTruth:M,expectedTrajectory:G,toolMocks:F,...u?{source:u}:{}});const R=T.find(U=>U.id===d);Ve.success(`Item saved to "${R?.name}"`),f(""),p("{}"),v(""),b(""),w(""),l()}catch(R){Ve.error(`Failed to save item: ${R instanceof Error?R.message:"Unknown error"}`)}},q=()=>{f(""),l()};return o.jsxs(Ca,{dialogTitle:"Save as Dataset Item",dialogDescription:"Save data as a dataset item",isOpen:i,onClose:l,level:c,children:[o.jsxs(Ca.Top,{children:[a,"›",o.jsxs(Pl,{children:[o.jsx(hm,{})," Save as Dataset Item"]})]}),o.jsxs(Ca.Content,{children:[o.jsx(Ca.Header,{children:o.jsxs(Ca.Heading,{children:[o.jsx(hm,{})," Save as Dataset Item"]})}),o.jsxs("form",{onSubmit:H,className:"grid gap-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"target-dataset",children:"Dataset *"}),o.jsxs(la,{value:d,onValueChange:f,disabled:_.isPending||C,children:[o.jsx(ua,{id:"target-dataset",children:o.jsx(ca,{placeholder:C?"Loading datasets...":"Select a dataset"})}),o.jsx(da,{children:T.length===0?o.jsx("div",{className:"text-neutral4 px-2 py-4 text-center text-sm",children:"No datasets available"}):T.map(z=>o.jsx(xr,{value:z.id,children:z.name},z.id))})]})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Gr,{value:h,onChange:P,showCopyButton:!1,className:"min-h-[120px]"})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),o.jsx(Gr,{value:m,onChange:L,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),o.jsx(Gr,{value:y,onChange:D,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-tool-mocks",children:"Tool Mocks (JSON, optional)"}),o.jsx(Gr,{value:x,onChange:B,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ie,{type:"button",variant:"outline",onClick:q,children:"Cancel"}),o.jsx(ie,{type:"submit",variant:"default",disabled:_.isPending||r||!d||T.length===0,children:_.isPending?"Saving...":r?"Loading...":"Save Item"})]})]})]})]})}function Nqr(e){return e?yO({input:e.input,output:e.output,groundTruth:null},2):"{}"}function Iqr(e){return e?yO({score:e.score,reason:e.reason??null},2):""}function Aqr({score:e,isOpen:t,onClose:n,level:r=2}){return o.jsx(K4t,{initialInput:Nqr(e),initialGroundTruth:Iqr(e),breadcrumb:o.jsxs(Pl,{children:[o.jsx(gYt,{})," ",y0(e?.id)]}),isOpen:t,onClose:n,level:r,source:e?.traceId?{type:"trace",referenceId:e.traceId}:void 0})}function Rqr(e){if(!e)return!1;const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function LE(e,t,n){return o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"text-neutral2 flex items-center gap-1.5 tracking-widest uppercase [&>svg]:size-3.5",children:[t,e]}),o.jsxs("span",{children:["› Score ",o.jsxs("b",{className:"text-neutral3",children:["#",n.id]})]})]})}function X4t({score:e,onClose:t,onPrevious:n,onNext:r}){const{Link:s}=dn(),[a,i]=g.useState(!1),l=Rqr(e),c=l?"N/A — code-based scorer does not use prompts":"N/A — step not configured";return o.jsxs(o.Fragment,{children:[o.jsxs(Gt,{children:[o.jsxs(Gt.Header,{children:[o.jsxs(Gt.Heading,{children:["Score ",o.jsxs("b",{children:["# ",e.id]})]}),o.jsxs(es,{className:"ml-auto shrink-0",children:[o.jsx(Gt.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Previous score",nextLabel:"Next score"}),o.jsx(Gt.CloseButton,{onClick:t})]})]}),o.jsxs(Gt.Content,{children:[o.jsxs(En,{children:[e.scorer?.name!=null&&o.jsxs(o.Fragment,{children:[o.jsx(En.Key,{children:"Scorer"}),o.jsx(En.Value,{children:String(e.scorer.name)})]}),e.createdAt&&o.jsxs(o.Fragment,{children:[o.jsx(En.Key,{children:"Created"}),o.jsx(En.Value,{children:dr(new Date(e.createdAt),"MMM dd, HH:mm:ss.SSS")})]}),e.traceId&&o.jsxs(o.Fragment,{children:[o.jsx(En.Key,{children:"Trace Id"}),o.jsx(En.ValueLink,{href:`/traces?traceId=${encodeURIComponent(e.traceId)}`,as:s,children:e.traceId})]}),e.spanId&&e.traceId&&o.jsxs(o.Fragment,{children:[o.jsx(En.Key,{children:"Span Id"}),o.jsx(En.ValueLink,{href:`/traces?traceId=${encodeURIComponent(e.traceId)}&spanId=${encodeURIComponent(e.spanId)}`,as:s,children:e.spanId})]})]}),o.jsx("div",{className:"mt-6 mb-6 flex justify-end",children:o.jsxs(ie,{size:"sm",onClick:()=>i(!0),children:[o.jsx(Qe,{children:o.jsx(Qu,{})}),"Save as Dataset Item"]})}),o.jsxs("div",{className:"text-neutral4 mb-6",children:[o.jsxs("div",{className:K("text-neutral2 text-ui-lg flex gap-2 items-baseline","[&>svg]:w-5 [&>svg]:h-5 [&>svg]:translate-y-1"),children:[o.jsx(Qh,{}),o.jsx("span",{className:"",children:"Score:"}),o.jsx("b",{className:"text-neutral3 font-mono",children:`${e.score==null||Number.isNaN(e.score)?"n/a":e.score}`})]}),o.jsx("div",{className:"text-ui-smd mt-2 font-mono",children:e.reason||(l?"N/A — code-based scorer does not generate a reason":"N/A — step not configured")})]}),o.jsxs("div",{className:"grid gap-4",children:[o.jsx(Gt.CodeSection,{title:"Input",dialogTitle:LE("Input",o.jsx(Ox,{}),e),icon:o.jsx(Ox,{}),codeStr:JSON.stringify(e.input??null,null,2)}),o.jsx(Gt.CodeSection,{title:"Output",dialogTitle:LE("Output",o.jsx(nm,{}),e),icon:o.jsx(nm,{}),codeStr:JSON.stringify(e.output??null,null,2)}),o.jsx(Gt.CodeSection,{title:"Preprocess Prompt",dialogTitle:LE("Preprocess Prompt",o.jsx($p,{}),e),icon:o.jsx($p,{}),codeStr:e.preprocessPrompt||c,simplified:!0}),o.jsx(Gt.CodeSection,{title:"Analyze Prompt",dialogTitle:LE("Analyze Prompt",o.jsx($p,{}),e),icon:o.jsx($p,{}),codeStr:e.analyzePrompt||c,simplified:!0}),o.jsx(Gt.CodeSection,{title:"Generate Score Prompt",dialogTitle:LE("Generate Score Prompt",o.jsx($p,{}),e),icon:o.jsx($p,{}),codeStr:e.generateScorePrompt||c,simplified:!0}),o.jsx(Gt.CodeSection,{title:"Generate Reason Prompt",dialogTitle:LE("Generate Reason Prompt",o.jsx($p,{}),e),icon:o.jsx($p,{}),codeStr:e.generateReasonPrompt||c,simplified:!0})]})]})]}),o.jsx(Aqr,{score:e,isOpen:a,onClose:()=>i(!1)})]})}const sXe=["input","entity"],Pqr={input:"Input",entity:"Entity"};function $qr(e){const t=["auto","auto","minmax(0, 10rem)"];return e.has("entity")&&t.push("minmax(0, 14rem)"),e.has("input")&&t.push("minmax(0, 40rem)"),t.join(" ")}function Mqr(e){return{...e,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt)}}function Dqr({scores:e,onScoreClick:t,errorMsg:n,isLoading:r,isFetchingNextPage:s,hasNextPage:a,setEndOfListElement:i,selectedScoreId:l}){const[c,u]=g.useState(l),d=l??c,[f,h]=g.useState(new Set),p=g.useMemo(()=>new Set(sXe.filter(I=>!f.has(I))),[f]),m=g.useMemo(()=>$qr(p),[p]),v=g.useCallback(I=>{h(A=>{const P=new Set(A);return P.has(I)?P.delete(I):P.add(I),P})},[]);g.useEffect(()=>{u(l)},[l]);const y=g.useCallback(I=>{const A=d===I?void 0:I;u(A),t?.(A??"")},[d,t]),b=g.useMemo(()=>d?e?.find(I=>I.id===d):void 0,[e,d]),x=b?e?.indexOf(b)??-1:-1,w=x>0?()=>{const I=e[x-1];u(I.id),t?.(I.id)}:void 0,k=e&&x>=0&&x<e.length-1?()=>{const I=e[x+1];u(I.id),t?.(I.id)}:void 0,{containerRef:C,getRowProps:_}=ao({count:e?.length??0}),T=g.useCallback(()=>{u(void 0),t?.("")},[t]);if(r)return o.jsx(Bo,{columns:m});if(!e)return null;const E=o.jsxs(Ru.Top,{children:[o.jsx(Ru.TopCell,{children:"Date"}),o.jsx(Ru.TopCell,{children:"Time"}),o.jsx(Ru.TopCell,{children:"Score"}),p.has("entity")&&o.jsx(Ru.TopCell,{children:"Entity"}),p.has("input")&&o.jsx(Ru.TopCell,{children:"Input"})]});if(n)return o.jsxs(Ru,{columns:m,children:[E,o.jsx(Ru.NoMatch,{message:n})]});if(e.length===0)return null;const N=!!b;return o.jsxs("div",{className:K("grid h-full max-h-full min-h-0 gap-4",N?"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[o.jsxs("div",{className:"flex h-full min-h-0 min-w-0 flex-col gap-0",children:[o.jsx("div",{className:"flex shrink-0 items-center justify-end pb-2",children:o.jsxs(at,{children:[o.jsx(at.Trigger,{asChild:!0,children:o.jsxs(ie,{variant:"outline",size:"sm",children:[o.jsx(Ict,{className:"size-3.5"}),"Columns"]})}),o.jsxs(at.Content,{align:"end",children:[o.jsx(at.Label,{children:"Toggle columns"}),sXe.map(I=>o.jsx(at.CheckboxItem,{checked:p.has(I),onClick:()=>v(I),children:Pqr[I]},I))]})]})}),o.jsxs(Ru,{columns:m,className:"min-h-0 flex-1",scrollRef:C,children:[E,e.map((I,A)=>o.jsxs(Ru.RowButton,{onClick:()=>y(I.id),className:d===I.id?"bg-surface4":"",..._(A),children:[o.jsx(Ru.DateCell,{timestamp:I.createdAt}),o.jsx(Ru.TimeCell,{timestamp:I.createdAt}),o.jsx(Ru.ScoreCell,{score:I.score}),p.has("entity")&&o.jsx(Ru.EntityCell,{entityId:I.entityId}),p.has("input")&&o.jsx(Ru.InputCell,{input:I.input})]},I.id)),o.jsx(Ru.NextPageLoading,{isLoading:s,hasMore:a,setEndOfListElement:i})]})]}),b&&o.jsx("div",{className:"grid h-full max-h-full min-h-0 grid-rows-[1fr] overflow-hidden",children:o.jsx(X4t,{score:Mqr(b),onClose:T,onPrevious:w,onNext:k})})]})}const Lqr=({onRunExperiment:e})=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx(Mc,{}),titleSlot:"No scores yet",descriptionSlot:"Scores will appear here once a scorer evaluates agents or workflows. More info in the documentation.",actionSlot:o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e&&o.jsxs(ie,{variant:"primary",onClick:e,children:[o.jsx(Dc,{}),"Run Experiment"]}),o.jsxs(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/evals/overview",target:"_blank",rel:"noopener noreferrer",children:["Scorers Documentation ",o.jsx(ta,{})]})]})})});function xje({data:e,className:t,labelsAreHidden:n,isLoading:r,LinkComponent:s}){const a=({children:i})=>n?o.jsx(T1,{children:i}):i;return!e||e.length===0?null:o.jsx("dl",{className:K("grid grid-cols-[auto_1fr] content-start items-start gap-x-4",t),children:e.map(({key:i,label:l,value:c,icon:u,separator:d},f)=>{const h=Array.isArray(c);return o.jsxs(qe.Fragment,{children:[o.jsxs("dt",{className:K("flex min-h-9 items-center justify-between gap-8 text-ui-md text-neutral3"),children:[o.jsxs("span",{className:K("flex items-center gap-2","[&>svg]:size-[1.4em] [&>svg]:text-neutral3 [&>svg]:opacity-50",{"[&>svg]:opacity-20":r}),children:[u," ",o.jsx(a,{children:l})]}),!n&&o.jsx("span",{className:K("text-neutral3","[&>svg]:size-[1em] [&>svg]:text-neutral3"),children:d})]}),o.jsx("dd",{className:K("flex min-h-9 flex-wrap items-center gap-2 py-1 text-ui-md text-wrap text-neutral5","truncate [&>a]:flex [&>a]:min-h-7 [&>a]:w-auto [&>a]:max-w-full [&>a]:items-center [&>a]:gap-2 [&>a]:rounded-md [&>a]:bg-surface4 [&>a]:px-2 [&>a]:py-0.5 [&>a]:text-ui-md [&>a]:leading-none [&>a]:text-neutral5 [&>a]:transition-colors","[&>a:hover]:bg-surface6 [&>a:hover]:text-neutral6","[&>a>svg]:ml-[-0.5em] [&>a>svg]:size-[1em] [&>a>svg]:text-neutral3"),children:r?o.jsx("span",{className:K("w-full rounded-e-lg bg-surface4"),style:{width:`${Math.floor(Math.random()*61)+50}%`},children:" "}):h?c?.map(p=>p.path&&s?o.jsx(aXe,{description:p.description,children:o.jsxs(s,{href:p.path,children:[p?.name," ",o.jsx(Lr,{})]})},p.id):p.path?o.jsx(aXe,{description:p.description,children:o.jsxs("a",{href:p.path,children:[p?.name," ",o.jsx(Lr,{})]})},p.id):o.jsx("span",{children:p?.name},p.id)):o.jsx(o.Fragment,{children:c||o.jsx("span",{className:"text-ui-sm text-neutral3",children:"n/a"})})})]},i??f)})})}function aXe({description:e,children:t}){return e?o.jsxs(iA,{children:[o.jsx(x_,{render:qe.isValidElement(t)?t:void 0}),o.jsx(w_,{className:"max-w-60 text-center",children:e})]}):t}function Fqr({children:e,className:t}){return o.jsx("div",{className:K("grid gap-12",t),children:e})}function zqr({onEntityChange:e,onReset:t,selectedEntity:n,entityOptions:r,isLoading:s}){return o.jsxs(es,{children:[o.jsx(Cm,{label:"Filter by Entity",labelIsHidden:!0,name:"select-entity",placeholder:"Select...",size:"md",options:r||[],onValueChange:a=>{const i=r?.find(l=>l.value===a);i&&e(i)},value:n?.value||"",className:"min-w-56",disabled:s}),n&&n.value!=="all"&&o.jsxs(ie,{onClick:t,disabled:s,size:"md",children:["Reset",o.jsx(Qe,{children:o.jsx(or,{})})]})]})}const Bqr=25,Uqr=5e3;function qqr(e){return z4(e.state.error,"scores")||B4(e.state.error)?!1:Uqr}function Vqr(e,t,n){if(e?.pagination?.hasMore)return n+1}function Hqr(e){const t=new Set;return e.pages.flatMap(r=>r.scores??[]).filter(r=>t.has(r.id)?!1:(t.add(r.id),!0))}const Wqr=({scorerId:e,entityId:t,entityType:n})=>{const r=Ye(),{inView:s,setRef:a}=a0(),i=Ly({queryKey:["scores",e,t,n],queryFn:({pageParam:d})=>r.listScoresByScorerId({scorerId:e,page:d,perPage:Bqr,entityId:t,entityType:n}),initialPageParam:0,getNextPageParam:Vqr,select:Hqr,refetchInterval:qqr}),{hasNextPage:l,isFetchingNextPage:c,fetchNextPage:u}=i;return g.useEffect(()=>{s&&l&&!c&&u()},[s,l,c,u]),{...i,setEndOfListElement:a}},Zqr=e=>{const t=Ye(),[n,r]=g.useState(null),[s,a]=g.useState(!0),[i,l]=g.useState(null);return g.useEffect(()=>{(async()=>{a(!0),l(null);try{const u=await t.getScorer(e);r(u)}catch(u){r(null);const d=u instanceof Error?u:new Error("Error fetching scorer");l(d),console.error("Error fetching scorer",u),Ve.error("Error fetching scorer")}finally{a(!1)}})()},[e,t]),{scorer:n,isLoading:s,error:i}},up=()=>{const e=Ye(),t=Zl();return mt({queryKey:["scorers",t],queryFn:()=>e.listScorers(t),staleTime:0,gcTime:0})};function Gqr({value:e,onValueChange:t,placeholder:n="Select a scorer...",searchPlaceholder:r="Search scorers...",emptyText:s="No scorers found.",className:a,disabled:i=!1,variant:l,size:c}){const{data:u={},isLoading:d,isError:f,error:h}=up(),{navigate:p,paths:m}=dn();g.useEffect(()=>{if(f){const b=h instanceof Error?h.message:"Failed to load scorers";Ve.error(`Error loading scorers: ${b}`)}},[f,h]);const v=Object.keys(u).map(b=>({label:u[b]?.scorer.config.name||b,value:b})),y=b=>{t?t(b):b&&b!==e&&p(m.scorerLink(b))};return o.jsx(vl,{options:v,value:e,onValueChange:y,placeholder:d?"Loading scorers...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||d||f,variant:l,size:c})}function J4t({children:e,className:t}){return o.jsx("div",{className:K("rounded-xl border border-border1 bg-surface-overlay-soft px-4 py-3",t),children:e})}function Qqr({changePct:e,prevValue:t,lowerIsBetter:n,className:r}){const s=n?e<0:e>=0;return o.jsxs("div",{className:K("flex flex-wrap items-center gap-1 text-sm text-neutral1",r),children:[o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("span",{className:K("[&>svg]:size-4",s?"text-green-600":"text-red-600"),children:e>=0?o.jsx(otn,{}):o.jsx(atn,{})}),o.jsx("span",{className:K(s?"text-green-600":"text-red-600"),children:`${e>=0?"+":"-"}${Math.abs(e).toFixed(1)}%`})]}),t&&o.jsxs("div",{children:["vs previous ",o.jsx("b",{className:"text-neutral2 font-semibold",children:t})]})]})}function Yqr({message:e="Failed to load data",className:t}){return o.jsx("span",{className:K("text-ui-sm text-accent2",t),children:e})}function Kqr({children:e,className:t}){return o.jsx("span",{className:K("text-ui-md leading-relaxed text-neutral3",t),children:e})}function Xqr({className:e}){return o.jsx("span",{className:K("text-sm",e),children:o.jsx(Vt,{size:"md",variant:"pulse",className:"text-neutral1"})})}function Jqr({message:e="No previous value to compare",className:t}){return o.jsx("span",{className:K("text-sm text-neutral1",t),children:e})}function eVr({message:e="No data yet",className:t}){return o.jsx("span",{className:K("text-sm text-neutral1",t),children:e})}function tVr({children:e,className:t}){return o.jsx(J4t,{className:K("min-w-72 flex-1",t),children:o.jsx("div",{className:"grid gap-1",children:e})})}function nVr({children:e,className:t}){return o.jsx("strong",{className:K("text-header-lg font-semibold text-neutral4",t),children:e})}const Xr=Object.assign(tVr,{Label:Kqr,Value:nVr,Change:Qqr,NoChange:Jqr,NoData:eVr,Error:Yqr,Loading:Xqr});function rVr({children:e,className:t}){return o.jsx("div",{className:K("flex shrink-0 items-center gap-1",t),children:e})}function sVr({children:e,className:t}){return o.jsx("div",{className:K("overflow-x-auto ",t),children:e})}function eLt({children:e,className:t}){return o.jsx("p",{className:K("mt-0.5 text-ui-md leading-tight text-neutral2",t),children:e})}function aVr({message:e="Failed to load data",className:t}){return o.jsx("div",{className:K("flex flex-col items-center justify-center gap-3",t),children:o.jsx("p",{className:"text-ui-sm text-accent2",children:e})})}function iVr({className:e}){return o.jsx("div",{className:K("flex items-center justify-center",e),children:o.jsx(Vt,{size:"md",variant:"pulse",className:"text-neutral1"})})}function oVr({message:e="No data yet",className:t}){return o.jsx("div",{className:K("flex h-full items-center justify-center",t),children:o.jsx("p",{className:"text-neutral1 text-sm",children:e})})}function iXe({children:e,className:t}){return o.jsx(J4t,{className:K("2xl:min-w-120 md:min-w-88 xl:min-w-104 grid min-h-72 min-w-80 flex-1 grid-rows-[4rem_1fr] gap-2 lg:min-w-sm",t),children:e})}function lVr({value:e,label:t,className:n}){return o.jsxs("div",{className:K("grid content-start justify-end gap-1 text-right",n),children:[o.jsx("span",{className:"text-ui-lg text-neutral4 leading-none font-semibold",children:e}),t&&o.jsx("span",{className:"text-ui-md text-neutral2",children:t})]})}function tLt({children:e,className:t,as:n="h2"}){return o.jsx(n,{className:K("text-ui-md font-normal text-neutral4",t),children:e})}function cVr(e){if("children"in e)return o.jsx("div",{className:e.className,children:e.children});const{title:t,description:n,titleAs:r}=e;return o.jsxs("div",{className:e.className,children:[o.jsx(tLt,{as:r,children:t}),n&&o.jsx(eLt,{children:n})]})}function uVr({children:e,className:t}){return o.jsx("div",{className:K("flex items-start gap-4 [&>:first-child]:min-w-0 [&>:first-child]:flex-1",t),children:e})}const Ht=Object.assign(iXe,{Root:iXe,Kpi:Xr,TopBar:uVr,Actions:rVr,TitleAndDescription:cVr,Title:tLt,Description:eLt,Summary:lVr,Loading:iVr,Error:aVr,Content:sVr,NoData:oVr});function dVr({active:e,payload:t,label:n,suffix:r}){return!e||!t?.length?null:o.jsxs("div",{className:"border-border1 bg-surface2 rounded-md border px-3 py-2 text-xs shadow-lg",children:[o.jsx("p",{className:"text-icon6 mb-1 font-medium",children:n}),t.map(s=>o.jsxs("p",{className:"text-icon2",children:[o.jsx("span",{className:"mr-2 inline-block size-2 rounded-full",style:{backgroundColor:s.color}}),s.name,":"," ",o.jsxs("span",{className:"font-mono",children:[s.value,r]})]},s.name))]})}const oXe="#a1a1aa";function ID({data:e,series:t,height:n=210,yDomain:r,onPointClick:s,xAxisInterval:a=5,xAxisMinTickGap:i,showDots:l=!1}){const c=typeof s=="function";return o.jsxs("div",{children:[o.jsx("div",{className:"mb-4 flex w-full flex-wrap items-end gap-4 gap-y-1",children:t.map(u=>{const d=u.aggregate?.(e);return o.jsxs("div",{className:"inline-flex items-baseline gap-2",children:[o.jsx("div",{className:"size-2 shrink-0 -translate-y-px rounded-full",style:{backgroundColor:u.color}}),o.jsx("span",{className:"text-ui-sm text-neutral3 max-w-24 truncate",children:u.label}),d&&o.jsxs("span",{className:"text-ui-sm text-neutral4",children:[d.value,d.suffix&&o.jsxs("span",{className:"text-ui-sm text-neutral2",children:[" ",d.suffix]})]})]},u.dataKey)})}),o.jsx("div",{style:{height:n},children:o.jsx(S4,{width:"100%",height:"100%",children:o.jsxs(QEr,{data:e,children:[o.jsx(WRt,{stroke:"currentColor",strokeOpacity:.08,vertical:!1,className:"text-black dark:text-white"}),o.jsx(P4,{dataKey:"time",tick:{fontSize:10,fill:oXe,fontFamily:"var(--font-mono)"},tickLine:!1,axisLine:!1,interval:a,minTickGap:i}),o.jsx($4,{tick:{fontSize:10,fill:oXe,fontFamily:"var(--font-mono)"},tickLine:!1,axisLine:!1,width:30,domain:r}),o.jsx(RZ,{content:o.jsx(dVr,{})}),t.map(u=>o.jsx(tPt,{type:"linear",dataKey:u.dataKey,stroke:u.color,strokeWidth:2,dot:l?{r:3,fill:u.color,strokeWidth:0}:!1,activeDot:c?{r:4,style:{cursor:"pointer"},onClick:(d,f)=>{const h=f?.payload;h&&s(h,u.dataKey)}}:void 0,name:u.label},u.dataKey))]})})})]})}const lXe=["#22c55e","#4f83f1","#8b5cf6","#fb923c","#f472b6","#facc15"];function fVr({summaryData:e,overTimeData:t,scorerNames:n,avgScore:r,isLoading:s,isError:a}){const i=e.length>0,l=g.useMemo(()=>n.map((c,u)=>({dataKey:c,label:c,color:lXe[u%lXe.length],aggregate:d=>({value:d.length>0?(d.reduce((f,h)=>f+(h[c]??0),0)/d.length).toFixed(2):"0",suffix:"avg"})})),[n]);return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Scores",description:"Evaluation scorer performance across all scorers."}),i&&o.jsx(Ht.Summary,{value:r!=null?`avg ${r}`:"—",label:"Across all scorers"})]}),s?o.jsx(Ht.Loading,{}):a?o.jsx(Ht.Error,{message:"Failed to load scores data"}):o.jsx(Ht.Content,{children:i?o.jsxs(Zc,{defaultTab:"over-time",className:"overflow-visible",children:[o.jsxs(Wc,{children:[o.jsx(Qr,{value:"over-time",children:"Over Time"}),o.jsx(Qr,{value:"summary",children:"Summary"})]}),o.jsx(_s,{value:"over-time",children:t.length>0?o.jsx(ID,{data:t,series:l,yDomain:[0,1]}):o.jsx(Ht.NoData,{message:"No time series data yet"})}),o.jsx(_s,{value:"summary",children:o.jsxs(pe,{columns:"auto auto auto auto auto",className:"max-h-80",mask:{left:!1},children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{sticky:"start",children:"Scorer"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Avg"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Min"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Max"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Count"})]}),e.map(c=>o.jsxs(pe.RowStatic,{children:[o.jsx(pe.RowHeaderCell,{className:"text-ui-sm",children:c.scorer}),o.jsx(pe.NumberCell,{highlight:!0,children:c.avg.toFixed(2)}),o.jsx(pe.NumberCell,{children:c.min.toFixed(2)}),o.jsx(pe.NumberCell,{children:c.max.toFixed(2)}),o.jsx(pe.NumberCell,{children:c.count.toLocaleString()})]},c.scorer))]})})]}):o.jsx(Ht.NoData,{message:"No scores data yet"})})]})}const cXe="minmax(0,1fr) minmax(0,1.5fr) auto auto auto";function hVr({scorers:e,isLoading:t,search:n="",sourceFilter:r="all"}){const{paths:s,Link:a}=dn(),i=g.useMemo(()=>Object.entries(e).map(([d,f])=>({...f,id:d})),[e]),l=g.useMemo(()=>{const d=n.toLowerCase();return i.filter(f=>{const h=!d||f.scorer.config?.id?.toLowerCase().includes(d)||f.scorer.config?.name?.toLowerCase().includes(d),p=r==="all"||f.source===r;return h&&p})},[i,n,r]),{containerRef:c,getRowProps:u}=ao({count:l.length});return t?o.jsx(Bo,{columns:cXe}):o.jsxs(pe,{columns:cXe,scrollRef:c,children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{children:"Name"}),o.jsx(pe.TopCell,{children:"Description"}),o.jsx(pe.TopCell,{children:"Source"}),o.jsx(pe.TopCellSmart,{long:"Agents",short:o.jsx(Ri,{}),tooltip:"Number of attached Agents",className:"text-center"}),o.jsx(pe.TopCellSmart,{long:"Workflows",short:o.jsx(fI,{}),tooltip:"Number of attached Workflows",className:"text-center"})]}),l.map((d,f)=>{const h=d.scorer.config?.name||d.id,p=d.scorer.config?.description||"",m=d.agentIds?.length??0,v=d.workflowIds?.length??0,y=d.scorer.config?.type==="trajectory";return o.jsxs(pe.RowLink,{to:s.scorerLink(d.id),LinkComponent:a,...u(f),children:[o.jsx(pe.NameCell,{children:o.jsxs("span",{className:"flex max-w-full min-w-0 items-center gap-1.5",children:[o.jsx("span",{className:"min-w-0 truncate",children:h}),y&&o.jsx(bt,{size:"xs",variant:"purple",className:"shrink-0",children:"trajectory"})]})}),o.jsx(pe.DescriptionCell,{children:p}),o.jsx(pe.Cell,{children:o.jsx(bt,{size:"xs",variant:d.source==="code"?"blue":"neutral",children:d.source})}),o.jsx(pe.TextCell,{className:"text-center",children:m||""}),o.jsx(pe.TextCell,{className:"text-center",children:v||""})]},d.id)})]})}const pVr=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx(Mc,{}),titleSlot:"No Scorers yet",descriptionSlot:"Configure scorers in code to get started. More info in the documentation.",actionSlot:o.jsxs(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/evals/overview",target:"_blank",rel:"noopener noreferrer",children:["Scorers Documentation ",o.jsx(ta,{})]})})}),mVr=[{value:"all",label:"All sources"},{value:"code",label:"Code"},{value:"stored",label:"Stored"}];function gVr({search:e,onSearchChange:t,sourceFilter:n,onSourceFilterChange:r,onReset:s,hasActiveFilters:a}){const[i,l]=g.useState(e),c=g.useRef(e),u=Uy(p=>{c.current=p,t(p)},300);g.useEffect(()=>{e!==c.current&&(c.current=e,u.cancel(),l(e))},[e,u]),g.useEffect(()=>()=>u.cancel(),[u]);const d=g.useCallback(p=>{l(p.target.value),u(p.target.value)},[u]),f=g.useCallback(()=>{c.current="",u.cancel(),l(""),t("")},[t,u]),h=g.useCallback(()=>{c.current="",u.cancel(),l(""),s?.()},[s,u]);return o.jsxs("div",{className:"flex w-full max-w-[40rem] items-center gap-2",children:[o.jsxs(es,{spacing:"close",className:"min-w-0 flex-1",children:[o.jsxs(du,{variant:"outline",size:"default",children:[o.jsx(Ic,{align:"inline-start",children:o.jsx(Ds,{})}),o.jsx(fu,{name:"scorer-search",type:"search","aria-label":"Search scorers",placeholder:"Filter by scorer name",value:i,onChange:d}),i&&o.jsx(Ic,{align:"inline-end",children:o.jsx(ije,{"aria-label":"Clear search",onClick:f,children:o.jsx(or,{})})})]}),o.jsxs(la,{value:n,onValueChange:r,children:[o.jsx(ua,{"aria-label":"Filter by source",className:"rounded-full",children:o.jsx(ca,{placeholder:"All sources"})}),o.jsx(da,{align:"end",children:mVr.map(p=>o.jsx(xr,{value:p.value,children:p.label},p.value))})]})]}),s&&a&&o.jsxs(ie,{onClick:h,variant:"outline",children:[o.jsx(or,{})," Reset"]})]})}const mxe={checked(e){return e?{"data-checked":""}:{"data-unchecked":""}},...Im,...r_},nLt=g.createContext(void 0);function vVr(){return g.useContext(nLt)}const rLt=g.createContext(void 0);function yVr(){const e=g.useContext(rLt);if(e===void 0)throw new Error(Ir(52));return e}const bVr=g.forwardRef(function(t,n){const{render:r,className:s,disabled:a=!1,readOnly:i=!1,required:l=!1,"aria-labelledby":c,value:u,inputRef:d,nativeButton:f=!1,id:h,style:p,...m}=t,v=vVr(),{disabled:y,readOnly:b,required:x,form:w,checkedValue:k,touched:C=!1,validation:_,name:T,setCheckedValue:E=ra,setTouched:N=ra,registerInputRef:I=ra}=v??{},{setTouched:A,setFilled:P,state:L,disabled:D}=Pm(),B=zxt(),{labelId:H,getDescriptionProps:q}=r0(),z=D||B.disabled||y||a,V=b||i,M=x||l,G=w,F=v?k===u:u==="",R=g.useRef(null),U=g.useRef(null),Z=_?.registerInput,Y=g.useCallback(Me=>Z?.(Me,{controlRef:R,value:void 0}),[Z]),te=qd(d,U,I,Y);Tt(()=>{U.current?.checked&&P(!0)},[P]),Tt(()=>{if(U.current){if(z&&F){I(null);return}I(U.current)}},[F,z,I]);const J=Vi(),ee=s_({id:h,implicit:!1,controlRef:R}),re=f?void 0:ee,ae=RSe(c,H,U,!f,re),X={role:"radio","aria-checked":F,"aria-labelledby":ae,[VEe]:F?"":void 0,id:f?ee:J,onKeyDown(Me){Me.key==="Enter"&&Me.preventDefault()},onClick(Me){if(Me.defaultPrevented||z||V)return;Me.preventDefault();const Pe=U.current;Pe&&iO(Pe,Me)},onFocus(Me){Me.defaultPrevented||z||V||!C||(U.current?.click(),N(!1))}},{getButtonProps:ne,buttonRef:se}=Yd({disabled:z,native:f,composite:!1}),ce={type:"radio",ref:te,form:G,id:re,name:T,tabIndex:-1,style:T?gI:k1,"aria-hidden":!0,...u!==void 0?{value:K7(u)}:ya,disabled:z,checked:F,required:M,readOnly:V,onChange(Me){if(Me.nativeEvent.defaultPrevented||z||V||u===void 0)return;const Pe=nn(Ji,Me.nativeEvent);E(u,Pe),!Pe.isCanceled&&A(!0)},onClick(Me){Me.stopPropagation()},onFocus(){R.current?.focus()}},le=g.useMemo(()=>({...L,required:M,disabled:z,readOnly:V,checked:F}),[L,z,V,F,M]),be=le,he=v!==void 0,xe=[n,R,se],Ae=[X,m,ne,q,_?Me=>_.getValidationProps(z,Me):ya],De=In("span",t,{enabled:!he,state:le,ref:xe,props:Ae,stateAttributesMapping:mxe});return o.jsxs(rLt.Provider,{value:be,children:[he?o.jsx(T$t,{tag:"span",render:r,className:s,style:p,state:le,refs:xe,props:Ae,stateAttributesMapping:mxe}):De,o.jsx("input",{...ce,suppressHydrationWarning:!0})]})}),xVr=g.forwardRef(function(t,n){const{render:r,className:s,style:a,keepMounted:i=!1,...l}=t,c=yVr(),u=c.checked,{mounted:d,transitionStatus:f,setMounted:h}=Kg(u),p={...c,transitionStatus:f},m=g.useRef(null),v=i||d,y=In("span",t,{ref:[n,m],state:p,props:l,stateAttributesMapping:mxe});return hc({open:u,ref:m,onComplete(){u||h(!1)}}),v?y:null});function wVr(e,t){return e.matches(":disabled")?!1:!t||e.form===t?!0:e.form===null&&!e.hasAttribute("form")}const SVr=g.createContext(void 0);function kVr(e=!1){const t=g.useContext(SVr);if(!t&&!e)throw new Error(Ir(86));return t}const OVr=[bxt],CVr=g.forwardRef(function(t,n){const{render:r,className:s,disabled:a,readOnly:i,required:l,onValueChange:c,value:u,defaultValue:d,form:f,name:h,inputRef:p,id:m,style:v,...y}=t,{setTouched:b,setFocused:x,validationMode:w,name:k,disabled:C,state:_,validation:T,setDirty:E,setFilled:N,validityData:I}=Pm(),{labelId:A}=r0(),{clearErrors:P,elementRef:L}=kI(),D=kVr(!0),B=C||a,H=k??h,q=Vi(m),[z,V]=Rf({controlled:u,default:d,name:"RadioGroup",state:"value"}),[M,G]=g.useState(!1),F=yt((se,ce)=>{c?.(se,ce),!ce.isCanceled&&V(se)}),R=T.getInputControl,U=g.useMemo(()=>({get current(){return R()}}),[R]),Z=g.useRef(null),Y=g.useRef(null);function te(se){let ce;return p&&(typeof p=="function"?ce=p(se):p.current=se),Z.current=se,ce}const J=yt(se=>{if(!se||se.disabled)return;Y.current||(Y.current=se);const ce=Z.current,le=se.checked||ce==null||ce.disabled?te(se):void 0;return()=>{Y.current===se&&(Y.current=null),Z.current===se?le?(le(),Z.current=null):te(null):le?.()}}),ee=yt(()=>{const se=L.current;if(!se)return z??null;for(const ce of T.registeredInputs.keys())if(ce.checked&&wVr(ce,se))return z??null;return null});SI(U,q,z??null,ee,!B,h),Xv(z,()=>{P(H),E(z!==I.initialValue),N(z!=null),T.change(z);const se=Y.current;z==null&&se&&!se.disabled&&te(se)});const re=A??D?.legendId,ae={..._,disabled:B??!1,required:l??!1,readOnly:i??!1},X=g.useMemo(()=>({checkedValue:z,disabled:B,form:f,validation:T,name:H,readOnly:i,registerInputRef:J,required:l,setCheckedValue:F,setTouched:G,touched:M}),[z,B,f,T,H,i,J,l,F,G,M]),ne={id:m,role:"radiogroup","aria-required":l||void 0,"aria-disabled":B||void 0,"aria-readonly":i||void 0,"aria-labelledby":re,onFocus(){x(!0)},onBlur(se){cn(se.currentTarget,se.relatedTarget)||(b(!0),x(!1),w==="onBlur"&&T.commit(z))},onKeyDownCapture(se){se.key.startsWith("Arrow")&&(G(!0),x(!0))}};return o.jsx(nLt.Provider,{value:X,children:o.jsx(QPt,{render:r,className:s,style:v,state:ae,props:[ne,y,se=>T.getValidationProps(B??!1,se)],refs:[n],stateAttributesMapping:r_,enableHomeAndEndKeys:!1,modifierKeys:OVr})})}),nL=g.forwardRef(({className:e,...t},n)=>o.jsx(CVr,{ref:n,"data-slot":"radio-group",className:K("grid gap-2",e),...t}));nL.displayName="RadioGroup";const Mh=g.forwardRef(({className:e,...t},n)=>o.jsx(bVr,{ref:n,"data-slot":"radio-group-item",className:K("flex size-4 shrink-0 cursor-pointer items-center justify-center rounded-full","border border-neutral6/[0.06] bg-neutral6/[0.12] text-surface1 outline-hidden",Yr.all,"hover:border-neutral6/[0.12] hover:bg-neutral6/[0.16]","active:scale-95 active:border-neutral6/[0.18] active:bg-neutral6/[0.18]","focus-visible:border-neutral5/50 focus-visible:outline-1 focus-visible:outline-offset-2 focus-visible:outline-neutral5/55 focus-visible:outline-solid","data-[checked]:border-neutral6 data-[checked]:bg-neutral6 data-[checked]:text-surface1","data-[checked]:hover:border-neutral5 data-[checked]:hover:bg-neutral5","data-[checked]:active:border-neutral4 data-[checked]:active:bg-neutral4","data-[disabled]:cursor-not-allowed data-[disabled]:border-neutral6/[0.38] data-[disabled]:bg-neutral6/[0.38] data-[disabled]:hover:border-neutral6/[0.38] data-[disabled]:hover:bg-neutral6/[0.38] data-[disabled]:active:scale-100","data-[disabled]:data-[checked]:border-neutral6/[0.38] data-[disabled]:data-[checked]:bg-neutral6/[0.38] data-[disabled]:data-[checked]:text-neutral6",e),...t,children:o.jsx(xVr,{keepMounted:!0,className:K("flex items-center justify-center text-current","scale-50 opacity-0 transition-[opacity,scale] duration-200 ease-out-custom","data-[checked]:scale-100 data-[checked]:opacity-100","data-[starting-style]:scale-50 data-[starting-style]:opacity-0","data-[ending-style]:scale-50 data-[ending-style]:opacity-0"),children:o.jsx("span",{className:"size-1.5 rounded-full bg-current"})})}));Mh.displayName="RadioGroupItem";function Ld({title:e,subtitle:t,icon:n,className:r}){return o.jsxs("header",{className:K("flex flex-col w-fit",r),children:[o.jsxs(ve,{as:"h2",variant:"header-md",className:"flex items-center gap-2",children:[n&&o.jsx(Qe,{size:"lg",className:"text-accent1",children:n}),e]}),t&&o.jsx(ve,{className:"text-ui-md text-neutral3 !font-light",children:t})]})}function b0({title:e,icon:t}){return o.jsxs(ve,{as:"h4",variant:"ui-sm",className:"text-neutral2 flex items-center gap-1 uppercase",children:[t&&o.jsx(Qe,{size:"sm",className:"text-neutral1",children:t}),e]})}const gxe=e=>"field"in e,sLt=e=>e?e.conditions.reduce((t,n)=>gxe(n)?t+1:t+sLt(n),0):0,wje=()=>({field:"",operator:"equals",value:""}),_Vr=(e="AND")=>({operator:e,conditions:[wje()]}),AD=e=>Array.isArray(e.type)?e.type.find(t=>t!=="null")||"string":e.type||"string",aLt=e=>{const t=AD(e);return t==="object"&&e.properties?Object.keys(e.properties).length>0:t==="array"&&e.items?AD(e.items)==="object"&&!!e.items.properties:!1},vxe=(e,t="")=>e?Object.entries(e).map(([n,r])=>{const s=t?`${t}.${n}`:n,a=AD(r),i=aLt(r);return{path:s,label:r.title||n,type:a,hasChildren:i,children:a==="object"?r.properties:void 0,items:a==="array"?r.items:void 0}}):[],EVr=e=>vxe(e.properties),TVr=(e,t)=>e.type==="object"&&e.children?vxe(e.children,t):e.type==="array"&&e.items&&AD(e.items)==="object"&&e.items.properties?vxe(e.items.properties,t):[],iLt=e=>e.split(".").filter(Boolean),oLt=(e,t)=>{const n=iLt(t);if(n.length===0)return;let r=e.properties,s="",a;for(let i=0;i<n.length;i++){const l=n[i];if(l===void 0)return;const c=r?.[l];if(!c)return;s=s?`${s}.${l}`:l;const u=AD(c),d=aLt(c);a={path:s,label:c.title||l,type:u,hasChildren:d,children:u==="object"?c.properties:void 0,items:u==="array"?c.items:void 0},u==="object"&&c.properties?r=c.properties:u==="array"&&c.items?.properties?r=c.items.properties:r=void 0}return a},jVr=e=>{switch(e){case"object":return o.jsx(sc,{});case"array":return o.jsx(u1,{});case"number":case"integer":return o.jsx(AV,{});case"boolean":return o.jsx(z0e,{});default:return o.jsx(U0e,{})}},NVr=({options:e,value:t,onChange:n,placeholder:r="Select field",className:s})=>o.jsx("div",{className:K("relative",s),children:o.jsxs(la,{value:t,onValueChange:n,children:[o.jsx(ua,{className:"bg-surface4 text-neutral6 min-w-35",size:"sm",children:o.jsx(ca,{placeholder:r})}),o.jsx(da,{children:e.map(a=>o.jsx(xr,{value:a.path,children:o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(Qe,{size:"sm",className:"text-neutral3",children:jVr(a.type)}),a.label,a.hasChildren&&o.jsx("span",{className:"text-neutral3",children:"..."})]})},a.path))})]})}),IVr=({schema:e,value:t,onChange:n,className:r})=>{const s=g.useMemo(()=>iLt(t),[t]),a=g.useMemo(()=>{const l=[],c=EVr(e);if(c.length===0)return l;l.push({options:c,value:s[0]||"",basePath:""});let u="";for(let d=0;d<s.length;d++){const f=s[d];if(f===void 0)break;u=u?`${u}.${f}`:f;const h=oLt(e,u);if(!h||!h.hasChildren)break;const p=TVr(h,u);if(p.length===0)break;const m=s[d+1],v=m?`${u}.${m}`:"";l.push({options:p,value:v,basePath:u})}return l},[e,s]),i=g.useCallback((l,c)=>{n(c)},[n]);return a.length===0?o.jsx("div",{className:K("text-sm text-neutral3",r),children:"No fields available"}):o.jsx("div",{className:K("flex items-center gap-1",r),children:a.map((l,c)=>o.jsxs(g.Fragment,{children:[c>0&&o.jsx("span",{className:"text-neutral3",children:"."}),o.jsx(NVr,{options:l.options,value:l.value,onChange:u=>i(c,u),placeholder:c===0?"Select field":"Select property"})]},`${l.basePath}-${c}`))})},AVr={equals:"equals",not_equals:"not equals",contains:"contains",not_contains:"not contains",greater_than:"greater than",less_than:"less than",greater_than_or_equal:"greater than or equal",less_than_or_equal:"less than or equal",in:"in",not_in:"not in",exists:"exists",not_exists:"not exists"},RVr=["equals","not_equals","contains","not_contains","greater_than","less_than","greater_than_or_equal","less_than_or_equal","in","not_in","exists","not_exists"],PVr={equals:o.jsx(Rct,{}),not_equals:o.jsx(EKt,{}),contains:o.jsx(Ken,{}),not_contains:o.jsx(d1,{}),greater_than:o.jsx(Lr,{}),less_than:o.jsx(KD,{}),greater_than_or_equal:o.jsx(Ect,{}),less_than_or_equal:o.jsx(IYt,{}),in:o.jsx(u1,{}),not_in:o.jsx(ZXt,{}),exists:o.jsx(Ur,{}),not_exists:o.jsx(k0e,{})},$Vr=({value:e,onChange:t,operators:n,className:r})=>{const s=n??RVr;return o.jsx("div",{className:K("relative",r),children:o.jsxs(la,{value:e,onValueChange:t,children:[o.jsx(ua,{className:"bg-surface4 text-neutral6 min-w-[150px]",size:"sm",children:o.jsx(ca,{placeholder:"Select operator"})}),o.jsx(da,{children:s.map(a=>o.jsx(xr,{value:a,children:o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(Qe,{size:"sm",className:"text-neutral3",children:PVr[a]}),AVr[a]]})},a))})]})})},lLt=e=>{const t=e.trim();if(t==="")return"";if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;const n=t.toLowerCase();if(n==="infinity"||n==="-infinity"||n==="nan")return t;const r=Number(t);return Number.isNaN(r)?e:r},MVr=e=>e.trim()===""?[]:e.split(",").map(t=>lLt(t.trim())),Qq=e=>e===null?"null":e===void 0?"":Array.isArray(e)?e.map(Qq).join(", "):String(e),DVr=e=>e===!0?"true":e===!1?"false":"",LVr=({value:e,onChange:t,className:n})=>{const r=DVr(e),s=g.useCallback(a=>{t(a==="true")},[t]);return o.jsxs("div",{className:K("relative",n),children:[o.jsx(Qe,{size:"sm",className:"text-neutral3 pointer-events-none absolute top-1/2 left-2 z-10 -translate-y-1/2",children:o.jsx(z0e,{})}),o.jsxs(la,{value:r,onValueChange:s,children:[o.jsx(ua,{className:"bg-surface4 min-w-35 pl-7",size:"sm",children:o.jsx(ca,{placeholder:"Select value"})}),o.jsxs(da,{children:[o.jsx(xr,{value:"true",children:"true"}),o.jsx(xr,{value:"false",children:"false"})]})]})]})},FVr=({value:e,onChange:t,placeholder:n,className:r})=>{const s=e===void 0||e===""?"":String(e),a=g.useCallback(i=>{const l=i.target.value;if(l==="")t("");else{const c=Number(l);t(Number.isNaN(c)?l:c)}},[t]);return o.jsxs("div",{className:K("relative",r),children:[o.jsx(Qe,{size:"sm",className:"text-neutral3 pointer-events-none absolute top-1/2 left-2 -translate-y-1/2",children:o.jsx(AV,{})}),o.jsx(jn,{type:"number",value:s,onChange:a,placeholder:n||"Enter number",className:"bg-surface4 min-w-35 pl-7",size:"sm"})]})},zVr=({value:e,onChange:t,placeholder:n,className:r})=>{const s=Qq(e),a=g.useCallback(i=>{t(lLt(i.target.value))},[t]);return o.jsxs("div",{className:K("relative",r),children:[o.jsx(Qe,{size:"sm",className:"text-neutral3 pointer-events-none absolute top-1/2 left-2 -translate-y-1/2",children:o.jsx(U0e,{})}),o.jsx(jn,{value:s,onChange:a,placeholder:n||"Enter value",className:"bg-surface4 min-w-35 pl-7",size:"sm"})]})},BVr=({value:e,onChange:t,placeholder:n,className:r})=>{const s=g.useMemo(()=>Array.isArray(e)?e.map(Qq).join(", "):Qq(e),[e]),a=g.useCallback(i=>{t(MVr(i.target.value))},[t]);return o.jsx(jn,{value:s,onChange:a,placeholder:n||"Enter values (comma-separated)",className:K("min-w-40 bg-surface4",r),size:"sm"})},UVr=({value:e,onChange:t,operator:n,fieldType:r,placeholder:s,className:a})=>n==="in"||n==="not_in"?o.jsx(BVr,{value:e,onChange:t,placeholder:s,className:a}):r==="boolean"?o.jsx(LVr,{value:e,onChange:t,placeholder:s,className:a}):r==="number"||r==="integer"?o.jsx(FVr,{value:e,onChange:t,placeholder:s,className:a}):o.jsx(zVr,{value:e,onChange:t,placeholder:s,className:a}),qVr=new Set(["string","number","boolean","integer"]),VVr=({schema:e,rule:t,onChange:n,onRemove:r,className:s})=>{const a=g.useMemo(()=>oLt(e,t.field)?.type,[e,t.field]),i=a!==void 0&&qVr.has(a),l=a==="array",c=t.operator==="in"||t.operator==="not_in",u=t.operator==="exists"||t.operator==="not_exists",d=i||l,f=!u&&(i||l&&c),h=g.useCallback(v=>{n({...t,field:v})},[t,n]),p=g.useCallback(v=>{if(v==="exists"||v==="not_exists"){n({...t,operator:v,value:void 0});return}const b=v==="in"||v==="not_in",x=t.operator==="in"||t.operator==="not_in";let w=t.value;b&&!x?w=t.value!==void 0?[t.value]:[]:!b&&x&&(w=Array.isArray(t.value)?t.value[0]:t.value),n({...t,operator:v,value:w})},[t,n]),m=g.useCallback(v=>{n({...t,value:v})},[t,n]);return o.jsxs("div",{className:"flex justify-between gap-2",children:[o.jsxs("div",{className:K("flex flex-wrap items-center gap-2",s),children:[o.jsx(IVr,{schema:e,value:t.field,onChange:h}),d&&o.jsxs(o.Fragment,{children:[o.jsx($Vr,{value:t.operator,onChange:p,operators:l?["in","not_in"]:void 0}),f&&o.jsx(UVr,{value:t.value,onChange:m,operator:t.operator,fieldType:a})]})]}),o.jsx(ie,{type:"button",onClick:r,tooltip:"Remove rule",size:"icon-sm",variant:"ghost",children:o.jsx(or,{})})]})},HVr=3,cLt=({schema:e,group:t,onChange:n,onRemove:r,depth:s,maxDepth:a})=>{const i=s===0,l=()=>{n({...t,operator:t.operator==="AND"?"OR":"AND"})},c=(h,p)=>{n({...t,conditions:t.conditions.map((m,v)=>v===h?p:m)})},u=h=>{const p=t.conditions.filter((m,v)=>v!==h);p.length===0&&r?r():n({...t,conditions:p})},d=()=>{n({...t,conditions:[...t.conditions,wje()]})},f=()=>{n({...t,conditions:[...t.conditions,_Vr(t.operator==="AND"?"OR":"AND")]})};return o.jsxs("div",{className:K(i?"bg-surface2":"bg-surface3 pl-6"),children:[!i&&o.jsxs("div",{className:"border-border1 flex items-center justify-between border-b border-dashed py-1.5 pr-4 pl-3",children:[o.jsx("span",{className:"text-ui-xs text-neutral3",children:"Group"}),r&&o.jsx(ie,{type:"button",onClick:r,tooltip:"Remove group",size:"icon-sm",variant:"ghost",children:o.jsx(or,{})})]}),t.conditions.map((h,p)=>o.jsx("div",{className:"border-border1 border-b border-dashed last:border-b-0",children:o.jsxs("div",{className:K("relative",gxe(h)&&"border-l-4 border-border1 p-4"),children:[p>0&&o.jsx("button",{type:"button",onClick:l,className:K("absolute top-0 left-1/2 z-10 -translate-1/2 cursor-pointer rounded-full px-3 py-0.5 text-ui-xs",t.operator==="OR"?"bg-accent6Dark text-accent6 hover:bg-accent6Dark/70":"bg-accent3Dark text-accent3 hover:bg-accent3Dark/70"),children:t.operator.toLowerCase()}),gxe(h)?o.jsx(VVr,{schema:e,rule:h,onChange:m=>c(p,m),onRemove:()=>u(p)}):o.jsx(cLt,{schema:e,group:h,onChange:m=>c(p,m),onRemove:()=>u(p),depth:s+1,maxDepth:a})]})},p)),o.jsxs("div",{className:"flex gap-1 p-2",children:[o.jsxs(ie,{type:"button",onClick:d,variant:"ghost",size:"sm",children:[o.jsx(Qe,{children:o.jsx(_r,{})}),"Add rule"]}),s<a-1&&o.jsxs(ie,{type:"button",onClick:f,variant:"ghost",size:"sm",children:[o.jsx(Qe,{children:o.jsx(dKt,{})}),"Add group"]})]})]})},WVr=({schema:e,ruleGroup:t,onChange:n,maxDepth:r=HVr,className:s})=>{const a=g.useCallback(l=>{n(l)},[n]),i=g.useCallback(()=>{n({operator:"AND",conditions:[wje()]})},[n]);return t?o.jsx("div",{className:s,children:o.jsx(cLt,{schema:e,group:t,onChange:a,depth:0,maxDepth:r})}):o.jsxs("button",{type:"button",onClick:i,className:"border-border1 text-ui-sm text-neutral3 hover:text-neutral6 flex w-full items-center justify-center gap-2 rounded-md border border-dashed p-2",children:[o.jsx(Qe,{children:o.jsx(_r,{})}),"Add conditional rule"]})};function oA({entityName:e,schema:t,rules:n,onRulesChange:r}){const s=Object.keys(t?.properties??{}).length>0;if(!t||!s)return null;const a=sLt(n);return o.jsxs(pr,{children:[o.jsx(zSe,{asChild:!0,children:o.jsxs(ie,{tooltip:a>0?`${a} rules`:"Display Conditions",size:"icon-sm",variant:"ghost",className:"relative",children:[o.jsx(ven,{className:"text-accent6"}),a>0&&o.jsx("span",{className:"bg-accent1 absolute -top-0.5 -right-0.5 size-2 rounded-full"})]})}),o.jsxs(mr,{className:"w-full max-w-5xl",children:[o.jsxs(gr,{children:[o.jsxs(ur,{children:["Display Conditions for ",e]}),o.jsx(Cs,{children:"Configure when this entity should be displayed based on variable values."})]}),o.jsx(jr,{children:o.jsx(WVr,{schema:t,ruleGroup:n,onChange:r})})]})]})}function uLt({form:e,onPublish:t,onSaveDraft:n,isSubmitting:r=!1,isSavingDraft:s=!1,formRef:a,mode:i="create"}){const{register:l,control:c,formState:{errors:u}}=e,d=Mn({control:c,name:"defaultSampling.type"}),f=Mn({control:c,name:"model.provider"});return o.jsxs("div",{className:"flex h-full flex-col",children:[o.jsx(Nr,{className:"min-h-0 flex-1",children:o.jsxs("div",{className:"flex flex-col gap-6 p-4",children:[o.jsx(Ld,{title:"Configuration",subtitle:"Define your scorer's name, type, and settings."}),o.jsxs("div",{className:"flex flex-col gap-1.5",children:[o.jsxs(Dt,{htmlFor:"scorer-name",className:"text-neutral5 text-xs",children:["Name ",o.jsx("span",{className:"text-accent2",children:"*"})]}),o.jsx(jn,{id:"scorer-name",placeholder:"My Scorer",variant:"outline",...l("name"),error:!!u.name}),u.name&&o.jsx("span",{className:"text-accent2 text-xs",children:u.name.message})]}),o.jsxs("div",{className:"flex flex-col gap-1.5",children:[o.jsxs(Dt,{htmlFor:"scorer-description",className:"text-neutral5 text-xs",children:["Description ",o.jsx("span",{className:"text-accent2",children:"*"})]}),o.jsx(zo,{id:"scorer-description",placeholder:"Describe what this scorer does",variant:"outline",...l("description"),error:!!u.description}),u.description&&o.jsx("span",{className:"text-accent2 text-xs",children:u.description.message})]}),o.jsxs("div",{className:"flex flex-col gap-1.5",children:[o.jsxs(Dt,{className:"text-neutral5 text-xs",children:["Provider ",o.jsx("span",{className:"text-accent2",children:"*"})]}),o.jsx($s,{name:"model.provider",control:c,render:({field:h})=>o.jsx(Yy,{value:h.value,onValueChange:h.onChange,container:a})}),u.model?.provider&&o.jsx("span",{className:"text-accent2 text-xs",children:u.model.provider.message})]}),o.jsxs("div",{className:"flex flex-col gap-1.5",children:[o.jsxs(Dt,{className:"text-neutral5 text-xs",children:["Model ",o.jsx("span",{className:"text-accent2",children:"*"})]}),o.jsx($s,{name:"model.name",control:c,render:({field:h})=>o.jsx(Ky,{value:h.value,onValueChange:h.onChange,llmId:f||"",container:a})}),u.model?.name&&o.jsx("span",{className:"text-accent2 text-xs",children:u.model.name.message})]}),o.jsxs("div",{className:"flex flex-col gap-1.5",children:[o.jsx(Dt,{className:"text-neutral5 text-xs",children:"Score Range"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx($s,{name:"scoreRange.min",control:c,render:({field:h})=>o.jsx(jn,{type:"number",placeholder:"Min",variant:"outline",value:h.value,onChange:p=>h.onChange(parseFloat(p.target.value)||0)})}),o.jsx("span",{className:"text-neutral3 text-xs",children:"to"}),o.jsx($s,{name:"scoreRange.max",control:c,render:({field:h})=>o.jsx(jn,{type:"number",placeholder:"Max",variant:"outline",value:h.value,onChange:p=>h.onChange(parseFloat(p.target.value)||0)})})]})]}),o.jsxs("div",{className:"flex flex-col gap-1.5",children:[o.jsx(Dt,{className:"text-neutral5 text-xs",children:"Default Sampling"}),o.jsx($s,{name:"defaultSampling.type",control:c,render:({field:h})=>o.jsxs(nL,{value:h.value??"none",onValueChange:h.onChange,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Mh,{value:"none",id:"sampling-none"}),o.jsx(Dt,{htmlFor:"sampling-none",className:"text-neutral5 text-xs",children:"None"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Mh,{value:"ratio",id:"sampling-ratio"}),o.jsx(Dt,{htmlFor:"sampling-ratio",className:"text-neutral5 text-xs",children:"Ratio"})]})]})}),d==="ratio"&&o.jsx($s,{name:"defaultSampling.rate",control:c,render:({field:h})=>o.jsx(jn,{type:"number",step:"0.1",min:"0",max:"1",placeholder:"Rate (0-1)",variant:"outline",value:h.value??"",onChange:p=>h.onChange(parseFloat(p.target.value)||0)})})]})]})}),o.jsx("div",{className:"shrink-0 p-4",children:i==="edit"&&n?o.jsxs("div",{className:"flex gap-2",children:[o.jsx(ie,{variant:"outline",onClick:n,disabled:s||r,className:"flex-1",children:s?o.jsxs(o.Fragment,{children:[o.jsx(Vt,{className:"h-4 w-4"}),"Saving..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Qe,{children:o.jsx(Qu,{})}),"Save"]})}),o.jsx(ie,{variant:"primary",onClick:t,disabled:r||s,className:"flex-1",children:r?o.jsxs(o.Fragment,{children:[o.jsx(Vt,{className:"h-4 w-4"}),"Publishing..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Qe,{children:o.jsx(Ur,{})}),"Publish"]})})]}):o.jsx(ie,{variant:"primary",onClick:t,disabled:r,className:"w-full",children:r?o.jsxs(o.Fragment,{children:[o.jsx(Vt,{className:"h-4 w-4"}),"Creating..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Qe,{children:o.jsx(Ur,{})}),"Create scorer"]})})})]})}function dLt({form:e}){const{control:t}=e;return o.jsxs("div",{className:"flex h-full flex-col gap-3 px-4",children:[o.jsx(Ld,{title:"Instructions",subtitle:"Write your scorer's system prompt."}),o.jsx($s,{name:"instructions",control:t,render:({field:n})=>o.jsx("div",{className:"flex flex-1 flex-col",children:o.jsx(Gr,{value:n.value??"",onChange:n.onChange,language:"markdown",showCopyButton:!1,placeholder:"Enter scorer instructions...",className:"min-h-[200px] flex-1"})})})]})}const ZVr=async e=>{const t={};return!e.name||e.name.trim()===""?t.name={type:"required",message:"Name is required"}:e.name.length>100&&(t.name={type:"maxLength",message:"Name must be 100 characters or less"}),e.description&&e.description.length>500&&(t.description={type:"maxLength",message:"Description must be 500 characters or less"}),(!e.model?.provider||e.model.provider.trim()==="")&&(t["model.provider"]={type:"required",message:"Provider is required"}),(!e.model?.name||e.model.name.trim()==="")&&(t["model.name"]={type:"required",message:"Model is required"}),(!e.instructions||e.instructions.trim()==="")&&(t.instructions={type:"required",message:"Instructions are required"}),{values:Object.keys(t).length===0?e:{},errors:Object.keys(t).length>0?t:{}}};function fLt(e={}){const{initialValues:t}=e;return{form:dS({resolver:ZVr,defaultValues:{name:t?.name??"",description:t?.description??"",type:t?.type??"llm-judge",model:t?.model??{provider:"",name:""},instructions:t?.instructions??"",scoreRange:t?.scoreRange??{min:0,max:1},defaultSampling:t?.defaultSampling}})}}const GVr=["llm-judge"],QVr=wke("type",[ws({type:$x("none")}),ws({type:$x("ratio"),rate:pf().min(0).max(1)})]);ws({name:cr().min(1,"Name is required").max(100,"Name must be 100 characters or less"),description:cr().max(500,"Description must be 500 characters or less"),type:qy(GVr),model:ws({provider:cr(),name:cr()}),instructions:cr(),scoreRange:ws({min:pf(),max:pf()}),defaultSampling:QVr.optional()});const hLt=(e,t)=>{const n=Ye(),{requestContext:r}=ys();return mt({queryKey:["stored-scorer",e,t?.status,r],queryFn:()=>e?n.getStoredScorer(e).details(r,t):null,enabled:!!e})},Sje=e=>{const t=Ye(),n=Ar(),{requestContext:r}=ys(),s=Sn({mutationFn:l=>t.createStoredScorer(l),onSuccess:()=>{n.invalidateQueries({queryKey:["stored-scorers"]}),n.invalidateQueries({queryKey:["scorers"]})}}),a=Sn({mutationFn:l=>{if(!e)throw new Error("scorerId is required for update");return t.getStoredScorer(e).update(l,r)},onSuccess:()=>{n.invalidateQueries({queryKey:["stored-scorers"]}),n.invalidateQueries({queryKey:["scorers"]}),e&&n.invalidateQueries({queryKey:["stored-scorer",e]})}}),i=Sn({mutationFn:()=>{if(!e)throw new Error("scorerId is required for delete");return t.getStoredScorer(e).delete(r)},onSuccess:()=>{n.invalidateQueries({queryKey:["stored-scorers"]}),n.invalidateQueries({queryKey:["scorers"]}),e&&n.invalidateQueries({queryKey:["stored-scorer",e]})}});return{createStoredScorer:s,updateStoredScorer:a,deleteStoredScorer:i}},V1=({children:e,leftSlot:t})=>o.jsxs("div",{className:"grid h-full grid-cols-[auto_1fr] overflow-y-auto",children:[o.jsx("div",{className:"border-border1 bg-surface3 h-full overflow-y-auto border-r",children:t}),o.jsx("div",{className:"h-full overflow-y-auto py-4",children:e})]});function YVr({onSuccess:e}){const{createStoredScorer:t}=Sje(),n=g.useRef(null),{form:r}=fLt(),s=async()=>{if(!await r.trigger()){Ve.error("Please fill in all required fields");return}const i=r.getValues();try{const l={name:i.name,description:i.description||void 0,type:i.type,model:i.model,instructions:i.instructions||void 0,scoreRange:i.scoreRange,defaultSampling:i.defaultSampling?.type==="ratio"&&typeof i.defaultSampling.rate=="number"?i.defaultSampling:{type:"none"}},c=await t.mutateAsync(l);Ve.success("Scorer created successfully"),e?.(c)}catch(l){Ve.error(`Failed to create scorer: ${l instanceof Error?l.message:"Unknown error"}`)}};return o.jsx(V1,{leftSlot:o.jsx(uLt,{form:r,onPublish:s,isSubmitting:t.isPending,formRef:n}),children:o.jsx("form",{ref:n,className:"h-full",children:o.jsx(dLt,{form:r})})})}const KVr=3e3;function XVr(e){return z4(e.state.error,"scores")||B4(e.state.error)?!1:KVr}const kje=({traceId:e="",spanId:t="",page:n})=>{const r=Ye();return mt({queryKey:["trace-span-scores",e,t,n],queryFn:()=>r.listScoresBySpan({traceId:e,spanId:t,page:n||0,perPage:10}),enabled:!!e&&!!t,refetchInterval:XVr,gcTime:0,staleTime:0})},pLt=({scorerId:e,params:t})=>{const n=Ye(),{requestContext:r}=ys();return mt({queryKey:["scorer-versions",e,t,r],queryFn:()=>n.getStoredScorer(e).listVersions(t,r),enabled:!!e})},JVr=({scorerId:e,versionId:t})=>{const n=Ye(),{requestContext:r}=ys();return mt({queryKey:["scorer-version",e,t,r],queryFn:()=>n.getStoredScorer(e).getVersion(t,r),enabled:!!e&&!!t})};function eHr(e){const t=Ye(),n=Zl(),r=e?.start||e?.end?e:void 0;return mt({queryKey:["score-metrics",n,r?.start?.toISOString(),r?.end?.toISOString()],queryFn:async()=>{const s=await t.listScorers(n),a=Object.keys(s??{});if(a.length===0)return{summaryData:[],overTimeData:[],scorerNames:[],avgScore:null,prevAvgScore:null};const i=await Promise.all(a.map(async N=>{const I=[];let A=0;for(;;){const P=await t.listScores({filters:{scorerId:N,timestamp:r},pagination:{page:A,perPage:100},orderBy:{field:"timestamp",direction:"DESC"}});if(I.push(...P.scores),!P.pagination?.hasMore)break;A++}return I})),l=[];for(const N of i)for(const I of N)l.push({scorerId:I.scorerId,score:I.score,timestamp:typeof I.timestamp=="string"?I.timestamp:new Date(I.timestamp).toISOString()});if(l.length===0)return{summaryData:[],overTimeData:[],scorerNames:[],avgScore:null,prevAvgScore:null};const c=[...l].sort((N,I)=>new Date(N.timestamp).getTime()-new Date(I.timestamp).getTime()),u=Math.floor(c.length/2),d=c.slice(0,u),f=new Map;for(const N of l)f.has(N.scorerId)||f.set(N.scorerId,[]),f.get(N.scorerId).push(N.score);const h=Array.from(f.entries()).map(([N,I])=>({scorer:N,avg:I.reduce((A,P)=>A+P,0)/I.length,min:Math.min(...I),max:Math.max(...I),count:I.length})),p=h.map(N=>N.scorer),m=h.reduce((N,I)=>N+I.avg,0)/h.length;let v=null;if(d.length>0){const N=new Map;for(const A of d)N.has(A.scorerId)||N.set(A.scorerId,[]),N.get(A.scorerId).push(A.score);const I=Array.from(N.values()).map(A=>A.reduce((P,L)=>P+L,0)/A.length);v=I.reduce((A,P)=>A+P,0)/I.length,v=Math.round(v*100)/100}const y=l.map(N=>new Date(N.timestamp).getTime()),b=Math.max(...y)-Math.min(...y);let x;b<36e5?x=6e4:b<864e5?x=36e5:x=864e5;const w=new Map;for(const N of l){const I=new Date(N.timestamp),A=Math.floor(I.getTime()/x)*x;w.has(A)||w.set(A,new Map);const P=w.get(A);P.has(N.scorerId)||P.set(N.scorerId,[]),P.get(N.scorerId).push(N.score)}const k=Array.from(w.entries()).sort(([N],[I])=>N-I),C=k.length>0?k[0][0]:0,T=((k.length>0?k[k.length-1][0]:0)-C)/864e5,E=k.map(([N,I])=>{const A=new Date(N);let P;T>1?P=A.toLocaleDateString("en-US",{month:"short",day:"numeric"})+" "+A.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}):P=A.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1});const L={time:P};for(const D of p){const B=I.get(D);B&&B.length>0&&(L[D]=+(B.reduce((H,q)=>H+q,0)/B.length).toFixed(2))}return L});return{summaryData:h,overTimeData:E,scorerNames:p,avgScore:Math.round(m*100)/100,prevAvgScore:v}}})}function tHr(e){return new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})}function nHr({scorerId:e,value:t,onValueChange:n,className:r,disabled:s=!1,variant:a,activeVersionId:i}){const{data:l,isLoading:c}=pLt({scorerId:e,params:{orderBy:{direction:"DESC"}}}),u=l?.versions??[],f=(i?u.find(p=>p.id===i):void 0)?.versionNumber,h=[{label:"Latest",value:""},...u.map(p=>{const m=p.id===i,v=f!==void 0&&p.versionNumber>f;return{label:`v${p.versionNumber}`,value:p.id,description:tHr(p.createdAt),end:m?o.jsx(bt,{variant:"green",children:"Published"}):v?o.jsx(bt,{variant:"blue",children:"Draft"}):void 0}})];return o.jsx(vl,{options:h,value:t,onValueChange:n,placeholder:c?"Loading versions...":"Versions",searchPlaceholder:"Search versions...",emptyText:"No versions found.",className:r,disabled:s||c,variant:a})}const yh="mastra_workspace",Uv={FILESYSTEM:{READ_FILE:`${yh}_read_file`,WRITE_FILE:`${yh}_write_file`,EDIT_FILE:`${yh}_edit_file`,LIST_FILES:`${yh}_list_files`,DELETE:`${yh}_delete`,FILE_STAT:`${yh}_file_stat`,MKDIR:`${yh}_mkdir`},SANDBOX:{EXECUTE_COMMAND:`${yh}_execute_command`,GET_PROCESS_OUTPUT:`${yh}_get_process_output`,KILL_PROCESS:`${yh}_kill_process`},SEARCH:{SEARCH:`${yh}_search`,INDEX:`${yh}_index`}},mLt=g.createContext(void 0),rHr=()=>{};function Oje(){const e=g.useContext(mLt);if(!e)throw new Error("ToolCall compounds must be rendered within ToolCall");return e}function sHr({open:e,defaultOpen:t=!1,onOpenChange:n=rHr,status:r="idle",className:s,children:a,...i}){const[l,c]=g.useState(t),u=e??l,d=g.useId(),f=h=>{e===void 0&&c(h),n(h)};return o.jsx(mLt.Provider,{value:{open:u,status:r},children:o.jsxs(fc,{open:u,onOpenChange:f,className:K("max-w-full min-w-0",s),role:"group","aria-busy":r==="running","aria-invalid":r==="error"||void 0,"aria-describedby":r==="idle"?void 0:d,"data-status":r,...i,children:[a,r!=="idle"&&o.jsx("span",{id:d,className:"sr-only",children:r==="running"?"Tool call running":"Tool call failed"})]})})}const aHr=({className:e,...t})=>o.jsx(ql,{className:K("group/row w-full cursor-pointer rounded-md text-left transition-colors hover:bg-neutral6/5 focus-visible:ring-1 focus-visible:ring-accent1 focus-visible:outline-hidden motion-reduce:transition-none",e),...t}),gLt=({className:e,children:t,...n})=>{const{status:r}=Oje();return o.jsx(I3t,{active:r==="running",className:K("flex w-full min-w-0 items-center gap-2 px-1.5 py-1",e),...n,children:t})},vLt=({className:e,...t})=>o.jsx("span",{className:K("flex size-4 shrink-0 items-center justify-center",e),...t}),yLt=({className:e,...t})=>o.jsx(ve,{as:"span",variant:"ui-sm",className:K("text-icon3 max-w-[55%] shrink-0 truncate",e),...t}),bLt=({className:e,...t})=>{const n=y3t();return o.jsx(ve,{as:"span",variant:"ui-xs",font:"mono",className:K("text-icon3 min-w-0 truncate",n,e),...t})},xLt=({rule:e,className:t,...n})=>o.jsx("span",{"aria-hidden":!0,className:K("min-w-2 flex-1",e&&"h-px bg-border1 mask-r-from-[calc(100%-min(100%,160px))]",t),...n}),yxe=({className:e,...t})=>o.jsx("span",{className:K("flex shrink-0 items-center",e),...t}),wLt=({className:e,children:t,...n})=>{const{open:r}=Oje();return o.jsx("span",{className:K("flex size-4 shrink-0 items-center justify-center",e),...n,children:o.jsx("span",{"aria-hidden":!0,className:K("text-icon3 flex shrink-0 items-center opacity-0 transition duration-150 motion-reduce:transition-none","group-hover/row:opacity-100 group-focus-visible/row:opacity-100",r&&"rotate-90 opacity-100"),children:t??o.jsx(Lr,{size:13})})})},iHr=({leading:e,icon:t,label:n,detail:r,disclosure:s=!0,...a})=>{const{status:i}=Oje();return o.jsxs(gLt,{...a,children:[e,o.jsx(vLt,{children:o.jsx(t,{size:14,strokeWidth:1.75,"aria-hidden":!0,className:i==="error"?"text-error/80":"text-icon2"})}),o.jsx(yLt,{children:n}),r&&o.jsx(bLt,{children:r}),o.jsx(xLt,{}),i==="error"&&o.jsx(yxe,{children:o.jsx(or,{size:13,role:"img","aria-label":"Failed",className:"text-error shrink-0"})}),s&&o.jsx(wLt,{})]})},oHr=({className:e,children:t,...n})=>o.jsx(Vl,{className:"max-w-full min-w-0",...n,children:o.jsx("div",{className:K("relative ml-[14px] flex max-w-full min-w-0 flex-col gap-1.5 py-1.5 pr-1 pl-4 before:absolute before:inset-y-0 before:left-0 before:w-px before:bg-border1 before:mask-b-from-[calc(100%-min(40%,80px))] before:content-['']",e),children:t})}),l2=({copyText:e,className:t,children:n,...r})=>o.jsxs("div",{className:"group/block relative max-w-full min-w-0",children:[o.jsx("pre",{className:K("m-0 max-h-60 max-w-full overflow-auto rounded-md bg-neutral6/5 px-3 py-2 font-mono text-xs leading-normal break-words whitespace-pre-wrap",t),...r,children:n}),o.jsx(_a,{content:e,size:"sm",variant:"ghost",className:"absolute top-1 right-1 opacity-0 transition-opacity group-hover/block:opacity-100 focus-visible:opacity-100"})]});function bxe(e){if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}function lHr(e,t){return t in e}function cHr(e,t){if(!e||typeof e!="object"||!lHr(e,t))return;const n=e[t];return typeof n=="number"?String(n):typeof n=="string"&&n.length>0?n:void 0}function uHr(e,t){for(const n of t){const r=cHr(e,n);if(r)return r}}const dHr={view:{icon:ac,label:"Read",detailKeys:["path"]},read_file:{icon:ac,label:"Read",detailKeys:["path"]},write_file:{icon:fE,label:"Write",detailKeys:["path"]},create_file:{icon:fE,label:"Write",detailKeys:["path"]},edit_file:{icon:fE,label:"Edit",detailKeys:["path"]},string_replace:{icon:fE,label:"Edit",detailKeys:["path"]},str_replace:{icon:fE,label:"Edit",detailKeys:["path"]},ast_edit:{icon:fE,label:"Edit",detailKeys:["path"]},execute_command:{icon:Qct,label:"Run",detailKeys:["command"],isCommand:!0},get_process_output:{icon:Sen,label:"Process output",detailKeys:["pid"]},kill_process:{icon:C0e,label:"Stop process",detailKeys:["pid"]},find_files:{icon:_Me,label:"Find files",detailKeys:["pattern","path"]},list_files:{icon:_Me,label:"List files",detailKeys:["pattern","path"]},grep:{icon:Ds,label:"Search",detailKeys:["pattern","path"]},search_content:{icon:Ds,label:"Search",detailKeys:["pattern","query"]},search:{icon:Ds,label:"Search",detailKeys:["query"]},web_search:{icon:Ry,label:"Search the web",detailKeys:["query"]},lsp_inspect:{icon:sc,label:"Inspect code",detailKeys:["path"]},file_stat:{icon:GKt,label:"File info",detailKeys:["path"]},delete:{icon:Fl,label:"Delete",detailKeys:["path"]},delete_file:{icon:Fl,label:"Delete",detailKeys:["path"]},mkdir:{icon:JD,label:"New folder",detailKeys:["path"]},skill:{icon:k$,label:"Skill",detailKeys:["name"]},skill_search:{icon:k$,label:"Search skills",detailKeys:["query"]},skill_read:{icon:k$,label:"Skill file",detailKeys:["path"]}};function fHr(e){const t=e.replace(/[_-]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function hHr(e){return e.replace(/^\s*cd\s+(?:'[^']*'|"[^"]*"|[^\s&|;]+)\s*&&\s*/,"")||e}function pHr(e,t){const n=dHr[e.replace(/^mastra_workspace_/,"")];if(!n)return{icon:Ud,label:fHr(e)};const r=n.detailKeys?uHr(t,n.detailKeys):void 0;return r?n.isCommand?{icon:n.icon,label:n.label,detail:hHr(r),command:r}:{icon:n.icon,label:n.label,detail:r}:{icon:n.icon,label:n.label}}const SLt=g.createContext({messages:[]}),kLt=g.createContext({isRunning:!1,cancelRun:()=>{},canSendWhileStreaming:!1}),OLt=g.createContext({send:()=>{}}),CLt=g.createContext({tasks:[]}),_Lt=g.createContext(void 0),mHr=()=>g.useContext(SLt).messages,rL=()=>g.useContext(kLt),Cje=()=>g.useContext(OLt).send,gHr=()=>g.useContext(CLt).tasks,sL=({children:e,initialCollapsed:t=!0,icon:n,title:r,detail:s,collapsible:a=!0,extraInfo:i,header:l,status:c="idle","data-testid":u})=>{const[d,f]=g.useState(!t),{isRunning:h}=rL(),[p]=g.useState(()=>h);g.useEffect(()=>{f(!t)},[t]);const m=l??o.jsxs(gLt,{children:[o.jsx(vLt,{children:n}),o.jsx(yLt,{children:r}),s&&o.jsx(bLt,{children:s}),o.jsx(xLt,{}),c==="error"&&o.jsx(yxe,{children:o.jsx(or,{size:13,role:"img","aria-label":"Failed",className:"text-error shrink-0"})}),a&&o.jsx(wLt,{})]}),v=!a||d;return o.jsxs(sHr,{open:v,onOpenChange:f,status:c,className:K(p&&"motion-safe:animate-in fade-in-0 slide-in-from-bottom-1"),"data-testid":u,children:[o.jsxs("span",{className:"flex w-full min-w-0 items-center",children:[a?o.jsx(aHr,{className:"min-w-0 flex-1",children:m}):o.jsx("span",{className:"min-w-0 flex-1",children:m}),i&&o.jsx(yxe,{className:"gap-1 pr-1",children:i})]}),o.jsx(oHr,{children:e})]})},_je=()=>o.jsx(sL,{icon:o.jsx(Vt,{className:"text-neutral3"}),title:o.jsx(Et,{className:"ml-2 h-2 w-12"}),collapsible:!1}),vHr=({agents:e})=>{const{Link:t,paths:n}=dn();return e.length===0?o.jsx(SS,{children:"No agents"}):o.jsx(wS,{children:e.map(r=>o.jsx(Zx,{children:o.jsx(t,{href:n.agentLink(r.id),"data-testid":"agent-badge",children:o.jsx(bt,{variant:"green",icon:o.jsx(Ri,{}),children:r.name})})},r.id))})},yHr=({agentId:e})=>{const{data:t,isLoading:n}=Yl(e),{mutate:r}=n2r(e),{mutateAsync:s}=r2r(e),a=o0(),{isCmsAvailable:i,isLoading:l}=kS();if(n)return o.jsx(Et,{className:"h-full"});if(!t)return o.jsx("div",{children:"Agent not found"});const c=t.agents??{},u=Object.keys(c).map(k=>({...c[k],id:k})),d=t.tools??{},f=Object.keys(d).map(k=>d[k]),h=t.workflows??{},p=Object.keys(h).map(k=>({id:k,...h[k]})),m=t.skills??[],v=t.workspaceTools??[],y=t.browserTools??[],b=t.workspaceId,x=t.inputProcessors??[],w=t.outputProcessors??[];return o.jsxs("div",{className:"flex flex-col gap-4","data-testid":"agent-metadata",children:[t.modelList&&o.jsxs(Ku,{className:"bg-surface3",children:[o.jsx(gj,{children:o.jsx(om,{children:"Models"})}),o.jsx(lm,{children:o.jsx(XBr,{modelList:t.modelList,updateModelInModelList:s,reorderModelList:r})})]}),o.jsxs(Ku,{className:"bg-surface3",children:[o.jsxs(gj,{className:"flex-row items-baseline gap-2 space-y-0",children:[o.jsx(om,{children:"Capabilities"}),o.jsx(n1,{children:"Everything this agent can call at runtime"})]}),o.jsxs(lm,{children:[u.length>0&&o.jsx(iw,{title:o.jsx(FE,{title:"Agents",count:u.length}),hint:{link:"https://mastra.ai/en/docs/agents/overview",title:"Agents documentation"},children:o.jsx(vHr,{agents:u})}),o.jsx(iw,{title:o.jsx(FE,{title:"Tools",count:f.length}),hint:{link:"https://mastra.ai/en/docs/agents/using-tools-and-mcp",title:"Using Tools and MCP documentation"},children:o.jsx(bHr,{tools:f,agentId:e})}),o.jsx(iw,{title:o.jsx(FE,{title:"Workflows",count:p.length}),hint:{link:"https://mastra.ai/en/docs/workflows/overview",title:"Workflows documentation"},children:o.jsx(xHr,{workflows:p})}),v.length>0&&o.jsx(iw,{title:o.jsx(FE,{title:"Workspace Tools",count:v.length}),hint:{link:"https://mastra.ai/en/reference/workspace/workspace-class#agent-tools",title:"Workspace tools documentation"},children:o.jsx(OHr,{tools:v})}),y.length>0&&o.jsx(iw,{title:o.jsx(FE,{title:"Browser Tools",count:y.length}),hint:{link:"https://mastra.ai/en/docs/agents/adding-browser-control",title:"Browser tools documentation"},children:o.jsx(CHr,{tools:y})}),(x.length>0||w.length>0)&&o.jsx(iw,{title:"Processors",hint:{link:"https://mastra.ai/docs/agents/processors",title:"Processors documentation"},children:o.jsx(_Hr,{inputProcessors:x,outputProcessors:w})}),o.jsx(iw,{title:o.jsx(FE,{title:"Skills",count:m.length}),hint:{link:"https://mastra.ai/en/docs/workspace/skills",title:"Skills documentation"},children:o.jsx(SHr,{skills:m,agentId:e,workspaceId:b})}),o.jsx(iw,{title:"Scorers",children:o.jsx(wHr,{entityId:t.name,entityType:"AGENT"})})]})]}),o.jsxs(Ku,{className:"bg-surface3",children:[o.jsx(gj,{children:o.jsx(om,{children:"System Prompt"})}),o.jsxs(lm,{className:"space-y-3",children:[o.jsx(rd,{className:"border-border1 rounded-md border",value:X4(t.instructions),editable:!1,extensions:[wOe({base:rC,codeLanguages:AOt}),Pt.lineWrapping],theme:a}),!l&&!i&&o.jsx(Rn,{variant:"warning",title:"Read-only",children:o.jsxs(Rn.Message,{children:["To edit the system prompt in Studio, add ",o.jsx("code",{className:"font-medium",children:"@mastra/editor"})," to your project. See the"," ",o.jsx("a",{href:"https://mastra.ai/docs/editor/overview",target:"_blank",rel:"noopener noreferrer",className:"underline",children:"documentation"}),"."]})})]})]})]})},FE=({title:e,count:t})=>o.jsxs("span",{className:"flex items-center gap-1.5",children:[e,o.jsx(bt,{variant:"neutral",children:t})]}),bHr=({tools:e,agentId:t})=>{const{Link:n,paths:r}=dn();return e.length===0?o.jsx(SS,{children:"No tools"}):o.jsx(wS,{children:e.map(s=>o.jsx(Zx,{children:o.jsx(n,{href:r.agentToolLink(t,s.id),"data-testid":"tool-badge",children:o.jsx(bt,{icon:o.jsx(Bf,{className:"text-accent6"}),children:s.id})})},s.id))})},xHr=({workflows:e})=>{const{Link:t,paths:n}=dn();return e.length===0?o.jsx(SS,{children:"No workflows"}):o.jsx(wS,{children:e.map(r=>o.jsx(Zx,{children:o.jsx(t,{href:n.workflowLink(r.id),"data-testid":"workflow-badge",children:o.jsx(bt,{icon:o.jsx(Bc,{className:"text-accent3"}),children:r.name})})},r.id))})},wHr=({entityId:e,entityType:t})=>{const{Link:n,paths:r}=dn(),{data:s={},isLoading:a}=up(),i=Object.keys(s).filter(l=>{const c=s[l];return t==="AGENT"?c.agentNames?.includes?.(e):c.workflowIds.includes(e)}).map(l=>({...s[l],id:l}));return a?o.jsx(_je,{}):i.length===0?o.jsx(SS,{children:"No Scorers"}):o.jsx(wS,{children:i.map(l=>o.jsx(Zx,{children:o.jsx(n,{href:r.scorerLink(l.id),"data-testid":"scorer-badge",children:o.jsx(bt,{icon:o.jsx(Qh,{className:"text-neutral3"}),children:l.scorer.config.name})})},l.id))})},SHr=({skills:e,agentId:t,workspaceId:n})=>{const{Link:r,paths:s}=dn(),{isSkillActivated:a}=U4t();return e.length===0?o.jsx(SS,{children:"No skills"}):o.jsx(wS,{children:e.map(i=>{const l=a(i.name),c=o.jsxs(bt,{icon:o.jsx(b_,{className:`h-3 w-3 ${l?"text-green-400":"text-accent2"}`}),variant:l?"green":"neutral",children:[i.name,l&&o.jsx("span",{className:"sr-only",children:"Active"})]});return o.jsx(Zx,{children:l?o.jsx(Wl,{children:o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx(r,{href:s.agentSkillLink(t,i.name,i.path,n),"data-testid":"skill-badge",children:c})}),o.jsx(yn,{className:"bg-surface3 text-neutral6 border-border1 border",children:"Active"})]})}):o.jsx(r,{href:s.agentSkillLink(t,i.name,i.path,n),"data-testid":"skill-badge",children:c})},i.path)})})};function kHr(e){const t=`${yh}_`;return e.startsWith(t)?e.slice(t.length):e}const OHr=({tools:e})=>e.length===0?o.jsx(SS,{children:"No workspace tools"}):o.jsx(wS,{children:e.map(t=>o.jsx(Zx,{children:o.jsx(bt,{icon:o.jsx(cI,{className:"text-accent1 h-3 w-3"}),children:kHr(t)})},t))}),CHr=({tools:e})=>e.length===0?o.jsx(SS,{children:"No browser tools"}):o.jsx(wS,{children:e.map(t=>o.jsx(Zx,{children:o.jsx(bt,{icon:o.jsx(Ry,{className:"h-3 w-3 text-cyan-500"}),children:t})},t))}),_Hr=({inputProcessors:e,outputProcessors:t})=>{const{Link:n,paths:r}=dn();if(e.length===0&&t.length===0)return o.jsx(SS,{children:"No processors"});const s=e[0]?.id,a=t[0]?.id;return o.jsxs(wS,{children:[e.length>0&&s&&o.jsx(Zx,{children:o.jsx(n,{href:`${r.workflowLink(s)}/graph`,"data-testid":"processor-badge",children:o.jsx(bt,{icon:o.jsx(jD,{className:"text-accent4"}),children:"input"})})}),t.length>0&&a&&o.jsx(Zx,{children:o.jsx(n,{href:`${r.workflowLink(a)}/graph`,"data-testid":"processor-badge",children:o.jsx(bt,{icon:o.jsx(jD,{className:"text-accent5"}),children:"output"})})})]})},O_=e=>{const t=Ye(),n=Zl();return mt({queryKey:["memory",e,n],queryFn:()=>e?t.getMemoryStatus(e,n):null,enabled:!!e,staleTime:300*1e3,gcTime:600*1e3,retry:!1})},OS=e=>{const t=Ye(),n=Zl();return mt({queryKey:["memory","config",e,n],queryFn:()=>e?t.getMemoryConfig({agentId:e,requestContext:n}):null,enabled:!!e,staleTime:300*1e3,gcTime:600*1e3,retry:!1,refetchOnWindowFocus:!1})},Eje=({threadId:e,agentId:t})=>{const n=Ye(),r=Zl();return mt({queryKey:["memory","thread",e,t,r],queryFn:()=>n.getMemoryThread({threadId:e,agentId:t}).get({requestContext:r}),enabled:!!e&&e!=="new"&&!!t,staleTime:300*1e3,gcTime:600*1e3,retry:!1,refetchOnWindowFocus:!1})},ELt=({resourceId:e,agentId:t,isMemoryEnabled:n})=>{const r=Ye(),s=Zl();return mt({queryKey:["memory","threads",e,t,s],queryFn:async()=>n?(await r.listMemoryThreads({resourceId:e,agentId:t,requestContext:s})).threads:null,enabled:!!n,staleTime:0,gcTime:0,retry:!1,refetchOnWindowFocus:!1})},EHr=()=>{const e=Ye(),t=Ar(),n=Zl();return Sn({mutationFn:({threadId:r,agentId:s})=>e.getMemoryThread({threadId:r,agentId:s}).delete({requestContext:n}),onSuccess:(r,s)=>{const{agentId:a}=s;a&&t.invalidateQueries({queryKey:["memory","threads",a,a]}),Ve.success("Chat deleted successfully")},onError:()=>{Ve.error("Failed to delete chat")}})},THr=({agentId:e,resourceId:t,threadId:n})=>{const r=Zl(),s=Ye();return Sn({mutationFn:async({searchQuery:a,memoryConfig:i})=>s.searchMemory({agentId:e,resourceId:t,threadId:n,searchQuery:a,memoryConfig:i,requestContext:r})})},jHr=()=>{const e=Ye(),t=Ar(),n=Zl();return Sn({mutationFn:async({threadId:r,agentId:s,title:a})=>e.getMemoryThread({threadId:r,agentId:s}).clone({title:a,requestContext:n}),onSuccess:(r,s)=>{const{agentId:a}=s;a&&t.invalidateQueries({queryKey:["memory","threads",a,a]}),Ve.success("Thread cloned successfully")},onError:()=>{Ve.error("Failed to clone thread")}})},NHr=({agentId:e,resourceId:t,threadId:n,enabled:r=!0,isActive:s=!1})=>{const a=Ye(),i=Zl();return mt({queryKey:["observational-memory",e,t,n,i],queryFn:async()=>!t&&!n?null:a.getObservationalMemory({agentId:e,resourceId:t,threadId:n,requestContext:i}),enabled:r&&!!e&&(!!t||!!n),staleTime:s?1e3:30*1e3,gcTime:300*1e3,retry:!1,refetchOnWindowFocus:!1,refetchInterval:s?2e3:!1,placeholderData:l=>l})},TLt=({agentId:e,resourceId:t,threadId:n,pollWhenActive:r=!0})=>{const s=Ye(),a=Zl(),[i,l]=g.useState(!1),c=mt({queryKey:["memory-status",e,t,n,a],queryFn:()=>e?s.getMemoryStatus(e,a,{resourceId:t,threadId:n}):null,enabled:!!e,staleTime:i&&r?1e3:30*1e3,gcTime:300*1e3,retry:!1,refetchOnWindowFocus:!1,refetchInterval:i&&r?2e3:!1,placeholderData:f=>f}),u=c.data?.observationalMemory?.isObserving,d=c.data?.observationalMemory?.isReflecting;return g.useEffect(()=>{l(u||d||!1)},[u,d]),c},uXe=e=>e===void 0?"Default":typeof e=="number"?`${e.toLocaleString()} tokens`:`${e.min.toLocaleString()}-${e.max.toLocaleString()} tokens`,dXe={success:"green",info:"blue",warning:"yellow"};function IHr({value:e,badge:t}){return typeof e=="boolean"?o.jsx(bt,{size:"xs",indicator:"dot",variant:e?t?dXe[t]:"green":"red",children:e?"Yes":"No"}):t?o.jsx(bt,{size:"xs",variant:dXe[t],children:e}):o.jsx(o.Fragment,{children:e})}const AHr=({agentId:e})=>{const{data:t,isLoading:n}=OS(e),r=t?.config,s=g.useMemo(()=>{if(!r)return[];const a=!!r,i=[{title:"General",items:[{label:"Memory Enabled",value:a,badge:a?"success":void 0},{label:"Last Messages",value:r.lastMessages||0},{label:"Auto-generate Titles",value:!!r.generateTitle,badge:r.generateTitle?"info":void 0}]}];if(r.semanticRecall){const d=!!r.semanticRecall,f=typeof r.semanticRecall=="object"?r.semanticRecall:{};i.push({title:"Semantic Recall",items:[{label:"Enabled",value:d,badge:d?"success":void 0},...d?[{label:"Scope",value:f.scope||"resource"},{label:"Top K Results",value:f.topK||4},{label:"Message Range",value:typeof f.messageRange=="object"?`${f.messageRange.before||1} before, ${f.messageRange.after||1} after`:f.messageRange!==void 0?`${f.messageRange} before, ${f.messageRange} after`:"1 before, 1 after"}]:[]]})}const l=r.observationalMemory,c=l!==null&&typeof l=="object";if(l===!0||c&&l.enabled!==!1){const d=c?l.observationModel||l.model||l.observation?.model:void 0,f=c?l.reflectionModel||l.model||l.reflection?.model:void 0;i.push({title:"Observational Memory",items:[{label:"Enabled",value:!0,badge:"success"},{label:"Scope",value:c&&l.scope||"thread"},{label:"Message Tokens",value:uXe(c?l.observation?.messageTokens:void 0)},{label:"Observation Tokens",value:uXe(c?l.reflection?.observationTokens:void 0)},...d?[{label:"Observation Model",value:String(d)}]:[],...f?[{label:"Reflection Model",value:String(f)}]:[]]})}return i},[r]);return n?o.jsx("div",{className:"p-4",children:o.jsx(Et,{className:"h-32 w-full"})}):!r||s.length===0?o.jsx("div",{className:"p-4",children:o.jsx(ve,{variant:"ui-xs",className:"text-neutral3",children:"No memory configuration available"})}):o.jsx("div",{className:"divide-border1 divide-y pt-1.5 pb-2",children:s.map(a=>o.jsxs(fc,{defaultOpen:a.title!=="Observational Memory",children:[o.jsxs(ql,{className:"text-neutral5 flex w-full items-center justify-between px-4 py-2.5",children:[o.jsx(ve,{as:"span",variant:"ui-md",className:"font-medium text-inherit",children:a.title}),o.jsx(Lr,{className:"text-neutral3 size-4"})]}),o.jsx(Vl,{className:"px-4 pb-3",children:o.jsx(xje,{data:a.items.map(i=>({key:`${a.title}-${i.label}`,label:i.label,value:o.jsx(IHr,{value:i.value??"",badge:i.badge})}))})})]},a.title))})};function RHr({agentId:e}){const{data:t}=nG(),n=!!t?.length;return o.jsx("div",{className:"h-full w-full min-w-0","data-testid":"agent-settings-view",children:o.jsx(Nr,{className:"h-full w-full",viewPortClassName:"h-full",mask:{top:!1},children:o.jsxs("div",{className:"grid grid-cols-1 items-start gap-4 px-5 py-4 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]",children:[o.jsx(yHr,{agentId:e}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs(Ku,{className:"bg-surface3",children:[o.jsx(gj,{children:o.jsx(om,{children:"Memory"})}),o.jsx(lm,{className:"p-0",children:o.jsx(AHr,{agentId:e})})]}),n&&o.jsxs(Ku,{className:"bg-surface3",children:[o.jsx(gj,{children:o.jsx(om,{children:"Channels"})}),o.jsx(lm,{children:o.jsx(ZBr,{agentId:e})})]})]})]})})})}const PHr=({agentId:e})=>{const{data:t,isLoading:n}=Yl(e),{handleCopy:r,isCopied:s}=Ff({text:e}),a=t?.name||"";return o.jsx(Wl,{children:o.jsx("div",{className:"min-w-0 overflow-x-hidden p-3",children:o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsxs("button",{type:"button",onClick:r,"aria-label":"Copy Agent ID for use in code",className:"group/agent-title text-neutral6 flex max-w-full min-w-0 cursor-pointer items-center gap-2","data-testid":"agent-entity-header-copy-id",children:[o.jsx("span",{className:"flex size-7 shrink-0 items-center justify-center",children:o.jsx(Qe,{size:"lg",children:o.jsx(Ri,{})})}),n?o.jsx(Et,{className:"h-3 w-32"}):o.jsx(ve,{variant:"header-md",as:"h2",className:"truncate font-medium",children:a}),s?o.jsx(Ur,{className:"text-neutral3 h-4 w-4 shrink-0"}):o.jsx(zd,{className:"text-neutral3 h-4 w-4 shrink-0"})]})}),o.jsx(yn,{children:"Copy Agent ID for use in code"})]})})})};function bG(e){const t=(window.MASTRA_STUDIO_BASE_PATH??"").replace(/\/$/,"");if(!t)return e;const n=new URL(e,window.location.origin);if(n.origin!==window.location.origin)return e;const r=`${n.pathname}${n.search}${n.hash}`;return n.pathname===t||n.pathname.startsWith(`${t}/`)?r:`${t}${n.pathname}${n.search}${n.hash}`}function $Hr({agentId:e}){const{data:t}=Yl(e),{canCreateAgent:n}=EMt(),{Link:r,paths:s}=dn(),a=`${window.location.origin}${bG(`/agents/${encodeURIComponent(e)}/session`)}`,{handleCopy:i,isCopied:l}=Ff({text:a,copyMessage:"Session URL copied to clipboard!"}),c=t?.source==="stored",u=s.cmsAgentEditLink(e),d=n&&c&&!!u;return o.jsx(Wl,{children:o.jsxs("div",{className:"flex items-start justify-between gap-2 pr-3 max-lg:py-2",children:[o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col max-lg:hidden",children:[o.jsx(PHr,{agentId:e}),t?.description&&o.jsx("p",{className:"text-neutral4 -mt-2 max-w-prose pr-3 pb-1 pl-12 text-sm",children:t.description})]}),o.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-2 py-2",children:[d&&o.jsxs(ie,{variant:"outline",size:"sm",as:r,to:u,children:[o.jsx(Qe,{size:"sm",children:o.jsx(Yh,{})}),"Edit"]}),o.jsxs(ie,{variant:"ghost",size:"sm",type:"button",onClick:i,tooltip:"Copy session URL to share with your team","data-testid":"agent-entity-header-share",children:[o.jsx(Qe,{size:"sm",children:l?o.jsx(Ur,{}):o.jsx(Dct,{})}),"Share"]}),o.jsxs(ie,{variant:"primary",size:"sm",as:r,to:s.agentNewThreadLink(e),"data-testid":"agent-view-header-new-chat",children:[o.jsx(Qe,{size:"sm",children:o.jsx(dJt,{})}),"Open chat"]})]})]})})}function MHr(){const{agentId:e}=fr(),{data:t,isLoading:n,error:r}=Yl(e);return r&&hs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{})}):r&&ps(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ks,{resource:"agents"})}):n?o.jsx(VBr,{}):t?o.jsx(pG,{children:o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[o.jsx($Hr,{agentId:e}),o.jsx("div",{className:"min-h-0 overflow-hidden",children:o.jsx(RHr,{agentId:e})})]})},e):o.jsx("div",{className:"py-4 text-center",children:"Agent not found"})}function vs({children:e,className:t,style:n}){const r=jLt("MainContentLayout"),s=KPt();return o.jsxs("main",{className:K("grid h-full grid-rows-[auto_1fr] content-start items-start",t),style:{...n,...r?{border:"3px dotted red"}:{}},children:[s&&o.jsx("h1",{className:"sr-only",children:s}),e]})}function by({children:e,className:t,isCentered:n=!1,isDivided:r=!1,hasLeftServiceColumn:s=!1,style:a}){const i=jLt("MainContentContent"),l=DHr({isCentered:n,isDivided:r,hasLeftServiceColumn:s,className:t});return o.jsx("div",{className:l,style:{...a,...i?{border:"3px dotted orange"}:{}},children:e})}const DHr=({isCentered:e,isDivided:t,hasLeftServiceColumn:n,className:r})=>K("grid h-full overflow-y-auto ","min-w-min overflow-x-auto",{"items-start content-start":!e&&!t&&!n,"grid place-items-center":e,"grid-cols-[1fr_1fr]":t&&!n,"grid-cols-[12rem_1fr_1fr]":t&&n,"grid-cols-[auto_1fr]":!t&&n},r);function jLt(e){try{const t=localStorage.getItem("add-dev-style-to-components");return t?t.split(",").map(r=>r.trim()).filter(Boolean).includes(e):!1}catch(t){return console.error("Error reading or parsing localStorage:",t),!1}}function NLt({config:e,redirectUri:t,className:n,loginUrl:r="/login"}){const{mutate:s,isPending:a}=rDt();if(!e)return null;if(e.type==="sso"||e.type==="both"&&e.sso){const l=e.sso,c=()=>{s({redirectUri:t},{onSuccess:u=>{window.location.href=u.url}})};return o.jsxs(ie,{onClick:c,disabled:a,className:n,children:[l?.icon&&o.jsx("span",{className:"mr-2",children:l.icon}),l?.text||"Sign in"]})}const i=()=>{const l=new URL(bG(r),window.location.origin);t&&l.searchParams.set("redirect",t),window.location.href=l.toString()};return o.jsx(ie,{onClick:i,className:n,children:"Sign in"})}function fXe({user:e,size:t="sm"}){if(!e)return null;const n=e.name||e.email||"User";return o.jsx(OC,{src:e.avatarUrl,name:n,size:t})}function LHr({user:e}){const[t,n]=g.useState(!1),{mutate:r,isPending:s}=U2r(),{data:a}=pc(),{isImpersonating:i,impersonatedRole:l,startImpersonation:c,stopImpersonation:u,isSwitching:d}=RH();if(!e)return null;const f=()=>{r(void 0,{onSuccess:m=>{m.redirectTo?window.location.href=m.redirectTo:window.location.reload()}})},h=a&&Am(a)?a.availableRoles:void 0,p=e.name||e.email||"User";return o.jsxs(Vf,{open:t,onOpenChange:n,children:[o.jsx(Xd,{asChild:!0,children:o.jsx("button",{type:"button",className:"hover:bg-surface2 flex items-center gap-2 rounded-md p-1 transition-colors",children:o.jsx(fXe,{user:e,size:"sm"})})}),o.jsxs(Jd,{align:"end",className:"w-64 p-0",children:[o.jsx("div",{className:"border-border1 border-b p-3",children:o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(fXe,{user:e,size:"md"}),o.jsxs("div",{className:"flex flex-col overflow-hidden",children:[o.jsx(ve,{variant:"ui-md",className:"truncate font-medium",children:p}),e.email&&o.jsx(ve,{variant:"ui-sm",className:"text-neutral3 truncate",children:e.email})]})]})}),h&&h.length>0&&o.jsxs("div",{className:"border-border1 border-b p-2",children:[o.jsx(ve,{variant:"ui-xs",className:"text-neutral3 px-2 py-1 tracking-wider uppercase",children:"Preview as role"}),h.map(m=>{const v=i&&l?.id===m.id;return o.jsxs("button",{type:"button",disabled:d,onClick:()=>{v?u():c(m),n(!1)},className:`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors ${v?"bg-surface2":"hover:bg-surface2"} ${d?"cursor-not-allowed opacity-50":""}`,children:[d&&o.jsx(Vs,{className:"h-3.5 w-3.5 animate-spin"}),o.jsx("span",{className:"flex-1 capitalize",children:m.name}),v&&o.jsx(or,{className:"text-neutral3 hover:text-neutral1 h-3.5 w-3.5"})]},m.id)})]}),o.jsxs("div",{className:"flex flex-col gap-1 p-2",children:[o.jsxs(ie,{as:Da,to:"/settings",variant:"ghost",className:"w-full justify-start",onClick:()=>n(!1),children:[o.jsx(Ij,{className:"h-4 w-4"}),"Settings"]}),o.jsx(ie,{variant:"ghost",onClick:f,disabled:s,className:"w-full justify-start",children:s?"Signing out...":"Sign out"})]})]})]})}function RD({className:e}){const{data:t,isLoading:n,error:r}=pc();return n||r||!t?.enabled?null:Am(t)?o.jsx(LHr,{user:t.user}):o.jsx(NLt,{config:t.login,redirectUri:typeof window<"u"?window.location.href:void 0,className:e})}const Ez="__custom__",ILt=()=>{const e=cwt(),{requestContext:t,setRequestContext:n}=ys(),r=g.useMemo(()=>{if(!e)return Ez;const a=JSON.stringify(t??{});for(const[i,l]of Object.entries(e))if(JSON.stringify(l)===a)return i;return Ez},[e,t]),s=a=>{if(a===Ez){n({});return}if(!e)return;const i=e[a];i&&n(i)};return o.jsxs(UH,{children:[o.jsxs(ESe,{children:[o.jsx(Wh,{className:"h-5 w-8 shrink-0"}),"Mastra Studio",o.jsx(RD,{})]}),e&&Object.keys(e).length>0&&o.jsx(Kbt,{children:o.jsxs(la,{value:r,onValueChange:s,children:[o.jsx(ua,{size:"sm",className:"w-[200px]",children:o.jsx(ca,{placeholder:"Select a preset..."})}),o.jsxs(da,{children:[o.jsx(xr,{value:Ez,children:"Custom"}),Object.keys(e).map(a=>o.jsx(xr,{value:a,children:a},a))]})]})})]})},hXe={modelSettings:{maxRetries:2,maxSteps:15,chatWithGenerateLegacy:!1,chatWithGenerate:!1,chatWithLegacyStream:!1}};function FHr({agentId:e,defaultSettings:t}){const[n,r]=g.useState(t),s=`mastra-agent-store-${e}`;return g.useEffect(()=>{try{const l=localStorage.getItem(s),c=l?JSON.parse(l):{},u={...c,modelSettings:{...hXe.modelSettings,...c?.modelSettings??{},...t?.modelSettings??{}}};r(u)}catch{}},[s,t]),{settings:n,setSettings:l=>{r(c=>({...c,...l})),localStorage.setItem(s,JSON.stringify({...l,agentId:e}))},resetAll:()=>{const l={modelSettings:{...hXe.modelSettings,...t?.modelSettings??{}}};r(l),localStorage.removeItem(s)}}}const ALt=g.createContext({});function Tje({children:e,agentId:t,defaultSettings:n}){const{settings:r,setSettings:s,resetAll:a}=FHr({agentId:t,defaultSettings:n});return o.jsx(ALt.Provider,{value:{settings:r,setSettings:s,resetAll:a},children:e})}const jje=()=>g.useContext(ALt),xxe=(e,t)=>["memory","status",e,t],Yq=(e,t)=>["memory","thread",e,"messages",t??0];function zHr(e,t){const n=Ye(),r=0,s=100;return mt({queryKey:Yq(e,r),queryFn:e?()=>n.getMemoryThread({threadId:e}).listMessages({page:r,perPage:s}):n_})}const Kq=(e,t)=>["memory","observational-memory",e,t];function RLt(e,t,n){const r=Ye();return mt({queryKey:Kq(e,t),queryFn:e&&t?()=>r.getObservationalMemory({agentId:e,threadId:t,resourceId:n}):n_,staleTime:5e3})}const PLt="mastra-memory-om-observation",pXe={"data-om-observation-start":"start","data-om-observation-end":"end","data-om-observation-failed":"failed","data-om-buffering-start":"bufferingStart","data-om-buffering-end":"bufferingEnd","data-om-buffering-failed":"bufferingFailed","data-om-activation":"activation"},$Lt=(e,t)=>{for(const n of e){if(!(n.type in pXe))continue;const r=n,s=r.data?.cycleId;if(!s)continue;const a=pXe[r.type],i=t.get(s)||{};i[a]=r,t.set(s,i)}return t},Nje=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0,Ije=e=>Array.isArray(e)&&e.length>0,Xk=e=>({...Nje(e?.extractedValues)?{extractedValues:e.extractedValues}:{},...Ije(e?.extractionFailures)?{extractionFailures:e.extractionFailures}:{}}),MT=e=>Object.keys(Xk(e)).length>0,Tz=(e,t)=>{if(!e?.data||!t)return e;const n=Xk(e.data),r=Xk(t);if(!Object.keys(r).length)return e;const s={...n.extractedValues??r.extractedValues?{extractedValues:n.extractedValues??r.extractedValues}:{},...n.extractionFailures??r.extractionFailures?{extractionFailures:n.extractionFailures??r.extractionFailures}:{}};return{...e,data:{...e.data,...s}}},BHr=(e,t)=>{for(const[n,r]of e){const s=t.get(n);s&&(r.end=Tz(r.end,s.end),r.failed=Tz(r.failed,s.failed),r.bufferingEnd=Tz(r.bufferingEnd,s.bufferingEnd),r.bufferingFailed=Tz(r.bufferingFailed,s.bufferingFailed));const a={...s??{}};MT(r.end?.data)&&(a.end=Xk(r.end?.data)),MT(r.failed?.data)&&(a.failed=Xk(r.failed?.data)),MT(r.bufferingEnd?.data)&&(a.bufferingEnd=Xk(r.bufferingEnd?.data)),MT(r.bufferingFailed?.data)&&(a.bufferingFailed=Xk(r.bufferingFailed?.data)),Object.keys(a).length>0&&t.set(n,a)}return e},UHr=(e,t)=>{const n=new Map;for(const r of e){const s=r?.content?.parts;Array.isArray(s)&&$Lt(s,n)}return t?BHr(n,t):n},qHr=(e,t)=>{const n=t.start?.data;if(!n)return;const r=t.end?.data,s=t.failed?.data,a=!!t.failed,i=!!t.end,l=!!n.disconnectedAt||i&&!!r?.disconnectedAt,c=a?"failed":l?"disconnected":i?"observed":"observing",u={...n,...i?r:{},...a?s:{},_state:a?"failed":l?"disconnected":i?"complete":"loading"};return{cycleId:e,recordId:typeof u.recordId=="string"?u.recordId:void 0,status:c,operationType:u.operationType,observations:u.observations,extractedValues:Nje(u.extractedValues)?u.extractedValues:void 0,extractionFailures:Ije(u.extractionFailures)?u.extractionFailures:void 0,omData:u,isLoading:c==="observing"}},VHr=(e,t)=>{const n=t.bufferingStart?.data;if(!n)return;const r=t.bufferingEnd?.data,s=t.bufferingFailed?.data,a=t.activation?.data,i=!!t.bufferingFailed,l=!!t.activation,c=!!t.bufferingEnd,u=!!n.disconnectedAt,d=i?"buffering-failed":u?"disconnected":c?"buffering-complete":l?"activated":"buffering",f={...n,...c?r:{},...i?s:{},...l?a:{},_state:d};return!f.tokensObserved&&f.tokensActivated&&(f.tokensObserved=f.tokensActivated),{cycleId:e,recordId:typeof f.recordId=="string"?f.recordId:void 0,status:d,operationType:f.operationType,observations:f.observations,extractedValues:Nje(f.extractedValues)?f.extractedValues:void 0,extractionFailures:Ije(f.extractionFailures)?f.extractionFailures:void 0,omData:f,isLoading:d==="buffering"}},jz=(e,t,n)=>n==="observation"?qHr(e,t):VHr(e,t),Nz=(e,t,n)=>({type:"dynamic-tool",toolCallId:`om-${t}-${e}`,toolName:PLt,input:n.omData,output:n.isLoading?void 0:{status:t==="observation"?n.status==="failed"?"failed":n.status==="disconnected"?"disconnected":"complete":n.status,omData:n.omData},state:n.isLoading?"input-available":"output-available"}),mXe=(e,t)=>t==="observation"?!!e?.end||!!e?.failed:!!e?.bufferingEnd||!!e?.bufferingFailed,gXe=(e,t)=>t==="observation"?e==="data-om-observation-end"||e==="data-om-observation-failed":e==="data-om-buffering-end"||e==="data-om-buffering-failed"||e==="data-om-activation",HHr=(e,t)=>{if(!e||!Array.isArray(e.content?.parts))return e;const n=$Lt(e.content.parts,new Map),r=[];for(const s of e.content.parts){const a=s.data?.cycleId,i=s.type;if(i==="data-om-observation-start"&&a){const l=n.get(a),c=t.get(a);if(!l)continue;const u=mXe(c,"observation")?c??l:{start:l.start},d=jz(a,u,"observation");if(!d)continue;r.push(Nz(a,"observation",d))}else if(i==="data-om-buffering-start"&&a){const l=n.get(a),c=t.get(a);if(!l)continue;const u=mXe(c,"buffering")?c??l:{bufferingStart:l.bufferingStart},d=jz(a,u,"buffering");if(!d)continue;r.push(Nz(a,"buffering",d))}else if(a&&gXe(i,"observation")){const l=n.get(a),c=t.get(a);if(l?.start||c?.start||!c)continue;const u=jz(a,c,"observation");if(!u)continue;r.push(Nz(a,"observation",u))}else if(a&&gXe(i,"buffering")){const l=n.get(a),c=t.get(a);if(l?.bufferingStart||c?.bufferingStart||i==="data-om-activation"&&(l?.bufferingEnd||l?.bufferingFailed)||!c)continue;const u=jz(a,c,"buffering");if(!u)continue;r.push(Nz(a,"buffering",u))}else{if(i?.startsWith("data-om-"))continue;r.push(s)}}return{...e,content:{...e.content,parts:r}}},MLt=(e,t)=>e.map(n=>{if(n.role!=="assistant")return n;const r=n.content?.parts;if(!Array.isArray(r))return n;const{parts:s,changed:a}=t(r);return a?{...n,content:{...n.content,parts:s}}:n}),Aje=e=>{const t=new Set,n=new Set,r=new Set;for(const s of e){const a=s.content?.parts;if(Array.isArray(a))for(const i of a){const l=i?.data?.cycleId;l&&((i.type==="data-om-observation-end"||i.type==="data-om-observation-failed")&&t.add(l),(i.type==="data-om-buffering-end"||i.type==="data-om-buffering-failed")&&n.add(l),i.type==="data-om-activation"&&r.add(l))}}return{observation:t,buffering:n,activatedBuffering:r}},vXe=e=>{const t=Aje(e),n=new Set([...t.buffering,...t.activatedBuffering]);return MLt(e,r=>{let s=!1;return{parts:r.map(i=>{if(i.type==="data-om-observation-start"){const l=i.data?.cycleId;return!l||i.data?.disconnectedAt||t.observation.has(l)?i:(s=!0,{...i,data:{...i.data,disconnectedAt:new Date().toISOString(),_state:"disconnected"}})}if(i.type==="data-om-buffering-start"){const l=i.data?.cycleId;return!l||i.data?.disconnectedAt||n.has(l)?i:(s=!0,{...i,data:{...i.data,disconnectedAt:new Date().toISOString(),_state:"disconnected"}})}if(i.type==="tool-call"&&i.toolName===PLt){const l=i.metadata?.omData||i.args;if(!l?.completedAt&&!l?.failedAt&&!l?.disconnectedAt)return s=!0,{...i,metadata:{...i.metadata,omData:{...l,disconnectedAt:new Date().toISOString(),_state:"disconnected"}}}}return i}),changed:s}})},WHr=e=>{const{buffering:t,activatedBuffering:n}=Aje(e),r=new Set([...t,...n]);for(const s of e){const a=s.content?.parts;if(Array.isArray(a))for(const i of a){const l=i?.data?.cycleId;if(i.type==="data-om-buffering-start"&&l&&!i.data?.disconnectedAt&&!r.has(l)||i.type==="data-om-buffering-end"&&l&&i.data?.operationType==="observation"&&!MT(i.data))return!0}}return!1},DLt=(e,t)=>{const n=new Map,r=Aje(e).buffering;if(t?.bufferedObservationChunks)for(const s of t.bufferedObservationChunks)s.cycleId&&n.set(s.cycleId,s);return MLt(e,s=>{const a=[];let i=!1;for(const l of s){if(l.type==="data-om-buffering-end"&&l.data?.cycleId&&l.data?.operationType==="observation"){const c=n.get(l.data.cycleId);if(c&&!MT(l.data)){a.push({...l,data:{...l.data,observations:l.data.observations??c.observations,extractedValues:c.extractedValues,extractionFailures:c.extractionFailures}}),i=!0;continue}}if(a.push(l),l.type==="data-om-buffering-start"&&l.data?.cycleId&&!l.data?.disconnectedAt&&!r.has(l.data.cycleId)){const c=l.data.cycleId,u=l.data.operationType,d={cycleId:c,operationType:u,completedAt:new Date().toISOString()};if(u==="observation"){const f=n.get(c);f&&(d.tokensBuffered=f.messageTokens,d.bufferedTokens=f.tokenCount,d.observations=f.observations,d.extractedValues=f.extractedValues,d.extractionFailures=f.extractionFailures)}else u==="reflection"&&t&&(d.tokensBuffered=t.bufferedReflectionInputTokens,d.bufferedTokens=t.bufferedReflectionTokens,d.observations=t.bufferedReflection);a.push({type:"data-om-buffering-end",data:d}),r.add(c),i=!0}}return{parts:a,changed:i}})},ZHr=e=>{const t=[];let n=null;for(const r of e){const s=r?.content?.parts;if(Array.isArray(s))for(const a of s)a?.type==="data-om-activation"&&a?.data?.cycleId&&t.push(a.data.cycleId),a?.type==="data-om-status"&&a?.data&&(n=a.data)}return{activatedCycleIds:t,lastProgress:n}},GHr="tool-calls",QHr=e=>`Agent stopped because it reached maxSteps${typeof e=="number"?` (${e})`:""} while tool calls were still pending. Increase maxSteps in advanced settings and try again.`,YHr=e=>{if(e.type!=="finish")return;const t=e.payload?.stepResult?.reason;return typeof t=="string"?t:void 0},KHr=e=>YHr(e)===GHr,wxe=e=>{const t=e.payload?.error;let n;if(typeof t=="string")n=t;else if(t instanceof Error)n=t.message;else if(t&&typeof t=="object"&&typeof t.message=="string")n=t.message;else if(t==null)n="Unknown error";else try{n=JSON.stringify(t)??String(t)}catch{try{n=String(t)}catch{n="Unknown error"}}return{id:`error-${e.runId??"unknown"}-${Date.now()}`,role:"assistant",createdAt:new Date,content:{format:2,parts:[{type:"text",text:n}],metadata:{status:"error"}}}},XHr=(e,t)=>wxe({runId:e.runId,payload:{error:QHr(t)}}),yXe=e=>{const t=e.type;if(t==="error"||t==="data-om-observation-start"||t==="data-om-observation-end"||t==="data-om-observation-failed"||t==="data-om-status"||t==="data-om-activation")return e},JHr=e=>{const t=new zC;return Object.entries(e.requestContext??{}).forEach(([n,r])=>{t.set(n,r)}),e.agentVersionId&&t.set("agentVersionId",e.agentVersionId),t},bXe=e=>(e.type==="tool-result"||e.type==="tool-execution-end")&&e.payload?.toolName==="updateWorkingMemory"&&typeof e.payload.result=="object"&&"success"in e.payload.result&&e.payload.result?.success,eWr=({agentId:e,requestContext:t,agentVersionId:n,threadId:r,modelSettingsArgs:s,model:a,chatWithNetwork:i,chatWithGenerate:l,maxSteps:c,isOMEnabled:u,tracingOptions:d,threadSignalsUnsupportedRef:f,isRunningStream:h,sendMessage:p,cancelRun:m,setMessages:v,setStreamErrors:y,refreshThreadList:b,refreshWorkingMemory:x,handleObservationStart:w,handleProgressUpdate:k,refreshObservationalMemory:C,handleActivation:_,resetObservationalMemoryStreamState:T,signalTimelineRefresh:E})=>{const N=Ye(),I=Ar(),A=g.useRef(null),P=g.useRef({requestContext:t,agentVersionId:n,threadId:r,modelSettingsArgs:s,model:a,chatWithNetwork:i,chatWithGenerate:l,maxSteps:c,isOMEnabled:u,tracingOptions:d});P.current={requestContext:t,agentVersionId:n,threadId:r,modelSettingsArgs:s,model:a,chatWithNetwork:i,chatWithGenerate:l,maxSteps:c,isOMEnabled:u,tracingOptions:d};const L=g.useCallback(z=>{z&&(I.refetchQueries({queryKey:Kq(e,z)}),I.refetchQueries({queryKey:Yq(z)}),I.refetchQueries({queryKey:xxe(e,z)}),E())},[e,I,E]),D=g.useCallback(z=>{!z||!P.current.isOMEnabled||N.awaitBufferStatus({agentId:e,resourceId:e,threadId:z}).then(V=>{v(M=>DLt(M,V?.record)),I.invalidateQueries({queryKey:["observational-memory",e]}),I.invalidateQueries({queryKey:["memory-status",e]}),L(z)}).catch(()=>{})},[e,N,I,L,v]),B=g.useCallback(z=>{z?.type==="error"&&y(V=>[...V,wxe(z)]),z?.type==="data-om-observation-start"&&w(z.data?.operationType),z?.type==="data-om-status"&&k(z.data),(z?.type==="data-om-observation-end"||z?.type==="data-om-observation-failed"||z?.type==="data-om-activation")&&C(z.data?.operationType),z?.type==="data-om-activation"&&_(z.data)},[_,w,k,C,y]),H=g.useCallback(async({message:z,attachments:V=[]})=>{const M=P.current;if(f.current&&(h||A.current))return;y([]);const G=new AbortController;A.current=G;const F=JHr(M);try{if(M.chatWithNetwork)await p({message:z,mode:"network",coreUserMessages:V,requestContext:F,threadId:M.threadId,modelSettings:M.modelSettingsArgs,model:M.model,signal:G.signal,tracingOptions:M.tracingOptions,onNetworkChunk:async R=>{bXe(R)&&x?.(),R.type==="network-execution-event-step-finish"&&b?.(),B(yXe(R))}});else if(M.chatWithGenerate){await p({message:z,mode:"generate",coreUserMessages:V,requestContext:F,threadId:M.threadId,modelSettings:M.modelSettingsArgs,model:M.model,signal:G.signal,tracingOptions:M.tracingOptions}),await b?.(),L(M.threadId);return}else{await p({message:z,mode:"stream",coreUserMessages:V,requestContext:F,threadId:M.threadId,modelSettings:M.modelSettingsArgs,model:M.model,tracingOptions:M.tracingOptions,onChunk:async R=>{R.type==="finish"&&(KHr(R)&&y(U=>[...U,XHr(R,M.maxSteps)]),await b?.()),bXe(R)&&x?.(),B(yXe(R))},signal:G.signal}),L(M.threadId),D(M.threadId);return}setTimeout(()=>{b?.()},500),L(M.threadId),D(M.threadId)}catch(R){if(console.error("Error occurred in ChatProvider",R),R.name==="AbortError")return;y(U=>[...U,wxe({runId:"thrown",payload:{error:R}})]),T()}finally{A.current=null}},[D,B,h,b,L,x,T,p,y,f]),q=g.useCallback(async()=>{A.current?.abort(),A.current=null,T(),m?.(),D(P.current.threadId)},[m,D,T]);return{send:H,cancel:q}};function xXe(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function tWr(e,t,n){const r=Ye(),[s,a]=g.useState(!1),[i,l]=g.useState(null),[c,u]=g.useState("thread"),[d,f]=g.useState("markdown"),[h,p]=g.useState(!0),[m,v]=g.useState(!1),{requestContext:y}=ys(),b=g.useCallback(async()=>{p(!0);try{if(!e||!t){l(null),p(!1);return}const w=await r.getWorkingMemory({agentId:e,threadId:t,resourceId:n,requestContext:y}),{workingMemory:k,source:C,workingMemoryTemplate:_,threadExists:T}=w;if(a(T),l(k),u(C),f(_?.format||"markdown"),_?.format==="json"){let E="";k?E=xXe(k):_?.content?E=xXe(_.content):E="",l(E)}else l(k||_?.content||"")}catch(w){l(null),console.error("Error fetching working memory",w)}finally{p(!1)}},[e,t,n]);return g.useEffect(()=>{b()},[b]),{threadExists:s,workingMemoryData:i,workingMemorySource:c,workingMemoryFormat:d,isLoading:h,isUpdating:m,refetch:b,updateWorkingMemory:async w=>{v(!0);try{if(d==="json")try{JSON.parse(w)}catch{throw new Error("Invalid JSON working memory")}await r.updateWorkingMemory({agentId:e,threadId:t,workingMemory:w,resourceId:n,requestContext:y}),b()}catch(k){throw console.error("Error updating working memory",k),k}finally{v(!1)}}}}const LLt=g.createContext({threadExists:!1,workingMemoryData:null,workingMemorySource:"thread",isLoading:!1,isUpdating:!1,updateWorkingMemory:()=>Promise.resolve(),refetch:()=>Promise.resolve()});function FLt({agentId:e,threadId:t,resourceId:n,children:r}){const s=tWr(e,t,n);return o.jsx(LLt.Provider,{value:s,children:r})}function zLt(){const e=g.useContext(LLt);if(!e)throw new Error("useWorkingMemory must be used within a WorkingMemoryProvider");return e}const BLt=g.createContext(null);function ULt({children:e}){const[t,n]=g.useState(!1),[r,s]=g.useState(!1),[a,i]=g.useState(0),[l,c]=g.useState(null),[u,d]=g.useState(new Set),f=g.useCallback(()=>{i(Date.now())},[]),h=g.useCallback(m=>{d(v=>new Set([...v,m]))},[]),p=g.useCallback(()=>{n(!1),s(!1),d(new Set)},[]);return o.jsx(BLt.Provider,{value:{isObservingFromStream:t,setIsObservingFromStream:n,isReflectingFromStream:r,setIsReflectingFromStream:s,observationsUpdatedAt:a,signalObservationsUpdated:f,streamProgress:l,setStreamProgress:c,activatedCycleIds:u,markCycleIdActivated:h,clearProgress:p},children:e})}function xG(){const e=g.useContext(BLt);return e||{isObservingFromStream:!1,setIsObservingFromStream:()=>{},isReflectingFromStream:!1,setIsReflectingFromStream:()=>{},observationsUpdatedAt:0,signalObservationsUpdated:()=>{},streamProgress:null,setStreamProgress:()=>{},activatedCycleIds:new Set,markCycleIdActivated:()=>{},clearProgress:()=>{}}}const qLt=g.createContext(null),nWr={isPanelOpen:!1,openPanel:()=>{},closePanel:()=>{},selectedTimestamp:null,setSelectedTimestamp:()=>{}};function rWr({children:e}){const[t,n]=g.useState(!1),[r,s]=g.useState(null),a=g.useCallback(()=>n(!0),[]),i=g.useCallback(()=>n(!1),[]),l=g.useMemo(()=>({isPanelOpen:t,openPanel:a,closePanel:i,selectedTimestamp:r,setSelectedTimestamp:s}),[t,a,i,r]);return o.jsx(qLt.Provider,{value:l,children:e})}function wG(){return g.useContext(qLt)??nWr}const Rje=g.createContext(null);function Pje({children:e,...t}){return o.jsx(Rje.Provider,{value:t,children:e})}function Wo(){const e=g.useContext(Rje);if(!e)throw new Error("useAgentEditFormContext must be used within an AgentEditFormProvider");return e}function VLt(){return g.useContext(Rje)}const $je=g.createContext(null);function HLt({children:e,defaultProvider:t="",defaultModel:n=""}){const[r,s]=g.useState({provider:t,model:n,explicit:!1}),a=f=>{s({provider:f,model:"",explicit:!1})},i=(f,h)=>{s({provider:f,model:h,explicit:!0})},{provider:l,model:c,explicit:u}=r,d=u?`${l}/${c}`:void 0;return o.jsx($je.Provider,{value:{provider:l,model:c,modelOverride:d,setProvider:a,setModel:i},children:e})}function Mje(){const e=g.useContext($je);if(!e)throw new Error("usePlaygroundModel must be used within a PlaygroundModelProvider");return e}function Dje(){return g.useContext($je)??void 0}const WLt=g.createContext(null);function sWr({children:e}){const[t,n]=g.useState([]),[r,s]=g.useState([]),[a,i]=g.useState(null),{updateExperimentResult:l}=wi(),c=Ye(),u=g.useCallback(x=>{n(w=>{const k=new Set(w.map(_=>_.itemId)),C=x.filter(_=>!k.has(_.itemId));return[...w,...C.map((_,T)=>({..._,id:_.id||`review-${Date.now()}-${T}`,tags:_.tags??[]}))]})},[]),d=g.useCallback(x=>{n(w=>{const k=new Map(x.map(_=>[_.id,_])),C=w.filter(_=>!k.has(_.id));return[...x,...C]})},[]),f=g.useCallback(x=>{const w=t.find(k=>k.id===x);w?.experimentId&&w?.datasetId&&l.mutate({datasetId:w.datasetId,experimentId:w.experimentId,resultId:w.id,status:null}),n(k=>k.filter(C=>C.id!==x))},[t,l]),h=g.useCallback(async x=>{const w=t.find(k=>k.id===x);w?.experimentId&&w?.datasetId&&await l.mutateAsync({datasetId:w.datasetId,experimentId:w.experimentId,resultId:w.id,status:"complete"}),n(k=>k.filter(C=>C.id!==x))},[t,l]),p=g.useCallback((x,w)=>{const k=t.find(C=>C.id===x);k?.experimentId&&k?.datasetId&&l.mutate({datasetId:k.datasetId,experimentId:k.experimentId,resultId:k.id,tags:w}),n(C=>C.map(_=>_.id===x?{..._,tags:w}:_))},[t,l]),m=g.useCallback((x,w)=>{const k=t.find(C=>C.id===x);k?.traceId&&w!==void 0&&c.createFeedback({feedback:{traceId:k.traceId,source:"studio",feedbackSource:"studio",feedbackType:"rating",value:w==="positive"?1:-1,reviewStatus:"reviewed",experimentId:k.experimentId??void 0,sourceId:k.id}}).catch(()=>{}),n(C=>C.map(_=>_.id===x?{..._,rating:w}:_))},[t,c]),v=g.useCallback((x,w)=>{const k=t.find(C=>C.id===x);k?.experimentId&&k?.datasetId&&l.mutate({datasetId:k.datasetId,experimentId:k.experimentId,resultId:k.id,comment:w}),k?.traceId&&c.createFeedback({feedback:{traceId:k.traceId,source:"studio",feedbackSource:"studio",feedbackType:"comment",value:w,comment:w,reviewStatus:"reviewed",experimentId:k.experimentId??void 0,sourceId:k.id}}).catch(()=>{}),n(C=>C.map(_=>_.id===x?{..._,comment:w}:_))},[t,c,l]),y=g.useCallback((x,w)=>{n(k=>k.map(C=>C.id===x?{...C,clusterId:w}:C))},[]),b=g.useCallback(()=>{n([]),s([]),i(null)},[]);return o.jsx(WLt.Provider,{value:{items:t,clusters:r,activeClusterId:a,addItems:u,removeItem:f,completeItem:h,setItemTags:p,rateItem:m,commentItem:v,setClusters:s,setActiveClusterId:i,assignCluster:y,clearAll:b,loadPersistedItems:d},children:e})}function ZLt(){const e=g.useContext(WLt);if(!e)throw new Error("useReviewQueue must be used within ReviewQueueProvider");return e}function aWr({isSupportedModel:e,threadSignalsEnabled:t,threadId:n,threadSignalsUnsupported:r}){return e&&t&&!!n&&!r}const GLt=g.createContext(void 0);function QLt({children:e,approveToolcall:t,declineToolcall:n,approveToolcallGenerate:r,declineToolcallGenerate:s,approveNetworkToolcall:a,declineNetworkToolcall:i,isRunning:l,toolCallApprovals:c,networkToolCallApprovals:u}){return o.jsx(GLt.Provider,{value:{approveToolcall:t,declineToolcall:n,approveToolcallGenerate:r,declineToolcallGenerate:s,approveNetworkToolcall:a,declineNetworkToolcall:i,isRunning:l,toolCallApprovals:c,networkToolCallApprovals:u},children:e})}function Lje(){const e=g.useContext(GLt);if(!e)throw new Error("useToolCall must be used within a ToolCallProvider");return e}function iWr({children:e,agentId:t,initialMessages:n,threadId:r,refreshThreadList:s,settings:a,requestContext:i,modelVersion:l,agentVersionId:c,supportsMemory:u}){const{settings:d}=VH(),f=Dje()?.modelOverride,[h,p]=g.useState([]),[m,v]=g.useState(!1),y=g.useRef(!1),b=a?.modelSettings??{},x=window.MASTRA_AGENT_SIGNALS!=="false"&&u!==!1&&!b.chatWithLegacyStream;g.useEffect(()=>{p([]),y.current=!1,v(!1)},[t,r]);const w=g.useMemo(()=>{if(!c&&!i)return;const _e=new zC;return Object.entries(i??{}).forEach(([et,dt])=>{_e.set(et,dt)}),c&&_e.set("agentVersionId",c),_e},[c,i]),{messages:k,tasks:C,sendMessage:_,cancelRun:T,isRunning:E,isAwaitingToolApproval:N,setMessages:I,approveToolCall:A,declineToolCall:P,approveToolCallGenerate:L,declineToolCallGenerate:D,toolCallApprovals:B,approveNetworkToolCall:H,declineNetworkToolCall:q,networkToolCallApprovals:z}=m1e({agentId:t,threadId:r,initialMessages:n,requestContext:w,enableThreadSignals:x,onThreadSignalsUnsupported:()=>{y.current=!0,v(!0)}}),{refetch:V}=zLt(),M=Ar(),G=Ye(),{data:F}=OS(t),R=F?.config?.observationalMemory,U=R===!0||typeof R=="object"&&R!==null&&(!("enabled"in R)||R.enabled!==!1),{setIsObservingFromStream:Z,setIsReflectingFromStream:Y,signalObservationsUpdated:te,setStreamProgress:J,markCycleIdActivated:ee}=xG(),re=g.useCallback(_e=>{_e==="reflection"?Y(!0):Z(!0)},[Z,Y]),ae=g.useCallback(_e=>{_e.threadId&&_e.threadId!==r||J({windows:_e.windows,recordId:_e.recordId,threadId:_e.threadId,stepNumber:_e.stepNumber,generationCount:_e.generationCount})},[J,r]),X=g.useCallback(_e=>{_e==="reflection"?Y(!1):Z(!1),te(),M.invalidateQueries({queryKey:["observational-memory",t]}),M.invalidateQueries({queryKey:["memory-status",t]}),M.refetchQueries({queryKey:Kq(t,r)}),M.refetchQueries({queryKey:Yq(r)}),M.refetchQueries({queryKey:xxe(t,r)})},[t,M,Z,Y,te,r]),ne=g.useCallback(_e=>{const et=_e?.cycleId;et&&ee(et)},[ee]),se=g.useCallback(()=>{Z(!1),Y(!1),I(_e=>vXe(_e)),M.invalidateQueries({queryKey:["observational-memory",t]}),M.invalidateQueries({queryKey:["memory-status",t]}),M.refetchQueries({queryKey:Kq(t,r)}),M.refetchQueries({queryKey:Yq(r)}),M.refetchQueries({queryKey:xxe(t,r)})},[t,M,Z,Y,I,r]);g.useEffect(()=>{const{activatedCycleIds:_e,lastProgress:et}=ZHr(n||[]);for(const dt of _e)ee(dt);et&&ae(et)},[ae,n,ee]),g.useEffect(()=>{if(!r||!WHr(n||[]))return;let _e=!1;return G.awaitBufferStatus({agentId:t,resourceId:t,threadId:r}).then(et=>{_e||I(dt=>DLt(dt,et?.record))}).catch(()=>{_e||I(et=>vXe(et))}),()=>{_e=!0}},[t,G,n,I,r]);const{frequencyPenalty:ce,presencePenalty:le,maxRetries:be,maxSteps:he,maxTokens:xe,temperature:Ae,topK:De,topP:Me,seed:Pe,chatWithGenerate:Re,chatWithNetwork:Le,chatWithLegacyStream:Ee,providerOptions:Te,requireToolApproval:ze}=b,Ce={frequencyPenalty:ce,presencePenalty:le,maxRetries:be,temperature:Ae,topK:De,topP:Me,seed:Pe,maxTokens:xe,providerOptions:Te,maxSteps:he,requireToolApproval:ze},{send:Fe,cancel:tt}=eWr({agentId:t,requestContext:i,agentVersionId:c,threadId:r,modelSettingsArgs:Ce,model:f,chatWithNetwork:Le,chatWithGenerate:Re,maxSteps:he,isOMEnabled:U,tracingOptions:d?.tracingOptions,threadSignalsUnsupportedRef:y,isRunningStream:E,sendMessage:_,cancelRun:T,setMessages:I,setStreamErrors:p,refreshThreadList:s,refreshWorkingMemory:V,handleObservationStart:re,handleProgressUpdate:ae,refreshObservationalMemory:X,handleActivation:ne,resetObservationalMemoryStreamState:se,signalTimelineRefresh:te}),Ge=l==="v2"||l==="v3",ge=g.useRef(new Map),Se=g.useMemo(()=>UHr(k,ge.current),[k]),de=g.useMemo(()=>[...k.filter(_e=>_e.content?.metadata?.status!=="error"),...h].map(_e=>HHr(_e,Se)),[k,h,Se]),ke=E||N,fe=aWr({isSupportedModel:Ge,threadSignalsEnabled:x&&(!Re&&!Le&&!Ee),threadId:r,threadSignalsUnsupported:m}),ye=g.useMemo(()=>({messages:de}),[de]),je=g.useMemo(()=>({isRunning:ke,cancelRun:tt,canSendWhileStreaming:fe}),[ke,tt,fe]),$e=g.useMemo(()=>({send:Fe}),[Fe]),He=g.useMemo(()=>({tasks:C}),[C]),vt=g.useMemo(()=>({agentId:t,agentVersionId:c,requestContext:i}),[t,c,i]);return o.jsx(_Lt.Provider,{value:vt,children:o.jsx(kLt.Provider,{value:je,children:o.jsx(SLt.Provider,{value:ye,children:o.jsx(CLt.Provider,{value:He,children:o.jsx(OLt.Provider,{value:$e,children:o.jsx(QLt,{approveToolcall:A,declineToolcall:P,approveToolcallGenerate:L,declineToolcallGenerate:D,approveNetworkToolcall:H,declineNetworkToolcall:q,isRunning:E,toolCallApprovals:B,networkToolCallApprovals:z,children:e})})})})})})}function YLt({children:e}){const t=g.useRef(!1);return g.useEffect(()=>{t.current=!0},[]),o.jsx(g3t,{value:t,children:e})}function gie({children:e,className:t}){const n=y3t();return o.jsx("div",{className:K(n,t),children:o.jsx(YLt,{children:e})})}function oWr(e){const t=g.useRef(null);return g.useEffect(()=>{const n=t.current;if(!n||!e)return;let r,s=0,a=0;const i=()=>{r=void 0;const c=n.getBoundingClientRect(),u=Math.atan2(a-(c.top+c.height/2),s-(c.left+c.width/2));n.style.setProperty("--composer-ring-angle",`${u*180/Math.PI+90}deg`)},l=c=>{s=c.clientX,a=c.clientY,r??=requestAnimationFrame(i)};return window.addEventListener("pointermove",l,{passive:!0}),()=>{window.removeEventListener("pointermove",l),r!==void 0&&cancelAnimationFrame(r)}},[e]),t}const KLt=g.forwardRef(({children:e,...t},n)=>o.jsx("form",{ref:n,"data-slot":"composer",...t,children:e}));KLt.displayName="Composer";const XLt=g.forwardRef(({children:e,className:t,sendingPulseKey:n=0,...r},s)=>o.jsxs("div",{ref:s,"data-slot":"composer-box",className:K("@container relative mx-auto mt-auto w-full max-w-3xl overflow-hidden rounded-[22px] border border-border2/40 bg-surface3 transition-colors duration-normal focus-within:border-border2",t),...r,children:[o.jsx(lWr,{pulseKey:n}),o.jsx("div",{className:"relative z-10",children:e})]}));XLt.displayName="ComposerBox";const JLt=({busy:e=!1,className:t,...n})=>{const r=oWr(!e);return o.jsx("div",{ref:r,"data-slot":"composer-ring","data-busy":e?"true":"false",className:K("composer-ring relative mx-auto w-full max-w-3xl rounded-[23px] p-px",t),...n})};JLt.displayName="ComposerRing";const e5t=g.forwardRef(({className:e,...t},n)=>o.jsx("div",{ref:n,role:"region","data-slot":"composer-attachments",className:K("mx-auto w-full max-w-3xl pb-2",e),...t}));e5t.displayName="ComposerAttachments";const t5t=g.forwardRef(({className:e,maxHeight:t="212px",...n},r)=>o.jsx(Nr,{maxHeight:t,children:o.jsx("textarea",{ref:r,"data-slot":"composer-input",className:K("min-h-17 field-sizing-content w-full resize-none overflow-hidden bg-transparent px-3 pt-3 pb-2 text-ui-lg leading-ui-lg text-neutral6 outline-hidden placeholder:text-neutral3 focus:outline-hidden disabled:cursor-not-allowed disabled:opacity-50",e),...n})}));t5t.displayName="ComposerInput";const n5t=g.forwardRef(({className:e,...t},n)=>o.jsx("div",{ref:n,role:"region","data-slot":"composer-actions",className:K("flex flex-wrap-reverse items-center justify-between gap-2 px-1.5 pb-1.5",e),...t}));n5t.displayName="ComposerActions";const vie=({className:e})=>o.jsxs("div",{className:K("flex size-full flex-col -space-y-3",e),children:[o.jsx("div",{className:"bg-accent1 w-full flex-1 blur-xl"}),o.jsx("div",{className:"bg-accent1Dark w-full flex-1 blur-xl"}),o.jsx("div",{className:"bg-accent1 w-full flex-1 blur-xl"}),o.jsx("div",{className:"bg-accent1Darker w-full flex-1 blur-xl"})]}),lWr=({pulseKey:e})=>e===0?null:o.jsxs("div",{"aria-hidden":"true","data-slot":"composer-sending-pulse",className:"composer-sending pointer-events-none absolute top-0 left-[-10%] z-0 flex h-10 w-[120%] transform-gpu",children:[o.jsx(vie,{}),o.jsx(vie,{className:"-translate-y-2"}),o.jsx(vie,{})]},e),wXe={start:!1,end:!1},SXe={currentAnchorId:void 0,visibleMessageIds:[]},cWr=8,uWr=0,dWr=64,fWr=160,hWr=160,SG=g.createContext(null),r5t=g.createContext(null),s5t=g.createContext(null),a5t=(e,t)=>{const n=g.useContext(e);if(!n)throw new Error(`${t} must be used within MessageScrollerProvider.`);return n},kG=e=>a5t(SG,e),pWr=e=>a5t(r5t,e),DT=.5,mWr=e=>{if(!e)return{start:0,end:0};const t=window.getComputedStyle(e);return{start:Number.parseFloat(t.paddingBlockStart||t.paddingTop)||0,end:Number.parseFloat(t.paddingBlockEnd||t.paddingBottom)||0}},i5t=e=>Math.max(0,e.scrollHeight-e.clientHeight),Sxe=(e,t)=>{const n=e.getBoundingClientRect(),r=t.getBoundingClientRect();return n.top-r.top+t.scrollTop},kXe=({align:e,contentElement:t,element:n,scrollMargin:r,viewportElement:s})=>{const a=mWr(t),i=Sxe(n,s),l=n.getBoundingClientRect().height,c=Math.max(0,s.clientHeight-a.start-a.end);if(e==="center")return i-a.start-(c-l)/2-r;if(e==="end")return i-s.clientHeight+l+a.end+r;if(e==="nearest"){const u=i+l,d=s.scrollTop+a.start,f=s.scrollTop+s.clientHeight-a.end;return i>=d&&u<=f?s.scrollTop:i<d?i-a.start-r:u-s.clientHeight+a.end+r}return i-a.start-r},gWr=({contentElement:e,items:t,viewportElement:n})=>{const r=i5t(n),s=t.at(-1)?.[1].element;if(!s||!e)return r;const a=Sxe(e,n)+e.getBoundingClientRect().height,i=Math.max(0,n.scrollHeight-a),l=Sxe(s,n)+s.getBoundingClientRect().height;return Math.min(r,Math.max(0,l+i-n.clientHeight))},vWr=({fallbackAnchorId:e,items:t,scrollMargin:n,scrollPreviousItemPeek:r,visibleMessageIds:s,viewportElement:a})=>{const i=a.getBoundingClientRect().top+n+r,l=t.filter(([,u])=>u.scrollAnchor);let c;for(const[u,d]of l)d.element.getBoundingClientRect().top<=i+DT&&(c=u);return c||(l.find(([u])=>s.has(u))?.[0]??e)},yWr=240,bWr=220,xWr="cubic-bezier(0.33, 1, 0.68, 1)";function OXe(e){if(typeof DOMMatrixReadOnly>"u")return 0;const{transform:t}=getComputedStyle(e);return!t||t==="none"?0:new DOMMatrixReadOnly(t).m42}const Xq=new WeakMap;function CXe(e){Xq.get(e)?.abort(),Xq.delete(e),e.style.transition="",e.style.transform=""}function wWr(){return typeof window>"u"||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function SWr(e,t){if(!e||t<=0||wWr())return;const n=OXe(e)+t;if(n>yWr){CXe(e);return}e.style.transition="none",e.style.transform=`translateY(${n}px)`,e.offsetHeight,e.style.transition=`transform ${bWr}ms ${xWr}`,e.style.transform="translateY(0)",Xq.get(e)?.abort();const r=new AbortController;Xq.set(e,r);const s=a=>{a.target===e&&OXe(e)===0&&CXe(e)};e.addEventListener("transitionend",s,{signal:r.signal}),e.addEventListener("transitioncancel",s,{signal:r.signal})}const kWr=560,OWr=240,CWr=e=>1-(1-e)**5;function _Wr(e,t,n){const s=typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches?0:kWr,a=performance.now(),i=e.scrollTop;let l=i,c=0,u=!1;const d=h=>{u=!0,n(h)},f=()=>{if(Math.abs(e.scrollTop-l)>1)return d("interrupted");const h=t();if(h===void 0)return d("expired");const p=performance.now()-a,m=s===0?1:Math.min(1,p/s);if(e.scrollTop=i+(h-i)*CWr(m),l=e.scrollTop,m===1&&Math.abs(l-h)<=DT)return d("arrived");if(p>=s+OWr)return d("expired");c=window.requestAnimationFrame(f)};return c=window.requestAnimationFrame(f),{cancel:()=>{u||(u=!0,window.cancelAnimationFrame(c))}}}const OG=(...e)=>t=>{e.forEach(n=>{if(n){if(typeof n=="function"){n(t);return}n.current=t}})},EWr=(e,t)=>e.start===t.start&&e.end===t.end,TWr=(e,t)=>e.currentAnchorId===t.currentAnchorId&&e.visibleMessageIds.length===t.visibleMessageIds.length&&e.visibleMessageIds.every((n,r)=>n===t.visibleMessageIds[r]),jWr=e=>e.sort(([,t],[,n])=>{const r=t.element.compareDocumentPosition(n.element);return r&Node.DOCUMENT_POSITION_FOLLOWING?-1:r&Node.DOCUMENT_POSITION_PRECEDING?1:0}),bP=(e,t,n)=>{if(typeof e.scrollTo=="function"){e.scrollTo({top:t,behavior:n});return}e.scrollTop=t},xP=e=>{if(typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(e);return}window.setTimeout(e,0)};function NWr({autoScroll:e=!1,children:t,defaultScrollPosition:n="end",onReachStart:r,preserveScrollOnPrepend:s=!1,reachStartThreshold:a=fWr,scrollEdgeThreshold:i=cWr,scrollMargin:l=uWr,scrollPreviousItemPeek:c=dWr}){const u=g.useRef(null);u.current??=new Map;const d=u.current,f=g.useRef(null),h=g.useRef(null);h.current??=new Set;const p=h.current,[m,v]=g.useState(0),[y,b]=g.useState(null),[x,w]=g.useState(null),[k,C]=g.useState(null),_=g.useRef(!1),T=g.useRef(!1),E=g.useRef(!1),N=g.useRef(null);N.current??=new Set;const I=N.current,A=g.useRef(null);A.current??=new WeakSet;const P=A.current,L=g.useRef(!1),[D,B]=g.useState(wXe),[H,q]=g.useState(SXe),z=g.useRef(!0),V=g.useRef(!0),M=g.useRef(null),G=g.useRef(null),F=g.useRef(0),R=g.useRef(!1),U=g.useRef(!1),Z=g.useRef(null),Y=g.useRef(void 0),te=g.useRef(r);g.useEffect(()=>{te.current=r},[r]);const J=g.useCallback(Ce=>{const Fe=[Ce.start&&"start",Ce.end&&"end"].filter(Boolean).join(" ");for(const tt of[y,x])tt&&(Fe?tt.setAttribute("data-scrollable",Fe):tt.removeAttribute("data-scrollable"));B(tt=>EWr(tt,Ce)?tt:Ce)},[y,x]),ee=g.useCallback(Ce=>{q(Fe=>TWr(Fe,Ce)?Fe:Ce)},[]),re=g.useCallback(()=>(f.current??=jWr(Array.from(d.entries())),f.current),[d]),ae=g.useCallback(()=>x?gWr({contentElement:k,items:re(),viewportElement:x}):0,[k,re,x]),X=g.useCallback(Ce=>{const Fe=d.get(Ce);if(!(!Fe||!x))return Math.max(0,kXe({align:"start",contentElement:k,element:Fe.element,scrollMargin:l,viewportElement:x}))},[k,d,l,x]),ne=g.useCallback(Ce=>{const Fe=X(Ce);return Fe===void 0||!x?Fe:Math.min(Fe,i5t(x))},[X,x]),se=g.useCallback(()=>{G.current?.cancel(),G.current=null},[]),ce=g.useCallback(({fromScroll:Ce=!1}={})=>{if(!x){z.current=!0,J(wXe);return}const{scrollTop:Fe}=x,tt=ae()-Fe,Ge=Fe<F.current;z.current=tt<hWr,M.current==="end"&&(Ge||z.current)&&(M.current=null),F.current=Fe,Ce&&M.current===null&&(Ge||z.current)&&(V.current=z.current),J({start:Fe>i,end:tt>i&&!(e&&V.current)})},[e,ae,J,i,x]),le=g.useCallback(()=>re().filter(([,Ce])=>Ce.scrollAnchor).at(-1)?.[0],[re]),be=g.useCallback(()=>{const Ce=re(),Fe=le()??Ce.at(-1)?.[0];if(Ce.length===0){ee(SXe);return}if(!x){ee({currentAnchorId:Fe,visibleMessageIds:Fe?[Fe]:[]});return}const tt=x.getBoundingClientRect(),Ge=new Set;if(typeof IntersectionObserver>"u"){const Se=tt.top+l+c;Ce.forEach(([de,ke])=>{const Ne=ke.element.getBoundingClientRect();Ne.bottom>Se&&Ne.top<tt.bottom&&Ge.add(de)})}else p.forEach(Se=>Ge.add(Se));const ge=Ce.flatMap(([Se])=>Ge.has(Se)?[Se]:[]);ee({currentAnchorId:vWr({fallbackAnchorId:Fe,items:Ce,scrollMargin:l,scrollPreviousItemPeek:c,visibleMessageIds:Ge,viewportElement:x}),visibleMessageIds:ge.length>0?ge:Fe?[Fe]:[]})},[le,re,p,ee,l,c,x]),he=g.useCallback(()=>{ce(),be()},[ce,be]),xe=g.useCallback(()=>{const Ce=!!(x&&x.scrollHeight>x.clientHeight);if(ce({fromScroll:!0}),be(),!!x&&(z.current&&Ce&&(R.current=!0),!!R.current&&Ce)){if(x.scrollTop>a){U.current=!1;return}U.current||te.current&&(U.current=!0,s&&(Z.current={scrollHeight:x.scrollHeight,scrollTop:x.scrollTop}),te.current())}},[s,a,ce,be,x]),Ae=g.useCallback((Ce,{align:Fe="start",behavior:tt="auto",scrollMargin:Ge=l}={})=>{if(!x||!k?.contains(Ce))return!1;const ge=Math.max(0,kXe({align:Fe,contentElement:k,element:Ce,scrollMargin:Ge,viewportElement:x}));return Math.abs(x.scrollTop-ge)<=DT?(bP(x,ge,"auto"),he(),!0):(bP(x,ge,tt),xP(he),!0)},[k,l,he,x]),De=g.useCallback(({behavior:Ce="auto"}={})=>x?(se(),M.current=null,bP(x,0,Ce),xP(he),!0):!1,[se,he,x]),Me=g.useCallback(({behavior:Ce="auto"}={})=>x?(se(),V.current=!0,M.current=Ce==="smooth"?"end":null,bP(x,ae(),Ce),he(),xP(he),!0):!1,[se,ae,he,x]),Pe=g.useCallback((Ce,Fe)=>{const tt=d.get(Ce);return tt?Ae(tt.element,Fe):!1},[d,Ae]),Re=g.useCallback(()=>{const Ce=M.current;if(!(Ce!==null&&Ce!=="end")&&e&&_.current&&V.current&&x){const tt=ae()-x.scrollTop;if(tt>DT){const Ge=Ce==="end";bP(x,ae(),Ge?"smooth":"auto"),Ge||SWr(k,tt)}}he()},[e,k,ae,he,x]),Le=g.useCallback((Ce,Fe,tt)=>(d.set(Ce,{element:Fe,scrollAnchor:tt}),f.current=null,v(Ge=>Ge+1),()=>{d.get(Ce)?.element===Fe&&(d.delete(Ce),p.delete(Ce),f.current=null,v(ge=>ge+1))}),[p,d]);g.useEffect(()=>{if(!k||!x||typeof IntersectionObserver>"u"){be();return}const Ce=new Map;for(const[tt,Ge]of d)Ce.set(Ge.element,tt);const Fe=new IntersectionObserver(tt=>{for(const Ge of tt){const ge=Ce.get(Ge.target);ge&&(Ge.isIntersecting?p.add(ge):p.delete(ge))}be()},{root:x,rootMargin:`${-(l+c)}px 0px 0px 0px`,threshold:[0,.01,.5,1]});for(const[,tt]of d)Fe.observe(tt.element);return be(),()=>Fe.disconnect()},[k,p,d,m,l,c,be,x]),g.useEffect(()=>{if(!x||typeof ResizeObserver>"u")return;const Ce=new ResizeObserver(he);return Ce.observe(x),()=>Ce.disconnect()},[he,x]),g.useLayoutEffect(()=>{ce(),be()},[m,ce,be]),g.useLayoutEffect(()=>{if(_.current||!x)return;if(d.size===0){T.current=!0;return}const Ce=()=>{const tt=le();V.current=!1;let Ge=!1;if(n==="start"?Ge=De({behavior:"auto"}):n==="last-anchor"?Ge=tt?Pe(tt,{align:"start",behavior:"auto"}):Me({behavior:"auto"}):Ge=Me({behavior:"auto"}),!!Ge){_.current=!0;for(const[ge,Se]of re())Se.scrollAnchor&&(I.add(ge),P.add(Se.element));L.current=!0}};if(!T.current){Ce();return}if(E.current)return;E.current=!0;let Fe=!1;return xP(()=>{xP(()=>{E.current=!1,!Fe&&!_.current&&Ce()})}),()=>{Fe=!0,E.current=!1}},[n,le,re,d,m,Me,Pe,De,P,I,x]),g.useLayoutEffect(()=>{const Ce=le(),Fe=Ce?d.get(Ce):void 0,tt=L.current&&Ce!==void 0&&Fe!==void 0&&!I.has(Ce)&&!P.has(Fe.element);for(const[Ge,ge]of re())ge.scrollAnchor&&(I.add(Ge),P.add(ge.element));if(L.current=_.current,tt&&Ce){e&&(V.current=!0),se();const Ge=x?X(Ce):void 0;Ge===void 0||!x||Math.abs(Ge-x.scrollTop)<=DT?M.current=null:(M.current={anchorId:Ce},G.current=_Wr(x,()=>ne(Ce),ge=>{G.current=null,M.current=null,ge==="interrupted"&&(V.current=z.current),he()})),he();return}!e||!_.current||!V.current||M.current!==null&&M.current!=="end"||x&&ae()-x.scrollTop<=DT||Me({behavior:M.current==="end"?"smooth":"auto"})},[X,e,se,ae,le,re,d,m,ne,Me,P,I,he,x]),g.useEffect(()=>()=>{se(),M.current=null},[se,x]),g.useLayoutEffect(()=>{const Ce=Y.current,Fe=k?.querySelector('[data-slot="message-scroller-item"]')?.dataset.messageId;Y.current=Fe;const tt=Z.current;if(Z.current=null,!tt||!x||Fe===Ce)return;U.current=!1;const Ge=x.scrollHeight-tt.scrollHeight;Ge>0&&(x.scrollTop=tt.scrollTop+Ge)},[k,m,x]);const Ee=g.useMemo(()=>({notifyContentResize:Re,notifyScroll:xe,registerItem:Le,scrollToEnd:Me,scrollToMessage:Pe,scrollToStart:De,setContentElement:C,setRootElement:b,setViewportElement:w,syncAfterScroll:he}),[Re,xe,Le,Me,Pe,De,he]),Te=g.useMemo(()=>({end:D.end,start:D.start}),[D.end,D.start]),ze=g.useMemo(()=>({currentAnchorId:H.currentAnchorId,visibleMessageIds:H.visibleMessageIds}),[H.currentAnchorId,H.visibleMessageIds]);return o.jsx(SG.Provider,{value:Ee,children:o.jsx(r5t.Provider,{value:Te,children:o.jsx(s5t.Provider,{value:ze,children:t})})})}const o5t=g.forwardRef(({className:e,...t},n)=>{const{setRootElement:r}=kG("MessageScroller");return o.jsx("div",{ref:OG(r,n),"data-slot":"message-scroller",className:K("group/message-scroller relative flex size-full min-h-0 flex-col overflow-hidden",e),...t})});o5t.displayName="MessageScroller";const l5t=g.forwardRef(({className:e,onScroll:t,role:n,tabIndex:r,...s},a)=>{const{setViewportElement:i,notifyScroll:l}=kG("MessageScrollerViewport"),c=g.useMemo(()=>OG(i,a),[a,i]);return o.jsx("div",{ref:c,role:n??"region",tabIndex:r??0,"data-slot":"message-scroller-viewport",className:K("[container-type:size] size-full min-h-0 min-w-0 overflow-y-auto overscroll-contain","data-autoscrolling:scrollbar-thumb-transparent data-autoscrolling:scrollbar-track-transparent",e),onScroll:u=>{l(),t?.(u)},...s})});l5t.displayName="MessageScrollerViewport";const c5t=g.forwardRef(({children:e,className:t,spacerClassName:n,role:r,"aria-relevant":s="additions",...a},i)=>{const{setContentElement:l,notifyContentResize:c,syncAfterScroll:u}=kG("MessageScrollerContent"),[d,f]=g.useState(null),h=g.useMemo(()=>OG(l,f,i),[i,l]);return g.useLayoutEffect(()=>{u()},[u]),g.useEffect(()=>{if(!d||typeof MutationObserver>"u")return;const p=new MutationObserver(c);return p.observe(d,{childList:!0,subtree:!1}),()=>p.disconnect()},[d,c]),g.useEffect(()=>{if(!d||typeof ResizeObserver>"u")return;const p=new ResizeObserver(c);return p.observe(d),()=>p.disconnect()},[d,c]),o.jsxs("div",{ref:h,role:r??"log","aria-relevant":s,"data-slot":"message-scroller-content",className:K("flex h-max min-h-full flex-col gap-6",t),...a,children:[e,o.jsx("div",{"aria-hidden":"true","data-message-scroller-spacer":"",hidden:!0,className:n})]})});c5t.displayName="MessageScrollerContent";const u5t=g.forwardRef(({className:e,messageId:t,scrollAnchor:n=!1,...r},s)=>{const a=g.useContext(SG)?.registerItem,i=g.useRef(void 0),l=g.useCallback(c=>{i.current?.(),i.current=void 0,OG(s)(c),!(!c||!t||!a)&&(i.current=a(t,c,n))},[t,s,a,n]);return o.jsx("div",{ref:l,"data-slot":"message-scroller-item","data-message-id":t,"data-scroll-anchor":n?"true":"false",className:K("min-w-0 shrink-0 [contain-intrinsic-size:auto_10rem] [content-visibility:auto]",e),...r})});u5t.displayName="MessageScrollerItem";const d5t=g.forwardRef(({behavior:e="smooth",direction:t="end",className:n,children:r,onClick:s,tabIndex:a,type:i="button",...l},c)=>{const{scrollToEnd:u,scrollToStart:d}=kG("MessageScrollerButton"),{start:f,end:h}=pWr("MessageScrollerButton"),p=t==="start"?f:h;return o.jsx("button",{ref:c,type:i,...l,"data-slot":"message-scroller-button","data-active":p?"true":"false","data-direction":t,tabIndex:p?a:-1,className:K("absolute inset-s-1/2 inline-flex min-h-5 min-w-7 -translate-x-1/2 items-center justify-center rounded-full border border-border1 bg-surface3 text-neutral6 shadow-[0_1px_2px_-1px_oklch(0%_0_0deg/10%),0_8px_20px_-12px_oklch(0%_0_0deg/25%)] transition-[translate,scale,opacity] duration-200 hover:bg-surface4 data-[active=false]:pointer-events-none data-[active=false]:scale-95 data-[active=false]:opacity-0 data-[active=false]:duration-400 data-[active=false]:ease-[cubic-bezier(0.7,0,0.84,0)] data-[active=true]:translate-y-0 data-[active=true]:scale-100 data-[active=true]:opacity-100 data-[active=true]:ease-[cubic-bezier(0.23,1,0.32,1)] data-[direction=end]:bottom-4 data-[direction=end]:data-[active=false]:translate-y-full data-[direction=start]:top-4 data-[direction=start]:data-[active=false]:-translate-y-full rtl:translate-x-1/2 data-[direction=start]:[&_svg]:rotate-180",n),onClick:m=>{p&&(s?.(m),!m.defaultPrevented&&(m.currentTarget.blur(),t==="start"?d({behavior:e}):u({behavior:e})))},children:r??o.jsxs(o.Fragment,{children:[o.jsx(CV,{className:"size-4","aria-hidden":!0}),o.jsx("span",{className:"sr-only",children:t==="end"?"Scroll to end":"Scroll to start"})]})})});d5t.displayName="MessageScrollerButton";const IWr=()=>{const e=g.useContext(SG);return g.useMemo(()=>{if(e)return{scrollToEnd:e.scrollToEnd,scrollToMessage:e.scrollToMessage,scrollToStart:e.scrollToStart}},[e])},AWr=()=>{const e=g.useContext(s5t);return g.useMemo(()=>e?{currentAnchorId:e.currentAnchorId,visibleMessageIds:e.visibleMessageIds}:void 0,[e])},CG=typeof window>"u"?g.useEffect:g.useLayoutEffect,RWr=e=>{const t=e.getBoundingClientRect().height,n=t>0?t:e.scrollHeight;return Math.ceil(n)};function PWr(){const[e,t]=g.useState(null),[n,r]=g.useState(null),s=g.useRef(null),a=g.useCallback(()=>{if(!e)return null;const l=RWr(e);return r(c=>c===l?c:l),l},[e]);CG(()=>{if(!e||(a(),typeof ResizeObserver>"u"))return;const l=()=>{s.current!==null&&window.cancelAnimationFrame(s.current),s.current=window.requestAnimationFrame(()=>{s.current=null,a()})},c=new ResizeObserver(l);return c.observe(e),()=>{c.disconnect(),s.current!==null&&(window.cancelAnimationFrame(s.current),s.current=null)}},[e,a]);const i=g.useMemo(()=>n===null?{}:{height:n},[n]);return{ref:t,height:n,heightStyle:i,measure:a}}const $Wr=360,_Xe=$Wr+80,EXe={currentTurn:void 0,previousTurn:void 0,index:null,phase:"hidden",top:0,transitionKey:0};function f5t({turns:e,currentAnchorId:t,visibleMessageIds:n,label:r="Conversation timeline",className:s,maxHeight:a="calc(100dvh - 12rem)",scrollAreaClassName:i,onSelect:l}){const c=g.useRef(null),u=g.useId(),[d,f]=g.useState(EXe),h=IWr(),p=AWr(),m=e.at(-1)?.messageId,v=t??p?.currentAnchorId??m,y=n??p?.visibleMessageIds??(v?[v]:[]),b=new Set(y),w=d.phase==="entering"||d.phase==="visible"?d.index:null,k=g.useCallback(T=>{if(l){l(T);return}h?.scrollToMessage(T.messageId,{behavior:"smooth",align:"start"})},[h,l]),C=(T,E)=>{const N=c.current?.getBoundingClientRect().top??0,I=E.getBoundingClientRect(),A=e[T];A&&f(P=>{const L=I.top+I.height/2-N;if(P.index===T&&P.phase!=="hidden"&&P.phase!=="exiting")return{...P,top:L};const D=P.currentTurn&&P.currentTurn.key!==A.key&&P.phase!=="hidden"?P.currentTurn:void 0;return{currentTurn:A,previousTurn:D,index:T,phase:"entering",top:L,transitionKey:P.transitionKey+1}})},_=()=>{f(T=>!T.currentTurn||T.phase==="hidden"||T.phase==="exiting"?{...T,index:null}:{...T,index:null,previousTurn:void 0,phase:"exiting",transitionKey:T.transitionKey+1})};return g.useEffect(()=>{if(d.phase!=="entering")return;const T=window.requestAnimationFrame??window.setTimeout,E=window.cancelAnimationFrame??window.clearTimeout;let N;const I=T(()=>{N=T(()=>{f(A=>A.transitionKey===d.transitionKey&&A.phase==="entering"?{...A,phase:"visible"}:A)})});return()=>{E(I),N!==void 0&&E(N)}},[d.phase,d.transitionKey]),g.useEffect(()=>{if(d.phase!=="visible"||!d.previousTurn)return;const T=window.setTimeout(()=>{f(E=>E.transitionKey===d.transitionKey?{...E,previousTurn:void 0}:E)},_Xe);return()=>window.clearTimeout(T)},[d.phase,d.previousTurn,d.transitionKey]),g.useEffect(()=>{if(d.phase!=="exiting")return;const T=window.setTimeout(()=>{f(E=>E.transitionKey===d.transitionKey?EXe:E)},_Xe);return()=>window.clearTimeout(T)},[d.phase,d.transitionKey]),e.length===0?null:o.jsxs("nav",{ref:c,"aria-label":r,"data-testid":"thread-rail",className:K("relative w-8 py-2",s),onMouseLeave:_,onBlur:T=>{const E=T.relatedTarget;(!(E instanceof Node)||!T.currentTarget.contains(E))&&_()},children:[o.jsx(Nr,{"data-testid":"thread-rail-scroll-area",maxHeight:a,className:K("w-8",i),viewPortClassName:"pr-3",children:o.jsx("div",{className:"flex w-4 flex-col items-start gap-2 py-2",children:e.map((T,E)=>{const N=w===null?null:Math.abs(E-w),I=T.messageId===v,A=b.has(T.messageId),P=w===E;return o.jsx(LWr,{turn:T,index:E,distance:N,active:I,inView:A,previewId:P?u:void 0,onHoverChange:C,onSelect:k},T.key)})})}),d.currentTurn&&o.jsx(FWr,{id:u,currentTurn:d.currentTurn,previousTurn:d.previousTurn,phase:d.phase,top:d.top})]})}const MWr=e=>e===0?"w-4":e===1?"w-3":"w-2",DWr=({distance:e,active:t,inView:n})=>e===0||t?"bg-neutral6":n?"bg-neutral5":e===1?"bg-neutral4":"bg-neutral3/60";function LWr({turn:e,index:t,distance:n,active:r,inView:s,previewId:a,onHoverChange:i,onSelect:l}){const c=MWr(n),u=DWr({distance:n,active:r,inView:s});return o.jsx("div",{"data-in-view":s?"true":void 0,"data-active":r?"true":void 0,className:"group/thread-rail-item relative flex items-center",children:o.jsx("button",{type:"button","aria-label":`Jump to ${e.prompt}`,"aria-current":r?"location":void 0,"aria-describedby":a,"data-in-view":s?"true":void 0,"data-active":r?"true":void 0,onClick:()=>l(e),onMouseEnter:d=>i(t,d.currentTarget),onFocus:d=>i(t,d.currentTarget),className:K("relative block h-px cursor-pointer rounded-full transition-[width,background-color] duration-normal ease-out","before:absolute before:inset-x-0 before:-inset-y-1 before:content-['']","focus-visible:ring-2 focus-visible:ring-accent1/40 focus-visible:outline-hidden",c,u)})})}function FWr({id:e,currentTurn:t,previousTurn:n,phase:r,top:s}){const{ref:a,heightStyle:i,measure:l}=PWr(),c=r==="visible"||r==="entering"&&!!n,u="scale-95 opacity-0 blur-xs",d="scale-100 opacity-100 blur-none",f="absolute inset-x-0 top-0 h-full origin-left transition-[opacity,filter,scale] duration-150 ease-in-out will-change-[opacity,filter,scale] motion-reduce:scale-100 motion-reduce:blur-none motion-reduce:transition-none";return g.useLayoutEffect(()=>{l()},[t.key,r,l]),o.jsxs("div",{id:e,"data-testid":"thread-rail-preview","data-visible":c?"true":void 0,className:K("pointer-events-none absolute top-0 left-full z-30 ml-3 w-72 overflow-hidden rounded-xl border border-border1 bg-surface3 text-left shadow-dialog transition-[height,translate,opacity] duration-360 ease-out-custom will-change-[height,translate,opacity] motion-reduce:transition-none",c?"opacity-100":"opacity-0"),style:{...i,translate:`0 calc(${s}px - 50%)`},children:[o.jsx("div",{ref:a,"data-testid":"thread-rail-preview-sizer","aria-hidden":!0,className:"invisible",children:o.jsx(yie,{turn:t,className:"p-3.5"})}),o.jsx("div",{"data-testid":"thread-rail-preview-viewport",className:"absolute inset-0",children:o.jsxs("div",{className:"relative h-full",children:[n&&o.jsx("div",{"data-testid":"thread-rail-preview-previous","aria-hidden":!0,className:K(f,r==="entering"?d:u),children:o.jsx(yie,{turn:n,className:"p-3.5"})},n.key),o.jsx("div",{"data-testid":"thread-rail-preview-current",className:K(f,r==="visible"?d:u),children:o.jsx(yie,{turn:t,className:"p-3.5"})},t.key)]})})]})}function yie({turn:e,className:t,...n}){return o.jsxs("div",{className:t,...n,children:[o.jsx("div",{className:"text-ui-md leading-ui-md text-neutral6 truncate font-medium",children:e.prompt}),e.reply&&o.jsx("p",{className:"text-ui-sm leading-ui-sm text-neutral4 mt-1.5 line-clamp-3",children:e.reply}),(e.files.length>0||e.hiddenFileCount>0)&&o.jsxs("div",{className:"border-border1/60 mt-3 flex flex-wrap items-center gap-2 border-t pt-2.5",children:[e.files.map(r=>o.jsxs("span",{className:"text-ui-sm text-neutral4 inline-flex max-w-44 items-center gap-1.5 truncate",children:[o.jsx(Ll,{className:"size-3.5 shrink-0 opacity-70","aria-hidden":!0}),r]},r)),e.hiddenFileCount>0&&o.jsxs("span",{className:"text-ui-sm text-neutral4 font-medium",children:["+",e.hiddenFileCount]})]})]})}const TXe=120,zWr=2,BWr="clientMessageId",_G=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),kxe=e=>{const t=e.content.metadata,n=_G(t)?t[BWr]:void 0;return typeof n=="string"&&n.length>0?n:e.id},h5t=(e,t)=>{const n=e.replace(/\s+/g," ").trim();return n.length===0?t:n.length<=TXe?n:`${n.slice(0,TXe-3).trimEnd()}...`},p5t=e=>e.content.parts.flatMap(t=>!_G(t)||t.type!=="text"||typeof t.text!="string"?[]:[t.text]).join(`
515
515
  `),_9=(e,t)=>{for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim().length>0)return r}},UWr=e=>{if(!e.startsWith("data:"))try{const t=new URL(e);return t.pathname.split("/").filter(Boolean).pop()||t.hostname||void 0}catch{const t=e.split(/[?#]/)[0]?.split("/").filter(Boolean).pop();return t&&!t.startsWith("data:")?t:void 0}},qWr=e=>{const t=_9(e,["mimeType","mediaType"])??"";return e.type==="image"||t.startsWith("image/")?"Image":t==="application/pdf"?"PDF":t.startsWith("video/")?"Video":t.startsWith("audio/")?"Audio":"File"},VWr=e=>{if(!_G(e))return;const t=_9(e,["type"]);if(t!=="file"&&t!=="image")return;const n=_9(e,["filename","name"]);if(n)return n;const r=_9(e,["url","image","data"]);return(r?UWr(r):void 0)??qWr(e)},HWr=e=>e.content.parts.map(VWr).filter(t=>!!t),WWr=e=>{const t=e.content.metadata?.signal,n=_G(t)?t.type:void 0;return typeof n=="string"?n:e.type},m5t=e=>{if(e.role==="user")return!0;if(e.role!=="signal")return!1;const t=WWr(e);return t==="user"||t==="user-message"},ZWr=(e,t)=>{for(let n=t+1;n<e.length;n+=1){const r=e[n];if(!r)continue;if(m5t(r))return;if(r.role!=="assistant")continue;const s=h5t(p5t(r),"");if(s)return s}},g5t=e=>e.flatMap((t,n)=>{if(!m5t(t))return[];const r=HWr(t),s=r.slice(0,zWr);return[{key:kxe(t),messageId:t.id,prompt:h5t(p5t(t),r.length>0?"Attached file":"User message"),reply:ZWr(e,n),files:s,hiddenFileCount:r.length-s.length}]}),GWr=(e,t)=>{const n=new Blob([JSON.stringify(t,null,2)],{type:"application/json"}),r=URL.createObjectURL(n),s=document.createElement("a");s.href=r,s.download=e,document.body.appendChild(s),s.click(),s.remove(),URL.revokeObjectURL(r)},jXe={jpg:"image/jpg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",pdf:"application/pdf",mp4:"video/mp4",mov:"video/quicktime",webm:"video/webm",mkv:"video/x-matroska",avi:"video/x-msvideo",mpeg:"video/mpeg",mpg:"video/mpeg",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac"},v5t=["https://","http://"],Fje=["gs://","s3://"],QWr=[...v5t,...Fje],YWr=e=>QWr.some(t=>e.startsWith(t)),y5t=e=>v5t.some(t=>e.startsWith(t)),KWr=e=>Fje.some(t=>e.startsWith(t)),NXe=e=>{try{const{pathname:t}=new URL(e),n=t.split(".").pop();return n?jXe[n.toLowerCase()]:void 0}catch{const t=e.split(".").pop()?.split(/[?#]/)[0];return t?jXe[t.toLowerCase()]:void 0}},XWr=async e=>{if(Fje.some(t=>e.startsWith(t)))return NXe(e);try{const t=await fetch(e,{method:"HEAD"});if(!t.ok)throw new Error("Failed to get file content type");const n=t.headers.get("content-type");if(!n)throw new Error("Failed to get file content type");return n}catch{return NXe(e)}},E9=async e=>new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const s=r.result;typeof s=="string"?t(s):n(new Error("Failed to convert file to base64."))},r.onerror=s=>{n(s)},r.readAsDataURL(e)}),b5t=g.createContext(null),JWr=e=>e.startsWith("image/")?"image":e==="application/pdf"?"pdf":e.startsWith("video/")||e.startsWith("audio/")?"video":"text";let eZr=0;const tZr=()=>`att-${Date.now()}-${++eZr}`,nZr=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(typeof r.result=="string"?r.result:""),r.onerror=()=>n(r.error),r.readAsText(e)}),IXe=e=>{const t=YWr(e.name),n=e.type||"text/plain";return{id:tZr(),file:e,name:e.name,contentType:n,kind:JWr(n),isUrl:t}},rZr=async e=>e.kind==="image"?{role:"user",content:[{type:"image",image:e.isUrl?e.name:await E9(e.file),mimeType:e.contentType}]}:e.kind==="pdf"?{role:"user",content:[{type:"file",data:e.isUrl?e.name:await E9(e.file),mimeType:e.contentType,filename:e.name}]}:e.kind==="video"?{role:"user",content:[{type:"file",data:e.isUrl?e.name:await E9(e.file),mimeType:e.contentType,filename:e.name}]}:{role:"user",content:await nZr(e.file)},sZr=({children:e})=>{const[t,n]=g.useState([]),r=g.useCallback(u=>{const d=Array.from(u);d.length!==0&&n(f=>[...f,...d.map(IXe)])},[]),s=g.useCallback(async u=>{const d=await XWr(u)??"application/octet-stream",f=new File([],u,{type:d});n(h=>[...h,IXe(f)])},[]),a=g.useCallback(u=>{n(d=>d.filter(f=>f.id!==u))},[]),i=g.useCallback(()=>n([]),[]),l=g.useCallback(async()=>Promise.all(t.map(rZr)),[t]),c=g.useMemo(()=>({attachments:t,addFiles:r,addUrl:s,remove:a,clear:i,toCoreUserMessages:l}),[t,r,s,a,i,l]);return o.jsx(b5t.Provider,{value:c,children:e})},EG=()=>{const e=g.useContext(b5t);if(!e)throw new Error("useComposerAttachments must be used within a ComposerAttachmentsProvider");return e},aZr=()=>{const[e,t]=g.useState(!1),{addFiles:n,addUrl:r}=EG(),s=()=>{const i=document.createElement("input");i.type="file",i.multiple=!0,i.hidden=!0;const l=()=>{window.removeEventListener("focus",c),i.remove()},c=()=>setTimeout(l,0);i.onchange=u=>{const d=u.target.files;d&&d.length>0&&(n(d),t(!1)),l()},document.body.appendChild(i),window.addEventListener("focus",c),i.click()},a=async i=>{i.preventDefault(),i.stopPropagation();const c=new FormData(i.target).get("url-attachment")?.toString().trim();if(c)try{await r(c),t(!1)}catch{}};return o.jsxs(Vf,{open:e,onOpenChange:t,children:[o.jsx(Xd,{asChild:!0,children:o.jsx(ie,{variant:"default",size:"icon-md",type:"button",tooltip:"Add attachment",children:o.jsx(_r,{className:"text-neutral3 hover:text-neutral6 h-5 w-5"})})}),o.jsxs(Jd,{align:"start",className:"w-80 p-4",children:[o.jsxs("form",{onSubmit:a,className:"flex flex-row items-end gap-2",children:[o.jsxs("div",{className:"w-full space-y-1",children:[o.jsx(Dt,{htmlFor:"url-attachment",className:"text-neutral3 text-ui-md",children:"Public URL"}),o.jsx(jn,{type:"text",name:"url-attachment",id:"url-attachment",className:"w-full",placeholder:"https://placehold.co/600x400/png"})]}),o.jsxs(ie,{type:"submit",className:"h-8!",variant:"default",children:[o.jsx(Qe,{children:o.jsx(Dct,{})}),"Add"]})]}),o.jsx("hr",{className:"border-border1 my-3"}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(ve,{variant:"ui-md",className:"text-neutral3",children:"Or from your computer"}),o.jsxs("button",{type:"button",onClick:s,className:"border-border1 text-neutral3 hover:bg-surface2 active:bg-surface3 flex h-28 w-full flex-col items-center justify-center gap-2 rounded-lg border border-dashed",children:[o.jsx(Nct,{className:"size-8"}),o.jsx(ve,{variant:"ui-lg",children:"Add a local file"})]})]})]})]})},iZr=e=>{const[t,n]=g.useState({isLoading:!1,text:""});return g.useEffect(()=>{if(!e)return;(async()=>{n(a=>({...a,isLoading:!0}));const s=await e.text();n(a=>({...a,isLoading:!1,text:s}))})()},[e]),t},LN="h-full w-full flex items-center justify-center",x5t=({data:e,url:t})=>{const[n,r]=g.useState(!1);return t?o.jsx("a",{href:t,className:LN,target:"_blank",rel:"noreferrer noopener",children:o.jsx(Ll,{className:"text-accent2","aria-label":"View PDF"})}):o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>r(!0),className:LN,type:"button",children:o.jsx(Ll,{className:"text-accent2","aria-label":"View PDF"})}),o.jsx(oZr,{data:e,open:n,onOpenChange:r})]})},oZr=({data:e,open:t,onOpenChange:n})=>o.jsx(pr,{open:t,onOpenChange:n,children:o.jsxs(mr,{className:"max-w-4xl",children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"PDF preview"}),o.jsx(Cs,{children:"Preview of the PDF document"})]}),o.jsx(jr,{children:t&&o.jsx("iframe",{src:e,width:"100%",height:"600px"})})]})}),lZr=e=>e?.startsWith("video/")?{Icon:WKt,label:"Video file"}:e?.startsWith("audio/")?{Icon:UKt,label:"Audio file"}:e?.startsWith("text/")||e==="application/pdf"?{Icon:Ll,label:"Document file"}:{Icon:IV,label:"File"},w5t=({name:e,url:t,contentType:n})=>{const{Icon:r,label:s}=lZr(n),a=o.jsx(r,{className:"text-accent2","aria-label":s});return t?o.jsx("a",{href:t,className:LN,target:"_blank",rel:"noreferrer noopener",title:e,children:a}):o.jsx("div",{className:LN,title:e,children:a})},S5t=({src:e})=>{const[t,n]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>n(!0),type:"button",className:LN,children:o.jsx("img",{src:e,className:"aspect-ratio max-h-[140px] max-w-[320px] object-cover",alt:"Preview"})}),o.jsx(cZr,{src:e,open:t,onOpenChange:n})]})},cZr=({src:e,open:t,onOpenChange:n})=>o.jsx(pr,{open:t,onOpenChange:n,children:o.jsxs(mr,{className:"max-w-4xl",children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Image preview"}),o.jsx(Cs,{children:"Preview of the image"})]}),o.jsx(jr,{children:t&&o.jsx("img",{src:e,alt:"Image"})})]})}),k5t=({data:e})=>{const[t,n]=g.useState(!1),r=e.replace(/<attachment[^>]*>/,"").replace(/<\/attachment>/g,"");return o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>n(!0),className:LN,type:"button",children:o.jsx(Ll,{className:"text-neutral3"})}),o.jsx(uZr,{data:r,open:t,onOpenChange:n})]})},uZr=({data:e,open:t,onOpenChange:n})=>o.jsx(pr,{open:t,onOpenChange:n,children:o.jsxs(mr,{className:"h-[80vh] max-w-4xl",children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Text preview"}),o.jsx(Cs,{children:"Preview of the text file"})]}),o.jsx(jr,{children:t&&o.jsx("div",{className:"whitespace-pre-wrap",children:e})})]})}),dZr=({file:e})=>{const{isLoading:t,text:n}=iZr(e);return o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:t?o.jsx(Vt,{}):o.jsx(k5t,{data:n})})},fZr=({attachment:e})=>{const[t,n]=g.useState({isLoading:!1,text:""});return g.useEffect(()=>{let r=!1;return(async()=>{if(!e.file)return;n(i=>({...i,isLoading:!0}));const a=await E9(e.file);r||n(i=>({...i,isLoading:!1,text:a}))})(),()=>{r=!0}},[e]),o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:t.isLoading?o.jsx(Vt,{}):o.jsx(x5t,{data:t.text,url:e.isUrl?e.name:void 0})})},hZr=({attachment:e})=>{const[t,n]=g.useState(e.isUrl?e.name:"");return g.useEffect(()=>{if(e.isUrl){n(e.name);return}const r=URL.createObjectURL(e.file);return n(r),()=>URL.revokeObjectURL(r)},[e]),o.jsx(S5t,{src:t})},pZr=({attachment:e})=>{const{remove:t}=EG();return o.jsxs("div",{className:"relative",children:[o.jsx(Gut,{children:o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx("div",{className:"bg-surface3 border-border1 size-16 overflow-hidden rounded-lg border",children:e.kind==="image"?o.jsx(hZr,{attachment:e}):e.kind==="pdf"?o.jsx(fZr,{attachment:e}):e.kind==="video"?o.jsx(w5t,{name:e.name,url:e.isUrl&&y5t(e.name)?e.name:void 0,contentType:e.contentType}):o.jsx(dZr,{file:e.file})})}),o.jsx(yn,{side:"top",children:e.name})]})}),o.jsx(ie,{variant:"default",size:"icon-sm",type:"button",tooltip:"Remove file",onClick:()=>t(e.id),className:"text-neutral3 hover:text-neutral6 bg-surface1 hover:bg-surface2 absolute -top-2 -right-2",children:o.jsx(Qe,{children:o.jsx(or,{})})})]})},mZr=()=>{const{attachments:e}=EG();return e.length===0?null:o.jsx("div",{className:"absolute inset-x-0 bottom-full px-2","data-attachments-row":!0,children:o.jsx("div",{className:"mx-auto w-full max-w-3xl overflow-x-auto",children:o.jsx("div",{className:"flex flex-row items-center gap-4 px-3 pt-3 pb-1",children:e.map(t=>o.jsx(pZr,{attachment:t},t.id))})})})},gZr=(e,t)=>{const n=Ye(),[r,s]=g.useState(!1),[a,i]=g.useState(!1),l=g.useRef(null);g.useEffect(()=>{let d=!1;return e?(n.getAgent(e).voice.getSpeakers(t).then(h=>{d||s(h.length>0)}).catch(()=>{d||s(!1)}),()=>{d=!0}):(s(!1),()=>{d=!0})},[e,n,t]);const c=g.useCallback(()=>{l.current?.(),l.current=null,typeof window<"u"&&window.speechSynthesis&&window.speechSynthesis.cancel(),i(!1)},[]),u=g.useCallback(async d=>{if(d){if(c(),i(!0),e&&r)try{const h=await n.getAgent(e).voice.speak(d);if(!h.body)throw new Error("No audio stream returned from voice.speak()");const p=await VCn(h.body,()=>i(!1));l.current=p??null;return}catch(f){i(!1),yu.error(f instanceof Error?f.message:"Voice generation failed.");return}if(typeof window<"u"&&window.speechSynthesis){const f=new SpeechSynthesisUtterance(d);f.onend=()=>i(!1),f.onerror=()=>i(!1),window.speechSynthesis.speak(f);return}i(!1)}},[e,n,r,c]);return g.useEffect(()=>()=>c(),[c]),{isSpeaking:a,readAloud:u,stop:c}},AXe=12;function vZr({containerRef:e}){const[t,n]=g.useState([]),[r,s]=g.useState(null),a=g.useRef(""),i=g.useRef(0),l=g.useCallback(()=>{const u=e.current;if(!u){a.current!==""&&(a.current="",n([]));return}const d=u.getBoundingClientRect(),f=Array.from(u.querySelectorAll("[data-om-badge]"));if(f.length===0){a.current!==""&&(a.current="",n([]));return}const h=[];for(let m=0;m<f.length;m++){const v=f[m],y=v.getAttribute("data-om-badge")||"",b=v.getAttribute("data-om-state")||"complete",x=v.getAttribute("data-om-type")||"observation",w=v.getBoundingClientRect();let k;const C=yZr(f,m,x);C?k=C.getBoundingClientRect().bottom+AXe-d.top:k=0;const T=w.bottom+AXe-d.top-k;T<=0||h.push({cycleId:y,omType:x,state:b,top:k,height:T})}const p=JSON.stringify(h);p!==a.current&&(a.current=p,n(h))},[e]);if(g.useEffect(()=>{const u=e.current;if(!u)return;l();const d=new ResizeObserver(()=>{cancelAnimationFrame(i.current),i.current=requestAnimationFrame(l)});d.observe(u);const f=new MutationObserver(()=>{cancelAnimationFrame(i.current),i.current=requestAnimationFrame(l)});return f.observe(u,{childList:!0,subtree:!0}),()=>{cancelAnimationFrame(i.current),d.disconnect(),f.disconnect()}},[l,e]),g.useEffect(()=>{const u=e.current;if(!u)return;const d=h=>{const p=h.target.closest("[data-om-badge]");p&&s(p.getAttribute("data-om-badge"))},f=h=>{h.target.closest("[data-om-badge]")&&s(null)};return u.addEventListener("mouseover",d),u.addEventListener("mouseout",f),()=>{u.removeEventListener("mouseover",d),u.removeEventListener("mouseout",f)}},[e]),t.length===0)return null;const c=t[t.length-1]?.cycleId??null;return o.jsx("div",{className:"pointer-events-none absolute inset-0",style:{zIndex:0},children:t.map(u=>{const d=u.cycleId===c,f=u.cycleId===r,h=r?f:d;return o.jsx(bZr,{highlight:u,visible:h},u.cycleId)})})}function yZr(e,t,n){for(let r=t-1;r>=0;r--){const s=e[r];if(s.getAttribute("data-om-state")!=="failed"&&(n==="observation"||s.getAttribute("data-om-type")==="reflection"))return s}return null}function bZr({highlight:e,visible:t}){const n=xZr(e.state),r=e.state.startsWith("buffering");return o.jsx("div",{className:"absolute right-0 left-0 transition-opacity duration-200",style:{top:e.top,height:e.height,border:`2px ${r?"dashed":"solid"} ${n}`,borderRadius:"0.5rem",opacity:t?1:0}})}function xZr(e){switch(e){case"complete":return"rgba(34, 197, 94, 0.4)";case"loading":return"rgba(59, 130, 246, 0.4)";case"failed":return"rgba(239, 68, 68, 0.4)";case"disconnected":return"rgba(234, 179, 8, 0.4)";case"buffering":return"rgba(156, 163, 175, 0.45)";case"buffering-complete":return"rgba(156, 163, 175, 0.45)";case"buffering-failed":return"rgba(239, 68, 68, 0.4)";case"activated":return"rgba(34, 197, 94, 0.4)";default:return"rgba(34, 197, 94, 0.4)"}}const O5t=g.createContext(null);function wZr({children:e,...t}){return o.jsx(O5t.Provider,{value:t,children:e})}function TG(){return g.useContext(O5t)}function C5t({open:e,onOpenChange:t,input:n,onInputChange:r,requestContext:s,initialGroundTruth:a=""}){const[i,l]=g.useState(a),[c,u]=g.useState("");g.useEffect(()=>{e&&l(a)},[e,a]);const{data:d,isLoading:f}=Xg(),{addItem:h}=wi(),p=g.useMemo(()=>d?.datasets??[],[d?.datasets]),m=g.useCallback(async()=>{if(!c){Ve.error("Please select a dataset");return}let v;try{v=JSON.parse(n)}catch{Ve.error("Input must be valid JSON");return}let y;if(i.trim())try{y=JSON.parse(i)}catch{Ve.error("Ground Truth must be valid JSON");return}try{const b=s&&Object.keys(s).length>0;await h.mutateAsync({datasetId:c,input:v,groundTruth:y,...b?{requestContext:s}:{}});const x=p.find(w=>w.id===c);Ve.success(`Item saved to "${x?.name}"`),t(!1),u(""),r(""),l("")}catch(b){Ve.error(`Failed to save item: ${b instanceof Error?b.message:"Unknown error"}`)}},[n,i,c,s,h,p,t,r]);return o.jsx(pr,{open:e,onOpenChange:t,children:o.jsxs(mr,{className:"max-w-lg",children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Save to Dataset"}),o.jsx(Cs,{children:"Save as a dataset item for evaluation."})]}),o.jsxs(jr,{className:"space-y-4 py-1",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"ds-target",children:"Dataset"}),o.jsxs(la,{value:c,onValueChange:u,disabled:h.isPending||f,children:[o.jsx(ua,{id:"ds-target",children:o.jsx(ca,{placeholder:f?"Loading...":"Select a dataset"})}),o.jsx(da,{children:p.length===0?o.jsx("div",{className:"text-neutral4 px-2 py-4 text-center text-sm",children:"No datasets available"}):p.map(v=>o.jsx(xr,{value:v.id,children:v.name},v.id))})]})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{children:"Input (JSON)"}),o.jsx(Gr,{value:n,onChange:r,showCopyButton:!1,className:"max-h-[240px] min-h-[120px]"})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{children:"Ground Truth (JSON, optional)"}),o.jsx(Gr,{value:i,onChange:l,showCopyButton:!1,className:"max-h-[160px] min-h-[80px]"})]})]}),o.jsxs(Bl,{className:"px-6",children:[o.jsx(ie,{variant:"default",size:"sm",onClick:()=>t(!1),children:"Cancel"}),o.jsxs(ie,{variant:"primary",size:"sm",onClick:m,disabled:h.isPending||!c||p.length===0,children:[o.jsx(Qe,{size:"sm",children:o.jsx(Qu,{})}),h.isPending?"Saving...":"Save Item"]})]})]})})}function SZr({messageText:e}){return TG()?.enabled?o.jsx(kZr,{messageText:e}):null}function kZr({messageText:e}){const t=TG(),[n,r]=g.useState(!1),[s,a]=g.useState(""),i=g.useCallback(()=>{a(JSON.stringify(e,null,2)),r(!0)},[e]);return o.jsxs(o.Fragment,{children:[o.jsx(ie,{variant:"default",size:"icon-md",tooltip:"Save to dataset",className:"text-neutral3 hover:text-neutral6 bg-transparent",onClick:i,children:o.jsx(hm,{className:"h-4 w-4"})}),o.jsx(C5t,{open:n,onOpenChange:r,input:s,onInputChange:a,requestContext:t?.requestContext})]})}function OZr(){return TG()?.enabled?o.jsx(CZr,{}):null}function CZr(){const e=TG(),t=Ye(),[n,r]=g.useState(!1),[s,a]=g.useState(""),[i,l]=g.useState(""),[c,u]=g.useState(!1),d=g.useCallback(async()=>{u(!0);try{const h=(await t.listThreadMessages(e.threadId,{agentId:e.agentId}))?.messages??[],p=h.length-1,m=h[p];if(m&&m.role==="assistant"){const v=h.slice(0,p);a(JSON.stringify(v,null,2)),l(JSON.stringify(m,null,2))}else a(JSON.stringify(h,null,2)),l("");r(!0)}catch(f){Ve.error(`Failed to fetch thread messages: ${f instanceof Error?f.message:"Unknown error"}`)}finally{u(!1)}},[t,e.threadId,e.agentId]);return o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",onClick:d,disabled:c,className:"text-neutral3 hover:text-neutral5 text-ui-xs leading-ui-xs mx-auto flex cursor-pointer items-center gap-1.5 py-3 transition-colors disabled:opacity-50",children:[c?o.jsx(Vt,{className:"h-3.5 w-3.5"}):o.jsx(hm,{className:"h-3.5 w-3.5"}),"Save full conversation to dataset"]}),o.jsx(C5t,{open:n,onOpenChange:r,input:s,onInputChange:a,requestContext:e.requestContext,initialGroundTruth:i})]})}const _5t=`
516
516
 
517
517
  `,E5t=Array.from({length:6},()=>"").join(" ");function _Zr(e){if(e.type==="text")return e.text;if(e.type==="reasoning")return e.reasoning}function T5t(e){return e.map(t=>_Zr(t)??E5t).join(_5t)}function EZr(e,t){const n=T5t(e);if(t.length>=n.length)return e;const r=[];let s=0;for(const a of e){const i=s===0?0:s+_5t.length;if(a.type!=="text"&&a.type!=="reasoning"){if(s=i+E5t.length,t.length<s)break;r.push(a);continue}const l=a.type==="text"?a.text:a.reasoning;s=i+l.length;const c=t.slice(i,s);if(c===l){r.push(a);continue}c&&r.push(a.type==="text"?{...a,text:c}:{...a,reasoning:c});break}return r}function TZr(e,t){const n=zFr(T5t(e),t);return EZr(e,n)}const jZr=({part:e,metadata:t,revealing:n})=>o.jsx(nje,{text:e.text??"",metadata:t,streaming:e.state==="streaming"||n}),NZr=({part:e})=>e.type==="data-signal"&&Y4(e.data)?o.jsx(L3t,{signal:e.data}):null,bie=({className:e,...t})=>o.jsx("div",{className:K("rounded-lg border border-border1 bg-surface2 p-3 text-sm",e),...t}),IZr=({className:e,...t})=>o.jsx("legend",{className:K("mb-3 font-medium text-neutral6",e),...t}),AZr=({className:e,...t})=>o.jsx("span",{className:K("block text-ui-xs font-normal text-neutral3",e),...t}),RZr=({type:e,label:t,description:n,className:r,...s})=>o.jsxs("label",{className:K("flex cursor-pointer items-start gap-2 rounded-md border border-border1 bg-surface3 px-3 py-2 text-neutral5 transition-colors hover:bg-surface4 has-[:checked]:border-border2 has-[:checked]:bg-surface4 has-[:disabled]:cursor-not-allowed has-[:disabled]:opacity-50",r),children:[o.jsx("input",{type:e,className:"mt-0.5 accent-current",...s}),o.jsxs("span",{children:[o.jsx("span",{className:"block",children:t}),n?o.jsx(AZr,{children:n}):null]})]}),RXe=({children:e="Submit answer",...t})=>o.jsx(ie,{type:"button",size:"sm",variant:"primary",...t,children:e}),PXe=({children:e="Submitting…",className:t,...n})=>o.jsx("span",{role:"status",className:K("text-ui-xs text-neutral3",t),...n,children:e}),PZr=({result:e,className:t,...n})=>o.jsxs("div",{role:e.isError?"alert":"status",className:K("space-y-2 rounded-md bg-surface3 p-3 text-neutral5",e.isError&&"text-error",t),...n,children:[o.jsx(bt,{size:"xs",variant:e.isError?"red":"green",children:e.isError?"Error":"Answered"}),o.jsx("p",{children:e.content})]}),$Zr=e=>e?.filter(t=>!!(t&&typeof t.label=="string"&&t.label))??[],MZr=({payload:e,options:t,result:n,isAnswered:r=!1,isSubmitting:s=!1,onSubmit:a,footer:i,...l})=>{const c=g.useId(),[u,d]=g.useState(""),[f,h]=g.useState([]);if(n||r)return o.jsxs(bie,{"data-testid":"ask-user",...l,children:[o.jsx("p",{className:"text-neutral6 mb-2 font-medium",children:e.question}),n?o.jsx(PZr,{result:n}):o.jsx(bt,{variant:"green",children:"Answered"})]});const p=()=>{const y=u.trim();y&&!s&&a(y)},m=y=>{y.key==="Enter"&&(y.preventDefault(),p())};if(t.length===0)return o.jsxs(bie,{"data-testid":"ask-user",...l,children:[o.jsx("label",{className:"text-neutral6 mb-2 block font-medium",htmlFor:c,children:e.question}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(jn,{id:c,value:u,onChange:y=>d(y.target.value),onKeyDown:m,placeholder:"Type your answer...",disabled:s,size:"sm"}),o.jsx(RXe,{"aria-label":"Submit answer",disabled:s||!u.trim(),onClick:p,children:"Submit"})]}),s?o.jsx(PXe,{className:"mt-2 block"}):null,i]});const v=e.selectionMode==="multi_select";return o.jsx(bie,{"data-testid":"ask-user",...l,children:o.jsxs("fieldset",{disabled:s,className:"space-y-2",children:[o.jsx(IZr,{children:e.question}),t.map(y=>{const b=f.includes(y.label);return o.jsx(RZr,{type:v?"checkbox":"radio",name:c,label:y.label,description:y.description,disabled:s,checked:b,onChange:()=>{if(!s){if(!v){h([y.label]),a(y.label);return}h(x=>x.includes(y.label)?x.filter(w=>w!==y.label):[...x,y.label])}}},y.label)}),v?o.jsx(RXe,{disabled:s||f.length===0,onClick:()=>a(f),children:"Submit answer"}):null,s?o.jsx(PXe,{}):null,i]})})},DZr=({payload:e,...t})=>{const n=$Zr(e.options),r=JSON.stringify([e.question,n.map(s=>s.label),e.selectionMode]);return o.jsx(MZr,{payload:e,options:n,...t},r)},LZr=({toolCallId:e,suspendPayload:t,result:n})=>{const{approveToolcall:r,isRunning:s,toolCallApprovals:a}=Lje(),i=a?.[e]?.status==="approved",l=c=>{r(e,c)};return o.jsx(DZr,{"data-testid":"ask-user-badge",payload:t,result:n,isAnswered:i,isSubmitting:s,onSubmit:l,className:"mb-4 w-full max-w-full"})};function FZr(e){return typeof e=="object"&&e!==null&&"question"in e&&typeof e.question=="string"}function zZr(e){if(typeof e=="object"&&e!==null&&typeof e.content=="string")return e}const BZr=({toolName:e,toolCallId:t,output:n,metadata:r})=>{const s=(r?.suspendedTools?.[e]??r?.suspendedTools?.[t])?.suspendPayload;return FZr(s)?o.jsx(LZr,{toolCallId:t,suspendPayload:s,result:zZr(n)}):null};function UZr(e){return e.metadata?.systemReminder||e.metadata?.dynamicAgentsMdReminder?!0:e.role!=="user"?!1:Array.isArray(e.parts)?e.parts.some(t=>t.type==="text"&&typeof t.text=="string"&&t.text.includes("<system-reminder")):typeof e.content=="string"&&e.content.includes("<system-reminder")}function T9(e){return e.filter(t=>!UZr(t))}function qZr(e,t={}){const n=new GOn().add(e,"memory");return t.version==="v7"?T9(n.get.all.aiV7.ui()):t.version==="v6"?T9(n.get.all.aiV6.ui()):T9(n.get.all.aiV5.ui())}function VZr(e){return T9(qZr(e))}const j5t=(e,t)=>Number(e.toPrecision(t)),HZr=({startedAt:e,endedAt:t})=>{const[n,r]=g.useState(e);return g.useEffect(()=>{if(r(e),t!=null)return;const a=setInterval(()=>{r(Date.now())},100);return()=>clearInterval(a)},[e,t]),t!=null?t-e:n-e},WZr=({backgroundTaskTaskId:e,backgroundTaskStartedAt:t,backgroundTaskCompletedAt:n,backgroundTaskSuspendedAt:r,open:s,onOpenChange:a})=>{const{data:i}=Zrr(e,!!n||!!r),{tasks:l}=Wrr({taskId:e,enabled:!n&&!r}),c=HZr({startedAt:new Date(t).getTime(),endedAt:n?new Date(n).getTime():r?new Date(r).getTime():void 0}),u=i||l[e],d=u?.args,f=u?.result,h=u?.suspendPayload;let p=null;try{const{__mastraMetadata:y,_background:b,...x}=typeof d=="object"?d:JSON.parse(d);p=o.jsx(Gr,{data:x})}catch{p=o.jsx("pre",{className:"bg-surface4 overflow-x-auto rounded-md p-4 whitespace-pre",children:d})}const m=typeof f=="string"?o.jsx("pre",{className:"bg-surface4 overflow-x-auto rounded-md p-4 whitespace-pre",children:f}):o.jsx(Gr,{data:f}),v=typeof h=="string"?o.jsx("pre",{className:"bg-surface4 overflow-x-auto rounded-md p-4 whitespace-pre",children:h}):o.jsx(Gr,{data:h});return o.jsx(pr,{open:s,onOpenChange:a,children:o.jsxs(mr,{children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Background Task Metadata"}),o.jsx(Cs,{children:"View the metadata of the background task."})]}),o.jsxs(jr,{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(ve,{className:"text-neutral3",children:"Background Task Duration"}),o.jsxs(ve,{className:"text-neutral6 text-ui-md",children:[j5t(c,3),"ms"]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(ve,{className:"text-neutral3",children:"Background Task Arguments"}),p]}),v!==void 0&&h&&o.jsxs("div",{className:"space-y-2",children:[o.jsx(ve,{className:"text-neutral3",children:"Background Task Suspend Data"}),v]}),m!==void 0&&f&&o.jsxs("div",{className:"space-y-2",children:[o.jsx(ve,{className:"text-neutral3",children:"Background Task Result"}),m]})]})]})})},zje=({backgroundTask:e})=>{const[t,n]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsx(ie,{variant:"default",size:"icon-md",tooltip:"Show background task information",onClick:()=>n(r=>!r),children:e.completedAt||e.suspendedAt?o.jsx(Gct,{className:"text-neutral3 size-5"}):o.jsx(Vs,{className:"text-neutral3 size-5 animate-spin"})}),o.jsx(WZr,{backgroundTaskTaskId:e.taskId,backgroundTaskStartedAt:e.startedAt,backgroundTaskCompletedAt:e.completedAt,backgroundTaskSuspendedAt:e.suspendedAt,open:t,onOpenChange:n})]})},ZZr=({selectionReason:e,open:t,onOpenChange:n,input:r})=>{let s=null;if(r)try{s=typeof r=="object"?o.jsx(Gr,{data:r}):o.jsx(Gr,{data:JSON.parse(r)})}catch{s=o.jsx("pre",{className:"whitespace-pre-wrap",children:r})}return o.jsx(pr,{open:t,onOpenChange:n,children:o.jsxs(mr,{children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Agent Network Metadata"}),o.jsx(Cs,{children:"View the metadata of the agent's network choice."})]}),o.jsxs(jr,{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(ve,{className:"text-neutral3",children:"Selection Reason"}),o.jsx("div",{className:"text-neutral6 text-ui-md",children:e})]}),s&&o.jsxs("div",{className:"space-y-2",children:[o.jsx(ve,{className:"text-neutral3",children:"Input"}),o.jsx("div",{className:"text-neutral6 text-ui-md",children:s})]})]})]})})},Bje=({selectionReason:e,input:t})=>{const[n,r]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsx(ie,{variant:"default",size:"icon-md",tooltip:"Show selection reason",onClick:()=>r(s=>!s),children:o.jsx(Gct,{className:"text-neutral3 size-5"})}),o.jsx(ZZr,{selectionReason:e||"",open:n,onOpenChange:r,input:t})]})},cy=({children:e})=>o.jsx(ve,{as:"p",variant:"ui-xs",className:"text-icon3 pb-1 select-none",children:e}),lA=({toolCalled:e,toolCallId:t,toolApprovalMetadata:n,toolName:r,isNetwork:s,isGenerateMode:a})=>{const{approveToolcall:i,declineToolcall:l,approveToolcallGenerate:c,declineToolcallGenerate:u,isRunning:d,toolCallApprovals:f,approveNetworkToolcall:h,declineNetworkToolcall:p,networkToolCallApprovals:m}=Lje(),v=()=>{s?h(r,n?.runId):a?c(t):i(t)},y=()=>{s?p(r,n?.runId):a?u(t):l(t)},b=s?m?.[n?.runId?`${n.runId}-${r}`:r]?.status:f?.[t]?.status;return n&&!e?o.jsxs("div",{children:[o.jsx(cy,{children:"Approval required"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(ie,{onClick:v,disabled:d||!!b,className:b==="approved"?"text-accent1!":"",children:[o.jsx(Qe,{children:o.jsx(Ur,{})}),"Approve"]}),o.jsxs(ie,{onClick:y,disabled:d||!!b,className:b==="declined"?"text-accent2!":"",children:[o.jsx(Qe,{children:o.jsx(or,{})}),"Decline"]})]})]}):null},GZr=({agentId:e,messages:t=[],metadata:n,toolCallId:r,toolApprovalMetadata:s,toolName:a,isNetwork:i,suspendPayload:l,toolCalled:c,isComplete:u=!1,keepOpenForStreamingChildMessages:d=!1})=>{const f=n?.mode==="network"?n.routingDecision:void 0,h=n?.mode==="network"?f?.selectionReason??n.selectionReason:void 0,p=n?.mode==="network"?f??n.agentInput:void 0,m=n?.mode==="stream"||n?.mode==="network"||n?.mode==="generate"?n?.requireApprovalMetadata:void 0,v=n?.mode==="stream"||n?.mode==="network"||n?.mode==="generate"?n?.suspendedTools:void 0,y=(n?.mode==="stream"||n?.mode==="generate")&&n?.backgroundTasks?n.backgroundTasks[r]:void 0,b=t.length>0&&t.every(C=>C.type==="text"?!0:C.toolOutput!==void 0);let x=b;i&&(x=c??b);const w=u&&!s&&!d;let k=typeof l=="string"?o.jsx(l2,{copyText:l,className:"text-icon3",children:l}):o.jsx(Gr,{data:l,"data-testid":"tool-suspend-payload"});return o.jsxs(sL,{"data-testid":"agent-badge",icon:o.jsx(Ri,{className:"text-accent1"}),title:e,initialCollapsed:w,extraInfo:n?.mode==="network"?o.jsx(Bje,{selectionReason:h??"",input:p}):y?.taskId&&y?.startedAt?o.jsx(zje,{backgroundTask:y}):null,children:[t.map((C,_)=>{if(C.type==="text")return o.jsx(DDt,{children:C.content},_);let T;try{T=typeof C.toolOutput=="string"?JSON.parse(C.toolOutput):C.toolOutput}catch{T=C.toolOutput}return o.jsx(qe.Fragment,{children:o.jsx(mAe,{toolName:C.toolName,input:C.args,output:T,state:"output-available",toolCallId:C.toolCallId,metadata:{mode:"stream",requireApprovalMetadata:m,suspendedTools:v}})},_)}),k!==void 0&&l&&o.jsxs("div",{children:[o.jsx(cy,{children:"Agent suspend payload"}),k]}),o.jsx(lA,{toolCalled:x,toolCallId:r,toolApprovalMetadata:s,toolName:a,isNetwork:i,isGenerateMode:n?.mode==="generate"})]})},QZr=e=>{const t=e.find(r=>r.role==="assistant");if(!t)return[];const n=[];for(const r of t.parts??[]){const s=r;if(typeof r.type=="string"&&r.type.startsWith("tool-")){const a=r.type.substring(5),i=a.startsWith("workflow-");n.push({type:"tool",toolCallId:s.toolCallId,toolName:a,args:s.input,toolOutput:i?{...s.output?.result,runId:s.output?.runId}:s.output})}r.type==="text"&&n.push({type:"text",content:s.text})}return n},YZr=({agentId:e,result:t,metadata:n,toolCallId:r,toolApprovalMetadata:s,toolName:a,isNetwork:i,suspendPayload:l,toolCalled:c,isComplete:u})=>{const d=!!(t?.subAgentThreadId&&!t.text&&!t.subAgentToolResults?.length),{data:f,isLoading:h}=$W({threadId:d?t?.subAgentThreadId:void 0,agentId:e,memory:!0});if(h)return o.jsx(_je,{});const p=f?.messages?VZr(f.messages):[];let m=t?.childMessages?.length?t.childMessages:void 0;if(!m&&t?.subAgentToolResults?.length){const y=t.subAgentToolResults.map(b=>({type:"tool",toolName:b.toolName,toolCallId:b.toolCallId,args:b.args,toolOutput:b.result}));t.text&&y.push({type:"text",content:t.text}),m=y}!m&&t?.text&&(m=[{type:"text",content:t.text}]),m||(m=QZr(p));const v=!!(t&&Object.prototype.hasOwnProperty.call(t,"childMessages"));return o.jsx(GZr,{agentId:e,messages:m??[],keepOpenForStreamingChildMessages:v,metadata:n,toolCallId:r,toolApprovalMetadata:s,toolName:a,isNetwork:i,suspendPayload:l,toolCalled:c,isComplete:u})},KZr=e=>o.jsxs("svg",{width:"126",height:"85",viewBox:"0 0 126 85",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{d:"M119.322 35.1641C119.322 50.36 94.1055 62.6787 62.9998 62.6787C31.894 62.6787 6.67773 50.36 6.67773 35.1641V49.8368C6.67773 65.0327 31.894 77.3514 62.9998 77.3514C94.1055 77.3514 119.322 65.0327 119.322 49.8368V35.1641Z",fill:"#2E2E2E",fillOpacity:"0.9"}),o.jsx("path",{d:"M119.322 35.1641C119.322 50.36 94.1055 62.6787 62.9998 62.6787C31.894 62.6787 6.67773 50.36 6.67773 35.1641M119.322 35.1641C119.322 19.9681 94.1055 7.64941 62.9998 7.64941C31.894 7.64941 6.67773 19.9681 6.67773 35.1641M119.322 35.1641V49.8368C119.322 65.0327 94.1055 77.3514 62.9998 77.3514C31.894 77.3514 6.67773 65.0327 6.67773 49.8368V35.1641",stroke:"#424242"}),o.jsx("path",{d:"M63.0002 0.96875C28.5152 0.96875 0.55957 15.6489 0.55957 33.7578V51.2433C0.55957 69.3522 28.5152 84.0323 63.0002 84.0323C97.4853 84.0323 125.441 69.3522 125.441 51.2433V33.7578C125.441 15.6489 97.4853 0.96875 63.0002 0.96875Z",stroke:"#707070"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M95.8997 32.6647C98.4806 33.9355 98.4744 36.0012 95.8997 37.2689L89.6657 40.3384C87.0848 41.6091 82.8892 41.6061 80.3146 40.3384L74.0805 37.2689C71.4996 35.9981 71.5059 33.9324 74.0805 32.6647L80.3146 29.5952C82.8955 28.3244 87.091 28.3275 89.6657 29.5952L95.8997 32.6647ZM74.0805 21.9215C76.6614 23.1923 76.6552 25.258 74.0805 26.5257L67.8465 29.5952C65.2656 30.866 61.0701 30.8629 58.4954 29.5952L52.2613 26.5257C49.6804 25.255 49.6867 23.1892 52.2613 21.9215L58.4954 18.852C61.0763 17.5813 65.2718 17.5843 67.8465 18.852L74.0805 21.9215ZM74.0805 43.4079C76.6614 44.6786 76.6552 46.7444 74.0805 48.0121L67.8465 51.0816C65.2656 52.3523 61.0701 52.3493 58.4954 51.0816L52.2613 48.0121C49.6804 46.7413 49.6867 44.6756 52.2613 43.4079L58.4954 40.3384C61.0763 39.0676 65.2718 39.0707 67.8465 40.3384L74.0805 43.4079ZM52.2613 32.6647C54.8422 33.9355 54.836 36.0012 52.2613 37.2689L46.0273 40.3384C43.4464 41.6091 39.2509 41.6061 36.6762 40.3384L30.4422 37.2689C27.8613 35.9981 27.8675 33.9324 30.4422 32.6647L36.6762 29.5952C39.2571 28.3244 43.4526 28.3275 46.0273 29.5952L52.2613 32.6647Z",fill:"#A9A9A9"})]});let $Xe;const N5t=()=>$Xe??=Promise.all([Va(()=>import("./standalone-Dfz2oS5J.js"),[],import.meta.url),Va(()=>import("./babel-lWBcy2sH.js"),[],import.meta.url),Va(()=>import("./estree-Dd9JfUIE.js"),[],import.meta.url)]).catch(e=>{throw $Xe=void 0,e}),kj=async e=>{const[t,n,r]=await N5t();return await t.format(e,{semi:!1,parser:"json",printWidth:80,tabWidth:2,plugins:[n,r]})},XZr=async e=>{const[t,n,r]=await N5t();return await t.format(e,{parser:"babel-ts",printWidth:80,tabWidth:2,plugins:[n,r]})},PD=e=>{try{const t=JSON.parse(e);return!!t&&typeof t=="object"}catch{return!1}},JZr=(e,t)=>{let n;try{n=typeof e=="object"?e:JSON.parse(e)}catch{return null}const r=n?.code;return typeof r!="string"?null:t==null?{code:r}:typeof t=="object"&&typeof t.success=="boolean"&&("result"in t||"logs"in t||"error"in t)?{code:r,result:t}:null},eGr=({toolName:e,code:t,result:n,metadata:r,toolCallId:s,toolApprovalMetadata:a,isNetwork:i,toolCalled:l})=>{const c=n?.logs??[],u=n?.error,d=n!==void 0&&n.result!==void 0,f=l??n!==void 0,[h,p]=g.useState(t);return g.useEffect(()=>{let m=!1;return XZr(t).then(v=>{m||p(v)}).catch(()=>{m||p(t)}),()=>{m=!0}},[t]),o.jsx(sL,{"data-testid":"code-mode-badge",icon:o.jsx(KZr,{className:"text-accent6"}),title:e,initialCollapsed:!a,children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx(cy,{children:"Program"}),o.jsx("div",{"data-testid":"code-mode-program",children:o.jsx(tje,{code:h,lang:"typescript"})})]}),u&&o.jsxs("div",{children:[o.jsx(cy,{children:"Error"}),o.jsxs("pre",{"data-testid":"code-mode-error",className:"bg-surface4 text-error rounded-md px-3 py-2 font-mono text-xs leading-normal break-words whitespace-pre-wrap",children:[u.name?`${u.name}: `:"",u.message,typeof u.line=="number"?` (line ${u.line})`:""]})]}),d&&o.jsxs("div",{children:[o.jsx(cy,{children:"Result"}),typeof n.result=="string"?o.jsx("pre",{className:"bg-surface4 max-h-60 overflow-auto rounded-md px-3 py-2 font-mono text-xs leading-normal break-words whitespace-pre-wrap","data-testid":"code-mode-result",children:n.result}):o.jsx(Gr,{data:n.result,"data-testid":"code-mode-result"})]}),c.length>0&&o.jsxs("div",{children:[o.jsx(cy,{children:"Logs"}),o.jsx("pre",{"data-testid":"code-mode-logs",className:"max-h-60 overflow-auto rounded-md bg-black px-3 py-2 font-mono text-xs leading-normal break-words whitespace-pre-wrap text-neutral-300",children:c.join(`
@@ -663,7 +663,7 @@ Token usage: ${n} input + ${r} output = ${s} total`:`The model stopped generatin
663
663
  "groundTruth": "Expected result (optional)",
664
664
  "metadata": { "key": "value" } // optional
665
665
  }
666
- ]`})]})]})}function wys({errors:e,maxErrors:t=5}){if(e.length===0)return null;const n=e.slice(0,t),r=e.length-t;return o.jsxs("div",{className:"bg-accent2/10 border-accent2/30 rounded-md border p-3",children:[o.jsxs("div",{className:"text-accent2 mb-2 flex items-center gap-2",children:[o.jsx(Qe,{children:o.jsx(uc,{className:"h-4 w-4"})}),o.jsxs("span",{className:"text-sm font-medium",children:[e.length," validation error",e.length!==1?"s":""]})]}),o.jsx("ul",{className:"text-accent2/80 space-y-1 text-sm",children:n.map((s,a)=>o.jsxs("li",{className:"flex gap-2",children:[o.jsx("span",{className:"shrink-0",children:"•"}),o.jsx("span",{children:s.message})]},a))}),r>0&&o.jsxs("div",{className:"text-accent2/60 mt-2 text-xs",children:["+",r," more error",r!==1?"s":""]})]})}function Sys({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=g.useState("upload"),[i,l]=g.useState(null),[c,u]=g.useState({current:0,total:0}),[d,f]=g.useState(null),[h,p]=g.useState(!1),{parseFile:m,isParsing:v,error:y}=yvs(),{batchInsertItems:b}=wi(),x=g.useCallback(async I=>{try{const A=await m(I);l(A),a("preview")}catch{}},[m]),w=g.useCallback(async()=>{if(!i||i.items.length===0)return;a("importing"),p(!0);const{items:I}=i;u({current:0,total:I.length});try{await b.mutateAsync({datasetId:e,items:I.map(A=>({input:A.input,groundTruth:A.groundTruth,metadata:A.metadata}))}),f({success:I.length,errors:0})}catch{f({success:0,errors:I.length})}u({current:I.length,total:I.length}),p(!1),a("complete")},[i,b,e]),k=g.useCallback(()=>{n(!1),r?.(),d&&d.success>0&&Ve.success(`Imported ${d.success} item${d.success!==1?"s":""}`),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150)},[n,r,d]),C=g.useCallback(()=>{h||(n(!1),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150))},[h,n]),_=i&&i.items.length>0&&i.errors.length===0,T=()=>{switch(s){case"upload":return o.jsx(xys,{onFileSelect:x,isParsing:v,error:y?.message});case"preview":return i?o.jsx("div",{className:"flex flex-col gap-4",children:i.errors.length>0?o.jsxs(o.Fragment,{children:[o.jsx(wys,{errors:i.errors}),o.jsx("div",{className:"text-neutral4 text-sm",children:"Please fix the errors in your JSON file and try again."})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"text-neutral4 text-sm",children:["Found ",i.items.length," valid item",i.items.length!==1?"s":""," to import."]}),o.jsx(bys,{items:i.items,maxRows:5})]})}):null;case"importing":return o.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[o.jsx(Vt,{}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-neutral1 text-lg font-medium",children:"Importing items..."}),o.jsxs("div",{className:"text-neutral4 mt-1 text-sm",children:[c.current," of ",c.total]})]})]});case"complete":return o.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[o.jsx("div",{className:"text-4xl",children:d&&d.errors===0?"✓":"⚠"}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-neutral1 text-lg font-medium",children:"Import Complete"}),o.jsxs("div",{className:"text-neutral4 mt-1 text-sm",children:[d?.success??0," item",d?.success!==1?"s":""," imported",d&&d.errors>0&&o.jsxs("span",{className:"text-accent2",children:[" ","(",d.errors," error",d.errors!==1?"s":"",")"]})]})]})]})}},E=()=>{switch(s){case"upload":return o.jsx(ie,{onClick:C,children:"Cancel"});case"preview":return o.jsxs(o.Fragment,{children:[o.jsx(ie,{onClick:()=>a("upload"),children:"Back"}),o.jsxs(ie,{variant:"primary",onClick:w,disabled:!_,children:["Import ",i?.items.length??0," Item",i?.items.length!==1?"s":""]})]});case"importing":return null;case"complete":return o.jsx(ie,{variant:"primary",onClick:k,children:"Done"})}},N={upload:"Import JSON",preview:"Preview Data",importing:"Importing",complete:"Import Complete"};return o.jsx(pr,{open:t,onOpenChange:C,children:o.jsxs(mr,{className:"max-h-[90vh] max-w-2xl",children:[o.jsxs(gr,{children:[o.jsx(ur,{children:N[s]}),o.jsx(Cs,{children:"Import dataset items from a JSON file."})]}),o.jsx(jr,{className:"max-h-[50vh] min-h-[200px] overflow-y-auto",children:T()}),o.jsx(Bl,{className:"flex justify-end gap-2 px-6 pt-4",children:E()})]})})}function kys(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"?!0:!!e.closest('[role="dialog"]:not([data-item-panel])')}function wHt({active:e,onPrevious:t,onNext:n,onClose:r}){g.useEffect(()=>{if(!e)return;const s=a=>{a.defaultPrevented||kys(a.target)||(a.key==="PageUp"?(a.preventDefault(),t?.()):a.key==="PageDown"?(a.preventDefault(),n?.()):a.key==="Escape"&&(a.preventDefault(),r()))};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,t,n,r])}const SHt=g.createContext(null);function Oys({datasetId:e,items:t,isLoadingItems:n,children:r}){const s=qr(),i=fvt("/datasets/:datasetId/items/:itemId")?.params.itemId,l=g.useCallback(p=>{s(`/datasets/${e}/items/${encodeURIComponent(p)}`)},[s,e]),c=g.useCallback(()=>{s(`/datasets/${e}`)},[s,e]),u=g.useMemo(()=>i?t.findIndex(p=>p.id===i):-1,[t,i]),d=g.useMemo(()=>{if(u<=0)return;const p=t[u-1].id;return()=>l(p)},[u,t,l]),f=g.useMemo(()=>{if(u<0||u>=t.length-1)return;const p=t[u+1].id;return()=>l(p)},[u,t,l]);wHt({active:!!i,onPrevious:d,onNext:f,onClose:c});const h=g.useMemo(()=>({datasetId:e,items:t,isLoadingItems:n,currentItemId:i,openItem:l,close:c,goToPreviousItem:d,goToNextItem:f}),[e,t,n,i,l,c,d,f]);return o.jsx(SHt.Provider,{value:h,children:r})}function kHt(){const e=g.useContext(SHt);if(!e)throw new Error("useDatasetItemPanel must be used within a DatasetItemPanelProvider");return e}function Cys({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,leftSlot:r,rightSlot:s}){const[a,i]=za(),{activeVersion:l}=mRe(a,i),[c,u]=g.useState(!1),[d,f]=g.useState(!1),[h,p]=g.useState(!1),[m,v]=g.useState([]),[y,b]=g.useState(!1),[x,w]=g.useState([]),[k,C]=g.useState(!1),[_,T]=g.useState([]),[E,N]=g.useState(0),[I,A]=g.useState(""),[P]=YH(I,300),{data:L}=zy(e),{data:D=[],isLoading:B,setEndOfListElement:H,isFetchingNextPage:q,hasNextPage:z}=Qx(e,P||void 0,l),{deleteItems:V}=wi(),{currentItemId:M,openItem:G,close:F}=kHt(),R=ae=>{M===ae?F():G(ae)},U=ae=>{v(ae),p(!0)},Z=ae=>{w(ae),b(!0)},Y=ae=>{b(ae),ae||(w([]),N(X=>X+1))},te=ae=>{T(ae),C(!0)},J=async()=>{await V.mutateAsync({datasetId:e,itemIds:_}),Ve.success(`Deleted ${_.length} items`),C(!1),T([]),N(ae=>ae+1)},ee=ae=>{p(!1),v([]),N(X=>X+1),n?.(ae)},re=ae=>{p(ae),ae||(v([]),N(X=>X+1))};return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"grid h-full overflow-auto",children:o.jsx(yys,{items:D,leftSlot:r,rightSlot:s,isLoading:B,onItemClick:R,featuredItemId:M,onAddClick:t??(()=>{}),onImportClick:()=>u(!0),onImportJsonClick:()=>f(!0),onBulkDeleteClick:te,onCreateDatasetClick:U,onAddToDatasetClick:Z,datasetName:L?.name,clearSelectionTrigger:E,setEndOfListElement:H,isFetchingNextPage:q,hasNextPage:z,searchQuery:I,activeSearchQuery:P,onSearchChange:A,currentDatasetVersion:L?.version})}),o.jsx(hys,{datasetId:e,open:c,onOpenChange:u}),o.jsx(Sys,{datasetId:e,open:d,onOpenChange:f}),o.jsx(Zvs,{open:h,onOpenChange:re,items:m,onSuccess:ee}),o.jsx(Gvs,{open:y,onOpenChange:Y,items:x,currentDatasetId:e}),o.jsx($t,{open:k,onOpenChange:C,children:o.jsxs($t.Content,{children:[o.jsxs($t.Header,{children:[o.jsx($t.Title,{children:"Delete Items"}),o.jsxs($t.Description,{children:["Are you sure you want to delete ",_.length," item",_.length!==1?"s":"","? This action cannot be undone."]})]}),o.jsxs($t.Footer,{children:[o.jsx($t.Cancel,{children:"Cancel"}),o.jsx($t.Action,{onClick:J,children:V.isPending?"Deleting...":"Delete"})]})]})})]})}function OHt({selectedScorers:e,setSelectedScorers:t,disabled:n=!1,container:r,label:s="Scorers (Optional)",helperText:a}){const{data:i,isLoading:l}=up(),c=Object.entries(i??{}).filter(([,u])=>u.isRegistered).map(([u,d])=>({value:u,label:d.scorer?.config?.name||u,description:d.scorer?.config?.description||""}));return o.jsxs("div",{className:"grid gap-2",children:[s?o.jsx(Dt,{children:s}):null,a?o.jsx("p",{className:"text-muted-foreground text-xs",children:a}):null,o.jsx(vl,{multiple:!0,options:c,value:e,onValueChange:t,placeholder:"Select scorers...",searchPlaceholder:"Search scorers...",emptyText:"No scorers available",disabled:n||l,container:r})]})}function CHt({overrideEnabled:e,onOverrideEnabledChange:t,selectedScorerIds:n,onSelectedScorerIdsChange:r,disabled:s=!1}){return o.jsxs("div",{className:"grid gap-3",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(yl,{id:"override-dataset-scorers",checked:e,onCheckedChange:t,disabled:s}),o.jsx(Dt,{htmlFor:"override-dataset-scorers",children:"Override dataset scorers"})]}),o.jsx("p",{className:"text-muted-foreground text-xs",children:e?"Only selected scorers run for this item. Leave empty to run no scorers.":"Use scorers attached to the dataset."}),e?o.jsx(OHt,{selectedScorers:n,setSelectedScorers:r,disabled:s,label:"Item scorers",helperText:"Choose from scorers that can be resolved by this Mastra instance."}):null]})}function _ys(e){if(!(e instanceof Error))return null;const t=e.message.match(/- ({.*})$/);if(!t)return null;try{const n=JSON.parse(t[1]);if(n.field&&Array.isArray(n.errors))return{field:n.field,errors:n.errors}}catch{}return null}function Qie({field:e,errors:t}){return t.length?o.jsx("div",{className:"mt-2 space-y-1",children:t.map((n,r)=>o.jsxs("p",{className:"text-destructive text-xs",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function Eys({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=g.useState("{}"),[i,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState(""),[h,p]=g.useState(!1),[m,v]=g.useState([]),[y,b]=g.useState(""),[x,w]=g.useState(null),{addItem:k}=wi(),C=()=>{a("{}"),l(""),u(""),f(""),p(!1),v([]),b(""),w(null)},_=P=>{C(),n(P)},T=async P=>{P.preventDefault();let L;try{L=JSON.parse(s)}catch{Ve.error("Input must be valid JSON");return}let D;if(i.trim())try{D=JSON.parse(i)}catch{Ve.error("Ground Truth must be valid JSON");return}let B;if(c.trim())try{B=JSON.parse(c)}catch{Ve.error("Expected Trajectory must be valid JSON");return}let H;if(d.trim())try{const z=JSON.parse(d);if(!Array.isArray(z)){Ve.error("Tool Mocks must be a JSON array");return}H=z}catch{Ve.error("Tool Mocks must be valid JSON");return}let q;if(y.trim())try{q=JSON.parse(y)}catch{Ve.error("Request Context must be valid JSON");return}try{await k.mutateAsync({datasetId:e,input:L,groundTruth:D,expectedTrajectory:B,toolMocks:H,scorerIds:h?m:void 0,requestContext:q}),Ve.success("Item added successfully"),_(!1),r?.()}catch(z){const V=_ys(z);V?w(V):Ve.error(`Failed to add item: ${z instanceof Error?z.message:"Unknown error"}`)}},E=P=>{a(P),x?.field==="input"&&w(null)},N=P=>{l(P),x?.field==="groundTruth"&&w(null)},I=P=>{f(P),x?.field==="toolMocks"&&w(null)},A=()=>{_(!1)};return o.jsxs(Ca,{dialogTitle:"Add Item",dialogDescription:"Create a new dataset item",isOpen:t,onClose:A,level:1,children:[o.jsx(Ca.Top,{children:"Add Item"}),o.jsxs(Ca.Content,{children:[o.jsx(Ca.Header,{children:o.jsx(Ca.Heading,{children:"Add Item"})}),o.jsxs("form",{onSubmit:T,className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Gr,{value:s,onChange:E,showCopyButton:!1,className:"min-h-[240px]"}),x?.field==="input"&&o.jsx(Qie,{field:"input",errors:x.errors})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),o.jsx(Gr,{value:i,onChange:N,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="groundTruth"&&o.jsx(Qie,{field:"groundTruth",errors:x.errors})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),o.jsx(Gr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[200px]"})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-tool-mocks",children:"Tool Mocks (JSON array, optional)"}),o.jsx(Gr,{value:d,onChange:I,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="toolMocks"&&o.jsx(Qie,{field:"toolMocks",errors:x.errors})]}),o.jsx(CHt,{overrideEnabled:h,onOverrideEnabledChange:p,selectedScorerIds:m,onSelectedScorerIdsChange:v,disabled:k.isPending}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-request-context",children:"Request Context (JSON, optional)"}),o.jsx(Gr,{value:y,onChange:b,showCopyButton:!1,className:"min-h-[200px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ie,{type:"button",onClick:A,children:"Cancel"}),o.jsx(ie,{type:"submit",variant:"primary",disabled:k.isPending,children:k.isPending?"Adding...":"Add Item"})]})]})]})]})}function Tys({item:e}){return o.jsx(Pa,{withMargins:!1,children:o.jsxs(Pa.Column,{children:[o.jsxs(Pa.Title,{size:"smaller",children:[o.jsx(NV,{}),o.jsx("span",{className:"truncate",children:e.id}),o.jsx(_a,{content:e.id,tooltip:`Copy item ID: ${e.id}`})]}),o.jsxs(Pa.Description,{children:[o.jsxs(Pl,{children:[o.jsx(yYt,{})," Created ",dr(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")]}),e.datasetVersion!=null&&o.jsxs(Pl,{children:[o.jsx(uI,{})," Version v",e.datasetVersion]})]})]})})}function gRe({item:e}){const t=e?.input?JSON.stringify(e.input,null,2):"null",n=e?.groundTruth?JSON.stringify(e.groundTruth,null,2):"null",r=e?.metadata?JSON.stringify(e.metadata,null,2):"null",s=e?.expectedTrajectory?JSON.stringify(e.expectedTrajectory,null,2):null;return o.jsxs(Fqr,{children:[o.jsx(Ca.CodeSection,{title:"Input",icon:o.jsx(Ox,{}),codeStr:t}),o.jsx(Ca.CodeSection,{title:"Ground Truth",icon:o.jsx(nm,{}),codeStr:n}),s&&o.jsx(Ca.CodeSection,{title:"Expected Trajectory",icon:o.jsx(P0e,{}),codeStr:s}),o.jsx(Ca.CodeSection,{title:"Scorers",icon:o.jsx(PV,{}),codeStr:e.scorerIds===void 0?"Inherited from dataset":JSON.stringify(e.scorerIds,null,2)}),o.jsx(Ca.CodeSection,{title:"Metadata",icon:o.jsx(dI,{}),codeStr:r})]})}function Yie({field:e,errors:t}){return t.length?o.jsx("div",{className:"mt-2 space-y-1",children:t.map((n,r)=>o.jsxs("p",{className:"text-destructive text-xs",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function jys({inputValue:e,setInputValue:t,groundTruthValue:n,setGroundTruthValue:r,metadataValue:s,setMetadataValue:a,trajectoryValue:i,setTrajectoryValue:l,toolMocksValue:c,setToolMocksValue:u,scorerOverrideEnabled:d,setScorerOverrideEnabled:f,selectedScorerIds:h,setSelectedScorerIds:p,requestContextValue:m,setRequestContextValue:v,validationErrors:y,onSave:b,onCancel:x,isSaving:w}){return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"mb-4",children:o.jsxs("h3",{className:"flex items-center gap-2 text-lg font-medium",children:[o.jsx(Yh,{className:"h-5 w-5"})," Edit Item"]})}),o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Input (JSON) *"}),o.jsx(Gr,{value:e,onChange:t,showCopyButton:!1,className:"min-h-[120px]"}),y?.field==="input"&&o.jsx(Yie,{field:"input",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Ground Truth (JSON, optional)"}),o.jsx(Gr,{value:n,onChange:r,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="groundTruth"&&o.jsx(Yie,{field:"groundTruth",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Expected Trajectory (JSON, optional)"}),o.jsx(Gr,{value:i,onChange:l,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Tool Mocks (JSON array, optional)"}),o.jsxs("p",{className:"text-muted-foreground text-xs",children:["Ordered static mocks served in place of executing the tool. Each entry is"," ",o.jsx("code",{children:'{ "toolName", "args", "output" }'}),". Calling a mocked tool with non-matching args fails the item; unmocked tools run live."]}),o.jsx(Gr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="toolMocks"&&o.jsx(Yie,{field:"toolMocks",errors:y.errors})]}),o.jsx(CHt,{overrideEnabled:d,onOverrideEnabledChange:f,selectedScorerIds:h,onSelectedScorerIdsChange:p,disabled:w}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Request Context (JSON, optional)"}),o.jsx(Gr,{value:m,onChange:v,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Metadata (JSON, optional)"}),o.jsx(Gr,{value:s,onChange:a,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex gap-2 pt-4",children:[o.jsx(ie,{variant:"primary",onClick:b,disabled:w,children:w?"Saving...":"Save Changes"}),o.jsx(ie,{onClick:x,disabled:w,children:"Cancel"})]})]})]})}const Nys={light:"bg-gray-100 border-gray-300 text-gray-700 shadow-[0_1px_0_rgba(0,0,0,0.1)]",dark:"bg-surface4 border-border1 text-neutral5 shadow-[0_1px_0_rgba(0,0,0,0.3)]"},Iys={default:"h-6 min-w-6 rounded-md px-1.5 text-ui-sm",sm:"h-5 min-w-5 rounded-md px-1 text-ui-xs",xs:"h-4 min-w-4 rounded px-1 text-ui-xs leading-none"},FT=({children:e,theme:t="dark",size:n="default",className:r})=>o.jsx("kbd",{className:K("inline-flex items-center justify-center border font-mono",Iys[n],Yr.transform,"active:scale-95 active:shadow-none",Nys[t],r),children:e}),Ays=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function Rys({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:a,isLoading:i}=Bm(),{data:l,isLoading:c}=Xy(),{data:u,isLoading:d}=up(),f=e==="agent"?Object.entries(a??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="workflow"?Object.entries(l??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="scorer"?Object.entries(u??{}).map(([v,y])=>({value:v,label:y.scorer?.config?.name??v})):[],h=e==="agent"&&i||e==="workflow"&&c||e==="scorer"&&d,p=v=>{t(v),r("")},m=e==="agent"?"Agent":e==="workflow"?"Workflow":"Scorer";return o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{children:"Target Type"}),o.jsx(vl,{options:Ays,value:e,onValueChange:p,placeholder:"Select target type",searchPlaceholder:"Search types...",emptyText:"No types available",container:s})]}),e&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{children:m}),o.jsx(vl,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:h,container:s})]})]})}const Pys=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform);function $ys({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return xm(e)}catch(r){return console.error("Failed to parse requestContextSchema:",r),null}},[e]);return n?o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Request Context"}),o.jsx(Q3,{schema:n,onValuesChange:t,className:"[&_button[type=submit]]:hidden"})]}):o.jsx("p",{className:"text-destructive text-sm",children:"Failed to parse request context schema"})}function Kie({index:e,title:t,done:n,isLast:r,children:s}){return o.jsxs("li",{className:"flex gap-4",children:[o.jsxs("div",{className:"flex flex-col items-center",children:[o.jsx("span",{"aria-hidden":"true",className:K("flex size-6 shrink-0 items-center justify-center rounded-full border text-ui-xs font-medium",n?"border-accent1 bg-accent1 text-white":"border-border1 text-neutral3"),children:e}),!r&&o.jsx("span",{"aria-hidden":"true",className:"bg-border1 mt-2 w-px flex-1"})]}),o.jsxs("div",{className:K("min-w-0 flex-1 space-y-3",!r&&"pb-6"),children:[o.jsx("p",{className:"text-ui-sm font-medium",children:t}),s]})]})}function cY({initialDatasetId:e,initialDatasetVersion:t,initialScorerIds:n,initialTargetType:r,initialTargetId:s,initialName:a,initialDescription:i,open:l,onOpenChange:c,onSuccess:u}){const d=g.useRef(null),[f,h]=g.useState(a??""),[p,m]=g.useState(i??""),[v,y]=g.useState(e??""),[b,x]=g.useState(t??null),[w,k]=g.useState(r??""),[C,_]=g.useState(s??""),[T,E]=g.useState(n??[]),[N,I]=g.useState({}),[A,P]=g.useState(""),{triggerExperiment:L}=wi(),{data:D}=zy(v),{total:B}=Qx(v,void 0,b),H=D?.requestContextSchema,q=!!(H&&Object.keys(H).length>0),z=!!(v&&w&&C&&f.trim()),V=L.isPending,M=[!f.trim()&&"name",!v&&"dataset",!C&&"target"].filter(Boolean),G=q?Object.values(N).some(J=>J!==void 0&&J!==""):A.trim().length>0,F=J=>{y(J),x(null),I({})},R=()=>{h(a??""),m(i??""),y(e??""),x(t??null),k(r??""),_(s??""),E(n??[]),I({}),P("")},U=()=>{if(q){const J=Object.entries(N).filter(([,ee])=>ee!==void 0&&ee!=="");return J.length>0?Object.fromEntries(J):void 0}if(A.trim()){let J;try{J=JSON.parse(A)}catch{throw new Error("Request Context must be valid JSON")}if(!J||typeof J!="object"||Array.isArray(J))throw new Error("Request Context must be a JSON object");return J}},Z=async()=>{if(!v||!w||!C||!f.trim())return;let J;try{J=U()}catch(ee){const re=ee instanceof Error?ee.message:"Request Context must be valid JSON";yu.error(re);return}try{const ee=await L.mutateAsync({datasetId:v,name:f.trim(),description:p.trim()||void 0,targetType:w,targetId:C,scorerIds:T.length>0?T:void 0,version:b??void 0,requestContext:J});yu.success("Experiment triggered successfully"),c(!1),u?.(ee.experimentId),R()}catch(ee){const re=ee instanceof Error?ee.message:"Failed to trigger experiment";yu.error(re)}},Y=()=>{V||(c(!1),R())},te=J=>{(J.metaKey||J.ctrlKey)&&J.key==="Enter"&&z&&!V&&(J.preventDefault(),Z())};return o.jsx(pr,{open:l,onOpenChange:Y,children:o.jsxs(mr,{ref:d,className:"w-[640px] max-w-[calc(100vw-2rem)] gap-0 p-0",onKeyDown:te,children:[o.jsxs(gr,{className:"border-border1 border-b px-6 py-4",children:[o.jsx(ur,{children:"Run experiment"}),o.jsx(Cs,{className:"text-ui-sm text-neutral3 not-sr-only",children:"Pick a dataset, choose what to run it against, and optionally score the results."})]}),o.jsxs(jr,{className:"max-h-[70vh] space-y-6 overflow-y-auto px-6 py-5",children:[o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"experiment-name",children:"Name *"}),o.jsx(jn,{id:"experiment-name",value:f,onChange:J=>h(J.target.value),placeholder:"Enter experiment name",autoFocus:!0,disabled:V})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"experiment-description",children:"Description"}),o.jsx(zo,{id:"experiment-description",value:p,onChange:J=>m(J.target.value),placeholder:"Enter experiment description (optional)",disabled:V,rows:2})]})]}),o.jsxs("ol",{className:"list-none",children:[o.jsxs(Kie,{index:1,title:"Dataset",done:!!v,children:[o.jsxs("div",{className:"grid grid-cols-[1fr_140px] gap-3",children:[o.jsx(eys,{value:v,onValueChange:F,container:d}),v&&o.jsx(bHt,{datasetId:v,value:b,onValueChange:x,container:d})]}),v&&B!==void 0&&o.jsxs("p",{className:"text-ui-xs text-neutral3",children:[B," ",B===1?"item":"items"]})]}),o.jsxs(Kie,{index:2,title:"Target",done:!!C,children:[o.jsx(Rys,{targetType:w,setTargetType:k,targetId:C,setTargetId:_,container:d}),w&&!C&&o.jsxs("p",{className:"text-ui-xs text-neutral3",children:["Choose ",w==="agent"?"an":"a"," ",w," to run"]})]}),o.jsx(Kie,{index:3,title:"Scorers (Optional)",done:T.length>0,isLast:!0,children:o.jsx(OHt,{label:"",selectedScorers:T,setSelectedScorers:E,disabled:V,container:d,helperText:"Scores are computed after each item runs."})})]}),o.jsxs(fc,{children:[o.jsxs(ql,{className:"text-ui-sm flex items-center gap-2",children:[o.jsx(Lr,{className:"size-4"}),"Request Context (JSON, optional)",G&&o.jsx(bt,{size:"xs",variant:"blue",children:"set"})]}),o.jsx(Vl,{className:"pt-3",children:q?o.jsx($ys,{requestContextSchema:H,onChange:I}):o.jsx(Gr,{value:A,onChange:P,showCopyButton:!1,"aria-label":"Request context JSON",className:"min-h-[160px]"})})]})]}),o.jsxs(Bl,{className:"border-border1 items-center border-t px-6 py-4 sm:justify-between",children:[o.jsx("p",{"data-testid":"experiment-run-status","aria-live":"polite",className:"flex items-center gap-2",children:M.length===0?o.jsxs(o.Fragment,{children:[o.jsx(bt,{variant:"green",indicator:"dot",children:"Ready"}),o.jsxs("span",{className:"text-ui-xs text-neutral3",children:[B??0," items · ",w," · ",T.length," scorers"]})]}):o.jsxs(bt,{variant:"neutral",indicator:"dot",children:["Missing ",M.join(", ")]})}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ie,{onClick:Y,disabled:V,children:"Cancel"}),o.jsx(ie,{variant:"primary",onClick:Z,disabled:!z||V,children:V?o.jsxs(o.Fragment,{children:[o.jsx(Vt,{className:"h-4 w-4"}),"Running..."]}):o.jsxs(o.Fragment,{children:["Run",o.jsxs("span",{className:"ml-1 inline-flex gap-0.5","aria-hidden":"true",children:[o.jsx(FT,{size:"xs",children:Pys?"⌘":"Ctrl"}),o.jsx(FT,{size:"xs",children:"↵"})]})]})})]})]})]})})}const _Ht=g.createContext(null);function Mys({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:a,children:i}){const l=qr(),u=fvt("/experiments/:experimentId/items/:itemId")?.params.itemId,d=g.useCallback(b=>{l(`/experiments/${e}/items/${encodeURIComponent(b)}`)},[l,e]),f=g.useCallback(()=>{l(`/experiments/${e}`)},[l,e]),h=g.useCallback(b=>{l(STe(e,b))},[l,e]),p=g.useMemo(()=>u?r.findIndex(b=>b.itemId===u):-1,[r,u]),m=g.useMemo(()=>{if(p<=0)return;const b=r[p-1].itemId;return()=>d(b)},[p,r,d]),v=g.useMemo(()=>{if(p<0||p>=r.length-1)return;const b=r[p+1].itemId;return()=>d(b)},[p,r,d]);wHt({active:!!u,onPrevious:m,onNext:v,onClose:f});const y=g.useMemo(()=>({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:a,currentItemId:u,openItem:d,close:f,openInReview:h,goToPreviousItem:m,goToNextItem:v}),[e,t,n,r,s,a,u,d,f,h,m,v]);return o.jsx(_Ht.Provider,{value:y,children:i})}function EHt(){const e=g.useContext(_Ht);if(!e)throw new Error("useExperimentItemPanel must be used within an ExperimentItemPanelProvider");return e}function Dys({results:e,isLoading:t,featuredResultId:n,onResultClick:r,columns:s,scoresByItemId:a,scorerIds:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u,selectedIds:d,onToggleSelect:f}){const{Link:h,paths:p}=dn(),m=!!(d&&f),v=[m?"2rem":"",...s.map(k=>k.size)].filter(Boolean).join(" "),y=s.some(k=>k.name==="input"),{containerRef:b,getRowProps:x}=ao({count:e.length}),w=k=>i?.includes(k.name)?o.jsx(pe.TopCell,{children:o.jsxs(h,{href:p.scorerLink(k.name),className:"flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[o.jsx(P_,{}),o.jsx("span",{className:"min-w-0 truncate",children:k.label})]})},k.name):o.jsx(pe.TopCell,{children:k.label},k.name);return t?o.jsx(Bo,{columns:v}):o.jsxs(pe,{columns:v,className:"min-w-0",scrollRef:b,children:[o.jsxs(pe.Top,{hasLeadingCell:m,children:[m&&o.jsx(pe.TopCell,{children:" "}),m?o.jsx(pe.TopCells,{colStart:2,children:s.map(w)}):s.map(w)]}),e.length===0?o.jsx(pe.NoMatch,{message:"No results yet"}):o.jsxs(o.Fragment,{children:[e.map((k,C)=>{const _=!!k.error,T=k.id===n,E=o.jsxs(o.Fragment,{children:[o.jsxs(pe.Cell,{className:"text-ui-smd text-neutral3 flex items-center gap-1.5 tracking-wide",children:[o.jsx("span",{children:k.itemId?.slice(0,8)??""}),_&&o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx(SO,{role:"img","aria-label":"Error",className:"text-error size-3.5"})}),o.jsx(yn,{children:k.error?.message||"Error"})]})]}),y&&o.jsx(pe.TextCell,{font:"mono",children:Fys(Lys(k.input),200)}),i?.map(N=>{const A=a?.[k.itemId]?.find(P=>P.scorerId===N);return o.jsx(pe.Cell,{className:"text-neutral3 text-ui-smd font-mono",children:A!=null?A.score.toFixed(3):"-"},N)})]});return m?o.jsxs(pe.RowWrapper,{children:[o.jsx(pe.SelectCell,{checked:d.has(k.id),onToggle:()=>f(k.id),"aria-label":`Select result ${k.itemId}`}),o.jsx(pe.RowButton,{colStart:2,featured:T,"data-selected":T||void 0,onClick:()=>r(k.id),...x(C),children:E})]},k.id):o.jsx(pe.RowButton,{featured:T,"data-selected":T||void 0,onClick:()=>r(k.id),...x(C),children:E},k.id)}),o.jsx(pe.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function Lys(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Fys(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}function zys({scoresByItemId:e,experimentStatus:t}){const{Link:n,paths:r}=dn(),{data:s}=up(),a=g.useMemo(()=>{if(!e)return[];const i={};for(const l of Object.values(e))for(const c of l)i[c.scorerId]||(i[c.scorerId]={sum:0,count:0}),i[c.scorerId].sum+=c.score,i[c.scorerId].count++;return Object.entries(i).map(([l,{sum:c,count:u}])=>({scorerId:l,avg:c/u})).sort((l,c)=>l.scorerId.localeCompare(c.scorerId))},[e]);if(a.length===0){const i=t==="running"||t==="pending",l=e!==void 0;let c,u;return i?(c="Experiment in progress",u="Summary metrics will appear here once the experiment completes."):l?(c="No scorers configured",u="Add scorers when triggering an experiment to evaluate results and see summary metrics here."):(c="Loading scores",u="Fetching scorer results…"),o.jsxs("div",{className:"text-ui-sm text-neutral3 flex items-center gap-2",children:[o.jsx(Qh,{className:"text-neutral3 size-4 shrink-0"}),o.jsx("span",{className:"text-neutral4",children:c}),o.jsx("span",{className:"truncate",children:u})]})}return o.jsx("div",{className:"flex items-stretch gap-2 overflow-x-auto pb-1",children:a.map(({scorerId:i,avg:l})=>{const c=s?.[i]?.scorer?.config?.name??i;return o.jsxs(Xr,{className:"w-52 min-w-0 flex-none p-3",children:[o.jsxs(n,{href:r.scorerLink(i),className:"text-ui-sm text-neutral3 [&>svg]:text-neutral3 flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3 [&>svg]:shrink-0",children:[o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx(P_,{role:"img","aria-label":"Scorer"})}),o.jsx(yn,{children:"Scorer"})]}),o.jsx("span",{className:"truncate",children:c})]}),o.jsxs("strong",{className:"text-ui-lg text-neutral4 font-semibold",children:[l.toFixed(3),o.jsx("span",{className:"text-ui-sm text-neutral3 ml-1.5 font-normal",children:"avg score"})]})]},i)})})}function Bys({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoading:s,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l}){const{currentItemId:c,openItem:u,close:d}=EHt(),[f,h]=g.useState(new Set),[p,m]=g.useState(!1),{updateExperimentResult:v}=wi(),y=g.useCallback(E=>{h(N=>{const I=new Set(N);return I.has(E)?I.delete(E):I.add(E),I})},[]),b=g.useCallback(()=>h(new Set),[]),x=g.useCallback(async E=>{if(p||E.length===0)return;m(!0);let N=0;const I=new Set;try{for(const A of E)try{await v.mutateAsync({datasetId:t,experimentId:e,resultId:A,status:"needs-review"}),N++,I.add(A)}catch{}}finally{m(!1)}I.size>0&&h(A=>{const P=new Set(A);for(const L of I)P.delete(L);return P}),N>0&&Ve(`${N} result${N>1?"s":""} flagged for review`)},[t,e,p,v]),w=g.useMemo(()=>c?r.find(E=>E.itemId===c)?.id??null:null,[r,c]),{data:k}=jC(e,n),C=g.useMemo(()=>{if(!k)return[];const E=new Set;for(const N of Object.values(k))for(const I of N)E.add(I.scorerId);return[...E].sort()},[k]),_=g.useCallback(E=>{const N=r.find(I=>I.id===E);N&&(N.itemId===c?d():u(N.itemId))},[r,c,d,u]),T=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"7rem"},{name:"input",label:"Input",size:"minmax(10rem,1fr)"},...C.map(E=>({name:E,label:E,size:"12rem"}))],[C]);return o.jsxs("div",{className:K("grid h-full gap-3 overflow-hidden",f.size>0?"grid-rows-[auto_auto_1fr]":"grid-rows-[auto_1fr]"),children:[o.jsx(zys,{scoresByItemId:k,experimentStatus:n}),f.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(ie,{variant:"outline",size:"sm",disabled:p,onClick:()=>x([...f]),children:[o.jsx(Qe,{size:"sm",children:o.jsx(X1,{})}),"Flag ",f.size," to review"]}),o.jsx(ie,{variant:"ghost",size:"sm",onClick:b,children:"Clear"})]}),o.jsx("div",{className:"min-h-0 overflow-y-auto",children:o.jsx(Dys,{results:r,isLoading:s,featuredResultId:w,onResultClick:_,columns:T,scoresByItemId:k,scorerIds:C,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l,selectedIds:f,onToggleSelect:y})})]})}const Ttt={pending:{icon:o.jsx(c1,{className:"text-warning1 size-4"}),label:"Pending"},running:{icon:o.jsx(Vt,{size:"sm"}),label:"Running"},completed:{icon:o.jsx(XD,{className:"text-neutral3 size-4"}),label:"Completed"},failed:{icon:o.jsx(OO,{className:"text-error size-4"}),label:"Failed"}};function Uys({status:e,className:t}){const n=Ttt[e]??Ttt.pending;return o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx("span",{tabIndex:0,className:K("flex shrink-0 items-center",t),children:n.icon})}),o.jsx(yn,{children:n.label})]})}const qys=e=>{const t=Ye();return mt({queryKey:["experiment-trace-light",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return t.getTraceLight(e)},select:zAe,enabled:!!e})};function THt({children:e,className:t}){return o.jsx("div",{className:K("",t),children:e})}function Vys({date:e,className:t,withTime:n=!1}){const r=e?e0t(new Date(e)):!1,s=e?U3(new Date(e))?"Today":dr(new Date(e),"MMM dd"):"",a=e&&!r?dr(new Date(e),"yyyy"):"",i=e&&n?`${dr(new Date(e),"'at' h:mm aaa")}`:"";return o.jsxs("div",{className:K("truncate text-ui-md text-neutral2",t),children:[s," ",a," ",i]})}function vRe(e){return!e||e.length===0?"":e?.map(t=>t.size).join(" ")}function Hys({columns:e,isSelectionActive:t,children:n}){return o.jsx("div",{className:K("sticky top-0 z-10 mb-4 rounded-lg bg-surface3 px-4"),children:o.jsx("div",{className:K("grid items-center gap-4 text-left text-ui-xs tracking-widest text-neutral3 uppercase",{"pl-12 [&>label]:absolute [&>label]:left-0":t}),style:{gridTemplateColumns:vRe(e)},children:n})})}function Wys({children:e,className:t}){return o.jsx("span",{className:K("py-3",t),children:e})}function Zys({id:e,className:t,isShortened:n=!0}){const r=n?e.slice(0,8):e;return o.jsx("div",{className:K("truncate py-[0.6rem] text-ui-md text-neutral2",t),children:r})}function Gys({children:e}){return o.jsx("ul",{className:"grid content-start",children:e})}function Qys({children:e}){const t=g.useRef(null);return o.jsx("div",{ref:t,className:K("overflow-y-auto"),children:e})}function Yys({children:e,className:t}){return o.jsx("label",{className:K("flex h-full w-14 items-center justify-center rounded-lg hover:bg-surface5",t),children:e})}function Kys({children:e,href:t,className:n,LinkComponent:r,tooltip:s}){const a=o.jsx(r,{href:t,className:K("flex w-full items-center justify-center gap-6 rounded-lg px-3 py-[0.6rem] text-left","hover:bg-surface4",Yr.colors,M3.visible,n),children:e});return s==null?a:o.jsxs(xn,{children:[o.jsx(vn,{render:a}),o.jsx(yn,{children:s})]})}function Xys({children:e,message:t,className:n,type:r}){return!e&&!t?null:o.jsx("div",{className:K("grid border-t border-border1",n),children:t?o.jsxs("p",{className:K("grid justify-center justify-items-center gap-2 p-8 text-center text-ui-md text-neutral3","[&>svg]:size-[1.5em] [&>svg]:opacity-75",{"[&>svg]:text-red-500":r==="error"}),children:[r==="error"?o.jsx(uc,{}):o.jsx(Em,{})," ",t]}):e})}function Jys({isLoading:e,hasMore:t,setEndOfListElement:n,loadingText:r="Loading more data...",noMoreDataText:s="No more data to load"}){return n?o.jsxs("div",{ref:n,className:"text-ui-md text-neutral3 mt-8 flex justify-center opacity-50",children:[e&&r,!t&&!e&&s]}):null}function ebs({currentPage:e,hasMore:t,onNextPage:n,onPrevPage:r}){const s=typeof e=="number"&&e>0||t;return o.jsxs("div",{className:K("flex items-center justify-center gap-8 pt-6 text-ui-md text-neutral3"),children:[o.jsxs("span",{children:["Page ",o.jsx("b",{children:e?e+1:"1"})]}),s&&o.jsxs("div",{className:K("flex gap-4","[&>button]:flex [&>button]:items-center [&>button]:gap-2 [&>button]:rounded-md [&>button]:border [&>button]:border-border1 [&>button]:p-1 [&>button]:px-2 [&>button]:text-neutral4 [&>button]:transition-colors [&>button:hover]:text-neutral5","[&_svg]:size-[1em] [&_svg]:text-neutral3"),children:[typeof e=="number"&&e>0&&o.jsxs("button",{onClick:r,children:[o.jsx(bl,{}),"Previous"]}),t&&o.jsxs("button",{onClick:n,children:["Next",o.jsx(Fd,{})]})]})]})}function tbs({children:e,className:t}){return o.jsx("div",{className:K("grid grid-rows-[auto_1fr] overflow-y-auto",t),children:e})}function nbs({isSelected:e,children:t,columns:n}){return o.jsx("li",{className:K("flex overflow-hidden rounded-lg border border-transparent border-t-border1 py-[3px] pb-[2px] text-ui-md text-neutral5 first:border-t-transparent","[&:last-child>button]:rounded-b-lg","[&.selected-row]:border [&.selected-row]:border-dashed [&.selected-row]:border-white/50 [&.selected-row]:pr-[3px] [&.selected-row]:first:border-t","[&:has(+.selected-row)]:rounded-b-none [&:has(+.selected-row)]:border-b-transparent","[.selected-row+&]:rounded-t-none",Yr.colors,{"selected-row":e,"grid px-4 gap-4 ":n}),style:{gridTemplateColumns:vRe(n)},children:t})}function rbs({item:e,isFeatured:t,onClick:n,children:r,columns:s,className:a,disabled:i,tooltip:l,...c}){const u=()=>{n?.(e?.id)},d=o.jsx("button",{...c,onClick:u,className:K("grid w-full items-center gap-4 rounded-lg px-4 text-left",Yr.colors,M3.visible,{"bg-surface4":t,"hover:bg-surface4":e&&!t&&!i},a),style:{gridTemplateColumns:vRe(s)},disabled:i,children:r});return l==null?d:o.jsxs(xn,{children:[o.jsx(vn,{render:d}),o.jsx(yn,{children:l})]})}function sbs(e){return e.charAt(0).toUpperCase()+e.slice(1)}function abs({status:e}){return e?o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx("div",{className:K("relative flex h-full w-10 items-center justify-center bg-transparent"),children:o.jsx("div",{className:K("size-2 rounded-full",{"bg-green-600":["success","completed"].includes(e),"bg-red-700":["error","failed"].includes(e),"bg-yellow-500":["pending","running"].includes(e)})})})}),o.jsx(yn,{children:sbs(e)})]}):null}function ibs({children:e,isLoading:t,className:n}){return o.jsx("div",{className:K("truncate py-[0.6rem] text-ui-md text-neutral4",n),children:t?o.jsx("div",{className:"bg-surface4 h-4 animate-pulse rounded-md text-transparent select-none"}):e})}const SV={latest:"Latest version",deleted:"Deleted in this version"};function obs({isLatest:e,isDeleted:t}){const n=[];return e&&n.push(SV.latest),t&&n.push(SV.deleted),n.length>0?n.join(" · "):void 0}function lbs({version:e,date:t,isLatest:n,isDeleted:r}){return o.jsxs(THt,{className:K("grid grid-cols-[1fr_auto] pl-1"),children:[o.jsxs("div",{className:K("grid gap-1 leading-none text-neutral3",{"text-neutral4":n}),children:[o.jsxs("strong",{className:"font-normal",children:["v. ",e]}),o.jsx("em",{className:K("text-ui-sm","font-normal","text-neutral2"),children:t?dr(new Date(t),"MMM d, yyyy HH:mm"):null})]}),(n||r)&&o.jsxs("div",{className:"flex items-center gap-1",children:[n&&o.jsx("span",{className:"inline-flex",role:"img","aria-label":SV.latest,children:o.jsx(bt,{variant:"blue",size:"sm",icon:o.jsx(c1,{})})}),r&&o.jsx("span",{className:"inline-flex",role:"img","aria-label":SV.deleted,children:o.jsx(bt,{variant:"red",size:"sm",icon:o.jsx(k0e,{})})})]})]})}const gi=Object.assign(tbs,{Header:Hys,HeaderCol:Wys,Items:Gys,Scroller:Qys,Row:nbs,RowButton:rbs,Message:Xys,NextPageLoading:Jys,Pagination:ebs,Cell:THt,TextCell:ibs,StatusCell:abs,VersionCell:lbs,IdCell:Zys,DateCell:Vys,LinkCell:Kys,LabelCell:Yys});function cbs({datasetId:e,itemId:t,onVersionSelect:n,onCompareVersionsClick:r,activeVersion:s}){const{data:a,isLoading:i}=pRe(e,t),[l,c]=g.useState(!1),[u,d]=g.useState(new Set),f=b=>{n?.(b)},h=b=>s==null?b.isLatest:b.datasetVersion===s,p=b=>{d(x=>{const w=new Set(x);if(w.has(b))w.delete(b);else if(w.size>=2){const[k]=Array.from(w);return new Set([k,b])}else w.add(b);return w})},m=()=>{c(!1),d(new Set)},v=()=>{c(!0)},y=()=>{u.size===2&&r?.([...u])};return o.jsxs(ma,{className:"min-w-56",children:[l?o.jsx(ma.Toolbar,{className:"grid w-full justify-stretch gap-3",children:o.jsxs(es,{children:[o.jsx(ie,{onClick:m,children:"Cancel"}),o.jsx(ie,{variant:"primary",disabled:u.size!==2,onClick:y,tooltip:u.size!==2?"Check 2 versions to compare":void 0,className:"grow",children:"Compare"})]})}):o.jsx(o.Fragment,{children:(a||[]).length>1&&o.jsx(ma.Toolbar,{children:o.jsxs(ie,{onClick:v,className:"w-full",children:[o.jsx(Nj,{})," Compare Ver."]})})}),i?o.jsx(ubs,{}):o.jsxs(gi,{children:[o.jsx(gi.Header,{children:o.jsx(gi.HeaderCol,{children:"Item Version History"})}),o.jsx(gi.Scroller,{children:o.jsx(gi.Items,{children:a?.map(b=>{const x=String(b.datasetVersion),w=typeof b.updatedAt=="string"?new Date(b.updatedAt):b.updatedAt;return o.jsxs(gi.Row,{isSelected:l&&u.has(x),children:[l&&o.jsx(gi.LabelCell,{children:o.jsx(Oo,{checked:u.has(x),disabled:b.isDeleted,onCheckedChange:()=>{},onClick:k=>{k.stopPropagation(),b.isDeleted||p(x)},"aria-label":`Select version ${b.datasetVersion}`})}),o.jsx(gi.RowButton,{item:b,columns:[{name:"version",label:"Item Version History",size:"1fr"}],isFeatured:h(b),onClick:()=>f(b),className:"py-2",tooltip:obs({isLatest:b.isLatest,isDeleted:b.isDeleted}),children:o.jsx(gi.VersionCell,{version:b.datasetVersion,date:w,isLatest:b.isLatest,isDeleted:b.isDeleted})})]},String(b.datasetVersion))})})})]})]})}function ubs(){return o.jsxs(gi,{children:[o.jsx(gi.Header,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(gi.HeaderCol,{children:"Item Version History"})}),o.jsx(gi.Items,{children:Array.from({length:3}).map((e,t)=>o.jsx(gi.Row,{children:o.jsx(gi.RowButton,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(gi.TextCell,{isLoading:!0,children:"Loading..."})})},t))})]})}function dbs(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${dr(n,"MMM dd 'at' H:mm:ss a")}`}return`v${e}`}function fbs({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=jAe(e),a=(s??[]).map(i=>({value:String(i.version),label:`${dbs(i.version,i.createdAt)}${i.isCurrent?" (current)":""}`}));return o.jsxs(ma.Toolbar,{className:"grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4",children:[o.jsx("div",{}),o.jsx(Cm,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:a,value:t??"",onValueChange:i=>r?.(i,n??"")}),o.jsx(Cm,{label:"Version B",labelIsHidden:!0,name:"version-b",options:a,value:n??"",onValueChange:i=>r?.(t??"",i)}),o.jsx("div",{})]})}const hbs=[{name:"id",label:"ID",size:"1fr"},{name:"versionA",label:"Version A",size:"1fr"},{name:"versionB",label:"Version B",size:"1fr"},{name:"compare",label:"Compare",size:"10rem"}],M9={added:{badgeVariant:"blue",borderColor:"border-blue-900",icon:o.jsx(_r,{}),tooltip:"Added in this version"},changed:{badgeVariant:"yellow",borderColor:"border-yellow-900",icon:o.jsx(HJt,{}),tooltip:"Changed in this version"},same:{badgeVariant:"green",borderColor:"border-green-900",icon:o.jsx(Rct,{}),tooltip:"Same in both versions"}};function Xie({red:e=!1,tooltip:t}){return o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx("span",{}),role:"img",tabIndex:0,"aria-label":t,className:"focus-visible:outline-neutral5/55 rounded focus-visible:outline-1 focus-visible:outline-offset-2 focus-visible:outline-solid",children:o.jsx(k0e,{className:K("text-neutral3/40 w-5 h-5 ",{"text-red-900":e})})}),o.jsx(yn,{children:t})]})}function Jie({variant:e,version:t}){if(!e)return o.jsxs("span",{className:"text-ui-md text-neutral4",children:["v. ",t]});const{badgeVariant:n,icon:r,tooltip:s}=M9[e];return o.jsxs("div",{className:"grid grid-cols-[1fr_auto]",children:[t!==void 0&&o.jsxs("span",{className:"text-ui-md text-neutral4 flex min-w-16 justify-end pr-3",children:["v. ",t]}),o.jsx("span",{className:"inline-flex",role:"img","aria-label":s,children:o.jsx(bt,{variant:n,size:"xs",icon:r})})]})}function pbs(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function jtt({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return"added";if(t==="changed"&&n)return"changed"}function mbs({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:a}){const{Link:i}=dn(),l=t>n;return o.jsx(gi,{children:o.jsx(gi.Scroller,{children:o.jsx(gi.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=a.get(c),f=pbs(u,d),h=jtt({otherVersionExists:d!==void 0,status:f,isNewer:l}),p=jtt({otherVersionExists:u!==void 0,status:f,isNewer:!l});return o.jsxs(gi.Row,{columns:hbs,children:[o.jsx(gi.IdCell,{id:c,isShortened:!1}),f!=="same"?o.jsxs(o.Fragment,{children:[u?.datasetVersion?o.jsx(gi.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:h?M9[h].tooltip:void 0,children:o.jsx(Jie,{variant:h,version:u.datasetVersion})}):o.jsx(gi.Cell,{className:"flex items-center justify-center",children:o.jsx(Xie,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?o.jsx(gi.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:p?M9[p].tooltip:void 0,children:o.jsx(Jie,{variant:p,version:d.datasetVersion})}):o.jsx(gi.Cell,{className:"flex items-center justify-center",children:o.jsx(Xie,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):o.jsx(gi.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",tooltip:M9.same.tooltip,children:o.jsx(Jie,{variant:"same",version:d?.datasetVersion})}),f==="changed"?o.jsx(gi.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}/versions?ids=${u?.datasetVersion},${d?.datasetVersion}`,children:"Compare"}):o.jsx(gi.Cell,{children:o.jsx(Xie,{tooltip:"Comparing is available only for changed items"})})]},c)})})})})}function gbs(){const e=qr(),[t,n]=g.useState(""),[r,s]=g.useState("all"),[a,i]=g.useState("all"),{data:l=[],isLoading:c,error:u,isFetchingNextPage:d,hasNextPage:f,setEndOfListElement:h}=dPn(),{data:p,isLoading:m,error:v}=BH(),y=g.useMemo(()=>p?.experiments??[],[p?.experiments]),b=g.useMemo(()=>_vs(l),[l]),x=c||m,w=u||v,k=()=>{e("/datasets/new")};if(w&&hs(w))return o.jsx(Zn,{children:o.jsx(Ts,{})});if(w&&ps(w))return o.jsx(Zn,{children:o.jsx(ks,{resource:"datasets"})});if(w)return o.jsx(Zn,{children:o.jsx(La,{title:"Failed to load datasets",message:w.message})});if(l.length===0&&!x)return o.jsx(Zn,{children:o.jsx(Ivs,{onCreateClick:k})});const C=r!=="all"||a!=="all"||t!=="",_=()=>{n(""),s("all"),i("all")};return o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(Pvs,{search:t,onSearchChange:n,experimentFilter:r,onExperimentFilterChange:s,tagFilter:a,onTagFilterChange:i,tagOptions:b,onReset:_,hasActiveFilters:C,onCreateClick:k})}),o.jsx(Nvs,{datasets:l,experiments:y,isLoading:x,search:t,experimentFilter:r,tagFilter:a,isFetchingNextPage:d,hasNextPage:f,setEndOfListElement:h})]})}function n8({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function vbs(){const{datasetId:e}=fr(),t=qr(),[n,r]=za(),{activeVersion:s,handleVersionChange:a}=mRe(n,r),[i,l]=g.useState(!1),[c,u]=g.useState(!1),[d,f]=g.useState(!1),[h,p]=g.useState(!1),{data:m,error:v,isLoading:y}=zy(e),{data:b=[],isLoading:x}=Qx(e,void 0,s),w=!x&&b.length===0;if(y)return null;if(v&&hs(v))return o.jsx(n8,{children:o.jsx(Ts,{})});if(v&&ps(v))return o.jsx(n8,{children:o.jsx(ks,{resource:"datasets"})});if(v&&JEe(v)||!y&&!v&&!m)return o.jsx(n8,{children:o.jsx(br,{iconSlot:o.jsx(hm,{}),titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:o.jsxs(ie,{as:Da,to:"/datasets",children:[o.jsx(bl,{}),"Back to Datasets"]})})});if(v)return o.jsx(n8,{children:o.jsx(La,{title:"Failed to load dataset",message:v instanceof Error?v.message:"An unexpected error occurred. Please try again."})});const k=_=>{t(`/experiments/${_}`)},C=()=>{t("/datasets")};return o.jsxs(Oys,{datasetId:e,items:b,isLoadingItems:x,children:[o.jsxs("div",{className:"relative h-full overflow-hidden",children:[o.jsx(Lt,{height:"full",className:"grid-rows-[1fr] p-0",children:o.jsx(Lt.MainArea,{children:o.jsx(Cys,{datasetId:e,onAddItemClick:()=>u(!0),leftSlot:o.jsx("span",{className:"text-ui-sm text-neutral3 mr-3 whitespace-nowrap",children:m?.createdAt?`Created ${dr(new Date(m.createdAt),"MMM d")}`:""}),rightSlot:o.jsxs(es,{children:[o.jsxs(ie,{as:Da,to:`/experiments?dataset=${e}`,children:[o.jsx(_0e,{}),"View experiments"]}),o.jsx(bHt,{datasetId:e,value:s,onValueChange:a,currentVersion:m?.version,className:"w-36"}),w?o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx("span",{className:"cursor-not-allowed",children:o.jsx("div",{className:"pointer-events-none opacity-50",inert:!0,"aria-disabled":"true",children:o.jsxs(ie,{variant:"primary",children:[o.jsx(Dc,{}),"Run Experiment"]})})})}),o.jsx(yn,{children:"Add items to the dataset before running an experiment"})]}):o.jsxs(ie,{variant:"primary",onClick:()=>l(!0),children:[o.jsx(Dc,{}),"Run Experiment"]}),o.jsxs(at,{children:[o.jsx(at.Trigger,{asChild:!0,children:o.jsx(ie,{size:"lg","aria-label":"Dataset actions menu",children:o.jsx(iI,{})})}),o.jsxs(at.Content,{align:"end",className:"w-48",children:[o.jsxs(at.Item,{onSelect:()=>{t(`/datasets/${e}/edit`)},children:[o.jsx(Yh,{})," Edit Dataset"]}),o.jsxs(at.Item,{onSelect:()=>p(!0),children:[o.jsx(zd,{})," Duplicate Dataset"]}),o.jsxs(at.Item,{onSelect:()=>f(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(Fl,{})," Delete Dataset"]})]})]})]})})})}),o.jsx(Bg,{})]}),o.jsx(cY,{initialDatasetId:e,initialDatasetVersion:s??void 0,open:i,onOpenChange:l,onSuccess:k},`${e}:${s??"latest"}`),o.jsx(Eys,{datasetId:e,open:c,onOpenChange:u}),m&&o.jsx(Qvs,{open:h,onOpenChange:p,sourceDatasetId:m.id,sourceDatasetName:m.name,sourceDatasetDescription:m.description,sourceDatasetTargetType:m.targetType}),m&&o.jsx(Jvs,{open:d,onOpenChange:f,datasetId:m.id,datasetName:m.name,onSuccess:C})]})}function eoe({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function ybs(){const{datasetId:e}=fr(),t=qr(),{data:n,error:r,isLoading:s}=zy(e),a=()=>{t(`/datasets/${e}`)};return s?null:r&&hs(r)?o.jsx(eoe,{children:o.jsx(Ts,{})}):r&&ps(r)?o.jsx(eoe,{children:o.jsx(ks,{resource:"datasets"})}):r||!n?o.jsx(eoe,{children:o.jsx(La,{title:"Failed to load dataset",message:r instanceof Error?r.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-6 py-8",children:[o.jsx(Pa,{className:"mb-6 p-0",children:o.jsxs(Pa.Column,{children:[o.jsxs(Pa.Title,{children:[o.jsx(hm,{})," Edit dataset"]}),o.jsx(Pa.Description,{children:n.name})]})}),o.jsx(Ku,{className:"p-6",children:o.jsx(Xvs,{dataset:{id:n.id,name:n.name,description:n.description||"",inputSchema:n.inputSchema,groundTruthSchema:n.groundTruthSchema,requestContextSchema:n.requestContextSchema},onSuccess:a,onCancel:a})})]})})]})}function uY({label:e,wide:t=!1,children:n}){return o.jsxs("div",{className:K("pointer-events-none absolute inset-0 z-30","grid transition-[grid-template-columns] duration-300 ease-in-out",t?"grid-cols-[1fr_4fr]":"grid-cols-[1fr_1fr]"),children:[o.jsx("div",{className:"pointer-events-none"}),o.jsx("div",{role:"dialog","data-item-panel":!0,"aria-label":e,className:"pointer-events-auto h-full min-h-0 min-w-0 overflow-y-auto",children:n})]})}const r8=()=>{},bbs=new Set,xbs=[{name:"id",label:"ID",size:"7rem"},{name:"input",label:"Input",size:"minmax(10rem,1fr)"},{name:"groundTruth",label:"Ground Truth",size:"minmax(10rem,1fr)"},{name:"trajectory",label:"Trajectory",size:"8rem"},{name:"createdAt",label:"Created",size:"10rem"}];function wbs({datasetId:e,currentItemId:t,open:n,onOpenChange:r}){const{navigate:s,paths:a}=dn(),[i,l]=g.useState(""),[c]=YH(i,300),{data:u,isLoading:d,setEndOfListElement:f,isFetchingNextPage:h,hasNextPage:p}=Qx(e,c||void 0),m=u.filter(y=>y.id!==t),v=y=>{r(!1),s(a.datasetItemCompareLink(e,t,y))};return o.jsx(pr,{open:n,onOpenChange:r,children:o.jsxs(mr,{className:"sm:max-w-[min(72rem,calc(100%-4rem))]",children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Compare with…"}),o.jsx(Cs,{children:"Pick an item to compare with the current one."})]}),o.jsxs(jr,{className:"grid max-h-[70vh] min-h-[24rem] grid-rows-[auto_1fr] gap-3",children:[o.jsx(wC,{name:"compare-with-dialog-search",label:"Search items to compare",labelIsHidden:!0,value:i,onChange:y=>l(y.target.value),placeholder:"Search items..."}),o.jsx("div",{className:"min-h-0 overflow-y-auto",children:o.jsx(xHt,{items:m,isLoading:d,onItemClick:v,selectOnNavigate:!1,columns:xbs,searchQuery:c||" ",setEndOfListElement:f,isFetchingNextPage:h,hasNextPage:p,isSelectionActive:!1,selectedIds:bbs,onToggleSelection:r8,onSelectAll:r8,onClearSelection:r8,onAddClick:r8})})]})]})})}function Sbs(e){if(!(e instanceof Error))return null;const t=e.message.match(/- ({.*})$/);if(!t)return null;try{const n=JSON.parse(t[1]);if(n.field&&Array.isArray(n.errors))return{field:n.field,errors:n.errors}}catch{}return null}function kbs({datasetId:e,item:t,items:n,onItemChange:r,onClose:s}){const{Link:a}=dn(),{updateItem:i,deleteItem:l}=wi(),[c,u]=g.useState(!1),[d,f]=g.useState(""),[h,p]=g.useState(""),[m,v]=g.useState(""),[y,b]=g.useState(""),[x,w]=g.useState(""),[k,C]=g.useState(t.scorerIds!==void 0),[_,T]=g.useState(t.scorerIds??[]),[E,N]=g.useState(""),[I,A]=g.useState(null),[P,L]=g.useState(!1),[D,B]=g.useState(!1);g.useEffect(()=>{t&&(f(JSON.stringify(t.input,null,2)),p(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),v(t.metadata?JSON.stringify(t.metadata,null,2):""),b(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),w(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),C(t.scorerIds!==void 0),T(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),L(!1),A(null))},[t?.id]);const H=n.findIndex(U=>U.id===t.id),q=H>0?()=>r(n[H-1].id):void 0,z=H>=0&&H<n.length-1?()=>r(n[H+1].id):void 0,V=async()=>{let U;try{U=JSON.parse(d)}catch{Ve.error("Input must be valid JSON");return}let Z;if(h.trim())try{Z=JSON.parse(h)}catch{Ve.error("Ground Truth must be valid JSON");return}let Y;if(m.trim())try{Y=JSON.parse(m)}catch{Ve.error("Metadata must be valid JSON");return}let te=null;if(y.trim())try{te=JSON.parse(y)}catch{Ve.error("Expected Trajectory must be valid JSON");return}let J;if(x.trim())try{const ae=JSON.parse(x);if(!Array.isArray(ae)){Ve.error("Tool Mocks must be a JSON array");return}J=ae}catch{Ve.error("Tool Mocks must be valid JSON");return}else J=[];let ee;if(E.trim())try{ee=JSON.parse(E)}catch{Ve.error("Request Context must be valid JSON");return}let re;k?re=_:t.scorerIds!==void 0&&(re=null);try{const ae=await i.mutateAsync({datasetId:e,itemId:t.id,input:U,groundTruth:Z,metadata:Y,expectedTrajectory:te,toolMocks:J,scorerIds:re,requestContext:ee});Ve.success("Item updated successfully"),C(ae.scorerIds!==void 0),T(ae.scorerIds??[]),u(!1),A(null)}catch(ae){const X=Sbs(ae);X?A(X):Ve.error(`Failed to update item: ${ae instanceof Error?ae.message:"Unknown error"}`)}},M=()=>{f(JSON.stringify(t.input,null,2)),p(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),v(t.metadata?JSON.stringify(t.metadata,null,2):""),b(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),w(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),C(t.scorerIds!==void 0),T(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),A(null)},G=U=>{f(U),I?.field==="input"&&A(null)},F=U=>{p(U),I?.field==="groundTruth"&&A(null)},R=async()=>{try{await l.mutateAsync({datasetId:e,itemId:t.id}),Ve.success("Item deleted successfully"),L(!1),s()}catch(U){Ve.error(`Failed to delete item: ${U instanceof Error?U.message:"Unknown error"}`)}};return o.jsxs(o.Fragment,{children:[o.jsxs(Gt,{children:[o.jsxs(Gt.Header,{children:[o.jsxs(Gt.Heading,{children:["Item ",o.jsxs("b",{children:["# ",t.id.length>12?`${t.id.slice(0,12)}…`:t.id]})]}),o.jsxs(es,{className:"ml-auto shrink-0",children:[o.jsx(Gt.NextPrevNav,{onPrevious:q,onNext:z,previousLabel:"Previous item",nextLabel:"Next item"}),!c&&o.jsxs(o.Fragment,{children:[o.jsx(ie,{as:a,href:`/datasets/${e}/items/${t.id}/versions`,size:"md",tooltip:"Go to item versions history","aria-label":"Go to item versions history",children:o.jsx(uI,{})}),o.jsxs(at,{children:[o.jsx(at.Trigger,{asChild:!0,children:o.jsx(ie,{size:"md","aria-label":"Actions menu",children:o.jsx(iI,{})})}),o.jsxs(at.Content,{align:"end",className:"w-48",children:[o.jsxs(at.Item,{onSelect:()=>u(!0),children:[o.jsx(Yh,{}),"Edit"]}),o.jsxs(at.Item,{onSelect:()=>B(!0),children:[o.jsx(Nj,{}),"Compare with…"]}),o.jsxs(at.Item,{onSelect:()=>L(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(Fl,{}),"Delete Item"]})]})]})]}),o.jsx(Gt.CloseButton,{onClick:s,tooltip:"Close detail panel"})]})]}),o.jsx(Gt.Content,{children:c?o.jsx(jys,{inputValue:d,setInputValue:G,groundTruthValue:h,setGroundTruthValue:F,metadataValue:m,setMetadataValue:v,trajectoryValue:y,setTrajectoryValue:b,toolMocksValue:x,setToolMocksValue:w,scorerOverrideEnabled:k,setScorerOverrideEnabled:C,selectedScorerIds:_,setSelectedScorerIds:T,requestContextValue:E,setRequestContextValue:N,validationErrors:I,onSave:V,onCancel:M,isSaving:i.isPending}):o.jsxs(o.Fragment,{children:[o.jsxs(En,{children:[o.jsx(En.Key,{children:"Dataset Id"}),o.jsx(En.ValueWithCopyBtn,{copyTooltip:"Copy Dataset Id to clipboard",copyValue:t.datasetId,children:t.datasetId}),o.jsx(En.Key,{children:"Version"}),o.jsxs(En.Value,{children:["v",t.datasetVersion]}),o.jsx(En.Key,{children:"Created"}),o.jsx(En.Value,{children:dr(new Date(t.createdAt),"MMM d, yyyy h:mm aaa")}),t.updatedAt&&new Date(t.updatedAt).getTime()!==new Date(t.createdAt).getTime()&&o.jsxs(o.Fragment,{children:[o.jsx(En.Key,{children:"Updated"}),o.jsx(En.Value,{children:dr(new Date(t.updatedAt),"MMM d, yyyy h:mm aaa")})]})]}),o.jsxs("div",{className:"mt-3 grid gap-3",children:[o.jsx(Gt.CodeSection,{title:"Input",icon:o.jsx(Ox,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(Gt.CodeSection,{title:"Ground Truth",icon:o.jsx(nm,{}),codeStr:JSON.stringify(t.groundTruth??null,null,2)}),t.expectedTrajectory!=null&&o.jsx(Gt.CodeSection,{title:"Expected Trajectory",icon:o.jsx(P0e,{}),codeStr:JSON.stringify(t.expectedTrajectory,null,2)}),o.jsx(Gt.CodeSection,{title:"Tool Mocks",icon:o.jsx(Ud,{}),codeStr:JSON.stringify(t.toolMocks??[],null,2)}),o.jsx(Gt.CodeSection,{title:"Scorers",icon:o.jsx(PV,{}),codeStr:t.scorerIds===void 0?"Inherited from dataset":JSON.stringify(t.scorerIds,null,2)}),t.requestContext!=null&&o.jsx(Gt.CodeSection,{title:"Request Context",icon:o.jsx(sc,{}),codeStr:JSON.stringify(t.requestContext,null,2)}),o.jsx(Gt.CodeSection,{title:"Metadata",icon:o.jsx(dI,{}),codeStr:JSON.stringify(t.metadata??null,null,2)})]})]})})]}),o.jsx(wbs,{datasetId:e,currentItemId:t.id,open:D,onOpenChange:B}),o.jsx($t,{open:P,onOpenChange:L,children:o.jsxs($t.Content,{children:[o.jsxs($t.Header,{children:[o.jsx($t.Title,{children:"Delete Item"}),o.jsx($t.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),o.jsxs($t.Footer,{children:[o.jsx($t.Cancel,{children:"Cancel"}),o.jsx($t.Action,{onClick:R,children:l.isPending?"Deleting...":"Yes, Delete"})]})]})})]})}function Obs(){const{itemId:e}=fr(),{datasetId:t,items:n,isLoadingItems:r,openItem:s,close:a}=kHt(),i=g.useMemo(()=>n.find(d=>d.id===e)??null,[n,e]),{data:l,isLoading:c}=WD(i?"":t,!i&&e?e:""),u=i??l??null;return e?o.jsx(uY,{label:`Dataset item ${e}`,children:u?o.jsx("div",{className:"[&>section]:bg-surface3 flex min-h-full flex-col p-3 [&>section]:min-h-0 [&>section]:flex-1 [&>section]:rounded-lg [&>section]:shadow-lg",children:o.jsx(kbs,{datasetId:t,item:u,items:n,onItemChange:s,onClose:a})}):r||c?o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(Vt,{})})}):o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(br,{iconSlot:o.jsx(hm,{}),titleSlot:"Item not found",descriptionSlot:`No loaded item "${e}".`,actionSlot:o.jsx(ie,{onClick:a,children:"Close"})})})})}):null}function Ntt(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,metadata:e.metadata??null},null,2)}function Cbs(){const{datasetId:e,itemId:t,secondItemId:n}=fr(),r=qr(),s=[t,n].filter(p=>!!p),{data:a,error:i}=zy(e??""),{Link:l,paths:c}=dn(),[u,d]=g.useState(!1),{data:f}=WD(e??"",s[0]??""),{data:h}=WD(e??"",s[1]??"");return i&&hs(i)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{})})}):i&&ps(i)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ks,{resource:"datasets"})})}):!e||s.length<2?o.jsx(vs,{children:o.jsx(by,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Select at least two items to compare."})})})}):o.jsxs(vs,{children:[o.jsx(By,{owner:"dataset-items-compare",children:o.jsxs(ie,{as:Da,to:`/datasets/${e}`,variant:"outline",children:[o.jsx(bl,{}),"Back to Dataset"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:K("grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",{"grid-rows-[auto_auto_1fr]":u}),children:[o.jsxs(Pa,{children:[o.jsxs(Pa.Column,{children:[o.jsxs(Pa.Title,{children:[o.jsx(Nj,{}),"Compare Dataset Items"]}),o.jsx(Pa.Description,{children:o.jsxs(Pl,{children:["Comparing ",s.length," items of"," ",o.jsx(Da,{to:`/datasets/${e}`,className:"text-info1 hover:underline",children:a?.name||e?.slice(0,8)})]})})]}),o.jsx(Pa.Column,{children:o.jsx(es,{children:o.jsx(ie,{variant:"primary",onClick:()=>d(p=>!p),children:u?o.jsxs(o.Fragment,{children:[o.jsx(TV,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(vKt,{})," Diff View"]})})})})]}),o.jsx(o1,{className:"grid-cols-[1fr_3vw_1fr]",children:s.map((p,m)=>o.jsxs(g.Fragment,{children:[o.jsx(_bs,{datasetId:e,itemId:p,Link:l,idx:m,itemIds:s,showContent:!u,onItemChange:v=>{const y=[...s];y[m]=v,r(c.datasetItemCompareLink(e,y[0],y[1]))}}),m==0&&o.jsx("div",{className:K("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},p))}),u&&f&&h&&o.jsx(FAe,{codeA:Ntt(f),codeB:Ntt(h)})]})})]})}function _bs({datasetId:e,itemId:t,Link:n,idx:r,itemIds:s,onItemChange:a,showContent:i=!0}){const{data:l,isLoading:c}=WD(e,t),{data:u}=Qx(e),d=new Set(s.filter((h,p)=>p!==r)),f=(u??[]).map(h=>({value:h.id,label:h.id,disabled:d.has(h.id)}));return o.jsxs(ma,{children:[o.jsxs(ma.Toolbar,{className:"flex gap-4",children:[o.jsxs(la,{name:`compare-item-${r}`,value:t,onValueChange:a,children:[o.jsx(ua,{"aria-label":"Item",children:o.jsx(ca,{placeholder:"Select item"})}),o.jsx(da,{children:f.map(h=>o.jsx(xr,{value:h.value,disabled:h.disabled,children:h.label},h.value))})]}),o.jsxs(ie,{as:n,to:`/datasets/${e}/items/${t}`,children:[o.jsx(uI,{}),"Versions"]})]}),i&&o.jsx(ma.Content,{children:c?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):l?o.jsxs(o.Fragment,{children:[o.jsx(Tys,{item:l}),o.jsx(gRe,{item:l,Link:n})]}):o.jsxs("div",{className:"text-neutral4 text-sm",children:["Item ",t.slice(0,8)," not found"]})})]})}function Itt(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,scorerIds:e.scorerIds??null,metadata:e.metadata??null},null,2)}function Ebs(){const{datasetId:e,itemId:t}=fr(),[n,r]=za(),[s,a]=g.useState(!1),i=n.get("ids")?.split(",").map(Number).filter(p=>!isNaN(p)&&p>0)??[],{data:l,error:c}=zy(e??""),{Link:u}=dn(),{data:d}=pRe(e??"",t??""),{data:f}=r0e(e??"",t??"",i[0]??0,l?.version),{data:h}=r0e(e??"",t??"",i[1]??0,l?.version);return c&&hs(c)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{})})}):c&&ps(c)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ks,{resource:"datasets"})})}):!e||!t?o.jsx(vs,{children:o.jsx(by,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Item not found."})})})}):i.length<2?o.jsx(Tbs,{datasetId:e,itemId:t,Link:u,onCompare:p=>r({ids:p.join(",")})}):o.jsxs(vs,{children:[o.jsx(By,{owner:"dataset-item-versions-compare",children:o.jsxs(ie,{as:Da,to:`/datasets/${e}/items/${t}`,variant:"outline",children:[o.jsx(bl,{}),"Back to Item"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:K("grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",{"grid-rows-[auto_auto_1fr]":s}),children:[o.jsxs(Pa,{children:[o.jsxs(Pa.Column,{children:[o.jsxs(Pa.Title,{children:[o.jsx(Nj,{}),"Compare Dataset Item Versions"]}),o.jsx(Pa.Description,{children:o.jsxs(Pl,{children:["Comparing ",i.length," versions of"," ",o.jsx(Da,{to:`/datasets/${e}/items/${t}`,className:"text-info1 hover:underline",children:t})]})})]}),o.jsx(Pa.Column,{children:o.jsx(es,{children:o.jsx(ie,{variant:"primary",onClick:()=>a(p=>!p),children:s?o.jsxs(o.Fragment,{children:[o.jsx(TV,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(fXt,{})," Diff View"]})})})})]}),o.jsx(o1,{className:"grid-cols-[1fr_3vw_1fr]",children:i.map((p,m)=>o.jsxs(g.Fragment,{children:[o.jsx(jbs,{datasetId:e,itemId:t,datasetVersion:p,latestVersion:l?.version,allVersions:d??[],versionNumbers:i,Link:u,idx:m,showContent:!s,onVersionChange:v=>{const y=[...i];y[m]=v,r({ids:y.join(",")})}}),m===0&&o.jsx("div",{className:K("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},p))}),s&&f&&h&&o.jsx(FAe,{codeA:Itt(f),codeB:Itt(h)})]})})]})}function Tbs({datasetId:e,itemId:t,Link:n,onCompare:r}){const[s,a]=g.useState(null),{data:i,isLoading:l}=pRe(e,t),c=(s!=null?i?.find(d=>d.datasetVersion===s):void 0)??i?.[0],u=c?{id:c.id,datasetId:e,datasetVersion:c.datasetVersion,input:c.input,groundTruth:c.groundTruth,scorerIds:c.scorerIds,metadata:c.metadata,createdAt:c.createdAt,updatedAt:c.updatedAt}:null;return o.jsxs(vs,{children:[o.jsx(By,{owner:"dataset-item-versions-history",children:o.jsxs(ie,{as:Da,to:`/datasets/${e}/items/${t}`,variant:"outline",children:[o.jsx(bl,{}),"Back to Item"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:"mx-auto grid h-full max-w-[140rem] grid-rows-[auto_1fr] gap-6",children:[o.jsx(Pa,{children:o.jsxs(Pa.Column,{children:[o.jsxs(Pa.Title,{children:[o.jsx(uI,{}),"Item Version History"]}),o.jsx(Pa.Description,{children:o.jsxs(Pl,{children:["Versions of ",t]})})]})}),o.jsxs(o1,{className:"grid-cols-[1fr_auto]",children:[o.jsx(ma,{children:o.jsx(ma.Content,{children:l?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):u?o.jsx(gRe,{item:u,Link:n}):o.jsx("div",{className:"text-neutral4 text-sm",children:"Item data not available"})})}),o.jsx(cbs,{datasetId:e,itemId:t,onClose:()=>{},onVersionSelect:d=>a(d.datasetVersion),onCompareVersionsClick:r,activeVersion:s})]})]})})]})}function jbs({datasetId:e,itemId:t,datasetVersion:n,latestVersion:r,allVersions:s,versionNumbers:a,Link:i,idx:l,showContent:c=!0,onVersionChange:u}){const{data:d,isLoading:f}=r0e(e,t,n,r),h=new Set(a.filter((v,y)=>y!==l)),p=s.map(v=>{const y=typeof v.updatedAt=="string"?new Date(v.updatedAt):v.updatedAt;return{value:String(v.datasetVersion),label:o.jsxs(o.Fragment,{children:[o.jsxs("b",{children:["v. ",v.datasetVersion]})," - ",dr(y,"MMM d, yyyy h:mm a"),v.isLatest?o.jsx(bt,{variant:"blue",size:"xs",children:"Latest"}):null]}),disabled:h.has(v.datasetVersion)}}),m=d?{id:d.id,datasetId:e,datasetVersion:d.datasetVersion,input:d.input,groundTruth:d.groundTruth,scorerIds:d.scorerIds,metadata:d.metadata,createdAt:d.createdAt,updatedAt:d.updatedAt}:null;return o.jsxs(ma,{children:[o.jsxs(ma.Toolbar,{className:"grid grid-cols-[auto_1fr] gap-4",children:[o.jsx(uI,{className:"h-6 w-6 opacity-50"}),o.jsxs(la,{name:`compare-version-${l}`,value:String(n),onValueChange:v=>u(Number(v)),children:[o.jsx(ua,{"aria-label":"Version",className:"w-full",children:o.jsx(ca,{placeholder:"Select version"})}),o.jsx(da,{children:p.map(v=>o.jsx(xr,{value:v.value,disabled:v.disabled,children:v.label},v.value))})]})]}),c&&o.jsx(ma.Content,{children:f?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):!d||!m?o.jsxs("div",{className:"text-neutral4 text-sm",children:["Version ",n," not found"]}):o.jsx(gRe,{item:m,Link:i})})]})}function Nbs(){const{datasetId:e}=fr(),[t]=za(),n=t.get("ids")?.split(",").map(Number).filter(v=>!isNaN(v)&&v>0)??[],r=qr(),{data:s,error:a}=zy(e??""),i=Qx(e??"",void 0,n[0]??null),l=Qx(e??"",void 0,n[1]??null),c=g.useMemo(()=>i.data??[],[i.data]),u=g.useMemo(()=>l.data??[],[l.data]),d=g.useMemo(()=>{const v=new Map;for(const y of[...c,...u])v.has(y.id)||v.set(y.id,{id:y.id,createdAt:new Date(y.createdAt)});return[...v.values()].sort((y,b)=>b.createdAt.getTime()-y.createdAt.getTime())},[c,u]),f=g.useMemo(()=>new Map(c.map(v=>[v.id,v])),[c]),h=g.useMemo(()=>new Map(u.map(v=>[v.id,v])),[u]);if(a&&hs(a))return o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{})})});if(a&&ps(a))return o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ks,{resource:"datasets"})})});if(!e||n.length<2)return o.jsx(vs,{children:o.jsx(by,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Select at least two versions to compare."})})})});const p=(v,y,b)=>{r(`/datasets/${e}/items/${v}/versions?ids=${y?.datasetVersion??""},${b?.datasetVersion??""}`)},m=(v,y)=>{r(`/datasets/${e}/versions?ids=${v},${y}`,{replace:!0})};return o.jsx(vs,{children:o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:"mx-auto grid h-full max-w-[140rem] grid-rows-[auto_1fr] gap-6",children:[o.jsxs(Pa,{children:[o.jsxs(Pa.Column,{children:[o.jsxs(Pa.Title,{children:[o.jsx(xen,{})," Compare Dataset Versions"]}),o.jsx(Pa.Description,{children:o.jsxs(Pl,{children:[o.jsx(uI,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),o.jsx(Pa.Column,{children:o.jsxs(ie,{as:Da,to:`/datasets/${e}`,children:[o.jsx(bl,{}),"Back to Dataset"]})})]}),o.jsx(o1,{children:o.jsxs(ma,{children:[o.jsx(fbs,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:m}),o.jsx(mbs,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:h,onItemClick:p})]})})]})})})}function Ibs(){const e=qr(),[t]=za(),n=t.get("targetType"),r=s0e(n)?n:void 0,s=t.get("targetIds"),a=r&&s?s.split(",").map(i=>i.trim()).filter(Boolean):void 0;return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-6 py-8",children:[o.jsx(Pa,{className:"mb-6 p-0",children:o.jsxs(Pa.Column,{children:[o.jsxs(Pa.Title,{children:[o.jsx(hm,{})," Create new dataset"]}),o.jsx(Pa.Description,{children:"Datasets group test cases used to evaluate your agents and workflows."})]})}),o.jsx(Ku,{className:"p-6",children:o.jsx(Wvs,{targetType:r,targetIds:a,onSuccess:i=>{e(`/datasets/${i}`)},onCancel:()=>{e(-1)}})})]})})]})}function o0e({children:e,className:t}){return o.jsx("div",{className:K("flex flex-wrap gap-8",t),children:e})}function Abs(e){if(!e||e.length<2)return null;const t=[...e].sort((i,l)=>new Date(i.createdAt).getTime()-new Date(l.createdAt).getTime()),n=Math.floor(t.length/2),r=n,s=t.length-n;if(r===0)return null;const a=(s-r)/r*100;return{changePct:Math.round(a*10)/10,prevValue:String(r)}}function Rbs({scorers:e,datasets:t,experiments:n,avgScore:r,prevAvgScore:s,totalNeedsReview:a,isLoadingScorers:i,isLoadingDatasets:l,isLoadingExperiments:c,isLoadingScores:u,isLoadingReview:d}){const f=e?Object.keys(e).length:void 0,h=t?.length,p=n?.length,m=r!=null&&s!=null&&s!==0?{changePct:Math.round((r-s)/s*100*10)/10,prevValue:String(s)}:null,v=Abs(n);return o.jsxs(o.Fragment,{children:[o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Total Scorers"}),i?o.jsx(Xr.Loading,{}):f!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(f)}),o.jsx(Xr.NoChange,{message:"Static count"})]}):o.jsx(Xr.NoData,{})]}),o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Total Datasets"}),l?o.jsx(Xr.Loading,{}):h!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(h)}),o.jsx(Xr.NoChange,{message:"Static count"})]}):o.jsx(Xr.NoData,{})]}),o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Avg Score"}),u?o.jsx(Xr.Loading,{}):r!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(r)}),m?o.jsx(Xr.Change,{changePct:m.changePct,prevValue:m.prevValue}):o.jsx(Xr.NoChange,{})]}):o.jsx(Xr.NoData,{})]}),o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Total Experiments"}),c?o.jsx(Xr.Loading,{}):p!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(p)}),v?o.jsx(Xr.Change,{changePct:v.changePct,prevValue:v.prevValue}):o.jsx(Xr.NoChange,{})]}):o.jsx(Xr.NoData,{})]}),o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Needs Review"}),d?o.jsx(Xr.Loading,{}):a!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(a)}),a>0?o.jsx(Xr.NoChange,{message:"items pending review"}):o.jsx(Xr.NoChange,{message:"All caught up"})]}):o.jsx(Xr.NoData,{})]})]})}function jHt(e){const t=y0(e.id)??e.id;return e.name||`Experiment #${t}`}const Pbs=60;function $bs({experiment:e}){return o.jsx("span",{className:"text-neutral4 block min-w-0 truncate text-left",children:jHt(e)})}function Mbs({experiment:e}){const t=e.description;if(!t)return o.jsx("span",{className:"text-neutral2",children:"—"});const n=o.jsx("span",{className:"text-neutral3 block min-w-0 truncate text-left",children:t});return t.length<=Pbs?n:o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:n}),o.jsx(yn,{children:t})]})}const dY=()=>{const{requestContext:e}=ys(),t=Ye();return mt({queryKey:["processors"],queryFn:()=>t.listProcessors(e)})},NHt=(e,t)=>{const n=Ye(),{requestContext:r}=ys();return mt({queryKey:["processor",e],queryFn:()=>n.getProcessor(e).details(r),enabled:!!e})},Dbs=()=>{const e=Ye(),{requestContext:t}=ys();return Sn({mutationFn:async({processorId:n,phase:r,messages:s,agentId:a})=>e.getProcessor(n).execute({phase:r,messages:s,agentId:a,requestContext:t})})};function IHt(){const{data:e}=Bm(),{data:t}=Xy(),{data:n}=up(),{data:r}=dY();return{agents:e,workflows:t,scorers:n,processors:r}}const AHt={agent:Ri,workflow:Bc,scorer:P_,processor:jD},RHt={agent:"Agent",workflow:"Workflow",scorer:"Scorer",processor:"Processor"},Lbs="External (caller-run)";function PHt(e,{agents:t,workflows:n,scorers:r,processors:s}){const{targetType:a,targetId:i}=e;if(!i)return Lbs;switch(a){case"agent":return t?.[i]?.name??i;case"workflow":return n?.[i]?.name??i;case"scorer":return r?.[i]?.scorer?.config?.name??i;case"processor":return s?.[i]?.name??i;default:return i}}function Fbs({experiment:e,datasetName:t,review:n}){const r=e.status??"pending",s=e.succeededCount??0,a=e.failedCount??0,i=e.totalItems??0;return o.jsxs(o.Fragment,{children:[o.jsx(pe.Cell,{children:o.jsx($bs,{experiment:e})}),o.jsx(pe.Cell,{children:o.jsx(Mbs,{experiment:e})}),t!==void 0&&o.jsx(pe.TextCell,{children:t}),o.jsx(pe.Cell,{children:o.jsx(zbs,{experiment:e})}),o.jsx(pe.Cell,{children:o.jsx(bt,{variant:uqt[r]??"neutral",indicator:"dot",children:LT[r]??r})}),o.jsx(pe.TextCell,{className:"text-center",children:i}),o.jsx(pe.TextCell,{className:"text-center",children:s}),o.jsx(pe.TextCell,{className:"text-center",children:o.jsx("span",{className:a>0?"text-accent2":"",children:a})}),o.jsx(pe.Cell,{className:"text-center",children:o.jsx(Bbs,{review:n})}),o.jsx(pe.TextCell,{children:Sus(e.createdAt)})]})}function zbs({experiment:e}){const t=IHt(),n=PHt(e,t),r=e.targetId?e.targetType:null,s=r?AHt[r]:null;return o.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 [&_svg]:size-3.5 [&_svg]:shrink-0",children:[s&&o.jsx("span",{className:"text-neutral3 flex",role:"img","aria-label":RHt[r],children:o.jsx(s,{})}),o.jsx("span",{className:r?"truncate":"text-neutral2 truncate",children:n})]})}function Bbs({review:e}){if(!e)return o.jsx("span",{className:"text-neutral2",children:"—"});const t=e.needsReview+e.complete;return t===0?o.jsx("span",{className:"text-neutral2",children:"—"}):e.needsReview>0?o.jsxs(bt,{size:"xs",variant:"yellow",children:[e.needsReview," pending"]}):o.jsxs(bt,{size:"xs",variant:"green",children:[e.complete,"/",t," reviewed"]})}const toe=`${yus} ${bus} ${xus} ${wus}`,Ubs=[{label:Ev.experiment},{label:Ev.description},{label:Ev.dataset},{label:Ev.target},{label:Ev.status},{label:Ev.items,className:"text-center"},{label:Ev.succeeded,className:"text-center"},{label:Ev.failed,className:"text-center"},{label:Ev.review,className:"text-center"},{label:Ev.date}];function qbs({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:a="all",datasetFilter:i="all",selection:l}){const c=l!==void 0,{paths:u,Link:d}=dn(),f=g.useMemo(()=>{const x=new Map;return t?.forEach(w=>x.set(w.id,w.name)),x},[t]),h=g.useMemo(()=>[...e].sort((x,w)=>{const k=x.createdAt?new Date(x.createdAt).getTime():0;return(w.createdAt?new Date(w.createdAt).getTime():0)-k}),[e]),p=g.useMemo(()=>{const x=s.toLowerCase();return h.filter(w=>{const k=w.datasetId?f.get(w.datasetId)??"":"",C=!x||w.id.toLowerCase().includes(x)||(w.name??"").toLowerCase().includes(x)||k.toLowerCase().includes(x)||(w.targetId??"").toLowerCase().includes(x),_=a==="all"||w.status===a,T=i==="all"||w.datasetId===i;return C&&_&&T})},[h,s,f,a,i]),{containerRef:m,getRowProps:v}=ao({count:p.length});if(r)return o.jsx(Bo,{columns:toe});const y=c?`auto ${toe}`:toe,b=Ubs.map(x=>o.jsx(pe.TopCell,{className:x.className,children:x.label},x.label));return o.jsxs(pe,{columns:y,scrollRef:m,children:[o.jsx(pe.Top,{hasLeadingCell:c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(pe.TopCell,{children:" "}),o.jsx(pe.TopCells,{colStart:2,children:b})]}):b}),p.map((x,w)=>{const k=x.datasetId?f.get(x.datasetId)??y0(x.datasetId)??x.datasetId:"—",C=o.jsx(Fbs,{experiment:x,datasetName:k,review:n?.get(x.id)});if(!l)return o.jsx(pe.RowLink,{to:u.experimentLink(x.id),LinkComponent:d,...v(w),children:C},x.id);const _=l.selectedExperimentIds.includes(x.id),T=()=>l.onToggleSelection(x.id);return o.jsxs(pe.RowWrapper,{children:[o.jsx(pe.SelectCell,{checked:_,onToggle:T,"aria-label":`Select experiment ${x.id}`}),o.jsx(pe.RowButton,{colStart:2,featured:_,onClick:T,...v(w),children:C})]},x.id)})]})}const Vbs=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function Hbs(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const s8={completed:L7.neutral3,running:"#facc15",pending:"#fb923c",failed:"#f87171"},Wbs=[{label:"Completed",color:s8.completed},{label:"Running",color:s8.running},{label:"Pending",color:s8.pending},{label:"Failed",color:s8.failed}];function Zbs({experiments:e,datasets:t,isLoading:n,isError:r}){const{data:s,maxVal:a}=g.useMemo(()=>{if(!e||e.length===0)return{data:[],maxVal:0};const l=new Map;if(t)for(const f of t)l.set(f.id,f.name);const c=new Map;for(const f of e){const h=f.datasetId??"unknown";c.has(h)||c.set(h,{completed:0,running:0,pending:0,failed:0});const p=c.get(h),m=f.status;m in p&&p[m]++}let u=0;return{data:Array.from(c.entries()).map(([f,h])=>{const p=h.completed+h.running+h.pending+h.failed;return p>u&&(u=p),{name:l.get(f)??f.slice(0,12),values:[h.completed,h.running,h.pending,h.failed]}}),maxVal:u}},[e,t]),i=s.length>0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Experiments by Dataset",description:"Experiment status breakdown per dataset."}),i&&o.jsx(Ht.Summary,{value:String(e?.length??0),label:"Total experiments"})]}),n?o.jsx(Ht.Loading,{}):r?o.jsx(Ht.Error,{message:"Failed to load experiments data"}):o.jsx(Ht.Content,{children:i?o.jsx(KN,{data:s,segments:Wbs,maxVal:a,fmt:l=>String(l)}):o.jsx(Ht.NoData,{message:"No experiments have been run yet"})})]})}const Gbs=({onRunExperiment:e})=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx(Mc,{}),titleSlot:"No Experiments yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Run an experiment from a dataset to evaluate ",o.jsx("br",{}),"your agents and workflows."]}),actionSlot:o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e&&o.jsxs(ie,{variant:"primary",onClick:e,children:[o.jsx(Dc,{}),"Run Experiment"]}),o.jsxs(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/evals/experiments",target:"_blank",rel:"noopener noreferrer",children:["Experiments Documentation ",o.jsx(ta,{})]})]})})});function Qbs({search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:i,onReset:l,hasActiveFilters:c,onRunClick:u,runTooltip:d="Run an experiment",onCompareClick:f,selection:h}){if(h){const{selectedCount:p,onExecuteCompare:m,onCancelSelection:v,compareDisabledReason:y}=h,b=p===2&&!y;return o.jsx("div",{className:"flex w-full items-center justify-end gap-4",children:o.jsxs("div",{className:"flex items-center gap-5",children:[o.jsxs("div",{className:"text-neutral3 flex items-center gap-2 pl-6 text-sm",children:[o.jsx(bt,{size:"md",variant:p<2?"red":"green",children:p}),o.jsx("span",{children:"of 2 experiments selected"}),y&&o.jsxs("span",{className:"text-accent2",children:["— ",y]}),o.jsx(qct,{})]}),o.jsxs(es,{children:[o.jsxs(ie,{variant:"primary",disabled:!b,onClick:m,children:[o.jsx(Nj,{className:"h-4 w-4"}),"Compare Experiments"]}),o.jsx(ie,{onClick:v,children:"Cancel"})]})]})})}return o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("div",{className:"max-w-120 min-w-64 flex-1",children:o.jsx(cd,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t})}),o.jsxs(es,{children:[o.jsx(Cm,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...Vbs],value:n,onValueChange:r,className:"whitespace-nowrap"}),o.jsx(Cm,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:i,value:s,onValueChange:a,className:"whitespace-nowrap"}),l&&c&&o.jsxs(ie,{onClick:l,size:"sm",variant:"default",children:[o.jsx(or,{className:"size-3"})," Reset"]})]}),o.jsxs(es,{className:"ml-auto shrink-0",children:[f&&o.jsxs(ie,{onClick:f,tooltip:"Select two experiments of the same dataset to compare",children:[o.jsx(Nj,{}),"Compare"]}),u&&o.jsxs(ie,{onClick:u,tooltip:d,variant:"primary",children:[o.jsx(Dc,{}),"Run Experiment"]})]})]})}const Ybs={present:!1,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},Att=e=>e?e instanceof Date?e.toISOString():e:null,Rtt=e=>{const t=new Map;for(const n of e??[])t.set(n.itemId,n);return t},Ptt=(e,t,n)=>{if(!e)return Ybs;const r=new Map;for(const s of n??[])r.set(s.scorerId,s.reason??null);return{present:!0,output:e.output,metadata:t?.metadata??null,comment:t?.comment??null,error:t?.error??null,startedAt:Att(t?.startedAt),completedAt:Att(t?.completedAt),scores:Object.entries(e.scores).map(([s,a])=>({scorerId:s,value:a,reason:r.get(s)??null})).sort((s,a)=>s.scorerId.localeCompare(a.scorerId))}},Kbs=({comparison:e,baselineId:t,contenderId:n,baselineResults:r,contenderResults:s,baselineScores:a,contenderScores:i})=>{if(!e)return[];const l=Rtt(r),c=Rtt(s);return e.items.map(u=>{const d=Ptt(u.results[t],l.get(u.itemId),a?.[u.itemId]),f=Ptt(u.results[n],c.get(u.itemId),i?.[u.itemId]),h={};for(const p of new Set([...d.scores,...f.scores].map(m=>m.scorerId))){const m=d.scores.find(y=>y.scorerId===p)?.value??null,v=f.scores.find(y=>y.scorerId===p)?.value??null;h[p]=m!=null&&v!=null?v-m:null}return{itemId:u.itemId,input:u.input,groundTruth:u.groundTruth,baseline:d,contender:f,deltas:h}})};function Lk({title:e,actions:t,tone:n="default",defaultOpen:r=!0,children:s}){return o.jsxs(fc,{defaultOpen:r,className:"grid gap-2",children:[o.jsxs("div",{className:"flex min-h-6 items-center justify-between gap-2",children:[o.jsxs(ql,{className:K("text-ui-md flex items-center gap-1.5 font-semibold [&>svg]:size-4",n==="negative"?"text-negative1":"text-neutral5"),children:[o.jsx(Lr,{}),e]}),t]}),o.jsx(Vl,{role:"region","aria-label":e,children:s})]})}function $tt({label:e,value:t}){return t==null?null:o.jsx(Lk,{title:e,defaultOpen:!1,children:o.jsx("pre",{className:"text-ui-sm text-neutral4 bg-surface3 max-h-40 overflow-auto rounded-md p-3 whitespace-pre-wrap",children:typeof t=="string"?t:JSON.stringify(t,null,2)})})}function $Ht({delta:e}){const t=e>0?"text-positive1":e<0?"text-negative1":"text-neutral3";return o.jsxs("span",{className:K("inline-flex min-w-20 items-center gap-1 font-mono text-sm",t),children:[o.jsx("span",{className:"inline-block w-3",children:e>0?"+":e<0?"-":""}),Math.abs(e).toFixed(2),e>0?o.jsx(QQt,{className:"size-3.5"}):e<0?o.jsx(FQt,{className:"size-3.5"}):null]})}function MHt({scorerId:e,value:t,delta:n,reason:r}){const{Link:s,paths:a}=dn();return o.jsxs("div",{className:"bg-surface2 grid gap-1 rounded-lg px-3 py-2",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4",children:[o.jsxs(s,{href:a.scorerLink(e),"aria-label":`Open ${e}`,className:"text-neutral5 flex min-w-0 items-center gap-1.5 text-sm font-medium hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[o.jsx(P_,{}),o.jsx("span",{className:"min-w-0 truncate",children:e})]}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:"text-neutral3 font-mono text-sm",children:t!=null?t.toFixed(2):"-"}),n!=null&&o.jsx($Ht,{delta:n})]})]}),r&&o.jsx("p",{className:"text-neutral3 text-sm",children:r})]})}function Mtt(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Xbs(e){if(!e.startedAt||!e.completedAt)return null;const t=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return Number.isFinite(t)?`${(t/1e3).toFixed(2)}s`:null}const Jbs="border-border1 bg-surface3 text-ui-md text-neutral4 max-h-[30vh] overflow-y-auto rounded-xl border p-4 font-mono break-all whitespace-pre-wrap dark:border-white/10 dark:bg-black/20";function Dtt({side:e,row:t,showDeltas:n,isLoading:r}){const s=t[e],a=Xbs(s);if(r)return o.jsx("div",{className:"flex h-32 items-center justify-center",children:o.jsx(Vt,{})});if(!s.present)return o.jsx("p",{className:"text-neutral3 py-8 text-center text-sm",children:"Not present in this experiment"});const i=Mtt(s.output);return o.jsxs("div",{className:"grid content-start gap-5",children:[a&&o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsxs("p",{className:"text-neutral3 flex items-center justify-end gap-1.5 text-sm [&>svg]:size-3.5",children:[o.jsx(c1,{}),a]})}),o.jsx(yn,{children:"Run duration"})]}),s.error?o.jsx(Lk,{title:"Error",tone:"negative",actions:o.jsx(_a,{content:s.error.message}),children:o.jsx("p",{className:"border-negative1/40 bg-negative1/5 text-ui-md text-neutral4 rounded-xl border p-4 break-words",children:s.error.message})}):o.jsx(Lk,{title:"Output",actions:o.jsx(_a,{content:i}),children:o.jsx("pre",{className:Jbs,children:i})}),s.scores.length>0&&o.jsx(Lk,{title:"Scores",children:o.jsx("div",{className:"grid gap-2",children:s.scores.map(l=>o.jsx(MHt,{scorerId:l.scorerId,value:l.value,delta:n?t.deltas[l.scorerId]:null,reason:l.reason},l.scorerId))})}),s.comment&&o.jsx(Lk,{title:"Comment",defaultOpen:!1,children:o.jsx("p",{className:"text-neutral3 text-sm",children:s.comment})}),s.metadata&&Object.keys(s.metadata).length>0&&o.jsx(Lk,{title:"Metadata",defaultOpen:!1,children:o.jsx("dl",{className:"grid gap-1",children:Object.entries(s.metadata).map(([l,c])=>o.jsxs("div",{className:"flex items-start justify-between gap-4 text-sm",children:[o.jsx("dt",{className:"text-neutral3",children:l}),o.jsx("dd",{className:"text-neutral5 font-mono break-all",children:Mtt(c)})]},l))})})]})}const exs={baseline:"Baseline",contender:"Contender"},txs={baseline:"purple",contender:"blue"},nxs="flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0";function Ltt({side:e,experiment:t,summary:n,showDeltas:r,versionMismatch:s}){const{Link:a,paths:i}=dn(),l=exs[e],c=t?y0(t.id)??t.id:null,u=t?.createdAt?new Date(t.createdAt):null,d=n??[];return o.jsxs("div",{className:"grid content-start gap-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(bt,{variant:txs[e],size:"xs",children:l}),t&&o.jsx(ie,{as:a,size:"xs",href:`/experiments/${t.id}`,"aria-label":`Open experiment ${t.name||c}`,children:o.jsx("span",{className:"min-w-0 truncate",children:t.name||c})})]}),t&&o.jsxs("div",{className:"text-ui-sm text-neutral3 flex flex-wrap gap-x-4 gap-y-1",children:[t.name&&o.jsxs(Pl,{children:[o.jsx(AV,{})," ",c]}),t.targetType==="agent"&&t.targetId?o.jsxs(a,{href:i.agentLink(t.targetId),className:nxs,children:[o.jsx(Ri,{}),o.jsx("span",{className:"min-w-0 truncate",children:t.targetId})]}):o.jsxs(Pl,{children:[o.jsx(Kct,{})," ",t.targetId]}),o.jsx("span",{className:K(s&&"text-accent6"),children:o.jsxs(Pl,{children:[o.jsx(RV,{})," v",t.datasetVersion??"—",s&&" · different dataset version"]})}),u&&o.jsxs(Pl,{children:[o.jsx(B9,{})," ",dr(u,"MMM d, yyyy HH:mm")]})]}),d.length>0&&o.jsx(Lk,{title:"Overall score",children:o.jsx("div",{className:"grid gap-2",children:d.map(({scorerId:f,average:h,delta:p})=>o.jsx(MHt,{scorerId:f,value:h,delta:r?p:null},f))})})]})}const HE="min-w-0 px-4 py-3";function rxs({datasetId:e,experimentIdA:t,experimentIdB:n}){const{Link:r,paths:s}=dn(),{data:a,isLoading:i,error:l}=lvs(e,t,n),{data:c}=VD(e,t),{data:u}=VD(e,n),d=c&&u&&c.datasetVersion!==u.datasetVersion,f=a?.baselineId??t,h=t===f?n:t,p=c?.id===f?c:u,m=c?.id===h?c:u,{data:v,isLoading:y}=HD({datasetId:e,experimentId:f,experimentStatus:p?.status}),{data:b,isLoading:x}=HD({datasetId:e,experimentId:h,experimentStatus:m?.status}),{data:w}=jC(f,p?.status),{data:k}=jC(h,m?.status),C=g.useMemo(()=>Kbs({comparison:a,baselineId:f,contenderId:h,baselineResults:v,contenderResults:b,baselineScores:w,contenderScores:k}),[a,f,h,v,b,w,k]),_=g.useMemo(()=>[...new Set(C.flatMap(E=>Object.keys(E.deltas)))].sort(),[C]),T=g.useMemo(()=>{const E=(A,P)=>{const L=C.map(D=>D[A].scores.find(B=>B.scorerId===P)?.value).filter(D=>D!=null);return L.length>0?L.reduce((D,B)=>D+B,0)/L.length:null},N=_.map(A=>({scorerId:A,average:E("baseline",A),delta:null})),I=_.map(A=>{const P=E("baseline",A),L=E("contender",A);return{scorerId:A,average:L,delta:P!=null&&L!=null?L-P:null}});return{baseline:N,contender:I}},[C,_]);return i?o.jsx("div",{className:"flex h-64 items-center justify-center",children:o.jsx(Vt,{})}):l?o.jsx(Rn,{variant:"warning",title:"Error loading comparison",children:o.jsx(Rn.Message,{children:l instanceof Error?l.message:"Unknown error"})}):!a||a.items.length===0?o.jsx("div",{className:"text-neutral4 py-8 text-center text-sm",children:"No comparison data"}):o.jsx("div",{className:"grid gap-4",children:o.jsxs("div",{role:"table","aria-label":"Experiments comparison",className:"grid",children:[o.jsxs("div",{role:"row",className:"border-border1 grid border-y xl:grid-cols-[minmax(20rem,24rem)_1fr_1fr] xl:divide-x xl:divide-[var(--border1)]",children:[o.jsx("div",{role:"columnheader","aria-label":"Items",className:`${HE} text-neutral3 text-ui-sm uppercase`,children:"Items"}),o.jsx("div",{role:"columnheader","aria-label":"Baseline",className:HE,children:o.jsx(Ltt,{side:"baseline",experiment:p,summary:T.baseline,versionMismatch:d})}),o.jsx("div",{role:"columnheader","aria-label":"Contender",className:HE,children:o.jsx(Ltt,{side:"contender",experiment:m,summary:T.contender,versionMismatch:d,showDeltas:!0})})]}),C.map(E=>{const N=Object.entries(E.deltas).filter(([,I])=>I!=null&&I!==0);return o.jsxs("div",{role:"row","aria-label":E.itemId,className:"border-border1 grid border-b xl:grid-cols-[minmax(20rem,24rem)_1fr_1fr] xl:divide-x xl:divide-[var(--border1)]",children:[o.jsxs("div",{role:"cell",className:`${HE} grid content-start gap-1`,children:[o.jsx(r,{href:s.datasetItemLink(e,E.itemId),"aria-label":`Open item ${E.itemId}`,className:K("text-ui-sm flex items-start gap-1.5 font-mono break-all hover:underline [&>svg]:mt-0.5 [&>svg]:size-3.5 [&>svg]:shrink-0",E.baseline.present&&E.contender.present?"text-neutral4":"text-neutral1"),children:o.jsx("span",{className:"min-w-0",children:E.itemId})}),N.length>0&&o.jsx("span",{className:"flex flex-wrap items-center gap-2",children:N.map(([I,A])=>o.jsx($Ht,{delta:A},I))}),o.jsxs("div",{className:"grid pt-3",children:[o.jsx($tt,{label:"Input",value:E.input}),o.jsx($tt,{label:"Ground truth",value:E.groundTruth})]})]}),o.jsx("div",{role:"cell","aria-label":"Baseline",className:HE,children:o.jsx(Dtt,{side:"baseline",row:E,isLoading:y})}),o.jsx("div",{role:"cell","aria-label":"Contender",className:HE,children:o.jsx(Dtt,{side:"contender",row:E,isLoading:x,showDeltas:!0})})]},E.itemId)})]})})}const sxs=100;function fY(e){const t=Ye(),n={perPage:sxs};return mt({queryKey:e?["dataset-experiments",e,n]:["experiments",n],queryFn:()=>e?t.listDatasetExperiments(e,n):t.listExperiments(n)})}const DHt=(e,t)=>{const n=Ye(),{data:r,isLoading:s}=fY(void 0),a=r?.experiments,i=t?a?.filter(c=>c.id===t):a,l=mt({queryKey:["review-items",e,t??"all",i?.map(c=>c.id)],queryFn:async()=>!i||i.length===0?[]:(await Promise.all(i.map(async u=>{if(!u.datasetId)return[];try{const{results:d}=await n.listDatasetExperimentResults(u.datasetId,u.id);return d.filter(f=>f.status===e).map(f=>({id:f.id,input:f.input,output:f.output,error:f.error,itemId:f.itemId,experimentId:f.experimentId,datasetId:u.datasetId??void 0,traceId:f.traceId??void 0,scores:f.scores?Object.fromEntries(f.scores.map(h=>[h.scorerId,h.score??0])):{},tags:f.tags??[],comment:f.comment??""}))}catch{return[]}}))).flat(),enabled:!!a,refetchOnWindowFocus:!1});return{...l,isLoading:l.isLoading||s}},axs=({experimentId:e}={})=>DHt("needs-review",e),ixs=({experimentId:e}={})=>DHt("complete",e);function oxs(e,t){if(typeof e=="string")return e.length>t?e.slice(0,t)+"...":e;try{const n=JSON.stringify(e);return n.length>t?n.slice(0,t)+"...":n}catch{return String(e)}}function lxs({datasetId:e,experimentId:t,featuredItemId:n,detailPanelVariant:r="inline"}){const s=Ye(),{data:a}=zy(e??""),{data:i,isLoading:l}=axs({experimentId:t}),{data:c,isLoading:u}=ixs({experimentId:t}),{updateExperimentResult:d}=wi(),[f,h]=g.useState(n??null);g.useEffect(()=>{n!==void 0&&h(n)},[n]);const[p,m]=g.useState(null),[v,y]=g.useState(new Set),[b,x]=g.useState(!1),[w,k]=g.useState(!1),[C,_]=g.useState(!1),[T,E]=g.useState(""),[N,I]=g.useState(""),[A,P]=g.useState(""),[L,D]=g.useState([]),[B,H]=g.useState(!1),[q,z]=g.useState({}),V=g.useMemo(()=>(i??[]).map(de=>de.id in q?{...de,rating:q[de.id]}:de),[i,q]),M=g.useMemo(()=>{const de=new Set;if(a?.tags)for(const ke of a.tags)de.add(ke);for(const ke of V)for(const Ne of ke.tags)de.add(Ne);return[...de].sort()},[a,V]),G=g.useCallback(de=>{!a||!e||(a.tags??[]).includes(de)},[a,e]),F=g.useMemo(()=>p?p==="__untagged__"?V.filter(de=>de.tags.length===0):V.filter(de=>de.tags.includes(p)):V,[V,p]),R=g.useMemo(()=>{const de=new Map;for(const ke of V)for(const Ne of ke.tags)de.set(Ne,(de.get(Ne)??0)+1);return[...de.entries()].sort((ke,Ne)=>Ne[1]-ke[1])},[V]),U=g.useMemo(()=>V.filter(de=>de.tags.length===0).length,[V]),Z=g.useMemo(()=>{let de=0;return p&&de++,b&&de++,de},[p,b]),Y=g.useCallback((de,ke)=>{const Ne=V.find(fe=>fe.id===de);Ne?.experimentId&&Ne?.datasetId&&d.mutate({datasetId:Ne.datasetId,experimentId:Ne.experimentId,resultId:Ne.id,tags:ke})},[V,d]),te=g.useCallback((de,ke)=>{const Ne=V.find(fe=>fe.id===de);Ne?.traceId&&ke!==void 0&&s.createFeedback({feedback:{traceId:Ne.traceId,source:"studio",feedbackSource:"studio",feedbackType:"rating",value:ke==="positive"?1:-1,reviewStatus:"reviewed",experimentId:Ne.experimentId??void 0,sourceId:Ne.id}}).catch(()=>{}),z(fe=>({...fe,[de]:ke}))},[V,s]),J=g.useCallback((de,ke)=>{const Ne=V.find(fe=>fe.id===de);Ne?.experimentId&&Ne?.datasetId&&d.mutate({datasetId:Ne.datasetId,experimentId:Ne.experimentId,resultId:Ne.id,comment:ke}),Ne?.traceId&&s.createFeedback({feedback:{traceId:Ne.traceId,source:"studio",feedbackSource:"studio",feedbackType:"comment",value:ke,comment:ke,reviewStatus:"reviewed",experimentId:Ne.experimentId??void 0,sourceId:Ne.id}}).catch(()=>{})},[V,s,d]),ee=g.useCallback(de=>{const ke=V.find(Ne=>Ne.id===de);y(Ne=>{const fe=new Set(Ne);return fe.delete(de),fe}),f===de&&h(null),ke?.experimentId&&ke?.datasetId&&d.mutate({datasetId:ke.datasetId,experimentId:ke.experimentId,resultId:ke.id,status:null})},[V,d,f]),re=g.useCallback(de=>{const ke=V.find(Ne=>Ne.id===de);y(Ne=>{const fe=new Set(Ne);return fe.delete(de),fe}),f===de&&h(null),ke?.experimentId&&ke?.datasetId&&d.mutate({datasetId:ke.datasetId,experimentId:ke.experimentId,resultId:ke.id,status:"complete"})},[V,d,f]),ae=g.useMemo(()=>{const de=b?c??[]:F;return!b||!p?de:p==="__untagged__"?de.filter(ke=>ke.tags.length===0):de.filter(ke=>ke.tags.includes(p))},[b,c,F,p]),X=b?u:!1,ne=g.useMemo(()=>new Set(ae.map(de=>de.id)),[ae]),se=g.useMemo(()=>[...v].filter(de=>ne.has(de)).length,[v,ne]),ce=ae.length>0&&se===ae.length,le=se>0&&!ce,be=g.useCallback(de=>{y(ke=>{const Ne=new Set(ke);return Ne.has(de)?Ne.delete(de):Ne.add(de),Ne})},[]),he=g.useCallback(()=>{y(ce?new Set:new Set(ae.map(de=>de.id)))},[ce,ae]),xe=g.useCallback(de=>{for(const ke of v){const Ne=V.find(fe=>fe.id===ke);Ne&&!Ne.tags.includes(de)&&Y(ke,[...Ne.tags,de])}},[V,v,Y]),Ae=g.useCallback(de=>{for(const ke of v){const Ne=V.find(fe=>fe.id===ke);Ne&&Ne.tags.includes(de)&&Y(ke,Ne.tags.filter(fe=>fe!==de))}},[V,v,Y]),De=g.useCallback(()=>{for(const de of v)re(de);y(new Set)},[v,re]),Me=g.useCallback(()=>{for(const de of v)ee(de);y(new Set)},[v,ee]),Pe=g.useCallback(()=>{E(""),_(!0)},[]),Re=g.useCallback(async()=>{if(!(!N||!A)){k(!0),_(!1);try{const de=V.filter(Ne=>v.has(Ne.id));if(de.length===0){k(!1);return}const ke=await s.clusterFailures({modelId:`${N}/${A}`,items:de.map(Ne=>({id:Ne.id,input:Ne.input,output:Ne.output??void 0,error:typeof Ne.error=="string"?Ne.error:Ne.error?String(Ne.error):void 0,scores:Ne.scores,existingTags:Ne.tags.length>0?Ne.tags:void 0})),availableTags:M.length>0?M:void 0,prompt:T||void 0});ke.proposedTags&&ke.proposedTags.length>0&&(D(ke.proposedTags.map(Ne=>({...Ne,accepted:!0}))),H(!0))}catch(de){console.error("Analysis failed:",de)}finally{k(!1)}}},[N,A,V,v,s,M,T]),Le=g.useCallback(()=>{for(const de of L){if(!de.accepted)continue;const ke=V.find(Ne=>Ne.id===de.itemId);if(ke){const Ne=[...new Set([...ke.tags,...de.tags])];Y(ke.id,Ne)}}H(!1)},[L,V,Y]),Ee=g.useCallback(de=>{h(ke=>ke===de?null:de)},[]),Te=g.useMemo(()=>f?ae.find(de=>de.id===f)??null:null,[f,ae]),ze=f?ae.findIndex(de=>de.id===f):-1,Ce=ze>0?()=>h(ae[ze-1].id):void 0,Fe=ze>=0&&ze<ae.length-1?()=>h(ae[ze+1].id):void 0,tt="auto minmax(0,20rem) minmax(0,1fr) minmax(0,8rem) 6rem 6rem",{containerRef:Ge,getRowProps:ge}=ao({count:ae.length});if(l)return o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(Vt,{className:"h-6 w-6"})});const Se=Te?o.jsx(hqt,{className:"h-full",item:Te,isCompleted:b,tagVocabulary:M,onRate:de=>te(Te.id,de),onSetTags:de=>{Y(Te.id,de);for(const ke of de)M.includes(ke)||G(ke)},onComment:de=>J(Te.id,de),onRemove:()=>ee(Te.id),onComplete:b?void 0:()=>re(Te.id),onPrevious:Ce,onNext:Fe,onClose:()=>h(null)}):null;return o.jsxs("div",{className:K("flex h-full min-h-0 flex-1",r==="overlay"?"overflow-visible":"overflow-hidden"),children:[o.jsx(pr,{open:C,onOpenChange:_,children:o.jsxs(mr,{children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Analyze Items"}),o.jsx(Cs,{children:"Use an LLM to automatically suggest tags for the selected items."})]}),o.jsxs("div",{className:"space-y-4 py-2",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx(Dt,{className:"mb-1 block text-xs",children:"Provider"}),o.jsx(Yy,{value:N,onValueChange:I})]}),o.jsxs("div",{children:[o.jsx(Dt,{className:"mb-1 block text-xs",children:"Model"}),o.jsx(Ky,{llmId:N,value:A,onValueChange:P})]})]}),o.jsxs(ve,{variant:"ui-xs",className:"text-neutral3",children:[v.size," item",v.size!==1?"s":""," will be analyzed"]}),o.jsxs("div",{children:[o.jsx(Dt,{className:"text-xs",children:"Instructions (optional)"}),o.jsx(zo,{value:T,onChange:de=>E(de.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3,className:"mt-1 text-xs"})]})]}),o.jsxs(Bl,{children:[o.jsx(ie,{variant:"outline",onClick:()=>_(!1),children:"Cancel"}),o.jsxs(ie,{onClick:Re,disabled:!N||!A||w,children:[w?o.jsx(Vt,{className:"mr-1 h-4 w-4"}):null,"Analyze"]})]})]})}),o.jsx(pr,{open:B,onOpenChange:H,children:o.jsxs(mr,{className:"max-h-[80vh] max-w-2xl overflow-y-auto",children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Review Proposed Tags"}),o.jsxs(Cs,{children:[L.filter(de=>de.accepted).length," of ",L.length," proposals selected"]})]}),o.jsx("div",{className:"space-y-3 py-2",children:L.map((de,ke)=>{const Ne=V.find(fe=>fe.id===de.itemId);return o.jsx("div",{className:K("p-3 border rounded-lg",!de.accepted&&"opacity-50"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(Oo,{checked:de.accepted,onCheckedChange:fe=>D(ye=>ye.map((je,$e)=>$e===ke?{...je,accepted:!!fe}:je))}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(ve,{variant:"ui-xs",className:"text-neutral4 block truncate",children:Ne?typeof Ne.input=="string"?Ne.input.slice(0,100):JSON.stringify(Ne.input).slice(0,100):de.itemId}),o.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:de.tags.map((fe,ye)=>o.jsx(mqt,{tag:fe,onRename:je=>D($e=>$e.map((He,vt)=>vt===ke?{...He,tags:He.tags.map((_e,et)=>et===ye?je:_e)}:He)),onRemove:()=>D(je=>je.map(($e,He)=>He===ke?{...$e,tags:$e.tags.filter((vt,_e)=>_e!==ye)}:$e))},`${fe}-${ye}`))}),de.reason&&o.jsx(ve,{variant:"ui-xs",className:"text-neutral3 mt-1 block italic",children:de.reason})]})]})},de.itemId)})}),o.jsxs(Bl,{children:[o.jsx(ie,{variant:"outline",onClick:()=>H(!1),children:"Cancel"}),o.jsxs(ie,{onClick:Le,disabled:L.filter(de=>de.accepted).length===0,children:["Accept ",L.filter(de=>de.accepted).length," proposals"]})]})]})}),o.jsxs("div",{className:K("grid h-full min-h-0 w-full grid-cols-1 gap-4",r==="overlay"?"overflow-visible":"overflow-hidden",Te&&r==="inline"&&"grid-cols-[1fr_1fr]"),children:[o.jsxs("div",{className:"grid min-h-0 w-full grid-rows-[auto_1fr] gap-3 overflow-hidden pt-3",children:[(V.length>0||Z>0)&&o.jsxs("div",{className:"flex w-full flex-wrap items-center justify-start gap-3",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs(at,{children:[o.jsx(at.Trigger,{asChild:!0,children:o.jsxs(ie,{size:"sm",children:[o.jsx(E0e,{}),"Filter",Z>0&&o.jsx(bt,{size:"xs",children:Z})]})}),o.jsxs(at.Content,{align:"start",className:K("min-w-48"),children:[o.jsxs(at.Sub,{children:[o.jsxs(at.SubTrigger,{children:["Status",b&&o.jsx("span",{className:K("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(at.SubContent,{children:[o.jsx(at.CheckboxItem,{checked:!b,onCheckedChange:()=>{x(!1),h(null)},onSelect:de=>de.preventDefault(),children:"Review Queue"}),o.jsx(at.CheckboxItem,{checked:b,onCheckedChange:()=>{x(!0),h(null)},onSelect:de=>de.preventDefault(),children:"Completed"})]})]}),o.jsxs(at.Sub,{children:[o.jsxs(at.SubTrigger,{children:["Tags",p&&o.jsx("span",{className:K("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(at.SubContent,{children:[o.jsx(at.CheckboxItem,{checked:!p,onCheckedChange:()=>m(null),onSelect:de=>de.preventDefault(),children:"All"}),U>0&&o.jsx(at.CheckboxItem,{checked:p==="__untagged__",onCheckedChange:()=>m(p==="__untagged__"?null:"__untagged__"),onSelect:de=>de.preventDefault(),children:"Untagged"}),R.length>0&&o.jsx(at.Separator,{}),R.map(([de])=>o.jsx(at.CheckboxItem,{checked:p===de,onCheckedChange:()=>m(p===de?null:de),onSelect:ke=>ke.preventDefault(),children:de},de))]})]}),Z>0&&o.jsxs(o.Fragment,{children:[o.jsx(at.Separator,{}),o.jsxs(at.Item,{onSelect:()=>{m(null),x(!1),h(null)},children:[o.jsx(or,{}),"Clear all filters"]})]})]})]}),Z>0&&o.jsxs(ie,{size:"sm",onClick:()=>{m(null),x(!1),h(null)},children:[o.jsx(or,{}),"Reset"]})]}),!b&&v.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(pqt,{selectedCount:v.size,vocabulary:M,onApplyTag:xe,onRemoveTag:Ae,onNewTag:de=>xe(de)}),o.jsxs(at,{children:[o.jsx(at.Trigger,{asChild:!0,children:o.jsxs(ie,{size:"sm",disabled:w,children:[w?o.jsx(Vt,{className:"h-4 w-4"}):o.jsx(Qe,{size:"sm",children:o.jsx(Js,{})}),"Actions"]})}),o.jsxs(at.Content,{align:"end",children:[o.jsxs(at.Item,{onSelect:De,children:[o.jsx(Qe,{size:"sm",children:o.jsx(kO,{})}),"Complete"]}),o.jsxs(at.Item,{onSelect:Me,children:[o.jsx(Qe,{size:"sm",children:o.jsx(Fl,{})}),"Remove"]}),o.jsx(at.Separator,{}),o.jsxs(at.Item,{onSelect:Pe,children:[o.jsx(Qe,{size:"sm",children:o.jsx(Dg,{})}),"Analyze"]})]})]})]})]}),X?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(Vt,{className:"h-6 w-6"})}):ae.length===0?o.jsx("div",{className:"flex h-full items-center justify-center py-12",children:o.jsx(br,{iconSlot:o.jsx(X1,{className:"text-neutral3 h-8 w-8"}),titleSlot:b?"No completed reviews yet":"No items to review",descriptionSlot:b?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here."})}):o.jsxs(pe,{columns:tt,fit:"container",className:"min-w-0",scrollRef:Ge,children:[o.jsxs(pe.Top,{hasLeadingCell:!0,children:[b?o.jsx(pe.TopCell,{children:" "}):o.jsx(pe.TopSelectCell,{checked:ce?!0:le?"indeterminate":!1,onToggle:()=>he(),"aria-label":"Select all"}),o.jsxs(pe.TopCells,{colStart:2,children:[o.jsx(pe.TopCell,{children:"Input"}),o.jsx(pe.TopCell,{children:"Comment"}),o.jsx(pe.TopCell,{children:"Tags"}),o.jsx(pe.TopCell,{children:"Rating"}),o.jsx(pe.TopCell,{children:"Scores"})]})]}),ae.map((de,ke)=>{const Ne=de.scores?Object.entries(de.scores):[],fe=f===de.id,ye=o.jsxs(o.Fragment,{children:[o.jsx(pe.Cell,{className:"text-neutral4 min-w-0",children:o.jsx("span",{className:"block truncate",children:oxs(de.input,200)})}),o.jsx(pe.Cell,{className:"min-w-0",children:de.comment?o.jsx(ve,{variant:"ui-xs",className:"text-neutral3 truncate",children:de.comment}):o.jsx(ve,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsx(pe.Cell,{className:"min-w-0",children:de.tags.length>0?o.jsx(ve,{variant:"ui-xs",className:"text-neutral4 truncate",children:de.tags.join(", ")}):o.jsx(ve,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsxs(pe.Cell,{children:[de.rating==="positive"&&o.jsx(Qe,{size:"sm",className:"text-positive1",children:o.jsx(F0e,{})}),de.rating==="negative"&&o.jsx(Qe,{size:"sm",className:"text-negative1",children:o.jsx(L0e,{})}),!de.rating&&o.jsx(ve,{variant:"ui-xs",className:"text-neutral2",children:"—"})]}),o.jsx(pe.Cell,{children:Ne.length>0?o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Qe,{size:"sm",className:"text-neutral3",children:o.jsx(Qh,{})}),o.jsx(ve,{variant:"ui-xs",className:"text-neutral4 font-mono",children:Ne[0][1].toFixed(2)}),Ne.length>1&&o.jsxs(bt,{children:["+",Ne.length-1]})]}):o.jsx(ve,{variant:"ui-xs",className:"text-neutral2",children:"—"})})]});return o.jsxs(pe.RowWrapper,{children:[b?o.jsx(pe.Cell,{className:"justify-items-center px-4",children:o.jsx("div",{role:"img","aria-label":de.error?"Error":"Success",title:de.error?"Error":"Success",className:K("w-2 h-2 rounded-full",de.error?"bg-red-700":"bg-green-600")})}):o.jsx(pe.SelectCell,{checked:v.has(de.id),onToggle:()=>be(de.id),"aria-label":`Select item ${de.id}`}),o.jsx(pe.RowButton,{colStart:2,featured:fe,onClick:()=>Ee(de.id),...ge(ke),children:ye})]},de.id)})]})]}),Se&&(r==="overlay"?o.jsx(uY,{label:`Review item ${Te?.id??""}`,children:Se}):Se)]})]})}const Ftt={needsReview:"#facc15",complete:"#22c55e"},cxs=[{label:"Needs Review",color:Ftt.needsReview},{label:"Reviewed",color:Ftt.complete}];function uxs({reviewSummary:e,experiments:t,datasets:n,isLoading:r,isError:s}){const{data:a,maxVal:i,totalInPipeline:l}=g.useMemo(()=>{if(!e?.counts||!t)return{data:[],maxVal:0,totalInPipeline:0};const u=new Map;for(const m of t)u.set(m.id,m);const d=new Map;if(n)for(const m of n)d.set(m.id,m.name);let f=0,h=0;const p=[];for(const m of e.counts){const v=m.needsReview+m.complete;if(v===0)continue;h+=v,v>f&&(f=v);const y=u.get(m.experimentId),b=y?.datasetId?d.get(y.datasetId):void 0,x=b?`${b} · ${m.experimentId.slice(0,8)}`:m.experimentId.slice(0,8);p.push({name:x,values:[m.needsReview,m.complete]})}return{data:p,maxVal:f,totalInPipeline:h}},[e,t,n]),c=a.length>0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Review Pipeline",description:"Items in review across experiments."}),c&&o.jsx(Ht.Summary,{value:String(l),label:"Items in pipeline"})]}),r?o.jsx(Ht.Loading,{}):s?o.jsx(Ht.Error,{message:"Failed to load review data"}):o.jsx(Ht.Content,{children:c?o.jsx(KN,{data:a,segments:cxs,maxVal:i,fmt:u=>String(u)}):o.jsx(Ht.NoData,{message:"No items have been sent to review yet"})})]})}function LHt(){const e=Ye();return mt({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function dxs(e){const t=new Map;if(!e?.counts)return t;for(const n of e.counts)t.set(n.experimentId,{needsReview:n.needsReview,complete:n.complete,total:n.total});return t}function fxs(e){return e?.counts?e.counts.reduce((t,n)=>({needsReview:t.needsReview+n.needsReview,complete:t.complete+n.complete,inPipeline:t.inPipeline+n.needsReview+n.complete}),{needsReview:0,complete:0,inPipeline:0}):{needsReview:0,complete:0,inPipeline:0}}function hxs(){const[e,t]=g.useState("all"),[n,r]=g.useState({}),{data:s,isLoading:a,error:i}=up(),{data:l,isLoading:c,error:u}=Xg(),{data:d,isLoading:f,error:h}=BH(),{data:p,isLoading:m,isError:v,error:y}=eHr(n),{data:b,isLoading:x,isError:w,error:k}=LHt(),C=l?.datasets,_=d?.experiments,T=g.useMemo(()=>fxs(b),[b]),E=i||u||h||y||k;return E&&hs(E)?o.jsx(Zn,{children:o.jsx(Ts,{})}):E&&ps(E)?o.jsx(Zn,{children:o.jsx(ks,{resource:"evaluation"})}):E?o.jsx(Zn,{children:o.jsx(La,{title:"Failed to load evaluation data",message:E.message})}):o.jsxs(Lt,{width:"wide",height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(Lt.Row,{children:o.jsx(Lt.Column,{children:o.jsx(q4,{preset:e,onPresetChange:t,dateFrom:n.start,dateTo:n.end,onDateChange:(N,I)=>r(A=>I==="from"?{...A,start:N}:{...A,end:N})})})})}),o.jsxs("div",{className:"flex flex-col gap-6",children:[o.jsx(o0e,{children:o.jsx(Rbs,{scorers:s,datasets:C,experiments:_,avgScore:p?.avgScore??null,prevAvgScore:p?.prevAvgScore??null,totalNeedsReview:T.needsReview,isLoadingScorers:a,isLoadingDatasets:c,isLoadingExperiments:f,isLoadingScores:m,isLoadingReview:x})}),o.jsx(fVr,{summaryData:p?.summaryData??[],overTimeData:p?.overTimeData??[],scorerNames:p?.scorerNames??[],avgScore:p?.avgScore??null,isLoading:m,isError:v}),o.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:[o.jsx(Rvs,{experiments:_,isLoading:f,isError:!!h}),o.jsx(Zbs,{experiments:_,datasets:C,isLoading:f,isError:!!h})]}),o.jsx(uxs,{reviewSummary:b,experiments:_,datasets:C,isLoading:x,isError:!!w})]})]})}function pxs(){const[e,t]=g.useState(""),[n,r]=g.useState("all"),[s,a]=g.useState(!1),[i,l]=g.useState(!1),[c,u]=g.useState([]),d=qr(),[f,h]=za(),p=f.get("dataset")??"all",m=g.useCallback(G=>{h(F=>{const R=new URLSearchParams(F);return G==="all"?R.delete("dataset"):R.set("dataset",G),R},{replace:!0})},[h]),{data:v,isLoading:y,error:b}=Xg(),{data:x,isLoading:w,error:k}=fY(p==="all"?void 0:p),{data:C}=LHt(),_=g.useMemo(()=>v?.datasets??[],[v?.datasets]),T=g.useMemo(()=>x?.experiments??[],[x?.experiments]),E=g.useMemo(()=>Hbs(_),[_]),N=g.useMemo(()=>dxs(C),[C]),I=y||w,A=k||b,P=G=>{u(F=>F.includes(G)?F.filter(R=>R!==G):F.length>=2?[F[0],G]:[...F,G])},L=()=>{u([]),l(!1)},{selectedIds:D,selectedDatasetIds:B}=g.useMemo(()=>{const G=new Map(T.map(R=>[R.id,R.datasetId])),F=c.filter(R=>G.has(R));return{selectedIds:F,selectedDatasetIds:new Set(F.map(R=>G.get(R)))}},[T,c]),H=D.length===2&&B.size!==1?"experiments must belong to the same dataset":void 0,q=()=>{if(D.length!==2||H)return;const[G,F]=D,[R]=B;if(!R)return;const U=new URLSearchParams({dataset:R,baseline:G,contender:F});d(`/experiments/compare?${U.toString()}`)};if(A&&hs(A))return o.jsx(Zn,{children:o.jsx(Ts,{})});if(k&&ps(k))return o.jsx(Zn,{children:o.jsx(ks,{resource:"experiments"})});if(b&&ps(b))return o.jsx(Zn,{children:o.jsx(ks,{resource:"datasets"})});if(A)return o.jsx(Zn,{children:o.jsx(La,{title:"Failed to load experiments",message:A.message})});const z=o.jsx(cY,{open:s,onOpenChange:a,onSuccess:G=>{d(`/experiments/${G}`)}});if(T.length===0&&!I&&p==="all")return o.jsxs(Zn,{children:[o.jsx(Gbs,{onRunExperiment:()=>a(!0)}),z]});const V=n!=="all"||p!=="all"||e!=="",M=()=>{t(""),r("all"),m("all")};return o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(Qbs,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:p,onDatasetFilterChange:m,datasetOptions:E,onReset:M,hasActiveFilters:V,onRunClick:()=>a(!0),onCompareClick:()=>l(!0),selection:i?{selectedCount:D.length,onExecuteCompare:q,onCancelSelection:L,compareDisabledReason:H}:void 0})}),o.jsx(qbs,{experiments:T,datasets:_,reviewByExperiment:N,isLoading:I,search:e,statusFilter:n,datasetFilter:p,selection:i?{selectedExperimentIds:D,onToggleSelection:P}:void 0}),z]})}function a8({experimentId:e}){const{Link:t,paths:n}=dn();return o.jsx(ie,{as:t,href:n.experimentLink(e),size:"sm","aria-label":`Open experiment ${e}`,children:e.slice(0,8)})}function mxs(){const[e,t]=za(),n=e.get("dataset")??"",r=e.get("baseline")??"",s=e.get("contender")??"",a=VD(n,r),i=VD(n,s),l=a.isLoading||i.isLoading,c=a.error??i.error;return c&&hs(c)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{})})}):c&&ps(c)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ks,{resource:"experiments"})})}):!n||!r||!s?o.jsx(vs,{children:o.jsx(by,{children:o.jsxs("div",{className:"text-neutral4 py-8 text-center",children:[o.jsx("p",{children:"Select two experiments to compare."}),o.jsxs("p",{className:"mt-2 text-sm",children:["Use the URL format: /experiments/compare?dataset=","{datasetId}","&baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})}):l?null:c&&!JEe(c)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(La,{title:"Failed to load experiments",message:c.message})})}):c||!a.data||!i.data?o.jsx(vs,{children:o.jsx(by,{children:o.jsxs("div",{className:"text-neutral4 py-8 text-center",children:[o.jsxs("p",{children:["Experiments must belong to the same dataset (",n,") to be compared."]}),o.jsxs("p",{className:"mt-2 flex items-center justify-center gap-2 text-sm",children:["One of",o.jsx(a8,{experimentId:r}),"and",o.jsx(a8,{experimentId:s}),"was not found in it."]})]})})}):o.jsx(vs,{children:o.jsx(by,{children:o.jsxs("div",{className:"grid w-full content-start",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4 px-6 py-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[o.jsx(ve,{as:"h1",variant:"ui-lg",className:"text-neutral6 font-medium",children:"Experiments comparison"}),o.jsxs("p",{className:"text-ui-sm text-neutral4 flex items-center gap-2",children:[o.jsx(a8,{experimentId:r}),"and",o.jsx(a8,{experimentId:s})]})]}),o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsxs(ie,{onClick:()=>t({dataset:n,baseline:s,contender:r}),children:[o.jsx(Sct,{}),"Swap sides"]})}),o.jsx(yn,{children:"Switch baseline and contender"})]})]}),o.jsx(rxs,{datasetId:n,experimentIdA:r,experimentIdB:s})]})})})}const FHt=e=>o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 8.64637 9.45103",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:o.jsx("path",{d:"M7.80735 5.87241C7.63209 5.97219 7.43696 6.06166 7.22844 6.13866C6.46456 6.42068 5.43714 6.58649 4.32296 6.58649C3.20873 6.58649 2.18135 6.4207 1.41747 6.13866C1.20889 6.06164 1.01385 5.97223 0.838558 5.87241V7.59003C0.838558 7.62341 0.855765 7.70759 1.00172 7.83512C1.14707 7.96201 1.38219 8.09563 1.70829 8.21605C2.3572 8.45563 3.28149 8.61268 4.32296 8.61269C5.36456 8.61269 6.28937 8.45568 6.9383 8.21605C7.26428 8.09566 7.49888 7.96198 7.64419 7.83512C7.79024 7.70754 7.80735 7.62342 7.80735 7.59003V5.87241ZM7.80735 3.00789C7.63214 3.10763 7.4369 3.19647 7.22844 3.27345C6.46455 3.55549 5.43719 3.72129 4.32296 3.72129C3.20868 3.72128 2.18136 3.55552 1.41747 3.27345C1.20896 3.19645 1.01381 3.10766 0.838558 3.00789V4.72551C0.838558 4.7589 0.855657 4.84301 1.00172 4.97059C1.14707 5.09749 1.38219 5.23111 1.70829 5.35153C2.3572 5.59109 3.28154 5.74747 4.32296 5.74748C5.36456 5.74748 6.28937 5.59116 6.9383 5.35153C7.26432 5.23112 7.49887 5.09747 7.64419 4.97059C7.7536 4.87505 7.79089 4.80404 7.80257 4.76033L7.80735 4.72551V3.00789ZM7.80735 1.86099C7.80735 1.82758 7.79045 1.74291 7.64419 1.61522C7.49887 1.48838 7.26421 1.35534 6.9383 1.23497C6.28937 0.995339 5.36456 0.838331 4.32296 0.838331C3.28149 0.83834 2.3572 0.995383 1.70829 1.23497C1.38219 1.35539 1.14707 1.48832 1.00172 1.61522C0.855475 1.7429 0.838558 1.82758 0.838558 1.86099C0.838673 1.89462 0.855968 1.97882 1.00172 2.10607C1.14707 2.23297 1.38219 2.3659 1.70829 2.48632C2.3572 2.7259 3.28149 2.88295 4.32296 2.88296C5.36456 2.88296 6.28937 2.72595 6.9383 2.48632C7.26421 2.36595 7.49887 2.23291 7.64419 2.10607C7.78996 1.97881 7.80724 1.89462 7.80735 1.86099ZM8.64637 7.59003C8.64637 7.95465 8.44458 8.25006 8.1958 8.46728C7.94608 8.68529 7.60876 8.86274 7.22844 9.00318C6.46455 9.28522 5.43718 9.45102 4.32296 9.45102C3.20869 9.45101 2.18135 9.28525 1.41747 9.00318C1.03715 8.86274 0.699831 8.68529 0.450113 8.46728C0.201377 8.25007 0.000227451 7.9546 0.000227451 7.59003V1.86099C0.000227451 1.49643 0.201388 1.20095 0.450113 0.983742C0.699831 0.765728 1.03715 0.588275 1.41747 0.447838C2.18136 0.165769 3.20868 8.74396e-06 4.32296 0C5.43719 0 6.46455 0.165797 7.22844 0.447838C7.60876 0.588275 7.94608 0.765728 8.1958 0.983742C8.44457 1.20096 8.64637 1.49638 8.64637 1.86099V7.59003Z",fill:"currentColor"})});function zHt(e){const{data:t}=jC(e.id,e.status);return g.useMemo(()=>{if(e.scorerIds?.length)return e.scorerIds;if(!t)return[];const n=new Set;for(const r of Object.values(t))for(const s of r)n.add(s.scorerId);return[...n].sort()},[e.scorerIds,t])}function noe({icon:e,typeLabel:t,children:n}){return o.jsxs("div",{className:"text-ui-sm text-neutral5 flex flex-none items-center gap-1.5 [&_svg]:size-3.5 [&_svg]:shrink-0",children:[o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx("span",{className:"text-neutral3 flex",role:"img","aria-label":t}),children:e}),o.jsx(yn,{children:t})]}),n]})}function roe({label:e}){return o.jsxs("div",{className:"text-neutral2 text-ui-xs flex flex-none items-center gap-1.5",children:[o.jsx("span",{className:"whitespace-nowrap",children:e}),o.jsx(Fd,{className:"size-3.5 shrink-0","aria-hidden":!0})]})}const ztt="text-neutral5 inline-flex items-center gap-1.5 hover:underline";function gxs({experiment:e,className:t}){const{Link:n,paths:r}=dn(),s=IHt(),{scorers:a}=s,{data:i,isLoading:l}=zy(e.datasetId??""),c=zHt(e),u=c.map(b=>a?.[b]?.scorer?.config?.name??b),d=e.targetType,f=e.targetId,h=()=>PHt(e,s),p=()=>{if(!f)return null;switch(d){case"agent":return r.agentLink(f);case"workflow":return r.workflowLink(f);case"scorer":return r.scorerLink(f);default:return null}},m=d&&AHt[d]||Ri,v=d&&RHt[d]||"Evaluation target",y=p();return o.jsxs("div",{className:K("flex items-center gap-3 overflow-x-auto",t),children:[o.jsx(noe,{icon:o.jsx(FHt,{}),typeLabel:"Dataset",children:e.datasetId?o.jsxs(n,{href:r.datasetLink(e.datasetId),className:ztt,children:[l?o.jsx(Et,{className:"h-4 w-28"}):i?.name??e.datasetId,e.datasetVersion!=null&&o.jsxs("span",{className:"text-neutral3",children:["(v",e.datasetVersion,")"]})]}):o.jsx("span",{className:"text-neutral3",children:"No dataset"})}),o.jsx(roe,{label:"each item"}),o.jsx(noe,{icon:o.jsx(m,{}),typeLabel:v,children:y?o.jsx(n,{href:y,className:ztt,children:h()}):o.jsx("span",{className:"text-neutral3",children:h()})}),o.jsx(roe,{label:"output"}),o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx("div",{tabIndex:0,className:"flex outline-offset-4",children:o.jsx(noe,{icon:o.jsx(P_,{}),typeLabel:"Scorers",children:c.length===0?"Scorers":`${c.length} scorer${c.length===1?"":"s"}`})})}),o.jsx(yn,{children:u.length>0?u.join(", "):"No scorer has produced a score yet"})]}),o.jsx(roe,{label:"comparing ground truth"}),o.jsx("div",{className:"text-ui-sm text-neutral5 flex-none whitespace-nowrap",children:"Score"})]})}function i8({label:e,children:t}){return o.jsxs("div",{className:"min-w-0 flex-1 px-6 py-3",children:[o.jsx("div",{className:"text-ui-sm text-neutral2 tracking-widest uppercase",children:e}),o.jsx("div",{className:"text-ui-md text-neutral5 mt-1 flex flex-wrap items-baseline gap-x-1.5",children:t})]})}function vxs(e){if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(1).replace(/\.0$/,"")}s`;const t=Math.floor(e/6e4),n=Math.round(e%6e4/1e3);if(t<60)return n>0?`${t}m ${n}s`:`${t}m`;const r=Math.floor(t/60),s=t%60;return s>0?`${r}h ${s}m`:`${r}h`}function yxs({experiment:e,className:t}){const{data:n}=jC(e.id,e.status),r=g.useMemo(()=>{if(!n)return;const l=Object.values(n).flat();if(l.length!==0)return l.reduce((c,u)=>c+u.score,0)/l.length},[n]),s=e.startedAt??e.createdAt,a=s?new Date(s):null,i=(()=>{if(e.status==="running")return"Running…";if(!e.startedAt||!e.completedAt)return"—";const l=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return l<0?"—":vxs(l)})();return o.jsxs("div",{className:K("flex w-full items-stretch divide-x divide-border1 border-y border-border1",t),children:[o.jsx(i8,{label:"Avg score",children:r===void 0?o.jsx("span",{className:"text-neutral3",children:"—"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{children:r.toFixed(3)}),(e.status==="running"||e.status==="pending")&&o.jsx("span",{className:"text-neutral3",children:"· so far"})]})}),o.jsx(i8,{label:"Items",children:e.status==="running"||e.status==="pending"?o.jsxs("span",{className:"text-neutral3",children:[(e.succeededCount??0)+(e.failedCount??0),"/",e.totalItems," items processed"]}):o.jsxs(o.Fragment,{children:[o.jsxs("span",{children:[e.totalItems," item",e.totalItems===1?"":"s"]}),(e.failedCount??0)>0&&o.jsxs("span",{className:"text-error",children:["· ",e.failedCount," errored"]})]})}),o.jsx(i8,{label:"Started",children:a?o.jsxs(o.Fragment,{children:[o.jsx("span",{children:dr(a,"MMM d, h:mm a")}),o.jsxs("span",{className:"text-neutral3",children:["· ",jMn(a,{addSuffix:!0})]})]}):o.jsx("span",{children:"—"})}),o.jsx(i8,{label:"Duration",children:o.jsx("span",{children:i})})]})}function bxs({experiment:e,open:t,onOpenChange:n}){const[r,s]=g.useState(e.name??""),[a,i]=g.useState(e.description??""),{updateExperiment:l}=wi(),c=!!r.trim()&&!l.isPending,u=async d=>{if(d.preventDefault(),!(!c||!e.datasetId))try{await l.mutateAsync({datasetId:e.datasetId,experimentId:e.id,name:r.trim(),description:a.trim()}),Ve.success("Experiment renamed"),n(!1)}catch(f){Ve.error(`Failed to rename experiment: ${f instanceof Error?f.message:"Unknown error"}`)}};return o.jsx(pr,{open:t,onOpenChange:n,children:o.jsxs(mr,{className:"max-w-md",children:[o.jsx(gr,{children:o.jsx(ur,{children:"Rename Experiment"})}),o.jsx(jr,{children:o.jsxs("form",{onSubmit:u,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"rename-experiment-name",children:"Name *"}),o.jsx(jn,{id:"rename-experiment-name",value:r,onChange:d=>s(d.target.value),placeholder:"Enter experiment name",autoFocus:!0})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"rename-experiment-description",children:"Description"}),o.jsx(jn,{id:"rename-experiment-description",value:a,onChange:d=>i(d.target.value),placeholder:"Enter experiment description (optional)"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ie,{type:"button",onClick:()=>n(!1),disabled:l.isPending,children:"Cancel"}),o.jsx(ie,{type:"submit",variant:"primary",disabled:!c,children:l.isPending?"Saving...":"Save"})]})]})})]})})}function xxs({experiment:e}){const[t,n]=g.useState(!1);return e.datasetId?o.jsxs(o.Fragment,{children:[o.jsx(ie,{onClick:()=>n(!0),tooltip:"Rename this experiment",variant:"ghost",size:"icon-sm",children:o.jsx(Yh,{})}),t&&o.jsx(bxs,{experiment:e,open:!0,onOpenChange:n})]}):null}const wxs=["agent","workflow","scorer"];function Sxs({experiment:e}){const[t,n]=g.useState(!1),r=qr(),{paths:s}=dn(),a=zHt(e),i=wxs.find(l=>l===e.targetType);return!e.datasetId||!i||!e.targetId?null:o.jsxs(o.Fragment,{children:[o.jsxs(ie,{variant:"primary",onClick:()=>n(!0),tooltip:"Run this experiment again with the same configuration",children:[o.jsx(Dc,{}),"Rerun"]}),t&&o.jsx(cY,{open:!0,onOpenChange:n,initialDatasetId:e.datasetId,initialDatasetVersion:e.datasetVersion??void 0,initialTargetType:i,initialTargetId:e.targetId,initialScorerIds:a,initialName:e.name??void 0,initialDescription:e.description??void 0,onSuccess:l=>{r(s.experimentLink(l))}},a.join(","))]})}function kxs({experiment:e}){const{Link:t,paths:n}=dn(),r=e.agentVersion&&e.targetType==="agent"&&e.targetId?`${n.agentLink(e.targetId)}/editor?version=${encodeURIComponent(e.agentVersion)}`:null;return o.jsxs(Lt.TopArea,{children:[o.jsxs(Lt.Row,{children:[o.jsx(Lt.Column,{className:"justify-items-start gap-3",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx(Uys,{status:e.status,className:"h-7"}),o.jsxs(Dl,{children:[o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Dl.Title,{children:e.name||`Experiment #${e.id.slice(0,8)}`}),o.jsx(xxs,{experiment:e})]}),e.description&&o.jsx(Dl.Description,{children:e.description}),o.jsx(gxs,{experiment:e,className:"mt-2"})]})]})}),o.jsxs(Lt.Column,{className:"justify-items-end gap-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(ie,{as:t,to:STe(e.id),children:[o.jsx(X1,{}),"View items to review"]}),o.jsx(Sxs,{experiment:e})]}),e.agentVersion&&o.jsxs(En,{numOfCol:1,children:[o.jsx(En.Key,{children:"Version"}),r?o.jsx(En.ValueLink,{href:r,as:t,children:e.agentVersion}):o.jsx(En.Value,{children:e.agentVersion})]})]})]}),o.jsx(yxs,{experiment:e,className:"-mx-6 w-auto"})]})}function o8({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function Oxs(){const{experimentId:e}=fr(),{data:t,isLoading:n}=BH(),s=t?.experiments?.find(p=>p.id===e)?.datasetId??"",{data:a,isLoading:i,error:l}=VD(s,e??""),{data:c,isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:h}=HD({datasetId:s,experimentId:e??"",experimentStatus:a?.status});return!e||n||i?null:l&&hs(l)?o.jsx(o8,{children:o.jsx(Ts,{})}):l&&ps(l)?o.jsx(o8,{children:o.jsx(ks,{resource:"datasets"})}):l&&JEe(l)||!n&&!s||!i&&!l&&!a?o.jsx(o8,{children:o.jsx(br,{iconSlot:o.jsx(O0e,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:o.jsxs(ie,{as:Da,to:"/experiments",children:[o.jsx(bl,{}),"Back to Experiments"]})})}):l?o.jsx(o8,{children:o.jsx(La,{title:"Failed to load experiment",message:l instanceof Error?l.message:"An unexpected error occurred. Please try again."})}):o.jsx(Mys,{experimentId:e,datasetId:s,experimentStatus:a.status,results:c??[],isLoadingResults:u,hasNextPage:h,children:o.jsxs("div",{className:"relative h-full overflow-hidden",children:[o.jsxs(Lt,{height:"full",children:[o.jsx(kxs,{experiment:a}),o.jsx(Lt.MainArea,{className:"overflow-visible",children:o.jsx(Bys,{experimentId:e,datasetId:s,experimentStatus:a.status,results:c??[],isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:h})})]}),o.jsx(Bg,{})]})})}function soe(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function Cxs({report:e}){const{served:t,unconsumed:n,liveCalls:r,failure:s}=e,a=[...t.map(i=>({outcome:"served",toolName:i.toolName,args:i.args})),...r.map(i=>({outcome:"live",toolName:i.toolName,args:i.args})),...n.map(i=>({outcome:"unconsumed",toolName:i.toolName,args:i.args}))];return o.jsxs("div",{className:"grid gap-2","data-testid":"tool-mock-report",children:[o.jsx(Gt.SectionHeading,{icon:o.jsx(Ud,{}),className:"mb-2",children:"Tool Mocks"}),s&&o.jsx(Rn,{variant:"destructive",title:"Mock mismatch",children:o.jsxs(Rn.Message,{children:[o.jsx("span",{className:"block",children:`Tool "${s.toolName}" was called with arguments that did not match an available mock (${s.code}).`}),o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Called with: ",soe(s.args)]}),n.length>0&&o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Unconsumed mocks: ",n.map(i=>soe(i.args)).join(", ")]})]})}),o.jsx("div",{className:"border-border1 divide-border1 divide-y rounded border text-sm",children:a.map((i,l)=>o.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-1.5",children:[o.jsxs("span",{className:"min-w-0 truncate",children:[o.jsx("span",{className:"text-neutral4 font-mono",children:i.toolName}),o.jsx("span",{className:"text-neutral3 ml-2 font-mono text-xs",children:soe(i.args)})]}),o.jsx("span",{className:`shrink-0 rounded px-2 py-0.5 text-xs ${_xs(i.outcome)}`,children:i.outcome})]},`${i.outcome}-${i.toolName}-${l}`))})]})}function _xs(e){switch(e){case"served":return"bg-accent1/10 text-accent1";case"live":return"bg-orange-500/10 text-orange-400";case"unconsumed":return"bg-neutral3/10 text-neutral4"}}function Exs({result:e,scores:t,onPrevious:n,onNext:r,onClose:s,onShowTrace:a,onOpenInReview:i,onScoreClick:l,featuredScoreId:c,onFlagForReview:u,collapsed:d=!1,scorePanelSlot:f}){const h=!!e?.error,p=l8(e?.input),m=l8(e?.output),v=l8(e?.groundTruth),y=u&&e.status!=="needs-review"&&e.status!=="complete",b=Array.isArray(e.tags)?e.tags:[];return o.jsxs(Gt,{collapsed:d,children:[o.jsxs(Gt.Header,{children:[o.jsxs(Gt.Heading,{children:["Result ",o.jsxs("b",{children:["# ",e.id.length>12?`${e.id.slice(0,12)}…`:e.id]})]}),o.jsxs(es,{className:"ml-auto shrink-0",children:[o.jsx(Gt.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Previous result",nextLabel:"Next result"}),e.traceId&&o.jsxs(ie,{size:"md",onClick:a,children:[o.jsx(sY,{}),"Trace"]}),y&&o.jsxs(ie,{size:"md",variant:"primary",onClick:()=>u(e.id),children:[o.jsx(X1,{}),"Flag for Review"]}),e.status==="needs-review"&&i&&o.jsxs(ie,{size:"md",variant:"primary",onClick:i,children:[o.jsx(ta,{}),"Review"]}),o.jsx(Gt.CloseButton,{onClick:s,tooltip:"Close result panel"})]})]}),!d&&o.jsx(Txs,{scorePanelSlot:f,children:o.jsxs(Gt.Content,{children:[o.jsxs("div",{className:"mb-6 grid gap-4",children:[o.jsxs(En,{children:[o.jsx(En.Key,{children:"Item Id"}),o.jsx(En.ValueWithCopyBtn,{copyTooltip:"Copy Item Id to clipboard",copyValue:e.itemId,children:e.itemId}),o.jsx(En.Key,{children:"Created"}),o.jsx(En.Value,{children:dr(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")})]}),h&&o.jsx(Rn,{variant:"destructive",title:"Error",children:o.jsx(Rn.Message,{children:l8(e?.error&&typeof e.error=="object"?e.error.message:e?.error)})}),t&&t.length>0&&o.jsxs(pe,{columns:"1fr 1fr",children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{children:"Scorer"}),o.jsx(pe.TopCell,{children:"Score"})]}),t.map(x=>o.jsxs(pe.RowButton,{featured:c===x.id,onClick:()=>l?.(x.id),children:[o.jsx(pe.Cell,{children:x.scorerId}),o.jsx(pe.TextCell,{font:"mono",children:x.score.toFixed(3)})]},x.id))]}),e.toolMockReport&&o.jsx(Cxs,{report:e.toolMockReport}),(e.status||b.length>0)&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Gt.SectionHeading,{icon:o.jsx(dI,{}),className:"mb-2",children:"Review"}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.status&&o.jsx("span",{className:`rounded-full px-2 py-0.5 text-xs font-medium ${e.status==="needs-review"?"bg-orange-500/10 text-orange-400":e.status==="complete"?"bg-accent1/10 text-accent1":"bg-neutral3/10 text-neutral4"}`,children:e.status}),b.map(x=>o.jsx("span",{className:"bg-surface4 text-neutral4 rounded px-2 py-0.5 text-xs",children:x},x))]})]})]}),o.jsxs("div",{className:"grid gap-3",children:[o.jsx(Gt.CodeSection,{title:"Input",icon:o.jsx(NV,{}),codeStr:p}),o.jsx(Gt.CodeSection,{title:"Output",icon:o.jsx(nm,{}),codeStr:m}),o.jsx(Gt.CodeSection,{title:"Ground Truth",icon:o.jsx(Kct,{}),codeStr:v})]})]})})]})}function Txs({scorePanelSlot:e,children:t}){return e?o.jsxs("div",{className:"grid min-h-0 flex-1 grid-cols-[1fr_1fr]",children:[o.jsx("div",{className:"flex min-h-0 flex-col overflow-hidden",children:t}),o.jsx("div",{className:"animate-in border-border1 fade-in-0 flex min-h-0 flex-col overflow-hidden border-l duration-300",children:e})]}):o.jsx(o.Fragment,{children:t})}function l8(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function jxs(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function Nxs({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s,collapsed:a,onCollapsedChange:i,className:l}){const[c,u]=g.useState(!1),d=a??c,f=i??u,h=jxs(e),p=h?"N/A — code-based scorer":"N/A — step not configured";return o.jsxs(Gt,{collapsed:d,className:l,children:[o.jsxs(Gt.Header,{children:[o.jsxs(Gt.Heading,{children:["Score ",o.jsx("b",{children:e.scorerId})]}),o.jsxs(es,{className:"ml-auto shrink-0",children:[i&&o.jsx(ie,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(aI,{}):o.jsx(_V,{})}),(n||t)&&o.jsx(Gt.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:"Previous score",nextLabel:"Next score"}),s&&e.traceId&&o.jsxs(ie,{size:"md",onClick:s,children:[o.jsx(sY,{}),"Trace"]}),o.jsx(Gt.CloseButton,{onClick:r,tooltip:"Close score panel"})]})]}),!d&&o.jsx(Gt.Content,{children:o.jsxs("div",{className:"grid gap-3",children:[o.jsx(Gt.CodeSection,{title:`Score: ${e.score}`,icon:o.jsx(Qh,{}),codeStr:e.reason||p,simplified:!0}),!h&&o.jsxs(o.Fragment,{children:[o.jsx(Gt.CodeSection,{title:"Preprocess Prompt",icon:o.jsx($p,{}),codeStr:e.preprocessPrompt||p,simplified:!0}),o.jsx(Gt.CodeSection,{title:"Analyze Prompt",icon:o.jsx($p,{}),codeStr:e.analyzePrompt||p,simplified:!0}),o.jsx(Gt.CodeSection,{title:"Generate Score Prompt",icon:o.jsx($p,{}),codeStr:e.generateScorePrompt||p,simplified:!0}),o.jsx(Gt.CodeSection,{title:"Generate Reason Prompt",icon:o.jsx($p,{}),codeStr:e.generateReasonPrompt||p,simplified:!0})]})]})})]})}function Ixs(){const{itemId:e}=fr();return e?o.jsx(Axs,{itemId:e},e):null}function Axs({itemId:e}){const{experimentId:t,datasetId:n,experimentStatus:r,results:s,isLoadingResults:a,hasNextPage:i,close:l,openInReview:c,goToPreviousItem:u,goToNextItem:d}=EHt(),f=g.useMemo(()=>s.find(R=>R.itemId===e)??null,[s,e]),{data:h}=jC(t,r),{updateExperimentResult:p}=wi(),m=g.useCallback(async R=>{try{await p.mutateAsync({datasetId:n,experimentId:t,resultId:R,status:"needs-review"}),Ve("Result flagged for review")}catch{Ve.error("Failed to flag result for review")}},[n,t,p]),v=f?h?.[f.itemId]:void 0,[y,b]=g.useState(null),[x,w]=g.useState(void 0),[k,C]=g.useState(null),[_,T]=g.useState(!1),[E,N]=g.useState(!1),I=v?.find(R=>R.id===k)??null,A=g.useCallback(R=>{C(U=>R===U?null:R),b(null),w(void 0)},[]),P=()=>{if(!k||!v)return;const R=v.findIndex(U=>U.id===k);if(R>=0&&R<v.length-1)return()=>C(v[R+1].id)},L=()=>{if(!k||!v)return;const R=v.findIndex(U=>U.id===k);if(R>0)return()=>C(v[R-1].id)},{data:D,isLoading:B}=qys(y),H=D?.spans,q=H?.find(R=>!R.parentSpanId),z=q?.entityType==="agent"?"Agent":q?.entityType==="workflow_run"?"Workflow":void 0,{data:V}=eRe({traceId:y??void 0}),{data:M}=fRe({traceId:y??void 0,spanId:x}),{data:G}=kje({traceId:y??void 0,spanId:q?.spanId,page:0}),F=(()=>{const R=[],U=!!y;return R.push(_?"auto":U?"2fr":"1fr"),U&&R.push(E?"auto":"3fr"),R.join(" ")})();return o.jsx(uY,{label:`Experiment item ${e}`,wide:!!x||!!I&&!_,children:f?o.jsxs("div",{className:"[&>section]:bg-surface3 grid h-full min-h-0 content-start gap-4 p-3 [&>section]:rounded-lg [&>section]:shadow-lg",style:{gridTemplateRows:F},children:[o.jsx(Exs,{result:f,scores:v,onPrevious:u,onNext:d,onClose:l,onScoreClick:A,featuredScoreId:k,onShowTrace:()=>{f.traceId&&(b(f.traceId),w(void 0),C(null),T(!0),N(!1))},onOpenInReview:()=>c(f.id),onFlagForReview:()=>{m(f.id)},collapsed:_,scorePanelSlot:I?o.jsx(Nxs,{score:I,onNext:P(),onPrevious:L(),onClose:()=>C(null),onShowTrace:()=>{I.traceId&&(b(I.traceId),w(void 0),T(!0),N(!1))},className:"rounded-none border-0 bg-transparent"}):null}),y&&o.jsx(rY,{traceId:y,spans:H,isLoadingSpans:B,selectedSpanId:x??null,onClose:()=>{b(null),w(void 0),T(!1)},onSpanSelect:w,showUnavailableFeaturesMsg:!1,collapsed:E,onCollapsedChange:N,traceHref:`/traces?traceId=${encodeURIComponent(y)}`,anchorSpanId:q?.spanId,feedbackTabBadge:V?.pagination?.total??void 0,feedbackTabSlot:({traceId:R})=>o.jsx(iY,{traceId:R}),scoresTabBadge:G?.pagination?.total??void 0,scoresTabSlot:({traceId:R,rootSpanId:U})=>U?o.jsx(mHt,{traceId:R,spanId:U,isTopLevelSpan:!q?.parentSpanId,entityType:z,onScoreSelect:Z=>{v?.some(Y=>Y.id===Z)&&(C(Z),T(!1))}}):null,spanFeedbackTabBadge:M?.pagination?.total??void 0,spanFeedbackTabSlot:({traceId:R,spanId:U})=>R&&U?o.jsx(hRe,{traceId:R,spanId:U},`${R}:${U}`):null,spanPanelClassName:"rounded-none border-0 bg-transparent"})]}):a||i?o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(Vt,{})})}):o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(br,{iconSlot:o.jsx(O0e,{}),titleSlot:"Item not found",descriptionSlot:`No loaded result for item "${e}".`,actionSlot:o.jsx(ie,{onClick:l,children:"Close"})})})})})}const yRe=e=>o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 9.83952 9.3295",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.67171 0.838331H6.70163V4.05307L9.68767 8.09999C10.0634 8.6093 9.69869 9.32932 9.06643 9.3295H0.772551C0.140289 9.3293 -0.223777 8.60929 0.151995 8.09999L3.13804 4.05307V0.838331H2.17136V0H7.67171V0.838331ZM3.97705 4.32955L3.89513 4.44015L2.34681 6.53802H7.49285L5.94453 4.44015L5.86261 4.32955V0.860859H3.97705V4.32955Z",fill:"currentColor"})}),kV="all",Btt=60,Rxs=e=>e.length>Btt?`${e.slice(0,Btt)}…`:e;function Pxs({value:e,onValueChange:t,className:n,variant:r,allOption:s}){const{data:a,isLoading:i,isError:l}=fY(void 0),c=(a?.experiments??[]).map(d=>({label:jHt(d),value:d.id,start:o.jsx(yRe,{className:"text-neutral3 size-4 shrink-0","data-testid":"experiments-icon"}),description:d.description?Rxs(d.description):y0(d.id)??d.id})),u=s?[{label:"All experiments",value:kV},...c]:c;return o.jsx(vl,{options:u,value:e??(s?kV:""),onValueChange:t,placeholder:i?"Loading experiments...":l?"Failed to load experiments":"Select experiment",searchPlaceholder:"Search experiments...",emptyText:"No experiments found.",className:n,disabled:i||l,variant:r})}function $xs(){const[e,t]=za(),n=e.get("experiment"),r=e.get("review"),{data:s,error:a}=fY(void 0),i=s?.experiments.find(c=>c.id===n),l=c=>{t(c===kV?{}:{experiment:c},{replace:!0})};return a&&hs(a)?o.jsx(Zn,{children:o.jsx(Ts,{})}):a&&ps(a)?o.jsx(Zn,{children:o.jsx(ks,{resource:"experiments"})}):a?o.jsx(Zn,{children:o.jsx(La,{title:"Failed to load experiments",message:a.message})}):o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(Lt.Row,{children:o.jsx(Lt.Column,{className:"justify-items-start",children:o.jsx(Pxs,{allOption:!0,value:n??void 0,onValueChange:l,className:"w-80"})})})}),o.jsx(Lt.MainArea,{className:"overflow-visible",children:o.jsx(lxs,{datasetId:i?.datasetId??void 0,experimentId:n??void 0,featuredItemId:r,detailPanelVariant:"overlay"},n??kV)})]})}const Mxs=20;function Dxs({reviewStatus:e}){const t=Ye(),n=Ly({queryKey:["feedback","list",e],queryFn:({pageParam:r})=>t.listFeedback({filters:{reviewStatus:e},pagination:{page:r,perPage:Mxs},orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:r=>r.pagination?.hasMore?r.pagination.page+1:void 0});return{...n,items:n.data?.pages.flatMap(r=>r.feedback)??[],total:n.data?.pages[0]?.pagination?.total}}function Lxs({enabled:e}){const t=Ye();return mt({queryKey:["feedback","inbox-count"],queryFn:()=>t.listFeedback({filters:{reviewStatus:"needs-review"},pagination:{page:0,perPage:1},orderBy:{field:"timestamp",direction:"DESC"}}),enabled:e,refetchInterval:3e3})}function Fxs(){const e=Ye(),t=Ar();return Sn({mutationFn:({feedbackId:n,reviewStatus:r})=>e.updateFeedbackReviewStatus({feedbackId:n,reviewStatus:r}),onSuccess:()=>t.invalidateQueries({queryKey:["feedback"]})})}const Utt="minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) auto";function zxs({items:e,isLoading:t,error:n}){const r=qr(),[s,a]=g.useState(""),i=s.trim().toLowerCase(),l=i?e.filter(d=>[d.itemId,d.experimentId,d.datasetId,d.traceId??""].some(f=>f.toLowerCase().includes(i))):e,{containerRef:c,getRowProps:u}=ao({count:l.length});return t?o.jsx(Bo,{columns:Utt}):n?o.jsx(La,{title:"Failed to load dataset items",message:n.message}):e.length===0?o.jsx(br,{iconSlot:o.jsx(N0e,{className:"text-neutral3 h-8 w-8"}),titleSlot:"Nothing to review",descriptionSlot:"Experiment results that need review will show up here."}):o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_1fr] gap-4",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(cd,{onSearch:a,label:"Filter dataset items",placeholder:"Filter by item, experiment, dataset or trace",shortcutDisabled:!0})}),o.jsx("div",{className:"min-h-0 overflow-hidden",children:o.jsxs(pe,{columns:Utt,fit:"container",scrollRef:c,children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{children:"Item"}),o.jsx(pe.TopCell,{children:"Experiment"}),o.jsx(pe.TopCell,{children:"Dataset"}),o.jsx(pe.TopCell,{children:"Trace"}),o.jsx(pe.TopCell,{children:" "})]}),l.length===0?o.jsx(pe.NoMatch,{message:"No dataset items match your search"}):l.map((d,f)=>{const h=STe(d.experimentId,d.id);return o.jsxs(pe.RowWrapper,{children:[o.jsxs(pe.RowButton,{colEnd:-2,onClick:()=>r(h),...u(f),children:[o.jsx(pe.TextCell,{font:"mono",children:d.itemId}),o.jsx(pe.TextCell,{font:"mono",children:d.experimentId}),o.jsx(pe.TextCell,{font:"mono",children:d.datasetId}),o.jsx(pe.TextCell,{font:"mono",children:d.traceId??"—"})]}),o.jsx(pe.ActionsCell,{className:"pl-2",children:d.traceId?o.jsx(ie,{as:Da,to:`/traces?traceId=${encodeURIComponent(d.traceId)}`,variant:"ghost",size:"sm",children:"Open trace"}):null})]},d.id)})]})})]})}function Bxs(){return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx(N0e,{}),titleSlot:"Your inbox is empty",descriptionSlot:o.jsxs(o.Fragment,{children:["Feedback left on traces and experiment results flagged for review ",o.jsx("br",{}),"will show up here until you mark them reviewed."]}),actionSlot:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ie,{as:Da,to:"/experiments",variant:"outline",children:"Go to experiments"}),o.jsx(ie,{as:Da,to:"/traces",variant:"outline",children:"Go to traces"})]})})})}function l0e(e){return e.comment?e.comment:typeof e.value=="string"?e.value:e.feedbackType==="thumbs"?e.value===1?"Thumbs up":"Thumbs down":JSON.stringify(e.value)??String(e.value)}const qtt="minmax(0, 2fr) auto minmax(0, 1fr) auto auto";function Uxs({items:e,isLoading:t,error:n,hasNextPage:r,isFetchingNextPage:s,fetchNextPage:a,onMarkReviewed:i,pendingFeedbackId:l,onSelect:c,selectedFeedbackId:u}){const[d,f]=g.useState(""),h=d.trim().toLowerCase(),p=h?e.filter(x=>l0e(x).toLowerCase().includes(h)||(x.traceId??"").toLowerCase().includes(h)||(x.feedbackSource??"").toLowerCase().includes(h)):e,{containerRef:m,getRowProps:v}=ao({count:p.length}),{inView:y,setRef:b}=a0({root:m});return g.useEffect(()=>{y&&r&&!s&&a()},[y,r,s,a]),t?o.jsx(Bo,{columns:qtt}):n?o.jsx(La,{title:"Failed to load feedback",message:n.message}):o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_1fr] gap-4",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(cd,{onSearch:f,label:"Filter feedback",placeholder:"Filter loaded feedback by text, trace or source"})}),o.jsx("div",{className:"min-h-0 overflow-hidden",children:o.jsxs(pe,{columns:qtt,fit:"container",scrollRef:m,children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{children:"Feedback"}),o.jsx(pe.TopCell,{children:"Source"}),o.jsx(pe.TopCell,{children:"Trace"}),o.jsx(pe.TopCell,{children:"Date"}),o.jsx(pe.TopCell,{children:" "})]}),p.length===0?o.jsx(pe.NoMatch,{message:h?"No feedback matches your search":"No feedback needs review"}):p.map((x,w)=>{const k=x.feedbackId;return o.jsxs(pe.RowWrapper,{children:[o.jsxs(pe.RowButton,{colEnd:-2,disabled:!x.traceId,featured:k!==void 0&&k===u,onClick:()=>c(x),...v(w),children:[o.jsx(pe.TextCell,{className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:l0e(x)})}),o.jsx(pe.Cell,{children:o.jsx(bt,{size:"sm",children:x.feedbackSource})}),o.jsx(pe.TextCell,{font:"mono",className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:x.traceId??"—"})}),o.jsx(pe.TextCell,{children:dr(x.timestamp,"MMM d, h:mm a")})]}),o.jsx(pe.ActionsCell,{className:"pl-2",children:k?o.jsx(ie,{variant:"ghost",size:"sm",onClick:()=>i(k),disabled:l===k,children:"Mark reviewed"}):null})]},k??`${String(x.timestamp)}-${x.traceId}`)}),o.jsx(pe.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:b})]})})]})}function qxs({feedback:e,traceId:t,initialSpanId:n,onClose:r,onPrevious:s,onNext:a,onMarkReviewed:i,isMarkingReviewed:l}){const[c,u]=g.useState(n),{spans:d,isLoading:f}=BAe({traceId:t,anchorSpanId:null,listMode:"traces"});return o.jsx(uY,{label:`Review feedback for trace ${t}`,wide:!!c,children:o.jsxs("div",{className:"[&>*]:bg-surface3 grid h-full min-h-0 grid-rows-[auto_minmax(0,1fr)] gap-4 p-3 [&>*]:rounded-lg [&>*]:shadow-lg",children:[o.jsxs(Gt,{className:"max-h-[33vh]",children:[o.jsxs(Gt.Header,{className:"items-start",children:[o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Gt.Heading,{children:"Feedback"}),o.jsx(bt,{variant:"neutral",emphasis:"muted",children:e.feedbackType}),e.feedbackSource&&o.jsx(bt,{variant:"neutral",emphasis:"muted",children:e.feedbackSource})]}),o.jsxs(ve,{as:"p",variant:"ui-sm",className:"text-neutral3",children:[dr(new Date(e.timestamp),"MMM dd, yyyy HH:mm:ss"),e.feedbackUserId?` · ${e.feedbackUserId}`:null]})]}),o.jsx(es,{className:"ml-auto shrink-0",children:o.jsxs(ie,{variant:"primary",size:"sm",onClick:i,disabled:l,children:[o.jsx(Qe,{children:o.jsx(Ur,{})}),"Mark as reviewed"]})})]}),o.jsx(Gt.Content,{children:o.jsx(ve,{as:"p",variant:"ui-md",className:"text-neutral5 whitespace-pre-wrap",children:l0e(e)})})]}),o.jsx("section",{className:"min-h-0 overflow-hidden",children:o.jsx(rY,{className:"h-full rounded-none border-0 bg-transparent",spanPanelClassName:"rounded-none border-0 bg-transparent",traceId:t,spans:d,isLoadingSpans:f,selectedSpanId:c??null,initialSpanId:n,onSpanSelect:u,onClose:r,onPrevious:s,onNext:a,traceHref:`/traces?traceId=${encodeURIComponent(t)}`,feedbackTabSlot:({traceId:h})=>o.jsx(iY,{traceId:h}),spanFeedbackTabSlot:({traceId:h,spanId:p})=>h&&p?o.jsx(hRe,{traceId:h,spanId:p},`${h}:${p}`):null})})]})})}const BHt=100;async function Vxs(e){const t=[];let n=0,r=!0;for(;r;){const s=await e.listExperiments({page:n,perPage:BHt});t.push(...s.experiments),r=s.pagination.hasMore,n+=1}return t}async function Hxs(e,t,n){const r=[];let s=0,a=!0;for(;a;){const i=await e.listDatasetExperimentResults(t,n,{page:s,perPage:BHt});r.push(...i.results),a=i.pagination.hasMore,s+=1}return r}function Wxs(){const e=Ye();return mt({queryKey:["inbox-dataset-review-items"],queryFn:async()=>{const t=await Vxs(e);return(await Promise.all(t.map(async r=>{const s=r.datasetId;return s?(await Hxs(e,s,r.id)).filter(i=>i.status==="needs-review").map(i=>({id:i.id,datasetId:s,experimentId:r.id,itemId:i.itemId,traceId:i.traceId??void 0,input:i.input,output:i.output})):[]}))).flat()},refetchInterval:3e3,refetchOnWindowFocus:!1})}function Zxs({enabled:e}){const t=Ye();return mt({queryKey:["inbox-dataset-review-count"],queryFn:async()=>{const{counts:n}=await t.getExperimentReviewSummary();return n.reduce((r,s)=>r+s.needsReview,0)},enabled:e,refetchInterval:3e3})}function Gxs(e){return e==="dataset"||e==="feedback"}function Qxs(){const[e,t]=za(),n=e.get("tab"),r=Gxs(n)?n:"feedback",s=Dxs({reviewStatus:"needs-review"}),a=Fxs(),i=Wxs(),l=i.data??[],c=s.total??0,u=!s.isLoading&&!i.isLoading&&!s.error&&!i.error&&s.items.length===0&&l.length===0,d=e.get("feedbackId")??void 0,f=e.get("traceId")??void 0,h=e.get("spanId")??void 0,p=T=>{t(E=>{const N=new URLSearchParams(E);for(const I of["feedbackId","traceId","spanId"]){const A=T[I];A?N.set(I,A):N.delete(I)}return N},{replace:!0})},m=()=>p({}),v=T=>p({feedbackId:T.feedbackId??void 0,traceId:T.traceId??void 0,spanId:T.spanId??void 0}),y=s.items.findIndex(T=>T.feedbackId===d),b=y>=0?s.items[y]:void 0,x=y>0?s.items[y-1]:void 0,w=y>=0&&y<s.items.length-1?s.items[y+1]:void 0,k=!!f&&!!d,C=T=>{a.mutate({feedbackId:T,reviewStatus:"reviewed"},{onSuccess:()=>T===d&&m()})},_=T=>{t(E=>{const N=new URLSearchParams(E);return N.set("tab",T),N},{replace:!0})};return o.jsxs("div",{className:"relative h-full overflow-hidden",children:[o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs(Dl,{children:[o.jsx(Dl.Title,{children:"Inbox"}),o.jsx(Dl.Description,{children:"Items waiting for review"})]})}),o.jsx(Lt.MainArea,{className:"min-h-0 overflow-hidden",children:u?o.jsx(Bxs,{}):o.jsxs(Zc,{defaultTab:"feedback",value:r,onValueChange:_,className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[o.jsxs(Wc,{variant:"pill-ghost",children:[o.jsxs(Qr,{value:"feedback",className:"px-3 py-2.5",children:[o.jsx(Qe,{size:"sm",children:o.jsx(t3,{})}),o.jsx(ve,{variant:"ui-sm",className:"text-inherit",children:"Feedback"}),c>0&&o.jsx(bt,{variant:"yellow",size:"sm",children:c})]}),o.jsxs(Qr,{value:"dataset",className:"px-3 py-2.5",children:[o.jsx(Qe,{size:"sm",children:o.jsx(X1,{})}),o.jsx(ve,{variant:"ui-sm",className:"text-inherit",children:"Dataset items"}),l.length>0&&o.jsx(bt,{variant:"yellow",size:"sm",children:l.length})]})]}),o.jsx(_s,{value:"feedback",className:"h-full min-h-0 pt-4",children:o.jsx(Uxs,{items:s.items,isLoading:s.isLoading,error:s.error??void 0,hasNextPage:s.hasNextPage,isFetchingNextPage:s.isFetchingNextPage,fetchNextPage:s.fetchNextPage,onMarkReviewed:C,pendingFeedbackId:a.isPending?a.variables?.feedbackId:void 0,onSelect:v,selectedFeedbackId:d})}),o.jsx(_s,{value:"dataset",className:"h-full min-h-0 pt-4",children:o.jsx(zxs,{items:l,isLoading:i.isLoading,error:i.error??void 0})})]})})]}),k&&f&&b&&o.jsx(qxs,{feedback:b,traceId:f,initialSpanId:h,onClose:m,onPrevious:x?()=>v(x):void 0,onNext:w?()=>v(w):void 0,onMarkReviewed:()=>d&&C(d),isMarkingReviewed:a.isPending},`${d}:${f}`)]})}function Yxs({connection:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsxs("li",{className:"flex items-center justify-between border-b py-2",children:[o.jsxs("div",{children:[o.jsx("div",{className:"font-mono text-xs",children:e.connectionId}),o.jsxs("div",{className:"text-xs text-gray-500",children:[e.label??"(no label)"," · ",e.status,e.scope?` · ${e.scope}`:"",t&&e.authorId?` · author: ${e.authorId}`:""]})]}),o.jsx("button",{type:"button",className:"text-red-600 underline disabled:opacity-50",onClick:r,disabled:n,children:"Disconnect"})]})}function UHt({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("ul",{className:"space-y-1",children:e.map(s=>o.jsx(Yxs,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function Kxs({groups:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("div",{className:"space-y-4",children:e.map(([s,a])=>o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-semibold text-gray-700","data-testid":`integration-author-group-${s}`,children:s==="shared"?"Shared":`Owned by ${s}`}),o.jsx(UHt,{connections:a,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function Xxs({providerId:e,toolkit:t,connections:n,groupedByAuthor:r,isAdmin:s,isLoading:a,error:i,disconnectPending:l,disconnectError:c,onDisconnect:u}){return o.jsxs("div",{className:"space-y-2 border rounded p-4",children:[o.jsx("h2",{className:"text-lg font-semibold",children:"Existing connections"}),!e||!t?o.jsx("p",{className:"text-gray-500",children:"Pick a provider and toolkit to list connections."}):a?o.jsx("p",{className:"text-gray-500",children:"Loading…"}):i?o.jsx("p",{className:"text-red-600",children:String(i)}):n.length===0?o.jsx("p",{className:"text-gray-500",children:"No connections."}):r?o.jsx(Kxs,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):o.jsx(UHt,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?o.jsx("p",{className:"text-red-600",children:String(c)}):null]})}function Jxs({providers:e,toolkits:t,providerId:n,toolkit:r,label:s,providersLoading:a,providersError:i,toolkitsLoading:l,toolkitsError:c,authorizePending:u,authorizeError:d,authorizedConnection:f,onProviderChange:h,onToolkitChange:p,onLabelChange:m,onConnect:v}){return o.jsxs("div",{className:"space-y-4 border rounded p-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"provider-select",children:"Provider"}),o.jsxs("select",{id:"provider-select",className:"border rounded px-2 py-1 w-full",value:n,onChange:y=>h(y.target.value),disabled:a,children:[o.jsx("option",{value:"",children:"— select provider —"}),e.map(y=>o.jsxs("option",{value:y.id,children:[y.displayName??y.name," (",y.id,")"]},y.id))]}),a&&o.jsx("span",{className:"text-gray-500",children:"Loading providers…"}),i?o.jsx("span",{className:"text-red-600",children:String(i)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"toolkit-select",children:"Toolkit"}),o.jsxs("select",{id:"toolkit-select",className:"border rounded px-2 py-1 w-full",value:r,onChange:y=>p(y.target.value),disabled:!n||l,children:[o.jsx("option",{value:"",children:"— select toolkit —"}),t.map(y=>o.jsxs("option",{value:y.slug,children:[y.name," (",y.slug,")"]},y.slug))]}),l&&o.jsx("span",{className:"text-gray-500",children:"Loading toolkits…"}),c?o.jsx("span",{className:"text-red-600",children:String(c)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"label-input",children:"Label (optional)"}),o.jsx("input",{id:"label-input",type:"text",className:"border rounded px-2 py-1 w-full",placeholder:"My personal Gmail",value:s,onChange:y=>m(y.target.value),disabled:!n||!r})]}),o.jsx("button",{type:"button",className:"bg-blue-600 text-white rounded px-4 py-2 disabled:opacity-50",onClick:v,disabled:!n||!r||u,children:u?"Authorizing…":"Connect"}),d?o.jsx("p",{className:"text-red-600",children:String(d)}):null,f&&o.jsxs("p",{className:"text-green-700",children:["Authorized: ",f.connectionId," (status: ",f.status,")"]})]})}const Vtt=e=>e.authorId?.trim()||"shared",e0s=(e,t)=>{if(!t||new Set(e.map(Vtt)).size<=1)return null;const r=new Map;for(const a of e){const i=Vtt(a);r.set(i,[...r.get(i)??[],a])}const s=Array.from(r.entries());return s.sort(([a],[i])=>a==="shared"?1:i==="shared"?-1:a.localeCompare(i)),s},t0s=["*","tool-providers:*","tool-providers:admin"];function n0s(){const{data:e}=zm();return e?.permissions?.some(t=>t0s.includes(t))??!1}function r0s(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,a]=g.useState(""),i=sA(),l=uG(e||null),c=n4t(e||null,n||null),u=t4t(),d=X3t(),f=n0s(),h=i.data?.providers??[],p=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),v=g.useMemo(()=>e0s(m,f),[m,f]),y=w=>{t(w),r("")},b=()=>{!e||!n||u.mutate({providerId:e,toolkit:n,label:s.trim()||null},{onSuccess:()=>{a(""),c.refetch()}})},x=w=>{d.mutate({providerId:e,connectionId:w})};return o.jsxs("div",{className:"p-6 max-w-3xl space-y-6 text-sm",children:[o.jsx("h1",{className:"text-2xl font-semibold",children:"Integrations"}),o.jsx("p",{className:"text-gray-500",children:"Minimal page to verify the ToolProvider backend. Pick a provider and toolkit, then connect."}),o.jsx(Jxs,{providers:h,toolkits:p,providerId:e,toolkit:n,label:s,providersLoading:i.isLoading,providersError:i.error,toolkitsLoading:l.isLoading,toolkitsError:l.error,authorizePending:u.isPending,authorizeError:u.error,authorizedConnection:u.data,onProviderChange:y,onToolkitChange:r,onLabelChange:a,onConnect:b}),o.jsx(Xxs,{providerId:e,toolkit:n,connections:m,groupedByAuthor:v,isAdmin:f,isLoading:c.isLoading,error:c.error,disconnectPending:d.isPending,disconnectError:d.error,onDisconnect:x})]})}function s0s({title:e,description:t,errorBanner:n,children:r}){return o.jsx("div",{"data-testid":"login-page",className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsxs("div",{className:"w-full max-w-sm space-y-6",children:[o.jsxs("div",{className:"flex flex-col items-center space-y-2",children:[o.jsx(Wh,{className:"h-10 w-10"}),o.jsx("h1",{className:"text-neutral6 text-xl font-semibold",children:e})]}),t,n,r]})})}function qHt({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:a}=pc(),{mutate:i,isPending:l,error:c}=V2r(),{mutate:u,isPending:d,error:f}=W2r(),{mutate:h,isPending:p}=rDt(),[m,v]=g.useState(n),[y,b]=g.useState(""),[x,w]=g.useState(""),[k,C]=g.useState("");if(a)return o.jsx("div",{className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"text-neutral3",children:"Loading..."})});if(!s?.enabled||!s?.login)return o.jsx("div",{className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"text-neutral3",children:"Authentication is not configured"})});const{login:_}=s,T=_.type==="sso"||_.type==="both",E=_.type==="credentials"||_.type==="both",N=_.sso,I=_.signUpEnabled!==!1,A=m==="signin"||!I,P=A?l:d,L=A?c:f,D=()=>{t?t():e?window.location.href=e:window.location.href=bG("/")},B=M=>{M.preventDefault(),A?i({email:x,password:k},{onSuccess:D}):u({email:x,password:k,name:y||void 0},{onSuccess:D})},H=()=>{h({redirectUri:e},{onSuccess:M=>{window.location.href=M.url}})},q=()=>{v(A?"signup":"signin")},z=_.description?o.jsxs("div",{className:"border-border1 bg-surface1 flex items-start gap-2.5 rounded-md border p-3",children:[o.jsx(Bd,{className:"text-neutral4 mt-0.5 h-4 w-4 shrink-0"}),o.jsx("p",{className:"text-neutral3 text-sm",children:_.description})]}):null,V=r?o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:r}):null;return o.jsxs(s0s,{title:A?"Sign in to Mastra Studio":"Create your account",description:z,errorBanner:V,children:[E&&o.jsxs("form",{onSubmit:B,className:"space-y-4",children:[!A&&o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"name",className:"text-neutral4 block text-sm",children:"Name"}),o.jsx(jn,{id:"name",type:"text",value:y,onChange:M=>b(M.target.value),placeholder:"Your name",variant:"default",size:"lg"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"email",className:"text-neutral4 block text-sm",children:"Email"}),o.jsx(jn,{id:"email",type:"email",value:x,onChange:M=>w(M.target.value),placeholder:"you@example.com",required:!0,variant:"default",size:"lg"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"password",className:"text-neutral4 block text-sm",children:"Password"}),o.jsx(jn,{id:"password",type:"password",value:k,onChange:M=>C(M.target.value),placeholder:A?"Enter your password":"Create a password",required:!0,variant:"default",size:"lg"})]}),L&&o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:L.message}),o.jsx(ie,{type:"submit",disabled:P,className:"w-full",size:"lg",children:P?A?"Signing in...":"Creating account...":A?"Sign in":"Create account"}),I&&o.jsxs("div",{className:"text-center text-sm",children:[o.jsx("span",{className:"text-neutral3",children:A?"Don't have an account? ":"Already have an account? "}),o.jsx("button",{type:"button",onClick:q,className:"text-neutral6 hover:underline",children:A?"Sign up":"Sign in"})]})]}),T&&E&&o.jsxs("div",{className:"relative",children:[o.jsx("div",{className:"absolute inset-0 flex items-center",children:o.jsx("div",{className:"border-border1 w-full border-t"})}),o.jsx("div",{className:"relative flex justify-center text-sm",children:o.jsx("span",{className:"bg-surface1 text-neutral3 px-2",children:"or continue with"})})]}),T&&N&&o.jsxs(ie,{onClick:H,disabled:p,className:"w-full",size:"lg",variant:"outline",children:[N.icon&&o.jsx("span",{className:"mr-2",children:N.icon}),p?"Redirecting...":N.text||"Sign in"]})]})}function a0s(){const[e]=za(),t=qr(),n=e.get("redirect")||"/",s=e.get("mode")==="signup"?"signup":"signin",a=e.get("error_description")||e.get("error")||null,i=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(qHt,{redirectUri:n,onSuccess:i,initialMode:s,errorMessage:a})}const gh=Aa.KeyValueList;function i0s(e){return e instanceof Date?e:new Date(e)}function o0s({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:a,collapsed:i,onCollapsedChange:l}){const[c,u]=g.useState(!1),d=i??c,f=l??u,h=i0s(e.timestamp),p=e.traceId,m=e.spanId;return o.jsxs(Aa,{collapsed:d,children:[o.jsxs(Aa.Header,{children:[o.jsxs(Aa.Heading,{children:["Log ",o.jsx("b",{children:dr(h,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(es,{className:"ml-auto shrink-0",children:[l&&o.jsx(ie,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(aI,{}):o.jsx(_V,{})}),o.jsxs(es,{spacing:"close",children:[o.jsx(ie,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(K1,{})}),o.jsx(ie,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(CV,{})})]}),o.jsx(Aa.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(Aa.Content,{children:[o.jsx("p",{className:"text-ui-md text-neutral4 font-mono wrap-break-word whitespace-pre-wrap",children:e.message}),(p||m)&&o.jsxs("div",{className:K("my-8 grid gap-2","[&>button]:justify-between [&>button]:overflow-hidden"),children:[p&&o.jsxs(es,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(ie,{size:"md",className:"min-w-0 flex-1 overflow-hidden",onClick:()=>n?.(p),children:[o.jsx(Fd,{}),o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",p]})]}),o.jsx(_a,{content:p,size:"md",tooltip:"Copy Trace ID to clipboard"})]}),m&&o.jsxs(es,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(ie,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!p||!r,onClick:()=>p&&r?.(p,m),children:[o.jsx(Fd,{}),o.jsx("span",{children:"Span"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",m]})]}),o.jsx(_a,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(gh,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(gh.Key,{children:"Entity Type"}),o.jsx(gh.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(gh.Key,{children:"Entity Name"}),o.jsx(gh.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(gh.Key,{children:"Service"}),o.jsx(gh.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(gh.Key,{children:"Environment"}),o.jsx(gh.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(gh.Key,{children:"Source"}),o.jsx(gh.Value,{children:e.source})]}),e.metadata&&Object.keys(e.metadata).length>0&&o.jsx(o.Fragment,{children:Object.entries(e.metadata).map(([v,y])=>o.jsxs(g.Fragment,{children:[o.jsx(gh.Key,{children:v}),o.jsx(gh.Value,{children:String(y)})]},v))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(Aa.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function l0s({error:e,resource:t,errorTitle:n}){if(hs(e))return o.jsx(Ts,{});if(ps(e))return o.jsx(ks,{resource:t});if(B4(e))return o.jsx(br,{iconSlot:o.jsx(Mc,{}),titleSlot:"Observability storage is not available",descriptionSlot:"The observability storage domain is disabled or not configured. Enable it in your storage configuration to view logs in Studio."});if(z4(e,"logs"))return o.jsx(br,{iconSlot:o.jsx(Mc,{}),titleSlot:"Logs are not available with your current storage",descriptionSlot:"The configured observability storage provider does not support listing logs. Switch to a storage provider with logs support to view runtime logs in Studio."});const r=e instanceof Error?e.message:void 0;return o.jsx(La,{title:n,message:r??"Unknown error"})}function c0s({listSlot:e,logPanelSlot:t,tracePanelSlot:n,spanPanelSlot:r,logCollapsed:s}){const a=!!t;return o.jsxs("div",{className:K("grid h-full min-h-0 items-start gap-4",a?"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[e,a&&o.jsxs("div",{className:K("grid h-full gap-4 overflow-auto",n&&r?s?"grid-rows-[auto_1fr_1fr]":"grid-rows-[1fr_1fr_1fr]":n?s?"grid-rows-[auto_1fr]":"grid-rows-[1fr_1fr]":s?"grid-rows-[auto]":"grid-rows-[1fr]"),children:[t,n,r]})]})}const u0s={debug:{label:"DEBUG",color:"#71717a"},info:{label:"INFO",color:"#60a5fa"},warn:{label:"WARN",color:"#facc15"},error:{label:"ERROR",color:"#f87171"},fatal:{label:"FATAL",color:"#dc2626"}};function d0s({level:e}){const t=u0s[e];return o.jsx(ho,{children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function f0s({entityType:e,className:t}){const n=K("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case"agent":return o.jsx(Ri,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return o.jsx(Bc,{className:n,"aria-hidden":!0});case"tool":return o.jsx(Bf,{className:n,"aria-hidden":!0});default:return null}}function h0s({entityType:e,entityName:t}){const n=e??"";return o.jsxs(ho,{className:"flex min-w-0 items-center gap-2",children:[o.jsx(f0s,{entityType:n}),t?o.jsx("span",{className:"text-ui-smd min-w-0 truncate",children:t}):"-"]})}function p0s({message:e}){return o.jsx(ho,{className:"text-ui-smd text-neutral4 min-w-0 truncate font-mono",children:e})}function m0s({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(ho,{children:null});const t=Object.entries(e).map(([n,r])=>{if(typeof r=="string")return`${n}: ${r}`;try{return`${n}: ${JSON.stringify(r)}`}catch{return`${n}: <unserializable>`}}).join(", ");return o.jsx(ZEe,{font:"mono",children:t})}const tc=Object.assign(D4,{Top:F4,TopCell:vS,TopCellWithTooltip:YZ,TopCellSmart:c$t,RowWrapper:YEe,RowButton:L4,RowLink:l$t,Spacer:KEe,NoMatch:QZ,DateCell:a$t,TimeCell:i$t,LevelCell:d0s,EntityCell:h0s,MessageCell:p0s,DataCell:m0s,NextPageLoading:GZ}),Htt="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",g0s=36,v0s=8;function y0s({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=g.useRef(null),u=Zqt({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>g0s,overscan:v0s}),{getRowProps:d}=ao({count:e.length,containerRef:c,onNavigate:y=>u.scrollToIndex(y)}),f=g.useRef(t);if(g.useEffect(()=>{f.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),f.current=t},[t]),t)return o.jsx(Bo,{columns:Htt});const h=u.getVirtualItems(),p=u.getTotalSize(),m=h[0]?.start??0,v=h.length>0?Math.max(0,p-(h[h.length-1]?.end??0)):0;return o.jsxs(tc,{columns:Htt,scrollRef:c,className:"min-w-0",children:[o.jsxs(tc.Top,{children:[o.jsx(tc.TopCell,{children:"Date"}),o.jsx(tc.TopCell,{children:"Time"}),o.jsx(tc.TopCell,{children:"Level"}),o.jsx(tc.TopCell,{children:"Entity"}),o.jsx(tc.TopCell,{children:"Message"}),o.jsx(tc.TopCell,{children:"Data"})]}),e.length===0?o.jsx(tc.NoMatch,{message:"No logs match your search"}):o.jsxs(o.Fragment,{children:[o.jsx(tc.Spacer,{height:m}),h.map(y=>{const b=e[y.index];if(!b)return null;const x=a.get(b);if(!x)return null;const w=x===i;return o.jsxs(tc.RowButton,{ref:u.measureElement,"data-index":y.index,...d(y.index),onClick:()=>l(b),featured:w,variant:b.level==="error"||b.level==="fatal"?"error":"default",children:[o.jsx(tc.DateCell,{timestamp:b.timestamp}),o.jsx(tc.TimeCell,{timestamp:b.timestamp}),o.jsx(tc.LevelCell,{level:b.level}),o.jsx(tc.EntityCell,{entityType:b.entityType,entityName:b.entityName}),o.jsx(tc.MessageCell,{message:b.message}),o.jsx(tc.DataCell,{data:b.data})]},x)}),o.jsx(tc.Spacer,{height:v})]}),o.jsx(tc.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function b0s({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>x0s(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(sRe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(nRe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function x0s(e,t){const n=t.find(r=>r.id===e.fieldId);return n?n.kind==="text"?typeof e.value=="string"&&e.value.trim()!=="":n.kind==="pick-multi"?n.multi?Array.isArray(e.value)&&e.value.length>0:typeof e.value=="string"&&e.value!==""&&e.value!=="Any":n.kind==="multi-select"?Array.isArray(e.value)&&e.value.length>0:!1:!1}const w0s={"last-24h":"the last 24 hours","last-3d":"the last 3 days","last-7d":"the last 7 days","last-14d":"the last 14 days","last-30d":"the last 30 days"},aoe="MMM d, yyyy HH:mm",ioe="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function S0s({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${w0s[e]}`,description:ioe}:t&&n?{title:`No logs between ${dr(t,aoe)} and ${dr(n,aoe)}`,description:ioe}:t?{title:`No logs since ${dr(t,aoe)}`,description:ioe}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const k0s=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=S0s({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx(Mc,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",children:["Logging Documentation ",o.jsx(ta,{})]})})})},O0s=20,C0s=1e4;function _0s(e,t,n){if(e?.pagination?.hasMore)return n+1}function E0s(e){const t=new Set,n=[];for(const r of e.pages)for(const s of r.logs??[]){const a=s.logId??JSON.stringify(s);t.has(a)||(t.add(a),n.push(s))}return n}function T0s(e){return z4(e.state.error,"logs")||B4(e.state.error)?!1:C0s}const j0s=({filters:e}={})=>{const t=Ye(),{inView:n,setRef:r}=a0(),s=Ly({queryKey:["logs",e],queryFn:({pageParam:h})=>t.listLogsVNext({pagination:{page:h,perPage:O0s},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:_0s,select:E0s,retry:!1,refetchInterval:T0s}),{hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,data:c,isLoading:u,isError:d,error:f}=s;return g.useEffect(()=>{n&&a&&!i&&l()},[n,a,i,l]),{data:c,hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,isLoading:u,isError:d,error:f,setEndOfListElement:r}},c8={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},VHt=[{label:"Agent",entityType:c8.AGENT},{label:"Workflow",entityType:c8.WORKFLOW},{label:"Scorer",entityType:c8.SCORER},{label:"Ingest",entityType:c8.INGEST}],N0s=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],Xx="rootEntityType",rx="datePreset",sx="dateFrom",ax="dateTo",I0s=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),jl={level:"filterLevel",tags:"filterTags",entityName:"filterEntityName",traceId:"filterTraceId",spanId:"filterSpanId",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId"},KL=Object.keys(jl),bRe=new Set(["tags"]),xRe="mastra:logs:saved-filters";function A0s(e,t=xRe){const n=D0s(e),r=e.get(rx);r&&n.set(rx,r);const s=e.get(sx);s&&n.set(sx,s);const a=e.get(ax);a&&n.set(ax,a);try{localStorage.setItem(t,n.toString())}catch{}}function R0s(e=xRe){try{localStorage.removeItem(e)}catch{}}function Wtt(e=xRe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function P0s(e){if(e.has(rx)||e.has(sx)||e.has(ax)||e.has(Xx))return!0;for(const t of KL)if(e.has(jl[t]))return!0;return!1}function $0s({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:VHt.map(u=>({label:u.label,value:u.entityType})),placeholder:"Choose entity type",emptyText:"No entity types."},{id:"entityName",label:"Primitive Name",kind:"pick-multi",options:t.map(u=>({label:u,value:u})),placeholder:"Choose entity names",emptyText:"No entity names found.",isLoading:s?.entityNames},{id:"level",label:"Level",kind:"pick-multi",searchable:!1,options:N0s.map(u=>({label:u.label,value:u.value})),placeholder:"Choose level",emptyText:"No levels."},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"traceId",label:"Trace ID",kind:"text"},{id:"spanId",label:"Span ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"threadId",label:"Thread ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function M0s(e){const t=[],n=new Map([[Xx,"rootEntityType"]]);for(const s of KL)n.set(jl[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),bRe.has(a)){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function D0s(e){const t=new URLSearchParams,n=e.get(Xx);n&&t.set(Xx,n);for(const r of KL){const s=jl[r];if(bRe.has(r)){for(const i of e.getAll(s))t.append(s,i);continue}const a=e.get(s);a&&t.set(s,a)}return t}function L0s(e,t){e.delete(Xx);for(const n of KL)e.delete(jl[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(Xx,n.value);continue}const r=jl[n.fieldId];if(r){if(bRe.has(n.fieldId)&&Array.isArray(n.value)){if(n.value.length===0)e.append(r,"");else for(const s of n.value)e.append(r,s);continue}typeof n.value=="string"&&e.set(r,n.value.trim())}}}function F0s({rootEntityType:e,dateFrom:t,dateTo:n,tokens:r}){const s={};e&&(s.rootEntityType=e),(t||n)&&(s.timestamp={...t?{start:t}:{},...n?{end:n}:{}});for(const a of r){if(a.fieldId==="tags"){Array.isArray(a.value)&&a.value.length>0?s.tags=a.value:typeof a.value=="string"&&a.value.trim()&&(s.tags=[a.value.trim()]);continue}if(a.fieldId==="level"){typeof a.value=="string"&&a.value.trim()&&a.value!=="Any"&&(s.level=a.value);continue}if(typeof a.value=="string"&&a.value.trim()&&a.value!=="Any")switch(a.fieldId){case"entityName":s.rootEntityName=a.value;break;case"traceId":s.traceId=a.value;break;case"spanId":s.spanId=a.value;break;case"runId":s.runId=a.value;break;case"threadId":s.threadId=a.value;break;case"sessionId":s.sessionId=a.value;break;case"requestId":s.requestId=a.value;break;case"resourceId":s.resourceId=a.value;break;case"userId":s.userId=a.value;break;case"organizationId":s.organizationId=a.value;break;case"serviceName":s.serviceName=a.value;break;case"environment":s.environment=a.value;break;case"experimentId":s.experimentId=a.value;break}}return s}function z0s(e,t){return t.map(n=>{const r=e.find(s=>s.id===n.fieldId);return r?r.kind==="text"?{fieldId:n.fieldId,value:""}:r.kind==="pick-multi"?r.multi?{fieldId:n.fieldId,value:[]}:{fieldId:n.fieldId,value:"Any"}:n:n})}const B0s="Filters setting for Logs saved",U0s="Filters setting for Logs cleared up";function q0s(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=g.useState(()=>Wtt(r)!==null),c=g.useCallback(()=>{A0s(e,r),l(!0);const f=s?.saved??B0s;f!==!1&&Ve.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{R0s(r),l(!1);const f=s?.cleared??U0s;f!==!1&&Ve.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(a||d.current||(d.current=!0,P0s(e)))return;const f=Wtt(r);f&&t(h=>{const p=new URLSearchParams(h);for(const[m,v]of f)p.append(m,v);return p},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function V0s(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return(t>>>0).toString(36)}function H0s(e){const t=new Map;for(const n of e){if(n.logId){t.set(n,n.logId);continue}const r=n.timestamp instanceof Date?n.timestamp.toISOString():n.timestamp;t.set(n,V0s(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function W0s(e,t,n,r){const s=g.useMemo(()=>H0s(e),[e]),a=g.useMemo(()=>{const p=new Map;for(const[m,v]of e.entries()){const y=s.get(v);y&&p.set(y,{log:v,idx:m})}return p},[e,s]),l=(t?a.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=g.useCallback(p=>s.get(p),[s]),d=g.useCallback(p=>{const m=s.get(p);if(m){if(t===m){n({logId:null});return}n(r?{logId:m,traceId:p.traceId??null,spanId:null}:{logId:m})}},[s,t,r,n]),f=l>0?()=>{const p=e[l-1];if(!p)return;const m=s.get(p);m&&n(r?{logId:m,traceId:p.traceId??null,spanId:null}:{logId:m})}:void 0,h=l>=0&&l<e.length-1?()=>{const p=e[l+1];if(!p)return;const m=s.get(p);m&&n(r?{logId:m,traceId:p.traceId??null,spanId:null}:{logId:m})}:void 0;return{logIdMap:s,getLogId:u,featuredLog:c,handleLogClick:d,handlePreviousLog:f,handleNextLog:h}}const c0e="logId",u0e="traceId",d0e="spanId",IP=1440*60*1e3,Z0s={"last-24h":IP,"last-3d":3*IP,"last-7d":7*IP,"last-14d":14*IP,"last-30d":30*IP};function u8(e){e.delete(c0e),e.delete(u0e),e.delete(d0e)}function G0s(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const C=e.get(rx);return C&&I0s.has(C)?C:"last-24h"},[e]),a=e.get(sx),i=e.get(ax),l=g.useMemo(()=>{if(s==="custom"){if(!a)return;const _=new Date(a);return Number.isNaN(_.getTime())?void 0:_}if(s==="all")return;const C=Z0s[s];return C?new Date(Date.now()-C):void 0},[s,a]),c=g.useMemo(()=>{if(s!=="custom"||!i)return;const C=new Date(i);return Number.isNaN(C.getTime())?void 0:C},[s,i]),u=g.useRef(s);u.current=s;const d=e.get(c0e),f=e.get(u0e),h=e.get(d0e),p=g.useMemo(()=>VHt.find(C=>C.entityType===e.get(Xx)),[e]),m=g.useMemo(()=>M0s(e),[e]),v=g.useCallback(C=>{t(_=>{const T=new URLSearchParams(_);for(const[E,N]of Object.entries(C)){const I=E==="logId"?c0e:E==="traceId"?u0e:d0e;N?T.set(I,N):T.delete(I)}return T},{replace:!0})},[t]),y=g.useCallback(C=>{t(_=>{const T=new URLSearchParams(_);return L0s(T,C),u8(T),T},{replace:!0})},[t]),b=y,x=g.useCallback((C,_)=>{if(u.current!=="custom")return;const T=_==="from"?sx:ax;t(E=>{const N=new URLSearchParams(E);return C?N.set(T,C.toISOString()):N.delete(T),u8(N),N},{replace:!0})},[t]),w=g.useCallback(C=>{u.current=C,t(_=>{const T=new URLSearchParams(_);return C==="last-24h"?(T.delete(rx),T.delete(sx),T.delete(ax)):C==="custom"?T.set(rx,"custom"):(T.set(rx,C),T.delete(sx),T.delete(ax)),u8(T),T},{replace:!0})},[t]),k=g.useCallback(()=>{t(C=>{const _=new URLSearchParams(C);_.delete(Xx);for(const T of KL)_.delete(jl[T]);return _.delete(rx),_.delete(sx),_.delete(ax),u8(_),_},{replace:!0}),r?.()},[t,r]);return g.useMemo(()=>({searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,featuredLogId:d,featuredTraceId:f,featuredSpanId:h,selectedEntityOption:p,filterTokens:m,handleFeaturedChange:v,handleFilterTokensChange:b,handleDateChange:x,handleDatePresetChange:w,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,h,p,m,v,b,x,w,k,y])}const Rb=Aa.KeyValueList;function Q0s({spanId:e,span:t,isLoading:n,onClose:r}){const s=zQ(t?.startedAt,t?.endedAt),a=vV(t?.startedAt),i=vV(t?.endedAt);return o.jsxs(Aa,{children:[o.jsxs(Aa.Header,{children:[o.jsxs(Aa.Heading,{children:["Span ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Aa.CloseButton,{onClick:r})]}),n?o.jsx(Aa.LoadingData,{children:"Loading span..."}):t?o.jsxs(Aa.Content,{children:[o.jsxs(Rb,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(Rb.Key,{children:"Type"}),o.jsx(Rb.Value,{children:t.spanType})]}),a&&o.jsxs(o.Fragment,{children:[o.jsx(Rb.Key,{children:"Started"}),o.jsx(Rb.Value,{children:a})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(Rb.Key,{children:"Ended"}),o.jsx(Rb.Value,{children:i})]}),s&&o.jsxs(o.Fragment,{children:[o.jsx(Rb.Key,{children:"Duration"}),o.jsx(Rb.Value,{children:s})]})]}),o.jsx("br",{}),o.jsx(Aa.CodeSection,{title:"Input",icon:o.jsx(Ox,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(Aa.CodeSection,{title:"Output",icon:o.jsx(nm,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(Aa.CodeSection,{title:"Metadata",icon:o.jsx(sc,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(Aa.CodeSection,{title:"Attributes",icon:o.jsx(sc,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(Aa.NoData,{children:"Span not found."})]})}function Y0s({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:a}){const i=g.useMemo(()=>HL(t??[]),[t]),[l,c]=g.useState([]);g.useEffect(()=>{i.length>0&&c(UQ(i))},[i]);const u=d=>{s?.(a===d?void 0:d)};return o.jsxs(Aa,{children:[o.jsxs(Aa.Header,{children:[o.jsxs(Aa.Heading,{children:["Trace ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Aa.CloseButton,{onClick:r})]}),n?o.jsx(Aa.LoadingData,{children:"Loading trace..."}):i.length===0?o.jsx(Aa.NoData,{children:"No spans found for this trace."}):o.jsx(Aa.Content,{children:o.jsx(qAe,{hierarchicalSpans:i,onSpanClick:u,selectedSpanId:a??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}function K0s(){const[e,t]=za(),n=G0s(e,t),r=q0s(e,t),[s,a]=g.useState(),[i,l]=g.useState(!1),{data:c=[],isPending:u}=dRe(),{data:d=[],isPending:f}=lRe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:h=[],isPending:p}=cRe(),{data:m=[],isPending:v}=uRe(),y=g.useMemo(()=>$0s({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:h,loading:{tags:u,entityNames:f,serviceNames:v,environments:p}}),[c,d,m,h,u,f,v,p]),b=g.useMemo(()=>F0s({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:x=[],isLoading:w,error:k,isFetchingNextPage:C,hasNextPage:_,setEndOfListElement:T}=j0s({filters:b}),{logIdMap:E,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:P}=W0s(x,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:L,isLoading:D}=VL(n.featuredTraceId??null),{data:B,isLoading:H}=BQ(n.featuredTraceId??"",n.featuredSpanId??""),q=g.useCallback(()=>n.applyFilterTokens(z0s(y,n.filterTokens)),[y,n]),z=g.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),V=g.useCallback(Y=>n.handleFeaturedChange({traceId:Y,spanId:null}),[n]),M=g.useCallback((Y,te)=>n.handleFeaturedChange({traceId:Y,spanId:te}),[n]),G=g.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),F=g.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),R=g.useCallback(Y=>n.handleFeaturedChange({spanId:Y??null}),[n]),U=o.jsxs(Lt.TopArea,{children:[o.jsx(Lt.Row,{children:o.jsxs(Lt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(q4,{preset:n.datePreset,onPresetChange:n.handleDatePresetChange,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,onDateChange:n.handleDateChange,disabled:w,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),o.jsx(aRe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:w,onStartTextFilter:a})]})}),o.jsx(b0s,{isLoading:w,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:q,onRemoveAll:n.handleRemoveAll,onSave:r.handleSave,onRemoveSaved:r.hasSavedFilters?r.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(k)return o.jsxs(Lt,{width:"wide",height:"full",children:[U,o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(l0s,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const Z=!!n.selectedEntityOption||n.filterTokens.length>0;return x.length===0&&!w&&!Z?o.jsxs(Lt,{width:"wide",height:"full",children:[U,o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(k0s,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Lt,{width:"wide",height:"full",children:[U,o.jsx(c0s,{logCollapsed:i,listSlot:o.jsx(y0s,{logs:x,isLoading:w,isFetchingNextPage:C,hasNextPage:_,setEndOfListElement:T,logIdMap:E,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(o0s,{log:N,onClose:z,onTraceClick:V,onSpanClick:M,onPrevious:A,onNext:P,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(Y0s,{traceId:n.featuredTraceId,spans:L?.spans,isLoading:D,onClose:G,onSpanSelect:R,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(Q0s,{spanId:n.featuredSpanId,span:B?.span,isLoading:H,onClose:F}):null})]})}function X0s({server:e,rowProps:t}){const{paths:n,Link:r}=dn(),a=Ye().options.baseUrl,i=a?`${a}/api/mcp/${e.id}/sse`:"",{data:l}=iUt(e),c=Object.values(l||{}),u=c.length,d=c.filter(p=>p.toolType==="agent").length,f=c.filter(p=>p.toolType==="workflow").length,h=Dh(e.name,50);return o.jsxs(pe.RowLink,{to:n.mcpServerLink(e.id),LinkComponent:r,...t,children:[o.jsx(pe.NameCell,{children:h}),o.jsx(pe.DescriptionCell,{children:i}),o.jsx(pe.TextCell,{className:"text-center",children:d||""}),o.jsx(pe.TextCell,{className:"text-center",children:u||""}),o.jsx(pe.TextCell,{className:"text-center",children:f||""})]})}function J0s({mcpServers:e,isLoading:t,search:n=""}){const r=g.useMemo(()=>{const i=n.toLowerCase();return e.filter(l=>l.name?.toLowerCase().includes(i)||l.id?.toLowerCase().includes(i))},[e,n]),{containerRef:s,getRowProps:a}=ao({count:r.length});return t?o.jsx(Bo,{columns:"auto 1fr auto auto auto"}):o.jsxs(pe,{columns:"auto 1fr auto auto auto",scrollRef:s,children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{children:"Name"}),o.jsx(pe.TopCell,{children:"URL"}),o.jsx(pe.TopCellSmart,{long:"Agents",short:o.jsx(Ri,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(pe.TopCellSmart,{long:"Tools",short:o.jsx(Bf,{}),tooltip:"Tools",className:"text-center"}),o.jsx(pe.TopCellSmart,{long:"Workflows",short:o.jsx(Bc,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(pe.NoMatch,{message:"No MCP Servers match your search"}):null,r.map((i,l)=>o.jsx(X0s,{server:i,rowProps:a(l)},i.id))]})}const ews=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx(Mc,{}),titleSlot:"No MCP Servers yet",descriptionSlot:o.jsxs(o.Fragment,{children:["MCP servers are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsxs(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(ta,{})]})})}),tws=()=>{const{data:e=[],isLoading:t,error:n}=NQ(),[r,s]=g.useState("");return n&&hs(n)?o.jsx(Zn,{children:o.jsx(Ts,{})}):n&&ps(n)?o.jsx(Zn,{children:o.jsx(ks,{resource:"MCP servers"})}):n?o.jsx(Zn,{children:o.jsx(La,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(Zn,{children:o.jsx(ews,{})}):o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx(cd,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(J0s,{mcpServers:e,isLoading:t,search:r})]})},nws=(e,t)=>{const n=new Map,r=Object.keys(t);for(const s of r){const a=t[s],i=a.tools,l=Object.keys(i);for(const c of l){const u=i[c];n.has(u.id)||n.set(u.id,{...u,agents:[]}),n.get(u.id).agents.push({...a,id:s})}}for(const[s,a]of Object.entries(e))n.has(a.id)||n.set(a.id,{...a,agents:[]});return Array.from(n.values())};function rws({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=dn(),i=g.useMemo(()=>nws(e,t),[e,t]),l=g.useMemo(()=>i.filter(d=>d.id.toLowerCase().includes(r.toLowerCase())),[i,r]),{containerRef:c,getRowProps:u}=ao({count:l.length});return n?o.jsx(Bo,{columns:"auto 1fr auto"}):o.jsxs(pe,{columns:"auto 1fr auto",scrollRef:c,children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{children:"Name"}),o.jsx(pe.TopCell,{children:"Description"}),o.jsx(pe.TopCellSmart,{long:"Agents",short:o.jsx(Ri,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(pe.NoMatch,{message:"No Tools match your search"}):null,l.map((d,f)=>{const h=Dh(d.id,50),p=Dh(d.description??"",200),m=d.agents.length;return o.jsxs(pe.RowLink,{to:s.toolLink(d.id),LinkComponent:a,...u(f),children:[o.jsx(pe.NameCell,{children:h}),o.jsx(pe.DescriptionCell,{children:p}),o.jsx(pe.TextCell,{className:"text-center",children:m||""})]},d.id)})]})}const sws=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx(Mc,{}),titleSlot:"No Tools yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Mastra tools are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsxs(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(ta,{})]})})}),aws=()=>{const e=Ye();return Sn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new zC;Object.entries(r??{}).forEach(([a,i])=>{s.set(a,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(a){throw Ve.error("Error executing dev tool"),console.error("Error executing dev tool:",a),a}}})},iws=({toolId:e})=>{const{canExecute:t}=Eo(),n=t("tools"),{data:r={}}=Bm(),s=g.useMemo(()=>{for(const v of Object.values(r))if(v.tools){const y=Object.values(v.tools).find(b=>b.id===e);if(y)return y}return null},[r,e]),{data:a,isLoading:i,error:l}=s2r(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=aws(),{requestContext:h}=ys();g.useEffect(()=>{if(l){const v=l instanceof Error?l.message:"Failed to load tool";Ve.error(`Error loading tool: ${v}`)}},[l]);const p=async(v,y)=>{if(!c)return;const b={...h??{},...y??{}};return u({toolId:c.id,input:v,requestContext:b})},m=c?.inputSchema?xm(Ix(c?.inputSchema)):ws({});return i?o.jsxs("div",{className:"p-6",children:[o.jsx(Et,{className:"mb-4 h-8 w-48"}),o.jsx(Et,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(vAe,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:p,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ve,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ve,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function ows({value:e,onValueChange:t,placeholder:n="Select a tool...",searchPlaceholder:r="Search tools...",emptyText:s="No tools found.",className:a,disabled:i=!1,variant:l,size:c}){const{data:u={},isLoading:d,isError:f,error:h}=nA(),{data:p={},isLoading:m,isError:v,error:y}=Bm(),{navigate:b,paths:x}=dn();g.useEffect(()=>{if(f){const _=h instanceof Error?h.message:"Failed to load tools";Ve.error(`Error loading tools: ${_}`)}},[f,h]),g.useEffect(()=>{if(v){const _=y instanceof Error?y.message:"Failed to load agents";Ve.error(`Error loading agents: ${_}`)}},[v,y]);const w=new Map;Object.values(p).forEach(_=>{_.tools&&Object.values(_.tools).forEach(T=>{w.has(T.id)||w.set(T.id,T)})}),Object.values(u).forEach(_=>{w.has(_.id)||w.set(_.id,_)});const k=Array.from(w.values()).map(_=>({label:_.id,value:_.id})),C=_=>{t?t(_):_&&_!==e&&b(x.toolLink(_))};return o.jsx(vl,{options:k,value:e,onValueChange:C,placeholder:d||m?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||d||m||f||v,variant:l,size:c})}const lws=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=g.useState({sseUrl:"",httpStreamUrl:""});if(g.useEffect(()=>{if(!t)return;const i=window.MASTRA_SERVER_HOST,l=window.MASTRA_SERVER_PORT;let c=null;i&&l&&(c=`http://${i}:${l}`);const u=c||"http://localhost:4111",d=`${u}/api/mcp/${t.id}/sse`,f=`${u}/api/mcp/${t.id}/mcp`;s({sseUrl:d,httpStreamUrl:f})},[t]),e)return null;if(!t)return o.jsx(by,{children:o.jsx(ve,{as:"h1",variant:"header-md",className:"text-neutral3 py-20 text-center font-medium",children:"Server not found"})});const a=`npx -y mcp-remote ${n}`;return o.jsxs(by,{isDivided:!0,children:[o.jsxs("div",{className:"mx-auto w-full max-w-2xl px-8 py-12",children:[o.jsx(ve,{as:"h1",variant:"header-md",className:"text-neutral6 pb-4 font-medium",children:t.name}),o.jsxs("div",{className:"flex items-center gap-1 pb-6",children:[o.jsx(bt,{icon:o.jsx(rVt,{}),size:"sm",children:"Version"}),o.jsx(bt,{size:"sm",children:t.version_detail.version})]}),o.jsx(ve,{className:"text-neutral3 pb-4",children:"This MCP server can be accessed through multiple transport methods. Choose the one that best fits your use case."}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(bt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"HTTP"}),children:"Regular HTTP Endpoint"}),o.jsx(ve,{className:"text-neutral3 pt-1 pb-2",children:"Use for stateless HTTP transport with streamable responses."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ve,{className:"bg-surface4 rounded-lg px-2 py-1",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx(_a,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(bt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"SSE"}),children:"Server-Sent Events"}),o.jsx(ve,{className:"text-neutral3 pt-1 pb-2",children:"Use for real-time communication via SSE."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ve,{className:"bg-surface4 rounded-lg px-2 py-1",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx(_a,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(bt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"CLI"}),children:"Command Line"}),o.jsx(ve,{className:"text-neutral3 pt-1 pb-2",children:"Use for local command-line access via npx and mcp-remote."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ve,{className:"bg-surface4 rounded-lg px-2 py-1",children:a}),o.jsx("div",{className:"pt-1",children:o.jsx(_a,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"border-border1 h-full overflow-y-scroll border-l",children:o.jsx(cws,{server:t})})]})},cws=({server:e})=>{const{data:t={},isLoading:n}=iUt(e);if(n)return null;const r=Object.keys(t);return o.jsxs("div",{className:"overflow-y-scroll p-5",children:[o.jsxs("div",{className:"text-neutral6 flex items-center gap-2",children:[o.jsx(Qe,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(N_,{})}),o.jsx(ve,{variant:"header-md",as:"h2",className:"font-medium",children:"Available Tools"})]}),o.jsx("div",{className:"flex flex-col gap-2 pt-6",children:r.map(s=>{const a=t[s];return o.jsx(dws,{tool:a,serverId:e.id},s)})})]})};function uws(e){if(!e)return!1;const t=e.ui;return!!(typeof t?.resourceUri=="string"&&t.resourceUri.startsWith("ui://")||typeof e["ui/resourceUri"]=="string"&&e["ui/resourceUri"].startsWith("ui://"))}const dws=({tool:e,serverId:t})=>{const n=g.useRef(null),{Link:r,paths:s}=dn(),a=hUt[e.toolType||"tool"],i=uws(e._meta);return o.jsxs(Wf,{onClick:()=>n.current?.click(),children:[o.jsx(e4t,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Gf,{children:[o.jsx(Zf,{children:o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(r,{ref:n,href:s.mcpServerToolLink(t,e.id),children:e.id}),i&&o.jsx(bt,{size:"xs",children:"App"})]})}),o.jsx(cp,{children:e.description})]})]})},fws=()=>{const{serverId:e}=fr(),{data:t=[],isLoading:n}=NQ(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(lws,{isLoading:n,server:r})})};function hws(e){if(!e)return;const t=e.ui;if(t?.resourceUri)return t.resourceUri;const n=e["ui/resourceUri"];if(typeof n=="string")return n}const pws=({toolId:e,serverId:t})=>{const{canExecute:n}=Eo(),r=n("tools"),s=Ye(),{data:a,isLoading:i,error:l}=pAe(t,e),{mutateAsync:c,isPending:u,data:d}=yis(t,e),f=a?hws(a._meta):void 0,{data:h}=mt({queryKey:["mcp-app-resource",t,f],queryFn:async()=>f?(await s.readMcpServerResource(t,f)).contents[0]?.text??null:null,enabled:!!f}),p=g.useCallback(async(y,b)=>await c(b),[c]);g.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";Ve.error(`Error loading tool: ${y}`)}},[l]);const m=async y=>{if(a)return await c(y)};if(i)return o.jsxs("div",{className:"p-6",children:[o.jsx(Et,{className:"mb-4 h-8 w-48"}),o.jsx(Et,{className:"h-32 w-full"})]});if(l)return null;if(!a)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ve,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ve,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let v;try{v=xm(a.inputSchema)}catch(y){console.error("Error processing input schema:",y),Ve.error("Failed to process tool input schema."),v=ws({})}return o.jsxs("div",{className:"flex flex-col gap-4",children:[h&&o.jsx("div",{className:"border-border1 border-b p-4",children:o.jsx(aUt,{html:h,toolName:a.name??a.id,onToolCall:p})}),o.jsx(vAe,{executionResult:d,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},mws=()=>{const{serverId:e,toolId:t}=fr(),{data:n,isLoading:r}=pAe(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(pws,{toolId:t,serverId:e})})},HHt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],XN="rootEntityType",JN={tags:"filterTags",entityId:"filterEntityId",entityName:"filterEntityName",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId",provider:"filterProvider",model:"filterModel"},hY=Object.keys(JN),wRe="mastra:metrics:saved-filters";function gws(e){const t=wws(e);try{localStorage.setItem(wRe,t.toString())}catch{}}function vws(){try{localStorage.removeItem(wRe)}catch{}}function WHt(){try{const e=localStorage.getItem(wRe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function yws(e){if(e.has(XN))return!0;for(const t of hY)if(e.has(JN[t]))return!0;return!1}function bws({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:HHt.map(u=>({label:u.label,value:u.entityType})),placeholder:"Choose entity type",emptyText:"No entity types."},{id:"entityName",label:"Primitive Name",kind:"pick-multi",options:t.map(u=>({label:u,value:u})),placeholder:"Choose entity names",emptyText:"No entity names found.",isLoading:s?.entityNames},{id:"entityId",label:"Primitive ID",kind:"text"},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"threadId",label:"Thread ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function xws(e){const t=[],n=new Map([[XN,"rootEntityType"]]);for(const s of hY)n.set(JN[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),a==="tags"){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}if(a==="rootEntityType"||a==="entityName"||a==="serviceName"||a==="environment"||a==="provider"||a==="model"){const l=e.getAll(s);if(l.length>1){t.push({fieldId:a,value:l});continue}}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function wws(e){const t=new URLSearchParams,n=e.getAll(XN);for(const r of n)t.append(XN,r);for(const r of hY){const s=JN[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function Sws(e,t){e.delete(XN);for(const n of hY)e.delete(JN[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?XN:JN[n.fieldId];if(r)if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string"&&a!=="");if(s.length===0){n.fieldId==="tags"&&e.append(r,"");continue}for(const a of s)e.append(r,a)}else typeof n.value=="string"&&e.set(r,n.value.trim())}}const kws="Any";function Ztt(e){const t=e.trim();return t===""||t===kws}const Ows=new Set(HHt.map(e=>e.entityType));function Gtt(e){const t=e.trim();return Ows.has(t)?t:void 0}function Cws(e){const t={};for(const n of e){const r=n.fieldId;if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string").map(a=>a.trim()).filter(a=>!Ztt(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?Gtt(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(Ztt(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=Gtt(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const ZHt=[{label:"Last 24 hours",value:"24h"},{label:"Last 3 days",value:"3d"},{label:"Last 7 days",value:"7d"},{label:"Last 14 days",value:"14d"},{label:"Last 30 days",value:"30d"}],_ws=new Set(ZHt.map(e=>e.value));function Ews(e){return typeof e=="string"&&(_ws.has(e)||e==="custom")}const GHt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function pY(){return g.useContext(GHt)}function Tws(e,t){return e!=="custom"?ZHt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${dr(t.from,"MMM d, yyyy")} – ${dr(t.to,"MMM d, yyyy")}`:dr(t.from,"MMM d, yyyy"):"Custom range"}function jws({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:a,onCustomRangeChange:i,tracesBasePath:l,logsBasePath:c}){const u=g.useMemo(()=>JSON.stringify(n),[n]),d=g.useMemo(()=>n,[u]),f=g.useMemo(()=>Cws(d),[d]),h=g.useMemo(()=>JSON.stringify(f),[f]),p=Tws(t,a),m=g.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:a,setCustomRange:i??(()=>{}),dateRangeLabel:p,filterTokens:d,setFilterTokens:s,dimensionalFilter:f,dimensionalFilterKey:h,tracesBasePath:l,logsBasePath:c}),[t,r,a,i,p,d,s,f,h,l,c]);return o.jsx(GHt.Provider,{value:m,children:e})}const Nws=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function Iws(e){switch(e){case"3d":return"last-3d";case"7d":return"last-7d";case"14d":return"last-14d";case"30d":return"last-30d";case"custom":return"custom";default:return"last-24h"}}function Aws(e){switch(e){case"last-3d":return"3d";case"last-7d":return"7d";case"last-14d":return"14d";case"last-30d":return"30d";case"custom":return"custom";default:return"24h"}}function Rws(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=pY(),s=g.useRef(e);s.current=e;const a=g.useRef(n);return a.current=n,o.jsx(q4,{preset:Iws(e),onPresetChange:i=>{const l=Aws(i);s.current=l,t(l)},dateFrom:n?.from,dateTo:n?.to,onDateChange:(i,l)=>{if(s.current!=="custom")return;const c={...a.current,[l]:i};a.current=c,r(c)},presets:Nws})}const f0e=1440*60*1e3,Pws={"24h":f0e,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function $ws(e,t,n){if(e!=="custom"){const r=Pws[e]??f0e;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-f0e),end:t?.to??new Date(n)}}function Hm(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=pY(),s=g.useRef(null),a=e==="custom"?`custom:${t?.from?.getTime()??""}:${t?.to?.getTime()??""}`:`preset:${e}`;(!s.current||s.current.key!==a)&&(s.current={key:a,anchor:Date.now()});const i=s.current.anchor,l=g.useMemo(()=>$ws(e,t,i),[e,t,i]),c=g.useMemo(()=>({timestamp:l,...n}),[l,r]),u=g.useMemo(()=>`${a}|${r}`,[a,r]);return{datePreset:e,customRange:t,timestamp:l,filters:c,dimensionalFilter:n,filterKey:u}}function QHt(){const e=Ye(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function XL({href:e,LinkComponent:t="a"}){return o.jsx(ie,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(ac,{})})}function Mws({href:e,LinkComponent:t="a"}){return o.jsx(ie,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(nJt,{})})}function Dws(e){return e==="agents"||e==="workflows"||e==="tools"}function Qtt(e,t){if(e.length===0)return"0";const n=e.reduce((r,s)=>{const a=s[t];return r+(typeof a=="number"&&Number.isFinite(a)?a:0)},0);return`${Math.round(n/e.length)}`}function Lws(e){const t=e;return typeof t?.tsMs=="number"&&Number.isFinite(t.tsMs)}const Fws=[{dataKey:"p50",label:"p50",color:Gh.blue,aggregate:e=>({value:Qtt(e,"p50"),suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:Gh.yellow,aggregate:e=>({value:Qtt(e,"p95"),suffix:"avg ms"})}];function ooe({data:e,onPointClick:t}){return e.length===0?o.jsx(Ht.NoData,{message:"No latency data yet"}):o.jsx(ID,{data:e,series:Fws,onPointClick:t?n=>Lws(n)?t(n):void 0:void 0})}function zws({data:e,isLoading:t,isError:n,onPointClick:r,actions:s}){const a=(e?.agentData.length??0)>0,i=(e?.workflowData.length??0)>0,l=(e?.toolData.length??0)>0,c={agents:a,workflows:i,tools:l},u=a?"agents":i?"workflows":l?"tools":"agents",[d,f]=g.useState("agents"),h=c[d]?d:u,p=typeof s=="function"?s(h):s,m=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),v=e?Object.values(e).filter(Array.isArray).flat().map(b=>b.p50).filter(b=>typeof b=="number"):[],y=v.length>0?`${Math.round(v.reduce((b,x)=>b+x,0)/v.length)}ms`:"—";return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(Ht.Summary,{value:y,label:"Avg p50"}),p?o.jsx(Ht.Actions,{children:p}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load latency data"}):o.jsx(Ht.Content,{children:m?o.jsxs(Zc,{value:h,onValueChange:b=>{Dws(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(Wc,{children:[o.jsx(Qr,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(Qr,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(Qr,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(_s,{value:"agents",children:o.jsx(ooe,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(_s,{value:"workflows",children:o.jsx(ooe,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(_s,{value:"tools",children:o.jsx(ooe,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Ht.NoData,{message:"No latency data yet"})})]})}function Bws(e){switch(e){case"24h":return"last-24h";case"3d":return"last-3d";case"7d":return"last-7d";case"14d":return"last-14d";case"30d":return"last-30d";case"custom":return"custom";default:return}}function Uws(e,t){if(t==="1h"){const s=new Date(e);s.setUTCMinutes(0,0,0);const a=new Date(s.getTime()+3600*1e3);return{from:s,to:a}}const n=new Date(e);n.setUTCHours(0,0,0,0);const r=new Date(n.getTime()+1440*60*1e3);return{from:n,to:r}}function YHt(e,t,n,r,s,a,i){if(i){e.set(t,"custom"),e.set(n,i.from.toISOString()),e.set(r,i.to.toISOString());return}if(s==="custom"){e.set(t,"custom"),a?.from&&e.set(n,a.from.toISOString()),a?.to&&e.set(r,a.to.toISOString());return}const l=Bws(s);l&&e.set(t,l)}function $o(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function KHt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function Ytt({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const a=new URLSearchParams;a.set(zw,"branches"),YHt(a,Bw,Uw,qw,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Yx,i),r.status&&a.set(Kx,r.status),$o(a,Tl.entityName,r.entityName??n.entityName),$o(a,Tl.threadId,r.threadId??n.threadId),$o(a,Tl.resourceId,r.resourceId??n.resourceId),$o(a,Tl.entityId,n.entityId),$o(a,Tl.runId,n.runId),$o(a,Tl.sessionId,n.sessionId),$o(a,Tl.requestId,n.requestId),$o(a,Tl.userId,n.userId),$o(a,Tl.organizationId,n.organizationId),$o(a,Tl.experimentId,n.experimentId),$o(a,Tl.serviceName,n.serviceName),$o(a,Tl.environment,n.environment),KHt(a,Tl.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function qws({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;YHt(a,rx,sx,ax,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Xx,i),$o(a,jl.entityName,r.entityName??n.entityName),$o(a,jl.threadId,r.threadId??n.threadId),$o(a,jl.resourceId,r.resourceId??n.resourceId),$o(a,jl.runId,n.runId),$o(a,jl.sessionId,n.sessionId),$o(a,jl.requestId,n.requestId),$o(a,jl.userId,n.userId),$o(a,jl.organizationId,n.organizationId),$o(a,jl.experimentId,n.experimentId),$o(a,jl.serviceName,n.serviceName),$o(a,jl.environment,n.environment),KHt(a,jl.tags,n.tags),r.status==="error"&&a.append(jl.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function xA(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=pY(),a=g.useCallback((c={})=>Ytt({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=g.useCallback((c={})=>qws({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=Uws(u,d);return Ytt({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const XHt="1h";async function loe(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:XHt,filters:n}),s=r.series.find(l=>l.percentile===.5),a=r.series.find(l=>l.percentile===.95);if(!s||!a)return[];const i=new Map(a.points.map(l=>[new Date(l.timestamp).getTime(),l.value]));return s.points.map(l=>{const c=new Date(l.timestamp),u=c.getTime();return{time:c.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}),tsMs:u,p50:Math.round(l.value),p95:Math.round(i.get(u)??0)}})}function Vws(){const e=Ye(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([loe(e,"mastra_agent_duration_ms",t),loe(e,"mastra_workflow_duration_ms",t),loe(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:XHt}}})}const Ktt={agents:Xu.AGENT,workflows:Xu.WORKFLOW_RUN,tools:Xu.TOOL};function Hws(){const{data:e,isLoading:t,isError:n}=Vws(),{getTracesHref:r,getBucketTracesHref:s}=xA(),{Link:a}=dn(),i=qr();return o.jsx(zws,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:Ktt[l]},c.tsMs,"1h"))},actions:l=>o.jsx(XL,{href:r({rootEntityType:Ktt[l]}),LinkComponent:a})})}function Wws(e){return e==="threads"||e==="resources"}function coe(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function Zws({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("threads"),c=e.data?.map(y=>({...y,key:y.threadId}))??[],u=t.data?.map(y=>({...y,key:y.resourceId}))??[],d=c.length>0,f=u.length>0,h=e.data?.reduce((y,b)=>y+b.runs,0)??0,p=t.data?.reduce((y,b)=>y+b.threadCount,0)??0,m=i==="threads"?e:t,v=typeof s=="function"?s(i):s;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&o.jsx(Ht.Summary,{value:h.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&o.jsx(Ht.Summary,{value:p.toLocaleString(),label:"Total threads"}),v?o.jsx(Ht.Actions,{children:v}):null]}),m.isLoading?o.jsx(Ht.Loading,{}):m.isError?o.jsx(Ht.Error,{message:"Failed to load memory data"}):o.jsx(Ht.Content,{children:o.jsxs(Zc,{defaultTab:"threads",value:i,onValueChange:y=>{Wws(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Wc,{children:[o.jsx(Qr,{value:"threads",children:"Threads"}),o.jsx(Qr,{value:"resources",children:"Resources"})]}),o.jsx(_s,{value:"threads",children:d?o.jsxs(pe,{columns:"auto auto auto auto auto",...Jxe,children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(pe.RowHeaderCell,{className:"text-ui-sm",children:coe(y.threadId)}),o.jsx(pe.NumberCell,{children:y.resourceId?coe(y.resourceId):"—"}),o.jsx(pe.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(pe.NumberCell,{children:y.tokens>0?il(y.tokens):"—"}),o.jsx(pe.NumberCell,{children:y.cost!=null?Zh(y.cost,y.costUnit):"—"})]});return b?o.jsx(pe.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(pe.RowStatic,{children:x},y.key)})]}):o.jsx(Ht.NoData,{message:"No thread activity yet"})}),o.jsx(_s,{value:"resources",children:f?o.jsxs(pe,{columns:"auto auto auto auto",...Jxe,children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(pe.RowHeaderCell,{className:"text-ui-sm",children:coe(y.resourceId)}),o.jsx(pe.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(pe.NumberCell,{children:y.tokens>0?il(y.tokens):"—"}),o.jsx(pe.NumberCell,{children:y.cost!=null?Zh(y.cost,y.costUnit):"—"})]});return b?o.jsx(pe.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(pe.RowStatic,{children:x},y.key)})]}):o.jsx(Ht.NoData,{message:"No resource activity yet"})})]})})]})}const uoe=20;function Gws(){const e=Ye(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","top-active-threads",n],queryFn:async()=>{const r={groupBy:["threadId","resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count",limit:uoe}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:uoe}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:uoe})]),l=new Map,c=d=>bA(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const h=f.dimensions.threadId;if(!h)continue;const p=c(h);p.tokens+=f.value,f.estimatedCost!=null&&(p.cost=(p.cost??0)+f.estimatedCost,f.costUnit&&(p.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.threadId).map(d=>{const f=d.dimensions.threadId,h=l.get(f);return{threadId:f,resourceId:d.dimensions.resourceId??null,runs:d.value,tokens:h?.tokens??0,cost:h?.cost??null,costUnit:h?.costUnit??null}})}})}const doe=20;function Qws(){const e=Ye(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","top-resources-by-threads",n],queryFn:async()=>{const r={groupBy:["resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",limit:doe}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:doe}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:doe})]),l=new Map,c=d=>bA(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const h=f.dimensions.resourceId;if(!h)continue;const p=c(h);p.tokens+=f.value,f.estimatedCost!=null&&(p.cost=(p.cost??0)+f.estimatedCost,f.costUnit&&(p.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.resourceId).map(d=>{const f=d.dimensions.resourceId,h=l.get(f);return{resourceId:f,threadCount:d.value,tokens:h?.tokens??0,cost:h?.cost??null,costUnit:h?.costUnit??null}})}})}function Yws(){const e=Gws(),t=Qws(),{getTracesHref:n}=xA(),{Link:r}=dn();return o.jsx(Zws,{threads:{data:e.data,isLoading:e.isLoading,isError:e.isError},resources:{data:t.data,isLoading:t.isLoading,isError:t.isError},LinkComponent:r,getThreadRowHref:s=>n({threadId:s.threadId,...s.resourceId?{resourceId:s.resourceId}:{}}),getResourceRowHref:s=>n({resourceId:s.resourceId})})}function JL({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:a}){const i=t!=null;return o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:e}),o.jsx(Xr.Value,{className:i?void 0:"invisible",children:i?t:"—"}),a?o.jsx(Xr.Error,{}):s?o.jsx(Xr.Loading,{}):i?r!=null?o.jsx(Xr.Change,{changePct:r,prevValue:n}):o.jsx(Xr.NoChange,{}):o.jsx(Xr.NoData,{})]})}function Kws(){const e=Ye(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","active-resources-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"resourceId",filters:t,comparePeriod:"previous_period"})})}function Xws(){const e=Ye(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","active-threads-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",filters:t,comparePeriod:"previous_period"})})}function Jws(){const e=Ye(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","model-cost-kpi",n],queryFn:async()=>{const r=await e.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"});return{cost:r.estimatedCost??null,costUnit:r.costUnit??null,previousCost:r.previousEstimatedCost??null,costChangePercent:r.costChangePercent??null}}})}function e1s(){const e=Ye(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","total-tokens-kpi",n],queryFn:async()=>{const[r,s]=await Promise.all([e.getMetricAggregate({name:["mastra_model_total_input_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"}),e.getMetricAggregate({name:["mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"})]),a=r.value!=null||s.value!=null,i=r.previousValue!=null||s.previousValue!=null,l=(r.value??0)+(s.value??0),c=(r.previousValue??0)+(s.previousValue??0),u=i&&c>0?(l-c)/c*100:null;return{value:a?l:null,previousValue:i?c:null,changePercent:u}}})}function t1s(){const{data:e,isLoading:t,isError:n}=QHt();return o.jsx(JL,{label:"Total Agent Runs",value:e?.value!=null?e.value.toLocaleString():null,prevValue:e?.previousValue!=null?e.previousValue.toLocaleString():void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function n1s(){const{data:e,isLoading:t,isError:n}=Jws();return o.jsx(JL,{label:"Total Model Cost",value:e?.cost!=null?Zh(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?Zh(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function r1s(){const{data:e,isLoading:t,isError:n}=e1s();return o.jsx(JL,{label:"Total Tokens",value:e?.value!=null?il(e.value):null,prevValue:e?.previousValue!=null?il(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function s1s(){const{data:e,isLoading:t,isError:n}=Xws();return o.jsx(JL,{label:"Total Threads",value:e?.value!=null?il(e.value):null,prevValue:e?.previousValue!=null?il(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function a1s(){const{data:e,isLoading:t,isError:n}=Kws();return o.jsx(JL,{label:"Total Resources",value:e?.value!=null?il(e.value):null,prevValue:e?.previousValue!=null?il(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function i1s({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>o1s(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(sRe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(nRe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function o1s(e,t){const n=t.find(r=>r.id===e.fieldId);return n?n.kind==="text"?typeof e.value=="string"&&e.value.trim()!=="":n.kind==="pick-multi"?n.multi?Array.isArray(e.value)&&e.value.length>0:typeof e.value=="string"&&e.value!==""&&e.value!=="Any":n.kind==="multi-select"?Array.isArray(e.value)&&e.value.length>0:!1:!1}function l1s({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const i=!!e&&e.length>0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Model Usage & Cost",description:"Token consumption by model."}),i&&(()=>{const l=e.reduce((d,f)=>d+(f.cost??0),0),c=new Set;for(const d of e)d.cost!=null&&d.costUnit&&c.add(d.costUnit);let u;return c.size===0?u=l>0?Zh(l):"—":c.size===1?u=l>0?Zh(l,[...c][0]):"—":u="Mixed",o.jsx(Ht.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(Ht.Actions,{children:s}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load model usage data"}):o.jsx(Ht.Content,{children:i?o.jsxs(pe,{columns:"auto auto auto auto auto auto",...Jxe,children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{sticky:"start",children:"Model"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(pe.RowHeaderCell,{className:"text-ui-sm",children:l.model}),o.jsx(pe.NumberCell,{children:l.input}),o.jsx(pe.NumberCell,{children:l.output}),o.jsx(pe.NumberCell,{children:l.cacheRead}),o.jsx(pe.NumberCell,{children:l.cacheWrite}),o.jsx(pe.NumberCell,{highlight:!0,children:l.cost!=null?Zh(l.cost,l.costUnit):"—"})]});return c?o.jsx(pe.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(pe.RowStatic,{children:u},l.model)})]}):o.jsx(Ht.NoData,{message:"No model usage data yet"})})]})}function c1s(){const e=Ye(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","model-usage-cost",n],queryFn:async()=>{const[r,s,a,i]=await Promise.all(["mastra_model_total_input_tokens","mastra_model_total_output_tokens","mastra_model_input_cache_read_tokens","mastra_model_input_cache_write_tokens"].map(d=>e.getMetricBreakdown({name:[d],groupBy:["model"],aggregation:"sum",orderDirection:"DESC",filters:t})));if(!r||!s||!a||!i)return[];const l=new Map,c=d=>bA(l,d,()=>({input:0,output:0,cacheRead:0,cacheWrite:0,cost:null,costUnit:null})),u=(d,f)=>{f.estimatedCost!=null&&(d.cost=(d.cost??0)+f.estimatedCost,f.costUnit&&(d.costUnit=f.costUnit))};for(const d of r.groups){const f=d.dimensions.model??"unknown",h=c(f);h.input=d.value,u(h,d)}for(const d of s.groups){const f=d.dimensions.model??"unknown",h=c(f);h.output=d.value,u(h,d)}for(const d of a.groups){const f=d.dimensions.model??"unknown",h=c(f);h.cacheRead=d.value}for(const d of i.groups){const f=d.dimensions.model??"unknown",h=c(f);h.cacheWrite=d.value}return Array.from(l.entries()).map(([d,f])=>({model:d,input:il(f.input),output:il(f.output),cacheRead:il(f.cacheRead),cacheWrite:il(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function u1s(){const{data:e,isLoading:t,isError:n}=c1s(),{getTracesHref:r}=xA(),{Link:s}=dn();return o.jsx(l1s,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:Xu.AGENT}),actions:o.jsx(XL,{href:r({rootEntityType:Xu.AGENT}),LinkComponent:s})})}function d1s(e){return e==="tokens"||e==="cost"}function f1s({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("tokens"),c=e??[],u=c.length>0,d=c.reduce((b,x)=>b+x.total,0),f=c.filter(b=>b.cost!=null&&b.cost>0),h=new Set(f.map(b=>b.costUnit??"usd")),p=h.size<=1,m=p?[...h][0]??"usd":null,v=p?f.reduce((b,x)=>b+(x.cost??0),0):0,y=p&&v>0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&y?o.jsx(Ht.Summary,{value:Zh(v,m),label:"Total cost"}):o.jsx(Ht.Summary,{value:il(d),label:"Total tokens"})),u&&s?o.jsx(Ht.Actions,{children:s}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load token usage data"}):o.jsx(Ht.Content,{children:u?o.jsxs(Zc,{defaultTab:"tokens",value:i,onValueChange:b=>{d1s(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Wc,{children:[o.jsx(Qr,{value:"tokens",children:"Tokens"}),o.jsx(Qr,{value:"cost",children:"Cost"})]}),o.jsx(_s,{value:"tokens",children:o.jsx(KN,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:Gh.blueDark},{label:"Output",color:Gh.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:il})}),o.jsx(_s,{value:"cost",children:y?o.jsx(KN,{LinkComponent:a,data:f.slice().sort((b,x)=>(x.cost??0)-(b.cost??0)).map(b=>({name:b.name,values:[b.cost],href:r?.(b)})),segments:[{label:"Cost",color:Gh.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>Zh(b,m)}):o.jsx(Ht.NoData,{message:"No cost data yet"})})]}):o.jsx(Ht.NoData,{message:"No token usage data yet"})})]})}function h1s(){const e=Ye(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","token-usage-by-agent",n],queryFn:async()=>{const r={groupBy:["entityName"],aggregation:"sum",orderDirection:"DESC",filters:t},[s,a]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"]}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"]})]),i=new Map,l=u=>bA(i,u,()=>({input:0,output:0,cost:null,costUnit:null})),c=(u,d)=>{d.estimatedCost!=null&&(u.cost=(u.cost??0)+d.estimatedCost,d.costUnit&&(u.costUnit=d.costUnit))};for(const u of s.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.input=u.value,c(f,u)}for(const u of a.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.output=u.value,c(f,u)}return Array.from(i.entries()).map(([u,d])=>({name:u,input:d.input,output:d.output,total:d.input+d.output,cost:d.cost,costUnit:d.costUnit})).sort((u,d)=>d.total-u.total)}})}function p1s(){const{data:e,isLoading:t,isError:n}=h1s(),{getTracesHref:r}=xA(),{Link:s}=dn();return o.jsx(f1s,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:Xu.AGENT,entityName:a.name}),actions:o.jsx(XL,{href:r({rootEntityType:Xu.AGENT}),LinkComponent:s})})}function h0e(e,t=il){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const m1s=[{dataKey:"input",label:"Input tokens",color:Gh.blue,aggregate:h0e("input")},{dataKey:"output",label:"Output tokens",color:Gh.yellow,aggregate:h0e("output")}];function g1s(e){return e==="tokens"||e==="cost"}function v1s({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[a,i]=g.useState("tokens"),l=e??[],c=l.map(k=>({...k})),u=l.length>0,d=l.reduce((k,C)=>k+C.total,0),f=l.filter(k=>k.cost!=null&&k.cost>0),h=f.map(k=>({...k})),p=new Set(f.map(k=>k.costUnit).filter(k=>!!k)),m=p.size===1&&f.every(k=>k.costUnit!=null),v=m?[...p][0]??null:null,y=m?f.reduce((k,C)=>k+(C.cost??0),0):0,b=m&&y>0,x=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",w=[{dataKey:"cost",label:"Cost",color:Gh.purple,aggregate:h0e("cost",k=>Zh(k,v))}];return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Token usage over time",description:x}),u&&(a==="cost"&&b?o.jsx(Ht.Summary,{value:Zh(y,v),label:"Total cost"}):o.jsx(Ht.Summary,{value:il(d),label:"Total tokens"})),u&&s?o.jsx(Ht.Actions,{children:s}):null]}),n?o.jsx(Ht.Loading,{}):r?o.jsx(Ht.Error,{message:"Failed to load token usage timeline"}):o.jsx(Ht.Content,{children:u?o.jsxs(Zc,{defaultTab:"tokens",value:a,onValueChange:k=>{g1s(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(Wc,{children:[o.jsx(Qr,{value:"tokens",children:"Tokens"}),o.jsx(Qr,{value:"cost",children:"Cost"})]}),o.jsx(_s,{value:"tokens",children:o.jsx(ID,{data:c,series:m1s})}),o.jsx(_s,{value:"cost",children:b?o.jsx(ID,{data:h,series:w}):o.jsx(Ht.NoData,{message:"No cost data yet"})})]}):o.jsx(Ht.NoData,{message:"No token usage data yet"})})]})}function y1s(e){return e==="24h"?"1h":"1d"}function b1s(e,t){return t==="1h"?e.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}):e.toLocaleDateString("en-US",{month:"short",day:"2-digit"})}function Xtt(e,t,n){for(const r of t?.points??[]){const s=new Date(r.timestamp).getTime();if(!Number.isFinite(s))continue;const a=e.get(s)??{tsMs:s,input:0,output:0,cost:null,costUnits:new Set,hasUnknownCostUnit:!1};a[n]+=r.value,r.estimatedCost!=null&&(a.cost=(a.cost??0)+r.estimatedCost,t?.costUnit?a.costUnits.add(t.costUnit):a.hasUnknownCostUnit=!0),e.set(s,a)}}function x1s(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function w1s(){const e=Ye(),{datePreset:t,filters:n,filterKey:r}=Hm(),s=y1s(t);return mt({queryKey:["metrics","token-usage-timeseries",r,s],queryFn:async()=>{const[a,i]=await Promise.all([e.getMetricTimeSeries({name:["mastra_model_total_input_tokens"],interval:s,aggregation:"sum",filters:n}),e.getMetricTimeSeries({name:["mastra_model_total_output_tokens"],interval:s,aggregation:"sum",filters:n})]),l=new Map;return Xtt(l,a.series[0],"input"),Xtt(l,i.series[0],"output"),{data:Array.from(l.values()).sort((u,d)=>u.tsMs-d.tsMs).map(u=>{const d=new Date(u.tsMs);return{time:b1s(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:x1s(u)}}),interval:s}}})}function S1s(){const{data:e,isLoading:t,isError:n}=w1s(),{getTracesHref:r}=xA(),{Link:s}=dn();return o.jsx(v1s,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(XL,{href:r(),LinkComponent:s})})}function foe({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(KN,{LinkComponent:r,data:e.map(s=>{const a=n?.(s),i=t?.(s);return a?{name:s.name,values:[s.completed,s.errors],hrefs:[i,a]}:{name:s.name,values:[s.completed,s.errors],href:i}}),segments:[{label:"Completed",color:Gh.blueDark},{label:"Errors",color:Gh.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:il})}function k1s({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:a,LinkComponent:i}){const[l,c]=g.useState("agents"),u=typeof a=="function"?a(l):a,d=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),f=e?[...e.agentData,...e.workflowData,...e.toolData].reduce((m,v)=>m+v.completed+v.errors,0):0,h=m=>r?v=>r(m,v):void 0,p=m=>s?v=>s(m,v):void 0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(Ht.Summary,{value:il(f),label:"Total runs"}),u?o.jsx(Ht.Actions,{children:u}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load trace volume data"}):o.jsx(Ht.Content,{children:d?o.jsxs(Zc,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Wc,{children:[o.jsx(Qr,{value:"agents",children:"Agents"}),o.jsx(Qr,{value:"workflows",children:"Workflows"}),o.jsx(Qr,{value:"tools",children:"Tools"})]}),o.jsx(_s,{value:"agents",children:e.agentData.length>0?o.jsx(foe,{data:e.agentData,rowHrefs:h("agents"),errorHrefs:p("agents"),LinkComponent:i}):o.jsx(Ht.NoData,{message:"No agent data yet"})}),o.jsx(_s,{value:"workflows",children:e.workflowData.length>0?o.jsx(foe,{data:e.workflowData,rowHrefs:h("workflows"),errorHrefs:p("workflows"),LinkComponent:i}):o.jsx(Ht.NoData,{message:"No workflow data yet"})}),o.jsx(_s,{value:"tools",children:e.toolData.length>0?o.jsx(foe,{data:e.toolData,rowHrefs:h("tools"),errorHrefs:p("tools"),LinkComponent:i}):o.jsx(Ht.NoData,{message:"No tool data yet"})})]}):o.jsx(Ht.NoData,{message:"No trace volume data yet"})})]})}async function hoe(e,t,n){const r=await e.getMetricBreakdown({name:[t],groupBy:["entityName","status"],aggregation:"count",orderDirection:"DESC",filters:n}),s=new Map;for(const a of r.groups){const i=a.dimensions.entityName??"unknown",l=a.dimensions.status??"ok",c=bA(s,i,()=>({completed:0,errors:0}));l==="error"?c.errors+=a.value:c.completed+=a.value}return Array.from(s.entries()).map(([a,i])=>({name:a,...i})).sort((a,i)=>i.completed+i.errors-(a.completed+a.errors))}function O1s(){const e=Ye(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([hoe(e,"mastra_agent_duration_ms",t),hoe(e,"mastra_workflow_duration_ms",t),hoe(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const d8={agents:Xu.AGENT,workflows:Xu.WORKFLOW_RUN,tools:Xu.TOOL};function C1s(){const{data:e,isLoading:t,isError:n}=O1s(),{getTracesHref:r,getLogsHref:s}=xA(),{Link:a}=dn();return o.jsx(k1s,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:d8[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:d8[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(XL,{href:r({rootEntityType:d8[i]}),LinkComponent:a}),o.jsx(Mws,{href:s({rootEntityType:d8[i],status:"error"}),LinkComponent:a})]})})}const poe="period",f8="dateFrom",h8="dateTo";function _1s(){const[e,t]=za(),n=e.get(poe),r=Ews(n)?n:"24h",s=g.useMemo(()=>{if(r!=="custom")return;const d=p=>{if(!p)return;const m=new Date(p);return Number.isNaN(m.getTime())?void 0:m},f=d(e.get(f8)),h=d(e.get(h8));if(!(!f&&!h))return{from:f,to:h}},[r,e.toString()]),a=g.useMemo(()=>xws(e),[e.toString()]),i=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d==="24h"?h.delete(poe):h.set(poe,d),d!=="custom"&&(h.delete(f8),h.delete(h8)),h},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d?.from?h.set(f8,d.from.toISOString()):h.delete(f8),d?.to?h.set(h8,d.to.toISOString()):h.delete(h8),h},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return Sws(h,d),h},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,yws(e)))return;const d=WHt();d&&t(f=>{const h=new URLSearchParams(f);for(const[p,m]of d)h.append(p,m);return h},{replace:!0})},[]),o.jsx(jws,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(E1s,{})})}function E1s(){const[e]=za(),{error:t,isLoading:n}=QHt(),{filterTokens:r,setFilterTokens:s}=pY(),[a,i]=g.useState(),{supportsMetrics:l,isInMemory:c,isLoading:u}=fHt(),{data:d,isLoading:f}=dRe(),{data:h,isLoading:p}=lRe(),{data:m,isLoading:v}=uRe(),{data:y,isLoading:b}=cRe(),x=g.useMemo(()=>bws({availableTags:d??[],availableEntityNames:h??[],availableServiceNames:m??[],availableEnvironments:y??[],loading:{tags:f,entityNames:p,serviceNames:v,environments:b}}),[d,h,m,y,f,p,v,b]),[w,k]=g.useState(()=>WHt()!==null),C=g.useCallback(()=>{gws(e),k(!0),Ve.success("Filters setting for Metrics saved")},[e]),_=g.useCallback(()=>{vws(),k(!1),Ve.success("Filters setting for Metrics cleared up")},[]),T=g.useCallback(()=>{s([])},[s]),E=g.useCallback(()=>{const N=r.map(I=>{const A=x.find(P=>P.id===I.fieldId);return A?A.kind==="text"?{fieldId:I.fieldId,value:""}:A.kind==="pick-multi"?A.multi?{fieldId:I.fieldId,value:[]}:{fieldId:I.fieldId,value:"Any"}:A.kind==="multi-select"?{fieldId:I.fieldId,value:[]}:I:I});s(N)},[x,r,s]);return t&&hs(t)?o.jsx(Zn,{children:o.jsx(Ts,{})}):t&&ps(t)?o.jsx(Zn,{children:o.jsx(ks,{resource:"metrics"})}):t?o.jsx(Zn,{children:o.jsx(La,{title:"Failed to load metrics",message:t.message})}):o.jsxs(Lt,{width:"wide",height:"full",children:[o.jsxs(Lt.TopArea,{children:[o.jsx(Lt.Row,{children:o.jsxs(Lt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(Rws,{}),o.jsx(aRe,{fields:x,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(i1s,{isLoading:n,filterFields:x,filterTokens:r,onFilterTokensChange:s,onClear:E,onRemoveAll:T,onSave:C,onRemoveSaved:w?_:void 0,autoFocusFilterFieldId:a})]}),u?null:l?o.jsxs("div",{className:"grid content-start gap-8 pb-10",children:[c&&o.jsx(Rn,{variant:"info",title:"Metrics are not persisted",children:o.jsx(Rn.Message,{children:"This project uses in-memory storage for observability. Metrics will be lost on every server restart. For persistent metrics, switch the observability storage to ClickHouse, DuckDB, Postgres v-next, or Spanner."})}),o.jsxs(o0e,{children:[o.jsx(t1s,{}),o.jsx(n1s,{}),o.jsx(r1s,{}),o.jsx(s1s,{}),o.jsx(a1s,{})]}),o.jsxs(o0e,{children:[o.jsx(u1s,{}),o.jsx(p1s,{}),o.jsx(S1s,{}),o.jsx(Yws,{}),o.jsx(C1s,{}),o.jsx(Hws,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx(Mc,{}),titleSlot:"Metrics are not available with your current storage",descriptionSlot:"Metrics require ClickHouse, DuckDB, Postgres v-next, Spanner, or in-memory storage for observability. Other relational databases (LibSQL, MSSQL) and document stores (MongoDB) do not support metrics collection. To enable metrics on an existing project, switch the observability storage in the Mastra configuration.",actionSlot:o.jsxs(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(ta,{})]})})})]})}const T1s=50;function j1s(){const{paths:e}=dn(),{isCmsAvailable:t}=kS(),[n,r]=g.useState(""),[s,a]=g.useState(0),{data:i,isLoading:l,error:c,isPlaceholderData:u}=vUt({page:s,perPage:T1s}),d=i?.promptBlocks??[],f=i?.hasMore??!1,h=g.useCallback(()=>{u||a(v=>v+1)},[u]),p=g.useCallback(()=>{u||a(v=>Math.max(0,v-1))},[u]),m=g.useCallback(v=>{r(v),a(0)},[]);return c&&hs(c)?o.jsx(Zn,{children:o.jsx(Ts,{})}):c&&ps(c)?o.jsx(Zn,{children:o.jsx(ks,{resource:"prompt blocks"})}):c?o.jsx(Zn,{children:o.jsx(La,{title:"Failed to load prompt blocks",message:c.message})}):d.length===0&&!l&&s===0?o.jsx(Zn,{children:o.jsx(kls,{})}):o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(cd,{onSearch:m,label:"Filter prompts",placeholder:"Filter by name or description"})}),t&&o.jsxs(ie,{as:Da,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(_r,{}),"Create Prompt"]})]})}),o.jsx(Sls,{promptBlocks:d,isLoading:l,search:n,currentPage:s,hasMore:f,onNextPage:h,onPrevPage:p})]})}function N1s(){return o.jsx(Lt,{width:"narrow",children:o.jsx(Lt.MainArea,{children:o.jsx(los,{children:o.jsx(Dxe,{})})})})}const I1s=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:SKt,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:Oct,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:ta,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:t3,href:"https://discord.gg/BTYqqHKUrf",external:!0},{title:"Share with your team",description:"Running Mastra Studio locally? Deploy to the cloud so your team can collaborate.",icon:Nct,href:"https://mastra.ai/cloud",external:!0},{title:"Talk to our Sales team",description:"Get a custom demo, discuss on-prem deployments, and how we can help you accelerate getting agents into production.",icon:Cct,href:"https://mastra.ai/contact?ref=studio",external:!0}];function A1s(){return o.jsx(Lt,{width:"narrow",children:o.jsx(Lt.MainArea,{children:o.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:I1s.map(e=>o.jsxs("a",{href:e.href,...e.external?{target:"_blank",rel:"noreferrer"}:{},className:"group border-border1 bg-surface2 hover:border-accent1 hover:bg-surface3 flex flex-col gap-3 rounded-lg border p-5 transition-colors",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsx(e.icon,{className:"text-icon3 group-hover:text-accent1 h-5 w-5 transition-colors"}),o.jsx("span",{className:"text-ui-md text-text1 font-medium",children:e.title}),e.external&&o.jsx(ta,{className:"text-icon3 ml-auto h-3.5 w-3.5 opacity-0 transition-opacity group-hover:opacity-100"})]}),o.jsx("p",{className:"text-ui-sm text-text3 leading-relaxed",children:e.description})]},e.href))})})})}function R1s(){const{data:e={},isLoading:t,error:n}=up(),[r,s]=g.useState(""),[a,i]=g.useState("all");if(n&&hs(n))return o.jsx(Zn,{children:o.jsx(Ts,{})});if(n&&ps(n))return o.jsx(Zn,{children:o.jsx(ks,{resource:"scorers"})});if(n)return o.jsx(Zn,{children:o.jsx(La,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(Zn,{children:o.jsx(pVr,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(gVr,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(hVr,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}function P1s(){const{scorerId:e}=fr(),[t,n]=za(),r=t.get("scoreId")??void 0,[s,a]=g.useState(r),[i,l]=g.useState(!1),c=qr(),[u,d]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:f,error:h}=Zqr(e),{data:p={},isLoading:m,error:v}=Bm(),{isLoading:y,error:b}=Xy(),{data:x=[],isLoading:w,error:k,isFetchingNextPage:C,hasNextPage:_,setEndOfListElement:T}=Wqr({scorerId:e,entityId:u?.value==="all"?void 0:u?.value,entityType:u?.type==="ALL"?void 0:u?.type}),E=g.useMemo(()=>f?.agentIds?.filter(R=>p[R]).map(R=>({value:R,label:p[R].name,type:"AGENT"}))||[],[f?.agentIds,p]),N=g.useMemo(()=>f?.workflowIds?.map(R=>({value:R,label:R,type:"WORKFLOW"}))||[],[f?.workflowIds]),I=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...E,...N],[E,N]),A=t.get("entity")??"all",P=I.find(R=>R.value===A);P&&P.value!==u?.value&&d(P),g.useEffect(()=>{if(h){const R=h instanceof Error?h.message:"Failed to load scorer";Ve.error(`Error loading scorer: ${R}`)}},[h]),g.useEffect(()=>{if(v){const R=v instanceof Error?v.message:"Failed to load agents";Ve.error(`Error loading agents: ${R}`)}},[v]),g.useEffect(()=>{if(b){const R=b instanceof Error?b.message:"Failed to load workflows";Ve.error(`Error loading workflows: ${R}`)}},[b]);const L=R=>{R?.value&&n(U=>{const Z=new URLSearchParams(U);return Z.set("entity",R.value),Z})};g.useEffect(()=>{const R=t.get("scoreId")??void 0;if(R===s)return;if(!R){a(void 0);return}x.find(Z=>Z.id===R)&&a(R)},[t,x]);const D=g.useCallback(R=>{a(R||void 0),n(U=>{const Z=new URLSearchParams(U);return R?Z.set("scoreId",R):Z.delete("scoreId"),Z})},[n]);if(!f)return null;const B=hs(h)||hs(v)||hs(b),H=h&&ps(h),q=!B&&!H&&(h||v||b),z=!w&&x.length===0,V=u?.value!=="all",M=f?.scorer?.source==="stored"?o.jsx(By,{owner:"scorer-detail",children:o.jsxs(ie,{variant:"default",as:Da,to:`/cms/scorers/${e}/edit`,size:"sm",children:[o.jsx(Yh,{})," Edit"]})}):null,G=e?o.jsx(cY,{open:i,onOpenChange:l,initialScorerIds:[e],onSuccess:R=>{c(`/experiments/${R}`)}}):null;if(B||H||q||z&&!V){const R=(h instanceof Error?h.message:void 0)??(v instanceof Error?v.message:void 0)??(b instanceof Error?b.message:void 0)??"An unexpected error occurred";return o.jsxs(Lt,{width:"wide",height:"full",className:"grid-rows-[1fr]",children:[M,o.jsx(Lt.MainArea,{isCentered:!0,children:B?o.jsx(Ts,{}):H?o.jsx(ks,{resource:"scorers"}):q?o.jsx(La,{title:"Failed to load scorer",message:R}):o.jsx(Lqr,{onRunExperiment:()=>l(!0)})}),G]})}return o.jsxs(Lt,{width:"wide",height:"full",children:[M,o.jsx(Lt.TopArea,{children:o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx(zqr,{selectedEntity:u,entityOptions:I,onEntityChange:L,onReset:()=>{n(R=>{const U=new URLSearchParams(R);return U.set("entity","all"),U})},isLoading:w||m||y}),o.jsxs(ie,{variant:"primary",onClick:()=>l(!0),children:[o.jsx(Dc,{}),"Run Experiment"]})]})}),o.jsx(Dqr,{scores:x,isLoading:w,selectedScoreId:s,isFetchingNextPage:C,hasNextPage:_,setEndOfListElement:T,onScoreClick:D,errorMsg:k?.message}),G]})}const $1s=uo("flex min-w-0 flex-col",{variants:{variant:{default:"gap-3 sm:flex-row sm:items-center sm:justify-between",factory:"gap-2 px-4 py-3 lg:flex-row lg:items-center lg:justify-between lg:gap-4"}},defaultVariants:{variant:"default"}}),M1s=uo("flex min-w-0 flex-col",{variants:{variant:{default:"",factory:"gap-0.5"}},defaultVariants:{variant:"default"}}),Jtt=uo("",{variants:{variant:{default:"text-sm font-medium",factory:"text-ui-md leading-ui-md text-neutral5"}},defaultVariants:{variant:"default"}}),D1s=uo("flex flex-col gap-0.5",{variants:{variant:{default:"text-sm text-neutral3",factory:"text-ui-sm text-neutral3"}},defaultVariants:{variant:"default"}});function L1s({label:e,description:t,htmlFor:n,variant:r,className:s,children:a}){return o.jsxs("div",{className:K($1s({variant:r}),s),"data-slot":"settings-row",children:[o.jsxs("div",{className:M1s({variant:r}),children:[n?o.jsx(Dt,{htmlFor:n,className:Jtt({variant:r}),children:e}):o.jsx("span",{className:Jtt({variant:r}),children:e}),t&&o.jsx("div",{className:D1s({variant:r}),children:t})]}),a]})}const JHt=[{value:"dark",label:"Dark",Icon:wJt},{value:"light",label:"Light",Icon:Hen},{value:"system",label:"System",Icon:Uct}],F1s=e=>JHt.some(t=>t.value===e);function z1s({option:e}){const{Icon:t}=e;return o.jsxs("span",{className:"inline-flex max-w-full min-w-0 items-center gap-2",children:[o.jsx(t,{"aria-hidden":"true",className:"h-4 w-4 shrink-0 opacity-70"}),o.jsx("span",{className:"min-w-0 truncate",children:e.label})]})}const B1s=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=PH(),{theme:r,setTheme:s}=a_();return o.jsx(Lt,{width:"narrow",children:o.jsxs(Lt.MainArea,{className:"mt-6 flex flex-col gap-5",children:[o.jsx(uxe,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(L1s,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(la,{value:r,onValueChange:a=>{F1s(a)&&s(a)},children:[o.jsx(ua,{id:"theme",className:"w-full sm:w-48",children:o.jsx(ca,{className:"inline-flex max-w-full min-w-0 items-center"})}),o.jsx(da,{children:JHt.map(a=>o.jsx(xr,{value:a.value,children:o.jsx(z1s,{option:a})},a.value))})]})})}),o.jsx(uxe,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(V4t,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function U1s(){const[e]=za(),t=qr(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(qHt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}function q1s(e){return e.replace(/\/$/,"").split("/").pop()}function mY({children:e,className:t}){return o.jsx("div",{className:K("border border-border1 rounded-lg mt-12 py-8 lg:min-h-[25rem] transition-height px-4 lg:px-12",t),children:e})}function V1s({templates:e,linkComponent:t,className:n,isLoading:r}){const s=t||"a";return r?o.jsx("div",{className:K("grid gap-y-4",n),children:Array.from({length:5}).map((a,i)=>o.jsx("div",{className:"bg-surface3 h-16 animate-pulse rounded-lg"},i))}):o.jsx("div",{className:K("grid gap-y-4",n),children:e.map(a=>{const i=a?.agents||a?.tools||a?.networks||a?.workflows||a?.mcp;return o.jsxs("article",{className:K("border border-border1 rounded-lg overflow-hidden w-full grid grid-cols-[1fr_auto] bg-surface3 transition-colors hover:bg-surface4"),children:[o.jsxs(s,{to:`/templates/${a.slug}`,className:K("grid [&:hover_p]:text-neutral5",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":a.imageURL}),children:[a.imageURL&&o.jsx("div",{className:K("overflow-hidden"),children:o.jsx("div",{className:"thumb transition-scale h-full w-full bg-cover duration-150",style:{backgroundImage:`url(${a.imageURL})`}})}),o.jsxs("div",{className:K("grid py-3 px-6 w-full gap-0.5","[&_svg]:w-[1em] [&_svg]:h-[1em] [&_svg]:text-neutral3"),children:[o.jsx("h2",{className:"text-ui-lg text-neutral5",children:a.title}),o.jsx("p",{className:"text-ui-md text-neutral4 transition-colors duration-500",children:a.description}),o.jsxs("div",{className:"text-neutral3 text-ui-md mt-3 hidden flex-wrap items-center gap-4 2xl:flex",children:[i&&o.jsxs("ul",{className:K("flex gap-4 text-ui-md text-neutral3 m-0 p-0 list-none","[&>li]:flex [&>li]:items-center [&>li]:gap-0.5 text-neutral4"),children:[a?.agents&&a.agents.length>0&&o.jsxs("li",{children:[o.jsx(Ri,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(Bf,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(Vct,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(fI,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(N_,{})," ",a.mcp.length]})]}),i&&a.supportedProviders&&o.jsx("small",{children:"|"}),o.jsx("div",{className:"text-neutral3 flex items-center gap-4",children:a.supportedProviders.map(l=>o.jsx("span",{className:"",children:l},l))})]})]})]}),o.jsx("a",{href:a.githubUrl,className:K("group items-center gap-2 text-ui-md ml-auto pr-4 hidden","lg:flex"),target:"_blank",rel:"noopener noreferrer",children:o.jsxs("span",{className:"bg-surface1 group-hover:bg-surface2 text-neutral3 group-hover:text-neutral5 flex items-center gap-2 rounded px-2 py-1 transition-colors",children:[o.jsx(hG,{})," ",q1s(a.githubUrl)]})})]},a.slug)})})}function H1s({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:s,onProviderChange:a,searchTerm:i,onSearchChange:l,onReset:c,className:u,isLoading:d}){return d?o.jsxs("div",{className:K("h-[6.5rem] flex items-center gap-8","[&>div]:bg-surface3 [&>div]:w-48 [&>div]:h-8 [&>div]:animate-pulse",u),children:[o.jsx("div",{})," ",o.jsx("div",{})," ",o.jsx("div",{})]}):o.jsxs("div",{className:K("flex flex-wrap mx-auto sticky top-0 gap-4 bg-surface2 py-8",u),children:[o.jsx(wC,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(Cm,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(Cm,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(ie,{onClick:c,children:["Reset ",o.jsx(or,{})]})]})}function W1s(){const{data:e,isLoading:t}=Mrr(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[a,i]=g.useState("all"),[l,c]=g.useState("all"),[u,d]=g.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(x=>{f.push({value:x,label:x})});const h=[{value:"all",label:"Any provider"}];(s||[]).forEach(x=>{h.push({value:x,label:x})});const p=(x,w)=>{w==="tag"?i(x):w==="provider"&&c(x)},m=x=>{d(x)},v=()=>{i("all"),c("all"),d("")},y=n.filter(x=>!(u&&!x.title.toLowerCase().includes(u)&&!x.description.toLowerCase().includes(u)||a!=="all"&&!x.tags.includes(a)||l!=="all"&&!x.supportedProviders.includes(l))),b=u||a!=="all"||l!=="all";return o.jsxs(vs,{children:[o.jsx(UH,{children:o.jsxs(ESe,{children:[o.jsx(Qe,{children:o.jsx(fy,{})}),"Templates"]})}),o.jsxs("div",{className:K("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(H1s,{selectedTag:a,onTagChange:x=>p(x,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:x=>p(x,"provider"),providerOptions:h,searchTerm:u,onSearchChange:m,onReset:b?v:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(V1s,{templates:y,linkComponent:Da,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const Z1s="1.65.0-alpha.6";function G1s({errorMsg:e,validationErrors:t}){const n=typeof e=="string"?e:e!=null?String(e):void 0,r=n?.includes("Invalid schema for function"),s=n?.includes("validation issue")||t&&t.length>0,a=()=>s?"Template installation completed but some validation issues remain. The template may still be functional, but you should review and fix these issues.":r?"There was an issue with the AI model configuration. This may be related to the selected model or AI SDK version compatibility.":"An unexpected error occurred during template installation.",i=()=>s?{icon:o.jsx(uc,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(MKt,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(mY,{className:"text-neutral3 mb-8 content-center space-y-4",children:[o.jsxs("div",{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[l,o.jsxs("div",{className:"space-y-2 text-center",children:[o.jsx("p",{className:"text-ui-md text-neutral5 font-medium",children:c}),o.jsx("p",{className:"text-ui-md text-neutral3",children:a()})]})]}),t&&t.length>0&&o.jsxs("details",{className:"text-xs",children:[o.jsxs("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:["Show Validation Issues (",t.length,")"]}),o.jsx("div",{className:"mt-4 max-h-60 space-y-2 overflow-auto rounded bg-gray-100 p-3 text-left text-xs dark:bg-gray-800",children:t.map((u,d)=>o.jsxs("div",{className:"border-l-2 border-red-400 pl-2",children:[o.jsx("div",{className:"font-medium text-red-600 dark:text-red-400",children:u.type==="typescript"?"🔴 TypeScript Error":"⚠️ Lint Error"}),o.jsx("div",{className:"mt-1 font-mono text-xs wrap-break-word whitespace-pre-wrap text-gray-700 dark:text-gray-300",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-xs",children:[o.jsx("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:"Show Details"}),o.jsx("div",{className:"mt-4 max-h-60 overflow-auto rounded bg-gray-100 p-3 text-left font-mono text-xs dark:bg-gray-800",children:o.jsx("div",{className:"wrap-break-word whitespace-pre-wrap",children:n})})]})]})}function Q1s({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:s,handleInstallTemplate:a,handleVariableChange:i,isLoadingEnvVars:l,isInstalling:c,defaultModelProvider:u,defaultModelId:d,onModelUpdate:f}){return o.jsx(mY,{children:o.jsxs("div",{className:"mx-auto my-4 grid max-w-[40rem] gap-8 p-4 lg:p-8",children:[o.jsxs("h2",{className:K("text-neutral4 text-header-sm font-semibold flex items-center gap-2","[&>svg]:w-[1.2em] [&_svg]:h-[1.2em] [&_svg]:opacity-70"),children:["Install Template ",o.jsx(Hct,{})]}),o.jsx(Cm,{name:"template-provider",options:e,label:"Template AI Model Provider",onValueChange:n,value:t,placeholder:"Select",layout:"horizontal"}),t&&Object.entries(r||{}).length>0&&o.jsxs(o.Fragment,{children:[o.jsx("h3",{className:"text-neutral3 text-ui-md",children:"Set required Environmental Variables"}),o.jsx("div",{className:"grid grid-cols-[1fr_1fr] items-start gap-4",children:l?o.jsxs("div",{className:K("flex items-center justify-center col-span-2 text-neutral3 text-ui-sm gap-4","[&_svg]:opacity-50 [&_svg]:w-[1.1em] [&_svg]:h-[1.1em]","animate-in fade-in duration-300"),children:[o.jsx(Vt,{})," Loading variables..."]}):Object.entries(r).map(([h,p])=>o.jsxs(g.Fragment,{children:[o.jsx(ep,{name:`env-${h}`,labelIsHidden:!0,label:"Key",value:h,disabled:!0,className:"w-full"}),o.jsx(ep,{name:h,labelIsHidden:!0,label:"Value",value:p,onChange:i,errorMsg:s.includes(h)?"Value is required.":"",autoComplete:"off",className:"w-full"})]},h))}),o.jsxs("div",{className:"border-border1 relative mt-3.5 border-t pt-12",children:[o.jsx("div",{className:"bg-surface2 text-ui-sm text-neutral3 absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full",children:"And"}),o.jsx("h3",{className:"text-neutral4 text-ui-lg",children:"Set AI Model for Template Installation"}),o.jsx("p",{className:"text-neutral3 text-ui-md mt-2 mb-8",children:"This model will be used by the workflow to process and install the template"}),o.jsx(q4t,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(ie,{className:K("flex items-center gap-2 mt-4 justify-center text-ui-md w-full bg-surface5 min-h-10 rounded-lg text-neutral5 hover:bg-surface6 transition-colors","[&>svg]:w-[1.1em] [&_svg]:h-[1.1em] [&_svg]:text-neutral5"),onClick:a,disabled:!t||!u||!d||s.length>0||c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(Vt,{className:"h-4 w-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(Fd,{})]})})]})})}function Y1s({title:e,description:t,githubUrl:n,isLoading:r,infoData:s,templateSlug:a}){const i=a?`feat/install-template-${a}`:"feat/install-template-[slug]";return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:K("grid mt-8 items-center"),children:o.jsxs("div",{className:K("text-header-lg flex items-center gap-3","[&>svg]:w-[1.2em] [&>svg]:h-[1.2em] [&>svg]:opacity-50",{"[&>svg]:opacity-20":r}),children:[o.jsx(fy,{}),o.jsx("h2",{className:K({"bg-surface4 flex rounded-lg min-w-[50%]":r}),children:r?o.jsx(o.Fragment,{children:" "}):e})]})}),o.jsxs("div",{className:"grid gap-x-24 lg:grid-cols-[1fr_1fr]",children:[o.jsxs("div",{className:"grid",children:[o.jsx("p",{className:K("mb-4 text-ui-md text-neutral4 mt-2 leading-7",{"bg-surface4 rounded-lg ":r}),children:r?o.jsx(o.Fragment,{children:" "}):t}),!r&&a&&o.jsxs("div",{className:K("bg-surface2 border border-surface4 rounded-lg p-4 mb-4","flex items-start gap-3"),children:[o.jsx("div",{className:"mt-0.5 shrink-0",children:o.jsx(Em,{className:"h-[1.1em] w-[1.1em] text-blue-500"})}),o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(T0e,{className:"text-neutral4 h-[1em] w-[1em]"}),o.jsx("span",{className:"text-ui-md text-neutral5 font-medium",children:"A new Git branch will be created"})]}),o.jsxs("div",{className:"text-ui-sm text-neutral4 space-y-1",children:[o.jsxs("div",{children:[o.jsx("span",{className:"font-medium",children:"Branch name:"})," ",o.jsx("code",{className:"bg-surface3 text-ui-sm rounded px-1.5 py-0.5 font-mono",children:i})]}),o.jsx("div",{children:"This ensures safe installation with easy rollback if needed. Your main branch remains unchanged."})]})]})]}),n&&o.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"text-neutral3 text-ui-md hover:text-neutral5 mt-auto flex items-center gap-2",children:[o.jsx(hG,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(xje,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function ent(e){switch(e){case"running":return o.jsx(Vt,{size:"sm","aria-hidden":!0});case"success":return o.jsx(Ur,{"aria-hidden":!0});case"failed":return o.jsx(or,{"aria-hidden":!0});default:return null}}function K1s(){return o.jsx("svg",{viewBox:"0 0 24 24",className:"text-neutral2","aria-hidden":!0,children:o.jsx("circle",{cx:"12",cy:"12",r:"8.5",pathLength:"48",fill:"none",stroke:"currentcolor",strokeWidth:"2.8",strokeLinecap:"round",strokeDasharray:"3 3"})})}function X1s({status:e,variant:t}){return t==="plain"?o.jsx("span",{className:K("flex size-4 items-center justify-center self-center [&>svg]:size-4",Yr.colors,{"[&>svg]:text-positive1":e==="success","[&>svg]:text-negative1":e==="failed"}),children:e==="pending"?o.jsx(K1s,{}):ent(e)}):o.jsx("span",{className:K("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",Yr.colors,Yr.transform,Yr.shadow,{"[&>svg]:text-notice-success-fg":e==="success","[&>svg]:text-notice-destructive-fg":e==="failed","border border-dashed border-neutral2":e==="pending","[&>svg]:size-4":e!=="running","bg-accent1Dark shadow-glow-accent1":e==="success","bg-accent2Dark shadow-glow-accent2":e==="failed","scale-110":e==="success"||e==="failed"}),children:ent(e)})}function J1s({step:e,isActive:t,position:n,variant:r="default"}){return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none",Yr.colors,{"border border-transparent":r==="default","border-dashed border-neutral2 bg-surface3":t&&r==="default"}),children:[o.jsxs("div",{className:"grid min-w-0 grid-cols-[auto_1fr] gap-2",children:[o.jsxs("span",{className:K("flex min-w-6 justify-end text-ui-md",Yr.colors,{"text-neutral5":t||e.status==="success","text-neutral3":!t&&e.status!=="success"}),children:[n,"."]}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("h4",{className:K("text-ui-md",Yr.colors,{"text-neutral5":t||e.status==="success","text-neutral3":!t&&e.status!=="success"}),children:e.title}),e.description&&o.jsx("p",{className:K("-mt-0.5 text-ui-md text-neutral2",{truncate:r==="plain"}),children:e.description})]})]}),o.jsx(X1s,{status:e.status,variant:r})]})}function eSs({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:K(n),children:t.map((r,s)=>o.jsx(J1s,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function tSs({steps:e}){const t=e.length,n=e.filter(r=>r.status==="success").length;return o.jsxs("div",{className:"flex w-full flex-col content-center justify-center gap-4",children:[o.jsx("div",{className:"grid w-full grid-cols-[0_repeat(9,1fr)]",children:e.map((r,s)=>o.jsx("div",{className:K("relative flex h-8 items-center justify-end",Yr.colors,{"bg-accent1Dark":r.status==="success"&&e?.[s-1]?.status==="success"}),children:o.jsx("div",{className:K("absolute right-0 z-10 flex size-8 translate-x-1/2 items-center justify-center self-center rounded-full bg-surface3 text-ui-sm font-bold text-neutral3 motion-reduce:transition-none",Yr.colors,Yr.transform,Yr.shadow,{"border border-dashed border-neutral2":r.status==="pending","bg-accent1Dark text-notice-success-fg shadow-glow-accent1 scale-110":r.status==="success","bg-accent2Dark text-notice-destructive-fg shadow-glow-accent2 scale-110":r.status==="failed"}),children:r.status==="running"?o.jsx(Vt,{}):s+1})},r.id))}),o.jsxs("div",{className:K("text-center text-xs text-neutral3",Yr.colors),children:[n," of ",t," steps completed"]})]})}function nSs({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",a=t?.payload?.workflowState,i=t?.payload?.currentStep,l=t?.error,c=a?.steps||{},u=Object.keys(c).length>0,d=v=>v==="input"||v.endsWith(".input")||v.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(v)||/[0-9a-f]{8,}/.test(v)?!1:r?.allSteps?v in r.allSteps:!0,f=Object.entries(c).filter(([v,y])=>d(v)),h=f.length,p=()=>{switch(s){case"initializing":return"Preparing template installation...";case"processing":return`Installing ${e} template`;case"completed":return"Template installation completed!";case"error":return"Template installation failed";default:return"Installing template..."}},m=f.map(([v,y])=>({id:v,status:y?.status,description:y?.description,title:v.charAt(0).toUpperCase()+v.slice(1).replace(/-/g," "),isActive:i?.id===v}));return o.jsxs(mY,{className:"text-neutral3 mb-8 content-center space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h3",{className:"text-neutral5 text-lg font-semibold",children:p()}),(t?.runId||n)&&o.jsxs("div",{className:"text-ui-sm text-neutral3 mt-2",children:["Run ID: ",t?.runId??n]})]}),u&&h>0&&!["error"].includes(s)&&o.jsx("div",{className:"mx-auto w-full max-w-[30rem] px-6",children:o.jsx(tSs,{steps:m})}),l&&s==="error"&&o.jsxs("div",{className:K("rounded-lg text-neutral5 p-6 flex items-center gap-3 text-ui-md bg-red-500/10","[&>svg]:w-6 [&>svg]:h-6 [&>svg]:opacity-70 [&>svg]:text-red-500"),children:[o.jsx(RJt,{}),l||"Something went wrong"]}),u&&o.jsx(eSs,{steps:m,currentStep:i,className:"pb-4"}),!u&&s==="initializing"&&o.jsxs("div",{className:"text-neutral3 grid justify-items-center gap-4 text-center text-sm",children:[o.jsx(Vt,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function rSs({name:e,installedEntities:t}){return o.jsxs(mY,{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(Hct,{}),o.jsx("h2",{className:"text-header-md",children:"Done!"}),o.jsxs("p",{className:"text-ui-md text-neutral3 text-center",children:["The ",o.jsx("b",{className:"text-neutral4",children:e})," template has been successfully installed.",t&&t.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("br",{})," Installed entities are listed below."]})]}),t&&t.length>0&&o.jsx(xje,{data:t})]})}function sSs(){const{templateSlug:e}=fr(),[t,n]=za(),[r,s]=g.useState(""),[a,i]=g.useState(""),[l,c]=g.useState(""),[u,d]=g.useState({}),[f,h]=g.useState([]),[p,m]=g.useState(null),[v,y]=g.useState(!1),[b,x]=g.useState(""),[w,k]=g.useState(!1),[C,_]=g.useState(!1),[T,E]=g.useState([]),{data:N,isLoading:I}=Drr({repoOrSlug:e,owner:"mastra-ai"}),P=Z1s?.includes("beta")??!1?"beta":"main",{data:L,isLoading:D}=Lrr({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:P}),{data:B,isLoading:H}=Frr(),{mutateAsync:q,isPending:z}=zrr(),{mutateAsync:V}=Brr(),{streamInstall:M,streamResult:G,isStreaming:F}=qrr(B),{observeInstall:R,streamResult:U,isStreaming:Z}=Vrr(B);g.useEffect(()=>{const ne=t.get("runId");ne&&!v&&!p&&!F&&!Z&&(console.info("🔄 Checking completed run after hot reload:",{runId:ne}),x(ne),V({runId:ne}).then(se=>{const ce=se.snapshot;if(ce?.status==="success"&&ce?.result?.success)y(!0);else if(ce?.result?.success===!1)if(ce?.result?.validationResults&&!ce?.result?.validationResults?.valid&&ce?.result?.validationResults?.remainingErrors>0){const{remainingErrors:be,errors:he}=ce.result.validationResults,xe=`Template installation completed but ${be} validation issue${be>1?"s":""} remain unresolved.`;m(xe),E(he||[])}else{const be=ce?.result?.message||ce?.result?.error||"Template installation failed";m(typeof be=="string"?be:String(be))}}).catch(se=>{console.error("❌ Failed to fetch run details:",se),m("Failed to retrieve installation status after reload")}))},[t,v,p,F,Z,V]),g.useEffect(()=>{const ne=t.get("runId"),se=t.get("resume"),ce=t.get("provider");if(ne&&se==="true"&&ce&&!F&&!Z&&!w&&!C&&B){x(ne),k(!0);try{V({runId:ne}).then(le=>{if(le.snapshot?.status==="running")return R.mutateAsync({runId:ne})}).then(()=>{n(le=>{const be=new URLSearchParams(le);return be.delete("resume"),be})}).catch(le=>{console.error("❌ Failed to resume template installation:",le),le.message?.includes("404")||le.message?.includes("not found")?m("Template installation run not found. It may have expired or been completed."):m("Failed to resume template installation. Please try again.")})}catch(le){console.error("❌ Auto-resume failed with error:",le),m("Failed to resume template installation. Please refresh and try again.")}}},[t,e,F,Z,w,C,B,V,R,n]);const Y=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],te=[{key:"tools",label:"Tools",value:N?.tools?.length?N.tools.map(ne=>ne).join(", "):"n/a",icon:o.jsx(Bf,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(ne=>ne).join(", "):"n/a",icon:o.jsx(Ri,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(ne=>ne).join(", "):"n/a",icon:o.jsx(fI,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(Eg,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(dI,{})}],J=[{...te[0]},{...te[1]},{...te[2]}].filter(ne=>ne.value!=="n/a");g.useEffect(()=>{L&&d(L)},[L]),g.useEffect(()=>{const ne=G||U;ne?.phase==="error"&&ne?.error&&m(typeof ne.error=="string"?ne.error:String(ne.error))},[G?.phase,G?.error,U?.phase,U?.error]);const ee=ne=>{s(ne)},re=async ne=>(i(ne.provider),c(ne.modelId),{message:"Model updated successfully"}),ae=async()=>{const ne=Object.entries(u).reduce((se,[ce,le])=>(le===""&&se.push(ce),se),[]);if(ne.length>0){h(ne);return}if(N){m(null),y(!1),x(""),_(!0);try{const ce={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:P,slug:N.slug,variables:u},{runId:le}=await q({});x(le),n(be=>{const he=new URLSearchParams(be);return he.set("runId",le),he.set("resume","true"),he.set("provider",r||"openai"),he}),await M.mutateAsync({inputData:ce,selectedModel:{provider:a,modelId:l},runId:le})}catch(se){_(!1),m(se?.message||"Template installation failed"),console.error("Template installation failed",se)}}},X=ne=>{const{name:se,value:ce}=ne.target;ce.trim()===""?h(le=>[...le,se]):h(le=>le.filter(be=>be!==se)),d(le=>({...le,[se]:ce}))};return o.jsx(vs,{children:o.jsx("div",{className:K("w-full lg:px-12 h-full overflow-y-scroll"),children:o.jsxs("div",{className:"mx-auto grid w-full max-w-[80rem] gap-y-4 p-6",children:[o.jsx(Y1s,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:te,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(F||Z)&&o.jsx(nSs,{name:N.title,streamResult:Z?U:G,runId:b,workflowInfo:B}),v&&o.jsx(rSs,{name:N.title,installedEntities:J,linkComponent:Da}),p&&o.jsx(G1s,{errorMsg:p,validationErrors:T.length>0?T:G?.validationResults?.errors||U?.validationResults?.errors}),!F&&!Z&&!v&&!p&&o.jsx(Q1s,{providerOptions:Y,selectedProvider:r,onProviderChange:ee,variables:u,setVariables:d,errors:f,setErrors:h,handleInstallTemplate:ae,handleVariableChange:X,isLoadingEnvVars:D||H,isInstalling:z,defaultModelProvider:a,defaultModelId:l,onModelUpdate:re})]})]})})})}const aSs=()=>{const{toolId:e,agentId:t}=fr();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(Cos,{toolId:e,agentId:t})})},iSs=()=>{const{toolId:e}=fr();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(iws,{toolId:e})})};function oSs(){const{data:e,isLoading:t,error:n}=Xy(),[r,s]=g.useState("");return n&&hs(n)?o.jsx(Zn,{children:o.jsx(Ts,{})}):n&&ps(n)?o.jsx(Zn,{children:o.jsx(ks,{resource:"workflows"})}):n?o.jsx(Zn,{children:o.jsx(La,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(Zn,{children:o.jsx(hYr,{})}):o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(cd,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsxs(ie,{as:Da,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(sI,{}),"Schedules"]})]})}),o.jsx(fYr,{workflows:e||{},isLoading:t,search:r})]})}const lSs={active:"bg-accent1",paused:"bg-accent3"},cSs={active:"text-accent1",paused:"text-accent3"},eWt=({status:e})=>o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${lSs[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${cSs[e]}`,children:e})]}),Ej=e=>!e||e<=0?"—":new Date(e).toLocaleString(),h2=e=>{if(!e||e<=0)return"—";const t=e-Date.now(),n=Math.abs(t),r=Math.floor(n/1e3);if(r<60)return t>=0?`in ${r}s`:`${r}s ago`;const s=Math.floor(r/60);if(s<60)return t>=0?`in ${s}m`:`${s}m ago`;const a=Math.floor(s/60);if(a<24)return t>=0?`in ${a}h`:`${a}h ago`;const i=Math.floor(a/24);return t>=0?`in ${i}d`:`${i}d ago`};function tWt({status:e}){const{icon:t,color:n}=uSs(e);return o.jsxs("span",{className:`text-ui-sm inline-flex items-center gap-1.5 whitespace-nowrap ${n}`,children:[o.jsx("span",{className:"inline-flex shrink-0 items-center","aria-hidden":!0,children:t}),o.jsx("span",{children:e})]})}function uSs(e){switch(e){case"success":return{icon:o.jsx(Ur,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(or,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(Vt,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(EV,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(Mc,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(c1,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const tnt="auto auto auto auto 1fr";function dSs(e){if(e===void 0)return"—";if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;const t=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return`${t}m ${n}s`}function fSs(e){const t=Math.abs(e),n=e<0?"-":"";return t<1e3?`${n}${t}ms`:t<6e4?`${n}${(t/1e3).toFixed(1)}s`:t<36e5?`${n}${(t/6e4).toFixed(1)}m`:`${n}${(t/36e5).toFixed(1)}h`}const hSs=3e4,pSs=5*6e4;function mSs({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=dn(),c=p=>!!(n&&p.runId&&p.outcome!=="failed"),u=e.filter(c).length,{containerRef:d,getRowProps:f}=ao({count:u});let h=-1;return t?o.jsx(Bo,{columns:tnt}):e.length===0?o.jsx(ve,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(pe,{columns:tnt,className:"min-w-0",scrollRef:d,children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{children:"Run"}),o.jsx(pe.TopCell,{children:"Status"}),o.jsx(pe.TopCell,{children:"Started"}),o.jsx(pe.TopCell,{children:"Duration"}),o.jsx(pe.TopCell,{children:" "})]}),e.map(p=>{const m=p.actualFireAt-p.scheduledFireAt,v=fSs(m),y=`Scheduled ${Ej(p.scheduledFireAt)} — published ${Ej(p.actualFireAt)} (drift ${v})`,b=p.outcome==="failed",x=b?p.error:p.run?.error,w=Math.abs(m),k=!b&&w>hSs&&w<=pSs,C=`${p.scheduleId}-${p.runId}-${p.actualFireAt}`,_=c(p);_&&(h+=1);const T=o.jsx("span",{className:_?"text-accent1 text-ui-sm font-mono whitespace-nowrap":"text-neutral3 text-ui-sm font-mono whitespace-nowrap",children:p.runId}),E=o.jsxs(o.Fragment,{children:[o.jsx(pe.Cell,{children:T}),o.jsx(pe.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[b?o.jsxs("span",{className:"text-ui-sm text-accent2 inline-flex items-center gap-1.5 whitespace-nowrap",children:[o.jsx(uc,{size:14}),"publish failed"]}):p.run?o.jsx(tWt,{status:p.run.status}):o.jsx("span",{className:"text-ui-sm text-neutral3 inline-flex items-center gap-1.5 whitespace-nowrap",children:"pending"}),x?o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(uc,{size:14})})}),o.jsx(yn,{children:x})]}):null]})}),o.jsx(pe.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:y,children:h2(p.actualFireAt)}),k?o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(uc,{size:14})})}),o.jsxs(yn,{children:["Published ",v," after the scheduled fire time"]})]}):null]})}),o.jsx(pe.Cell,{children:p.run?o.jsx("span",{children:dSs(p.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(pe.Cell,{children:" "})]});return _?o.jsx(pe.RowLink,{to:l.workflowRunLink(n,p.runId),LinkComponent:i,...f(h),children:E},C):o.jsx(pe.RowStatic,{children:E},C)}),o.jsx(pe.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const gSs=e=>{const t=Ye();return mt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},nnt=25,vSs=e=>{const t=Ye(),{inView:n,setRef:r}=a0(),s=Ly({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:nnt,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<nnt))return u.triggers[u.triggers.length-1].actualFireAt},refetchInterval:u=>(u.state.data?.pages.flatMap(h=>h.triggers)??[]).some(h=>h.run?h.run.status==="pending"||h.run.status==="running"||h.run.status==="waiting":h.outcome==="published")?5e3:!1}),a=s.data?.pages.flatMap(u=>u?.triggers??[])??[],{hasNextPage:i,isFetchingNextPage:l,fetchNextPage:c}=s;return g.useEffect(()=>{n&&i&&!l&&c()},[n,i,l,c]),{...s,data:a,setEndOfListElement:r}},ySs=e=>{const t=Ye(),n=Ar();return Sn({mutationFn:async r=>{if(!e)throw new Error("scheduleId is required");return r==="pause"?t.pauseSchedule(e):t.resumeSchedule(e)},onSuccess:(r,s)=>{n.invalidateQueries({queryKey:["schedule",e]}),n.invalidateQueries({queryKey:["schedules"]}),Ve.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{Ve.error(r.message)}})};function p8({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ve,{variant:"ui-xs",className:"text-neutral4 tracking-wide uppercase",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function bSs(){const{scheduleId:e}=fr(),{paths:t}=dn(),{data:n,error:r}=gSs(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=vSs(e),d=ySs(e);if(r&&hs(r))return o.jsx(Zn,{children:o.jsx(Ts,{})});if(r&&ps(r))return o.jsx(Zn,{children:o.jsx(ks,{resource:"schedules"})});if(r)return o.jsx(Zn,{children:o.jsx(La,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,h=n?.agentId;return o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx(Lt.Row,{className:"justify-end",children:o.jsxs(Lt.Column,{className:"flex justify-end gap-2",children:[o.jsxs(ie,{as:Da,to:t.schedulesLink(),variant:"ghost",children:[o.jsx(bl,{}),"Back to schedules"]}),f?o.jsx(ie,{as:Da,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(ie,{onClick:()=>d.mutate(n.status==="active"?"pause":"resume"),disabled:d.isPending,"data-testid":"schedule-toggle-button",children:n.status==="active"?o.jsxs(o.Fragment,{children:[o.jsx($V,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(Dc,{}),"Resume"]})}):null]})})}),n?o.jsxs("div",{className:"grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-6 overflow-hidden",children:[o.jsxs("div",{className:"border-border1 flex h-fit flex-col gap-4 rounded-md border p-4",children:[o.jsx(p8,{label:h?"Agent":"Workflow",children:f?o.jsx(Da,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):h?o.jsx(Da,{to:t.agentLink(h),className:"text-accent1 hover:underline",children:h}):"—"}),o.jsxs(p8,{label:"Cron",children:[o.jsx("code",{className:"text-ui-md font-mono",children:n.cron}),n.timezone?o.jsx("span",{className:"text-neutral4 text-ui-sm ml-2",children:n.timezone}):null]}),o.jsx(p8,{label:"Status",children:o.jsx(eWt,{status:n.status})}),o.jsx(p8,{label:"Next fire",children:o.jsx("span",{title:Ej(n.nextFireAt),children:h2(n.nextFireAt)})})]}),o.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[o.jsx(ve,{variant:"ui-md",className:"mb-3",children:"Trigger history"}),i?o.jsx(La,{title:"Failed to load trigger history",message:i.message}):o.jsx(mSs,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const rnt="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function xSs({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=dn(),a=g.useMemo(()=>{const c=n.toLowerCase();return c?e.filter(u=>u.id.toLowerCase().includes(c)||(u.workflowId??u.agentId??"").toLowerCase().includes(c)):e},[e,n]),{containerRef:i,getRowProps:l}=ao({count:a.length});return t?o.jsx(Bo,{columns:rnt}):o.jsxs(pe,{columns:rnt,className:"min-w-0",scrollRef:i,children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{children:"Target"}),o.jsx(pe.TopCell,{children:"Schedule ID"}),o.jsx(pe.TopCell,{children:"Cron"}),o.jsx(pe.TopCell,{children:"Status"}),o.jsx(pe.TopCell,{children:"Next fire"}),o.jsx(pe.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(pe.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(pe.NoMatch,{message:"No schedules configured"}):null,a.map((c,u)=>o.jsxs(pe.RowLink,{to:r.scheduleLink(c.id),LinkComponent:s,...l(u),children:[o.jsx(pe.NameCell,{children:c.workflowId??c.agentId}),o.jsx(pe.Cell,{className:"min-w-0",children:o.jsx("span",{className:"text-ui-smd text-neutral3 block truncate font-mono",title:c.id,children:c.id})}),o.jsx(pe.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("code",{className:"text-ui-sm font-mono",children:c.cron}),c.timezone?o.jsx("span",{className:"text-neutral4 text-ui-xs",children:c.timezone}):null]})}),o.jsx(pe.Cell,{children:o.jsx(eWt,{status:c.status})}),o.jsx(pe.Cell,{children:o.jsx("span",{className:"whitespace-nowrap",title:Ej(c.nextFireAt),children:h2(c.nextFireAt)})}),o.jsx(pe.Cell,{children:c.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(tWt,{status:c.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:Ej(c.lastFireAt),children:c.lastFireAt?h2(c.lastFireAt):""})]}):c.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:Ej(c.lastFireAt),children:h2(c.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},c.id))]})}function wSs({workflowId:e}={}){const{data:t,isLoading:n,error:r}=CSe(e?{workflowId:e}:{}),[s,a]=g.useState("");return r?o.jsx(La,{title:"Failed to load schedules",message:r.message}):o.jsxs("div",{className:"grid h-full grid-rows-[auto_1fr] gap-4 overflow-hidden",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(cd,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(xSs,{schedules:t??[],isLoading:n,search:s})})]})}function SSs(){const[e]=za(),t=e.get("workflowId")??void 0,{error:n}=CSe(t?{workflowId:t}:{});return n&&hs(n)?o.jsx(Zn,{children:o.jsx(Ts,{})}):n&&ps(n)?o.jsx(Zn,{children:o.jsx(ks,{resource:"schedules"})}):o.jsx(Lt,{children:o.jsx("div",{className:"h-full",children:o.jsx(wSs,{workflowId:t})})})}function kSs({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=KOe({stepGraph:e}),[a,i]=g.useState(!1),[l,c,u]=k_t(r),[d]=O_t(s),{edgeTypes:f,nodeTypes:h,styledEdges:p}=U5t({edges:d,workflowName:n,stepGraph:e});return g.useEffect(()=>{if(t){const m=setTimeout(()=>{i(!0)},500);return()=>clearTimeout(m)}},[t]),o.jsx("div",{className:"bg-surface1 relative h-full w-full",children:a?o.jsxs(S_t,{nodes:l,edges:p,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:h,onNodesChange:u,children:[o.jsx(Vje,{position:"bottom-left"}),o.jsx(__t,{variant:gy.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:o.jsx(Vt,{})})})}function OSs(){const{stepDetail:e,closeStepDetail:t}=MW();return e?o.jsxs("div",{className:"flex h-full flex-col","data-testid":"workflow-step-detail-panel",children:[o.jsxs("div",{className:"border-border1 bg-surface1 flex items-center justify-between border-b px-4 py-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[e.type==="map-config"&&o.jsx(u1,{className:"h-4 w-4",style:{color:Bu.map}}),e.type==="nested-graph"&&o.jsx(Bc,{className:"h-4 w-4",style:{color:Bu.workflow}}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx(ve,{variant:"ui-md",className:"text-neutral6 font-medium",children:e.type==="map-config"?`${e.stepName} Config`:`${e.stepName} Workflow`}),e.type==="map-config"&&e.stepId&&e.stepId!==e.stepName&&o.jsx(ve,{variant:"ui-xs",className:"text-neutral3",children:e.stepId})]})]}),o.jsx("button",{onClick:t,className:"hover:bg-surface3 rounded p-1 transition-colors","aria-label":"Close",children:o.jsx(or,{className:"text-neutral3 h-4 w-4"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(c2,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(YOe,{children:o.jsx(kSs,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function CSs(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function _Ss(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){const n=Object.keys(e);if(n.length===1)return n[0]}return t}function ESs({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:o.jsxs("div",{className:"border-border1 bg-surface4 space-y-5 rounded-lg border p-5","data-testid":"workflow-suspended-steps",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs(ve,{as:"p",variant:"ui-md",className:"text-neutral6 flex items-center gap-2 font-semibold",children:[o.jsx(Qe,{children:o.jsx(EV,{})}),"Step suspended"]}),o.jsx(bt,{variant:"yellow",children:"Needs input"})]}),e.map((s,a)=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const l=i?.resumeSchema?xm(Ix(i.resumeSchema)):mf(cr(),_f());return o.jsx(TSs,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function TSs({step:e,stepSchema:t,description:n,isStreaming:r,onResume:s}){const[a,i]=g.useState(!1);return o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(ve,{as:"p",variant:"ui-md",className:"text-neutral6 truncate font-medium",children:e.stepId}),n&&o.jsx(ve,{as:"p",variant:"ui-sm",className:"text-neutral3",children:n})]}),e.suspendPayload&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs(ve,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(Qe,{children:o.jsx(kJt,{})}),"The step is asking"]}),o.jsxs(fc,{open:a,onOpenChange:i,children:[o.jsxs(ql,{className:"border-border1 bg-surface3 flex w-full items-center justify-between gap-2 rounded-lg border px-3 py-2.5",children:[o.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(Qe,{children:o.jsx(Lr,{className:K("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(ve,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:_Ss(e.suspendPayload,e.stepId)})]}),o.jsx(ve,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:CSs(e.suspendPayload)})]}),o.jsx(Vl,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Gr,{data:e.suspendPayload,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs(ve,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(Qe,{children:o.jsx(_Jt,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(pU,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(Dc,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:l=>{const c=e.stepId?.split(".");s({stepId:c,runId:e.runId,suspendPayload:e.suspendPayload,resumeData:l,isLoading:!1})}})})]})]})}function jSs(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext(Gl),{runId:a}=fr(),i=R_t(e,r??""),l=Yer(),c=!!a,u=t?.status==="suspended",f=!!(a&&r&&a===r)&&e?.status==="suspended";return s||!n||i.length===0||c&&!u&&!f?null:o.jsx("div",{"data-testid":"workflow-suspended-overlay",className:"animate-in fade-in-0 slide-in-from-top-2 zoom-in-95 absolute top-2 right-2 z-20 max-h-[calc(100%-1rem)] w-[380px] max-w-[calc(100%-1rem)] overflow-y-auto rounded-lg shadow-lg duration-300",children:o.jsx(ESs,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const NSs=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.97865 4.57004C8.22604 4.75795 8.27426 5.11082 8.08635 5.35821L6.05486 8.03279C5.94873 8.17251 5.78348 8.25471 5.60803 8.25505C5.43257 8.2554 5.267 8.17385 5.16032 8.03454L3.80937 6.27034C3.6205 6.02369 3.66733 5.67063 3.91398 5.48176C4.16063 5.29288 4.51369 5.33972 4.70257 5.58637L5.6051 6.76498L7.19048 4.67774C7.37839 4.43036 7.73126 4.38213 7.97865 4.57004Z",fill:"currentColor"})]}),ISs=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.89741 4.10293C8.11707 4.32261 8.11706 4.67877 7.89738 4.89843L6.79517 6.00058L7.8962 7.10155C8.11588 7.32122 8.11589 7.67737 7.89623 7.89705C7.67656 8.11673 7.32041 8.11674 7.10073 7.89707L5.99965 6.79605L4.89856 7.89707C4.67889 8.11673 4.32273 8.11672 4.10307 7.89704C3.88341 7.67737 3.88342 7.32121 4.10309 7.10155L5.20413 6.00058L4.10191 4.89843C3.88224 4.67877 3.88223 4.32262 4.10189 4.10294C4.32155 3.88326 4.67771 3.88325 4.89738 4.10292L5.99965 5.20511L7.10191 4.10291C7.32159 3.88325 7.67774 3.88326 7.89741 4.10293Z",fill:"currentColor"})]}),ASs=e=>e.includes("."),RSs=e=>e==="input"||e.endsWith(".input"),PSs=1;function $Ss(e){return`${Number((e/1e3).toPrecision(3))}s`}function MSs(e,t){const n=Object.entries(e).filter(([i])=>!RSs(i));if(n.length===0)return[];const r=Math.min(...n.map(([,i])=>i.startedAt)),s=Math.max(...n.map(([,i])=>i.endedAt??t)),a=Math.max(s-r,1);return n.map(([i,l])=>{const c=l.endedAt===void 0,d=(l.endedAt??t)-l.startedAt,f=(l.startedAt-r)/a*100,h=Math.max(d/a*100,PSs);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:h,durationMs:d,isRunning:c,isNestedEntry:ASs(i)}})}const DSs=({status:e})=>o.jsxs(Qe,{children:[e==="success"&&o.jsx(NSs,{className:"text-accent1"}),e==="failed"&&o.jsx(ISs,{className:"text-accent2"}),e==="suspended"&&o.jsx(EV,{className:"text-accent3"}),e==="waiting"&&o.jsx(rpe,{className:"text-accent5"}),e==="skipped"&&o.jsx(rpe,{className:"text-icon3"}),e==="running"&&o.jsx(Vs,{className:"text-accent6 animate-spin"})]}),LSs={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function nWt(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const snt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},FSs=e=>{const t=e;return R5t({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},zSs=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=FSs(e.step),u=e.status==="running",d=!e.isNestedEntry;return o.jsxs("div",{role:"button",tabIndex:0,"data-testid":"workflow-timeline-row","data-workflow-step-key":e.stepId,"data-workflow-step-active":n?"true":void 0,"data-workflow-step-hovered":r?"true":void 0,"data-workflow-step-nested":e.isNestedEntry?"true":void 0,"aria-pressed":n,"aria-disabled":!d,onMouseEnter:()=>{d&&a(e.stepId)},onMouseLeave:()=>{d&&a(null)},onClick:()=>{d&&s(e.stepId)},onKeyDown:f=>{!d||f.key!=="Enter"&&f.key!==" "||(f.preventDefault(),s(e.stepId))},className:K("grid grid-cols-[auto_auto_auto_minmax(0,10rem)_minmax(0,1fr)_auto_5rem] items-center gap-2 rounded-md border border-transparent px-2 py-1 text-left transition-colors focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-accent1",d&&"cursor-pointer",d&&"hover:bg-surface4",d&&r&&!n&&"border-neutral6 bg-surface4",d&&n&&"border-accent1",e.isNestedEntry&&"cursor-default opacity-55"),children:[o.jsx("div",{className:"flex justify-center",children:o.jsx(DSs,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ie,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step input",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||i(e)},children:o.jsx(Fen,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(Jq,{indicators:c,className:"shrink-0"})}),o.jsx(ve,{as:"span",variant:"ui-sm",className:"text-neutral6 block max-w-full min-w-0 justify-self-stretch overflow-hidden text-left text-ellipsis whitespace-nowrap",children:nWt(e.stepId)}),o.jsx("div",{className:"bg-surface4 relative h-2 min-w-0 rounded",children:o.jsx("div",{"data-testid":"workflow-timeline-bar","data-offset":String(e.offsetPct),"data-width":String(e.widthPct),className:`absolute top-0 h-full rounded ${LSs[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ie,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step output",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||l(e)},children:o.jsx(Den,{})})}),o.jsx(ve,{as:"span",variant:"ui-sm",className:"text-neutral3 w-20 justify-self-end text-right tabular-nums",children:$Ss(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function BSs(){const{steps:e}=aL(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=WH(),[a,i]=g.useState(()=>Date.now()),[l,c]=g.useState(!1),[u,d]=g.useState(null),f=g.useRef(null);uxt(f,{enabled:!l});const h=MSs(e,a),p=h.some(m=>m.isRunning);return g.useEffect(()=>{if(!p)return;const m=setInterval(()=>i(Date.now()),100);return()=>clearInterval(m)},[p]),g.useEffect(()=>{if(l||h.length===0)return;const m=f.current;m&&(m.scrollTop=m.scrollHeight)},[l,h.length]),h.length===0?null:o.jsxs(o.Fragment,{children:[o.jsx("div",{"data-testid":"workflow-timeline",className:"pointer-events-none absolute right-0 bottom-0 z-20 px-2 pb-2",style:{left:"var(--workflow-left-panel-width, 0px)"},children:o.jsxs("div",{className:"rounded-studio-panel border-border1/50 bg-surface3 pointer-events-auto flex max-h-64 w-full min-w-0 flex-col gap-3 overflow-hidden border p-4 shadow-lg",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3",children:[o.jsx(ve,{as:"p",variant:"ui-md",className:"text-neutral3",children:"Timeline"}),o.jsx("button",{type:"button","aria-label":l?"Expand timeline":"Collapse timeline","aria-expanded":!l,onClick:()=>c(m=>!m),className:"text-neutral3 hover:bg-surface4 hover:text-neutral6 rounded-md p-1 transition-colors",children:o.jsx(Js,{className:K("h-4 w-4 transition-transform",l&&"-rotate-90")})})]}),!l&&o.jsx("div",{ref:f,"data-testid":"workflow-timeline-list",className:"flex min-h-0 flex-col gap-2 overflow-y-auto",children:h.map((m,v)=>o.jsx(zSs,{row:m,index:v,isSelected:t===m.stepId,isHovered:n===m.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:y=>d({type:"input",stepId:y.stepId,data:snt(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:snt(y.step.output)})},`timeline-item-${m.stepId}-${v}`))})]})}),o.jsx(pr,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx($_t,{data:u.data,title:`${nWt(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const USs=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=MW();return o.jsxs("div",{className:"flex h-full min-h-0",children:[o.jsx("div",{className:"flex h-full min-h-0 flex-1 flex-col",children:o.jsxs("div",{className:"relative min-h-0 flex-1 p-2 pb-0",children:[o.jsx(Q5t,{workflowId:e,workflow:t,isLoading:n}),o.jsx(jSs,{}),o.jsx(BSs,{})]})}),r&&o.jsx("div",{className:"border-border1 min-h-0 w-[420px] overflow-hidden border-l",children:o.jsx(OSs,{})})]})},ant=()=>{const{workflowId:e}=fr(),{data:t,isLoading:n,error:r}=f4(e);return r&&hs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{})}):r&&ps(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ks,{resource:"workflows"})}):o.jsx(mCe,{children:o.jsx(USs,{workflowId:e,workflow:t??void 0,isLoading:n})})};function qSs(e,t){if(e==null)return{};var n,r,s=Fkt(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function p0e(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function VSs(e){if(Array.isArray(e))return p0e(e)}function HSs(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function WSs(e,t){if(e){if(typeof e=="string")return p0e(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?p0e(e,t):void 0}}function ZSs(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
666
+ ]`})]})]})}function wys({errors:e,maxErrors:t=5}){if(e.length===0)return null;const n=e.slice(0,t),r=e.length-t;return o.jsxs("div",{className:"bg-accent2/10 border-accent2/30 rounded-md border p-3",children:[o.jsxs("div",{className:"text-accent2 mb-2 flex items-center gap-2",children:[o.jsx(Qe,{children:o.jsx(uc,{className:"h-4 w-4"})}),o.jsxs("span",{className:"text-sm font-medium",children:[e.length," validation error",e.length!==1?"s":""]})]}),o.jsx("ul",{className:"text-accent2/80 space-y-1 text-sm",children:n.map((s,a)=>o.jsxs("li",{className:"flex gap-2",children:[o.jsx("span",{className:"shrink-0",children:"•"}),o.jsx("span",{children:s.message})]},a))}),r>0&&o.jsxs("div",{className:"text-accent2/60 mt-2 text-xs",children:["+",r," more error",r!==1?"s":""]})]})}function Sys({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=g.useState("upload"),[i,l]=g.useState(null),[c,u]=g.useState({current:0,total:0}),[d,f]=g.useState(null),[h,p]=g.useState(!1),{parseFile:m,isParsing:v,error:y}=yvs(),{batchInsertItems:b}=wi(),x=g.useCallback(async I=>{try{const A=await m(I);l(A),a("preview")}catch{}},[m]),w=g.useCallback(async()=>{if(!i||i.items.length===0)return;a("importing"),p(!0);const{items:I}=i;u({current:0,total:I.length});try{await b.mutateAsync({datasetId:e,items:I.map(A=>({input:A.input,groundTruth:A.groundTruth,metadata:A.metadata}))}),f({success:I.length,errors:0})}catch{f({success:0,errors:I.length})}u({current:I.length,total:I.length}),p(!1),a("complete")},[i,b,e]),k=g.useCallback(()=>{n(!1),r?.(),d&&d.success>0&&Ve.success(`Imported ${d.success} item${d.success!==1?"s":""}`),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150)},[n,r,d]),C=g.useCallback(()=>{h||(n(!1),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150))},[h,n]),_=i&&i.items.length>0&&i.errors.length===0,T=()=>{switch(s){case"upload":return o.jsx(xys,{onFileSelect:x,isParsing:v,error:y?.message});case"preview":return i?o.jsx("div",{className:"flex flex-col gap-4",children:i.errors.length>0?o.jsxs(o.Fragment,{children:[o.jsx(wys,{errors:i.errors}),o.jsx("div",{className:"text-neutral4 text-sm",children:"Please fix the errors in your JSON file and try again."})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"text-neutral4 text-sm",children:["Found ",i.items.length," valid item",i.items.length!==1?"s":""," to import."]}),o.jsx(bys,{items:i.items,maxRows:5})]})}):null;case"importing":return o.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[o.jsx(Vt,{}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-neutral1 text-lg font-medium",children:"Importing items..."}),o.jsxs("div",{className:"text-neutral4 mt-1 text-sm",children:[c.current," of ",c.total]})]})]});case"complete":return o.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[o.jsx("div",{className:"text-4xl",children:d&&d.errors===0?"✓":"⚠"}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-neutral1 text-lg font-medium",children:"Import Complete"}),o.jsxs("div",{className:"text-neutral4 mt-1 text-sm",children:[d?.success??0," item",d?.success!==1?"s":""," imported",d&&d.errors>0&&o.jsxs("span",{className:"text-accent2",children:[" ","(",d.errors," error",d.errors!==1?"s":"",")"]})]})]})]})}},E=()=>{switch(s){case"upload":return o.jsx(ie,{onClick:C,children:"Cancel"});case"preview":return o.jsxs(o.Fragment,{children:[o.jsx(ie,{onClick:()=>a("upload"),children:"Back"}),o.jsxs(ie,{variant:"primary",onClick:w,disabled:!_,children:["Import ",i?.items.length??0," Item",i?.items.length!==1?"s":""]})]});case"importing":return null;case"complete":return o.jsx(ie,{variant:"primary",onClick:k,children:"Done"})}},N={upload:"Import JSON",preview:"Preview Data",importing:"Importing",complete:"Import Complete"};return o.jsx(pr,{open:t,onOpenChange:C,children:o.jsxs(mr,{className:"max-h-[90vh] max-w-2xl",children:[o.jsxs(gr,{children:[o.jsx(ur,{children:N[s]}),o.jsx(Cs,{children:"Import dataset items from a JSON file."})]}),o.jsx(jr,{className:"max-h-[50vh] min-h-[200px] overflow-y-auto",children:T()}),o.jsx(Bl,{className:"flex justify-end gap-2 px-6 pt-4",children:E()})]})})}function kys(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"?!0:!!e.closest('[role="dialog"]:not([data-item-panel])')}function wHt({active:e,onPrevious:t,onNext:n,onClose:r}){g.useEffect(()=>{if(!e)return;const s=a=>{a.defaultPrevented||kys(a.target)||(a.key==="PageUp"?(a.preventDefault(),t?.()):a.key==="PageDown"?(a.preventDefault(),n?.()):a.key==="Escape"&&(a.preventDefault(),r()))};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,t,n,r])}const SHt=g.createContext(null);function Oys({datasetId:e,items:t,isLoadingItems:n,children:r}){const s=qr(),i=fvt("/datasets/:datasetId/items/:itemId")?.params.itemId,l=g.useCallback(p=>{s(`/datasets/${e}/items/${encodeURIComponent(p)}`)},[s,e]),c=g.useCallback(()=>{s(`/datasets/${e}`)},[s,e]),u=g.useMemo(()=>i?t.findIndex(p=>p.id===i):-1,[t,i]),d=g.useMemo(()=>{if(u<=0)return;const p=t[u-1].id;return()=>l(p)},[u,t,l]),f=g.useMemo(()=>{if(u<0||u>=t.length-1)return;const p=t[u+1].id;return()=>l(p)},[u,t,l]);wHt({active:!!i,onPrevious:d,onNext:f,onClose:c});const h=g.useMemo(()=>({datasetId:e,items:t,isLoadingItems:n,currentItemId:i,openItem:l,close:c,goToPreviousItem:d,goToNextItem:f}),[e,t,n,i,l,c,d,f]);return o.jsx(SHt.Provider,{value:h,children:r})}function kHt(){const e=g.useContext(SHt);if(!e)throw new Error("useDatasetItemPanel must be used within a DatasetItemPanelProvider");return e}function Cys({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,leftSlot:r,rightSlot:s}){const[a,i]=za(),{activeVersion:l}=mRe(a,i),[c,u]=g.useState(!1),[d,f]=g.useState(!1),[h,p]=g.useState(!1),[m,v]=g.useState([]),[y,b]=g.useState(!1),[x,w]=g.useState([]),[k,C]=g.useState(!1),[_,T]=g.useState([]),[E,N]=g.useState(0),[I,A]=g.useState(""),[P]=YH(I,300),{data:L}=zy(e),{data:D=[],isLoading:B,setEndOfListElement:H,isFetchingNextPage:q,hasNextPage:z}=Qx(e,P||void 0,l),{deleteItems:V}=wi(),{currentItemId:M,openItem:G,close:F}=kHt(),R=ae=>{M===ae?F():G(ae)},U=ae=>{v(ae),p(!0)},Z=ae=>{w(ae),b(!0)},Y=ae=>{b(ae),ae||(w([]),N(X=>X+1))},te=ae=>{T(ae),C(!0)},J=async()=>{await V.mutateAsync({datasetId:e,itemIds:_}),Ve.success(`Deleted ${_.length} items`),C(!1),T([]),N(ae=>ae+1)},ee=ae=>{p(!1),v([]),N(X=>X+1),n?.(ae)},re=ae=>{p(ae),ae||(v([]),N(X=>X+1))};return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"grid h-full overflow-auto",children:o.jsx(yys,{items:D,leftSlot:r,rightSlot:s,isLoading:B,onItemClick:R,featuredItemId:M,onAddClick:t??(()=>{}),onImportClick:()=>u(!0),onImportJsonClick:()=>f(!0),onBulkDeleteClick:te,onCreateDatasetClick:U,onAddToDatasetClick:Z,datasetName:L?.name,clearSelectionTrigger:E,setEndOfListElement:H,isFetchingNextPage:q,hasNextPage:z,searchQuery:I,activeSearchQuery:P,onSearchChange:A,currentDatasetVersion:L?.version})}),o.jsx(hys,{datasetId:e,open:c,onOpenChange:u}),o.jsx(Sys,{datasetId:e,open:d,onOpenChange:f}),o.jsx(Zvs,{open:h,onOpenChange:re,items:m,onSuccess:ee}),o.jsx(Gvs,{open:y,onOpenChange:Y,items:x,currentDatasetId:e}),o.jsx($t,{open:k,onOpenChange:C,children:o.jsxs($t.Content,{children:[o.jsxs($t.Header,{children:[o.jsx($t.Title,{children:"Delete Items"}),o.jsxs($t.Description,{children:["Are you sure you want to delete ",_.length," item",_.length!==1?"s":"","? This action cannot be undone."]})]}),o.jsxs($t.Footer,{children:[o.jsx($t.Cancel,{children:"Cancel"}),o.jsx($t.Action,{onClick:J,children:V.isPending?"Deleting...":"Delete"})]})]})})]})}function OHt({selectedScorers:e,setSelectedScorers:t,disabled:n=!1,container:r,label:s="Scorers (Optional)",helperText:a}){const{data:i,isLoading:l}=up(),c=Object.entries(i??{}).filter(([,u])=>u.isRegistered).map(([u,d])=>({value:u,label:d.scorer?.config?.name||u,description:d.scorer?.config?.description||""}));return o.jsxs("div",{className:"grid gap-2",children:[s?o.jsx(Dt,{children:s}):null,a?o.jsx("p",{className:"text-muted-foreground text-xs",children:a}):null,o.jsx(vl,{multiple:!0,options:c,value:e,onValueChange:t,placeholder:"Select scorers...",searchPlaceholder:"Search scorers...",emptyText:"No scorers available",disabled:n||l,container:r})]})}function CHt({overrideEnabled:e,onOverrideEnabledChange:t,selectedScorerIds:n,onSelectedScorerIdsChange:r,disabled:s=!1}){return o.jsxs("div",{className:"grid gap-3",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(yl,{id:"override-dataset-scorers",checked:e,onCheckedChange:t,disabled:s}),o.jsx(Dt,{htmlFor:"override-dataset-scorers",children:"Override dataset scorers"})]}),o.jsx("p",{className:"text-muted-foreground text-xs",children:e?"Only selected scorers run for this item. Leave empty to run no scorers.":"Use scorers attached to the dataset."}),e?o.jsx(OHt,{selectedScorers:n,setSelectedScorers:r,disabled:s,label:"Item scorers",helperText:"Choose from scorers that can be resolved by this Mastra instance."}):null]})}function _ys(e){if(!(e instanceof Error))return null;const t=e.message.match(/- ({.*})$/);if(!t)return null;try{const n=JSON.parse(t[1]);if(n.field&&Array.isArray(n.errors))return{field:n.field,errors:n.errors}}catch{}return null}function Qie({field:e,errors:t}){return t.length?o.jsx("div",{className:"mt-2 space-y-1",children:t.map((n,r)=>o.jsxs("p",{className:"text-destructive text-xs",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function Eys({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=g.useState("{}"),[i,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState(""),[h,p]=g.useState(!1),[m,v]=g.useState([]),[y,b]=g.useState(""),[x,w]=g.useState(null),{addItem:k}=wi(),C=()=>{a("{}"),l(""),u(""),f(""),p(!1),v([]),b(""),w(null)},_=P=>{C(),n(P)},T=async P=>{P.preventDefault();let L;try{L=JSON.parse(s)}catch{Ve.error("Input must be valid JSON");return}let D;if(i.trim())try{D=JSON.parse(i)}catch{Ve.error("Ground Truth must be valid JSON");return}let B;if(c.trim())try{B=JSON.parse(c)}catch{Ve.error("Expected Trajectory must be valid JSON");return}let H;if(d.trim())try{const z=JSON.parse(d);if(!Array.isArray(z)){Ve.error("Tool Mocks must be a JSON array");return}H=z}catch{Ve.error("Tool Mocks must be valid JSON");return}let q;if(y.trim())try{q=JSON.parse(y)}catch{Ve.error("Request Context must be valid JSON");return}try{await k.mutateAsync({datasetId:e,input:L,groundTruth:D,expectedTrajectory:B,toolMocks:H,scorerIds:h?m:void 0,requestContext:q}),Ve.success("Item added successfully"),_(!1),r?.()}catch(z){const V=_ys(z);V?w(V):Ve.error(`Failed to add item: ${z instanceof Error?z.message:"Unknown error"}`)}},E=P=>{a(P),x?.field==="input"&&w(null)},N=P=>{l(P),x?.field==="groundTruth"&&w(null)},I=P=>{f(P),x?.field==="toolMocks"&&w(null)},A=()=>{_(!1)};return o.jsxs(Ca,{dialogTitle:"Add Item",dialogDescription:"Create a new dataset item",isOpen:t,onClose:A,level:1,children:[o.jsx(Ca.Top,{children:"Add Item"}),o.jsxs(Ca.Content,{children:[o.jsx(Ca.Header,{children:o.jsx(Ca.Heading,{children:"Add Item"})}),o.jsxs("form",{onSubmit:T,className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Gr,{value:s,onChange:E,showCopyButton:!1,className:"min-h-[240px]"}),x?.field==="input"&&o.jsx(Qie,{field:"input",errors:x.errors})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),o.jsx(Gr,{value:i,onChange:N,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="groundTruth"&&o.jsx(Qie,{field:"groundTruth",errors:x.errors})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),o.jsx(Gr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[200px]"})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-tool-mocks",children:"Tool Mocks (JSON array, optional)"}),o.jsx(Gr,{value:d,onChange:I,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="toolMocks"&&o.jsx(Qie,{field:"toolMocks",errors:x.errors})]}),o.jsx(CHt,{overrideEnabled:h,onOverrideEnabledChange:p,selectedScorerIds:m,onSelectedScorerIdsChange:v,disabled:k.isPending}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-request-context",children:"Request Context (JSON, optional)"}),o.jsx(Gr,{value:y,onChange:b,showCopyButton:!1,className:"min-h-[200px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ie,{type:"button",onClick:A,children:"Cancel"}),o.jsx(ie,{type:"submit",variant:"primary",disabled:k.isPending,children:k.isPending?"Adding...":"Add Item"})]})]})]})]})}function Tys({item:e}){return o.jsx(Pa,{withMargins:!1,children:o.jsxs(Pa.Column,{children:[o.jsxs(Pa.Title,{size:"smaller",children:[o.jsx(NV,{}),o.jsx("span",{className:"truncate",children:e.id}),o.jsx(_a,{content:e.id,tooltip:`Copy item ID: ${e.id}`})]}),o.jsxs(Pa.Description,{children:[o.jsxs(Pl,{children:[o.jsx(yYt,{})," Created ",dr(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")]}),e.datasetVersion!=null&&o.jsxs(Pl,{children:[o.jsx(uI,{})," Version v",e.datasetVersion]})]})]})})}function gRe({item:e}){const t=e?.input?JSON.stringify(e.input,null,2):"null",n=e?.groundTruth?JSON.stringify(e.groundTruth,null,2):"null",r=e?.metadata?JSON.stringify(e.metadata,null,2):"null",s=e?.expectedTrajectory?JSON.stringify(e.expectedTrajectory,null,2):null;return o.jsxs(Fqr,{children:[o.jsx(Ca.CodeSection,{title:"Input",icon:o.jsx(Ox,{}),codeStr:t}),o.jsx(Ca.CodeSection,{title:"Ground Truth",icon:o.jsx(nm,{}),codeStr:n}),s&&o.jsx(Ca.CodeSection,{title:"Expected Trajectory",icon:o.jsx(P0e,{}),codeStr:s}),o.jsx(Ca.CodeSection,{title:"Scorers",icon:o.jsx(PV,{}),codeStr:e.scorerIds===void 0?"Inherited from dataset":JSON.stringify(e.scorerIds,null,2)}),o.jsx(Ca.CodeSection,{title:"Metadata",icon:o.jsx(dI,{}),codeStr:r})]})}function Yie({field:e,errors:t}){return t.length?o.jsx("div",{className:"mt-2 space-y-1",children:t.map((n,r)=>o.jsxs("p",{className:"text-destructive text-xs",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function jys({inputValue:e,setInputValue:t,groundTruthValue:n,setGroundTruthValue:r,metadataValue:s,setMetadataValue:a,trajectoryValue:i,setTrajectoryValue:l,toolMocksValue:c,setToolMocksValue:u,scorerOverrideEnabled:d,setScorerOverrideEnabled:f,selectedScorerIds:h,setSelectedScorerIds:p,requestContextValue:m,setRequestContextValue:v,validationErrors:y,onSave:b,onCancel:x,isSaving:w}){return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"mb-4",children:o.jsxs("h3",{className:"flex items-center gap-2 text-lg font-medium",children:[o.jsx(Yh,{className:"h-5 w-5"})," Edit Item"]})}),o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Input (JSON) *"}),o.jsx(Gr,{value:e,onChange:t,showCopyButton:!1,className:"min-h-[120px]"}),y?.field==="input"&&o.jsx(Yie,{field:"input",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Ground Truth (JSON, optional)"}),o.jsx(Gr,{value:n,onChange:r,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="groundTruth"&&o.jsx(Yie,{field:"groundTruth",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Expected Trajectory (JSON, optional)"}),o.jsx(Gr,{value:i,onChange:l,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Tool Mocks (JSON array, optional)"}),o.jsxs("p",{className:"text-muted-foreground text-xs",children:["Ordered static mocks served in place of executing the tool. Each entry is"," ",o.jsx("code",{children:'{ "toolName", "args", "output" }'}),". Calling a mocked tool with non-matching args fails the item; unmocked tools run live."]}),o.jsx(Gr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="toolMocks"&&o.jsx(Yie,{field:"toolMocks",errors:y.errors})]}),o.jsx(CHt,{overrideEnabled:d,onOverrideEnabledChange:f,selectedScorerIds:h,onSelectedScorerIdsChange:p,disabled:w}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Request Context (JSON, optional)"}),o.jsx(Gr,{value:m,onChange:v,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Metadata (JSON, optional)"}),o.jsx(Gr,{value:s,onChange:a,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex gap-2 pt-4",children:[o.jsx(ie,{variant:"primary",onClick:b,disabled:w,children:w?"Saving...":"Save Changes"}),o.jsx(ie,{onClick:x,disabled:w,children:"Cancel"})]})]})]})}const Nys={light:"bg-gray-100 border-gray-300 text-gray-700 shadow-[0_1px_0_rgba(0,0,0,0.1)]",dark:"bg-surface4 border-border1 text-neutral5 shadow-[0_1px_0_rgba(0,0,0,0.3)]"},Iys={default:"h-6 min-w-6 rounded-md px-1.5 text-ui-sm",sm:"h-5 min-w-5 rounded-md px-1 text-ui-xs",xs:"h-4 min-w-4 rounded px-1 text-ui-xs leading-none"},FT=({children:e,theme:t="dark",size:n="default",className:r})=>o.jsx("kbd",{className:K("inline-flex items-center justify-center border font-mono",Iys[n],Yr.transform,"active:scale-95 active:shadow-none",Nys[t],r),children:e}),Ays=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function Rys({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:a,isLoading:i}=Bm(),{data:l,isLoading:c}=Xy(),{data:u,isLoading:d}=up(),f=e==="agent"?Object.entries(a??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="workflow"?Object.entries(l??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="scorer"?Object.entries(u??{}).map(([v,y])=>({value:v,label:y.scorer?.config?.name??v})):[],h=e==="agent"&&i||e==="workflow"&&c||e==="scorer"&&d,p=v=>{t(v),r("")},m=e==="agent"?"Agent":e==="workflow"?"Workflow":"Scorer";return o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{children:"Target Type"}),o.jsx(vl,{options:Ays,value:e,onValueChange:p,placeholder:"Select target type",searchPlaceholder:"Search types...",emptyText:"No types available",container:s})]}),e&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{children:m}),o.jsx(vl,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:h,container:s})]})]})}const Pys=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform);function $ys({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return xm(e)}catch(r){return console.error("Failed to parse requestContextSchema:",r),null}},[e]);return n?o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Request Context"}),o.jsx(Q3,{schema:n,onValuesChange:t,className:"[&_button[type=submit]]:hidden"})]}):o.jsx("p",{className:"text-destructive text-sm",children:"Failed to parse request context schema"})}function Kie({index:e,title:t,done:n,isLast:r,children:s}){return o.jsxs("li",{className:"flex gap-4",children:[o.jsxs("div",{className:"flex flex-col items-center",children:[o.jsx("span",{"aria-hidden":"true",className:K("flex size-6 shrink-0 items-center justify-center rounded-full border text-ui-xs font-medium",n?"border-accent1 bg-accent1 text-white":"border-border1 text-neutral3"),children:e}),!r&&o.jsx("span",{"aria-hidden":"true",className:"bg-border1 mt-2 w-px flex-1"})]}),o.jsxs("div",{className:K("min-w-0 flex-1 space-y-3",!r&&"pb-6"),children:[o.jsx("p",{className:"text-ui-sm font-medium",children:t}),s]})]})}function cY({initialDatasetId:e,initialDatasetVersion:t,initialScorerIds:n,initialTargetType:r,initialTargetId:s,initialName:a,initialDescription:i,open:l,onOpenChange:c,onSuccess:u}){const d=g.useRef(null),[f,h]=g.useState(a??""),[p,m]=g.useState(i??""),[v,y]=g.useState(e??""),[b,x]=g.useState(t??null),[w,k]=g.useState(r??""),[C,_]=g.useState(s??""),[T,E]=g.useState(n??[]),[N,I]=g.useState({}),[A,P]=g.useState(""),{triggerExperiment:L}=wi(),{data:D}=zy(v),{total:B}=Qx(v,void 0,b),H=D?.requestContextSchema,q=!!(H&&Object.keys(H).length>0),z=!!(v&&w&&C&&f.trim()),V=L.isPending,M=[!f.trim()&&"name",!v&&"dataset",!C&&"target"].filter(Boolean),G=q?Object.values(N).some(J=>J!==void 0&&J!==""):A.trim().length>0,F=J=>{y(J),x(null),I({})},R=()=>{h(a??""),m(i??""),y(e??""),x(t??null),k(r??""),_(s??""),E(n??[]),I({}),P("")},U=()=>{if(q){const J=Object.entries(N).filter(([,ee])=>ee!==void 0&&ee!=="");return J.length>0?Object.fromEntries(J):void 0}if(A.trim()){let J;try{J=JSON.parse(A)}catch{throw new Error("Request Context must be valid JSON")}if(!J||typeof J!="object"||Array.isArray(J))throw new Error("Request Context must be a JSON object");return J}},Z=async()=>{if(!v||!w||!C||!f.trim())return;let J;try{J=U()}catch(ee){const re=ee instanceof Error?ee.message:"Request Context must be valid JSON";yu.error(re);return}try{const ee=await L.mutateAsync({datasetId:v,name:f.trim(),description:p.trim()||void 0,targetType:w,targetId:C,scorerIds:T.length>0?T:void 0,version:b??void 0,requestContext:J});yu.success("Experiment triggered successfully"),c(!1),u?.(ee.experimentId),R()}catch(ee){const re=ee instanceof Error?ee.message:"Failed to trigger experiment";yu.error(re)}},Y=()=>{V||(c(!1),R())},te=J=>{(J.metaKey||J.ctrlKey)&&J.key==="Enter"&&z&&!V&&(J.preventDefault(),Z())};return o.jsx(pr,{open:l,onOpenChange:Y,children:o.jsxs(mr,{ref:d,className:"w-[640px] max-w-[calc(100vw-2rem)] gap-0 p-0",onKeyDown:te,children:[o.jsxs(gr,{className:"border-border1 border-b px-6 py-4",children:[o.jsx(ur,{children:"Run experiment"}),o.jsx(Cs,{className:"text-ui-sm text-neutral3 not-sr-only",children:"Pick a dataset, choose what to run it against, and optionally score the results."})]}),o.jsxs(jr,{className:"max-h-[70vh] space-y-6 overflow-y-auto px-6 py-5",children:[o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"experiment-name",children:"Name *"}),o.jsx(jn,{id:"experiment-name",value:f,onChange:J=>h(J.target.value),placeholder:"Enter experiment name",autoFocus:!0,disabled:V})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"experiment-description",children:"Description"}),o.jsx(zo,{id:"experiment-description",value:p,onChange:J=>m(J.target.value),placeholder:"Enter experiment description (optional)",disabled:V,rows:2})]})]}),o.jsxs("ol",{className:"list-none",children:[o.jsxs(Kie,{index:1,title:"Dataset",done:!!v,children:[o.jsxs("div",{className:"grid grid-cols-[1fr_140px] gap-3",children:[o.jsx(eys,{value:v,onValueChange:F,container:d}),v&&o.jsx(bHt,{datasetId:v,value:b,onValueChange:x,container:d})]}),v&&B!==void 0&&o.jsxs("p",{className:"text-ui-xs text-neutral3",children:[B," ",B===1?"item":"items"]})]}),o.jsxs(Kie,{index:2,title:"Target",done:!!C,children:[o.jsx(Rys,{targetType:w,setTargetType:k,targetId:C,setTargetId:_,container:d}),w&&!C&&o.jsxs("p",{className:"text-ui-xs text-neutral3",children:["Choose ",w==="agent"?"an":"a"," ",w," to run"]})]}),o.jsx(Kie,{index:3,title:"Scorers (Optional)",done:T.length>0,isLast:!0,children:o.jsx(OHt,{label:"",selectedScorers:T,setSelectedScorers:E,disabled:V,container:d,helperText:"Scores are computed after each item runs."})})]}),o.jsxs(fc,{children:[o.jsxs(ql,{className:"text-ui-sm flex items-center gap-2",children:[o.jsx(Lr,{className:"size-4"}),"Request Context (JSON, optional)",G&&o.jsx(bt,{size:"xs",variant:"blue",children:"set"})]}),o.jsx(Vl,{className:"pt-3",children:q?o.jsx($ys,{requestContextSchema:H,onChange:I}):o.jsx(Gr,{value:A,onChange:P,showCopyButton:!1,"aria-label":"Request context JSON",className:"min-h-[160px]"})})]})]}),o.jsxs(Bl,{className:"border-border1 items-center border-t px-6 py-4 sm:justify-between",children:[o.jsx("p",{"data-testid":"experiment-run-status","aria-live":"polite",className:"flex items-center gap-2",children:M.length===0?o.jsxs(o.Fragment,{children:[o.jsx(bt,{variant:"green",indicator:"dot",children:"Ready"}),o.jsxs("span",{className:"text-ui-xs text-neutral3",children:[B??0," items · ",w," · ",T.length," scorers"]})]}):o.jsxs(bt,{variant:"neutral",indicator:"dot",children:["Missing ",M.join(", ")]})}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ie,{onClick:Y,disabled:V,children:"Cancel"}),o.jsx(ie,{variant:"primary",onClick:Z,disabled:!z||V,children:V?o.jsxs(o.Fragment,{children:[o.jsx(Vt,{className:"h-4 w-4"}),"Running..."]}):o.jsxs(o.Fragment,{children:["Run",o.jsxs("span",{className:"ml-1 inline-flex gap-0.5","aria-hidden":"true",children:[o.jsx(FT,{size:"xs",children:Pys?"⌘":"Ctrl"}),o.jsx(FT,{size:"xs",children:"↵"})]})]})})]})]})]})})}const _Ht=g.createContext(null);function Mys({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:a,children:i}){const l=qr(),u=fvt("/experiments/:experimentId/items/:itemId")?.params.itemId,d=g.useCallback(b=>{l(`/experiments/${e}/items/${encodeURIComponent(b)}`)},[l,e]),f=g.useCallback(()=>{l(`/experiments/${e}`)},[l,e]),h=g.useCallback(b=>{l(STe(e,b))},[l,e]),p=g.useMemo(()=>u?r.findIndex(b=>b.itemId===u):-1,[r,u]),m=g.useMemo(()=>{if(p<=0)return;const b=r[p-1].itemId;return()=>d(b)},[p,r,d]),v=g.useMemo(()=>{if(p<0||p>=r.length-1)return;const b=r[p+1].itemId;return()=>d(b)},[p,r,d]);wHt({active:!!u,onPrevious:m,onNext:v,onClose:f});const y=g.useMemo(()=>({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:a,currentItemId:u,openItem:d,close:f,openInReview:h,goToPreviousItem:m,goToNextItem:v}),[e,t,n,r,s,a,u,d,f,h,m,v]);return o.jsx(_Ht.Provider,{value:y,children:i})}function EHt(){const e=g.useContext(_Ht);if(!e)throw new Error("useExperimentItemPanel must be used within an ExperimentItemPanelProvider");return e}function Dys({results:e,isLoading:t,featuredResultId:n,onResultClick:r,columns:s,scoresByItemId:a,scorerIds:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u,selectedIds:d,onToggleSelect:f}){const{Link:h,paths:p}=dn(),m=!!(d&&f),v=[m?"2rem":"",...s.map(k=>k.size)].filter(Boolean).join(" "),y=s.some(k=>k.name==="input"),{containerRef:b,getRowProps:x}=ao({count:e.length}),w=k=>i?.includes(k.name)?o.jsx(pe.TopCell,{children:o.jsxs(h,{href:p.scorerLink(k.name),className:"flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[o.jsx(P_,{}),o.jsx("span",{className:"min-w-0 truncate",children:k.label})]})},k.name):o.jsx(pe.TopCell,{children:k.label},k.name);return t?o.jsx(Bo,{columns:v}):o.jsxs(pe,{columns:v,className:"min-w-0",scrollRef:b,children:[o.jsxs(pe.Top,{hasLeadingCell:m,children:[m&&o.jsx(pe.TopCell,{children:" "}),m?o.jsx(pe.TopCells,{colStart:2,children:s.map(w)}):s.map(w)]}),e.length===0?o.jsx(pe.NoMatch,{message:"No results yet"}):o.jsxs(o.Fragment,{children:[e.map((k,C)=>{const _=!!k.error,T=k.id===n,E=o.jsxs(o.Fragment,{children:[o.jsxs(pe.Cell,{className:"text-ui-smd text-neutral3 flex items-center gap-1.5 tracking-wide",children:[o.jsx("span",{children:k.itemId?.slice(0,8)??""}),_&&o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx(SO,{role:"img","aria-label":"Error",className:"text-error size-3.5"})}),o.jsx(yn,{children:k.error?.message||"Error"})]})]}),y&&o.jsx(pe.TextCell,{font:"mono",children:Fys(Lys(k.input),200)}),i?.map(N=>{const A=a?.[k.itemId]?.find(P=>P.scorerId===N);return o.jsx(pe.Cell,{className:"text-neutral3 text-ui-smd font-mono",children:A!=null?A.score.toFixed(3):"-"},N)})]});return m?o.jsxs(pe.RowWrapper,{children:[o.jsx(pe.SelectCell,{checked:d.has(k.id),onToggle:()=>f(k.id),"aria-label":`Select result ${k.itemId}`}),o.jsx(pe.RowButton,{colStart:2,featured:T,"data-selected":T||void 0,onClick:()=>r(k.id),...x(C),children:E})]},k.id):o.jsx(pe.RowButton,{featured:T,"data-selected":T||void 0,onClick:()=>r(k.id),...x(C),children:E},k.id)}),o.jsx(pe.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function Lys(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Fys(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}function zys({scoresByItemId:e,experimentStatus:t}){const{Link:n,paths:r}=dn(),{data:s}=up(),a=g.useMemo(()=>{if(!e)return[];const i={};for(const l of Object.values(e))for(const c of l)i[c.scorerId]||(i[c.scorerId]={sum:0,count:0}),i[c.scorerId].sum+=c.score,i[c.scorerId].count++;return Object.entries(i).map(([l,{sum:c,count:u}])=>({scorerId:l,avg:c/u})).sort((l,c)=>l.scorerId.localeCompare(c.scorerId))},[e]);if(a.length===0){const i=t==="running"||t==="pending",l=e!==void 0;let c,u;return i?(c="Experiment in progress",u="Summary metrics will appear here once the experiment completes."):l?(c="No scorers configured",u="Add scorers when triggering an experiment to evaluate results and see summary metrics here."):(c="Loading scores",u="Fetching scorer results…"),o.jsxs("div",{className:"text-ui-sm text-neutral3 flex items-center gap-2",children:[o.jsx(Qh,{className:"text-neutral3 size-4 shrink-0"}),o.jsx("span",{className:"text-neutral4",children:c}),o.jsx("span",{className:"truncate",children:u})]})}return o.jsx("div",{className:"flex items-stretch gap-2 overflow-x-auto pb-1",children:a.map(({scorerId:i,avg:l})=>{const c=s?.[i]?.scorer?.config?.name??i;return o.jsxs(Xr,{className:"w-52 min-w-0 flex-none p-3",children:[o.jsxs(n,{href:r.scorerLink(i),className:"text-ui-sm text-neutral3 [&>svg]:text-neutral3 flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3 [&>svg]:shrink-0",children:[o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx(P_,{role:"img","aria-label":"Scorer"})}),o.jsx(yn,{children:"Scorer"})]}),o.jsx("span",{className:"truncate",children:c})]}),o.jsxs("strong",{className:"text-ui-lg text-neutral4 font-semibold",children:[l.toFixed(3),o.jsx("span",{className:"text-ui-sm text-neutral3 ml-1.5 font-normal",children:"avg score"})]})]},i)})})}function Bys({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoading:s,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l}){const{currentItemId:c,openItem:u,close:d}=EHt(),[f,h]=g.useState(new Set),[p,m]=g.useState(!1),{updateExperimentResult:v}=wi(),y=g.useCallback(E=>{h(N=>{const I=new Set(N);return I.has(E)?I.delete(E):I.add(E),I})},[]),b=g.useCallback(()=>h(new Set),[]),x=g.useCallback(async E=>{if(p||E.length===0)return;m(!0);let N=0;const I=new Set;try{for(const A of E)try{await v.mutateAsync({datasetId:t,experimentId:e,resultId:A,status:"needs-review"}),N++,I.add(A)}catch{}}finally{m(!1)}I.size>0&&h(A=>{const P=new Set(A);for(const L of I)P.delete(L);return P}),N>0&&Ve(`${N} result${N>1?"s":""} flagged for review`)},[t,e,p,v]),w=g.useMemo(()=>c?r.find(E=>E.itemId===c)?.id??null:null,[r,c]),{data:k}=jC(e,n),C=g.useMemo(()=>{if(!k)return[];const E=new Set;for(const N of Object.values(k))for(const I of N)E.add(I.scorerId);return[...E].sort()},[k]),_=g.useCallback(E=>{const N=r.find(I=>I.id===E);N&&(N.itemId===c?d():u(N.itemId))},[r,c,d,u]),T=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"7rem"},{name:"input",label:"Input",size:"minmax(10rem,1fr)"},...C.map(E=>({name:E,label:E,size:"12rem"}))],[C]);return o.jsxs("div",{className:K("grid h-full gap-3 overflow-hidden",f.size>0?"grid-rows-[auto_auto_1fr]":"grid-rows-[auto_1fr]"),children:[o.jsx(zys,{scoresByItemId:k,experimentStatus:n}),f.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(ie,{variant:"outline",size:"sm",disabled:p,onClick:()=>x([...f]),children:[o.jsx(Qe,{size:"sm",children:o.jsx(X1,{})}),"Flag ",f.size," to review"]}),o.jsx(ie,{variant:"ghost",size:"sm",onClick:b,children:"Clear"})]}),o.jsx("div",{className:"min-h-0 overflow-y-auto",children:o.jsx(Dys,{results:r,isLoading:s,featuredResultId:w,onResultClick:_,columns:T,scoresByItemId:k,scorerIds:C,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l,selectedIds:f,onToggleSelect:y})})]})}const Ttt={pending:{icon:o.jsx(c1,{className:"text-warning1 size-4"}),label:"Pending"},running:{icon:o.jsx(Vt,{size:"sm"}),label:"Running"},completed:{icon:o.jsx(XD,{className:"text-neutral3 size-4"}),label:"Completed"},failed:{icon:o.jsx(OO,{className:"text-error size-4"}),label:"Failed"}};function Uys({status:e,className:t}){const n=Ttt[e]??Ttt.pending;return o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx("span",{tabIndex:0,className:K("flex shrink-0 items-center",t),children:n.icon})}),o.jsx(yn,{children:n.label})]})}const qys=e=>{const t=Ye();return mt({queryKey:["experiment-trace-light",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return t.getTraceLight(e)},select:zAe,enabled:!!e})};function THt({children:e,className:t}){return o.jsx("div",{className:K("",t),children:e})}function Vys({date:e,className:t,withTime:n=!1}){const r=e?e0t(new Date(e)):!1,s=e?U3(new Date(e))?"Today":dr(new Date(e),"MMM dd"):"",a=e&&!r?dr(new Date(e),"yyyy"):"",i=e&&n?`${dr(new Date(e),"'at' h:mm aaa")}`:"";return o.jsxs("div",{className:K("truncate text-ui-md text-neutral2",t),children:[s," ",a," ",i]})}function vRe(e){return!e||e.length===0?"":e?.map(t=>t.size).join(" ")}function Hys({columns:e,isSelectionActive:t,children:n}){return o.jsx("div",{className:K("sticky top-0 z-10 mb-4 rounded-lg bg-surface3 px-4"),children:o.jsx("div",{className:K("grid items-center gap-4 text-left text-ui-xs tracking-widest text-neutral3 uppercase",{"pl-12 [&>label]:absolute [&>label]:left-0":t}),style:{gridTemplateColumns:vRe(e)},children:n})})}function Wys({children:e,className:t}){return o.jsx("span",{className:K("py-3",t),children:e})}function Zys({id:e,className:t,isShortened:n=!0}){const r=n?e.slice(0,8):e;return o.jsx("div",{className:K("truncate py-[0.6rem] text-ui-md text-neutral2",t),children:r})}function Gys({children:e}){return o.jsx("ul",{className:"grid content-start",children:e})}function Qys({children:e}){const t=g.useRef(null);return o.jsx("div",{ref:t,className:K("overflow-y-auto"),children:e})}function Yys({children:e,className:t}){return o.jsx("label",{className:K("flex h-full w-14 items-center justify-center rounded-lg hover:bg-surface5",t),children:e})}function Kys({children:e,href:t,className:n,LinkComponent:r,tooltip:s}){const a=o.jsx(r,{href:t,className:K("flex w-full items-center justify-center gap-6 rounded-lg px-3 py-[0.6rem] text-left","hover:bg-surface4",Yr.colors,M3.visible,n),children:e});return s==null?a:o.jsxs(xn,{children:[o.jsx(vn,{render:a}),o.jsx(yn,{children:s})]})}function Xys({children:e,message:t,className:n,type:r}){return!e&&!t?null:o.jsx("div",{className:K("grid border-t border-border1",n),children:t?o.jsxs("p",{className:K("grid justify-center justify-items-center gap-2 p-8 text-center text-ui-md text-neutral3","[&>svg]:size-[1.5em] [&>svg]:opacity-75",{"[&>svg]:text-red-500":r==="error"}),children:[r==="error"?o.jsx(uc,{}):o.jsx(Em,{})," ",t]}):e})}function Jys({isLoading:e,hasMore:t,setEndOfListElement:n,loadingText:r="Loading more data...",noMoreDataText:s="No more data to load"}){return n?o.jsxs("div",{ref:n,className:"text-ui-md text-neutral3 mt-8 flex justify-center opacity-50",children:[e&&r,!t&&!e&&s]}):null}function ebs({currentPage:e,hasMore:t,onNextPage:n,onPrevPage:r}){const s=typeof e=="number"&&e>0||t;return o.jsxs("div",{className:K("flex items-center justify-center gap-8 pt-6 text-ui-md text-neutral3"),children:[o.jsxs("span",{children:["Page ",o.jsx("b",{children:e?e+1:"1"})]}),s&&o.jsxs("div",{className:K("flex gap-4","[&>button]:flex [&>button]:items-center [&>button]:gap-2 [&>button]:rounded-md [&>button]:border [&>button]:border-border1 [&>button]:p-1 [&>button]:px-2 [&>button]:text-neutral4 [&>button]:transition-colors [&>button:hover]:text-neutral5","[&_svg]:size-[1em] [&_svg]:text-neutral3"),children:[typeof e=="number"&&e>0&&o.jsxs("button",{onClick:r,children:[o.jsx(bl,{}),"Previous"]}),t&&o.jsxs("button",{onClick:n,children:["Next",o.jsx(Fd,{})]})]})]})}function tbs({children:e,className:t}){return o.jsx("div",{className:K("grid grid-rows-[auto_1fr] overflow-y-auto",t),children:e})}function nbs({isSelected:e,children:t,columns:n}){return o.jsx("li",{className:K("flex overflow-hidden rounded-lg border border-transparent border-t-border1 py-[3px] pb-[2px] text-ui-md text-neutral5 first:border-t-transparent","[&:last-child>button]:rounded-b-lg","[&.selected-row]:border [&.selected-row]:border-dashed [&.selected-row]:border-white/50 [&.selected-row]:pr-[3px] [&.selected-row]:first:border-t","[&:has(+.selected-row)]:rounded-b-none [&:has(+.selected-row)]:border-b-transparent","[.selected-row+&]:rounded-t-none",Yr.colors,{"selected-row":e,"grid px-4 gap-4 ":n}),style:{gridTemplateColumns:vRe(n)},children:t})}function rbs({item:e,isFeatured:t,onClick:n,children:r,columns:s,className:a,disabled:i,tooltip:l,...c}){const u=()=>{n?.(e?.id)},d=o.jsx("button",{...c,onClick:u,className:K("grid w-full items-center gap-4 rounded-lg px-4 text-left",Yr.colors,M3.visible,{"bg-surface4":t,"hover:bg-surface4":e&&!t&&!i},a),style:{gridTemplateColumns:vRe(s)},disabled:i,children:r});return l==null?d:o.jsxs(xn,{children:[o.jsx(vn,{render:d}),o.jsx(yn,{children:l})]})}function sbs(e){return e.charAt(0).toUpperCase()+e.slice(1)}function abs({status:e}){return e?o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx("div",{className:K("relative flex h-full w-10 items-center justify-center bg-transparent"),children:o.jsx("div",{className:K("size-2 rounded-full",{"bg-green-600":["success","completed"].includes(e),"bg-red-700":["error","failed"].includes(e),"bg-yellow-500":["pending","running"].includes(e)})})})}),o.jsx(yn,{children:sbs(e)})]}):null}function ibs({children:e,isLoading:t,className:n}){return o.jsx("div",{className:K("truncate py-[0.6rem] text-ui-md text-neutral4",n),children:t?o.jsx("div",{className:"bg-surface4 h-4 animate-pulse rounded-md text-transparent select-none"}):e})}const SV={latest:"Latest version",deleted:"Deleted in this version"};function obs({isLatest:e,isDeleted:t}){const n=[];return e&&n.push(SV.latest),t&&n.push(SV.deleted),n.length>0?n.join(" · "):void 0}function lbs({version:e,date:t,isLatest:n,isDeleted:r}){return o.jsxs(THt,{className:K("grid grid-cols-[1fr_auto] pl-1"),children:[o.jsxs("div",{className:K("grid gap-1 leading-none text-neutral3",{"text-neutral4":n}),children:[o.jsxs("strong",{className:"font-normal",children:["v. ",e]}),o.jsx("em",{className:K("text-ui-sm","font-normal","text-neutral2"),children:t?dr(new Date(t),"MMM d, yyyy HH:mm"):null})]}),(n||r)&&o.jsxs("div",{className:"flex items-center gap-1",children:[n&&o.jsx("span",{className:"inline-flex",role:"img","aria-label":SV.latest,children:o.jsx(bt,{variant:"blue",size:"sm",icon:o.jsx(c1,{})})}),r&&o.jsx("span",{className:"inline-flex",role:"img","aria-label":SV.deleted,children:o.jsx(bt,{variant:"red",size:"sm",icon:o.jsx(k0e,{})})})]})]})}const gi=Object.assign(tbs,{Header:Hys,HeaderCol:Wys,Items:Gys,Scroller:Qys,Row:nbs,RowButton:rbs,Message:Xys,NextPageLoading:Jys,Pagination:ebs,Cell:THt,TextCell:ibs,StatusCell:abs,VersionCell:lbs,IdCell:Zys,DateCell:Vys,LinkCell:Kys,LabelCell:Yys});function cbs({datasetId:e,itemId:t,onVersionSelect:n,onCompareVersionsClick:r,activeVersion:s}){const{data:a,isLoading:i}=pRe(e,t),[l,c]=g.useState(!1),[u,d]=g.useState(new Set),f=b=>{n?.(b)},h=b=>s==null?b.isLatest:b.datasetVersion===s,p=b=>{d(x=>{const w=new Set(x);if(w.has(b))w.delete(b);else if(w.size>=2){const[k]=Array.from(w);return new Set([k,b])}else w.add(b);return w})},m=()=>{c(!1),d(new Set)},v=()=>{c(!0)},y=()=>{u.size===2&&r?.([...u])};return o.jsxs(ma,{className:"min-w-56",children:[l?o.jsx(ma.Toolbar,{className:"grid w-full justify-stretch gap-3",children:o.jsxs(es,{children:[o.jsx(ie,{onClick:m,children:"Cancel"}),o.jsx(ie,{variant:"primary",disabled:u.size!==2,onClick:y,tooltip:u.size!==2?"Check 2 versions to compare":void 0,className:"grow",children:"Compare"})]})}):o.jsx(o.Fragment,{children:(a||[]).length>1&&o.jsx(ma.Toolbar,{children:o.jsxs(ie,{onClick:v,className:"w-full",children:[o.jsx(Nj,{})," Compare Ver."]})})}),i?o.jsx(ubs,{}):o.jsxs(gi,{children:[o.jsx(gi.Header,{children:o.jsx(gi.HeaderCol,{children:"Item Version History"})}),o.jsx(gi.Scroller,{children:o.jsx(gi.Items,{children:a?.map(b=>{const x=String(b.datasetVersion),w=typeof b.updatedAt=="string"?new Date(b.updatedAt):b.updatedAt;return o.jsxs(gi.Row,{isSelected:l&&u.has(x),children:[l&&o.jsx(gi.LabelCell,{children:o.jsx(Oo,{checked:u.has(x),disabled:b.isDeleted,onCheckedChange:()=>{},onClick:k=>{k.stopPropagation(),b.isDeleted||p(x)},"aria-label":`Select version ${b.datasetVersion}`})}),o.jsx(gi.RowButton,{item:b,columns:[{name:"version",label:"Item Version History",size:"1fr"}],isFeatured:h(b),onClick:()=>f(b),className:"py-2",tooltip:obs({isLatest:b.isLatest,isDeleted:b.isDeleted}),children:o.jsx(gi.VersionCell,{version:b.datasetVersion,date:w,isLatest:b.isLatest,isDeleted:b.isDeleted})})]},String(b.datasetVersion))})})})]})]})}function ubs(){return o.jsxs(gi,{children:[o.jsx(gi.Header,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(gi.HeaderCol,{children:"Item Version History"})}),o.jsx(gi.Items,{children:Array.from({length:3}).map((e,t)=>o.jsx(gi.Row,{children:o.jsx(gi.RowButton,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(gi.TextCell,{isLoading:!0,children:"Loading..."})})},t))})]})}function dbs(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${dr(n,"MMM dd 'at' H:mm:ss a")}`}return`v${e}`}function fbs({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=jAe(e),a=(s??[]).map(i=>({value:String(i.version),label:`${dbs(i.version,i.createdAt)}${i.isCurrent?" (current)":""}`}));return o.jsxs(ma.Toolbar,{className:"grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4",children:[o.jsx("div",{}),o.jsx(Cm,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:a,value:t??"",onValueChange:i=>r?.(i,n??"")}),o.jsx(Cm,{label:"Version B",labelIsHidden:!0,name:"version-b",options:a,value:n??"",onValueChange:i=>r?.(t??"",i)}),o.jsx("div",{})]})}const hbs=[{name:"id",label:"ID",size:"1fr"},{name:"versionA",label:"Version A",size:"1fr"},{name:"versionB",label:"Version B",size:"1fr"},{name:"compare",label:"Compare",size:"10rem"}],M9={added:{badgeVariant:"blue",borderColor:"border-blue-900",icon:o.jsx(_r,{}),tooltip:"Added in this version"},changed:{badgeVariant:"yellow",borderColor:"border-yellow-900",icon:o.jsx(HJt,{}),tooltip:"Changed in this version"},same:{badgeVariant:"green",borderColor:"border-green-900",icon:o.jsx(Rct,{}),tooltip:"Same in both versions"}};function Xie({red:e=!1,tooltip:t}){return o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx("span",{}),role:"img",tabIndex:0,"aria-label":t,className:"focus-visible:outline-neutral5/55 rounded focus-visible:outline-1 focus-visible:outline-offset-2 focus-visible:outline-solid",children:o.jsx(k0e,{className:K("text-neutral3/40 w-5 h-5 ",{"text-red-900":e})})}),o.jsx(yn,{children:t})]})}function Jie({variant:e,version:t}){if(!e)return o.jsxs("span",{className:"text-ui-md text-neutral4",children:["v. ",t]});const{badgeVariant:n,icon:r,tooltip:s}=M9[e];return o.jsxs("div",{className:"grid grid-cols-[1fr_auto]",children:[t!==void 0&&o.jsxs("span",{className:"text-ui-md text-neutral4 flex min-w-16 justify-end pr-3",children:["v. ",t]}),o.jsx("span",{className:"inline-flex",role:"img","aria-label":s,children:o.jsx(bt,{variant:n,size:"xs",icon:r})})]})}function pbs(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function jtt({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return"added";if(t==="changed"&&n)return"changed"}function mbs({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:a}){const{Link:i}=dn(),l=t>n;return o.jsx(gi,{children:o.jsx(gi.Scroller,{children:o.jsx(gi.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=a.get(c),f=pbs(u,d),h=jtt({otherVersionExists:d!==void 0,status:f,isNewer:l}),p=jtt({otherVersionExists:u!==void 0,status:f,isNewer:!l});return o.jsxs(gi.Row,{columns:hbs,children:[o.jsx(gi.IdCell,{id:c,isShortened:!1}),f!=="same"?o.jsxs(o.Fragment,{children:[u?.datasetVersion?o.jsx(gi.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:h?M9[h].tooltip:void 0,children:o.jsx(Jie,{variant:h,version:u.datasetVersion})}):o.jsx(gi.Cell,{className:"flex items-center justify-center",children:o.jsx(Xie,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?o.jsx(gi.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:p?M9[p].tooltip:void 0,children:o.jsx(Jie,{variant:p,version:d.datasetVersion})}):o.jsx(gi.Cell,{className:"flex items-center justify-center",children:o.jsx(Xie,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):o.jsx(gi.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",tooltip:M9.same.tooltip,children:o.jsx(Jie,{variant:"same",version:d?.datasetVersion})}),f==="changed"?o.jsx(gi.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}/versions?ids=${u?.datasetVersion},${d?.datasetVersion}`,children:"Compare"}):o.jsx(gi.Cell,{children:o.jsx(Xie,{tooltip:"Comparing is available only for changed items"})})]},c)})})})})}function gbs(){const e=qr(),[t,n]=g.useState(""),[r,s]=g.useState("all"),[a,i]=g.useState("all"),{data:l=[],isLoading:c,error:u,isFetchingNextPage:d,hasNextPage:f,setEndOfListElement:h}=dPn(),{data:p,isLoading:m,error:v}=BH(),y=g.useMemo(()=>p?.experiments??[],[p?.experiments]),b=g.useMemo(()=>_vs(l),[l]),x=c||m,w=u||v,k=()=>{e("/datasets/new")};if(w&&hs(w))return o.jsx(Zn,{children:o.jsx(Ts,{})});if(w&&ps(w))return o.jsx(Zn,{children:o.jsx(ks,{resource:"datasets"})});if(w)return o.jsx(Zn,{children:o.jsx(La,{title:"Failed to load datasets",message:w.message})});if(l.length===0&&!x)return o.jsx(Zn,{children:o.jsx(Ivs,{onCreateClick:k})});const C=r!=="all"||a!=="all"||t!=="",_=()=>{n(""),s("all"),i("all")};return o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(Pvs,{search:t,onSearchChange:n,experimentFilter:r,onExperimentFilterChange:s,tagFilter:a,onTagFilterChange:i,tagOptions:b,onReset:_,hasActiveFilters:C,onCreateClick:k})}),o.jsx(Nvs,{datasets:l,experiments:y,isLoading:x,search:t,experimentFilter:r,tagFilter:a,isFetchingNextPage:d,hasNextPage:f,setEndOfListElement:h})]})}function n8({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function vbs(){const{datasetId:e}=fr(),t=qr(),[n,r]=za(),{activeVersion:s,handleVersionChange:a}=mRe(n,r),[i,l]=g.useState(!1),[c,u]=g.useState(!1),[d,f]=g.useState(!1),[h,p]=g.useState(!1),{data:m,error:v,isLoading:y}=zy(e),{data:b=[],isLoading:x}=Qx(e,void 0,s),w=!x&&b.length===0;if(y)return null;if(v&&hs(v))return o.jsx(n8,{children:o.jsx(Ts,{})});if(v&&ps(v))return o.jsx(n8,{children:o.jsx(ks,{resource:"datasets"})});if(v&&JEe(v)||!y&&!v&&!m)return o.jsx(n8,{children:o.jsx(br,{iconSlot:o.jsx(hm,{}),titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:o.jsxs(ie,{as:Da,to:"/datasets",children:[o.jsx(bl,{}),"Back to Datasets"]})})});if(v)return o.jsx(n8,{children:o.jsx(La,{title:"Failed to load dataset",message:v instanceof Error?v.message:"An unexpected error occurred. Please try again."})});const k=_=>{t(`/experiments/${_}`)},C=()=>{t("/datasets")};return o.jsxs(Oys,{datasetId:e,items:b,isLoadingItems:x,children:[o.jsxs("div",{className:"relative h-full overflow-hidden",children:[o.jsx(Lt,{height:"full",className:"grid-rows-[1fr] p-0",children:o.jsx(Lt.MainArea,{children:o.jsx(Cys,{datasetId:e,onAddItemClick:()=>u(!0),leftSlot:o.jsx("span",{className:"text-ui-sm text-neutral3 mr-3 whitespace-nowrap",children:m?.createdAt?`Created ${dr(new Date(m.createdAt),"MMM d")}`:""}),rightSlot:o.jsxs(es,{children:[o.jsxs(ie,{as:Da,to:`/experiments?dataset=${e}`,children:[o.jsx(_0e,{}),"View experiments"]}),o.jsx(bHt,{datasetId:e,value:s,onValueChange:a,currentVersion:m?.version,className:"w-36"}),w?o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx("span",{className:"cursor-not-allowed",children:o.jsx("div",{className:"pointer-events-none opacity-50",inert:!0,"aria-disabled":"true",children:o.jsxs(ie,{variant:"primary",children:[o.jsx(Dc,{}),"Run Experiment"]})})})}),o.jsx(yn,{children:"Add items to the dataset before running an experiment"})]}):o.jsxs(ie,{variant:"primary",onClick:()=>l(!0),children:[o.jsx(Dc,{}),"Run Experiment"]}),o.jsxs(at,{children:[o.jsx(at.Trigger,{asChild:!0,children:o.jsx(ie,{size:"lg","aria-label":"Dataset actions menu",children:o.jsx(iI,{})})}),o.jsxs(at.Content,{align:"end",className:"w-48",children:[o.jsxs(at.Item,{onSelect:()=>{t(`/datasets/${e}/edit`)},children:[o.jsx(Yh,{})," Edit Dataset"]}),o.jsxs(at.Item,{onSelect:()=>p(!0),children:[o.jsx(zd,{})," Duplicate Dataset"]}),o.jsxs(at.Item,{onSelect:()=>f(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(Fl,{})," Delete Dataset"]})]})]})]})})})}),o.jsx(Bg,{})]}),o.jsx(cY,{initialDatasetId:e,initialDatasetVersion:s??void 0,open:i,onOpenChange:l,onSuccess:k},`${e}:${s??"latest"}`),o.jsx(Eys,{datasetId:e,open:c,onOpenChange:u}),m&&o.jsx(Qvs,{open:h,onOpenChange:p,sourceDatasetId:m.id,sourceDatasetName:m.name,sourceDatasetDescription:m.description,sourceDatasetTargetType:m.targetType}),m&&o.jsx(Jvs,{open:d,onOpenChange:f,datasetId:m.id,datasetName:m.name,onSuccess:C})]})}function eoe({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function ybs(){const{datasetId:e}=fr(),t=qr(),{data:n,error:r,isLoading:s}=zy(e),a=()=>{t(`/datasets/${e}`)};return s?null:r&&hs(r)?o.jsx(eoe,{children:o.jsx(Ts,{})}):r&&ps(r)?o.jsx(eoe,{children:o.jsx(ks,{resource:"datasets"})}):r||!n?o.jsx(eoe,{children:o.jsx(La,{title:"Failed to load dataset",message:r instanceof Error?r.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-6 py-8",children:[o.jsx(Pa,{className:"mb-6 p-0",children:o.jsxs(Pa.Column,{children:[o.jsxs(Pa.Title,{children:[o.jsx(hm,{})," Edit dataset"]}),o.jsx(Pa.Description,{children:n.name})]})}),o.jsx(Ku,{className:"p-6",children:o.jsx(Xvs,{dataset:{id:n.id,name:n.name,description:n.description||"",inputSchema:n.inputSchema,groundTruthSchema:n.groundTruthSchema,requestContextSchema:n.requestContextSchema},onSuccess:a,onCancel:a})})]})})]})}function uY({label:e,wide:t=!1,children:n}){return o.jsxs("div",{className:K("pointer-events-none absolute inset-0 z-30","grid transition-[grid-template-columns] duration-300 ease-in-out",t?"grid-cols-[1fr_4fr]":"grid-cols-[1fr_1fr]"),children:[o.jsx("div",{className:"pointer-events-none"}),o.jsx("div",{role:"dialog","data-item-panel":!0,"aria-label":e,className:"pointer-events-auto h-full min-h-0 min-w-0 overflow-y-auto",children:n})]})}const r8=()=>{},bbs=new Set,xbs=[{name:"id",label:"ID",size:"7rem"},{name:"input",label:"Input",size:"minmax(10rem,1fr)"},{name:"groundTruth",label:"Ground Truth",size:"minmax(10rem,1fr)"},{name:"trajectory",label:"Trajectory",size:"8rem"},{name:"createdAt",label:"Created",size:"10rem"}];function wbs({datasetId:e,currentItemId:t,open:n,onOpenChange:r}){const{navigate:s,paths:a}=dn(),[i,l]=g.useState(""),[c]=YH(i,300),{data:u,isLoading:d,setEndOfListElement:f,isFetchingNextPage:h,hasNextPage:p}=Qx(e,c||void 0),m=u.filter(y=>y.id!==t),v=y=>{r(!1),s(a.datasetItemCompareLink(e,t,y))};return o.jsx(pr,{open:n,onOpenChange:r,children:o.jsxs(mr,{className:"sm:max-w-[min(72rem,calc(100%-4rem))]",children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Compare with…"}),o.jsx(Cs,{children:"Pick an item to compare with the current one."})]}),o.jsxs(jr,{className:"grid max-h-[70vh] min-h-[24rem] grid-rows-[auto_1fr] gap-3",children:[o.jsx(wC,{name:"compare-with-dialog-search",label:"Search items to compare",labelIsHidden:!0,value:i,onChange:y=>l(y.target.value),placeholder:"Search items..."}),o.jsx("div",{className:"min-h-0 overflow-y-auto",children:o.jsx(xHt,{items:m,isLoading:d,onItemClick:v,selectOnNavigate:!1,columns:xbs,searchQuery:c||" ",setEndOfListElement:f,isFetchingNextPage:h,hasNextPage:p,isSelectionActive:!1,selectedIds:bbs,onToggleSelection:r8,onSelectAll:r8,onClearSelection:r8,onAddClick:r8})})]})]})})}function Sbs(e){if(!(e instanceof Error))return null;const t=e.message.match(/- ({.*})$/);if(!t)return null;try{const n=JSON.parse(t[1]);if(n.field&&Array.isArray(n.errors))return{field:n.field,errors:n.errors}}catch{}return null}function kbs({datasetId:e,item:t,items:n,onItemChange:r,onClose:s}){const{Link:a}=dn(),{updateItem:i,deleteItem:l}=wi(),[c,u]=g.useState(!1),[d,f]=g.useState(""),[h,p]=g.useState(""),[m,v]=g.useState(""),[y,b]=g.useState(""),[x,w]=g.useState(""),[k,C]=g.useState(t.scorerIds!==void 0),[_,T]=g.useState(t.scorerIds??[]),[E,N]=g.useState(""),[I,A]=g.useState(null),[P,L]=g.useState(!1),[D,B]=g.useState(!1);g.useEffect(()=>{t&&(f(JSON.stringify(t.input,null,2)),p(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),v(t.metadata?JSON.stringify(t.metadata,null,2):""),b(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),w(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),C(t.scorerIds!==void 0),T(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),L(!1),A(null))},[t?.id]);const H=n.findIndex(U=>U.id===t.id),q=H>0?()=>r(n[H-1].id):void 0,z=H>=0&&H<n.length-1?()=>r(n[H+1].id):void 0,V=async()=>{let U;try{U=JSON.parse(d)}catch{Ve.error("Input must be valid JSON");return}let Z;if(h.trim())try{Z=JSON.parse(h)}catch{Ve.error("Ground Truth must be valid JSON");return}let Y;if(m.trim())try{Y=JSON.parse(m)}catch{Ve.error("Metadata must be valid JSON");return}let te=null;if(y.trim())try{te=JSON.parse(y)}catch{Ve.error("Expected Trajectory must be valid JSON");return}let J;if(x.trim())try{const ae=JSON.parse(x);if(!Array.isArray(ae)){Ve.error("Tool Mocks must be a JSON array");return}J=ae}catch{Ve.error("Tool Mocks must be valid JSON");return}else J=[];let ee;if(E.trim())try{ee=JSON.parse(E)}catch{Ve.error("Request Context must be valid JSON");return}let re;k?re=_:t.scorerIds!==void 0&&(re=null);try{const ae=await i.mutateAsync({datasetId:e,itemId:t.id,input:U,groundTruth:Z,metadata:Y,expectedTrajectory:te,toolMocks:J,scorerIds:re,requestContext:ee});Ve.success("Item updated successfully"),C(ae.scorerIds!==void 0),T(ae.scorerIds??[]),u(!1),A(null)}catch(ae){const X=Sbs(ae);X?A(X):Ve.error(`Failed to update item: ${ae instanceof Error?ae.message:"Unknown error"}`)}},M=()=>{f(JSON.stringify(t.input,null,2)),p(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),v(t.metadata?JSON.stringify(t.metadata,null,2):""),b(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),w(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),C(t.scorerIds!==void 0),T(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),A(null)},G=U=>{f(U),I?.field==="input"&&A(null)},F=U=>{p(U),I?.field==="groundTruth"&&A(null)},R=async()=>{try{await l.mutateAsync({datasetId:e,itemId:t.id}),Ve.success("Item deleted successfully"),L(!1),s()}catch(U){Ve.error(`Failed to delete item: ${U instanceof Error?U.message:"Unknown error"}`)}};return o.jsxs(o.Fragment,{children:[o.jsxs(Gt,{children:[o.jsxs(Gt.Header,{children:[o.jsxs(Gt.Heading,{children:["Item ",o.jsxs("b",{children:["# ",t.id.length>12?`${t.id.slice(0,12)}…`:t.id]})]}),o.jsxs(es,{className:"ml-auto shrink-0",children:[o.jsx(Gt.NextPrevNav,{onPrevious:q,onNext:z,previousLabel:"Previous item",nextLabel:"Next item"}),!c&&o.jsxs(o.Fragment,{children:[o.jsx(ie,{as:a,href:`/datasets/${e}/items/${t.id}/versions`,size:"md",tooltip:"Go to item versions history","aria-label":"Go to item versions history",children:o.jsx(uI,{})}),o.jsxs(at,{children:[o.jsx(at.Trigger,{asChild:!0,children:o.jsx(ie,{size:"md","aria-label":"Actions menu",children:o.jsx(iI,{})})}),o.jsxs(at.Content,{align:"end",className:"w-48",children:[o.jsxs(at.Item,{onSelect:()=>u(!0),children:[o.jsx(Yh,{}),"Edit"]}),o.jsxs(at.Item,{onSelect:()=>B(!0),children:[o.jsx(Nj,{}),"Compare with…"]}),o.jsxs(at.Item,{onSelect:()=>L(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(Fl,{}),"Delete Item"]})]})]})]}),o.jsx(Gt.CloseButton,{onClick:s,tooltip:"Close detail panel"})]})]}),o.jsx(Gt.Content,{children:c?o.jsx(jys,{inputValue:d,setInputValue:G,groundTruthValue:h,setGroundTruthValue:F,metadataValue:m,setMetadataValue:v,trajectoryValue:y,setTrajectoryValue:b,toolMocksValue:x,setToolMocksValue:w,scorerOverrideEnabled:k,setScorerOverrideEnabled:C,selectedScorerIds:_,setSelectedScorerIds:T,requestContextValue:E,setRequestContextValue:N,validationErrors:I,onSave:V,onCancel:M,isSaving:i.isPending}):o.jsxs(o.Fragment,{children:[o.jsxs(En,{children:[o.jsx(En.Key,{children:"Dataset Id"}),o.jsx(En.ValueWithCopyBtn,{copyTooltip:"Copy Dataset Id to clipboard",copyValue:t.datasetId,children:t.datasetId}),o.jsx(En.Key,{children:"Version"}),o.jsxs(En.Value,{children:["v",t.datasetVersion]}),o.jsx(En.Key,{children:"Created"}),o.jsx(En.Value,{children:dr(new Date(t.createdAt),"MMM d, yyyy h:mm aaa")}),t.updatedAt&&new Date(t.updatedAt).getTime()!==new Date(t.createdAt).getTime()&&o.jsxs(o.Fragment,{children:[o.jsx(En.Key,{children:"Updated"}),o.jsx(En.Value,{children:dr(new Date(t.updatedAt),"MMM d, yyyy h:mm aaa")})]})]}),o.jsxs("div",{className:"mt-3 grid gap-3",children:[o.jsx(Gt.CodeSection,{title:"Input",icon:o.jsx(Ox,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(Gt.CodeSection,{title:"Ground Truth",icon:o.jsx(nm,{}),codeStr:JSON.stringify(t.groundTruth??null,null,2)}),t.expectedTrajectory!=null&&o.jsx(Gt.CodeSection,{title:"Expected Trajectory",icon:o.jsx(P0e,{}),codeStr:JSON.stringify(t.expectedTrajectory,null,2)}),o.jsx(Gt.CodeSection,{title:"Tool Mocks",icon:o.jsx(Ud,{}),codeStr:JSON.stringify(t.toolMocks??[],null,2)}),o.jsx(Gt.CodeSection,{title:"Scorers",icon:o.jsx(PV,{}),codeStr:t.scorerIds===void 0?"Inherited from dataset":JSON.stringify(t.scorerIds,null,2)}),t.requestContext!=null&&o.jsx(Gt.CodeSection,{title:"Request Context",icon:o.jsx(sc,{}),codeStr:JSON.stringify(t.requestContext,null,2)}),o.jsx(Gt.CodeSection,{title:"Metadata",icon:o.jsx(dI,{}),codeStr:JSON.stringify(t.metadata??null,null,2)})]})]})})]}),o.jsx(wbs,{datasetId:e,currentItemId:t.id,open:D,onOpenChange:B}),o.jsx($t,{open:P,onOpenChange:L,children:o.jsxs($t.Content,{children:[o.jsxs($t.Header,{children:[o.jsx($t.Title,{children:"Delete Item"}),o.jsx($t.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),o.jsxs($t.Footer,{children:[o.jsx($t.Cancel,{children:"Cancel"}),o.jsx($t.Action,{onClick:R,children:l.isPending?"Deleting...":"Yes, Delete"})]})]})})]})}function Obs(){const{itemId:e}=fr(),{datasetId:t,items:n,isLoadingItems:r,openItem:s,close:a}=kHt(),i=g.useMemo(()=>n.find(d=>d.id===e)??null,[n,e]),{data:l,isLoading:c}=WD(i?"":t,!i&&e?e:""),u=i??l??null;return e?o.jsx(uY,{label:`Dataset item ${e}`,children:u?o.jsx("div",{className:"[&>section]:bg-surface3 flex min-h-full flex-col p-3 [&>section]:min-h-0 [&>section]:flex-1 [&>section]:rounded-lg [&>section]:shadow-lg",children:o.jsx(kbs,{datasetId:t,item:u,items:n,onItemChange:s,onClose:a})}):r||c?o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(Vt,{})})}):o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(br,{iconSlot:o.jsx(hm,{}),titleSlot:"Item not found",descriptionSlot:`No loaded item "${e}".`,actionSlot:o.jsx(ie,{onClick:a,children:"Close"})})})})}):null}function Ntt(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,metadata:e.metadata??null},null,2)}function Cbs(){const{datasetId:e,itemId:t,secondItemId:n}=fr(),r=qr(),s=[t,n].filter(p=>!!p),{data:a,error:i}=zy(e??""),{Link:l,paths:c}=dn(),[u,d]=g.useState(!1),{data:f}=WD(e??"",s[0]??""),{data:h}=WD(e??"",s[1]??"");return i&&hs(i)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{})})}):i&&ps(i)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ks,{resource:"datasets"})})}):!e||s.length<2?o.jsx(vs,{children:o.jsx(by,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Select at least two items to compare."})})})}):o.jsxs(vs,{children:[o.jsx(By,{owner:"dataset-items-compare",children:o.jsxs(ie,{as:Da,to:`/datasets/${e}`,variant:"outline",children:[o.jsx(bl,{}),"Back to Dataset"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:K("grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",{"grid-rows-[auto_auto_1fr]":u}),children:[o.jsxs(Pa,{children:[o.jsxs(Pa.Column,{children:[o.jsxs(Pa.Title,{children:[o.jsx(Nj,{}),"Compare Dataset Items"]}),o.jsx(Pa.Description,{children:o.jsxs(Pl,{children:["Comparing ",s.length," items of"," ",o.jsx(Da,{to:`/datasets/${e}`,className:"text-info1 hover:underline",children:a?.name||e?.slice(0,8)})]})})]}),o.jsx(Pa.Column,{children:o.jsx(es,{children:o.jsx(ie,{variant:"primary",onClick:()=>d(p=>!p),children:u?o.jsxs(o.Fragment,{children:[o.jsx(TV,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(vKt,{})," Diff View"]})})})})]}),o.jsx(o1,{className:"grid-cols-[1fr_3vw_1fr]",children:s.map((p,m)=>o.jsxs(g.Fragment,{children:[o.jsx(_bs,{datasetId:e,itemId:p,Link:l,idx:m,itemIds:s,showContent:!u,onItemChange:v=>{const y=[...s];y[m]=v,r(c.datasetItemCompareLink(e,y[0],y[1]))}}),m==0&&o.jsx("div",{className:K("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},p))}),u&&f&&h&&o.jsx(FAe,{codeA:Ntt(f),codeB:Ntt(h)})]})})]})}function _bs({datasetId:e,itemId:t,Link:n,idx:r,itemIds:s,onItemChange:a,showContent:i=!0}){const{data:l,isLoading:c}=WD(e,t),{data:u}=Qx(e),d=new Set(s.filter((h,p)=>p!==r)),f=(u??[]).map(h=>({value:h.id,label:h.id,disabled:d.has(h.id)}));return o.jsxs(ma,{children:[o.jsxs(ma.Toolbar,{className:"flex gap-4",children:[o.jsxs(la,{name:`compare-item-${r}`,value:t,onValueChange:a,children:[o.jsx(ua,{"aria-label":"Item",children:o.jsx(ca,{placeholder:"Select item"})}),o.jsx(da,{children:f.map(h=>o.jsx(xr,{value:h.value,disabled:h.disabled,children:h.label},h.value))})]}),o.jsxs(ie,{as:n,to:`/datasets/${e}/items/${t}`,children:[o.jsx(uI,{}),"Versions"]})]}),i&&o.jsx(ma.Content,{children:c?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):l?o.jsxs(o.Fragment,{children:[o.jsx(Tys,{item:l}),o.jsx(gRe,{item:l,Link:n})]}):o.jsxs("div",{className:"text-neutral4 text-sm",children:["Item ",t.slice(0,8)," not found"]})})]})}function Itt(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,scorerIds:e.scorerIds??null,metadata:e.metadata??null},null,2)}function Ebs(){const{datasetId:e,itemId:t}=fr(),[n,r]=za(),[s,a]=g.useState(!1),i=n.get("ids")?.split(",").map(Number).filter(p=>!isNaN(p)&&p>0)??[],{data:l,error:c}=zy(e??""),{Link:u}=dn(),{data:d}=pRe(e??"",t??""),{data:f}=r0e(e??"",t??"",i[0]??0,l?.version),{data:h}=r0e(e??"",t??"",i[1]??0,l?.version);return c&&hs(c)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{})})}):c&&ps(c)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ks,{resource:"datasets"})})}):!e||!t?o.jsx(vs,{children:o.jsx(by,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Item not found."})})})}):i.length<2?o.jsx(Tbs,{datasetId:e,itemId:t,Link:u,onCompare:p=>r({ids:p.join(",")})}):o.jsxs(vs,{children:[o.jsx(By,{owner:"dataset-item-versions-compare",children:o.jsxs(ie,{as:Da,to:`/datasets/${e}/items/${t}`,variant:"outline",children:[o.jsx(bl,{}),"Back to Item"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:K("grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",{"grid-rows-[auto_auto_1fr]":s}),children:[o.jsxs(Pa,{children:[o.jsxs(Pa.Column,{children:[o.jsxs(Pa.Title,{children:[o.jsx(Nj,{}),"Compare Dataset Item Versions"]}),o.jsx(Pa.Description,{children:o.jsxs(Pl,{children:["Comparing ",i.length," versions of"," ",o.jsx(Da,{to:`/datasets/${e}/items/${t}`,className:"text-info1 hover:underline",children:t})]})})]}),o.jsx(Pa.Column,{children:o.jsx(es,{children:o.jsx(ie,{variant:"primary",onClick:()=>a(p=>!p),children:s?o.jsxs(o.Fragment,{children:[o.jsx(TV,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(fXt,{})," Diff View"]})})})})]}),o.jsx(o1,{className:"grid-cols-[1fr_3vw_1fr]",children:i.map((p,m)=>o.jsxs(g.Fragment,{children:[o.jsx(jbs,{datasetId:e,itemId:t,datasetVersion:p,latestVersion:l?.version,allVersions:d??[],versionNumbers:i,Link:u,idx:m,showContent:!s,onVersionChange:v=>{const y=[...i];y[m]=v,r({ids:y.join(",")})}}),m===0&&o.jsx("div",{className:K("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},p))}),s&&f&&h&&o.jsx(FAe,{codeA:Itt(f),codeB:Itt(h)})]})})]})}function Tbs({datasetId:e,itemId:t,Link:n,onCompare:r}){const[s,a]=g.useState(null),{data:i,isLoading:l}=pRe(e,t),c=(s!=null?i?.find(d=>d.datasetVersion===s):void 0)??i?.[0],u=c?{id:c.id,datasetId:e,datasetVersion:c.datasetVersion,input:c.input,groundTruth:c.groundTruth,scorerIds:c.scorerIds,metadata:c.metadata,createdAt:c.createdAt,updatedAt:c.updatedAt}:null;return o.jsxs(vs,{children:[o.jsx(By,{owner:"dataset-item-versions-history",children:o.jsxs(ie,{as:Da,to:`/datasets/${e}/items/${t}`,variant:"outline",children:[o.jsx(bl,{}),"Back to Item"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:"mx-auto grid h-full max-w-[140rem] grid-rows-[auto_1fr] gap-6",children:[o.jsx(Pa,{children:o.jsxs(Pa.Column,{children:[o.jsxs(Pa.Title,{children:[o.jsx(uI,{}),"Item Version History"]}),o.jsx(Pa.Description,{children:o.jsxs(Pl,{children:["Versions of ",t]})})]})}),o.jsxs(o1,{className:"grid-cols-[1fr_auto]",children:[o.jsx(ma,{children:o.jsx(ma.Content,{children:l?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):u?o.jsx(gRe,{item:u,Link:n}):o.jsx("div",{className:"text-neutral4 text-sm",children:"Item data not available"})})}),o.jsx(cbs,{datasetId:e,itemId:t,onClose:()=>{},onVersionSelect:d=>a(d.datasetVersion),onCompareVersionsClick:r,activeVersion:s})]})]})})]})}function jbs({datasetId:e,itemId:t,datasetVersion:n,latestVersion:r,allVersions:s,versionNumbers:a,Link:i,idx:l,showContent:c=!0,onVersionChange:u}){const{data:d,isLoading:f}=r0e(e,t,n,r),h=new Set(a.filter((v,y)=>y!==l)),p=s.map(v=>{const y=typeof v.updatedAt=="string"?new Date(v.updatedAt):v.updatedAt;return{value:String(v.datasetVersion),label:o.jsxs(o.Fragment,{children:[o.jsxs("b",{children:["v. ",v.datasetVersion]})," - ",dr(y,"MMM d, yyyy h:mm a"),v.isLatest?o.jsx(bt,{variant:"blue",size:"xs",children:"Latest"}):null]}),disabled:h.has(v.datasetVersion)}}),m=d?{id:d.id,datasetId:e,datasetVersion:d.datasetVersion,input:d.input,groundTruth:d.groundTruth,scorerIds:d.scorerIds,metadata:d.metadata,createdAt:d.createdAt,updatedAt:d.updatedAt}:null;return o.jsxs(ma,{children:[o.jsxs(ma.Toolbar,{className:"grid grid-cols-[auto_1fr] gap-4",children:[o.jsx(uI,{className:"h-6 w-6 opacity-50"}),o.jsxs(la,{name:`compare-version-${l}`,value:String(n),onValueChange:v=>u(Number(v)),children:[o.jsx(ua,{"aria-label":"Version",className:"w-full",children:o.jsx(ca,{placeholder:"Select version"})}),o.jsx(da,{children:p.map(v=>o.jsx(xr,{value:v.value,disabled:v.disabled,children:v.label},v.value))})]})]}),c&&o.jsx(ma.Content,{children:f?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):!d||!m?o.jsxs("div",{className:"text-neutral4 text-sm",children:["Version ",n," not found"]}):o.jsx(gRe,{item:m,Link:i})})]})}function Nbs(){const{datasetId:e}=fr(),[t]=za(),n=t.get("ids")?.split(",").map(Number).filter(v=>!isNaN(v)&&v>0)??[],r=qr(),{data:s,error:a}=zy(e??""),i=Qx(e??"",void 0,n[0]??null),l=Qx(e??"",void 0,n[1]??null),c=g.useMemo(()=>i.data??[],[i.data]),u=g.useMemo(()=>l.data??[],[l.data]),d=g.useMemo(()=>{const v=new Map;for(const y of[...c,...u])v.has(y.id)||v.set(y.id,{id:y.id,createdAt:new Date(y.createdAt)});return[...v.values()].sort((y,b)=>b.createdAt.getTime()-y.createdAt.getTime())},[c,u]),f=g.useMemo(()=>new Map(c.map(v=>[v.id,v])),[c]),h=g.useMemo(()=>new Map(u.map(v=>[v.id,v])),[u]);if(a&&hs(a))return o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{})})});if(a&&ps(a))return o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ks,{resource:"datasets"})})});if(!e||n.length<2)return o.jsx(vs,{children:o.jsx(by,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Select at least two versions to compare."})})})});const p=(v,y,b)=>{r(`/datasets/${e}/items/${v}/versions?ids=${y?.datasetVersion??""},${b?.datasetVersion??""}`)},m=(v,y)=>{r(`/datasets/${e}/versions?ids=${v},${y}`,{replace:!0})};return o.jsx(vs,{children:o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:"mx-auto grid h-full max-w-[140rem] grid-rows-[auto_1fr] gap-6",children:[o.jsxs(Pa,{children:[o.jsxs(Pa.Column,{children:[o.jsxs(Pa.Title,{children:[o.jsx(xen,{})," Compare Dataset Versions"]}),o.jsx(Pa.Description,{children:o.jsxs(Pl,{children:[o.jsx(uI,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),o.jsx(Pa.Column,{children:o.jsxs(ie,{as:Da,to:`/datasets/${e}`,children:[o.jsx(bl,{}),"Back to Dataset"]})})]}),o.jsx(o1,{children:o.jsxs(ma,{children:[o.jsx(fbs,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:m}),o.jsx(mbs,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:h,onItemClick:p})]})})]})})})}function Ibs(){const e=qr(),[t]=za(),n=t.get("targetType"),r=s0e(n)?n:void 0,s=t.get("targetIds"),a=r&&s?s.split(",").map(i=>i.trim()).filter(Boolean):void 0;return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-6 py-8",children:[o.jsx(Pa,{className:"mb-6 p-0",children:o.jsxs(Pa.Column,{children:[o.jsxs(Pa.Title,{children:[o.jsx(hm,{})," Create new dataset"]}),o.jsx(Pa.Description,{children:"Datasets group test cases used to evaluate your agents and workflows."})]})}),o.jsx(Ku,{className:"p-6",children:o.jsx(Wvs,{targetType:r,targetIds:a,onSuccess:i=>{e(`/datasets/${i}`)},onCancel:()=>{e(-1)}})})]})})]})}function o0e({children:e,className:t}){return o.jsx("div",{className:K("flex flex-wrap gap-8",t),children:e})}function Abs(e){if(!e||e.length<2)return null;const t=[...e].sort((i,l)=>new Date(i.createdAt).getTime()-new Date(l.createdAt).getTime()),n=Math.floor(t.length/2),r=n,s=t.length-n;if(r===0)return null;const a=(s-r)/r*100;return{changePct:Math.round(a*10)/10,prevValue:String(r)}}function Rbs({scorers:e,datasets:t,experiments:n,avgScore:r,prevAvgScore:s,totalNeedsReview:a,isLoadingScorers:i,isLoadingDatasets:l,isLoadingExperiments:c,isLoadingScores:u,isLoadingReview:d}){const f=e?Object.keys(e).length:void 0,h=t?.length,p=n?.length,m=r!=null&&s!=null&&s!==0?{changePct:Math.round((r-s)/s*100*10)/10,prevValue:String(s)}:null,v=Abs(n);return o.jsxs(o.Fragment,{children:[o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Total Scorers"}),i?o.jsx(Xr.Loading,{}):f!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(f)}),o.jsx(Xr.NoChange,{message:"Static count"})]}):o.jsx(Xr.NoData,{})]}),o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Total Datasets"}),l?o.jsx(Xr.Loading,{}):h!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(h)}),o.jsx(Xr.NoChange,{message:"Static count"})]}):o.jsx(Xr.NoData,{})]}),o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Avg Score"}),u?o.jsx(Xr.Loading,{}):r!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(r)}),m?o.jsx(Xr.Change,{changePct:m.changePct,prevValue:m.prevValue}):o.jsx(Xr.NoChange,{})]}):o.jsx(Xr.NoData,{})]}),o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Total Experiments"}),c?o.jsx(Xr.Loading,{}):p!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(p)}),v?o.jsx(Xr.Change,{changePct:v.changePct,prevValue:v.prevValue}):o.jsx(Xr.NoChange,{})]}):o.jsx(Xr.NoData,{})]}),o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Needs Review"}),d?o.jsx(Xr.Loading,{}):a!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(a)}),a>0?o.jsx(Xr.NoChange,{message:"items pending review"}):o.jsx(Xr.NoChange,{message:"All caught up"})]}):o.jsx(Xr.NoData,{})]})]})}function jHt(e){const t=y0(e.id)??e.id;return e.name||`Experiment #${t}`}const Pbs=60;function $bs({experiment:e}){return o.jsx("span",{className:"text-neutral4 block min-w-0 truncate text-left",children:jHt(e)})}function Mbs({experiment:e}){const t=e.description;if(!t)return o.jsx("span",{className:"text-neutral2",children:"—"});const n=o.jsx("span",{className:"text-neutral3 block min-w-0 truncate text-left",children:t});return t.length<=Pbs?n:o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:n}),o.jsx(yn,{children:t})]})}const dY=()=>{const{requestContext:e}=ys(),t=Ye();return mt({queryKey:["processors"],queryFn:()=>t.listProcessors(e)})},NHt=(e,t)=>{const n=Ye(),{requestContext:r}=ys();return mt({queryKey:["processor",e],queryFn:()=>n.getProcessor(e).details(r),enabled:!!e})},Dbs=()=>{const e=Ye(),{requestContext:t}=ys();return Sn({mutationFn:async({processorId:n,phase:r,messages:s,agentId:a})=>e.getProcessor(n).execute({phase:r,messages:s,agentId:a,requestContext:t})})};function IHt(){const{data:e}=Bm(),{data:t}=Xy(),{data:n}=up(),{data:r}=dY();return{agents:e,workflows:t,scorers:n,processors:r}}const AHt={agent:Ri,workflow:Bc,scorer:P_,processor:jD},RHt={agent:"Agent",workflow:"Workflow",scorer:"Scorer",processor:"Processor"},Lbs="External (caller-run)";function PHt(e,{agents:t,workflows:n,scorers:r,processors:s}){const{targetType:a,targetId:i}=e;if(!i)return Lbs;switch(a){case"agent":return t?.[i]?.name??i;case"workflow":return n?.[i]?.name??i;case"scorer":return r?.[i]?.scorer?.config?.name??i;case"processor":return s?.[i]?.name??i;default:return i}}function Fbs({experiment:e,datasetName:t,review:n}){const r=e.status??"pending",s=e.succeededCount??0,a=e.failedCount??0,i=e.totalItems??0;return o.jsxs(o.Fragment,{children:[o.jsx(pe.Cell,{children:o.jsx($bs,{experiment:e})}),o.jsx(pe.Cell,{children:o.jsx(Mbs,{experiment:e})}),t!==void 0&&o.jsx(pe.TextCell,{children:t}),o.jsx(pe.Cell,{children:o.jsx(zbs,{experiment:e})}),o.jsx(pe.Cell,{children:o.jsx(bt,{variant:uqt[r]??"neutral",indicator:"dot",children:LT[r]??r})}),o.jsx(pe.TextCell,{className:"text-center",children:i}),o.jsx(pe.TextCell,{className:"text-center",children:s}),o.jsx(pe.TextCell,{className:"text-center",children:o.jsx("span",{className:a>0?"text-accent2":"",children:a})}),o.jsx(pe.Cell,{className:"text-center",children:o.jsx(Bbs,{review:n})}),o.jsx(pe.TextCell,{children:Sus(e.createdAt)})]})}function zbs({experiment:e}){const t=IHt(),n=PHt(e,t),r=e.targetId?e.targetType:null,s=r?AHt[r]:null;return o.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 [&_svg]:size-3.5 [&_svg]:shrink-0",children:[s&&o.jsx("span",{className:"text-neutral3 flex",role:"img","aria-label":RHt[r],children:o.jsx(s,{})}),o.jsx("span",{className:r?"truncate":"text-neutral2 truncate",children:n})]})}function Bbs({review:e}){if(!e)return o.jsx("span",{className:"text-neutral2",children:"—"});const t=e.needsReview+e.complete;return t===0?o.jsx("span",{className:"text-neutral2",children:"—"}):e.needsReview>0?o.jsxs(bt,{size:"xs",variant:"yellow",children:[e.needsReview," pending"]}):o.jsxs(bt,{size:"xs",variant:"green",children:[e.complete,"/",t," reviewed"]})}const toe=`${yus} ${bus} ${xus} ${wus}`,Ubs=[{label:Ev.experiment},{label:Ev.description},{label:Ev.dataset},{label:Ev.target},{label:Ev.status},{label:Ev.items,className:"text-center"},{label:Ev.succeeded,className:"text-center"},{label:Ev.failed,className:"text-center"},{label:Ev.review,className:"text-center"},{label:Ev.date}];function qbs({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:a="all",datasetFilter:i="all",selection:l}){const c=l!==void 0,{paths:u,Link:d}=dn(),f=g.useMemo(()=>{const x=new Map;return t?.forEach(w=>x.set(w.id,w.name)),x},[t]),h=g.useMemo(()=>[...e].sort((x,w)=>{const k=x.createdAt?new Date(x.createdAt).getTime():0;return(w.createdAt?new Date(w.createdAt).getTime():0)-k}),[e]),p=g.useMemo(()=>{const x=s.toLowerCase();return h.filter(w=>{const k=w.datasetId?f.get(w.datasetId)??"":"",C=!x||w.id.toLowerCase().includes(x)||(w.name??"").toLowerCase().includes(x)||k.toLowerCase().includes(x)||(w.targetId??"").toLowerCase().includes(x),_=a==="all"||w.status===a,T=i==="all"||w.datasetId===i;return C&&_&&T})},[h,s,f,a,i]),{containerRef:m,getRowProps:v}=ao({count:p.length});if(r)return o.jsx(Bo,{columns:toe});const y=c?`auto ${toe}`:toe,b=Ubs.map(x=>o.jsx(pe.TopCell,{className:x.className,children:x.label},x.label));return o.jsxs(pe,{columns:y,scrollRef:m,children:[o.jsx(pe.Top,{hasLeadingCell:c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(pe.TopCell,{children:" "}),o.jsx(pe.TopCells,{colStart:2,children:b})]}):b}),p.map((x,w)=>{const k=x.datasetId?f.get(x.datasetId)??y0(x.datasetId)??x.datasetId:"—",C=o.jsx(Fbs,{experiment:x,datasetName:k,review:n?.get(x.id)});if(!l)return o.jsx(pe.RowLink,{to:u.experimentLink(x.id),LinkComponent:d,...v(w),children:C},x.id);const _=l.selectedExperimentIds.includes(x.id),T=()=>l.onToggleSelection(x.id);return o.jsxs(pe.RowWrapper,{children:[o.jsx(pe.SelectCell,{checked:_,onToggle:T,"aria-label":`Select experiment ${x.id}`}),o.jsx(pe.RowButton,{colStart:2,featured:_,onClick:T,...v(w),children:C})]},x.id)})]})}const Vbs=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function Hbs(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const s8={completed:L7.neutral3,running:"#facc15",pending:"#fb923c",failed:"#f87171"},Wbs=[{label:"Completed",color:s8.completed},{label:"Running",color:s8.running},{label:"Pending",color:s8.pending},{label:"Failed",color:s8.failed}];function Zbs({experiments:e,datasets:t,isLoading:n,isError:r}){const{data:s,maxVal:a}=g.useMemo(()=>{if(!e||e.length===0)return{data:[],maxVal:0};const l=new Map;if(t)for(const f of t)l.set(f.id,f.name);const c=new Map;for(const f of e){const h=f.datasetId??"unknown";c.has(h)||c.set(h,{completed:0,running:0,pending:0,failed:0});const p=c.get(h),m=f.status;m in p&&p[m]++}let u=0;return{data:Array.from(c.entries()).map(([f,h])=>{const p=h.completed+h.running+h.pending+h.failed;return p>u&&(u=p),{name:l.get(f)??f.slice(0,12),values:[h.completed,h.running,h.pending,h.failed]}}),maxVal:u}},[e,t]),i=s.length>0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Experiments by Dataset",description:"Experiment status breakdown per dataset."}),i&&o.jsx(Ht.Summary,{value:String(e?.length??0),label:"Total experiments"})]}),n?o.jsx(Ht.Loading,{}):r?o.jsx(Ht.Error,{message:"Failed to load experiments data"}):o.jsx(Ht.Content,{children:i?o.jsx(KN,{data:s,segments:Wbs,maxVal:a,fmt:l=>String(l)}):o.jsx(Ht.NoData,{message:"No experiments have been run yet"})})]})}const Gbs=({onRunExperiment:e})=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx(Mc,{}),titleSlot:"No Experiments yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Run an experiment from a dataset to evaluate ",o.jsx("br",{}),"your agents and workflows."]}),actionSlot:o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e&&o.jsxs(ie,{variant:"primary",onClick:e,children:[o.jsx(Dc,{}),"Run Experiment"]}),o.jsxs(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/evals/experiments",target:"_blank",rel:"noopener noreferrer",children:["Experiments Documentation ",o.jsx(ta,{})]})]})})});function Qbs({search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:i,onReset:l,hasActiveFilters:c,onRunClick:u,runTooltip:d="Run an experiment",onCompareClick:f,selection:h}){if(h){const{selectedCount:p,onExecuteCompare:m,onCancelSelection:v,compareDisabledReason:y}=h,b=p===2&&!y;return o.jsx("div",{className:"flex w-full items-center justify-end gap-4",children:o.jsxs("div",{className:"flex items-center gap-5",children:[o.jsxs("div",{className:"text-neutral3 flex items-center gap-2 pl-6 text-sm",children:[o.jsx(bt,{size:"md",variant:p<2?"red":"green",children:p}),o.jsx("span",{children:"of 2 experiments selected"}),y&&o.jsxs("span",{className:"text-accent2",children:["— ",y]}),o.jsx(qct,{})]}),o.jsxs(es,{children:[o.jsxs(ie,{variant:"primary",disabled:!b,onClick:m,children:[o.jsx(Nj,{className:"h-4 w-4"}),"Compare Experiments"]}),o.jsx(ie,{onClick:v,children:"Cancel"})]})]})})}return o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("div",{className:"max-w-120 min-w-64 flex-1",children:o.jsx(cd,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t})}),o.jsxs(es,{children:[o.jsx(Cm,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...Vbs],value:n,onValueChange:r,className:"whitespace-nowrap"}),o.jsx(Cm,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:i,value:s,onValueChange:a,className:"whitespace-nowrap"}),l&&c&&o.jsxs(ie,{onClick:l,size:"sm",variant:"default",children:[o.jsx(or,{className:"size-3"})," Reset"]})]}),o.jsxs(es,{className:"ml-auto shrink-0",children:[f&&o.jsxs(ie,{onClick:f,tooltip:"Select two experiments of the same dataset to compare",children:[o.jsx(Nj,{}),"Compare"]}),u&&o.jsxs(ie,{onClick:u,tooltip:d,variant:"primary",children:[o.jsx(Dc,{}),"Run Experiment"]})]})]})}const Ybs={present:!1,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},Att=e=>e?e instanceof Date?e.toISOString():e:null,Rtt=e=>{const t=new Map;for(const n of e??[])t.set(n.itemId,n);return t},Ptt=(e,t,n)=>{if(!e)return Ybs;const r=new Map;for(const s of n??[])r.set(s.scorerId,s.reason??null);return{present:!0,output:e.output,metadata:t?.metadata??null,comment:t?.comment??null,error:t?.error??null,startedAt:Att(t?.startedAt),completedAt:Att(t?.completedAt),scores:Object.entries(e.scores).map(([s,a])=>({scorerId:s,value:a,reason:r.get(s)??null})).sort((s,a)=>s.scorerId.localeCompare(a.scorerId))}},Kbs=({comparison:e,baselineId:t,contenderId:n,baselineResults:r,contenderResults:s,baselineScores:a,contenderScores:i})=>{if(!e)return[];const l=Rtt(r),c=Rtt(s);return e.items.map(u=>{const d=Ptt(u.results[t],l.get(u.itemId),a?.[u.itemId]),f=Ptt(u.results[n],c.get(u.itemId),i?.[u.itemId]),h={};for(const p of new Set([...d.scores,...f.scores].map(m=>m.scorerId))){const m=d.scores.find(y=>y.scorerId===p)?.value??null,v=f.scores.find(y=>y.scorerId===p)?.value??null;h[p]=m!=null&&v!=null?v-m:null}return{itemId:u.itemId,input:u.input,groundTruth:u.groundTruth,baseline:d,contender:f,deltas:h}})};function Lk({title:e,actions:t,tone:n="default",defaultOpen:r=!0,children:s}){return o.jsxs(fc,{defaultOpen:r,className:"grid gap-2",children:[o.jsxs("div",{className:"flex min-h-6 items-center justify-between gap-2",children:[o.jsxs(ql,{className:K("text-ui-md flex items-center gap-1.5 font-semibold [&>svg]:size-4",n==="negative"?"text-negative1":"text-neutral5"),children:[o.jsx(Lr,{}),e]}),t]}),o.jsx(Vl,{role:"region","aria-label":e,children:s})]})}function $tt({label:e,value:t}){return t==null?null:o.jsx(Lk,{title:e,defaultOpen:!1,children:o.jsx("pre",{className:"text-ui-sm text-neutral4 bg-surface3 max-h-40 overflow-auto rounded-md p-3 whitespace-pre-wrap",children:typeof t=="string"?t:JSON.stringify(t,null,2)})})}function $Ht({delta:e}){const t=e>0?"text-positive1":e<0?"text-negative1":"text-neutral3";return o.jsxs("span",{className:K("inline-flex min-w-20 items-center gap-1 font-mono text-sm",t),children:[o.jsx("span",{className:"inline-block w-3",children:e>0?"+":e<0?"-":""}),Math.abs(e).toFixed(2),e>0?o.jsx(QQt,{className:"size-3.5"}):e<0?o.jsx(FQt,{className:"size-3.5"}):null]})}function MHt({scorerId:e,value:t,delta:n,reason:r}){const{Link:s,paths:a}=dn();return o.jsxs("div",{className:"bg-surface2 grid gap-1 rounded-lg px-3 py-2",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4",children:[o.jsxs(s,{href:a.scorerLink(e),"aria-label":`Open ${e}`,className:"text-neutral5 flex min-w-0 items-center gap-1.5 text-sm font-medium hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[o.jsx(P_,{}),o.jsx("span",{className:"min-w-0 truncate",children:e})]}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:"text-neutral3 font-mono text-sm",children:t!=null?t.toFixed(2):"-"}),n!=null&&o.jsx($Ht,{delta:n})]})]}),r&&o.jsx("p",{className:"text-neutral3 text-sm",children:r})]})}function Mtt(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Xbs(e){if(!e.startedAt||!e.completedAt)return null;const t=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return Number.isFinite(t)?`${(t/1e3).toFixed(2)}s`:null}const Jbs="border-border1 bg-surface3 text-ui-md text-neutral4 max-h-[30vh] overflow-y-auto rounded-xl border p-4 font-mono break-all whitespace-pre-wrap dark:border-white/10 dark:bg-black/20";function Dtt({side:e,row:t,showDeltas:n,isLoading:r}){const s=t[e],a=Xbs(s);if(r)return o.jsx("div",{className:"flex h-32 items-center justify-center",children:o.jsx(Vt,{})});if(!s.present)return o.jsx("p",{className:"text-neutral3 py-8 text-center text-sm",children:"Not present in this experiment"});const i=Mtt(s.output);return o.jsxs("div",{className:"grid content-start gap-5",children:[a&&o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsxs("p",{className:"text-neutral3 flex items-center justify-end gap-1.5 text-sm [&>svg]:size-3.5",children:[o.jsx(c1,{}),a]})}),o.jsx(yn,{children:"Run duration"})]}),s.error?o.jsx(Lk,{title:"Error",tone:"negative",actions:o.jsx(_a,{content:s.error.message}),children:o.jsx("p",{className:"border-negative1/40 bg-negative1/5 text-ui-md text-neutral4 rounded-xl border p-4 break-words",children:s.error.message})}):o.jsx(Lk,{title:"Output",actions:o.jsx(_a,{content:i}),children:o.jsx("pre",{className:Jbs,children:i})}),s.scores.length>0&&o.jsx(Lk,{title:"Scores",children:o.jsx("div",{className:"grid gap-2",children:s.scores.map(l=>o.jsx(MHt,{scorerId:l.scorerId,value:l.value,delta:n?t.deltas[l.scorerId]:null,reason:l.reason},l.scorerId))})}),s.comment&&o.jsx(Lk,{title:"Comment",defaultOpen:!1,children:o.jsx("p",{className:"text-neutral3 text-sm",children:s.comment})}),s.metadata&&Object.keys(s.metadata).length>0&&o.jsx(Lk,{title:"Metadata",defaultOpen:!1,children:o.jsx("dl",{className:"grid gap-1",children:Object.entries(s.metadata).map(([l,c])=>o.jsxs("div",{className:"flex items-start justify-between gap-4 text-sm",children:[o.jsx("dt",{className:"text-neutral3",children:l}),o.jsx("dd",{className:"text-neutral5 font-mono break-all",children:Mtt(c)})]},l))})})]})}const exs={baseline:"Baseline",contender:"Contender"},txs={baseline:"purple",contender:"blue"},nxs="flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0";function Ltt({side:e,experiment:t,summary:n,showDeltas:r,versionMismatch:s}){const{Link:a,paths:i}=dn(),l=exs[e],c=t?y0(t.id)??t.id:null,u=t?.createdAt?new Date(t.createdAt):null,d=n??[];return o.jsxs("div",{className:"grid content-start gap-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(bt,{variant:txs[e],size:"xs",children:l}),t&&o.jsx(ie,{as:a,size:"xs",href:`/experiments/${t.id}`,"aria-label":`Open experiment ${t.name||c}`,children:o.jsx("span",{className:"min-w-0 truncate",children:t.name||c})})]}),t&&o.jsxs("div",{className:"text-ui-sm text-neutral3 flex flex-wrap gap-x-4 gap-y-1",children:[t.name&&o.jsxs(Pl,{children:[o.jsx(AV,{})," ",c]}),t.targetType==="agent"&&t.targetId?o.jsxs(a,{href:i.agentLink(t.targetId),className:nxs,children:[o.jsx(Ri,{}),o.jsx("span",{className:"min-w-0 truncate",children:t.targetId})]}):o.jsxs(Pl,{children:[o.jsx(Kct,{})," ",t.targetId]}),o.jsx("span",{className:K(s&&"text-accent6"),children:o.jsxs(Pl,{children:[o.jsx(RV,{})," v",t.datasetVersion??"—",s&&" · different dataset version"]})}),u&&o.jsxs(Pl,{children:[o.jsx(B9,{})," ",dr(u,"MMM d, yyyy HH:mm")]})]}),d.length>0&&o.jsx(Lk,{title:"Overall score",children:o.jsx("div",{className:"grid gap-2",children:d.map(({scorerId:f,average:h,delta:p})=>o.jsx(MHt,{scorerId:f,value:h,delta:r?p:null},f))})})]})}const HE="min-w-0 px-4 py-3";function rxs({datasetId:e,experimentIdA:t,experimentIdB:n}){const{Link:r,paths:s}=dn(),{data:a,isLoading:i,error:l}=lvs(e,t,n),{data:c}=VD(e,t),{data:u}=VD(e,n),d=c&&u&&c.datasetVersion!==u.datasetVersion,f=a?.baselineId??t,h=t===f?n:t,p=c?.id===f?c:u,m=c?.id===h?c:u,{data:v,isLoading:y}=HD({datasetId:e,experimentId:f,experimentStatus:p?.status}),{data:b,isLoading:x}=HD({datasetId:e,experimentId:h,experimentStatus:m?.status}),{data:w}=jC(f,p?.status),{data:k}=jC(h,m?.status),C=g.useMemo(()=>Kbs({comparison:a,baselineId:f,contenderId:h,baselineResults:v,contenderResults:b,baselineScores:w,contenderScores:k}),[a,f,h,v,b,w,k]),_=g.useMemo(()=>[...new Set(C.flatMap(E=>Object.keys(E.deltas)))].sort(),[C]),T=g.useMemo(()=>{const E=(A,P)=>{const L=C.map(D=>D[A].scores.find(B=>B.scorerId===P)?.value).filter(D=>D!=null);return L.length>0?L.reduce((D,B)=>D+B,0)/L.length:null},N=_.map(A=>({scorerId:A,average:E("baseline",A),delta:null})),I=_.map(A=>{const P=E("baseline",A),L=E("contender",A);return{scorerId:A,average:L,delta:P!=null&&L!=null?L-P:null}});return{baseline:N,contender:I}},[C,_]);return i?o.jsx("div",{className:"flex h-64 items-center justify-center",children:o.jsx(Vt,{})}):l?o.jsx(Rn,{variant:"warning",title:"Error loading comparison",children:o.jsx(Rn.Message,{children:l instanceof Error?l.message:"Unknown error"})}):!a||a.items.length===0?o.jsx("div",{className:"text-neutral4 py-8 text-center text-sm",children:"No comparison data"}):o.jsx("div",{className:"grid gap-4",children:o.jsxs("div",{role:"table","aria-label":"Experiments comparison",className:"grid",children:[o.jsxs("div",{role:"row",className:"border-border1 grid border-y xl:grid-cols-[minmax(20rem,24rem)_1fr_1fr] xl:divide-x xl:divide-[var(--border1)]",children:[o.jsx("div",{role:"columnheader","aria-label":"Items",className:`${HE} text-neutral3 text-ui-sm uppercase`,children:"Items"}),o.jsx("div",{role:"columnheader","aria-label":"Baseline",className:HE,children:o.jsx(Ltt,{side:"baseline",experiment:p,summary:T.baseline,versionMismatch:d})}),o.jsx("div",{role:"columnheader","aria-label":"Contender",className:HE,children:o.jsx(Ltt,{side:"contender",experiment:m,summary:T.contender,versionMismatch:d,showDeltas:!0})})]}),C.map(E=>{const N=Object.entries(E.deltas).filter(([,I])=>I!=null&&I!==0);return o.jsxs("div",{role:"row","aria-label":E.itemId,className:"border-border1 grid border-b xl:grid-cols-[minmax(20rem,24rem)_1fr_1fr] xl:divide-x xl:divide-[var(--border1)]",children:[o.jsxs("div",{role:"cell",className:`${HE} grid content-start gap-1`,children:[o.jsx(r,{href:s.datasetItemLink(e,E.itemId),"aria-label":`Open item ${E.itemId}`,className:K("text-ui-sm flex items-start gap-1.5 font-mono break-all hover:underline [&>svg]:mt-0.5 [&>svg]:size-3.5 [&>svg]:shrink-0",E.baseline.present&&E.contender.present?"text-neutral4":"text-neutral1"),children:o.jsx("span",{className:"min-w-0",children:E.itemId})}),N.length>0&&o.jsx("span",{className:"flex flex-wrap items-center gap-2",children:N.map(([I,A])=>o.jsx($Ht,{delta:A},I))}),o.jsxs("div",{className:"grid pt-3",children:[o.jsx($tt,{label:"Input",value:E.input}),o.jsx($tt,{label:"Ground truth",value:E.groundTruth})]})]}),o.jsx("div",{role:"cell","aria-label":"Baseline",className:HE,children:o.jsx(Dtt,{side:"baseline",row:E,isLoading:y})}),o.jsx("div",{role:"cell","aria-label":"Contender",className:HE,children:o.jsx(Dtt,{side:"contender",row:E,isLoading:x,showDeltas:!0})})]},E.itemId)})]})})}const sxs=100;function fY(e){const t=Ye(),n={perPage:sxs};return mt({queryKey:e?["dataset-experiments",e,n]:["experiments",n],queryFn:()=>e?t.listDatasetExperiments(e,n):t.listExperiments(n)})}const DHt=(e,t)=>{const n=Ye(),{data:r,isLoading:s}=fY(void 0),a=r?.experiments,i=t?a?.filter(c=>c.id===t):a,l=mt({queryKey:["review-items",e,t??"all",i?.map(c=>c.id)],queryFn:async()=>!i||i.length===0?[]:(await Promise.all(i.map(async u=>{if(!u.datasetId)return[];try{const{results:d}=await n.listDatasetExperimentResults(u.datasetId,u.id);return d.filter(f=>f.status===e).map(f=>({id:f.id,input:f.input,output:f.output,error:f.error,itemId:f.itemId,experimentId:f.experimentId,datasetId:u.datasetId??void 0,traceId:f.traceId??void 0,scores:f.scores?Object.fromEntries(f.scores.map(h=>[h.scorerId,h.score??0])):{},tags:f.tags??[],comment:f.comment??""}))}catch{return[]}}))).flat(),enabled:!!a,refetchOnWindowFocus:!1});return{...l,isLoading:l.isLoading||s}},axs=({experimentId:e}={})=>DHt("needs-review",e),ixs=({experimentId:e}={})=>DHt("complete",e);function oxs(e,t){if(typeof e=="string")return e.length>t?e.slice(0,t)+"...":e;try{const n=JSON.stringify(e);return n.length>t?n.slice(0,t)+"...":n}catch{return String(e)}}function lxs({datasetId:e,experimentId:t,featuredItemId:n,detailPanelVariant:r="inline"}){const s=Ye(),{data:a}=zy(e??""),{data:i,isLoading:l}=axs({experimentId:t}),{data:c,isLoading:u}=ixs({experimentId:t}),{updateExperimentResult:d}=wi(),[f,h]=g.useState(n??null);g.useEffect(()=>{n!==void 0&&h(n)},[n]);const[p,m]=g.useState(null),[v,y]=g.useState(new Set),[b,x]=g.useState(!1),[w,k]=g.useState(!1),[C,_]=g.useState(!1),[T,E]=g.useState(""),[N,I]=g.useState(""),[A,P]=g.useState(""),[L,D]=g.useState([]),[B,H]=g.useState(!1),[q,z]=g.useState({}),V=g.useMemo(()=>(i??[]).map(de=>de.id in q?{...de,rating:q[de.id]}:de),[i,q]),M=g.useMemo(()=>{const de=new Set;if(a?.tags)for(const ke of a.tags)de.add(ke);for(const ke of V)for(const Ne of ke.tags)de.add(Ne);return[...de].sort()},[a,V]),G=g.useCallback(de=>{!a||!e||(a.tags??[]).includes(de)},[a,e]),F=g.useMemo(()=>p?p==="__untagged__"?V.filter(de=>de.tags.length===0):V.filter(de=>de.tags.includes(p)):V,[V,p]),R=g.useMemo(()=>{const de=new Map;for(const ke of V)for(const Ne of ke.tags)de.set(Ne,(de.get(Ne)??0)+1);return[...de.entries()].sort((ke,Ne)=>Ne[1]-ke[1])},[V]),U=g.useMemo(()=>V.filter(de=>de.tags.length===0).length,[V]),Z=g.useMemo(()=>{let de=0;return p&&de++,b&&de++,de},[p,b]),Y=g.useCallback((de,ke)=>{const Ne=V.find(fe=>fe.id===de);Ne?.experimentId&&Ne?.datasetId&&d.mutate({datasetId:Ne.datasetId,experimentId:Ne.experimentId,resultId:Ne.id,tags:ke})},[V,d]),te=g.useCallback((de,ke)=>{const Ne=V.find(fe=>fe.id===de);Ne?.traceId&&ke!==void 0&&s.createFeedback({feedback:{traceId:Ne.traceId,source:"studio",feedbackSource:"studio",feedbackType:"rating",value:ke==="positive"?1:-1,reviewStatus:"reviewed",experimentId:Ne.experimentId??void 0,sourceId:Ne.id}}).catch(()=>{}),z(fe=>({...fe,[de]:ke}))},[V,s]),J=g.useCallback((de,ke)=>{const Ne=V.find(fe=>fe.id===de);Ne?.experimentId&&Ne?.datasetId&&d.mutate({datasetId:Ne.datasetId,experimentId:Ne.experimentId,resultId:Ne.id,comment:ke}),Ne?.traceId&&s.createFeedback({feedback:{traceId:Ne.traceId,source:"studio",feedbackSource:"studio",feedbackType:"comment",value:ke,comment:ke,reviewStatus:"reviewed",experimentId:Ne.experimentId??void 0,sourceId:Ne.id}}).catch(()=>{})},[V,s,d]),ee=g.useCallback(de=>{const ke=V.find(Ne=>Ne.id===de);y(Ne=>{const fe=new Set(Ne);return fe.delete(de),fe}),f===de&&h(null),ke?.experimentId&&ke?.datasetId&&d.mutate({datasetId:ke.datasetId,experimentId:ke.experimentId,resultId:ke.id,status:null})},[V,d,f]),re=g.useCallback(de=>{const ke=V.find(Ne=>Ne.id===de);y(Ne=>{const fe=new Set(Ne);return fe.delete(de),fe}),f===de&&h(null),ke?.experimentId&&ke?.datasetId&&d.mutate({datasetId:ke.datasetId,experimentId:ke.experimentId,resultId:ke.id,status:"complete"})},[V,d,f]),ae=g.useMemo(()=>{const de=b?c??[]:F;return!b||!p?de:p==="__untagged__"?de.filter(ke=>ke.tags.length===0):de.filter(ke=>ke.tags.includes(p))},[b,c,F,p]),X=b?u:!1,ne=g.useMemo(()=>new Set(ae.map(de=>de.id)),[ae]),se=g.useMemo(()=>[...v].filter(de=>ne.has(de)).length,[v,ne]),ce=ae.length>0&&se===ae.length,le=se>0&&!ce,be=g.useCallback(de=>{y(ke=>{const Ne=new Set(ke);return Ne.has(de)?Ne.delete(de):Ne.add(de),Ne})},[]),he=g.useCallback(()=>{y(ce?new Set:new Set(ae.map(de=>de.id)))},[ce,ae]),xe=g.useCallback(de=>{for(const ke of v){const Ne=V.find(fe=>fe.id===ke);Ne&&!Ne.tags.includes(de)&&Y(ke,[...Ne.tags,de])}},[V,v,Y]),Ae=g.useCallback(de=>{for(const ke of v){const Ne=V.find(fe=>fe.id===ke);Ne&&Ne.tags.includes(de)&&Y(ke,Ne.tags.filter(fe=>fe!==de))}},[V,v,Y]),De=g.useCallback(()=>{for(const de of v)re(de);y(new Set)},[v,re]),Me=g.useCallback(()=>{for(const de of v)ee(de);y(new Set)},[v,ee]),Pe=g.useCallback(()=>{E(""),_(!0)},[]),Re=g.useCallback(async()=>{if(!(!N||!A)){k(!0),_(!1);try{const de=V.filter(Ne=>v.has(Ne.id));if(de.length===0){k(!1);return}const ke=await s.clusterFailures({modelId:`${N}/${A}`,items:de.map(Ne=>({id:Ne.id,input:Ne.input,output:Ne.output??void 0,error:typeof Ne.error=="string"?Ne.error:Ne.error?String(Ne.error):void 0,scores:Ne.scores,existingTags:Ne.tags.length>0?Ne.tags:void 0})),availableTags:M.length>0?M:void 0,prompt:T||void 0});ke.proposedTags&&ke.proposedTags.length>0&&(D(ke.proposedTags.map(Ne=>({...Ne,accepted:!0}))),H(!0))}catch(de){console.error("Analysis failed:",de)}finally{k(!1)}}},[N,A,V,v,s,M,T]),Le=g.useCallback(()=>{for(const de of L){if(!de.accepted)continue;const ke=V.find(Ne=>Ne.id===de.itemId);if(ke){const Ne=[...new Set([...ke.tags,...de.tags])];Y(ke.id,Ne)}}H(!1)},[L,V,Y]),Ee=g.useCallback(de=>{h(ke=>ke===de?null:de)},[]),Te=g.useMemo(()=>f?ae.find(de=>de.id===f)??null:null,[f,ae]),ze=f?ae.findIndex(de=>de.id===f):-1,Ce=ze>0?()=>h(ae[ze-1].id):void 0,Fe=ze>=0&&ze<ae.length-1?()=>h(ae[ze+1].id):void 0,tt="auto minmax(0,20rem) minmax(0,1fr) minmax(0,8rem) 6rem 6rem",{containerRef:Ge,getRowProps:ge}=ao({count:ae.length});if(l)return o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(Vt,{className:"h-6 w-6"})});const Se=Te?o.jsx(hqt,{className:"h-full",item:Te,isCompleted:b,tagVocabulary:M,onRate:de=>te(Te.id,de),onSetTags:de=>{Y(Te.id,de);for(const ke of de)M.includes(ke)||G(ke)},onComment:de=>J(Te.id,de),onRemove:()=>ee(Te.id),onComplete:b?void 0:()=>re(Te.id),onPrevious:Ce,onNext:Fe,onClose:()=>h(null)}):null;return o.jsxs("div",{className:K("flex h-full min-h-0 flex-1",r==="overlay"?"overflow-visible":"overflow-hidden"),children:[o.jsx(pr,{open:C,onOpenChange:_,children:o.jsxs(mr,{children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Analyze Items"}),o.jsx(Cs,{children:"Use an LLM to automatically suggest tags for the selected items."})]}),o.jsxs("div",{className:"space-y-4 py-2",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx(Dt,{className:"mb-1 block text-xs",children:"Provider"}),o.jsx(Yy,{value:N,onValueChange:I})]}),o.jsxs("div",{children:[o.jsx(Dt,{className:"mb-1 block text-xs",children:"Model"}),o.jsx(Ky,{llmId:N,value:A,onValueChange:P})]})]}),o.jsxs(ve,{variant:"ui-xs",className:"text-neutral3",children:[v.size," item",v.size!==1?"s":""," will be analyzed"]}),o.jsxs("div",{children:[o.jsx(Dt,{className:"text-xs",children:"Instructions (optional)"}),o.jsx(zo,{value:T,onChange:de=>E(de.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3,className:"mt-1 text-xs"})]})]}),o.jsxs(Bl,{children:[o.jsx(ie,{variant:"outline",onClick:()=>_(!1),children:"Cancel"}),o.jsxs(ie,{onClick:Re,disabled:!N||!A||w,children:[w?o.jsx(Vt,{className:"mr-1 h-4 w-4"}):null,"Analyze"]})]})]})}),o.jsx(pr,{open:B,onOpenChange:H,children:o.jsxs(mr,{className:"max-h-[80vh] max-w-2xl overflow-y-auto",children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Review Proposed Tags"}),o.jsxs(Cs,{children:[L.filter(de=>de.accepted).length," of ",L.length," proposals selected"]})]}),o.jsx("div",{className:"space-y-3 py-2",children:L.map((de,ke)=>{const Ne=V.find(fe=>fe.id===de.itemId);return o.jsx("div",{className:K("p-3 border rounded-lg",!de.accepted&&"opacity-50"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(Oo,{checked:de.accepted,onCheckedChange:fe=>D(ye=>ye.map((je,$e)=>$e===ke?{...je,accepted:!!fe}:je))}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(ve,{variant:"ui-xs",className:"text-neutral4 block truncate",children:Ne?typeof Ne.input=="string"?Ne.input.slice(0,100):JSON.stringify(Ne.input).slice(0,100):de.itemId}),o.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:de.tags.map((fe,ye)=>o.jsx(mqt,{tag:fe,onRename:je=>D($e=>$e.map((He,vt)=>vt===ke?{...He,tags:He.tags.map((_e,et)=>et===ye?je:_e)}:He)),onRemove:()=>D(je=>je.map(($e,He)=>He===ke?{...$e,tags:$e.tags.filter((vt,_e)=>_e!==ye)}:$e))},`${fe}-${ye}`))}),de.reason&&o.jsx(ve,{variant:"ui-xs",className:"text-neutral3 mt-1 block italic",children:de.reason})]})]})},de.itemId)})}),o.jsxs(Bl,{children:[o.jsx(ie,{variant:"outline",onClick:()=>H(!1),children:"Cancel"}),o.jsxs(ie,{onClick:Le,disabled:L.filter(de=>de.accepted).length===0,children:["Accept ",L.filter(de=>de.accepted).length," proposals"]})]})]})}),o.jsxs("div",{className:K("grid h-full min-h-0 w-full grid-cols-1 gap-4",r==="overlay"?"overflow-visible":"overflow-hidden",Te&&r==="inline"&&"grid-cols-[1fr_1fr]"),children:[o.jsxs("div",{className:"grid min-h-0 w-full grid-rows-[auto_1fr] gap-3 overflow-hidden pt-3",children:[(V.length>0||Z>0)&&o.jsxs("div",{className:"flex w-full flex-wrap items-center justify-start gap-3",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs(at,{children:[o.jsx(at.Trigger,{asChild:!0,children:o.jsxs(ie,{size:"sm",children:[o.jsx(E0e,{}),"Filter",Z>0&&o.jsx(bt,{size:"xs",children:Z})]})}),o.jsxs(at.Content,{align:"start",className:K("min-w-48"),children:[o.jsxs(at.Sub,{children:[o.jsxs(at.SubTrigger,{children:["Status",b&&o.jsx("span",{className:K("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(at.SubContent,{children:[o.jsx(at.CheckboxItem,{checked:!b,onCheckedChange:()=>{x(!1),h(null)},onSelect:de=>de.preventDefault(),children:"Review Queue"}),o.jsx(at.CheckboxItem,{checked:b,onCheckedChange:()=>{x(!0),h(null)},onSelect:de=>de.preventDefault(),children:"Completed"})]})]}),o.jsxs(at.Sub,{children:[o.jsxs(at.SubTrigger,{children:["Tags",p&&o.jsx("span",{className:K("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(at.SubContent,{children:[o.jsx(at.CheckboxItem,{checked:!p,onCheckedChange:()=>m(null),onSelect:de=>de.preventDefault(),children:"All"}),U>0&&o.jsx(at.CheckboxItem,{checked:p==="__untagged__",onCheckedChange:()=>m(p==="__untagged__"?null:"__untagged__"),onSelect:de=>de.preventDefault(),children:"Untagged"}),R.length>0&&o.jsx(at.Separator,{}),R.map(([de])=>o.jsx(at.CheckboxItem,{checked:p===de,onCheckedChange:()=>m(p===de?null:de),onSelect:ke=>ke.preventDefault(),children:de},de))]})]}),Z>0&&o.jsxs(o.Fragment,{children:[o.jsx(at.Separator,{}),o.jsxs(at.Item,{onSelect:()=>{m(null),x(!1),h(null)},children:[o.jsx(or,{}),"Clear all filters"]})]})]})]}),Z>0&&o.jsxs(ie,{size:"sm",onClick:()=>{m(null),x(!1),h(null)},children:[o.jsx(or,{}),"Reset"]})]}),!b&&v.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(pqt,{selectedCount:v.size,vocabulary:M,onApplyTag:xe,onRemoveTag:Ae,onNewTag:de=>xe(de)}),o.jsxs(at,{children:[o.jsx(at.Trigger,{asChild:!0,children:o.jsxs(ie,{size:"sm",disabled:w,children:[w?o.jsx(Vt,{className:"h-4 w-4"}):o.jsx(Qe,{size:"sm",children:o.jsx(Js,{})}),"Actions"]})}),o.jsxs(at.Content,{align:"end",children:[o.jsxs(at.Item,{onSelect:De,children:[o.jsx(Qe,{size:"sm",children:o.jsx(kO,{})}),"Complete"]}),o.jsxs(at.Item,{onSelect:Me,children:[o.jsx(Qe,{size:"sm",children:o.jsx(Fl,{})}),"Remove"]}),o.jsx(at.Separator,{}),o.jsxs(at.Item,{onSelect:Pe,children:[o.jsx(Qe,{size:"sm",children:o.jsx(Dg,{})}),"Analyze"]})]})]})]})]}),X?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(Vt,{className:"h-6 w-6"})}):ae.length===0?o.jsx("div",{className:"flex h-full items-center justify-center py-12",children:o.jsx(br,{iconSlot:o.jsx(X1,{className:"text-neutral3 h-8 w-8"}),titleSlot:b?"No completed reviews yet":"No items to review",descriptionSlot:b?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here."})}):o.jsxs(pe,{columns:tt,fit:"container",className:"min-w-0",scrollRef:Ge,children:[o.jsxs(pe.Top,{hasLeadingCell:!0,children:[b?o.jsx(pe.TopCell,{children:" "}):o.jsx(pe.TopSelectCell,{checked:ce?!0:le?"indeterminate":!1,onToggle:()=>he(),"aria-label":"Select all"}),o.jsxs(pe.TopCells,{colStart:2,children:[o.jsx(pe.TopCell,{children:"Input"}),o.jsx(pe.TopCell,{children:"Comment"}),o.jsx(pe.TopCell,{children:"Tags"}),o.jsx(pe.TopCell,{children:"Rating"}),o.jsx(pe.TopCell,{children:"Scores"})]})]}),ae.map((de,ke)=>{const Ne=de.scores?Object.entries(de.scores):[],fe=f===de.id,ye=o.jsxs(o.Fragment,{children:[o.jsx(pe.Cell,{className:"text-neutral4 min-w-0",children:o.jsx("span",{className:"block truncate",children:oxs(de.input,200)})}),o.jsx(pe.Cell,{className:"min-w-0",children:de.comment?o.jsx(ve,{variant:"ui-xs",className:"text-neutral3 truncate",children:de.comment}):o.jsx(ve,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsx(pe.Cell,{className:"min-w-0",children:de.tags.length>0?o.jsx(ve,{variant:"ui-xs",className:"text-neutral4 truncate",children:de.tags.join(", ")}):o.jsx(ve,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsxs(pe.Cell,{children:[de.rating==="positive"&&o.jsx(Qe,{size:"sm",className:"text-positive1",children:o.jsx(F0e,{})}),de.rating==="negative"&&o.jsx(Qe,{size:"sm",className:"text-negative1",children:o.jsx(L0e,{})}),!de.rating&&o.jsx(ve,{variant:"ui-xs",className:"text-neutral2",children:"—"})]}),o.jsx(pe.Cell,{children:Ne.length>0?o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Qe,{size:"sm",className:"text-neutral3",children:o.jsx(Qh,{})}),o.jsx(ve,{variant:"ui-xs",className:"text-neutral4 font-mono",children:Ne[0][1].toFixed(2)}),Ne.length>1&&o.jsxs(bt,{children:["+",Ne.length-1]})]}):o.jsx(ve,{variant:"ui-xs",className:"text-neutral2",children:"—"})})]});return o.jsxs(pe.RowWrapper,{children:[b?o.jsx(pe.Cell,{className:"justify-items-center px-4",children:o.jsx("div",{role:"img","aria-label":de.error?"Error":"Success",title:de.error?"Error":"Success",className:K("w-2 h-2 rounded-full",de.error?"bg-red-700":"bg-green-600")})}):o.jsx(pe.SelectCell,{checked:v.has(de.id),onToggle:()=>be(de.id),"aria-label":`Select item ${de.id}`}),o.jsx(pe.RowButton,{colStart:2,featured:fe,onClick:()=>Ee(de.id),...ge(ke),children:ye})]},de.id)})]})]}),Se&&(r==="overlay"?o.jsx(uY,{label:`Review item ${Te?.id??""}`,children:Se}):Se)]})]})}const Ftt={needsReview:"#facc15",complete:"#22c55e"},cxs=[{label:"Needs Review",color:Ftt.needsReview},{label:"Reviewed",color:Ftt.complete}];function uxs({reviewSummary:e,experiments:t,datasets:n,isLoading:r,isError:s}){const{data:a,maxVal:i,totalInPipeline:l}=g.useMemo(()=>{if(!e?.counts||!t)return{data:[],maxVal:0,totalInPipeline:0};const u=new Map;for(const m of t)u.set(m.id,m);const d=new Map;if(n)for(const m of n)d.set(m.id,m.name);let f=0,h=0;const p=[];for(const m of e.counts){const v=m.needsReview+m.complete;if(v===0)continue;h+=v,v>f&&(f=v);const y=u.get(m.experimentId),b=y?.datasetId?d.get(y.datasetId):void 0,x=b?`${b} · ${m.experimentId.slice(0,8)}`:m.experimentId.slice(0,8);p.push({name:x,values:[m.needsReview,m.complete]})}return{data:p,maxVal:f,totalInPipeline:h}},[e,t,n]),c=a.length>0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Review Pipeline",description:"Items in review across experiments."}),c&&o.jsx(Ht.Summary,{value:String(l),label:"Items in pipeline"})]}),r?o.jsx(Ht.Loading,{}):s?o.jsx(Ht.Error,{message:"Failed to load review data"}):o.jsx(Ht.Content,{children:c?o.jsx(KN,{data:a,segments:cxs,maxVal:i,fmt:u=>String(u)}):o.jsx(Ht.NoData,{message:"No items have been sent to review yet"})})]})}function LHt(){const e=Ye();return mt({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function dxs(e){const t=new Map;if(!e?.counts)return t;for(const n of e.counts)t.set(n.experimentId,{needsReview:n.needsReview,complete:n.complete,total:n.total});return t}function fxs(e){return e?.counts?e.counts.reduce((t,n)=>({needsReview:t.needsReview+n.needsReview,complete:t.complete+n.complete,inPipeline:t.inPipeline+n.needsReview+n.complete}),{needsReview:0,complete:0,inPipeline:0}):{needsReview:0,complete:0,inPipeline:0}}function hxs(){const[e,t]=g.useState("all"),[n,r]=g.useState({}),{data:s,isLoading:a,error:i}=up(),{data:l,isLoading:c,error:u}=Xg(),{data:d,isLoading:f,error:h}=BH(),{data:p,isLoading:m,isError:v,error:y}=eHr(n),{data:b,isLoading:x,isError:w,error:k}=LHt(),C=l?.datasets,_=d?.experiments,T=g.useMemo(()=>fxs(b),[b]),E=i||u||h||y||k;return E&&hs(E)?o.jsx(Zn,{children:o.jsx(Ts,{})}):E&&ps(E)?o.jsx(Zn,{children:o.jsx(ks,{resource:"evaluation"})}):E?o.jsx(Zn,{children:o.jsx(La,{title:"Failed to load evaluation data",message:E.message})}):o.jsxs(Lt,{width:"wide",height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(Lt.Row,{children:o.jsx(Lt.Column,{children:o.jsx(q4,{preset:e,onPresetChange:t,dateFrom:n.start,dateTo:n.end,onDateChange:(N,I)=>r(A=>I==="from"?{...A,start:N}:{...A,end:N})})})})}),o.jsxs("div",{className:"flex flex-col gap-6",children:[o.jsx(o0e,{children:o.jsx(Rbs,{scorers:s,datasets:C,experiments:_,avgScore:p?.avgScore??null,prevAvgScore:p?.prevAvgScore??null,totalNeedsReview:T.needsReview,isLoadingScorers:a,isLoadingDatasets:c,isLoadingExperiments:f,isLoadingScores:m,isLoadingReview:x})}),o.jsx(fVr,{summaryData:p?.summaryData??[],overTimeData:p?.overTimeData??[],scorerNames:p?.scorerNames??[],avgScore:p?.avgScore??null,isLoading:m,isError:v}),o.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:[o.jsx(Rvs,{experiments:_,isLoading:f,isError:!!h}),o.jsx(Zbs,{experiments:_,datasets:C,isLoading:f,isError:!!h})]}),o.jsx(uxs,{reviewSummary:b,experiments:_,datasets:C,isLoading:x,isError:!!w})]})]})}function pxs(){const[e,t]=g.useState(""),[n,r]=g.useState("all"),[s,a]=g.useState(!1),[i,l]=g.useState(!1),[c,u]=g.useState([]),d=qr(),[f,h]=za(),p=f.get("dataset")??"all",m=g.useCallback(G=>{h(F=>{const R=new URLSearchParams(F);return G==="all"?R.delete("dataset"):R.set("dataset",G),R},{replace:!0})},[h]),{data:v,isLoading:y,error:b}=Xg(),{data:x,isLoading:w,error:k}=fY(p==="all"?void 0:p),{data:C}=LHt(),_=g.useMemo(()=>v?.datasets??[],[v?.datasets]),T=g.useMemo(()=>x?.experiments??[],[x?.experiments]),E=g.useMemo(()=>Hbs(_),[_]),N=g.useMemo(()=>dxs(C),[C]),I=y||w,A=k||b,P=G=>{u(F=>F.includes(G)?F.filter(R=>R!==G):F.length>=2?[F[0],G]:[...F,G])},L=()=>{u([]),l(!1)},{selectedIds:D,selectedDatasetIds:B}=g.useMemo(()=>{const G=new Map(T.map(R=>[R.id,R.datasetId])),F=c.filter(R=>G.has(R));return{selectedIds:F,selectedDatasetIds:new Set(F.map(R=>G.get(R)))}},[T,c]),H=D.length===2&&B.size!==1?"experiments must belong to the same dataset":void 0,q=()=>{if(D.length!==2||H)return;const[G,F]=D,[R]=B;if(!R)return;const U=new URLSearchParams({dataset:R,baseline:G,contender:F});d(`/experiments/compare?${U.toString()}`)};if(A&&hs(A))return o.jsx(Zn,{children:o.jsx(Ts,{})});if(k&&ps(k))return o.jsx(Zn,{children:o.jsx(ks,{resource:"experiments"})});if(b&&ps(b))return o.jsx(Zn,{children:o.jsx(ks,{resource:"datasets"})});if(A)return o.jsx(Zn,{children:o.jsx(La,{title:"Failed to load experiments",message:A.message})});const z=o.jsx(cY,{open:s,onOpenChange:a,onSuccess:G=>{d(`/experiments/${G}`)}});if(T.length===0&&!I&&p==="all")return o.jsxs(Zn,{children:[o.jsx(Gbs,{onRunExperiment:()=>a(!0)}),z]});const V=n!=="all"||p!=="all"||e!=="",M=()=>{t(""),r("all"),m("all")};return o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(Qbs,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:p,onDatasetFilterChange:m,datasetOptions:E,onReset:M,hasActiveFilters:V,onRunClick:()=>a(!0),onCompareClick:()=>l(!0),selection:i?{selectedCount:D.length,onExecuteCompare:q,onCancelSelection:L,compareDisabledReason:H}:void 0})}),o.jsx(qbs,{experiments:T,datasets:_,reviewByExperiment:N,isLoading:I,search:e,statusFilter:n,datasetFilter:p,selection:i?{selectedExperimentIds:D,onToggleSelection:P}:void 0}),z]})}function a8({experimentId:e}){const{Link:t,paths:n}=dn();return o.jsx(ie,{as:t,href:n.experimentLink(e),size:"sm","aria-label":`Open experiment ${e}`,children:e.slice(0,8)})}function mxs(){const[e,t]=za(),n=e.get("dataset")??"",r=e.get("baseline")??"",s=e.get("contender")??"",a=VD(n,r),i=VD(n,s),l=a.isLoading||i.isLoading,c=a.error??i.error;return c&&hs(c)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{})})}):c&&ps(c)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ks,{resource:"experiments"})})}):!n||!r||!s?o.jsx(vs,{children:o.jsx(by,{children:o.jsxs("div",{className:"text-neutral4 py-8 text-center",children:[o.jsx("p",{children:"Select two experiments to compare."}),o.jsxs("p",{className:"mt-2 text-sm",children:["Use the URL format: /experiments/compare?dataset=","{datasetId}","&baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})}):l?null:c&&!JEe(c)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(La,{title:"Failed to load experiments",message:c.message})})}):c||!a.data||!i.data?o.jsx(vs,{children:o.jsx(by,{children:o.jsxs("div",{className:"text-neutral4 py-8 text-center",children:[o.jsxs("p",{children:["Experiments must belong to the same dataset (",n,") to be compared."]}),o.jsxs("p",{className:"mt-2 flex items-center justify-center gap-2 text-sm",children:["One of",o.jsx(a8,{experimentId:r}),"and",o.jsx(a8,{experimentId:s}),"was not found in it."]})]})})}):o.jsx(vs,{children:o.jsx(by,{children:o.jsxs("div",{className:"grid w-full content-start",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4 px-6 py-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[o.jsx(ve,{as:"h1",variant:"ui-lg",className:"text-neutral6 font-medium",children:"Experiments comparison"}),o.jsxs("p",{className:"text-ui-sm text-neutral4 flex items-center gap-2",children:[o.jsx(a8,{experimentId:r}),"and",o.jsx(a8,{experimentId:s})]})]}),o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsxs(ie,{onClick:()=>t({dataset:n,baseline:s,contender:r}),children:[o.jsx(Sct,{}),"Swap sides"]})}),o.jsx(yn,{children:"Switch baseline and contender"})]})]}),o.jsx(rxs,{datasetId:n,experimentIdA:r,experimentIdB:s})]})})})}const FHt=e=>o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 8.64637 9.45103",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:o.jsx("path",{d:"M7.80735 5.87241C7.63209 5.97219 7.43696 6.06166 7.22844 6.13866C6.46456 6.42068 5.43714 6.58649 4.32296 6.58649C3.20873 6.58649 2.18135 6.4207 1.41747 6.13866C1.20889 6.06164 1.01385 5.97223 0.838558 5.87241V7.59003C0.838558 7.62341 0.855765 7.70759 1.00172 7.83512C1.14707 7.96201 1.38219 8.09563 1.70829 8.21605C2.3572 8.45563 3.28149 8.61268 4.32296 8.61269C5.36456 8.61269 6.28937 8.45568 6.9383 8.21605C7.26428 8.09566 7.49888 7.96198 7.64419 7.83512C7.79024 7.70754 7.80735 7.62342 7.80735 7.59003V5.87241ZM7.80735 3.00789C7.63214 3.10763 7.4369 3.19647 7.22844 3.27345C6.46455 3.55549 5.43719 3.72129 4.32296 3.72129C3.20868 3.72128 2.18136 3.55552 1.41747 3.27345C1.20896 3.19645 1.01381 3.10766 0.838558 3.00789V4.72551C0.838558 4.7589 0.855657 4.84301 1.00172 4.97059C1.14707 5.09749 1.38219 5.23111 1.70829 5.35153C2.3572 5.59109 3.28154 5.74747 4.32296 5.74748C5.36456 5.74748 6.28937 5.59116 6.9383 5.35153C7.26432 5.23112 7.49887 5.09747 7.64419 4.97059C7.7536 4.87505 7.79089 4.80404 7.80257 4.76033L7.80735 4.72551V3.00789ZM7.80735 1.86099C7.80735 1.82758 7.79045 1.74291 7.64419 1.61522C7.49887 1.48838 7.26421 1.35534 6.9383 1.23497C6.28937 0.995339 5.36456 0.838331 4.32296 0.838331C3.28149 0.83834 2.3572 0.995383 1.70829 1.23497C1.38219 1.35539 1.14707 1.48832 1.00172 1.61522C0.855475 1.7429 0.838558 1.82758 0.838558 1.86099C0.838673 1.89462 0.855968 1.97882 1.00172 2.10607C1.14707 2.23297 1.38219 2.3659 1.70829 2.48632C2.3572 2.7259 3.28149 2.88295 4.32296 2.88296C5.36456 2.88296 6.28937 2.72595 6.9383 2.48632C7.26421 2.36595 7.49887 2.23291 7.64419 2.10607C7.78996 1.97881 7.80724 1.89462 7.80735 1.86099ZM8.64637 7.59003C8.64637 7.95465 8.44458 8.25006 8.1958 8.46728C7.94608 8.68529 7.60876 8.86274 7.22844 9.00318C6.46455 9.28522 5.43718 9.45102 4.32296 9.45102C3.20869 9.45101 2.18135 9.28525 1.41747 9.00318C1.03715 8.86274 0.699831 8.68529 0.450113 8.46728C0.201377 8.25007 0.000227451 7.9546 0.000227451 7.59003V1.86099C0.000227451 1.49643 0.201388 1.20095 0.450113 0.983742C0.699831 0.765728 1.03715 0.588275 1.41747 0.447838C2.18136 0.165769 3.20868 8.74396e-06 4.32296 0C5.43719 0 6.46455 0.165797 7.22844 0.447838C7.60876 0.588275 7.94608 0.765728 8.1958 0.983742C8.44457 1.20096 8.64637 1.49638 8.64637 1.86099V7.59003Z",fill:"currentColor"})});function zHt(e){const{data:t}=jC(e.id,e.status);return g.useMemo(()=>{if(e.scorerIds?.length)return e.scorerIds;if(!t)return[];const n=new Set;for(const r of Object.values(t))for(const s of r)n.add(s.scorerId);return[...n].sort()},[e.scorerIds,t])}function noe({icon:e,typeLabel:t,children:n}){return o.jsxs("div",{className:"text-ui-sm text-neutral5 flex flex-none items-center gap-1.5 [&_svg]:size-3.5 [&_svg]:shrink-0",children:[o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx("span",{className:"text-neutral3 flex",role:"img","aria-label":t}),children:e}),o.jsx(yn,{children:t})]}),n]})}function roe({label:e}){return o.jsxs("div",{className:"text-neutral2 text-ui-xs flex flex-none items-center gap-1.5",children:[o.jsx("span",{className:"whitespace-nowrap",children:e}),o.jsx(Fd,{className:"size-3.5 shrink-0","aria-hidden":!0})]})}const ztt="text-neutral5 inline-flex items-center gap-1.5 hover:underline";function gxs({experiment:e,className:t}){const{Link:n,paths:r}=dn(),s=IHt(),{scorers:a}=s,{data:i,isLoading:l}=zy(e.datasetId??""),c=zHt(e),u=c.map(b=>a?.[b]?.scorer?.config?.name??b),d=e.targetType,f=e.targetId,h=()=>PHt(e,s),p=()=>{if(!f)return null;switch(d){case"agent":return r.agentLink(f);case"workflow":return r.workflowLink(f);case"scorer":return r.scorerLink(f);default:return null}},m=d&&AHt[d]||Ri,v=d&&RHt[d]||"Evaluation target",y=p();return o.jsxs("div",{className:K("flex items-center gap-3 overflow-x-auto",t),children:[o.jsx(noe,{icon:o.jsx(FHt,{}),typeLabel:"Dataset",children:e.datasetId?o.jsxs(n,{href:r.datasetLink(e.datasetId),className:ztt,children:[l?o.jsx(Et,{className:"h-4 w-28"}):i?.name??e.datasetId,e.datasetVersion!=null&&o.jsxs("span",{className:"text-neutral3",children:["(v",e.datasetVersion,")"]})]}):o.jsx("span",{className:"text-neutral3",children:"No dataset"})}),o.jsx(roe,{label:"each item"}),o.jsx(noe,{icon:o.jsx(m,{}),typeLabel:v,children:y?o.jsx(n,{href:y,className:ztt,children:h()}):o.jsx("span",{className:"text-neutral3",children:h()})}),o.jsx(roe,{label:"output"}),o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx("div",{tabIndex:0,className:"flex outline-offset-4",children:o.jsx(noe,{icon:o.jsx(P_,{}),typeLabel:"Scorers",children:c.length===0?"Scorers":`${c.length} scorer${c.length===1?"":"s"}`})})}),o.jsx(yn,{children:u.length>0?u.join(", "):"No scorer has produced a score yet"})]}),o.jsx(roe,{label:"comparing ground truth"}),o.jsx("div",{className:"text-ui-sm text-neutral5 flex-none whitespace-nowrap",children:"Score"})]})}function i8({label:e,children:t}){return o.jsxs("div",{className:"min-w-0 flex-1 px-6 py-3",children:[o.jsx("div",{className:"text-ui-sm text-neutral2 tracking-widest uppercase",children:e}),o.jsx("div",{className:"text-ui-md text-neutral5 mt-1 flex flex-wrap items-baseline gap-x-1.5",children:t})]})}function vxs(e){if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(1).replace(/\.0$/,"")}s`;const t=Math.floor(e/6e4),n=Math.round(e%6e4/1e3);if(t<60)return n>0?`${t}m ${n}s`:`${t}m`;const r=Math.floor(t/60),s=t%60;return s>0?`${r}h ${s}m`:`${r}h`}function yxs({experiment:e,className:t}){const{data:n}=jC(e.id,e.status),r=g.useMemo(()=>{if(!n)return;const l=Object.values(n).flat();if(l.length!==0)return l.reduce((c,u)=>c+u.score,0)/l.length},[n]),s=e.startedAt??e.createdAt,a=s?new Date(s):null,i=(()=>{if(e.status==="running")return"Running…";if(!e.startedAt||!e.completedAt)return"—";const l=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return l<0?"—":vxs(l)})();return o.jsxs("div",{className:K("flex w-full items-stretch divide-x divide-border1 border-y border-border1",t),children:[o.jsx(i8,{label:"Avg score",children:r===void 0?o.jsx("span",{className:"text-neutral3",children:"—"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{children:r.toFixed(3)}),(e.status==="running"||e.status==="pending")&&o.jsx("span",{className:"text-neutral3",children:"· so far"})]})}),o.jsx(i8,{label:"Items",children:e.status==="running"||e.status==="pending"?o.jsxs("span",{className:"text-neutral3",children:[(e.succeededCount??0)+(e.failedCount??0),"/",e.totalItems," items processed"]}):o.jsxs(o.Fragment,{children:[o.jsxs("span",{children:[e.totalItems," item",e.totalItems===1?"":"s"]}),(e.failedCount??0)>0&&o.jsxs("span",{className:"text-error",children:["· ",e.failedCount," errored"]})]})}),o.jsx(i8,{label:"Started",children:a?o.jsxs(o.Fragment,{children:[o.jsx("span",{children:dr(a,"MMM d, h:mm a")}),o.jsxs("span",{className:"text-neutral3",children:["· ",jMn(a,{addSuffix:!0})]})]}):o.jsx("span",{children:"—"})}),o.jsx(i8,{label:"Duration",children:o.jsx("span",{children:i})})]})}function bxs({experiment:e,open:t,onOpenChange:n}){const[r,s]=g.useState(e.name??""),[a,i]=g.useState(e.description??""),{updateExperiment:l}=wi(),c=!!r.trim()&&!l.isPending,u=async d=>{if(d.preventDefault(),!(!c||!e.datasetId))try{await l.mutateAsync({datasetId:e.datasetId,experimentId:e.id,name:r.trim(),description:a.trim()}),Ve.success("Experiment renamed"),n(!1)}catch(f){Ve.error(`Failed to rename experiment: ${f instanceof Error?f.message:"Unknown error"}`)}};return o.jsx(pr,{open:t,onOpenChange:n,children:o.jsxs(mr,{className:"max-w-md",children:[o.jsx(gr,{children:o.jsx(ur,{children:"Rename Experiment"})}),o.jsx(jr,{children:o.jsxs("form",{onSubmit:u,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"rename-experiment-name",children:"Name *"}),o.jsx(jn,{id:"rename-experiment-name",value:r,onChange:d=>s(d.target.value),placeholder:"Enter experiment name",autoFocus:!0})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"rename-experiment-description",children:"Description"}),o.jsx(jn,{id:"rename-experiment-description",value:a,onChange:d=>i(d.target.value),placeholder:"Enter experiment description (optional)"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ie,{type:"button",onClick:()=>n(!1),disabled:l.isPending,children:"Cancel"}),o.jsx(ie,{type:"submit",variant:"primary",disabled:!c,children:l.isPending?"Saving...":"Save"})]})]})})]})})}function xxs({experiment:e}){const[t,n]=g.useState(!1);return e.datasetId?o.jsxs(o.Fragment,{children:[o.jsx(ie,{onClick:()=>n(!0),tooltip:"Rename this experiment",variant:"ghost",size:"icon-sm",children:o.jsx(Yh,{})}),t&&o.jsx(bxs,{experiment:e,open:!0,onOpenChange:n})]}):null}const wxs=["agent","workflow","scorer"];function Sxs({experiment:e}){const[t,n]=g.useState(!1),r=qr(),{paths:s}=dn(),a=zHt(e),i=wxs.find(l=>l===e.targetType);return!e.datasetId||!i||!e.targetId?null:o.jsxs(o.Fragment,{children:[o.jsxs(ie,{variant:"primary",onClick:()=>n(!0),tooltip:"Run this experiment again with the same configuration",children:[o.jsx(Dc,{}),"Rerun"]}),t&&o.jsx(cY,{open:!0,onOpenChange:n,initialDatasetId:e.datasetId,initialDatasetVersion:e.datasetVersion??void 0,initialTargetType:i,initialTargetId:e.targetId,initialScorerIds:a,initialName:e.name??void 0,initialDescription:e.description??void 0,onSuccess:l=>{r(s.experimentLink(l))}},a.join(","))]})}function kxs({experiment:e}){const{Link:t,paths:n}=dn(),r=e.agentVersion&&e.targetType==="agent"&&e.targetId?`${n.agentLink(e.targetId)}/editor?version=${encodeURIComponent(e.agentVersion)}`:null;return o.jsxs(Lt.TopArea,{children:[o.jsxs(Lt.Row,{children:[o.jsx(Lt.Column,{className:"justify-items-start gap-3",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx(Uys,{status:e.status,className:"h-7"}),o.jsxs(Dl,{children:[o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Dl.Title,{children:e.name||`Experiment #${e.id.slice(0,8)}`}),o.jsx(xxs,{experiment:e})]}),e.description&&o.jsx(Dl.Description,{children:e.description}),o.jsx(gxs,{experiment:e,className:"mt-2"})]})]})}),o.jsxs(Lt.Column,{className:"justify-items-end gap-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(ie,{as:t,to:STe(e.id),children:[o.jsx(X1,{}),"View items to review"]}),o.jsx(Sxs,{experiment:e})]}),e.agentVersion&&o.jsxs(En,{numOfCol:1,children:[o.jsx(En.Key,{children:"Version"}),r?o.jsx(En.ValueLink,{href:r,as:t,children:e.agentVersion}):o.jsx(En.Value,{children:e.agentVersion})]})]})]}),o.jsx(yxs,{experiment:e,className:"-mx-6 w-auto"})]})}function o8({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function Oxs(){const{experimentId:e}=fr(),{data:t,isLoading:n}=BH(),s=t?.experiments?.find(p=>p.id===e)?.datasetId??"",{data:a,isLoading:i,error:l}=VD(s,e??""),{data:c,isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:h}=HD({datasetId:s,experimentId:e??"",experimentStatus:a?.status});return!e||n||i?null:l&&hs(l)?o.jsx(o8,{children:o.jsx(Ts,{})}):l&&ps(l)?o.jsx(o8,{children:o.jsx(ks,{resource:"datasets"})}):l&&JEe(l)||!n&&!s||!i&&!l&&!a?o.jsx(o8,{children:o.jsx(br,{iconSlot:o.jsx(O0e,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:o.jsxs(ie,{as:Da,to:"/experiments",children:[o.jsx(bl,{}),"Back to Experiments"]})})}):l?o.jsx(o8,{children:o.jsx(La,{title:"Failed to load experiment",message:l instanceof Error?l.message:"An unexpected error occurred. Please try again."})}):o.jsx(Mys,{experimentId:e,datasetId:s,experimentStatus:a.status,results:c??[],isLoadingResults:u,hasNextPage:h,children:o.jsxs("div",{className:"relative h-full overflow-hidden",children:[o.jsxs(Lt,{height:"full",children:[o.jsx(kxs,{experiment:a}),o.jsx(Lt.MainArea,{className:"overflow-visible",children:o.jsx(Bys,{experimentId:e,datasetId:s,experimentStatus:a.status,results:c??[],isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:h})})]}),o.jsx(Bg,{})]})})}function soe(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function Cxs({report:e}){const{served:t,unconsumed:n,liveCalls:r,failure:s}=e,a=[...t.map(i=>({outcome:"served",toolName:i.toolName,args:i.args})),...r.map(i=>({outcome:"live",toolName:i.toolName,args:i.args})),...n.map(i=>({outcome:"unconsumed",toolName:i.toolName,args:i.args}))];return o.jsxs("div",{className:"grid gap-2","data-testid":"tool-mock-report",children:[o.jsx(Gt.SectionHeading,{icon:o.jsx(Ud,{}),className:"mb-2",children:"Tool Mocks"}),s&&o.jsx(Rn,{variant:"destructive",title:"Mock mismatch",children:o.jsxs(Rn.Message,{children:[o.jsx("span",{className:"block",children:`Tool "${s.toolName}" was called with arguments that did not match an available mock (${s.code}).`}),o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Called with: ",soe(s.args)]}),n.length>0&&o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Unconsumed mocks: ",n.map(i=>soe(i.args)).join(", ")]})]})}),o.jsx("div",{className:"border-border1 divide-border1 divide-y rounded border text-sm",children:a.map((i,l)=>o.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-1.5",children:[o.jsxs("span",{className:"min-w-0 truncate",children:[o.jsx("span",{className:"text-neutral4 font-mono",children:i.toolName}),o.jsx("span",{className:"text-neutral3 ml-2 font-mono text-xs",children:soe(i.args)})]}),o.jsx("span",{className:`shrink-0 rounded px-2 py-0.5 text-xs ${_xs(i.outcome)}`,children:i.outcome})]},`${i.outcome}-${i.toolName}-${l}`))})]})}function _xs(e){switch(e){case"served":return"bg-accent1/10 text-accent1";case"live":return"bg-orange-500/10 text-orange-400";case"unconsumed":return"bg-neutral3/10 text-neutral4"}}function Exs({result:e,scores:t,onPrevious:n,onNext:r,onClose:s,onShowTrace:a,onOpenInReview:i,onScoreClick:l,featuredScoreId:c,onFlagForReview:u,collapsed:d=!1,scorePanelSlot:f}){const h=!!e?.error,p=l8(e?.input),m=l8(e?.output),v=l8(e?.groundTruth),y=u&&e.status!=="needs-review"&&e.status!=="complete",b=Array.isArray(e.tags)?e.tags:[];return o.jsxs(Gt,{collapsed:d,children:[o.jsxs(Gt.Header,{children:[o.jsxs(Gt.Heading,{children:["Result ",o.jsxs("b",{children:["# ",e.id.length>12?`${e.id.slice(0,12)}…`:e.id]})]}),o.jsxs(es,{className:"ml-auto shrink-0",children:[o.jsx(Gt.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Previous result",nextLabel:"Next result"}),e.traceId&&o.jsxs(ie,{size:"md",onClick:a,children:[o.jsx(sY,{}),"Trace"]}),y&&o.jsxs(ie,{size:"md",variant:"primary",onClick:()=>u(e.id),children:[o.jsx(X1,{}),"Flag for Review"]}),e.status==="needs-review"&&i&&o.jsxs(ie,{size:"md",variant:"primary",onClick:i,children:[o.jsx(ta,{}),"Review"]}),o.jsx(Gt.CloseButton,{onClick:s,tooltip:"Close result panel"})]})]}),!d&&o.jsx(Txs,{scorePanelSlot:f,children:o.jsxs(Gt.Content,{children:[o.jsxs("div",{className:"mb-6 grid gap-4",children:[o.jsxs(En,{children:[o.jsx(En.Key,{children:"Item Id"}),o.jsx(En.ValueWithCopyBtn,{copyTooltip:"Copy Item Id to clipboard",copyValue:e.itemId,children:e.itemId}),o.jsx(En.Key,{children:"Created"}),o.jsx(En.Value,{children:dr(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")})]}),h&&o.jsx(Rn,{variant:"destructive",title:"Error",children:o.jsx(Rn.Message,{children:l8(e?.error&&typeof e.error=="object"?e.error.message:e?.error)})}),t&&t.length>0&&o.jsxs(pe,{columns:"1fr 1fr",children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{children:"Scorer"}),o.jsx(pe.TopCell,{children:"Score"})]}),t.map(x=>o.jsxs(pe.RowButton,{featured:c===x.id,onClick:()=>l?.(x.id),children:[o.jsx(pe.Cell,{children:x.scorerId}),o.jsx(pe.TextCell,{font:"mono",children:x.score.toFixed(3)})]},x.id))]}),e.toolMockReport&&o.jsx(Cxs,{report:e.toolMockReport}),(e.status||b.length>0)&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Gt.SectionHeading,{icon:o.jsx(dI,{}),className:"mb-2",children:"Review"}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.status&&o.jsx("span",{className:`rounded-full px-2 py-0.5 text-xs font-medium ${e.status==="needs-review"?"bg-orange-500/10 text-orange-400":e.status==="complete"?"bg-accent1/10 text-accent1":"bg-neutral3/10 text-neutral4"}`,children:e.status}),b.map(x=>o.jsx("span",{className:"bg-surface4 text-neutral4 rounded px-2 py-0.5 text-xs",children:x},x))]})]})]}),o.jsxs("div",{className:"grid gap-3",children:[o.jsx(Gt.CodeSection,{title:"Input",icon:o.jsx(NV,{}),codeStr:p}),o.jsx(Gt.CodeSection,{title:"Output",icon:o.jsx(nm,{}),codeStr:m}),o.jsx(Gt.CodeSection,{title:"Ground Truth",icon:o.jsx(Kct,{}),codeStr:v})]})]})})]})}function Txs({scorePanelSlot:e,children:t}){return e?o.jsxs("div",{className:"grid min-h-0 flex-1 grid-cols-[1fr_1fr]",children:[o.jsx("div",{className:"flex min-h-0 flex-col overflow-hidden",children:t}),o.jsx("div",{className:"animate-in border-border1 fade-in-0 flex min-h-0 flex-col overflow-hidden border-l duration-300",children:e})]}):o.jsx(o.Fragment,{children:t})}function l8(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function jxs(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function Nxs({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s,collapsed:a,onCollapsedChange:i,className:l}){const[c,u]=g.useState(!1),d=a??c,f=i??u,h=jxs(e),p=h?"N/A — code-based scorer":"N/A — step not configured";return o.jsxs(Gt,{collapsed:d,className:l,children:[o.jsxs(Gt.Header,{children:[o.jsxs(Gt.Heading,{children:["Score ",o.jsx("b",{children:e.scorerId})]}),o.jsxs(es,{className:"ml-auto shrink-0",children:[i&&o.jsx(ie,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(aI,{}):o.jsx(_V,{})}),(n||t)&&o.jsx(Gt.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:"Previous score",nextLabel:"Next score"}),s&&e.traceId&&o.jsxs(ie,{size:"md",onClick:s,children:[o.jsx(sY,{}),"Trace"]}),o.jsx(Gt.CloseButton,{onClick:r,tooltip:"Close score panel"})]})]}),!d&&o.jsx(Gt.Content,{children:o.jsxs("div",{className:"grid gap-3",children:[o.jsx(Gt.CodeSection,{title:`Score: ${e.score}`,icon:o.jsx(Qh,{}),codeStr:e.reason||p,simplified:!0}),!h&&o.jsxs(o.Fragment,{children:[o.jsx(Gt.CodeSection,{title:"Preprocess Prompt",icon:o.jsx($p,{}),codeStr:e.preprocessPrompt||p,simplified:!0}),o.jsx(Gt.CodeSection,{title:"Analyze Prompt",icon:o.jsx($p,{}),codeStr:e.analyzePrompt||p,simplified:!0}),o.jsx(Gt.CodeSection,{title:"Generate Score Prompt",icon:o.jsx($p,{}),codeStr:e.generateScorePrompt||p,simplified:!0}),o.jsx(Gt.CodeSection,{title:"Generate Reason Prompt",icon:o.jsx($p,{}),codeStr:e.generateReasonPrompt||p,simplified:!0})]})]})})]})}function Ixs(){const{itemId:e}=fr();return e?o.jsx(Axs,{itemId:e},e):null}function Axs({itemId:e}){const{experimentId:t,datasetId:n,experimentStatus:r,results:s,isLoadingResults:a,hasNextPage:i,close:l,openInReview:c,goToPreviousItem:u,goToNextItem:d}=EHt(),f=g.useMemo(()=>s.find(R=>R.itemId===e)??null,[s,e]),{data:h}=jC(t,r),{updateExperimentResult:p}=wi(),m=g.useCallback(async R=>{try{await p.mutateAsync({datasetId:n,experimentId:t,resultId:R,status:"needs-review"}),Ve("Result flagged for review")}catch{Ve.error("Failed to flag result for review")}},[n,t,p]),v=f?h?.[f.itemId]:void 0,[y,b]=g.useState(null),[x,w]=g.useState(void 0),[k,C]=g.useState(null),[_,T]=g.useState(!1),[E,N]=g.useState(!1),I=v?.find(R=>R.id===k)??null,A=g.useCallback(R=>{C(U=>R===U?null:R),b(null),w(void 0)},[]),P=()=>{if(!k||!v)return;const R=v.findIndex(U=>U.id===k);if(R>=0&&R<v.length-1)return()=>C(v[R+1].id)},L=()=>{if(!k||!v)return;const R=v.findIndex(U=>U.id===k);if(R>0)return()=>C(v[R-1].id)},{data:D,isLoading:B}=qys(y),H=D?.spans,q=H?.find(R=>!R.parentSpanId),z=q?.entityType==="agent"?"Agent":q?.entityType==="workflow_run"?"Workflow":void 0,{data:V}=eRe({traceId:y??void 0}),{data:M}=fRe({traceId:y??void 0,spanId:x}),{data:G}=kje({traceId:y??void 0,spanId:q?.spanId,page:0}),F=(()=>{const R=[],U=!!y;return R.push(_?"auto":U?"2fr":"1fr"),U&&R.push(E?"auto":"3fr"),R.join(" ")})();return o.jsx(uY,{label:`Experiment item ${e}`,wide:!!x||!!I&&!_,children:f?o.jsxs("div",{className:"[&>section]:bg-surface3 grid h-full min-h-0 content-start gap-4 p-3 [&>section]:rounded-lg [&>section]:shadow-lg",style:{gridTemplateRows:F},children:[o.jsx(Exs,{result:f,scores:v,onPrevious:u,onNext:d,onClose:l,onScoreClick:A,featuredScoreId:k,onShowTrace:()=>{f.traceId&&(b(f.traceId),w(void 0),C(null),T(!0),N(!1))},onOpenInReview:()=>c(f.id),onFlagForReview:()=>{m(f.id)},collapsed:_,scorePanelSlot:I?o.jsx(Nxs,{score:I,onNext:P(),onPrevious:L(),onClose:()=>C(null),onShowTrace:()=>{I.traceId&&(b(I.traceId),w(void 0),T(!0),N(!1))},className:"rounded-none border-0 bg-transparent"}):null}),y&&o.jsx(rY,{traceId:y,spans:H,isLoadingSpans:B,selectedSpanId:x??null,onClose:()=>{b(null),w(void 0),T(!1)},onSpanSelect:w,showUnavailableFeaturesMsg:!1,collapsed:E,onCollapsedChange:N,traceHref:`/traces?traceId=${encodeURIComponent(y)}`,anchorSpanId:q?.spanId,feedbackTabBadge:V?.pagination?.total??void 0,feedbackTabSlot:({traceId:R})=>o.jsx(iY,{traceId:R}),scoresTabBadge:G?.pagination?.total??void 0,scoresTabSlot:({traceId:R,rootSpanId:U})=>U?o.jsx(mHt,{traceId:R,spanId:U,isTopLevelSpan:!q?.parentSpanId,entityType:z,onScoreSelect:Z=>{v?.some(Y=>Y.id===Z)&&(C(Z),T(!1))}}):null,spanFeedbackTabBadge:M?.pagination?.total??void 0,spanFeedbackTabSlot:({traceId:R,spanId:U})=>R&&U?o.jsx(hRe,{traceId:R,spanId:U},`${R}:${U}`):null,spanPanelClassName:"rounded-none border-0 bg-transparent"})]}):a||i?o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(Vt,{})})}):o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(br,{iconSlot:o.jsx(O0e,{}),titleSlot:"Item not found",descriptionSlot:`No loaded result for item "${e}".`,actionSlot:o.jsx(ie,{onClick:l,children:"Close"})})})})})}const yRe=e=>o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 9.83952 9.3295",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.67171 0.838331H6.70163V4.05307L9.68767 8.09999C10.0634 8.6093 9.69869 9.32932 9.06643 9.3295H0.772551C0.140289 9.3293 -0.223777 8.60929 0.151995 8.09999L3.13804 4.05307V0.838331H2.17136V0H7.67171V0.838331ZM3.97705 4.32955L3.89513 4.44015L2.34681 6.53802H7.49285L5.94453 4.44015L5.86261 4.32955V0.860859H3.97705V4.32955Z",fill:"currentColor"})}),kV="all",Btt=60,Rxs=e=>e.length>Btt?`${e.slice(0,Btt)}…`:e;function Pxs({value:e,onValueChange:t,className:n,variant:r,allOption:s}){const{data:a,isLoading:i,isError:l}=fY(void 0),c=(a?.experiments??[]).map(d=>({label:jHt(d),value:d.id,start:o.jsx(yRe,{className:"text-neutral3 size-4 shrink-0","data-testid":"experiments-icon"}),description:d.description?Rxs(d.description):y0(d.id)??d.id})),u=s?[{label:"All experiments",value:kV},...c]:c;return o.jsx(vl,{options:u,value:e??(s?kV:""),onValueChange:t,placeholder:i?"Loading experiments...":l?"Failed to load experiments":"Select experiment",searchPlaceholder:"Search experiments...",emptyText:"No experiments found.",className:n,disabled:i||l,variant:r})}function $xs(){const[e,t]=za(),n=e.get("experiment"),r=e.get("review"),{data:s,error:a}=fY(void 0),i=s?.experiments.find(c=>c.id===n),l=c=>{t(c===kV?{}:{experiment:c},{replace:!0})};return a&&hs(a)?o.jsx(Zn,{children:o.jsx(Ts,{})}):a&&ps(a)?o.jsx(Zn,{children:o.jsx(ks,{resource:"experiments"})}):a?o.jsx(Zn,{children:o.jsx(La,{title:"Failed to load experiments",message:a.message})}):o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(Lt.Row,{children:o.jsx(Lt.Column,{className:"justify-items-start",children:o.jsx(Pxs,{allOption:!0,value:n??void 0,onValueChange:l,className:"w-80"})})})}),o.jsx(Lt.MainArea,{className:"overflow-visible",children:o.jsx(lxs,{datasetId:i?.datasetId??void 0,experimentId:n??void 0,featuredItemId:r,detailPanelVariant:"overlay"},n??kV)})]})}const Mxs=20;function Dxs({reviewStatus:e}){const t=Ye(),n=Ly({queryKey:["feedback","list",e],queryFn:({pageParam:r})=>t.listFeedback({filters:{reviewStatus:e},pagination:{page:r,perPage:Mxs},orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:r=>r.pagination?.hasMore?r.pagination.page+1:void 0});return{...n,items:n.data?.pages.flatMap(r=>r.feedback)??[],total:n.data?.pages[0]?.pagination?.total}}function Lxs({enabled:e}){const t=Ye();return mt({queryKey:["feedback","inbox-count"],queryFn:()=>t.listFeedback({filters:{reviewStatus:"needs-review"},pagination:{page:0,perPage:1},orderBy:{field:"timestamp",direction:"DESC"}}),enabled:e,refetchInterval:3e3})}function Fxs(){const e=Ye(),t=Ar();return Sn({mutationFn:({feedbackId:n,reviewStatus:r})=>e.updateFeedbackReviewStatus({feedbackId:n,reviewStatus:r}),onSuccess:()=>t.invalidateQueries({queryKey:["feedback"]})})}const Utt="minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) auto";function zxs({items:e,isLoading:t,error:n}){const r=qr(),[s,a]=g.useState(""),i=s.trim().toLowerCase(),l=i?e.filter(d=>[d.itemId,d.experimentId,d.datasetId,d.traceId??""].some(f=>f.toLowerCase().includes(i))):e,{containerRef:c,getRowProps:u}=ao({count:l.length});return t?o.jsx(Bo,{columns:Utt}):n?o.jsx(La,{title:"Failed to load dataset items",message:n.message}):e.length===0?o.jsx(br,{iconSlot:o.jsx(N0e,{className:"text-neutral3 h-8 w-8"}),titleSlot:"Nothing to review",descriptionSlot:"Experiment results that need review will show up here."}):o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_1fr] gap-4",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(cd,{onSearch:a,label:"Filter dataset items",placeholder:"Filter by item, experiment, dataset or trace",shortcutDisabled:!0})}),o.jsx("div",{className:"min-h-0 overflow-hidden",children:o.jsxs(pe,{columns:Utt,fit:"container",scrollRef:c,children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{children:"Item"}),o.jsx(pe.TopCell,{children:"Experiment"}),o.jsx(pe.TopCell,{children:"Dataset"}),o.jsx(pe.TopCell,{children:"Trace"}),o.jsx(pe.TopCell,{children:" "})]}),l.length===0?o.jsx(pe.NoMatch,{message:"No dataset items match your search"}):l.map((d,f)=>{const h=STe(d.experimentId,d.id);return o.jsxs(pe.RowWrapper,{children:[o.jsxs(pe.RowButton,{colEnd:-2,onClick:()=>r(h),...u(f),children:[o.jsx(pe.TextCell,{font:"mono",children:d.itemId}),o.jsx(pe.TextCell,{font:"mono",children:d.experimentId}),o.jsx(pe.TextCell,{font:"mono",children:d.datasetId}),o.jsx(pe.TextCell,{font:"mono",children:d.traceId??"—"})]}),o.jsx(pe.ActionsCell,{className:"pl-2",children:d.traceId?o.jsx(ie,{as:Da,to:`/traces?traceId=${encodeURIComponent(d.traceId)}`,variant:"ghost",size:"sm",children:"Open trace"}):null})]},d.id)})]})})]})}function Bxs(){return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx(N0e,{}),titleSlot:"Your inbox is empty",descriptionSlot:o.jsxs(o.Fragment,{children:["Feedback left on traces and experiment results flagged for review ",o.jsx("br",{}),"will show up here until you mark them reviewed."]}),actionSlot:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ie,{as:Da,to:"/experiments",variant:"outline",children:"Go to experiments"}),o.jsx(ie,{as:Da,to:"/traces",variant:"outline",children:"Go to traces"})]})})})}function l0e(e){return e.comment?e.comment:typeof e.value=="string"?e.value:e.feedbackType==="thumbs"?e.value===1?"Thumbs up":"Thumbs down":JSON.stringify(e.value)??String(e.value)}const qtt="minmax(0, 2fr) auto minmax(0, 1fr) auto auto";function Uxs({items:e,isLoading:t,error:n,hasNextPage:r,isFetchingNextPage:s,fetchNextPage:a,onMarkReviewed:i,pendingFeedbackId:l,onSelect:c,selectedFeedbackId:u}){const[d,f]=g.useState(""),h=d.trim().toLowerCase(),p=h?e.filter(x=>l0e(x).toLowerCase().includes(h)||(x.traceId??"").toLowerCase().includes(h)||(x.feedbackSource??"").toLowerCase().includes(h)):e,{containerRef:m,getRowProps:v}=ao({count:p.length}),{inView:y,setRef:b}=a0({root:m});return g.useEffect(()=>{y&&r&&!s&&a()},[y,r,s,a]),t?o.jsx(Bo,{columns:qtt}):n?o.jsx(La,{title:"Failed to load feedback",message:n.message}):o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_1fr] gap-4",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(cd,{onSearch:f,label:"Filter feedback",placeholder:"Filter loaded feedback by text, trace or source"})}),o.jsx("div",{className:"min-h-0 overflow-hidden",children:o.jsxs(pe,{columns:qtt,fit:"container",scrollRef:m,children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{children:"Feedback"}),o.jsx(pe.TopCell,{children:"Source"}),o.jsx(pe.TopCell,{children:"Trace"}),o.jsx(pe.TopCell,{children:"Date"}),o.jsx(pe.TopCell,{children:" "})]}),p.length===0?o.jsx(pe.NoMatch,{message:h?"No feedback matches your search":"No feedback needs review"}):p.map((x,w)=>{const k=x.feedbackId;return o.jsxs(pe.RowWrapper,{children:[o.jsxs(pe.RowButton,{colEnd:-2,disabled:!x.traceId,featured:k!==void 0&&k===u,onClick:()=>c(x),...v(w),children:[o.jsx(pe.TextCell,{className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:l0e(x)})}),o.jsx(pe.Cell,{children:o.jsx(bt,{size:"sm",children:x.feedbackSource})}),o.jsx(pe.TextCell,{font:"mono",className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:x.traceId??"—"})}),o.jsx(pe.TextCell,{children:dr(x.timestamp,"MMM d, h:mm a")})]}),o.jsx(pe.ActionsCell,{className:"pl-2",children:k?o.jsx(ie,{variant:"ghost",size:"sm",onClick:()=>i(k),disabled:l===k,children:"Mark reviewed"}):null})]},k??`${String(x.timestamp)}-${x.traceId}`)}),o.jsx(pe.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:b})]})})]})}function qxs({feedback:e,traceId:t,initialSpanId:n,onClose:r,onPrevious:s,onNext:a,onMarkReviewed:i,isMarkingReviewed:l}){const[c,u]=g.useState(n),{spans:d,isLoading:f}=BAe({traceId:t,anchorSpanId:null,listMode:"traces"});return o.jsx(uY,{label:`Review feedback for trace ${t}`,wide:!!c,children:o.jsxs("div",{className:"[&>*]:bg-surface3 grid h-full min-h-0 grid-rows-[auto_minmax(0,1fr)] gap-4 p-3 [&>*]:rounded-lg [&>*]:shadow-lg",children:[o.jsxs(Gt,{className:"max-h-[33vh]",children:[o.jsxs(Gt.Header,{className:"items-start",children:[o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Gt.Heading,{children:"Feedback"}),o.jsx(bt,{variant:"neutral",emphasis:"muted",children:e.feedbackType}),e.feedbackSource&&o.jsx(bt,{variant:"neutral",emphasis:"muted",children:e.feedbackSource})]}),o.jsxs(ve,{as:"p",variant:"ui-sm",className:"text-neutral3",children:[dr(new Date(e.timestamp),"MMM dd, yyyy HH:mm:ss"),e.feedbackUserId?` · ${e.feedbackUserId}`:null]})]}),o.jsx(es,{className:"ml-auto shrink-0",children:o.jsxs(ie,{variant:"primary",size:"sm",onClick:i,disabled:l,children:[o.jsx(Qe,{children:o.jsx(Ur,{})}),"Mark as reviewed"]})})]}),o.jsx(Gt.Content,{children:o.jsx(ve,{as:"p",variant:"ui-md",className:"text-neutral5 whitespace-pre-wrap",children:l0e(e)})})]}),o.jsx("section",{className:"min-h-0 overflow-hidden",children:o.jsx(rY,{className:"h-full rounded-none border-0 bg-transparent",spanPanelClassName:"rounded-none border-0 bg-transparent",traceId:t,spans:d,isLoadingSpans:f,selectedSpanId:c??null,initialSpanId:n,onSpanSelect:u,onClose:r,onPrevious:s,onNext:a,traceHref:`/traces?traceId=${encodeURIComponent(t)}`,feedbackTabSlot:({traceId:h})=>o.jsx(iY,{traceId:h}),spanFeedbackTabSlot:({traceId:h,spanId:p})=>h&&p?o.jsx(hRe,{traceId:h,spanId:p},`${h}:${p}`):null})})]})})}const BHt=100;async function Vxs(e){const t=[];let n=0,r=!0;for(;r;){const s=await e.listExperiments({page:n,perPage:BHt});t.push(...s.experiments),r=s.pagination.hasMore,n+=1}return t}async function Hxs(e,t,n){const r=[];let s=0,a=!0;for(;a;){const i=await e.listDatasetExperimentResults(t,n,{page:s,perPage:BHt});r.push(...i.results),a=i.pagination.hasMore,s+=1}return r}function Wxs(){const e=Ye();return mt({queryKey:["inbox-dataset-review-items"],queryFn:async()=>{const t=await Vxs(e);return(await Promise.all(t.map(async r=>{const s=r.datasetId;return s?(await Hxs(e,s,r.id)).filter(i=>i.status==="needs-review").map(i=>({id:i.id,datasetId:s,experimentId:r.id,itemId:i.itemId,traceId:i.traceId??void 0,input:i.input,output:i.output})):[]}))).flat()},refetchInterval:3e3,refetchOnWindowFocus:!1})}function Zxs({enabled:e}){const t=Ye();return mt({queryKey:["inbox-dataset-review-count"],queryFn:async()=>{const{counts:n}=await t.getExperimentReviewSummary();return n.reduce((r,s)=>r+s.needsReview,0)},enabled:e,refetchInterval:3e3})}function Gxs(e){return e==="dataset"||e==="feedback"}function Qxs(){const[e,t]=za(),n=e.get("tab"),r=Gxs(n)?n:"feedback",s=Dxs({reviewStatus:"needs-review"}),a=Fxs(),i=Wxs(),l=i.data??[],c=s.total??0,u=!s.isLoading&&!i.isLoading&&!s.error&&!i.error&&s.items.length===0&&l.length===0,d=e.get("feedbackId")??void 0,f=e.get("traceId")??void 0,h=e.get("spanId")??void 0,p=T=>{t(E=>{const N=new URLSearchParams(E);for(const I of["feedbackId","traceId","spanId"]){const A=T[I];A?N.set(I,A):N.delete(I)}return N},{replace:!0})},m=()=>p({}),v=T=>p({feedbackId:T.feedbackId??void 0,traceId:T.traceId??void 0,spanId:T.spanId??void 0}),y=s.items.findIndex(T=>T.feedbackId===d),b=y>=0?s.items[y]:void 0,x=y>0?s.items[y-1]:void 0,w=y>=0&&y<s.items.length-1?s.items[y+1]:void 0,k=!!f&&!!d,C=T=>{a.mutate({feedbackId:T,reviewStatus:"reviewed"},{onSuccess:()=>T===d&&m()})},_=T=>{t(E=>{const N=new URLSearchParams(E);return N.set("tab",T),N},{replace:!0})};return o.jsxs("div",{className:"relative h-full overflow-hidden",children:[o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs(Dl,{children:[o.jsx(Dl.Title,{children:"Inbox"}),o.jsx(Dl.Description,{children:"Items waiting for review"})]})}),o.jsx(Lt.MainArea,{className:"min-h-0 overflow-hidden",children:u?o.jsx(Bxs,{}):o.jsxs(Zc,{defaultTab:"feedback",value:r,onValueChange:_,className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[o.jsxs(Wc,{variant:"pill-ghost",children:[o.jsxs(Qr,{value:"feedback",className:"px-3 py-2.5",children:[o.jsx(Qe,{size:"sm",children:o.jsx(t3,{})}),o.jsx(ve,{variant:"ui-sm",className:"text-inherit",children:"Feedback"}),c>0&&o.jsx(bt,{variant:"yellow",size:"sm",children:c})]}),o.jsxs(Qr,{value:"dataset",className:"px-3 py-2.5",children:[o.jsx(Qe,{size:"sm",children:o.jsx(X1,{})}),o.jsx(ve,{variant:"ui-sm",className:"text-inherit",children:"Dataset items"}),l.length>0&&o.jsx(bt,{variant:"yellow",size:"sm",children:l.length})]})]}),o.jsx(_s,{value:"feedback",className:"h-full min-h-0 pt-4",children:o.jsx(Uxs,{items:s.items,isLoading:s.isLoading,error:s.error??void 0,hasNextPage:s.hasNextPage,isFetchingNextPage:s.isFetchingNextPage,fetchNextPage:s.fetchNextPage,onMarkReviewed:C,pendingFeedbackId:a.isPending?a.variables?.feedbackId:void 0,onSelect:v,selectedFeedbackId:d})}),o.jsx(_s,{value:"dataset",className:"h-full min-h-0 pt-4",children:o.jsx(zxs,{items:l,isLoading:i.isLoading,error:i.error??void 0})})]})})]}),k&&f&&b&&o.jsx(qxs,{feedback:b,traceId:f,initialSpanId:h,onClose:m,onPrevious:x?()=>v(x):void 0,onNext:w?()=>v(w):void 0,onMarkReviewed:()=>d&&C(d),isMarkingReviewed:a.isPending},`${d}:${f}`)]})}function Yxs({connection:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsxs("li",{className:"flex items-center justify-between border-b py-2",children:[o.jsxs("div",{children:[o.jsx("div",{className:"font-mono text-xs",children:e.connectionId}),o.jsxs("div",{className:"text-xs text-gray-500",children:[e.label??"(no label)"," · ",e.status,e.scope?` · ${e.scope}`:"",t&&e.authorId?` · author: ${e.authorId}`:""]})]}),o.jsx("button",{type:"button",className:"text-red-600 underline disabled:opacity-50",onClick:r,disabled:n,children:"Disconnect"})]})}function UHt({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("ul",{className:"space-y-1",children:e.map(s=>o.jsx(Yxs,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function Kxs({groups:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("div",{className:"space-y-4",children:e.map(([s,a])=>o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-semibold text-gray-700","data-testid":`integration-author-group-${s}`,children:s==="shared"?"Shared":`Owned by ${s}`}),o.jsx(UHt,{connections:a,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function Xxs({providerId:e,toolkit:t,connections:n,groupedByAuthor:r,isAdmin:s,isLoading:a,error:i,disconnectPending:l,disconnectError:c,onDisconnect:u}){return o.jsxs("div",{className:"space-y-2 border rounded p-4",children:[o.jsx("h2",{className:"text-lg font-semibold",children:"Existing connections"}),!e||!t?o.jsx("p",{className:"text-gray-500",children:"Pick a provider and toolkit to list connections."}):a?o.jsx("p",{className:"text-gray-500",children:"Loading…"}):i?o.jsx("p",{className:"text-red-600",children:String(i)}):n.length===0?o.jsx("p",{className:"text-gray-500",children:"No connections."}):r?o.jsx(Kxs,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):o.jsx(UHt,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?o.jsx("p",{className:"text-red-600",children:String(c)}):null]})}function Jxs({providers:e,toolkits:t,providerId:n,toolkit:r,label:s,providersLoading:a,providersError:i,toolkitsLoading:l,toolkitsError:c,authorizePending:u,authorizeError:d,authorizedConnection:f,onProviderChange:h,onToolkitChange:p,onLabelChange:m,onConnect:v}){return o.jsxs("div",{className:"space-y-4 border rounded p-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"provider-select",children:"Provider"}),o.jsxs("select",{id:"provider-select",className:"border rounded px-2 py-1 w-full",value:n,onChange:y=>h(y.target.value),disabled:a,children:[o.jsx("option",{value:"",children:"— select provider —"}),e.map(y=>o.jsxs("option",{value:y.id,children:[y.displayName??y.name," (",y.id,")"]},y.id))]}),a&&o.jsx("span",{className:"text-gray-500",children:"Loading providers…"}),i?o.jsx("span",{className:"text-red-600",children:String(i)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"toolkit-select",children:"Toolkit"}),o.jsxs("select",{id:"toolkit-select",className:"border rounded px-2 py-1 w-full",value:r,onChange:y=>p(y.target.value),disabled:!n||l,children:[o.jsx("option",{value:"",children:"— select toolkit —"}),t.map(y=>o.jsxs("option",{value:y.slug,children:[y.name," (",y.slug,")"]},y.slug))]}),l&&o.jsx("span",{className:"text-gray-500",children:"Loading toolkits…"}),c?o.jsx("span",{className:"text-red-600",children:String(c)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"label-input",children:"Label (optional)"}),o.jsx("input",{id:"label-input",type:"text",className:"border rounded px-2 py-1 w-full",placeholder:"My personal Gmail",value:s,onChange:y=>m(y.target.value),disabled:!n||!r})]}),o.jsx("button",{type:"button",className:"bg-blue-600 text-white rounded px-4 py-2 disabled:opacity-50",onClick:v,disabled:!n||!r||u,children:u?"Authorizing…":"Connect"}),d?o.jsx("p",{className:"text-red-600",children:String(d)}):null,f&&o.jsxs("p",{className:"text-green-700",children:["Authorized: ",f.connectionId," (status: ",f.status,")"]})]})}const Vtt=e=>e.authorId?.trim()||"shared",e0s=(e,t)=>{if(!t||new Set(e.map(Vtt)).size<=1)return null;const r=new Map;for(const a of e){const i=Vtt(a);r.set(i,[...r.get(i)??[],a])}const s=Array.from(r.entries());return s.sort(([a],[i])=>a==="shared"?1:i==="shared"?-1:a.localeCompare(i)),s},t0s=["*","tool-providers:*","tool-providers:admin"];function n0s(){const{data:e}=zm();return e?.permissions?.some(t=>t0s.includes(t))??!1}function r0s(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,a]=g.useState(""),i=sA(),l=uG(e||null),c=n4t(e||null,n||null),u=t4t(),d=X3t(),f=n0s(),h=i.data?.providers??[],p=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),v=g.useMemo(()=>e0s(m,f),[m,f]),y=w=>{t(w),r("")},b=()=>{!e||!n||u.mutate({providerId:e,toolkit:n,label:s.trim()||null},{onSuccess:()=>{a(""),c.refetch()}})},x=w=>{d.mutate({providerId:e,connectionId:w})};return o.jsxs("div",{className:"p-6 max-w-3xl space-y-6 text-sm",children:[o.jsx("h1",{className:"text-2xl font-semibold",children:"Integrations"}),o.jsx("p",{className:"text-gray-500",children:"Minimal page to verify the ToolProvider backend. Pick a provider and toolkit, then connect."}),o.jsx(Jxs,{providers:h,toolkits:p,providerId:e,toolkit:n,label:s,providersLoading:i.isLoading,providersError:i.error,toolkitsLoading:l.isLoading,toolkitsError:l.error,authorizePending:u.isPending,authorizeError:u.error,authorizedConnection:u.data,onProviderChange:y,onToolkitChange:r,onLabelChange:a,onConnect:b}),o.jsx(Xxs,{providerId:e,toolkit:n,connections:m,groupedByAuthor:v,isAdmin:f,isLoading:c.isLoading,error:c.error,disconnectPending:d.isPending,disconnectError:d.error,onDisconnect:x})]})}function s0s({title:e,description:t,errorBanner:n,children:r}){return o.jsx("div",{"data-testid":"login-page",className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsxs("div",{className:"w-full max-w-sm space-y-6",children:[o.jsxs("div",{className:"flex flex-col items-center space-y-2",children:[o.jsx(Wh,{className:"h-10 w-10"}),o.jsx("h1",{className:"text-neutral6 text-xl font-semibold",children:e})]}),t,n,r]})})}function qHt({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:a}=pc(),{mutate:i,isPending:l,error:c}=V2r(),{mutate:u,isPending:d,error:f}=W2r(),{mutate:h,isPending:p}=rDt(),[m,v]=g.useState(n),[y,b]=g.useState(""),[x,w]=g.useState(""),[k,C]=g.useState("");if(a)return o.jsx("div",{className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"text-neutral3",children:"Loading..."})});if(!s?.enabled||!s?.login)return o.jsx("div",{className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"text-neutral3",children:"Authentication is not configured"})});const{login:_}=s,T=_.type==="sso"||_.type==="both",E=_.type==="credentials"||_.type==="both",N=_.sso,I=_.signUpEnabled!==!1,A=m==="signin"||!I,P=A?l:d,L=A?c:f,D=()=>{t?t():e?window.location.href=e:window.location.href=bG("/")},B=M=>{M.preventDefault(),A?i({email:x,password:k},{onSuccess:D}):u({email:x,password:k,name:y||void 0},{onSuccess:D})},H=()=>{h({redirectUri:e},{onSuccess:M=>{window.location.href=M.url}})},q=()=>{v(A?"signup":"signin")},z=_.description?o.jsxs("div",{className:"border-border1 bg-surface1 flex items-start gap-2.5 rounded-md border p-3",children:[o.jsx(Bd,{className:"text-neutral4 mt-0.5 h-4 w-4 shrink-0"}),o.jsx("p",{className:"text-neutral3 text-sm",children:_.description})]}):null,V=r?o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:r}):null;return o.jsxs(s0s,{title:A?"Sign in to Mastra Studio":"Create your account",description:z,errorBanner:V,children:[E&&o.jsxs("form",{onSubmit:B,className:"space-y-4",children:[!A&&o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"name",className:"text-neutral4 block text-sm",children:"Name"}),o.jsx(jn,{id:"name",type:"text",value:y,onChange:M=>b(M.target.value),placeholder:"Your name",variant:"default",size:"lg"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"email",className:"text-neutral4 block text-sm",children:"Email"}),o.jsx(jn,{id:"email",type:"email",value:x,onChange:M=>w(M.target.value),placeholder:"you@example.com",required:!0,variant:"default",size:"lg"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"password",className:"text-neutral4 block text-sm",children:"Password"}),o.jsx(jn,{id:"password",type:"password",value:k,onChange:M=>C(M.target.value),placeholder:A?"Enter your password":"Create a password",required:!0,variant:"default",size:"lg"})]}),L&&o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:L.message}),o.jsx(ie,{type:"submit",disabled:P,className:"w-full",size:"lg",children:P?A?"Signing in...":"Creating account...":A?"Sign in":"Create account"}),I&&o.jsxs("div",{className:"text-center text-sm",children:[o.jsx("span",{className:"text-neutral3",children:A?"Don't have an account? ":"Already have an account? "}),o.jsx("button",{type:"button",onClick:q,className:"text-neutral6 hover:underline",children:A?"Sign up":"Sign in"})]})]}),T&&E&&o.jsxs("div",{className:"relative",children:[o.jsx("div",{className:"absolute inset-0 flex items-center",children:o.jsx("div",{className:"border-border1 w-full border-t"})}),o.jsx("div",{className:"relative flex justify-center text-sm",children:o.jsx("span",{className:"bg-surface1 text-neutral3 px-2",children:"or continue with"})})]}),T&&N&&o.jsxs(ie,{onClick:H,disabled:p,className:"w-full",size:"lg",variant:"outline",children:[N.icon&&o.jsx("span",{className:"mr-2",children:N.icon}),p?"Redirecting...":N.text||"Sign in"]})]})}function a0s(){const[e]=za(),t=qr(),n=e.get("redirect")||"/",s=e.get("mode")==="signup"?"signup":"signin",a=e.get("error_description")||e.get("error")||null,i=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(qHt,{redirectUri:n,onSuccess:i,initialMode:s,errorMessage:a})}const gh=Aa.KeyValueList;function i0s(e){return e instanceof Date?e:new Date(e)}function o0s({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:a,collapsed:i,onCollapsedChange:l}){const[c,u]=g.useState(!1),d=i??c,f=l??u,h=i0s(e.timestamp),p=e.traceId,m=e.spanId;return o.jsxs(Aa,{collapsed:d,children:[o.jsxs(Aa.Header,{children:[o.jsxs(Aa.Heading,{children:["Log ",o.jsx("b",{children:dr(h,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(es,{className:"ml-auto shrink-0",children:[l&&o.jsx(ie,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(aI,{}):o.jsx(_V,{})}),o.jsxs(es,{spacing:"close",children:[o.jsx(ie,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(K1,{})}),o.jsx(ie,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(CV,{})})]}),o.jsx(Aa.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(Aa.Content,{children:[o.jsx("p",{className:"text-ui-md text-neutral4 font-mono wrap-break-word whitespace-pre-wrap",children:e.message}),(p||m)&&o.jsxs("div",{className:K("my-8 grid gap-2","[&>button]:justify-between [&>button]:overflow-hidden"),children:[p&&o.jsxs(es,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(ie,{size:"md",className:"min-w-0 flex-1 overflow-hidden",onClick:()=>n?.(p),children:[o.jsx(Fd,{}),o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",p]})]}),o.jsx(_a,{content:p,size:"md",tooltip:"Copy Trace ID to clipboard"})]}),m&&o.jsxs(es,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(ie,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!p||!r,onClick:()=>p&&r?.(p,m),children:[o.jsx(Fd,{}),o.jsx("span",{children:"Span"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",m]})]}),o.jsx(_a,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(gh,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(gh.Key,{children:"Entity Type"}),o.jsx(gh.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(gh.Key,{children:"Entity Name"}),o.jsx(gh.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(gh.Key,{children:"Service"}),o.jsx(gh.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(gh.Key,{children:"Environment"}),o.jsx(gh.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(gh.Key,{children:"Source"}),o.jsx(gh.Value,{children:e.source})]}),e.metadata&&Object.keys(e.metadata).length>0&&o.jsx(o.Fragment,{children:Object.entries(e.metadata).map(([v,y])=>o.jsxs(g.Fragment,{children:[o.jsx(gh.Key,{children:v}),o.jsx(gh.Value,{children:String(y)})]},v))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(Aa.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function l0s({error:e,resource:t,errorTitle:n}){if(hs(e))return o.jsx(Ts,{});if(ps(e))return o.jsx(ks,{resource:t});if(B4(e))return o.jsx(br,{iconSlot:o.jsx(Mc,{}),titleSlot:"Observability storage is not available",descriptionSlot:"The observability storage domain is disabled or not configured. Enable it in your storage configuration to view logs in Studio."});if(z4(e,"logs"))return o.jsx(br,{iconSlot:o.jsx(Mc,{}),titleSlot:"Logs are not available with your current storage",descriptionSlot:"The configured observability storage provider does not support listing logs. Switch to a storage provider with logs support to view runtime logs in Studio."});const r=e instanceof Error?e.message:void 0;return o.jsx(La,{title:n,message:r??"Unknown error"})}function c0s({listSlot:e,logPanelSlot:t,tracePanelSlot:n,spanPanelSlot:r,logCollapsed:s}){const a=!!t;return o.jsxs("div",{className:K("grid h-full min-h-0 items-start gap-4",a?"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[e,a&&o.jsxs("div",{className:K("grid h-full gap-4 overflow-auto",n&&r?s?"grid-rows-[auto_1fr_1fr]":"grid-rows-[1fr_1fr_1fr]":n?s?"grid-rows-[auto_1fr]":"grid-rows-[1fr_1fr]":s?"grid-rows-[auto]":"grid-rows-[1fr]"),children:[t,n,r]})]})}const u0s={debug:{label:"DEBUG",color:"#71717a"},info:{label:"INFO",color:"#60a5fa"},warn:{label:"WARN",color:"#facc15"},error:{label:"ERROR",color:"#f87171"},fatal:{label:"FATAL",color:"#dc2626"}};function d0s({level:e}){const t=u0s[e];return o.jsx(ho,{children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function f0s({entityType:e,className:t}){const n=K("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case"agent":return o.jsx(Ri,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return o.jsx(Bc,{className:n,"aria-hidden":!0});case"tool":return o.jsx(Bf,{className:n,"aria-hidden":!0});default:return null}}function h0s({entityType:e,entityName:t}){const n=e??"";return o.jsxs(ho,{className:"flex min-w-0 items-center gap-2",children:[o.jsx(f0s,{entityType:n}),t?o.jsx("span",{className:"text-ui-smd min-w-0 truncate",children:t}):"-"]})}function p0s({message:e}){return o.jsx(ho,{className:"text-ui-smd text-neutral4 min-w-0 truncate font-mono",children:e})}function m0s({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(ho,{children:null});const t=Object.entries(e).map(([n,r])=>{if(typeof r=="string")return`${n}: ${r}`;try{return`${n}: ${JSON.stringify(r)}`}catch{return`${n}: <unserializable>`}}).join(", ");return o.jsx(ZEe,{font:"mono",children:t})}const tc=Object.assign(D4,{Top:F4,TopCell:vS,TopCellWithTooltip:YZ,TopCellSmart:c$t,RowWrapper:YEe,RowButton:L4,RowLink:l$t,Spacer:KEe,NoMatch:QZ,DateCell:a$t,TimeCell:i$t,LevelCell:d0s,EntityCell:h0s,MessageCell:p0s,DataCell:m0s,NextPageLoading:GZ}),Htt="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",g0s=36,v0s=8;function y0s({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=g.useRef(null),u=Zqt({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>g0s,overscan:v0s}),{getRowProps:d}=ao({count:e.length,containerRef:c,onNavigate:y=>u.scrollToIndex(y)}),f=g.useRef(t);if(g.useEffect(()=>{f.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),f.current=t},[t]),t)return o.jsx(Bo,{columns:Htt});const h=u.getVirtualItems(),p=u.getTotalSize(),m=h[0]?.start??0,v=h.length>0?Math.max(0,p-(h[h.length-1]?.end??0)):0;return o.jsxs(tc,{columns:Htt,scrollRef:c,className:"min-w-0",children:[o.jsxs(tc.Top,{children:[o.jsx(tc.TopCell,{children:"Date"}),o.jsx(tc.TopCell,{children:"Time"}),o.jsx(tc.TopCell,{children:"Level"}),o.jsx(tc.TopCell,{children:"Entity"}),o.jsx(tc.TopCell,{children:"Message"}),o.jsx(tc.TopCell,{children:"Data"})]}),e.length===0?o.jsx(tc.NoMatch,{message:"No logs match your search"}):o.jsxs(o.Fragment,{children:[o.jsx(tc.Spacer,{height:m}),h.map(y=>{const b=e[y.index];if(!b)return null;const x=a.get(b);if(!x)return null;const w=x===i;return o.jsxs(tc.RowButton,{ref:u.measureElement,"data-index":y.index,...d(y.index),onClick:()=>l(b),featured:w,variant:b.level==="error"||b.level==="fatal"?"error":"default",children:[o.jsx(tc.DateCell,{timestamp:b.timestamp}),o.jsx(tc.TimeCell,{timestamp:b.timestamp}),o.jsx(tc.LevelCell,{level:b.level}),o.jsx(tc.EntityCell,{entityType:b.entityType,entityName:b.entityName}),o.jsx(tc.MessageCell,{message:b.message}),o.jsx(tc.DataCell,{data:b.data})]},x)}),o.jsx(tc.Spacer,{height:v})]}),o.jsx(tc.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function b0s({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>x0s(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(sRe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(nRe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function x0s(e,t){const n=t.find(r=>r.id===e.fieldId);return n?n.kind==="text"?typeof e.value=="string"&&e.value.trim()!=="":n.kind==="pick-multi"?n.multi?Array.isArray(e.value)&&e.value.length>0:typeof e.value=="string"&&e.value!==""&&e.value!=="Any":n.kind==="multi-select"?Array.isArray(e.value)&&e.value.length>0:!1:!1}const w0s={"last-24h":"the last 24 hours","last-3d":"the last 3 days","last-7d":"the last 7 days","last-14d":"the last 14 days","last-30d":"the last 30 days"},aoe="MMM d, yyyy HH:mm",ioe="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function S0s({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${w0s[e]}`,description:ioe}:t&&n?{title:`No logs between ${dr(t,aoe)} and ${dr(n,aoe)}`,description:ioe}:t?{title:`No logs since ${dr(t,aoe)}`,description:ioe}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const k0s=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=S0s({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx(Mc,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",children:["Logging Documentation ",o.jsx(ta,{})]})})})},O0s=20,C0s=1e4;function _0s(e,t,n){if(e?.pagination?.hasMore)return n+1}function E0s(e){const t=new Set,n=[];for(const r of e.pages)for(const s of r.logs??[]){const a=s.logId??JSON.stringify(s);t.has(a)||(t.add(a),n.push(s))}return n}function T0s(e){return z4(e.state.error,"logs")||B4(e.state.error)?!1:C0s}const j0s=({filters:e}={})=>{const t=Ye(),{inView:n,setRef:r}=a0(),s=Ly({queryKey:["logs",e],queryFn:({pageParam:h})=>t.listLogsVNext({pagination:{page:h,perPage:O0s},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:_0s,select:E0s,retry:!1,refetchInterval:T0s}),{hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,data:c,isLoading:u,isError:d,error:f}=s;return g.useEffect(()=>{n&&a&&!i&&l()},[n,a,i,l]),{data:c,hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,isLoading:u,isError:d,error:f,setEndOfListElement:r}},c8={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},VHt=[{label:"Agent",entityType:c8.AGENT},{label:"Workflow",entityType:c8.WORKFLOW},{label:"Scorer",entityType:c8.SCORER},{label:"Ingest",entityType:c8.INGEST}],N0s=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],Xx="rootEntityType",rx="datePreset",sx="dateFrom",ax="dateTo",I0s=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),jl={level:"filterLevel",tags:"filterTags",entityName:"filterEntityName",traceId:"filterTraceId",spanId:"filterSpanId",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId"},KL=Object.keys(jl),bRe=new Set(["tags"]),xRe="mastra:logs:saved-filters";function A0s(e,t=xRe){const n=D0s(e),r=e.get(rx);r&&n.set(rx,r);const s=e.get(sx);s&&n.set(sx,s);const a=e.get(ax);a&&n.set(ax,a);try{localStorage.setItem(t,n.toString())}catch{}}function R0s(e=xRe){try{localStorage.removeItem(e)}catch{}}function Wtt(e=xRe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function P0s(e){if(e.has(rx)||e.has(sx)||e.has(ax)||e.has(Xx))return!0;for(const t of KL)if(e.has(jl[t]))return!0;return!1}function $0s({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:VHt.map(u=>({label:u.label,value:u.entityType})),placeholder:"Choose entity type",emptyText:"No entity types."},{id:"entityName",label:"Primitive Name",kind:"pick-multi",options:t.map(u=>({label:u,value:u})),placeholder:"Choose entity names",emptyText:"No entity names found.",isLoading:s?.entityNames},{id:"level",label:"Level",kind:"pick-multi",searchable:!1,options:N0s.map(u=>({label:u.label,value:u.value})),placeholder:"Choose level",emptyText:"No levels."},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"traceId",label:"Trace ID",kind:"text"},{id:"spanId",label:"Span ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"threadId",label:"Thread ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function M0s(e){const t=[],n=new Map([[Xx,"rootEntityType"]]);for(const s of KL)n.set(jl[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),bRe.has(a)){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function D0s(e){const t=new URLSearchParams,n=e.get(Xx);n&&t.set(Xx,n);for(const r of KL){const s=jl[r];if(bRe.has(r)){for(const i of e.getAll(s))t.append(s,i);continue}const a=e.get(s);a&&t.set(s,a)}return t}function L0s(e,t){e.delete(Xx);for(const n of KL)e.delete(jl[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(Xx,n.value);continue}const r=jl[n.fieldId];if(r){if(bRe.has(n.fieldId)&&Array.isArray(n.value)){if(n.value.length===0)e.append(r,"");else for(const s of n.value)e.append(r,s);continue}typeof n.value=="string"&&e.set(r,n.value.trim())}}}function F0s({rootEntityType:e,dateFrom:t,dateTo:n,tokens:r}){const s={};e&&(s.rootEntityType=e),(t||n)&&(s.timestamp={...t?{start:t}:{},...n?{end:n}:{}});for(const a of r){if(a.fieldId==="tags"){Array.isArray(a.value)&&a.value.length>0?s.tags=a.value:typeof a.value=="string"&&a.value.trim()&&(s.tags=[a.value.trim()]);continue}if(a.fieldId==="level"){typeof a.value=="string"&&a.value.trim()&&a.value!=="Any"&&(s.level=a.value);continue}if(typeof a.value=="string"&&a.value.trim()&&a.value!=="Any")switch(a.fieldId){case"entityName":s.rootEntityName=a.value;break;case"traceId":s.traceId=a.value;break;case"spanId":s.spanId=a.value;break;case"runId":s.runId=a.value;break;case"threadId":s.threadId=a.value;break;case"sessionId":s.sessionId=a.value;break;case"requestId":s.requestId=a.value;break;case"resourceId":s.resourceId=a.value;break;case"userId":s.userId=a.value;break;case"organizationId":s.organizationId=a.value;break;case"serviceName":s.serviceName=a.value;break;case"environment":s.environment=a.value;break;case"experimentId":s.experimentId=a.value;break}}return s}function z0s(e,t){return t.map(n=>{const r=e.find(s=>s.id===n.fieldId);return r?r.kind==="text"?{fieldId:n.fieldId,value:""}:r.kind==="pick-multi"?r.multi?{fieldId:n.fieldId,value:[]}:{fieldId:n.fieldId,value:"Any"}:n:n})}const B0s="Filters setting for Logs saved",U0s="Filters setting for Logs cleared up";function q0s(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=g.useState(()=>Wtt(r)!==null),c=g.useCallback(()=>{A0s(e,r),l(!0);const f=s?.saved??B0s;f!==!1&&Ve.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{R0s(r),l(!1);const f=s?.cleared??U0s;f!==!1&&Ve.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(a||d.current||(d.current=!0,P0s(e)))return;const f=Wtt(r);f&&t(h=>{const p=new URLSearchParams(h);for(const[m,v]of f)p.append(m,v);return p},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function V0s(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return(t>>>0).toString(36)}function H0s(e){const t=new Map;for(const n of e){if(n.logId){t.set(n,n.logId);continue}const r=n.timestamp instanceof Date?n.timestamp.toISOString():n.timestamp;t.set(n,V0s(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function W0s(e,t,n,r){const s=g.useMemo(()=>H0s(e),[e]),a=g.useMemo(()=>{const p=new Map;for(const[m,v]of e.entries()){const y=s.get(v);y&&p.set(y,{log:v,idx:m})}return p},[e,s]),l=(t?a.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=g.useCallback(p=>s.get(p),[s]),d=g.useCallback(p=>{const m=s.get(p);if(m){if(t===m){n({logId:null});return}n(r?{logId:m,traceId:p.traceId??null,spanId:null}:{logId:m})}},[s,t,r,n]),f=l>0?()=>{const p=e[l-1];if(!p)return;const m=s.get(p);m&&n(r?{logId:m,traceId:p.traceId??null,spanId:null}:{logId:m})}:void 0,h=l>=0&&l<e.length-1?()=>{const p=e[l+1];if(!p)return;const m=s.get(p);m&&n(r?{logId:m,traceId:p.traceId??null,spanId:null}:{logId:m})}:void 0;return{logIdMap:s,getLogId:u,featuredLog:c,handleLogClick:d,handlePreviousLog:f,handleNextLog:h}}const c0e="logId",u0e="traceId",d0e="spanId",IP=1440*60*1e3,Z0s={"last-24h":IP,"last-3d":3*IP,"last-7d":7*IP,"last-14d":14*IP,"last-30d":30*IP};function u8(e){e.delete(c0e),e.delete(u0e),e.delete(d0e)}function G0s(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const C=e.get(rx);return C&&I0s.has(C)?C:"last-24h"},[e]),a=e.get(sx),i=e.get(ax),l=g.useMemo(()=>{if(s==="custom"){if(!a)return;const _=new Date(a);return Number.isNaN(_.getTime())?void 0:_}if(s==="all")return;const C=Z0s[s];return C?new Date(Date.now()-C):void 0},[s,a]),c=g.useMemo(()=>{if(s!=="custom"||!i)return;const C=new Date(i);return Number.isNaN(C.getTime())?void 0:C},[s,i]),u=g.useRef(s);u.current=s;const d=e.get(c0e),f=e.get(u0e),h=e.get(d0e),p=g.useMemo(()=>VHt.find(C=>C.entityType===e.get(Xx)),[e]),m=g.useMemo(()=>M0s(e),[e]),v=g.useCallback(C=>{t(_=>{const T=new URLSearchParams(_);for(const[E,N]of Object.entries(C)){const I=E==="logId"?c0e:E==="traceId"?u0e:d0e;N?T.set(I,N):T.delete(I)}return T},{replace:!0})},[t]),y=g.useCallback(C=>{t(_=>{const T=new URLSearchParams(_);return L0s(T,C),u8(T),T},{replace:!0})},[t]),b=y,x=g.useCallback((C,_)=>{if(u.current!=="custom")return;const T=_==="from"?sx:ax;t(E=>{const N=new URLSearchParams(E);return C?N.set(T,C.toISOString()):N.delete(T),u8(N),N},{replace:!0})},[t]),w=g.useCallback(C=>{u.current=C,t(_=>{const T=new URLSearchParams(_);return C==="last-24h"?(T.delete(rx),T.delete(sx),T.delete(ax)):C==="custom"?T.set(rx,"custom"):(T.set(rx,C),T.delete(sx),T.delete(ax)),u8(T),T},{replace:!0})},[t]),k=g.useCallback(()=>{t(C=>{const _=new URLSearchParams(C);_.delete(Xx);for(const T of KL)_.delete(jl[T]);return _.delete(rx),_.delete(sx),_.delete(ax),u8(_),_},{replace:!0}),r?.()},[t,r]);return g.useMemo(()=>({searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,featuredLogId:d,featuredTraceId:f,featuredSpanId:h,selectedEntityOption:p,filterTokens:m,handleFeaturedChange:v,handleFilterTokensChange:b,handleDateChange:x,handleDatePresetChange:w,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,h,p,m,v,b,x,w,k,y])}const Rb=Aa.KeyValueList;function Q0s({spanId:e,span:t,isLoading:n,onClose:r}){const s=zQ(t?.startedAt,t?.endedAt),a=vV(t?.startedAt),i=vV(t?.endedAt);return o.jsxs(Aa,{children:[o.jsxs(Aa.Header,{children:[o.jsxs(Aa.Heading,{children:["Span ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Aa.CloseButton,{onClick:r})]}),n?o.jsx(Aa.LoadingData,{children:"Loading span..."}):t?o.jsxs(Aa.Content,{children:[o.jsxs(Rb,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(Rb.Key,{children:"Type"}),o.jsx(Rb.Value,{children:t.spanType})]}),a&&o.jsxs(o.Fragment,{children:[o.jsx(Rb.Key,{children:"Started"}),o.jsx(Rb.Value,{children:a})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(Rb.Key,{children:"Ended"}),o.jsx(Rb.Value,{children:i})]}),s&&o.jsxs(o.Fragment,{children:[o.jsx(Rb.Key,{children:"Duration"}),o.jsx(Rb.Value,{children:s})]})]}),o.jsx("br",{}),o.jsx(Aa.CodeSection,{title:"Input",icon:o.jsx(Ox,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(Aa.CodeSection,{title:"Output",icon:o.jsx(nm,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(Aa.CodeSection,{title:"Metadata",icon:o.jsx(sc,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(Aa.CodeSection,{title:"Attributes",icon:o.jsx(sc,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(Aa.NoData,{children:"Span not found."})]})}function Y0s({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:a}){const i=g.useMemo(()=>HL(t??[]),[t]),[l,c]=g.useState([]);g.useEffect(()=>{i.length>0&&c(UQ(i))},[i]);const u=d=>{s?.(a===d?void 0:d)};return o.jsxs(Aa,{children:[o.jsxs(Aa.Header,{children:[o.jsxs(Aa.Heading,{children:["Trace ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Aa.CloseButton,{onClick:r})]}),n?o.jsx(Aa.LoadingData,{children:"Loading trace..."}):i.length===0?o.jsx(Aa.NoData,{children:"No spans found for this trace."}):o.jsx(Aa.Content,{children:o.jsx(qAe,{hierarchicalSpans:i,onSpanClick:u,selectedSpanId:a??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}function K0s(){const[e,t]=za(),n=G0s(e,t),r=q0s(e,t),[s,a]=g.useState(),[i,l]=g.useState(!1),{data:c=[],isPending:u}=dRe(),{data:d=[],isPending:f}=lRe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:h=[],isPending:p}=cRe(),{data:m=[],isPending:v}=uRe(),y=g.useMemo(()=>$0s({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:h,loading:{tags:u,entityNames:f,serviceNames:v,environments:p}}),[c,d,m,h,u,f,v,p]),b=g.useMemo(()=>F0s({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:x=[],isLoading:w,error:k,isFetchingNextPage:C,hasNextPage:_,setEndOfListElement:T}=j0s({filters:b}),{logIdMap:E,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:P}=W0s(x,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:L,isLoading:D}=VL(n.featuredTraceId??null),{data:B,isLoading:H}=BQ(n.featuredTraceId??"",n.featuredSpanId??""),q=g.useCallback(()=>n.applyFilterTokens(z0s(y,n.filterTokens)),[y,n]),z=g.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),V=g.useCallback(Y=>n.handleFeaturedChange({traceId:Y,spanId:null}),[n]),M=g.useCallback((Y,te)=>n.handleFeaturedChange({traceId:Y,spanId:te}),[n]),G=g.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),F=g.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),R=g.useCallback(Y=>n.handleFeaturedChange({spanId:Y??null}),[n]),U=o.jsxs(Lt.TopArea,{children:[o.jsx(Lt.Row,{children:o.jsxs(Lt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(q4,{preset:n.datePreset,onPresetChange:n.handleDatePresetChange,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,onDateChange:n.handleDateChange,disabled:w,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),o.jsx(aRe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:w,onStartTextFilter:a})]})}),o.jsx(b0s,{isLoading:w,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:q,onRemoveAll:n.handleRemoveAll,onSave:r.handleSave,onRemoveSaved:r.hasSavedFilters?r.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(k)return o.jsxs(Lt,{width:"wide",height:"full",children:[U,o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(l0s,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const Z=!!n.selectedEntityOption||n.filterTokens.length>0;return x.length===0&&!w&&!Z?o.jsxs(Lt,{width:"wide",height:"full",children:[U,o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(k0s,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Lt,{width:"wide",height:"full",children:[U,o.jsx(c0s,{logCollapsed:i,listSlot:o.jsx(y0s,{logs:x,isLoading:w,isFetchingNextPage:C,hasNextPage:_,setEndOfListElement:T,logIdMap:E,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(o0s,{log:N,onClose:z,onTraceClick:V,onSpanClick:M,onPrevious:A,onNext:P,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(Y0s,{traceId:n.featuredTraceId,spans:L?.spans,isLoading:D,onClose:G,onSpanSelect:R,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(Q0s,{spanId:n.featuredSpanId,span:B?.span,isLoading:H,onClose:F}):null})]})}function X0s({server:e,rowProps:t}){const{paths:n,Link:r}=dn(),a=Ye().options.baseUrl,i=a?`${a}/api/mcp/${e.id}/sse`:"",{data:l}=iUt(e),c=Object.values(l||{}),u=c.length,d=c.filter(p=>p.toolType==="agent").length,f=c.filter(p=>p.toolType==="workflow").length,h=Dh(e.name,50);return o.jsxs(pe.RowLink,{to:n.mcpServerLink(e.id),LinkComponent:r,...t,children:[o.jsx(pe.NameCell,{children:h}),o.jsx(pe.DescriptionCell,{children:i}),o.jsx(pe.TextCell,{className:"text-center",children:d||""}),o.jsx(pe.TextCell,{className:"text-center",children:u||""}),o.jsx(pe.TextCell,{className:"text-center",children:f||""})]})}function J0s({mcpServers:e,isLoading:t,search:n=""}){const r=g.useMemo(()=>{const i=n.toLowerCase();return e.filter(l=>l.name?.toLowerCase().includes(i)||l.id?.toLowerCase().includes(i))},[e,n]),{containerRef:s,getRowProps:a}=ao({count:r.length});return t?o.jsx(Bo,{columns:"auto 1fr auto auto auto"}):o.jsxs(pe,{columns:"auto 1fr auto auto auto",scrollRef:s,children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{children:"Name"}),o.jsx(pe.TopCell,{children:"URL"}),o.jsx(pe.TopCellSmart,{long:"Agents",short:o.jsx(Ri,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(pe.TopCellSmart,{long:"Tools",short:o.jsx(Bf,{}),tooltip:"Tools",className:"text-center"}),o.jsx(pe.TopCellSmart,{long:"Workflows",short:o.jsx(Bc,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(pe.NoMatch,{message:"No MCP Servers match your search"}):null,r.map((i,l)=>o.jsx(X0s,{server:i,rowProps:a(l)},i.id))]})}const ews=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx(Mc,{}),titleSlot:"No MCP Servers yet",descriptionSlot:o.jsxs(o.Fragment,{children:["MCP servers are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsxs(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(ta,{})]})})}),tws=()=>{const{data:e=[],isLoading:t,error:n}=NQ(),[r,s]=g.useState("");return n&&hs(n)?o.jsx(Zn,{children:o.jsx(Ts,{})}):n&&ps(n)?o.jsx(Zn,{children:o.jsx(ks,{resource:"MCP servers"})}):n?o.jsx(Zn,{children:o.jsx(La,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(Zn,{children:o.jsx(ews,{})}):o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx(cd,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(J0s,{mcpServers:e,isLoading:t,search:r})]})},nws=(e,t)=>{const n=new Map,r=Object.keys(t);for(const s of r){const a=t[s],i=a.tools,l=Object.keys(i);for(const c of l){const u=i[c];n.has(u.id)||n.set(u.id,{...u,agents:[]}),n.get(u.id).agents.push({...a,id:s})}}for(const[s,a]of Object.entries(e))n.has(a.id)||n.set(a.id,{...a,agents:[]});return Array.from(n.values())};function rws({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=dn(),i=g.useMemo(()=>nws(e,t),[e,t]),l=g.useMemo(()=>i.filter(d=>d.id.toLowerCase().includes(r.toLowerCase())),[i,r]),{containerRef:c,getRowProps:u}=ao({count:l.length});return n?o.jsx(Bo,{columns:"auto 1fr auto"}):o.jsxs(pe,{columns:"auto 1fr auto",scrollRef:c,children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{children:"Name"}),o.jsx(pe.TopCell,{children:"Description"}),o.jsx(pe.TopCellSmart,{long:"Agents",short:o.jsx(Ri,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(pe.NoMatch,{message:"No Tools match your search"}):null,l.map((d,f)=>{const h=Dh(d.id,50),p=Dh(d.description??"",200),m=d.agents.length;return o.jsxs(pe.RowLink,{to:s.toolLink(d.id),LinkComponent:a,...u(f),children:[o.jsx(pe.NameCell,{children:h}),o.jsx(pe.DescriptionCell,{children:p}),o.jsx(pe.TextCell,{className:"text-center",children:m||""})]},d.id)})]})}const sws=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx(Mc,{}),titleSlot:"No Tools yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Mastra tools are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsxs(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(ta,{})]})})}),aws=()=>{const e=Ye();return Sn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new zC;Object.entries(r??{}).forEach(([a,i])=>{s.set(a,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(a){throw Ve.error("Error executing dev tool"),console.error("Error executing dev tool:",a),a}}})},iws=({toolId:e})=>{const{canExecute:t}=Eo(),n=t("tools"),{data:r={}}=Bm(),s=g.useMemo(()=>{for(const v of Object.values(r))if(v.tools){const y=Object.values(v.tools).find(b=>b.id===e);if(y)return y}return null},[r,e]),{data:a,isLoading:i,error:l}=s2r(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=aws(),{requestContext:h}=ys();g.useEffect(()=>{if(l){const v=l instanceof Error?l.message:"Failed to load tool";Ve.error(`Error loading tool: ${v}`)}},[l]);const p=async(v,y)=>{if(!c)return;const b={...h??{},...y??{}};return u({toolId:c.id,input:v,requestContext:b})},m=c?.inputSchema?xm(Ix(c?.inputSchema)):ws({});return i?o.jsxs("div",{className:"p-6",children:[o.jsx(Et,{className:"mb-4 h-8 w-48"}),o.jsx(Et,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(vAe,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:p,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ve,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ve,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function ows({value:e,onValueChange:t,placeholder:n="Select a tool...",searchPlaceholder:r="Search tools...",emptyText:s="No tools found.",className:a,disabled:i=!1,variant:l,size:c}){const{data:u={},isLoading:d,isError:f,error:h}=nA(),{data:p={},isLoading:m,isError:v,error:y}=Bm(),{navigate:b,paths:x}=dn();g.useEffect(()=>{if(f){const _=h instanceof Error?h.message:"Failed to load tools";Ve.error(`Error loading tools: ${_}`)}},[f,h]),g.useEffect(()=>{if(v){const _=y instanceof Error?y.message:"Failed to load agents";Ve.error(`Error loading agents: ${_}`)}},[v,y]);const w=new Map;Object.values(p).forEach(_=>{_.tools&&Object.values(_.tools).forEach(T=>{w.has(T.id)||w.set(T.id,T)})}),Object.values(u).forEach(_=>{w.has(_.id)||w.set(_.id,_)});const k=Array.from(w.values()).map(_=>({label:_.id,value:_.id})),C=_=>{t?t(_):_&&_!==e&&b(x.toolLink(_))};return o.jsx(vl,{options:k,value:e,onValueChange:C,placeholder:d||m?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||d||m||f||v,variant:l,size:c})}const lws=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=g.useState({sseUrl:"",httpStreamUrl:""});if(g.useEffect(()=>{if(!t)return;const i=window.MASTRA_SERVER_HOST,l=window.MASTRA_SERVER_PORT;let c=null;i&&l&&(c=`http://${i}:${l}`);const u=c||"http://localhost:4111",d=`${u}/api/mcp/${t.id}/sse`,f=`${u}/api/mcp/${t.id}/mcp`;s({sseUrl:d,httpStreamUrl:f})},[t]),e)return null;if(!t)return o.jsx(by,{children:o.jsx(ve,{as:"h1",variant:"header-md",className:"text-neutral3 py-20 text-center font-medium",children:"Server not found"})});const a=`npx -y mcp-remote ${n}`;return o.jsxs(by,{isDivided:!0,children:[o.jsxs("div",{className:"mx-auto w-full max-w-2xl px-8 py-12",children:[o.jsx(ve,{as:"h1",variant:"header-md",className:"text-neutral6 pb-4 font-medium",children:t.name}),o.jsxs("div",{className:"flex items-center gap-1 pb-6",children:[o.jsx(bt,{icon:o.jsx(rVt,{}),size:"sm",children:"Version"}),o.jsx(bt,{size:"sm",children:t.version_detail.version})]}),o.jsx(ve,{className:"text-neutral3 pb-4",children:"This MCP server can be accessed through multiple transport methods. Choose the one that best fits your use case."}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(bt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"HTTP"}),children:"Regular HTTP Endpoint"}),o.jsx(ve,{className:"text-neutral3 pt-1 pb-2",children:"Use for stateless HTTP transport with streamable responses."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ve,{className:"bg-surface4 rounded-lg px-2 py-1",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx(_a,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(bt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"SSE"}),children:"Server-Sent Events"}),o.jsx(ve,{className:"text-neutral3 pt-1 pb-2",children:"Use for real-time communication via SSE."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ve,{className:"bg-surface4 rounded-lg px-2 py-1",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx(_a,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(bt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"CLI"}),children:"Command Line"}),o.jsx(ve,{className:"text-neutral3 pt-1 pb-2",children:"Use for local command-line access via npx and mcp-remote."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ve,{className:"bg-surface4 rounded-lg px-2 py-1",children:a}),o.jsx("div",{className:"pt-1",children:o.jsx(_a,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"border-border1 h-full overflow-y-scroll border-l",children:o.jsx(cws,{server:t})})]})},cws=({server:e})=>{const{data:t={},isLoading:n}=iUt(e);if(n)return null;const r=Object.keys(t);return o.jsxs("div",{className:"overflow-y-scroll p-5",children:[o.jsxs("div",{className:"text-neutral6 flex items-center gap-2",children:[o.jsx(Qe,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(N_,{})}),o.jsx(ve,{variant:"header-md",as:"h2",className:"font-medium",children:"Available Tools"})]}),o.jsx("div",{className:"flex flex-col gap-2 pt-6",children:r.map(s=>{const a=t[s];return o.jsx(dws,{tool:a,serverId:e.id},s)})})]})};function uws(e){if(!e)return!1;const t=e.ui;return!!(typeof t?.resourceUri=="string"&&t.resourceUri.startsWith("ui://")||typeof e["ui/resourceUri"]=="string"&&e["ui/resourceUri"].startsWith("ui://"))}const dws=({tool:e,serverId:t})=>{const n=g.useRef(null),{Link:r,paths:s}=dn(),a=hUt[e.toolType||"tool"],i=uws(e._meta);return o.jsxs(Wf,{onClick:()=>n.current?.click(),children:[o.jsx(e4t,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Gf,{children:[o.jsx(Zf,{children:o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(r,{ref:n,href:s.mcpServerToolLink(t,e.id),children:e.id}),i&&o.jsx(bt,{size:"xs",children:"App"})]})}),o.jsx(cp,{children:e.description})]})]})},fws=()=>{const{serverId:e}=fr(),{data:t=[],isLoading:n}=NQ(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(lws,{isLoading:n,server:r})})};function hws(e){if(!e)return;const t=e.ui;if(t?.resourceUri)return t.resourceUri;const n=e["ui/resourceUri"];if(typeof n=="string")return n}const pws=({toolId:e,serverId:t})=>{const{canExecute:n}=Eo(),r=n("tools"),s=Ye(),{data:a,isLoading:i,error:l}=pAe(t,e),{mutateAsync:c,isPending:u,data:d}=yis(t,e),f=a?hws(a._meta):void 0,{data:h}=mt({queryKey:["mcp-app-resource",t,f],queryFn:async()=>f?(await s.readMcpServerResource(t,f)).contents[0]?.text??null:null,enabled:!!f}),p=g.useCallback(async(y,b)=>await c(b),[c]);g.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";Ve.error(`Error loading tool: ${y}`)}},[l]);const m=async y=>{if(a)return await c(y)};if(i)return o.jsxs("div",{className:"p-6",children:[o.jsx(Et,{className:"mb-4 h-8 w-48"}),o.jsx(Et,{className:"h-32 w-full"})]});if(l)return null;if(!a)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ve,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ve,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let v;try{v=xm(a.inputSchema)}catch(y){console.error("Error processing input schema:",y),Ve.error("Failed to process tool input schema."),v=ws({})}return o.jsxs("div",{className:"flex flex-col gap-4",children:[h&&o.jsx("div",{className:"border-border1 border-b p-4",children:o.jsx(aUt,{html:h,toolName:a.name??a.id,onToolCall:p})}),o.jsx(vAe,{executionResult:d,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},mws=()=>{const{serverId:e,toolId:t}=fr(),{data:n,isLoading:r}=pAe(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(pws,{toolId:t,serverId:e})})},HHt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],XN="rootEntityType",JN={tags:"filterTags",entityId:"filterEntityId",entityName:"filterEntityName",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId",provider:"filterProvider",model:"filterModel"},hY=Object.keys(JN),wRe="mastra:metrics:saved-filters";function gws(e){const t=wws(e);try{localStorage.setItem(wRe,t.toString())}catch{}}function vws(){try{localStorage.removeItem(wRe)}catch{}}function WHt(){try{const e=localStorage.getItem(wRe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function yws(e){if(e.has(XN))return!0;for(const t of hY)if(e.has(JN[t]))return!0;return!1}function bws({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:HHt.map(u=>({label:u.label,value:u.entityType})),placeholder:"Choose entity type",emptyText:"No entity types."},{id:"entityName",label:"Primitive Name",kind:"pick-multi",options:t.map(u=>({label:u,value:u})),placeholder:"Choose entity names",emptyText:"No entity names found.",isLoading:s?.entityNames},{id:"entityId",label:"Primitive ID",kind:"text"},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"threadId",label:"Thread ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function xws(e){const t=[],n=new Map([[XN,"rootEntityType"]]);for(const s of hY)n.set(JN[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),a==="tags"){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}if(a==="rootEntityType"||a==="entityName"||a==="serviceName"||a==="environment"||a==="provider"||a==="model"){const l=e.getAll(s);if(l.length>1){t.push({fieldId:a,value:l});continue}}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function wws(e){const t=new URLSearchParams,n=e.getAll(XN);for(const r of n)t.append(XN,r);for(const r of hY){const s=JN[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function Sws(e,t){e.delete(XN);for(const n of hY)e.delete(JN[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?XN:JN[n.fieldId];if(r)if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string"&&a!=="");if(s.length===0){n.fieldId==="tags"&&e.append(r,"");continue}for(const a of s)e.append(r,a)}else typeof n.value=="string"&&e.set(r,n.value.trim())}}const kws="Any";function Ztt(e){const t=e.trim();return t===""||t===kws}const Ows=new Set(HHt.map(e=>e.entityType));function Gtt(e){const t=e.trim();return Ows.has(t)?t:void 0}function Cws(e){const t={};for(const n of e){const r=n.fieldId;if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string").map(a=>a.trim()).filter(a=>!Ztt(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?Gtt(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(Ztt(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=Gtt(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const ZHt=[{label:"Last 24 hours",value:"24h"},{label:"Last 3 days",value:"3d"},{label:"Last 7 days",value:"7d"},{label:"Last 14 days",value:"14d"},{label:"Last 30 days",value:"30d"}],_ws=new Set(ZHt.map(e=>e.value));function Ews(e){return typeof e=="string"&&(_ws.has(e)||e==="custom")}const GHt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function pY(){return g.useContext(GHt)}function Tws(e,t){return e!=="custom"?ZHt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${dr(t.from,"MMM d, yyyy")} – ${dr(t.to,"MMM d, yyyy")}`:dr(t.from,"MMM d, yyyy"):"Custom range"}function jws({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:a,onCustomRangeChange:i,tracesBasePath:l,logsBasePath:c}){const u=g.useMemo(()=>JSON.stringify(n),[n]),d=g.useMemo(()=>n,[u]),f=g.useMemo(()=>Cws(d),[d]),h=g.useMemo(()=>JSON.stringify(f),[f]),p=Tws(t,a),m=g.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:a,setCustomRange:i??(()=>{}),dateRangeLabel:p,filterTokens:d,setFilterTokens:s,dimensionalFilter:f,dimensionalFilterKey:h,tracesBasePath:l,logsBasePath:c}),[t,r,a,i,p,d,s,f,h,l,c]);return o.jsx(GHt.Provider,{value:m,children:e})}const Nws=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function Iws(e){switch(e){case"3d":return"last-3d";case"7d":return"last-7d";case"14d":return"last-14d";case"30d":return"last-30d";case"custom":return"custom";default:return"last-24h"}}function Aws(e){switch(e){case"last-3d":return"3d";case"last-7d":return"7d";case"last-14d":return"14d";case"last-30d":return"30d";case"custom":return"custom";default:return"24h"}}function Rws(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=pY(),s=g.useRef(e);s.current=e;const a=g.useRef(n);return a.current=n,o.jsx(q4,{preset:Iws(e),onPresetChange:i=>{const l=Aws(i);s.current=l,t(l)},dateFrom:n?.from,dateTo:n?.to,onDateChange:(i,l)=>{if(s.current!=="custom")return;const c={...a.current,[l]:i};a.current=c,r(c)},presets:Nws})}const f0e=1440*60*1e3,Pws={"24h":f0e,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function $ws(e,t,n){if(e!=="custom"){const r=Pws[e]??f0e;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-f0e),end:t?.to??new Date(n)}}function Hm(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=pY(),s=g.useRef(null),a=e==="custom"?`custom:${t?.from?.getTime()??""}:${t?.to?.getTime()??""}`:`preset:${e}`;(!s.current||s.current.key!==a)&&(s.current={key:a,anchor:Date.now()});const i=s.current.anchor,l=g.useMemo(()=>$ws(e,t,i),[e,t,i]),c=g.useMemo(()=>({timestamp:l,...n}),[l,r]),u=g.useMemo(()=>`${a}|${r}`,[a,r]);return{datePreset:e,customRange:t,timestamp:l,filters:c,dimensionalFilter:n,filterKey:u}}function QHt(){const e=Ye(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function XL({href:e,LinkComponent:t="a"}){return o.jsx(ie,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(ac,{})})}function Mws({href:e,LinkComponent:t="a"}){return o.jsx(ie,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(nJt,{})})}function Dws(e){return e==="agents"||e==="workflows"||e==="tools"}function Qtt(e,t){if(e.length===0)return"0";const n=e.reduce((r,s)=>{const a=s[t];return r+(typeof a=="number"&&Number.isFinite(a)?a:0)},0);return`${Math.round(n/e.length)}`}function Lws(e){const t=e;return typeof t?.tsMs=="number"&&Number.isFinite(t.tsMs)}const Fws=[{dataKey:"p50",label:"p50",color:Gh.blue,aggregate:e=>({value:Qtt(e,"p50"),suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:Gh.yellow,aggregate:e=>({value:Qtt(e,"p95"),suffix:"avg ms"})}];function ooe({data:e,onPointClick:t}){return e.length===0?o.jsx(Ht.NoData,{message:"No latency data yet"}):o.jsx(ID,{data:e,series:Fws,onPointClick:t?n=>Lws(n)?t(n):void 0:void 0})}function zws({data:e,isLoading:t,isError:n,onPointClick:r,actions:s}){const a=(e?.agentData.length??0)>0,i=(e?.workflowData.length??0)>0,l=(e?.toolData.length??0)>0,c={agents:a,workflows:i,tools:l},u=a?"agents":i?"workflows":l?"tools":"agents",[d,f]=g.useState("agents"),h=c[d]?d:u,p=typeof s=="function"?s(h):s,m=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),v=e?Object.values(e).filter(Array.isArray).flat().map(b=>b.p50).filter(b=>typeof b=="number"):[],y=v.length>0?`${Math.round(v.reduce((b,x)=>b+x,0)/v.length)}ms`:"—";return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(Ht.Summary,{value:y,label:"Avg p50"}),p?o.jsx(Ht.Actions,{children:p}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load latency data"}):o.jsx(Ht.Content,{children:m?o.jsxs(Zc,{value:h,onValueChange:b=>{Dws(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(Wc,{children:[o.jsx(Qr,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(Qr,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(Qr,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(_s,{value:"agents",children:o.jsx(ooe,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(_s,{value:"workflows",children:o.jsx(ooe,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(_s,{value:"tools",children:o.jsx(ooe,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Ht.NoData,{message:"No latency data yet"})})]})}function Bws(e){switch(e){case"24h":return"last-24h";case"3d":return"last-3d";case"7d":return"last-7d";case"14d":return"last-14d";case"30d":return"last-30d";case"custom":return"custom";default:return}}function Uws(e,t){if(t==="1h"){const s=new Date(e);s.setUTCMinutes(0,0,0);const a=new Date(s.getTime()+3600*1e3);return{from:s,to:a}}const n=new Date(e);n.setUTCHours(0,0,0,0);const r=new Date(n.getTime()+1440*60*1e3);return{from:n,to:r}}function YHt(e,t,n,r,s,a,i){if(i){e.set(t,"custom"),e.set(n,i.from.toISOString()),e.set(r,i.to.toISOString());return}if(s==="custom"){e.set(t,"custom"),a?.from&&e.set(n,a.from.toISOString()),a?.to&&e.set(r,a.to.toISOString());return}const l=Bws(s);l&&e.set(t,l)}function $o(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function KHt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function Ytt({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const a=new URLSearchParams;a.set(zw,"branches"),YHt(a,Bw,Uw,qw,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Yx,i),r.status&&a.set(Kx,r.status),$o(a,Tl.entityName,r.entityName??n.entityName),$o(a,Tl.threadId,r.threadId??n.threadId),$o(a,Tl.resourceId,r.resourceId??n.resourceId),$o(a,Tl.entityId,n.entityId),$o(a,Tl.runId,n.runId),$o(a,Tl.sessionId,n.sessionId),$o(a,Tl.requestId,n.requestId),$o(a,Tl.userId,n.userId),$o(a,Tl.organizationId,n.organizationId),$o(a,Tl.experimentId,n.experimentId),$o(a,Tl.serviceName,n.serviceName),$o(a,Tl.environment,n.environment),KHt(a,Tl.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function qws({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;YHt(a,rx,sx,ax,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Xx,i),$o(a,jl.entityName,r.entityName??n.entityName),$o(a,jl.threadId,r.threadId??n.threadId),$o(a,jl.resourceId,r.resourceId??n.resourceId),$o(a,jl.runId,n.runId),$o(a,jl.sessionId,n.sessionId),$o(a,jl.requestId,n.requestId),$o(a,jl.userId,n.userId),$o(a,jl.organizationId,n.organizationId),$o(a,jl.experimentId,n.experimentId),$o(a,jl.serviceName,n.serviceName),$o(a,jl.environment,n.environment),KHt(a,jl.tags,n.tags),r.status==="error"&&a.append(jl.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function xA(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=pY(),a=g.useCallback((c={})=>Ytt({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=g.useCallback((c={})=>qws({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=Uws(u,d);return Ytt({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const XHt="1h";async function loe(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:XHt,filters:n}),s=r.series.find(l=>l.percentile===.5),a=r.series.find(l=>l.percentile===.95);if(!s||!a)return[];const i=new Map(a.points.map(l=>[new Date(l.timestamp).getTime(),l.value]));return s.points.map(l=>{const c=new Date(l.timestamp),u=c.getTime();return{time:c.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}),tsMs:u,p50:Math.round(l.value),p95:Math.round(i.get(u)??0)}})}function Vws(){const e=Ye(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([loe(e,"mastra_agent_duration_ms",t),loe(e,"mastra_workflow_duration_ms",t),loe(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:XHt}}})}const Ktt={agents:Xu.AGENT,workflows:Xu.WORKFLOW_RUN,tools:Xu.TOOL};function Hws(){const{data:e,isLoading:t,isError:n}=Vws(),{getTracesHref:r,getBucketTracesHref:s}=xA(),{Link:a}=dn(),i=qr();return o.jsx(zws,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:Ktt[l]},c.tsMs,"1h"))},actions:l=>o.jsx(XL,{href:r({rootEntityType:Ktt[l]}),LinkComponent:a})})}function Wws(e){return e==="threads"||e==="resources"}function coe(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function Zws({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("threads"),c=e.data?.map(y=>({...y,key:y.threadId}))??[],u=t.data?.map(y=>({...y,key:y.resourceId}))??[],d=c.length>0,f=u.length>0,h=e.data?.reduce((y,b)=>y+b.runs,0)??0,p=t.data?.reduce((y,b)=>y+b.threadCount,0)??0,m=i==="threads"?e:t,v=typeof s=="function"?s(i):s;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&o.jsx(Ht.Summary,{value:h.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&o.jsx(Ht.Summary,{value:p.toLocaleString(),label:"Total threads"}),v?o.jsx(Ht.Actions,{children:v}):null]}),m.isLoading?o.jsx(Ht.Loading,{}):m.isError?o.jsx(Ht.Error,{message:"Failed to load memory data"}):o.jsx(Ht.Content,{children:o.jsxs(Zc,{defaultTab:"threads",value:i,onValueChange:y=>{Wws(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Wc,{children:[o.jsx(Qr,{value:"threads",children:"Threads"}),o.jsx(Qr,{value:"resources",children:"Resources"})]}),o.jsx(_s,{value:"threads",children:d?o.jsxs(pe,{columns:"auto auto auto auto auto",...Jxe,children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(pe.RowHeaderCell,{className:"text-ui-sm",children:coe(y.threadId)}),o.jsx(pe.NumberCell,{children:y.resourceId?coe(y.resourceId):"—"}),o.jsx(pe.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(pe.NumberCell,{children:y.tokens>0?il(y.tokens):"—"}),o.jsx(pe.NumberCell,{children:y.cost!=null?Zh(y.cost,y.costUnit):"—"})]});return b?o.jsx(pe.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(pe.RowStatic,{children:x},y.key)})]}):o.jsx(Ht.NoData,{message:"No thread activity yet"})}),o.jsx(_s,{value:"resources",children:f?o.jsxs(pe,{columns:"auto auto auto auto",...Jxe,children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(pe.RowHeaderCell,{className:"text-ui-sm",children:coe(y.resourceId)}),o.jsx(pe.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(pe.NumberCell,{children:y.tokens>0?il(y.tokens):"—"}),o.jsx(pe.NumberCell,{children:y.cost!=null?Zh(y.cost,y.costUnit):"—"})]});return b?o.jsx(pe.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(pe.RowStatic,{children:x},y.key)})]}):o.jsx(Ht.NoData,{message:"No resource activity yet"})})]})})]})}const uoe=20;function Gws(){const e=Ye(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","top-active-threads",n],queryFn:async()=>{const r={groupBy:["threadId","resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count",limit:uoe}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:uoe}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:uoe})]),l=new Map,c=d=>bA(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const h=f.dimensions.threadId;if(!h)continue;const p=c(h);p.tokens+=f.value,f.estimatedCost!=null&&(p.cost=(p.cost??0)+f.estimatedCost,f.costUnit&&(p.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.threadId).map(d=>{const f=d.dimensions.threadId,h=l.get(f);return{threadId:f,resourceId:d.dimensions.resourceId??null,runs:d.value,tokens:h?.tokens??0,cost:h?.cost??null,costUnit:h?.costUnit??null}})}})}const doe=20;function Qws(){const e=Ye(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","top-resources-by-threads",n],queryFn:async()=>{const r={groupBy:["resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",limit:doe}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:doe}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:doe})]),l=new Map,c=d=>bA(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const h=f.dimensions.resourceId;if(!h)continue;const p=c(h);p.tokens+=f.value,f.estimatedCost!=null&&(p.cost=(p.cost??0)+f.estimatedCost,f.costUnit&&(p.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.resourceId).map(d=>{const f=d.dimensions.resourceId,h=l.get(f);return{resourceId:f,threadCount:d.value,tokens:h?.tokens??0,cost:h?.cost??null,costUnit:h?.costUnit??null}})}})}function Yws(){const e=Gws(),t=Qws(),{getTracesHref:n}=xA(),{Link:r}=dn();return o.jsx(Zws,{threads:{data:e.data,isLoading:e.isLoading,isError:e.isError},resources:{data:t.data,isLoading:t.isLoading,isError:t.isError},LinkComponent:r,getThreadRowHref:s=>n({threadId:s.threadId,...s.resourceId?{resourceId:s.resourceId}:{}}),getResourceRowHref:s=>n({resourceId:s.resourceId})})}function JL({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:a}){const i=t!=null;return o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:e}),o.jsx(Xr.Value,{className:i?void 0:"invisible",children:i?t:"—"}),a?o.jsx(Xr.Error,{}):s?o.jsx(Xr.Loading,{}):i?r!=null?o.jsx(Xr.Change,{changePct:r,prevValue:n}):o.jsx(Xr.NoChange,{}):o.jsx(Xr.NoData,{})]})}function Kws(){const e=Ye(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","active-resources-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"resourceId",filters:t,comparePeriod:"previous_period"})})}function Xws(){const e=Ye(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","active-threads-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",filters:t,comparePeriod:"previous_period"})})}function Jws(){const e=Ye(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","model-cost-kpi",n],queryFn:async()=>{const r=await e.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"});return{cost:r.estimatedCost??null,costUnit:r.costUnit??null,previousCost:r.previousEstimatedCost??null,costChangePercent:r.costChangePercent??null}}})}function e1s(){const e=Ye(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","total-tokens-kpi",n],queryFn:async()=>{const[r,s]=await Promise.all([e.getMetricAggregate({name:["mastra_model_total_input_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"}),e.getMetricAggregate({name:["mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"})]),a=r.value!=null||s.value!=null,i=r.previousValue!=null||s.previousValue!=null,l=(r.value??0)+(s.value??0),c=(r.previousValue??0)+(s.previousValue??0),u=i&&c>0?(l-c)/c*100:null;return{value:a?l:null,previousValue:i?c:null,changePercent:u}}})}function t1s(){const{data:e,isLoading:t,isError:n}=QHt();return o.jsx(JL,{label:"Total Agent Runs",value:e?.value!=null?e.value.toLocaleString():null,prevValue:e?.previousValue!=null?e.previousValue.toLocaleString():void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function n1s(){const{data:e,isLoading:t,isError:n}=Jws();return o.jsx(JL,{label:"Total Model Cost",value:e?.cost!=null?Zh(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?Zh(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function r1s(){const{data:e,isLoading:t,isError:n}=e1s();return o.jsx(JL,{label:"Total Tokens",value:e?.value!=null?il(e.value):null,prevValue:e?.previousValue!=null?il(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function s1s(){const{data:e,isLoading:t,isError:n}=Xws();return o.jsx(JL,{label:"Total Threads",value:e?.value!=null?il(e.value):null,prevValue:e?.previousValue!=null?il(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function a1s(){const{data:e,isLoading:t,isError:n}=Kws();return o.jsx(JL,{label:"Total Resources",value:e?.value!=null?il(e.value):null,prevValue:e?.previousValue!=null?il(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function i1s({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>o1s(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(sRe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(nRe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function o1s(e,t){const n=t.find(r=>r.id===e.fieldId);return n?n.kind==="text"?typeof e.value=="string"&&e.value.trim()!=="":n.kind==="pick-multi"?n.multi?Array.isArray(e.value)&&e.value.length>0:typeof e.value=="string"&&e.value!==""&&e.value!=="Any":n.kind==="multi-select"?Array.isArray(e.value)&&e.value.length>0:!1:!1}function l1s({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const i=!!e&&e.length>0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Model Usage & Cost",description:"Token consumption by model."}),i&&(()=>{const l=e.reduce((d,f)=>d+(f.cost??0),0),c=new Set;for(const d of e)d.cost!=null&&d.costUnit&&c.add(d.costUnit);let u;return c.size===0?u=l>0?Zh(l):"—":c.size===1?u=l>0?Zh(l,[...c][0]):"—":u="Mixed",o.jsx(Ht.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(Ht.Actions,{children:s}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load model usage data"}):o.jsx(Ht.Content,{children:i?o.jsxs(pe,{columns:"auto auto auto auto auto auto",...Jxe,children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{sticky:"start",children:"Model"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(pe.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(pe.RowHeaderCell,{className:"text-ui-sm",children:l.model}),o.jsx(pe.NumberCell,{children:l.input}),o.jsx(pe.NumberCell,{children:l.output}),o.jsx(pe.NumberCell,{children:l.cacheRead}),o.jsx(pe.NumberCell,{children:l.cacheWrite}),o.jsx(pe.NumberCell,{highlight:!0,children:l.cost!=null?Zh(l.cost,l.costUnit):"—"})]});return c?o.jsx(pe.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(pe.RowStatic,{children:u},l.model)})]}):o.jsx(Ht.NoData,{message:"No model usage data yet"})})]})}function c1s(){const e=Ye(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","model-usage-cost",n],queryFn:async()=>{const[r,s,a,i]=await Promise.all(["mastra_model_total_input_tokens","mastra_model_total_output_tokens","mastra_model_input_cache_read_tokens","mastra_model_input_cache_write_tokens"].map(d=>e.getMetricBreakdown({name:[d],groupBy:["model"],aggregation:"sum",orderDirection:"DESC",filters:t})));if(!r||!s||!a||!i)return[];const l=new Map,c=d=>bA(l,d,()=>({input:0,output:0,cacheRead:0,cacheWrite:0,cost:null,costUnit:null})),u=(d,f)=>{f.estimatedCost!=null&&(d.cost=(d.cost??0)+f.estimatedCost,f.costUnit&&(d.costUnit=f.costUnit))};for(const d of r.groups){const f=d.dimensions.model??"unknown",h=c(f);h.input=d.value,u(h,d)}for(const d of s.groups){const f=d.dimensions.model??"unknown",h=c(f);h.output=d.value,u(h,d)}for(const d of a.groups){const f=d.dimensions.model??"unknown",h=c(f);h.cacheRead=d.value}for(const d of i.groups){const f=d.dimensions.model??"unknown",h=c(f);h.cacheWrite=d.value}return Array.from(l.entries()).map(([d,f])=>({model:d,input:il(f.input),output:il(f.output),cacheRead:il(f.cacheRead),cacheWrite:il(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function u1s(){const{data:e,isLoading:t,isError:n}=c1s(),{getTracesHref:r}=xA(),{Link:s}=dn();return o.jsx(l1s,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:Xu.AGENT}),actions:o.jsx(XL,{href:r({rootEntityType:Xu.AGENT}),LinkComponent:s})})}function d1s(e){return e==="tokens"||e==="cost"}function f1s({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("tokens"),c=e??[],u=c.length>0,d=c.reduce((b,x)=>b+x.total,0),f=c.filter(b=>b.cost!=null&&b.cost>0),h=new Set(f.map(b=>b.costUnit??"usd")),p=h.size<=1,m=p?[...h][0]??"usd":null,v=p?f.reduce((b,x)=>b+(x.cost??0),0):0,y=p&&v>0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&y?o.jsx(Ht.Summary,{value:Zh(v,m),label:"Total cost"}):o.jsx(Ht.Summary,{value:il(d),label:"Total tokens"})),u&&s?o.jsx(Ht.Actions,{children:s}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load token usage data"}):o.jsx(Ht.Content,{children:u?o.jsxs(Zc,{defaultTab:"tokens",value:i,onValueChange:b=>{d1s(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Wc,{children:[o.jsx(Qr,{value:"tokens",children:"Tokens"}),o.jsx(Qr,{value:"cost",children:"Cost"})]}),o.jsx(_s,{value:"tokens",children:o.jsx(KN,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:Gh.blueDark},{label:"Output",color:Gh.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:il})}),o.jsx(_s,{value:"cost",children:y?o.jsx(KN,{LinkComponent:a,data:f.slice().sort((b,x)=>(x.cost??0)-(b.cost??0)).map(b=>({name:b.name,values:[b.cost],href:r?.(b)})),segments:[{label:"Cost",color:Gh.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>Zh(b,m)}):o.jsx(Ht.NoData,{message:"No cost data yet"})})]}):o.jsx(Ht.NoData,{message:"No token usage data yet"})})]})}function h1s(){const e=Ye(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","token-usage-by-agent",n],queryFn:async()=>{const r={groupBy:["entityName"],aggregation:"sum",orderDirection:"DESC",filters:t},[s,a]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"]}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"]})]),i=new Map,l=u=>bA(i,u,()=>({input:0,output:0,cost:null,costUnit:null})),c=(u,d)=>{d.estimatedCost!=null&&(u.cost=(u.cost??0)+d.estimatedCost,d.costUnit&&(u.costUnit=d.costUnit))};for(const u of s.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.input=u.value,c(f,u)}for(const u of a.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.output=u.value,c(f,u)}return Array.from(i.entries()).map(([u,d])=>({name:u,input:d.input,output:d.output,total:d.input+d.output,cost:d.cost,costUnit:d.costUnit})).sort((u,d)=>d.total-u.total)}})}function p1s(){const{data:e,isLoading:t,isError:n}=h1s(),{getTracesHref:r}=xA(),{Link:s}=dn();return o.jsx(f1s,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:Xu.AGENT,entityName:a.name}),actions:o.jsx(XL,{href:r({rootEntityType:Xu.AGENT}),LinkComponent:s})})}function h0e(e,t=il){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const m1s=[{dataKey:"input",label:"Input tokens",color:Gh.blue,aggregate:h0e("input")},{dataKey:"output",label:"Output tokens",color:Gh.yellow,aggregate:h0e("output")}];function g1s(e){return e==="tokens"||e==="cost"}function v1s({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[a,i]=g.useState("tokens"),l=e??[],c=l.map(k=>({...k})),u=l.length>0,d=l.reduce((k,C)=>k+C.total,0),f=l.filter(k=>k.cost!=null&&k.cost>0),h=f.map(k=>({...k})),p=new Set(f.map(k=>k.costUnit).filter(k=>!!k)),m=p.size===1&&f.every(k=>k.costUnit!=null),v=m?[...p][0]??null:null,y=m?f.reduce((k,C)=>k+(C.cost??0),0):0,b=m&&y>0,x=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",w=[{dataKey:"cost",label:"Cost",color:Gh.purple,aggregate:h0e("cost",k=>Zh(k,v))}];return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Token usage over time",description:x}),u&&(a==="cost"&&b?o.jsx(Ht.Summary,{value:Zh(y,v),label:"Total cost"}):o.jsx(Ht.Summary,{value:il(d),label:"Total tokens"})),u&&s?o.jsx(Ht.Actions,{children:s}):null]}),n?o.jsx(Ht.Loading,{}):r?o.jsx(Ht.Error,{message:"Failed to load token usage timeline"}):o.jsx(Ht.Content,{children:u?o.jsxs(Zc,{defaultTab:"tokens",value:a,onValueChange:k=>{g1s(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(Wc,{children:[o.jsx(Qr,{value:"tokens",children:"Tokens"}),o.jsx(Qr,{value:"cost",children:"Cost"})]}),o.jsx(_s,{value:"tokens",children:o.jsx(ID,{data:c,series:m1s})}),o.jsx(_s,{value:"cost",children:b?o.jsx(ID,{data:h,series:w}):o.jsx(Ht.NoData,{message:"No cost data yet"})})]}):o.jsx(Ht.NoData,{message:"No token usage data yet"})})]})}function y1s(e){return e==="24h"?"1h":"1d"}function b1s(e,t){return t==="1h"?e.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}):e.toLocaleDateString("en-US",{month:"short",day:"2-digit"})}function Xtt(e,t,n){for(const r of t?.points??[]){const s=new Date(r.timestamp).getTime();if(!Number.isFinite(s))continue;const a=e.get(s)??{tsMs:s,input:0,output:0,cost:null,costUnits:new Set,hasUnknownCostUnit:!1};a[n]+=r.value,r.estimatedCost!=null&&(a.cost=(a.cost??0)+r.estimatedCost,t?.costUnit?a.costUnits.add(t.costUnit):a.hasUnknownCostUnit=!0),e.set(s,a)}}function x1s(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function w1s(){const e=Ye(),{datePreset:t,filters:n,filterKey:r}=Hm(),s=y1s(t);return mt({queryKey:["metrics","token-usage-timeseries",r,s],queryFn:async()=>{const[a,i]=await Promise.all([e.getMetricTimeSeries({name:["mastra_model_total_input_tokens"],interval:s,aggregation:"sum",filters:n}),e.getMetricTimeSeries({name:["mastra_model_total_output_tokens"],interval:s,aggregation:"sum",filters:n})]),l=new Map;return Xtt(l,a.series[0],"input"),Xtt(l,i.series[0],"output"),{data:Array.from(l.values()).sort((u,d)=>u.tsMs-d.tsMs).map(u=>{const d=new Date(u.tsMs);return{time:b1s(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:x1s(u)}}),interval:s}}})}function S1s(){const{data:e,isLoading:t,isError:n}=w1s(),{getTracesHref:r}=xA(),{Link:s}=dn();return o.jsx(v1s,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(XL,{href:r(),LinkComponent:s})})}function foe({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(KN,{LinkComponent:r,data:e.map(s=>{const a=n?.(s),i=t?.(s);return a?{name:s.name,values:[s.completed,s.errors],hrefs:[i,a]}:{name:s.name,values:[s.completed,s.errors],href:i}}),segments:[{label:"Completed",color:Gh.blueDark},{label:"Errors",color:Gh.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:il})}function k1s({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:a,LinkComponent:i}){const[l,c]=g.useState("agents"),u=typeof a=="function"?a(l):a,d=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),f=e?[...e.agentData,...e.workflowData,...e.toolData].reduce((m,v)=>m+v.completed+v.errors,0):0,h=m=>r?v=>r(m,v):void 0,p=m=>s?v=>s(m,v):void 0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(Ht.Summary,{value:il(f),label:"Total runs"}),u?o.jsx(Ht.Actions,{children:u}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load trace volume data"}):o.jsx(Ht.Content,{children:d?o.jsxs(Zc,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Wc,{children:[o.jsx(Qr,{value:"agents",children:"Agents"}),o.jsx(Qr,{value:"workflows",children:"Workflows"}),o.jsx(Qr,{value:"tools",children:"Tools"})]}),o.jsx(_s,{value:"agents",children:e.agentData.length>0?o.jsx(foe,{data:e.agentData,rowHrefs:h("agents"),errorHrefs:p("agents"),LinkComponent:i}):o.jsx(Ht.NoData,{message:"No agent data yet"})}),o.jsx(_s,{value:"workflows",children:e.workflowData.length>0?o.jsx(foe,{data:e.workflowData,rowHrefs:h("workflows"),errorHrefs:p("workflows"),LinkComponent:i}):o.jsx(Ht.NoData,{message:"No workflow data yet"})}),o.jsx(_s,{value:"tools",children:e.toolData.length>0?o.jsx(foe,{data:e.toolData,rowHrefs:h("tools"),errorHrefs:p("tools"),LinkComponent:i}):o.jsx(Ht.NoData,{message:"No tool data yet"})})]}):o.jsx(Ht.NoData,{message:"No trace volume data yet"})})]})}async function hoe(e,t,n){const r=await e.getMetricBreakdown({name:[t],groupBy:["entityName","status"],aggregation:"count",orderDirection:"DESC",filters:n}),s=new Map;for(const a of r.groups){const i=a.dimensions.entityName??"unknown",l=a.dimensions.status??"ok",c=bA(s,i,()=>({completed:0,errors:0}));l==="error"?c.errors+=a.value:c.completed+=a.value}return Array.from(s.entries()).map(([a,i])=>({name:a,...i})).sort((a,i)=>i.completed+i.errors-(a.completed+a.errors))}function O1s(){const e=Ye(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([hoe(e,"mastra_agent_duration_ms",t),hoe(e,"mastra_workflow_duration_ms",t),hoe(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const d8={agents:Xu.AGENT,workflows:Xu.WORKFLOW_RUN,tools:Xu.TOOL};function C1s(){const{data:e,isLoading:t,isError:n}=O1s(),{getTracesHref:r,getLogsHref:s}=xA(),{Link:a}=dn();return o.jsx(k1s,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:d8[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:d8[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(XL,{href:r({rootEntityType:d8[i]}),LinkComponent:a}),o.jsx(Mws,{href:s({rootEntityType:d8[i],status:"error"}),LinkComponent:a})]})})}const poe="period",f8="dateFrom",h8="dateTo";function _1s(){const[e,t]=za(),n=e.get(poe),r=Ews(n)?n:"24h",s=g.useMemo(()=>{if(r!=="custom")return;const d=p=>{if(!p)return;const m=new Date(p);return Number.isNaN(m.getTime())?void 0:m},f=d(e.get(f8)),h=d(e.get(h8));if(!(!f&&!h))return{from:f,to:h}},[r,e.toString()]),a=g.useMemo(()=>xws(e),[e.toString()]),i=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d==="24h"?h.delete(poe):h.set(poe,d),d!=="custom"&&(h.delete(f8),h.delete(h8)),h},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d?.from?h.set(f8,d.from.toISOString()):h.delete(f8),d?.to?h.set(h8,d.to.toISOString()):h.delete(h8),h},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return Sws(h,d),h},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,yws(e)))return;const d=WHt();d&&t(f=>{const h=new URLSearchParams(f);for(const[p,m]of d)h.append(p,m);return h},{replace:!0})},[]),o.jsx(jws,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(E1s,{})})}function E1s(){const[e]=za(),{error:t,isLoading:n}=QHt(),{filterTokens:r,setFilterTokens:s}=pY(),[a,i]=g.useState(),{supportsMetrics:l,isInMemory:c,isLoading:u}=fHt(),{data:d,isLoading:f}=dRe(),{data:h,isLoading:p}=lRe(),{data:m,isLoading:v}=uRe(),{data:y,isLoading:b}=cRe(),x=g.useMemo(()=>bws({availableTags:d??[],availableEntityNames:h??[],availableServiceNames:m??[],availableEnvironments:y??[],loading:{tags:f,entityNames:p,serviceNames:v,environments:b}}),[d,h,m,y,f,p,v,b]),[w,k]=g.useState(()=>WHt()!==null),C=g.useCallback(()=>{gws(e),k(!0),Ve.success("Filters setting for Metrics saved")},[e]),_=g.useCallback(()=>{vws(),k(!1),Ve.success("Filters setting for Metrics cleared up")},[]),T=g.useCallback(()=>{s([])},[s]),E=g.useCallback(()=>{const N=r.map(I=>{const A=x.find(P=>P.id===I.fieldId);return A?A.kind==="text"?{fieldId:I.fieldId,value:""}:A.kind==="pick-multi"?A.multi?{fieldId:I.fieldId,value:[]}:{fieldId:I.fieldId,value:"Any"}:A.kind==="multi-select"?{fieldId:I.fieldId,value:[]}:I:I});s(N)},[x,r,s]);return t&&hs(t)?o.jsx(Zn,{children:o.jsx(Ts,{})}):t&&ps(t)?o.jsx(Zn,{children:o.jsx(ks,{resource:"metrics"})}):t?o.jsx(Zn,{children:o.jsx(La,{title:"Failed to load metrics",message:t.message})}):o.jsxs(Lt,{width:"wide",height:"full",children:[o.jsxs(Lt.TopArea,{children:[o.jsx(Lt.Row,{children:o.jsxs(Lt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(Rws,{}),o.jsx(aRe,{fields:x,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(i1s,{isLoading:n,filterFields:x,filterTokens:r,onFilterTokensChange:s,onClear:E,onRemoveAll:T,onSave:C,onRemoveSaved:w?_:void 0,autoFocusFilterFieldId:a})]}),u?null:l?o.jsxs("div",{className:"grid content-start gap-8 pb-10",children:[c&&o.jsx(Rn,{variant:"info",title:"Metrics are not persisted",children:o.jsx(Rn.Message,{children:"This project uses in-memory storage for observability. Metrics will be lost on every server restart. For persistent metrics, switch the observability storage to ClickHouse, DuckDB, Postgres v-next, or Spanner."})}),o.jsxs(o0e,{children:[o.jsx(t1s,{}),o.jsx(n1s,{}),o.jsx(r1s,{}),o.jsx(s1s,{}),o.jsx(a1s,{})]}),o.jsxs(o0e,{children:[o.jsx(u1s,{}),o.jsx(p1s,{}),o.jsx(S1s,{}),o.jsx(Yws,{}),o.jsx(C1s,{}),o.jsx(Hws,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx(Mc,{}),titleSlot:"Metrics are not available with your current storage",descriptionSlot:"Metrics require ClickHouse, DuckDB, Postgres v-next, Spanner, or in-memory storage for observability. Other relational databases (LibSQL, MSSQL) and document stores (MongoDB) do not support metrics collection. To enable metrics on an existing project, switch the observability storage in the Mastra configuration.",actionSlot:o.jsxs(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(ta,{})]})})})]})}const T1s=50;function j1s(){const{paths:e}=dn(),{isCmsAvailable:t}=kS(),[n,r]=g.useState(""),[s,a]=g.useState(0),{data:i,isLoading:l,error:c,isPlaceholderData:u}=vUt({page:s,perPage:T1s}),d=i?.promptBlocks??[],f=i?.hasMore??!1,h=g.useCallback(()=>{u||a(v=>v+1)},[u]),p=g.useCallback(()=>{u||a(v=>Math.max(0,v-1))},[u]),m=g.useCallback(v=>{r(v),a(0)},[]);return c&&hs(c)?o.jsx(Zn,{children:o.jsx(Ts,{})}):c&&ps(c)?o.jsx(Zn,{children:o.jsx(ks,{resource:"prompt blocks"})}):c?o.jsx(Zn,{children:o.jsx(La,{title:"Failed to load prompt blocks",message:c.message})}):d.length===0&&!l&&s===0?o.jsx(Zn,{children:o.jsx(kls,{})}):o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(cd,{onSearch:m,label:"Filter prompts",placeholder:"Filter by name or description"})}),t&&o.jsxs(ie,{as:Da,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(_r,{}),"Create Prompt"]})]})}),o.jsx(Sls,{promptBlocks:d,isLoading:l,search:n,currentPage:s,hasMore:f,onNextPage:h,onPrevPage:p})]})}function N1s(){return o.jsx(Lt,{width:"narrow",children:o.jsx(Lt.MainArea,{children:o.jsx(los,{children:o.jsx(Dxe,{})})})})}const I1s=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:SKt,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:Oct,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:ta,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:t3,href:"https://discord.gg/BTYqqHKUrf",external:!0},{title:"Share with your team",description:"Running Mastra Studio locally? Deploy to the cloud so your team can collaborate.",icon:Nct,href:"https://mastra.ai/cloud",external:!0},{title:"Talk to our Sales team",description:"Get a custom demo, discuss on-prem deployments, and how we can help you accelerate getting agents into production.",icon:Cct,href:"https://mastra.ai/contact?ref=studio",external:!0}];function A1s(){return o.jsx(Lt,{width:"narrow",children:o.jsx(Lt.MainArea,{children:o.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:I1s.map(e=>o.jsxs("a",{href:e.href,...e.external?{target:"_blank",rel:"noreferrer"}:{},className:"group border-border1 bg-surface2 hover:border-accent1 hover:bg-surface3 flex flex-col gap-3 rounded-lg border p-5 transition-colors",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsx(e.icon,{className:"text-icon3 group-hover:text-accent1 h-5 w-5 transition-colors"}),o.jsx("span",{className:"text-ui-md text-text1 font-medium",children:e.title}),e.external&&o.jsx(ta,{className:"text-icon3 ml-auto h-3.5 w-3.5 opacity-0 transition-opacity group-hover:opacity-100"})]}),o.jsx("p",{className:"text-ui-sm text-text3 leading-relaxed",children:e.description})]},e.href))})})})}function R1s(){const{data:e={},isLoading:t,error:n}=up(),[r,s]=g.useState(""),[a,i]=g.useState("all");if(n&&hs(n))return o.jsx(Zn,{children:o.jsx(Ts,{})});if(n&&ps(n))return o.jsx(Zn,{children:o.jsx(ks,{resource:"scorers"})});if(n)return o.jsx(Zn,{children:o.jsx(La,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(Zn,{children:o.jsx(pVr,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(gVr,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(hVr,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}function P1s(){const{scorerId:e}=fr(),[t,n]=za(),r=t.get("scoreId")??void 0,[s,a]=g.useState(r),[i,l]=g.useState(!1),c=qr(),[u,d]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:f,error:h}=Zqr(e),{data:p={},isLoading:m,error:v}=Bm(),{isLoading:y,error:b}=Xy(),{data:x=[],isLoading:w,error:k,isFetchingNextPage:C,hasNextPage:_,setEndOfListElement:T}=Wqr({scorerId:e,entityId:u?.value==="all"?void 0:u?.value,entityType:u?.type==="ALL"?void 0:u?.type}),E=g.useMemo(()=>f?.agentIds?.filter(R=>p[R]).map(R=>({value:R,label:p[R].name,type:"AGENT"}))||[],[f?.agentIds,p]),N=g.useMemo(()=>f?.workflowIds?.map(R=>({value:R,label:R,type:"WORKFLOW"}))||[],[f?.workflowIds]),I=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...E,...N],[E,N]),A=t.get("entity")??"all",P=I.find(R=>R.value===A);P&&P.value!==u?.value&&d(P),g.useEffect(()=>{if(h){const R=h instanceof Error?h.message:"Failed to load scorer";Ve.error(`Error loading scorer: ${R}`)}},[h]),g.useEffect(()=>{if(v){const R=v instanceof Error?v.message:"Failed to load agents";Ve.error(`Error loading agents: ${R}`)}},[v]),g.useEffect(()=>{if(b){const R=b instanceof Error?b.message:"Failed to load workflows";Ve.error(`Error loading workflows: ${R}`)}},[b]);const L=R=>{R?.value&&n(U=>{const Z=new URLSearchParams(U);return Z.set("entity",R.value),Z})};g.useEffect(()=>{const R=t.get("scoreId")??void 0;if(R===s)return;if(!R){a(void 0);return}x.find(Z=>Z.id===R)&&a(R)},[t,x]);const D=g.useCallback(R=>{a(R||void 0),n(U=>{const Z=new URLSearchParams(U);return R?Z.set("scoreId",R):Z.delete("scoreId"),Z})},[n]);if(!f)return null;const B=hs(h)||hs(v)||hs(b),H=h&&ps(h),q=!B&&!H&&(h||v||b),z=!w&&x.length===0,V=u?.value!=="all",M=f?.scorer?.source==="stored"?o.jsx(By,{owner:"scorer-detail",children:o.jsxs(ie,{variant:"default",as:Da,to:`/cms/scorers/${e}/edit`,size:"sm",children:[o.jsx(Yh,{})," Edit"]})}):null,G=e?o.jsx(cY,{open:i,onOpenChange:l,initialScorerIds:[e],onSuccess:R=>{c(`/experiments/${R}`)}}):null;if(B||H||q||z&&!V){const R=(h instanceof Error?h.message:void 0)??(v instanceof Error?v.message:void 0)??(b instanceof Error?b.message:void 0)??"An unexpected error occurred";return o.jsxs(Lt,{width:"wide",height:"full",className:"grid-rows-[1fr]",children:[M,o.jsx(Lt.MainArea,{isCentered:!0,children:B?o.jsx(Ts,{}):H?o.jsx(ks,{resource:"scorers"}):q?o.jsx(La,{title:"Failed to load scorer",message:R}):o.jsx(Lqr,{onRunExperiment:()=>l(!0)})}),G]})}return o.jsxs(Lt,{width:"wide",height:"full",children:[M,o.jsx(Lt.TopArea,{children:o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx(zqr,{selectedEntity:u,entityOptions:I,onEntityChange:L,onReset:()=>{n(R=>{const U=new URLSearchParams(R);return U.set("entity","all"),U})},isLoading:w||m||y}),o.jsxs(ie,{variant:"primary",onClick:()=>l(!0),children:[o.jsx(Dc,{}),"Run Experiment"]})]})}),o.jsx(Dqr,{scores:x,isLoading:w,selectedScoreId:s,isFetchingNextPage:C,hasNextPage:_,setEndOfListElement:T,onScoreClick:D,errorMsg:k?.message}),G]})}const $1s=uo("flex min-w-0 flex-col",{variants:{variant:{default:"gap-3 sm:flex-row sm:items-center sm:justify-between",factory:"gap-2 px-4 py-3 lg:flex-row lg:items-center lg:justify-between lg:gap-4"}},defaultVariants:{variant:"default"}}),M1s=uo("flex min-w-0 flex-col",{variants:{variant:{default:"",factory:"gap-0.5"}},defaultVariants:{variant:"default"}}),Jtt=uo("",{variants:{variant:{default:"text-sm font-medium",factory:"text-ui-md leading-ui-md text-neutral5"}},defaultVariants:{variant:"default"}}),D1s=uo("flex flex-col gap-0.5",{variants:{variant:{default:"text-sm text-neutral3",factory:"text-ui-sm text-neutral3"}},defaultVariants:{variant:"default"}});function L1s({label:e,description:t,htmlFor:n,variant:r,className:s,children:a}){return o.jsxs("div",{className:K($1s({variant:r}),s),"data-slot":"settings-row",children:[o.jsxs("div",{className:M1s({variant:r}),children:[n?o.jsx(Dt,{htmlFor:n,className:Jtt({variant:r}),children:e}):o.jsx("span",{className:Jtt({variant:r}),children:e}),t&&o.jsx("div",{className:D1s({variant:r}),children:t})]}),a]})}const JHt=[{value:"dark",label:"Dark",Icon:wJt},{value:"light",label:"Light",Icon:Hen},{value:"system",label:"System",Icon:Uct}],F1s=e=>JHt.some(t=>t.value===e);function z1s({option:e}){const{Icon:t}=e;return o.jsxs("span",{className:"inline-flex max-w-full min-w-0 items-center gap-2",children:[o.jsx(t,{"aria-hidden":"true",className:"h-4 w-4 shrink-0 opacity-70"}),o.jsx("span",{className:"min-w-0 truncate",children:e.label})]})}const B1s=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=PH(),{theme:r,setTheme:s}=a_();return o.jsx(Lt,{width:"narrow",children:o.jsxs(Lt.MainArea,{className:"mt-6 flex flex-col gap-5",children:[o.jsx(uxe,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(L1s,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(la,{value:r,onValueChange:a=>{F1s(a)&&s(a)},children:[o.jsx(ua,{id:"theme",className:"w-full sm:w-48",children:o.jsx(ca,{className:"inline-flex max-w-full min-w-0 items-center"})}),o.jsx(da,{children:JHt.map(a=>o.jsx(xr,{value:a.value,children:o.jsx(z1s,{option:a})},a.value))})]})})}),o.jsx(uxe,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(V4t,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function U1s(){const[e]=za(),t=qr(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(qHt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}function q1s(e){return e.replace(/\/$/,"").split("/").pop()}function mY({children:e,className:t}){return o.jsx("div",{className:K("border border-border1 rounded-lg mt-12 py-8 lg:min-h-[25rem] transition-height px-4 lg:px-12",t),children:e})}function V1s({templates:e,linkComponent:t,className:n,isLoading:r}){const s=t||"a";return r?o.jsx("div",{className:K("grid gap-y-4",n),children:Array.from({length:5}).map((a,i)=>o.jsx("div",{className:"bg-surface3 h-16 animate-pulse rounded-lg"},i))}):o.jsx("div",{className:K("grid gap-y-4",n),children:e.map(a=>{const i=a?.agents||a?.tools||a?.networks||a?.workflows||a?.mcp;return o.jsxs("article",{className:K("border border-border1 rounded-lg overflow-hidden w-full grid grid-cols-[1fr_auto] bg-surface3 transition-colors hover:bg-surface4"),children:[o.jsxs(s,{to:`/templates/${a.slug}`,className:K("grid [&:hover_p]:text-neutral5",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":a.imageURL}),children:[a.imageURL&&o.jsx("div",{className:K("overflow-hidden"),children:o.jsx("div",{className:"thumb transition-scale h-full w-full bg-cover duration-150",style:{backgroundImage:`url(${a.imageURL})`}})}),o.jsxs("div",{className:K("grid py-3 px-6 w-full gap-0.5","[&_svg]:w-[1em] [&_svg]:h-[1em] [&_svg]:text-neutral3"),children:[o.jsx("h2",{className:"text-ui-lg text-neutral5",children:a.title}),o.jsx("p",{className:"text-ui-md text-neutral4 transition-colors duration-500",children:a.description}),o.jsxs("div",{className:"text-neutral3 text-ui-md mt-3 hidden flex-wrap items-center gap-4 2xl:flex",children:[i&&o.jsxs("ul",{className:K("flex gap-4 text-ui-md text-neutral3 m-0 p-0 list-none","[&>li]:flex [&>li]:items-center [&>li]:gap-0.5 text-neutral4"),children:[a?.agents&&a.agents.length>0&&o.jsxs("li",{children:[o.jsx(Ri,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(Bf,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(Vct,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(fI,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(N_,{})," ",a.mcp.length]})]}),i&&a.supportedProviders&&o.jsx("small",{children:"|"}),o.jsx("div",{className:"text-neutral3 flex items-center gap-4",children:a.supportedProviders.map(l=>o.jsx("span",{className:"",children:l},l))})]})]})]}),o.jsx("a",{href:a.githubUrl,className:K("group items-center gap-2 text-ui-md ml-auto pr-4 hidden","lg:flex"),target:"_blank",rel:"noopener noreferrer",children:o.jsxs("span",{className:"bg-surface1 group-hover:bg-surface2 text-neutral3 group-hover:text-neutral5 flex items-center gap-2 rounded px-2 py-1 transition-colors",children:[o.jsx(hG,{})," ",q1s(a.githubUrl)]})})]},a.slug)})})}function H1s({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:s,onProviderChange:a,searchTerm:i,onSearchChange:l,onReset:c,className:u,isLoading:d}){return d?o.jsxs("div",{className:K("h-[6.5rem] flex items-center gap-8","[&>div]:bg-surface3 [&>div]:w-48 [&>div]:h-8 [&>div]:animate-pulse",u),children:[o.jsx("div",{})," ",o.jsx("div",{})," ",o.jsx("div",{})]}):o.jsxs("div",{className:K("flex flex-wrap mx-auto sticky top-0 gap-4 bg-surface2 py-8",u),children:[o.jsx(wC,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(Cm,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(Cm,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(ie,{onClick:c,children:["Reset ",o.jsx(or,{})]})]})}function W1s(){const{data:e,isLoading:t}=Mrr(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[a,i]=g.useState("all"),[l,c]=g.useState("all"),[u,d]=g.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(x=>{f.push({value:x,label:x})});const h=[{value:"all",label:"Any provider"}];(s||[]).forEach(x=>{h.push({value:x,label:x})});const p=(x,w)=>{w==="tag"?i(x):w==="provider"&&c(x)},m=x=>{d(x)},v=()=>{i("all"),c("all"),d("")},y=n.filter(x=>!(u&&!x.title.toLowerCase().includes(u)&&!x.description.toLowerCase().includes(u)||a!=="all"&&!x.tags.includes(a)||l!=="all"&&!x.supportedProviders.includes(l))),b=u||a!=="all"||l!=="all";return o.jsxs(vs,{children:[o.jsx(UH,{children:o.jsxs(ESe,{children:[o.jsx(Qe,{children:o.jsx(fy,{})}),"Templates"]})}),o.jsxs("div",{className:K("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(H1s,{selectedTag:a,onTagChange:x=>p(x,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:x=>p(x,"provider"),providerOptions:h,searchTerm:u,onSearchChange:m,onReset:b?v:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(V1s,{templates:y,linkComponent:Da,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const Z1s="1.65.0-alpha.7";function G1s({errorMsg:e,validationErrors:t}){const n=typeof e=="string"?e:e!=null?String(e):void 0,r=n?.includes("Invalid schema for function"),s=n?.includes("validation issue")||t&&t.length>0,a=()=>s?"Template installation completed but some validation issues remain. The template may still be functional, but you should review and fix these issues.":r?"There was an issue with the AI model configuration. This may be related to the selected model or AI SDK version compatibility.":"An unexpected error occurred during template installation.",i=()=>s?{icon:o.jsx(uc,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(MKt,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(mY,{className:"text-neutral3 mb-8 content-center space-y-4",children:[o.jsxs("div",{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[l,o.jsxs("div",{className:"space-y-2 text-center",children:[o.jsx("p",{className:"text-ui-md text-neutral5 font-medium",children:c}),o.jsx("p",{className:"text-ui-md text-neutral3",children:a()})]})]}),t&&t.length>0&&o.jsxs("details",{className:"text-xs",children:[o.jsxs("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:["Show Validation Issues (",t.length,")"]}),o.jsx("div",{className:"mt-4 max-h-60 space-y-2 overflow-auto rounded bg-gray-100 p-3 text-left text-xs dark:bg-gray-800",children:t.map((u,d)=>o.jsxs("div",{className:"border-l-2 border-red-400 pl-2",children:[o.jsx("div",{className:"font-medium text-red-600 dark:text-red-400",children:u.type==="typescript"?"🔴 TypeScript Error":"⚠️ Lint Error"}),o.jsx("div",{className:"mt-1 font-mono text-xs wrap-break-word whitespace-pre-wrap text-gray-700 dark:text-gray-300",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-xs",children:[o.jsx("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:"Show Details"}),o.jsx("div",{className:"mt-4 max-h-60 overflow-auto rounded bg-gray-100 p-3 text-left font-mono text-xs dark:bg-gray-800",children:o.jsx("div",{className:"wrap-break-word whitespace-pre-wrap",children:n})})]})]})}function Q1s({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:s,handleInstallTemplate:a,handleVariableChange:i,isLoadingEnvVars:l,isInstalling:c,defaultModelProvider:u,defaultModelId:d,onModelUpdate:f}){return o.jsx(mY,{children:o.jsxs("div",{className:"mx-auto my-4 grid max-w-[40rem] gap-8 p-4 lg:p-8",children:[o.jsxs("h2",{className:K("text-neutral4 text-header-sm font-semibold flex items-center gap-2","[&>svg]:w-[1.2em] [&_svg]:h-[1.2em] [&_svg]:opacity-70"),children:["Install Template ",o.jsx(Hct,{})]}),o.jsx(Cm,{name:"template-provider",options:e,label:"Template AI Model Provider",onValueChange:n,value:t,placeholder:"Select",layout:"horizontal"}),t&&Object.entries(r||{}).length>0&&o.jsxs(o.Fragment,{children:[o.jsx("h3",{className:"text-neutral3 text-ui-md",children:"Set required Environmental Variables"}),o.jsx("div",{className:"grid grid-cols-[1fr_1fr] items-start gap-4",children:l?o.jsxs("div",{className:K("flex items-center justify-center col-span-2 text-neutral3 text-ui-sm gap-4","[&_svg]:opacity-50 [&_svg]:w-[1.1em] [&_svg]:h-[1.1em]","animate-in fade-in duration-300"),children:[o.jsx(Vt,{})," Loading variables..."]}):Object.entries(r).map(([h,p])=>o.jsxs(g.Fragment,{children:[o.jsx(ep,{name:`env-${h}`,labelIsHidden:!0,label:"Key",value:h,disabled:!0,className:"w-full"}),o.jsx(ep,{name:h,labelIsHidden:!0,label:"Value",value:p,onChange:i,errorMsg:s.includes(h)?"Value is required.":"",autoComplete:"off",className:"w-full"})]},h))}),o.jsxs("div",{className:"border-border1 relative mt-3.5 border-t pt-12",children:[o.jsx("div",{className:"bg-surface2 text-ui-sm text-neutral3 absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full",children:"And"}),o.jsx("h3",{className:"text-neutral4 text-ui-lg",children:"Set AI Model for Template Installation"}),o.jsx("p",{className:"text-neutral3 text-ui-md mt-2 mb-8",children:"This model will be used by the workflow to process and install the template"}),o.jsx(q4t,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(ie,{className:K("flex items-center gap-2 mt-4 justify-center text-ui-md w-full bg-surface5 min-h-10 rounded-lg text-neutral5 hover:bg-surface6 transition-colors","[&>svg]:w-[1.1em] [&_svg]:h-[1.1em] [&_svg]:text-neutral5"),onClick:a,disabled:!t||!u||!d||s.length>0||c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(Vt,{className:"h-4 w-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(Fd,{})]})})]})})}function Y1s({title:e,description:t,githubUrl:n,isLoading:r,infoData:s,templateSlug:a}){const i=a?`feat/install-template-${a}`:"feat/install-template-[slug]";return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:K("grid mt-8 items-center"),children:o.jsxs("div",{className:K("text-header-lg flex items-center gap-3","[&>svg]:w-[1.2em] [&>svg]:h-[1.2em] [&>svg]:opacity-50",{"[&>svg]:opacity-20":r}),children:[o.jsx(fy,{}),o.jsx("h2",{className:K({"bg-surface4 flex rounded-lg min-w-[50%]":r}),children:r?o.jsx(o.Fragment,{children:" "}):e})]})}),o.jsxs("div",{className:"grid gap-x-24 lg:grid-cols-[1fr_1fr]",children:[o.jsxs("div",{className:"grid",children:[o.jsx("p",{className:K("mb-4 text-ui-md text-neutral4 mt-2 leading-7",{"bg-surface4 rounded-lg ":r}),children:r?o.jsx(o.Fragment,{children:" "}):t}),!r&&a&&o.jsxs("div",{className:K("bg-surface2 border border-surface4 rounded-lg p-4 mb-4","flex items-start gap-3"),children:[o.jsx("div",{className:"mt-0.5 shrink-0",children:o.jsx(Em,{className:"h-[1.1em] w-[1.1em] text-blue-500"})}),o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(T0e,{className:"text-neutral4 h-[1em] w-[1em]"}),o.jsx("span",{className:"text-ui-md text-neutral5 font-medium",children:"A new Git branch will be created"})]}),o.jsxs("div",{className:"text-ui-sm text-neutral4 space-y-1",children:[o.jsxs("div",{children:[o.jsx("span",{className:"font-medium",children:"Branch name:"})," ",o.jsx("code",{className:"bg-surface3 text-ui-sm rounded px-1.5 py-0.5 font-mono",children:i})]}),o.jsx("div",{children:"This ensures safe installation with easy rollback if needed. Your main branch remains unchanged."})]})]})]}),n&&o.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"text-neutral3 text-ui-md hover:text-neutral5 mt-auto flex items-center gap-2",children:[o.jsx(hG,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(xje,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function ent(e){switch(e){case"running":return o.jsx(Vt,{size:"sm","aria-hidden":!0});case"success":return o.jsx(Ur,{"aria-hidden":!0});case"failed":return o.jsx(or,{"aria-hidden":!0});default:return null}}function K1s(){return o.jsx("svg",{viewBox:"0 0 24 24",className:"text-neutral2","aria-hidden":!0,children:o.jsx("circle",{cx:"12",cy:"12",r:"8.5",pathLength:"48",fill:"none",stroke:"currentcolor",strokeWidth:"2.8",strokeLinecap:"round",strokeDasharray:"3 3"})})}function X1s({status:e,variant:t}){return t==="plain"?o.jsx("span",{className:K("flex size-4 items-center justify-center self-center [&>svg]:size-4",Yr.colors,{"[&>svg]:text-positive1":e==="success","[&>svg]:text-negative1":e==="failed"}),children:e==="pending"?o.jsx(K1s,{}):ent(e)}):o.jsx("span",{className:K("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",Yr.colors,Yr.transform,Yr.shadow,{"[&>svg]:text-notice-success-fg":e==="success","[&>svg]:text-notice-destructive-fg":e==="failed","border border-dashed border-neutral2":e==="pending","[&>svg]:size-4":e!=="running","bg-accent1Dark shadow-glow-accent1":e==="success","bg-accent2Dark shadow-glow-accent2":e==="failed","scale-110":e==="success"||e==="failed"}),children:ent(e)})}function J1s({step:e,isActive:t,position:n,variant:r="default"}){return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none",Yr.colors,{"border border-transparent":r==="default","border-dashed border-neutral2 bg-surface3":t&&r==="default"}),children:[o.jsxs("div",{className:"grid min-w-0 grid-cols-[auto_1fr] gap-2",children:[o.jsxs("span",{className:K("flex min-w-6 justify-end text-ui-md",Yr.colors,{"text-neutral5":t||e.status==="success","text-neutral3":!t&&e.status!=="success"}),children:[n,"."]}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("h4",{className:K("text-ui-md",Yr.colors,{"text-neutral5":t||e.status==="success","text-neutral3":!t&&e.status!=="success"}),children:e.title}),e.description&&o.jsx("p",{className:K("-mt-0.5 text-ui-md text-neutral2",{truncate:r==="plain"}),children:e.description})]})]}),o.jsx(X1s,{status:e.status,variant:r})]})}function eSs({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:K(n),children:t.map((r,s)=>o.jsx(J1s,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function tSs({steps:e}){const t=e.length,n=e.filter(r=>r.status==="success").length;return o.jsxs("div",{className:"flex w-full flex-col content-center justify-center gap-4",children:[o.jsx("div",{className:"grid w-full grid-cols-[0_repeat(9,1fr)]",children:e.map((r,s)=>o.jsx("div",{className:K("relative flex h-8 items-center justify-end",Yr.colors,{"bg-accent1Dark":r.status==="success"&&e?.[s-1]?.status==="success"}),children:o.jsx("div",{className:K("absolute right-0 z-10 flex size-8 translate-x-1/2 items-center justify-center self-center rounded-full bg-surface3 text-ui-sm font-bold text-neutral3 motion-reduce:transition-none",Yr.colors,Yr.transform,Yr.shadow,{"border border-dashed border-neutral2":r.status==="pending","bg-accent1Dark text-notice-success-fg shadow-glow-accent1 scale-110":r.status==="success","bg-accent2Dark text-notice-destructive-fg shadow-glow-accent2 scale-110":r.status==="failed"}),children:r.status==="running"?o.jsx(Vt,{}):s+1})},r.id))}),o.jsxs("div",{className:K("text-center text-xs text-neutral3",Yr.colors),children:[n," of ",t," steps completed"]})]})}function nSs({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",a=t?.payload?.workflowState,i=t?.payload?.currentStep,l=t?.error,c=a?.steps||{},u=Object.keys(c).length>0,d=v=>v==="input"||v.endsWith(".input")||v.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(v)||/[0-9a-f]{8,}/.test(v)?!1:r?.allSteps?v in r.allSteps:!0,f=Object.entries(c).filter(([v,y])=>d(v)),h=f.length,p=()=>{switch(s){case"initializing":return"Preparing template installation...";case"processing":return`Installing ${e} template`;case"completed":return"Template installation completed!";case"error":return"Template installation failed";default:return"Installing template..."}},m=f.map(([v,y])=>({id:v,status:y?.status,description:y?.description,title:v.charAt(0).toUpperCase()+v.slice(1).replace(/-/g," "),isActive:i?.id===v}));return o.jsxs(mY,{className:"text-neutral3 mb-8 content-center space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h3",{className:"text-neutral5 text-lg font-semibold",children:p()}),(t?.runId||n)&&o.jsxs("div",{className:"text-ui-sm text-neutral3 mt-2",children:["Run ID: ",t?.runId??n]})]}),u&&h>0&&!["error"].includes(s)&&o.jsx("div",{className:"mx-auto w-full max-w-[30rem] px-6",children:o.jsx(tSs,{steps:m})}),l&&s==="error"&&o.jsxs("div",{className:K("rounded-lg text-neutral5 p-6 flex items-center gap-3 text-ui-md bg-red-500/10","[&>svg]:w-6 [&>svg]:h-6 [&>svg]:opacity-70 [&>svg]:text-red-500"),children:[o.jsx(RJt,{}),l||"Something went wrong"]}),u&&o.jsx(eSs,{steps:m,currentStep:i,className:"pb-4"}),!u&&s==="initializing"&&o.jsxs("div",{className:"text-neutral3 grid justify-items-center gap-4 text-center text-sm",children:[o.jsx(Vt,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function rSs({name:e,installedEntities:t}){return o.jsxs(mY,{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(Hct,{}),o.jsx("h2",{className:"text-header-md",children:"Done!"}),o.jsxs("p",{className:"text-ui-md text-neutral3 text-center",children:["The ",o.jsx("b",{className:"text-neutral4",children:e})," template has been successfully installed.",t&&t.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("br",{})," Installed entities are listed below."]})]}),t&&t.length>0&&o.jsx(xje,{data:t})]})}function sSs(){const{templateSlug:e}=fr(),[t,n]=za(),[r,s]=g.useState(""),[a,i]=g.useState(""),[l,c]=g.useState(""),[u,d]=g.useState({}),[f,h]=g.useState([]),[p,m]=g.useState(null),[v,y]=g.useState(!1),[b,x]=g.useState(""),[w,k]=g.useState(!1),[C,_]=g.useState(!1),[T,E]=g.useState([]),{data:N,isLoading:I}=Drr({repoOrSlug:e,owner:"mastra-ai"}),P=Z1s?.includes("beta")??!1?"beta":"main",{data:L,isLoading:D}=Lrr({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:P}),{data:B,isLoading:H}=Frr(),{mutateAsync:q,isPending:z}=zrr(),{mutateAsync:V}=Brr(),{streamInstall:M,streamResult:G,isStreaming:F}=qrr(B),{observeInstall:R,streamResult:U,isStreaming:Z}=Vrr(B);g.useEffect(()=>{const ne=t.get("runId");ne&&!v&&!p&&!F&&!Z&&(console.info("🔄 Checking completed run after hot reload:",{runId:ne}),x(ne),V({runId:ne}).then(se=>{const ce=se.snapshot;if(ce?.status==="success"&&ce?.result?.success)y(!0);else if(ce?.result?.success===!1)if(ce?.result?.validationResults&&!ce?.result?.validationResults?.valid&&ce?.result?.validationResults?.remainingErrors>0){const{remainingErrors:be,errors:he}=ce.result.validationResults,xe=`Template installation completed but ${be} validation issue${be>1?"s":""} remain unresolved.`;m(xe),E(he||[])}else{const be=ce?.result?.message||ce?.result?.error||"Template installation failed";m(typeof be=="string"?be:String(be))}}).catch(se=>{console.error("❌ Failed to fetch run details:",se),m("Failed to retrieve installation status after reload")}))},[t,v,p,F,Z,V]),g.useEffect(()=>{const ne=t.get("runId"),se=t.get("resume"),ce=t.get("provider");if(ne&&se==="true"&&ce&&!F&&!Z&&!w&&!C&&B){x(ne),k(!0);try{V({runId:ne}).then(le=>{if(le.snapshot?.status==="running")return R.mutateAsync({runId:ne})}).then(()=>{n(le=>{const be=new URLSearchParams(le);return be.delete("resume"),be})}).catch(le=>{console.error("❌ Failed to resume template installation:",le),le.message?.includes("404")||le.message?.includes("not found")?m("Template installation run not found. It may have expired or been completed."):m("Failed to resume template installation. Please try again.")})}catch(le){console.error("❌ Auto-resume failed with error:",le),m("Failed to resume template installation. Please refresh and try again.")}}},[t,e,F,Z,w,C,B,V,R,n]);const Y=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],te=[{key:"tools",label:"Tools",value:N?.tools?.length?N.tools.map(ne=>ne).join(", "):"n/a",icon:o.jsx(Bf,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(ne=>ne).join(", "):"n/a",icon:o.jsx(Ri,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(ne=>ne).join(", "):"n/a",icon:o.jsx(fI,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(Eg,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(dI,{})}],J=[{...te[0]},{...te[1]},{...te[2]}].filter(ne=>ne.value!=="n/a");g.useEffect(()=>{L&&d(L)},[L]),g.useEffect(()=>{const ne=G||U;ne?.phase==="error"&&ne?.error&&m(typeof ne.error=="string"?ne.error:String(ne.error))},[G?.phase,G?.error,U?.phase,U?.error]);const ee=ne=>{s(ne)},re=async ne=>(i(ne.provider),c(ne.modelId),{message:"Model updated successfully"}),ae=async()=>{const ne=Object.entries(u).reduce((se,[ce,le])=>(le===""&&se.push(ce),se),[]);if(ne.length>0){h(ne);return}if(N){m(null),y(!1),x(""),_(!0);try{const ce={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:P,slug:N.slug,variables:u},{runId:le}=await q({});x(le),n(be=>{const he=new URLSearchParams(be);return he.set("runId",le),he.set("resume","true"),he.set("provider",r||"openai"),he}),await M.mutateAsync({inputData:ce,selectedModel:{provider:a,modelId:l},runId:le})}catch(se){_(!1),m(se?.message||"Template installation failed"),console.error("Template installation failed",se)}}},X=ne=>{const{name:se,value:ce}=ne.target;ce.trim()===""?h(le=>[...le,se]):h(le=>le.filter(be=>be!==se)),d(le=>({...le,[se]:ce}))};return o.jsx(vs,{children:o.jsx("div",{className:K("w-full lg:px-12 h-full overflow-y-scroll"),children:o.jsxs("div",{className:"mx-auto grid w-full max-w-[80rem] gap-y-4 p-6",children:[o.jsx(Y1s,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:te,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(F||Z)&&o.jsx(nSs,{name:N.title,streamResult:Z?U:G,runId:b,workflowInfo:B}),v&&o.jsx(rSs,{name:N.title,installedEntities:J,linkComponent:Da}),p&&o.jsx(G1s,{errorMsg:p,validationErrors:T.length>0?T:G?.validationResults?.errors||U?.validationResults?.errors}),!F&&!Z&&!v&&!p&&o.jsx(Q1s,{providerOptions:Y,selectedProvider:r,onProviderChange:ee,variables:u,setVariables:d,errors:f,setErrors:h,handleInstallTemplate:ae,handleVariableChange:X,isLoadingEnvVars:D||H,isInstalling:z,defaultModelProvider:a,defaultModelId:l,onModelUpdate:re})]})]})})})}const aSs=()=>{const{toolId:e,agentId:t}=fr();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(Cos,{toolId:e,agentId:t})})},iSs=()=>{const{toolId:e}=fr();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(iws,{toolId:e})})};function oSs(){const{data:e,isLoading:t,error:n}=Xy(),[r,s]=g.useState("");return n&&hs(n)?o.jsx(Zn,{children:o.jsx(Ts,{})}):n&&ps(n)?o.jsx(Zn,{children:o.jsx(ks,{resource:"workflows"})}):n?o.jsx(Zn,{children:o.jsx(La,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(Zn,{children:o.jsx(hYr,{})}):o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(cd,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsxs(ie,{as:Da,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(sI,{}),"Schedules"]})]})}),o.jsx(fYr,{workflows:e||{},isLoading:t,search:r})]})}const lSs={active:"bg-accent1",paused:"bg-accent3"},cSs={active:"text-accent1",paused:"text-accent3"},eWt=({status:e})=>o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${lSs[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${cSs[e]}`,children:e})]}),Ej=e=>!e||e<=0?"—":new Date(e).toLocaleString(),h2=e=>{if(!e||e<=0)return"—";const t=e-Date.now(),n=Math.abs(t),r=Math.floor(n/1e3);if(r<60)return t>=0?`in ${r}s`:`${r}s ago`;const s=Math.floor(r/60);if(s<60)return t>=0?`in ${s}m`:`${s}m ago`;const a=Math.floor(s/60);if(a<24)return t>=0?`in ${a}h`:`${a}h ago`;const i=Math.floor(a/24);return t>=0?`in ${i}d`:`${i}d ago`};function tWt({status:e}){const{icon:t,color:n}=uSs(e);return o.jsxs("span",{className:`text-ui-sm inline-flex items-center gap-1.5 whitespace-nowrap ${n}`,children:[o.jsx("span",{className:"inline-flex shrink-0 items-center","aria-hidden":!0,children:t}),o.jsx("span",{children:e})]})}function uSs(e){switch(e){case"success":return{icon:o.jsx(Ur,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(or,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(Vt,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(EV,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(Mc,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(c1,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const tnt="auto auto auto auto 1fr";function dSs(e){if(e===void 0)return"—";if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;const t=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return`${t}m ${n}s`}function fSs(e){const t=Math.abs(e),n=e<0?"-":"";return t<1e3?`${n}${t}ms`:t<6e4?`${n}${(t/1e3).toFixed(1)}s`:t<36e5?`${n}${(t/6e4).toFixed(1)}m`:`${n}${(t/36e5).toFixed(1)}h`}const hSs=3e4,pSs=5*6e4;function mSs({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=dn(),c=p=>!!(n&&p.runId&&p.outcome!=="failed"),u=e.filter(c).length,{containerRef:d,getRowProps:f}=ao({count:u});let h=-1;return t?o.jsx(Bo,{columns:tnt}):e.length===0?o.jsx(ve,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(pe,{columns:tnt,className:"min-w-0",scrollRef:d,children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{children:"Run"}),o.jsx(pe.TopCell,{children:"Status"}),o.jsx(pe.TopCell,{children:"Started"}),o.jsx(pe.TopCell,{children:"Duration"}),o.jsx(pe.TopCell,{children:" "})]}),e.map(p=>{const m=p.actualFireAt-p.scheduledFireAt,v=fSs(m),y=`Scheduled ${Ej(p.scheduledFireAt)} — published ${Ej(p.actualFireAt)} (drift ${v})`,b=p.outcome==="failed",x=b?p.error:p.run?.error,w=Math.abs(m),k=!b&&w>hSs&&w<=pSs,C=`${p.scheduleId}-${p.runId}-${p.actualFireAt}`,_=c(p);_&&(h+=1);const T=o.jsx("span",{className:_?"text-accent1 text-ui-sm font-mono whitespace-nowrap":"text-neutral3 text-ui-sm font-mono whitespace-nowrap",children:p.runId}),E=o.jsxs(o.Fragment,{children:[o.jsx(pe.Cell,{children:T}),o.jsx(pe.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[b?o.jsxs("span",{className:"text-ui-sm text-accent2 inline-flex items-center gap-1.5 whitespace-nowrap",children:[o.jsx(uc,{size:14}),"publish failed"]}):p.run?o.jsx(tWt,{status:p.run.status}):o.jsx("span",{className:"text-ui-sm text-neutral3 inline-flex items-center gap-1.5 whitespace-nowrap",children:"pending"}),x?o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(uc,{size:14})})}),o.jsx(yn,{children:x})]}):null]})}),o.jsx(pe.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:y,children:h2(p.actualFireAt)}),k?o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(uc,{size:14})})}),o.jsxs(yn,{children:["Published ",v," after the scheduled fire time"]})]}):null]})}),o.jsx(pe.Cell,{children:p.run?o.jsx("span",{children:dSs(p.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(pe.Cell,{children:" "})]});return _?o.jsx(pe.RowLink,{to:l.workflowRunLink(n,p.runId),LinkComponent:i,...f(h),children:E},C):o.jsx(pe.RowStatic,{children:E},C)}),o.jsx(pe.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const gSs=e=>{const t=Ye();return mt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},nnt=25,vSs=e=>{const t=Ye(),{inView:n,setRef:r}=a0(),s=Ly({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:nnt,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<nnt))return u.triggers[u.triggers.length-1].actualFireAt},refetchInterval:u=>(u.state.data?.pages.flatMap(h=>h.triggers)??[]).some(h=>h.run?h.run.status==="pending"||h.run.status==="running"||h.run.status==="waiting":h.outcome==="published")?5e3:!1}),a=s.data?.pages.flatMap(u=>u?.triggers??[])??[],{hasNextPage:i,isFetchingNextPage:l,fetchNextPage:c}=s;return g.useEffect(()=>{n&&i&&!l&&c()},[n,i,l,c]),{...s,data:a,setEndOfListElement:r}},ySs=e=>{const t=Ye(),n=Ar();return Sn({mutationFn:async r=>{if(!e)throw new Error("scheduleId is required");return r==="pause"?t.pauseSchedule(e):t.resumeSchedule(e)},onSuccess:(r,s)=>{n.invalidateQueries({queryKey:["schedule",e]}),n.invalidateQueries({queryKey:["schedules"]}),Ve.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{Ve.error(r.message)}})};function p8({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ve,{variant:"ui-xs",className:"text-neutral4 tracking-wide uppercase",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function bSs(){const{scheduleId:e}=fr(),{paths:t}=dn(),{data:n,error:r}=gSs(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=vSs(e),d=ySs(e);if(r&&hs(r))return o.jsx(Zn,{children:o.jsx(Ts,{})});if(r&&ps(r))return o.jsx(Zn,{children:o.jsx(ks,{resource:"schedules"})});if(r)return o.jsx(Zn,{children:o.jsx(La,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,h=n?.agentId;return o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx(Lt.Row,{className:"justify-end",children:o.jsxs(Lt.Column,{className:"flex justify-end gap-2",children:[o.jsxs(ie,{as:Da,to:t.schedulesLink(),variant:"ghost",children:[o.jsx(bl,{}),"Back to schedules"]}),f?o.jsx(ie,{as:Da,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(ie,{onClick:()=>d.mutate(n.status==="active"?"pause":"resume"),disabled:d.isPending,"data-testid":"schedule-toggle-button",children:n.status==="active"?o.jsxs(o.Fragment,{children:[o.jsx($V,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(Dc,{}),"Resume"]})}):null]})})}),n?o.jsxs("div",{className:"grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-6 overflow-hidden",children:[o.jsxs("div",{className:"border-border1 flex h-fit flex-col gap-4 rounded-md border p-4",children:[o.jsx(p8,{label:h?"Agent":"Workflow",children:f?o.jsx(Da,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):h?o.jsx(Da,{to:t.agentLink(h),className:"text-accent1 hover:underline",children:h}):"—"}),o.jsxs(p8,{label:"Cron",children:[o.jsx("code",{className:"text-ui-md font-mono",children:n.cron}),n.timezone?o.jsx("span",{className:"text-neutral4 text-ui-sm ml-2",children:n.timezone}):null]}),o.jsx(p8,{label:"Status",children:o.jsx(eWt,{status:n.status})}),o.jsx(p8,{label:"Next fire",children:o.jsx("span",{title:Ej(n.nextFireAt),children:h2(n.nextFireAt)})})]}),o.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[o.jsx(ve,{variant:"ui-md",className:"mb-3",children:"Trigger history"}),i?o.jsx(La,{title:"Failed to load trigger history",message:i.message}):o.jsx(mSs,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const rnt="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function xSs({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=dn(),a=g.useMemo(()=>{const c=n.toLowerCase();return c?e.filter(u=>u.id.toLowerCase().includes(c)||(u.workflowId??u.agentId??"").toLowerCase().includes(c)):e},[e,n]),{containerRef:i,getRowProps:l}=ao({count:a.length});return t?o.jsx(Bo,{columns:rnt}):o.jsxs(pe,{columns:rnt,className:"min-w-0",scrollRef:i,children:[o.jsxs(pe.Top,{children:[o.jsx(pe.TopCell,{children:"Target"}),o.jsx(pe.TopCell,{children:"Schedule ID"}),o.jsx(pe.TopCell,{children:"Cron"}),o.jsx(pe.TopCell,{children:"Status"}),o.jsx(pe.TopCell,{children:"Next fire"}),o.jsx(pe.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(pe.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(pe.NoMatch,{message:"No schedules configured"}):null,a.map((c,u)=>o.jsxs(pe.RowLink,{to:r.scheduleLink(c.id),LinkComponent:s,...l(u),children:[o.jsx(pe.NameCell,{children:c.workflowId??c.agentId}),o.jsx(pe.Cell,{className:"min-w-0",children:o.jsx("span",{className:"text-ui-smd text-neutral3 block truncate font-mono",title:c.id,children:c.id})}),o.jsx(pe.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("code",{className:"text-ui-sm font-mono",children:c.cron}),c.timezone?o.jsx("span",{className:"text-neutral4 text-ui-xs",children:c.timezone}):null]})}),o.jsx(pe.Cell,{children:o.jsx(eWt,{status:c.status})}),o.jsx(pe.Cell,{children:o.jsx("span",{className:"whitespace-nowrap",title:Ej(c.nextFireAt),children:h2(c.nextFireAt)})}),o.jsx(pe.Cell,{children:c.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(tWt,{status:c.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:Ej(c.lastFireAt),children:c.lastFireAt?h2(c.lastFireAt):""})]}):c.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:Ej(c.lastFireAt),children:h2(c.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},c.id))]})}function wSs({workflowId:e}={}){const{data:t,isLoading:n,error:r}=CSe(e?{workflowId:e}:{}),[s,a]=g.useState("");return r?o.jsx(La,{title:"Failed to load schedules",message:r.message}):o.jsxs("div",{className:"grid h-full grid-rows-[auto_1fr] gap-4 overflow-hidden",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(cd,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(xSs,{schedules:t??[],isLoading:n,search:s})})]})}function SSs(){const[e]=za(),t=e.get("workflowId")??void 0,{error:n}=CSe(t?{workflowId:t}:{});return n&&hs(n)?o.jsx(Zn,{children:o.jsx(Ts,{})}):n&&ps(n)?o.jsx(Zn,{children:o.jsx(ks,{resource:"schedules"})}):o.jsx(Lt,{children:o.jsx("div",{className:"h-full",children:o.jsx(wSs,{workflowId:t})})})}function kSs({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=KOe({stepGraph:e}),[a,i]=g.useState(!1),[l,c,u]=k_t(r),[d]=O_t(s),{edgeTypes:f,nodeTypes:h,styledEdges:p}=U5t({edges:d,workflowName:n,stepGraph:e});return g.useEffect(()=>{if(t){const m=setTimeout(()=>{i(!0)},500);return()=>clearTimeout(m)}},[t]),o.jsx("div",{className:"bg-surface1 relative h-full w-full",children:a?o.jsxs(S_t,{nodes:l,edges:p,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:h,onNodesChange:u,children:[o.jsx(Vje,{position:"bottom-left"}),o.jsx(__t,{variant:gy.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:o.jsx(Vt,{})})})}function OSs(){const{stepDetail:e,closeStepDetail:t}=MW();return e?o.jsxs("div",{className:"flex h-full flex-col","data-testid":"workflow-step-detail-panel",children:[o.jsxs("div",{className:"border-border1 bg-surface1 flex items-center justify-between border-b px-4 py-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[e.type==="map-config"&&o.jsx(u1,{className:"h-4 w-4",style:{color:Bu.map}}),e.type==="nested-graph"&&o.jsx(Bc,{className:"h-4 w-4",style:{color:Bu.workflow}}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx(ve,{variant:"ui-md",className:"text-neutral6 font-medium",children:e.type==="map-config"?`${e.stepName} Config`:`${e.stepName} Workflow`}),e.type==="map-config"&&e.stepId&&e.stepId!==e.stepName&&o.jsx(ve,{variant:"ui-xs",className:"text-neutral3",children:e.stepId})]})]}),o.jsx("button",{onClick:t,className:"hover:bg-surface3 rounded p-1 transition-colors","aria-label":"Close",children:o.jsx(or,{className:"text-neutral3 h-4 w-4"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(c2,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(YOe,{children:o.jsx(kSs,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function CSs(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function _Ss(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){const n=Object.keys(e);if(n.length===1)return n[0]}return t}function ESs({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:o.jsxs("div",{className:"border-border1 bg-surface4 space-y-5 rounded-lg border p-5","data-testid":"workflow-suspended-steps",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs(ve,{as:"p",variant:"ui-md",className:"text-neutral6 flex items-center gap-2 font-semibold",children:[o.jsx(Qe,{children:o.jsx(EV,{})}),"Step suspended"]}),o.jsx(bt,{variant:"yellow",children:"Needs input"})]}),e.map((s,a)=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const l=i?.resumeSchema?xm(Ix(i.resumeSchema)):mf(cr(),_f());return o.jsx(TSs,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function TSs({step:e,stepSchema:t,description:n,isStreaming:r,onResume:s}){const[a,i]=g.useState(!1);return o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(ve,{as:"p",variant:"ui-md",className:"text-neutral6 truncate font-medium",children:e.stepId}),n&&o.jsx(ve,{as:"p",variant:"ui-sm",className:"text-neutral3",children:n})]}),e.suspendPayload&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs(ve,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(Qe,{children:o.jsx(kJt,{})}),"The step is asking"]}),o.jsxs(fc,{open:a,onOpenChange:i,children:[o.jsxs(ql,{className:"border-border1 bg-surface3 flex w-full items-center justify-between gap-2 rounded-lg border px-3 py-2.5",children:[o.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(Qe,{children:o.jsx(Lr,{className:K("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(ve,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:_Ss(e.suspendPayload,e.stepId)})]}),o.jsx(ve,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:CSs(e.suspendPayload)})]}),o.jsx(Vl,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Gr,{data:e.suspendPayload,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs(ve,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(Qe,{children:o.jsx(_Jt,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(pU,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(Dc,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:l=>{const c=e.stepId?.split(".");s({stepId:c,runId:e.runId,suspendPayload:e.suspendPayload,resumeData:l,isLoading:!1})}})})]})]})}function jSs(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext(Gl),{runId:a}=fr(),i=R_t(e,r??""),l=Yer(),c=!!a,u=t?.status==="suspended",f=!!(a&&r&&a===r)&&e?.status==="suspended";return s||!n||i.length===0||c&&!u&&!f?null:o.jsx("div",{"data-testid":"workflow-suspended-overlay",className:"animate-in fade-in-0 slide-in-from-top-2 zoom-in-95 absolute top-2 right-2 z-20 max-h-[calc(100%-1rem)] w-[380px] max-w-[calc(100%-1rem)] overflow-y-auto rounded-lg shadow-lg duration-300",children:o.jsx(ESs,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const NSs=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.97865 4.57004C8.22604 4.75795 8.27426 5.11082 8.08635 5.35821L6.05486 8.03279C5.94873 8.17251 5.78348 8.25471 5.60803 8.25505C5.43257 8.2554 5.267 8.17385 5.16032 8.03454L3.80937 6.27034C3.6205 6.02369 3.66733 5.67063 3.91398 5.48176C4.16063 5.29288 4.51369 5.33972 4.70257 5.58637L5.6051 6.76498L7.19048 4.67774C7.37839 4.43036 7.73126 4.38213 7.97865 4.57004Z",fill:"currentColor"})]}),ISs=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.89741 4.10293C8.11707 4.32261 8.11706 4.67877 7.89738 4.89843L6.79517 6.00058L7.8962 7.10155C8.11588 7.32122 8.11589 7.67737 7.89623 7.89705C7.67656 8.11673 7.32041 8.11674 7.10073 7.89707L5.99965 6.79605L4.89856 7.89707C4.67889 8.11673 4.32273 8.11672 4.10307 7.89704C3.88341 7.67737 3.88342 7.32121 4.10309 7.10155L5.20413 6.00058L4.10191 4.89843C3.88224 4.67877 3.88223 4.32262 4.10189 4.10294C4.32155 3.88326 4.67771 3.88325 4.89738 4.10292L5.99965 5.20511L7.10191 4.10291C7.32159 3.88325 7.67774 3.88326 7.89741 4.10293Z",fill:"currentColor"})]}),ASs=e=>e.includes("."),RSs=e=>e==="input"||e.endsWith(".input"),PSs=1;function $Ss(e){return`${Number((e/1e3).toPrecision(3))}s`}function MSs(e,t){const n=Object.entries(e).filter(([i])=>!RSs(i));if(n.length===0)return[];const r=Math.min(...n.map(([,i])=>i.startedAt)),s=Math.max(...n.map(([,i])=>i.endedAt??t)),a=Math.max(s-r,1);return n.map(([i,l])=>{const c=l.endedAt===void 0,d=(l.endedAt??t)-l.startedAt,f=(l.startedAt-r)/a*100,h=Math.max(d/a*100,PSs);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:h,durationMs:d,isRunning:c,isNestedEntry:ASs(i)}})}const DSs=({status:e})=>o.jsxs(Qe,{children:[e==="success"&&o.jsx(NSs,{className:"text-accent1"}),e==="failed"&&o.jsx(ISs,{className:"text-accent2"}),e==="suspended"&&o.jsx(EV,{className:"text-accent3"}),e==="waiting"&&o.jsx(rpe,{className:"text-accent5"}),e==="skipped"&&o.jsx(rpe,{className:"text-icon3"}),e==="running"&&o.jsx(Vs,{className:"text-accent6 animate-spin"})]}),LSs={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function nWt(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const snt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},FSs=e=>{const t=e;return R5t({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},zSs=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=FSs(e.step),u=e.status==="running",d=!e.isNestedEntry;return o.jsxs("div",{role:"button",tabIndex:0,"data-testid":"workflow-timeline-row","data-workflow-step-key":e.stepId,"data-workflow-step-active":n?"true":void 0,"data-workflow-step-hovered":r?"true":void 0,"data-workflow-step-nested":e.isNestedEntry?"true":void 0,"aria-pressed":n,"aria-disabled":!d,onMouseEnter:()=>{d&&a(e.stepId)},onMouseLeave:()=>{d&&a(null)},onClick:()=>{d&&s(e.stepId)},onKeyDown:f=>{!d||f.key!=="Enter"&&f.key!==" "||(f.preventDefault(),s(e.stepId))},className:K("grid grid-cols-[auto_auto_auto_minmax(0,10rem)_minmax(0,1fr)_auto_5rem] items-center gap-2 rounded-md border border-transparent px-2 py-1 text-left transition-colors focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-accent1",d&&"cursor-pointer",d&&"hover:bg-surface4",d&&r&&!n&&"border-neutral6 bg-surface4",d&&n&&"border-accent1",e.isNestedEntry&&"cursor-default opacity-55"),children:[o.jsx("div",{className:"flex justify-center",children:o.jsx(DSs,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ie,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step input",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||i(e)},children:o.jsx(Fen,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(Jq,{indicators:c,className:"shrink-0"})}),o.jsx(ve,{as:"span",variant:"ui-sm",className:"text-neutral6 block max-w-full min-w-0 justify-self-stretch overflow-hidden text-left text-ellipsis whitespace-nowrap",children:nWt(e.stepId)}),o.jsx("div",{className:"bg-surface4 relative h-2 min-w-0 rounded",children:o.jsx("div",{"data-testid":"workflow-timeline-bar","data-offset":String(e.offsetPct),"data-width":String(e.widthPct),className:`absolute top-0 h-full rounded ${LSs[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ie,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step output",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||l(e)},children:o.jsx(Den,{})})}),o.jsx(ve,{as:"span",variant:"ui-sm",className:"text-neutral3 w-20 justify-self-end text-right tabular-nums",children:$Ss(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function BSs(){const{steps:e}=aL(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=WH(),[a,i]=g.useState(()=>Date.now()),[l,c]=g.useState(!1),[u,d]=g.useState(null),f=g.useRef(null);uxt(f,{enabled:!l});const h=MSs(e,a),p=h.some(m=>m.isRunning);return g.useEffect(()=>{if(!p)return;const m=setInterval(()=>i(Date.now()),100);return()=>clearInterval(m)},[p]),g.useEffect(()=>{if(l||h.length===0)return;const m=f.current;m&&(m.scrollTop=m.scrollHeight)},[l,h.length]),h.length===0?null:o.jsxs(o.Fragment,{children:[o.jsx("div",{"data-testid":"workflow-timeline",className:"pointer-events-none absolute right-0 bottom-0 z-20 px-2 pb-2",style:{left:"var(--workflow-left-panel-width, 0px)"},children:o.jsxs("div",{className:"rounded-studio-panel border-border1/50 bg-surface3 pointer-events-auto flex max-h-64 w-full min-w-0 flex-col gap-3 overflow-hidden border p-4 shadow-lg",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3",children:[o.jsx(ve,{as:"p",variant:"ui-md",className:"text-neutral3",children:"Timeline"}),o.jsx("button",{type:"button","aria-label":l?"Expand timeline":"Collapse timeline","aria-expanded":!l,onClick:()=>c(m=>!m),className:"text-neutral3 hover:bg-surface4 hover:text-neutral6 rounded-md p-1 transition-colors",children:o.jsx(Js,{className:K("h-4 w-4 transition-transform",l&&"-rotate-90")})})]}),!l&&o.jsx("div",{ref:f,"data-testid":"workflow-timeline-list",className:"flex min-h-0 flex-col gap-2 overflow-y-auto",children:h.map((m,v)=>o.jsx(zSs,{row:m,index:v,isSelected:t===m.stepId,isHovered:n===m.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:y=>d({type:"input",stepId:y.stepId,data:snt(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:snt(y.step.output)})},`timeline-item-${m.stepId}-${v}`))})]})}),o.jsx(pr,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx($_t,{data:u.data,title:`${nWt(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const USs=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=MW();return o.jsxs("div",{className:"flex h-full min-h-0",children:[o.jsx("div",{className:"flex h-full min-h-0 flex-1 flex-col",children:o.jsxs("div",{className:"relative min-h-0 flex-1 p-2 pb-0",children:[o.jsx(Q5t,{workflowId:e,workflow:t,isLoading:n}),o.jsx(jSs,{}),o.jsx(BSs,{})]})}),r&&o.jsx("div",{className:"border-border1 min-h-0 w-[420px] overflow-hidden border-l",children:o.jsx(OSs,{})})]})},ant=()=>{const{workflowId:e}=fr(),{data:t,isLoading:n,error:r}=f4(e);return r&&hs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{})}):r&&ps(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ks,{resource:"workflows"})}):o.jsx(mCe,{children:o.jsx(USs,{workflowId:e,workflow:t??void 0,isLoading:n})})};function qSs(e,t){if(e==null)return{};var n,r,s=Fkt(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function p0e(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function VSs(e){if(Array.isArray(e))return p0e(e)}function HSs(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function WSs(e,t){if(e){if(typeof e=="string")return p0e(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?p0e(e,t):void 0}}function ZSs(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
667
667
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function m0e(e){return VSs(e)||HSs(e)||WSs(e)||ZSs()}function GD(e){"@babel/helpers - typeof";return GD=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},GD(e)}function GSs(e,t){if(GD(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(GD(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function QSs(e){var t=GSs(e,"string");return GD(t)=="symbol"?t:t+""}function rWt(e,t,n){return(t=QSs(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function int(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function zT(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?int(Object(n),!0).forEach(function(r){rWt(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):int(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function YSs(e){var t=e.length;if(t===0||t===1)return e;if(t===2)return[e[0],e[1],"".concat(e[0],".").concat(e[1]),"".concat(e[1],".").concat(e[0])];if(t===3)return[e[0],e[1],e[2],"".concat(e[0],".").concat(e[1]),"".concat(e[0],".").concat(e[2]),"".concat(e[1],".").concat(e[0]),"".concat(e[1],".").concat(e[2]),"".concat(e[2],".").concat(e[0]),"".concat(e[2],".").concat(e[1]),"".concat(e[0],".").concat(e[1],".").concat(e[2]),"".concat(e[0],".").concat(e[2],".").concat(e[1]),"".concat(e[1],".").concat(e[0],".").concat(e[2]),"".concat(e[1],".").concat(e[2],".").concat(e[0]),"".concat(e[2],".").concat(e[0],".").concat(e[1]),"".concat(e[2],".").concat(e[1],".").concat(e[0])];if(t>=4)return[e[0],e[1],e[2],e[3],"".concat(e[0],".").concat(e[1]),"".concat(e[0],".").concat(e[2]),"".concat(e[0],".").concat(e[3]),"".concat(e[1],".").concat(e[0]),"".concat(e[1],".").concat(e[2]),"".concat(e[1],".").concat(e[3]),"".concat(e[2],".").concat(e[0]),"".concat(e[2],".").concat(e[1]),"".concat(e[2],".").concat(e[3]),"".concat(e[3],".").concat(e[0]),"".concat(e[3],".").concat(e[1]),"".concat(e[3],".").concat(e[2]),"".concat(e[0],".").concat(e[1],".").concat(e[2]),"".concat(e[0],".").concat(e[1],".").concat(e[3]),"".concat(e[0],".").concat(e[2],".").concat(e[1]),"".concat(e[0],".").concat(e[2],".").concat(e[3]),"".concat(e[0],".").concat(e[3],".").concat(e[1]),"".concat(e[0],".").concat(e[3],".").concat(e[2]),"".concat(e[1],".").concat(e[0],".").concat(e[2]),"".concat(e[1],".").concat(e[0],".").concat(e[3]),"".concat(e[1],".").concat(e[2],".").concat(e[0]),"".concat(e[1],".").concat(e[2],".").concat(e[3]),"".concat(e[1],".").concat(e[3],".").concat(e[0]),"".concat(e[1],".").concat(e[3],".").concat(e[2]),"".concat(e[2],".").concat(e[0],".").concat(e[1]),"".concat(e[2],".").concat(e[0],".").concat(e[3]),"".concat(e[2],".").concat(e[1],".").concat(e[0]),"".concat(e[2],".").concat(e[1],".").concat(e[3]),"".concat(e[2],".").concat(e[3],".").concat(e[0]),"".concat(e[2],".").concat(e[3],".").concat(e[1]),"".concat(e[3],".").concat(e[0],".").concat(e[1]),"".concat(e[3],".").concat(e[0],".").concat(e[2]),"".concat(e[3],".").concat(e[1],".").concat(e[0]),"".concat(e[3],".").concat(e[1],".").concat(e[2]),"".concat(e[3],".").concat(e[2],".").concat(e[0]),"".concat(e[3],".").concat(e[2],".").concat(e[1]),"".concat(e[0],".").concat(e[1],".").concat(e[2],".").concat(e[3]),"".concat(e[0],".").concat(e[1],".").concat(e[3],".").concat(e[2]),"".concat(e[0],".").concat(e[2],".").concat(e[1],".").concat(e[3]),"".concat(e[0],".").concat(e[2],".").concat(e[3],".").concat(e[1]),"".concat(e[0],".").concat(e[3],".").concat(e[1],".").concat(e[2]),"".concat(e[0],".").concat(e[3],".").concat(e[2],".").concat(e[1]),"".concat(e[1],".").concat(e[0],".").concat(e[2],".").concat(e[3]),"".concat(e[1],".").concat(e[0],".").concat(e[3],".").concat(e[2]),"".concat(e[1],".").concat(e[2],".").concat(e[0],".").concat(e[3]),"".concat(e[1],".").concat(e[2],".").concat(e[3],".").concat(e[0]),"".concat(e[1],".").concat(e[3],".").concat(e[0],".").concat(e[2]),"".concat(e[1],".").concat(e[3],".").concat(e[2],".").concat(e[0]),"".concat(e[2],".").concat(e[0],".").concat(e[1],".").concat(e[3]),"".concat(e[2],".").concat(e[0],".").concat(e[3],".").concat(e[1]),"".concat(e[2],".").concat(e[1],".").concat(e[0],".").concat(e[3]),"".concat(e[2],".").concat(e[1],".").concat(e[3],".").concat(e[0]),"".concat(e[2],".").concat(e[3],".").concat(e[0],".").concat(e[1]),"".concat(e[2],".").concat(e[3],".").concat(e[1],".").concat(e[0]),"".concat(e[3],".").concat(e[0],".").concat(e[1],".").concat(e[2]),"".concat(e[3],".").concat(e[0],".").concat(e[2],".").concat(e[1]),"".concat(e[3],".").concat(e[1],".").concat(e[0],".").concat(e[2]),"".concat(e[3],".").concat(e[1],".").concat(e[2],".").concat(e[0]),"".concat(e[3],".").concat(e[2],".").concat(e[0],".").concat(e[1]),"".concat(e[3],".").concat(e[2],".").concat(e[1],".").concat(e[0])]}var moe={};function KSs(e){if(e.length===0||e.length===1)return e;var t=e.join(".");return moe[t]||(moe[t]=YSs(e)),moe[t]}function XSs(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2?arguments[2]:void 0,r=e.filter(function(a){return a!=="token"}),s=KSs(r);return s.reduce(function(a,i){return zT(zT({},a),n[i])},t)}function ont(e){return e.join(" ")}function JSs(e,t){var n=0;return function(r){return n+=1,r.map(function(s,a){return sWt({node:s,stylesheet:e,useInlineStyles:t,key:"code-segment-".concat(n,"-").concat(a)})})}}function sWt(e){var t=e.node,n=e.stylesheet,r=e.style,s=r===void 0?{}:r,a=e.useInlineStyles,i=e.key,l=t.properties,c=t.type,u=t.tagName,d=t.value;if(c==="text")return d;if(u){var f=JSs(n,a),h;if(!a)h=zT(zT({},l),{},{className:ont(l.className)});else{var p=Object.keys(n).reduce(function(b,x){return x.split(".").forEach(function(w){b.includes(w)||b.push(w)}),b},[]),m=l.className&&l.className.includes("token")?["token"]:[],v=l.className&&m.concat(l.className.filter(function(b){return!p.includes(b)}));h=zT(zT({},l),{},{className:ont(v)||void 0,style:XSs(l.className,Object.assign({},l.style,s),n)})}var y=f(t.children);return qe.createElement(u,sC({key:i},h),y)}}const eks=(function(e,t){var n=e.listLanguages();return n.indexOf(t)!==-1});var tks=["language","children","style","customStyle","codeTagProps","useInlineStyles","showLineNumbers","showInlineLineNumbers","startingLineNumber","lineNumberContainerStyle","lineNumberStyle","wrapLines","wrapLongLines","lineProps","renderer","PreTag","CodeTag","code","astGenerator"];function lnt(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function Vw(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?lnt(Object(n),!0).forEach(function(r){rWt(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):lnt(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var nks=/\n/g;function rks(e){return e.match(nks)}function sks(e){var t=e.lines,n=e.startingLineNumber,r=e.style;return t.map(function(s,a){var i=a+n;return qe.createElement("span",{key:"line-".concat(a),className:"react-syntax-highlighter-line-number",style:typeof r=="function"?r(i):r},"".concat(i,`
668
668
  `))})}function aks(e){var t=e.codeString,n=e.codeStyle,r=e.containerStyle,s=r===void 0?{float:"left",paddingRight:"10px"}:r,a=e.numberStyle,i=a===void 0?{}:a,l=e.startingLineNumber;return qe.createElement("code",{style:Object.assign({},n,s)},sks({lines:t.replace(/\n$/,"").split(`
669
669
  `),style:i,startingLineNumber:l}))}function iks(e){return"".concat(e.toString().length,".25em")}function aWt(e,t){return{type:"element",tagName:"span",properties:{key:"line-number--".concat(e),className:["comment","linenumber","react-syntax-highlighter-line-number"],style:t},children:[{type:"text",value:e}]}}function iWt(e,t,n){var r={display:"inline-block",minWidth:iks(n),paddingRight:"1em",textAlign:"right",userSelect:"none"},s=typeof e=="function"?e(t):e,a=Vw(Vw({},r),s);return a}function D9(e){var t=e.children,n=e.lineNumber,r=e.lineNumberStyle,s=e.largestLineNumber,a=e.showInlineLineNumbers,i=e.lineProps,l=i===void 0?{}:i,c=e.className,u=c===void 0?[]:c,d=e.showLineNumbers,f=e.wrapLongLines,h=e.wrapLines,p=h===void 0?!1:h,m=p?Vw({},typeof l=="function"?l(n):l):{};if(m.className=m.className?[].concat(m0e(m.className.trim().split(/\s+/)),m0e(u)):u,n&&a){var v=iWt(r,n,s);t.unshift(aWt(n,v))}return f&d&&(m.style=Vw({display:"flex"},m.style)),{type:"element",tagName:"span",properties:m,children:t}}function oWt(e){for(var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[],r=0;r<e.length;r++){var s=e[r];if(s.type==="text")n.push(D9({children:[s],className:m0e(new Set(t))}));else if(s.children){var a=t.concat(s.properties.className);oWt(s.children,a).forEach(function(i){return n.push(i)})}}return n}function oks(e,t,n,r,s,a,i,l,c){var u,d=oWt(e.value),f=[],h=-1,p=0;function m(C,_){var T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return D9({children:C,lineNumber:_,lineNumberStyle:l,largestLineNumber:i,showInlineLineNumbers:s,lineProps:n,className:T,showLineNumbers:r,wrapLongLines:c,wrapLines:t})}function v(C,_){if(r&&_&&s){var T=iWt(l,_,i);C.unshift(aWt(_,T))}return C}function y(C,_){var T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return t||T.length>0?m(C,_,T):v(C,_)}for(var b=function(){var _=d[p],T=_.children[0].value,E=rks(T);if(E){var N=T.split(`