@mastra/deployer-cloud 1.65.0-alpha.11 → 1.65.0-alpha.12

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-K44HqE7F.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-DHjfgEgY.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 Ua}from"./preload-helper-PPVm8Dsz.js";function wYt(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 $j=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ql(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var IX={exports:{}},xR={};var PMe;function SYt(){if(PMe)return xR;PMe=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 xR.Fragment=t,xR.jsx=n,xR.jsxs=n,xR}var $Me;function kYt(){return $Me||($Me=1,IX.exports=SYt()),IX.exports}var o=kYt(),AX={exports:{}},Qr={},MMe;function OYt(){if(MMe)return Qr;MMe=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(z){return z===null||typeof z!="object"?null:(z=p&&z[p]||z["@@iterator"],typeof z=="function"?z:null)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y=Object.assign,b={};function x(z,P,U){this.props=z,this.context=P,this.refs=b,this.updater=U||v}x.prototype.isReactComponent={},x.prototype.setState=function(z,P){if(typeof z!="object"&&typeof z!="function"&&z!=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,z,P,"setState")},x.prototype.forceUpdate=function(z){this.updater.enqueueForceUpdate(this,z,"forceUpdate")};function w(){}w.prototype=x.prototype;function k(z,P,U){this.props=z,this.context=P,this.refs=b,this.updater=U||v}var O=k.prototype=new w;O.constructor=k,y(O,x.prototype),O.isPureReactComponent=!0;var _=Array.isArray;function T(){}var E={H:null,A:null,T:null,S:null},N=Object.prototype.hasOwnProperty;function I(z,P,U){var W=U.ref;return{$$typeof:t,type:z,key:P,ref:W!==void 0?W:null,props:U}}function A(z,P){return I(z.type,P,z.props)}function R(z){return typeof z=="object"&&z!==null&&z.$$typeof===t}function L(z){var P={"=":"=0",":":"=2"};return"$"+z.replace(/[=:]/g,function(U){return P[U]})}var D=/\/+/g;function B(z,P){return typeof z=="object"&&z!==null&&z.key!=null?L(""+z.key):P.toString(36)}function H(z){switch(z.status){case"fulfilled":return z.value;case"rejected":throw z.reason;default:switch(typeof z.status=="string"?z.then(T,T):(z.status="pending",z.then(function(P){z.status==="pending"&&(z.status="fulfilled",z.value=P)},function(P){z.status==="pending"&&(z.status="rejected",z.reason=P)})),z.status){case"fulfilled":return z.value;case"rejected":throw z.reason}}throw z}function q(z,P,U,W,Y){var te=typeof z;(te==="undefined"||te==="boolean")&&(z=null);var J=!1;if(z===null)J=!0;else switch(te){case"bigint":case"string":case"number":J=!0;break;case"object":switch(z.$$typeof){case t:case n:J=!0;break;case f:return J=z._init,q(J(z._payload),P,U,W,Y)}}if(J)return Y=Y(z),J=W===""?"."+B(z,0):W,_(Y)?(U="",J!=null&&(U=J.replace(D,"$&/")+"/"),q(Y,P,U,"",function(oe){return oe})):Y!=null&&(R(Y)&&(Y=A(Y,U+(Y.key==null||z&&z.key===Y.key?"":(""+Y.key).replace(D,"$&/")+"/")+J)),P.push(Y)),1;J=0;var ee=W===""?".":W+":";if(_(z))for(var re=0;re<z.length;re++)W=z[re],te=ee+B(W,re),J+=q(W,P,U,te,Y);else if(re=m(z),typeof re=="function")for(z=re.call(z),re=0;!(W=z.next()).done;)W=W.value,te=ee+B(W,re++),J+=q(W,P,U,te,Y);else if(te==="object"){if(typeof z.then=="function")return q(H(z),P,U,W,Y);throw P=String(z),Error("Objects are not valid as a React child (found: "+(P==="[object Object]"?"object with keys {"+Object.keys(z).join(", ")+"}":P)+"). If you meant to render a collection of children, use an array instead.")}return J}function F(z,P,U){if(z==null)return z;var W=[],Y=0;return q(z,W,"","",function(te){return P.call(U,te,Y++)}),W}function V(z){if(z._status===-1){var P=z._result;P=P(),P.then(function(U){(z._status===0||z._status===-1)&&(z._status=1,z._result=U)},function(U){(z._status===0||z._status===-1)&&(z._status=2,z._result=U)}),z._status===-1&&(z._status=0,z._result=P)}if(z._status===1)return z._result.default;throw z._result}var M=typeof reportError=="function"?reportError:function(z){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var P=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof z=="object"&&z!==null&&typeof z.message=="string"?String(z.message):String(z),error:z});if(!window.dispatchEvent(P))return}else if(typeof e=="object"&&typeof e.emit=="function"){e.emit("uncaughtException",z);return}console.error(z)},G={map:F,forEach:function(z,P,U){F(z,function(){P.apply(this,arguments)},U)},count:function(z){var P=0;return F(z,function(){P++}),P},toArray:function(z){return F(z,function(P){return P})||[]},only:function(z){if(!R(z))throw Error("React.Children.only expected to receive a single React element child.");return z}};return Qr.Activity=h,Qr.Children=G,Qr.Component=x,Qr.Fragment=r,Qr.Profiler=a,Qr.PureComponent=k,Qr.StrictMode=s,Qr.Suspense=u,Qr.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=E,Qr.__COMPILER_RUNTIME={__proto__:null,c:function(z){return E.H.useMemoCache(z)}},Qr.cache=function(z){return function(){return z.apply(null,arguments)}},Qr.cacheSignal=function(){return null},Qr.cloneElement=function(z,P,U){if(z==null)throw Error("The argument must be a React element, but you passed "+z+".");var W=y({},z.props),Y=z.key;if(P!=null)for(te in P.key!==void 0&&(Y=""+P.key),P)!N.call(P,te)||te==="key"||te==="__self"||te==="__source"||te==="ref"&&P.ref===void 0||(W[te]=P[te]);var te=arguments.length-2;if(te===1)W.children=U;else if(1<te){for(var J=Array(te),ee=0;ee<te;ee++)J[ee]=arguments[ee+2];W.children=J}return I(z.type,Y,W)},Qr.createContext=function(z){return z={$$typeof:l,_currentValue:z,_currentValue2:z,_threadCount:0,Provider:null,Consumer:null},z.Provider=z,z.Consumer={$$typeof:i,_context:z},z},Qr.createElement=function(z,P,U){var W,Y={},te=null;if(P!=null)for(W in P.key!==void 0&&(te=""+P.key),P)N.call(P,W)&&W!=="key"&&W!=="__self"&&W!=="__source"&&(Y[W]=P[W]);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(z&&z.defaultProps)for(W in J=z.defaultProps,J)Y[W]===void 0&&(Y[W]=J[W]);return I(z,te,Y)},Qr.createRef=function(){return{current:null}},Qr.forwardRef=function(z){return{$$typeof:c,render:z}},Qr.isValidElement=R,Qr.lazy=function(z){return{$$typeof:f,_payload:{_status:-1,_result:z},_init:V}},Qr.memo=function(z,P){return{$$typeof:d,type:z,compare:P===void 0?null:P}},Qr.startTransition=function(z){var P=E.T,U={};E.T=U;try{var W=z(),Y=E.S;Y!==null&&Y(U,W),typeof W=="object"&&W!==null&&typeof W.then=="function"&&W.then(T,M)}catch(te){M(te)}finally{P!==null&&U.types!==null&&(P.types=U.types),E.T=P}},Qr.unstable_useCacheRefresh=function(){return E.H.useCacheRefresh()},Qr.use=function(z){return E.H.use(z)},Qr.useActionState=function(z,P,U){return E.H.useActionState(z,P,U)},Qr.useCallback=function(z,P){return E.H.useCallback(z,P)},Qr.useContext=function(z){return E.H.useContext(z)},Qr.useDebugValue=function(){},Qr.useDeferredValue=function(z,P){return E.H.useDeferredValue(z,P)},Qr.useEffect=function(z,P){return E.H.useEffect(z,P)},Qr.useEffectEvent=function(z){return E.H.useEffectEvent(z)},Qr.useId=function(){return E.H.useId()},Qr.useImperativeHandle=function(z,P,U){return E.H.useImperativeHandle(z,P,U)},Qr.useInsertionEffect=function(z,P){return E.H.useInsertionEffect(z,P)},Qr.useLayoutEffect=function(z,P){return E.H.useLayoutEffect(z,P)},Qr.useMemo=function(z,P){return E.H.useMemo(z,P)},Qr.useOptimistic=function(z,P){return E.H.useOptimistic(z,P)},Qr.useReducer=function(z,P,U){return E.H.useReducer(z,P,U)},Qr.useRef=function(z){return E.H.useRef(z)},Qr.useState=function(z){return E.H.useState(z)},Qr.useSyncExternalStore=function(z,P,U){return E.H.useSyncExternalStore(z,P,U)},Qr.useTransition=function(){return E.H.useTransition()},Qr.version="19.2.7",Qr}var DMe;function iI(){return DMe||(DMe=1,AX.exports=OYt()),AX.exports}var g=iI();const qe=ql(g),oI=wYt({__proto__:null,default:qe},[g]);var RX={exports:{}},wR={},PX={exports:{}},$X={};var LMe;function CYt(){return LMe||(LMe=1,(function(e){function t(H,q){var F=H.length;H.push(q);e:for(;0<F;){var V=F-1>>>1,M=H[V];if(0<s(M,q))H[V]=q,H[F]=M,F=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],F=H.pop();if(F!==q){H[0]=F;e:for(var V=0,M=H.length,G=M>>>1;V<G;){var z=2*(V+1)-1,P=H[z],U=z+1,W=H[U];if(0>s(P,F))U<M&&0>s(W,P)?(H[V]=W,H[U]=F,V=U):(H[V]=P,H[z]=F,V=z);else if(U<M&&0>s(W,F))H[V]=W,H[U]=F,V=U;else break e}}return q}function s(H,q){var F=H.sortIndex-q.sortIndex;return F!==0?F: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 O(H){if(v=!1,k(H),!m)if(n(c)!==null)m=!0,_||(_=!0,R());else{var q=n(u);q!==null&&B(O,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 F=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(O,G.startTime-H),q=!1}}break e}finally{f=null,h=F,p=!1}q=void 0}}finally{q?R():_=!1}}}var R;if(typeof w=="function")R=function(){w(A)};else if(typeof MessageChannel<"u"){var L=new MessageChannel,D=L.port2;L.port1.onmessage=A,R=function(){D.postMessage(null)}}else R=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 F=h;h=q;try{return H()}finally{h=F}},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 F=h;h=H;try{return q()}finally{h=F}},e.unstable_scheduleCallback=function(H,q,F){var V=e.unstable_now();switch(typeof F=="object"&&F!==null?(F=F.delay,F=typeof F=="number"&&0<F?V+F:V):F=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=F+M,H={id:d++,callback:q,priorityLevel:H,startTime:F,expirationTime:M,sortIndex:-1},F>V?(H.sortIndex=F,t(u,H),n(c)===null&&H===n(u)&&(v?(x(T),T=-1):v=!0,B(O,F-V))):(H.sortIndex=M,t(c,H),m||p||(m=!0,_||(_=!0,R()))),H},e.unstable_shouldYield=I,e.unstable_wrapCallback=function(H){var q=h;return function(){var F=h;h=q;try{return H.apply(this,arguments)}finally{h=F}}}})($X)),$X}var FMe;function _Yt(){return FMe||(FMe=1,PX.exports=CYt()),PX.exports}var MX={exports:{}},Au={};var zMe;function EYt(){if(zMe)return Au;zMe=1;var e=iI();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 BMe;function rut(){if(BMe)return MX.exports;BMe=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(),MX.exports=EYt(),MX.exports}var UMe;function TYt(){if(UMe)return wR;UMe=1;var e={env:{}};var t=_Yt(),n=iI(),r=rut();function s(S){var C="https://react.dev/errors/"+S;if(1<arguments.length){C+="?args[]="+encodeURIComponent(arguments[1]);for(var j=2;j<arguments.length;j++)C+="&args[]="+encodeURIComponent(arguments[j])}return"Minified React error #"+S+"; visit "+C+" 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 C=S,j=S;if(S.alternate)for(;C.return;)C=C.return;else{S=C;do C=S,(C.flags&4098)!==0&&(j=C.return),S=C.return;while(S)}return C.tag===3?j:null}function l(S){if(S.tag===13){var C=S.memoizedState;if(C===null&&(S=S.alternate,S!==null&&(C=S.memoizedState)),C!==null)return C.dehydrated}return null}function c(S){if(S.tag===31){var C=S.memoizedState;if(C===null&&(S=S.alternate,S!==null&&(C=S.memoizedState)),C!==null)return C.dehydrated}return null}function u(S){if(i(S)!==S)throw Error(s(188))}function d(S){var C=S.alternate;if(!C){if(C=i(S),C===null)throw Error(s(188));return C!==S?null:S}for(var j=S,$=C;;){var Z=j.return;if(Z===null)break;var Q=Z.alternate;if(Q===null){if($=Z.return,$!==null){j=$;continue}break}if(Z.child===Q.child){for(Q=Z.child;Q;){if(Q===j)return u(Z),S;if(Q===$)return u(Z),C;Q=Q.sibling}throw Error(s(188))}if(j.return!==$.return)j=Z,$=Q;else{for(var ie=!1,we=Z.child;we;){if(we===j){ie=!0,j=Z,$=Q;break}if(we===$){ie=!0,$=Z,j=Q;break}we=we.sibling}if(!ie){for(we=Q.child;we;){if(we===j){ie=!0,j=Q,$=Z;break}if(we===$){ie=!0,$=Q,j=Z;break}we=we.sibling}if(!ie)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:C}function f(S){var C=S.tag;if(C===5||C===26||C===27||C===6)return S;for(S=S.child;S!==null;){if(C=f(S),C!==null)return C;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"),O=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"),R=Symbol.iterator;function L(S){return S===null||typeof S!="object"?null:(S=R&&S[R]||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 O:var C=S.render;return S=S.displayName,S||(S=C.displayName||C.name||"",S=S!==""?"ForwardRef("+S+")":"ForwardRef"),S;case E:return C=S.displayName||null,C!==null?C:B(S.type)||"Memo";case N:C=S._payload,S=S._init;try{return B(S(C))}catch{}}return null}var H=Array.isArray,q=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,F=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 z(S){return{current:S}}function P(S){0>G||(S.current=M[G],M[G]=null,G--)}function U(S,C){G++,M[G]=S.current,S.current=C}var W=z(null),Y=z(null),te=z(null),J=z(null);function ee(S,C){switch(U(te,C),U(Y,S),U(W,null),C.nodeType){case 9:case 11:S=(S=C.documentElement)&&(S=S.namespaceURI)?rMe(S):0;break;default:if(S=C.tagName,C=C.namespaceURI)C=rMe(C),S=sMe(C,S);else switch(S){case"svg":S=1;break;case"math":S=2;break;default:S=0}}P(W),U(W,S)}function re(){P(W),P(Y),P(te)}function oe(S){S.memoizedState!==null&&U(J,S);var C=W.current,j=sMe(C,S.type);C!==j&&(U(Y,S),U(W,j))}function X(S){Y.current===S&&(P(W),P(Y)),J.current===S&&(P(J),gR._currentValue=V)}var ne,se;function ce(S){if(ne===void 0)try{throw Error()}catch(j){var C=j.stack.trim().match(/\n( *(at )?)/);ne=C&&C[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 ye(S,C){if(!S||le)return"";le=!0;var j=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var $={DetermineComponentFrameRoot:function(){try{if(C){var Pt=function(){throw Error()};if(Object.defineProperty(Pt.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Pt,[])}catch(vt){var ct=vt}Reflect.construct(S,[],Pt)}else{try{Pt.call()}catch(vt){ct=vt}S.call(Pt.prototype)}}else{try{throw Error()}catch(vt){ct=vt}(Pt=S())&&typeof Pt.catch=="function"&&Pt.catch(function(){})}}catch(vt){if(vt&&ct&&typeof vt.stack=="string")return[vt.stack,ct.stack]}return[null,null]}};$.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var Z=Object.getOwnPropertyDescriptor($.DetermineComponentFrameRoot,"name");Z&&Z.configurable&&Object.defineProperty($.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var Q=$.DetermineComponentFrameRoot(),ie=Q[0],we=Q[1];if(ie&&we){var We=ie.split(`
@@ -231,7 +231,7 @@ attempted value: ${i}
231
231
  \${}
232
232
  }
233
233
  }`,{label:"class",detail:"definition",type:"keyword"}),pf('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),pf('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],Zkt=COe.concat([pf("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),pf("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),pf("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),D9e=new Ywt,Gkt=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function ZR(e){return(t,n)=>{let r=t.node.getChild("VariableDefinition");return r&&n(r,e),!0}}const FVn=["FunctionDeclaration"],zVn={FunctionDeclaration:ZR("function"),ClassDeclaration:ZR("class"),ClassExpression:()=>!0,EnumDeclaration:ZR("constant"),TypeAliasDeclaration:ZR("type"),NamespaceDeclaration:ZR("namespace"),VariableDefinition(e,t){e.matchContext(FVn)||t(e,"variable")},TypeDefinition(e,t){t(e,"type")},__proto__:null};function Qkt(e,t){let n=D9e.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(qa.IncludeAnonymous).iterate(i=>{if(s)s=!1;else if(i.name){let l=zVn[i.name];if(l&&l(i,a)||Gkt.has(i.name))return!1}else if(i.to-i.from>8192){for(let l of Qkt(e,i.node))r.push(l);return!1}}),D9e.set(t,r),r}const iU=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,_Oe=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function Ykt(e){let t=yi(e.state).resolveInner(e.pos,-1);if(_Oe.indexOf(t.name)>-1)return null;let n=t.name=="VariableName"||t.to-t.from<20&&iU.test(e.state.sliceDoc(t.from,t.to));if(!n&&!e.explicit)return null;let r=[];for(let s=t;s;s=s.parent)Gkt.has(s.name)&&(r=r.concat(Qkt(e.state.doc,s)));return{options:r,from:n?t.from:e.pos,validFor:iU}}function bte(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 Kkt(e){let t=r=>e.state.doc.sliceString(r.from,r.to),n=yi(e.state).resolveInner(e.pos,-1);return n.name=="PropertyName"?bte(t,n.parent,t(n)):(n.name=="."||n.name=="?.")&&n.parent.name=="MemberExpression"?bte(t,n.parent,""):_Oe.indexOf(n.name)>-1?null:n.name=="VariableName"||n.to-n.from<20&&iU.test(t(n))?{path:[],name:t(n)}:n.name=="MemberExpression"?bte(t,n,""):e.explicit?{path:[],name:""}:null}function BVn(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 UVn(e){let t=new Map;return n=>{let r=Kkt(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=BVn(s,!r.path.length)),{from:n.pos-r.name.length,options:a,validFor:iU}}}const im=rC.define({name:"javascript",parser:LVn.configure({props:[h_.add({IfStatement:mj({except:/^\s*({|else\b)/}),TryStatement:mj({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:M7n,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:$7n({closing:"}"}),ArrowFunction:e=>e.baseIndent+e.unit,"TemplateString BlockComment":()=>null,"Statement Property":mj({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}}),p_.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":aOe,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:"$"}}),Xkt={test:e=>/^JSX/.test(e.name),facet:SW({commentTokens:{block:{open:"{/*",close:"*/}"}}})},EOe=im.configure({dialect:"ts"},"typescript"),TOe=im.configure({dialect:"jsx",props:[nOe.add(e=>e.isTop?[Xkt]:void 0)]}),jOe=im.configure({dialect:"jsx ts",props:[nOe.add(e=>e.isTop?[Xkt]:void 0)]},"typescript");let Jkt=e=>({label:e,type:"keyword"});const eOt="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(Jkt),qVn=eOt.concat(["declare","implements","private","protected","public"].map(Jkt));function oU(e={}){let t=e.jsx?e.typescript?jOe:TOe:e.typescript?EOe:im,n=e.typescript?Zkt.concat(qVn):COe.concat(eOt);return new aC(t,[im.data.of({autocomplete:wBn(_Oe,XSt(n))}),im.data.of({autocomplete:Ykt}),e.jsx?tOt:[]])}function VVn(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 L9e(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 HVn=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),tOt=Rt.inputHandler.of((e,t,n,r,s)=>{if((HVn?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=yi(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=L9e(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=VVn(f);if(p&&p.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(i.doc.sliceString(d,d+2))&&(h=L9e(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 WVn(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(ZVn(u,r.doc,c))}return s}}function F9e(e,t,n,r){return n.line(e+r.line).from+t+(e==1?r.col-1:-1)}function ZVn(e,t,n){let r=F9e(e.line,e.column,t,n),s={from:r,to:e.endLine!=null&&e.endColumn!=1?F9e(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 jF=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:tOt,completionPath:Kkt,esLint:WVn,javascript:oU,javascriptLanguage:im,jsxLanguage:TOe,localCompletionSource:Ykt,scopeCompletionSource:UVn,snippets:COe,tsxLanguage:jOe,typescriptLanguage:EOe,typescriptSnippets:Zkt},Symbol.toStringTag,{value:"Module"})),GR=["_blank","_self","_top","_parent"],xte=["ascii","utf-8","utf-16","latin1","latin1"],wte=["get","post","put","delete"],Ste=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],hh=["true","false"],Xn={},GVn={a:{attrs:{href:null,ping:null,type:null,media:null,target:GR,hreflang:null}},abbr:Xn,address:Xn,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:Xn,aside:Xn,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:Xn,base:{attrs:{href:null,target:GR}},bdi:Xn,bdo:Xn,blockquote:{attrs:{cite:null}},body:Xn,br:Xn,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:Ste,formmethod:wte,formnovalidate:["novalidate"],formtarget:GR,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:Xn,center:Xn,cite:Xn,code:Xn,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:Xn,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:Xn,div:Xn,dl:Xn,dt:Xn,em:Xn,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:Xn,figure:Xn,footer:Xn,form:{attrs:{action:null,name:null,"accept-charset":xte,autocomplete:["on","off"],enctype:Ste,method:wte,novalidate:["novalidate"],target:GR}},h1:Xn,h2:Xn,h3:Xn,h4:Xn,h5:Xn,h6:Xn,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:Xn,hgroup:Xn,hr:Xn,html:{attrs:{manifest:null}},i:Xn,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:Ste,formmethod:wte,formnovalidate:["novalidate"],formtarget:GR,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:Xn,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:Xn,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:Xn,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:xte,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:Xn,noscript:Xn,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:Xn,param:{attrs:{name:null,value:null}},pre:Xn,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:Xn,rt:Xn,ruby:Xn,samp:Xn,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:xte}},section:Xn,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:Xn,source:{attrs:{src:null,type:null,media:null}},span:Xn,strong:Xn,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:Xn,summary:Xn,sup:Xn,table:Xn,tbody:Xn,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:Xn,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:Xn,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:Xn,time:{attrs:{datetime:null}},title:Xn,tr:Xn,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:Xn,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:Xn},nOt={accesskey:null,class:null,contenteditable:hh,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:hh,autocorrect:hh,autocapitalize:hh,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":hh,"aria-autocomplete":["inline","list","both","none"],"aria-busy":hh,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":hh,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":hh,"aria-hidden":hh,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":hh,"aria-multiselectable":hh,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":hh,"aria-relevant":null,"aria-required":hh,"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},rOt="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 rOt)nOt[e]=null;class HM{constructor(t,n){this.tags={...GVn,...t},this.globalAttrs={...nOt,...n},this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}}HM.default=new HM;function lN(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 cN(e,t=!1){for(;e;e=e.parent)if(e.name=="Element")if(t)t=!1;else return e;return null}function sOt(e,t,n){let r=n.tags[lN(e,cN(t))];return r?.children||n.allTags}function NOe(e,t){let n=[];for(let r=cN(t);r&&!r.type.isTop;r=cN(r.parent)){let s=lN(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 aOt=/^[:\-\.\w\u00b7-\uffff]*$/;function z9e(e,t,n,r,s){let a=/\s*>/.test(e.sliceDoc(s,s+5))?"":">",i=cN(n,n.name=="StartTag"||n.name=="TagName");return{from:r,to:s,options:sOt(e.doc,i,t).map(l=>({label:l,type:"type"})).concat(NOe(e.doc,n).map((l,c)=>({label:"/"+l,apply:"/"+l+a,type:"type",boost:99-c}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function B9e(e,t,n,r){let s=/\s*>/.test(e.sliceDoc(r,r+5))?"":">";return{from:n,to:r,options:NOe(e.doc,t).map((a,i)=>({label:a,apply:a+s,type:"type",boost:99-i})),validFor:aOt}}function QVn(e,t,n,r){let s=[],a=0;for(let i of sOt(e.doc,n,t))s.push({label:"<"+i,type:"type"});for(let i of NOe(e.doc,n))s.push({label:"</"+i+">",type:"type",boost:99-a++});return{from:r,to:r,options:s,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function YVn(e,t,n,r,s){let a=cN(n),i=a?t.tags[lN(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:aOt}}function KVn(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=cN(n),h=f?t.tags[lN(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 iOt(e,t){let{state:n,pos:r}=t,s=yi(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)?B9e(n,s,s.from,r):z9e(n,e,s,s.from,r):s.name=="StartTag"||s.name=="IncompleteTag"?z9e(n,e,s,r,r):s.name=="StartCloseTag"||s.name=="IncompleteCloseTag"?B9e(n,s,r,r):s.name=="OpenTag"||s.name=="SelfClosingTag"||s.name=="AttributeName"?YVn(n,e,s,s.name=="AttributeName"?s.from:r,r):s.name=="Is"||s.name=="AttributeValue"||s.name=="UnquotedAttributeValue"?KVn(n,e,s,s.name=="Is"?r:s.from,r):t.explicit&&(a.name=="Element"||a.name=="Text"||a.name=="Document")?QVn(n,e,s,r):null}function XVn(e){return iOt(HM.default,e)}function JVn(e){let{extraTags:t,extraGlobalAttributes:n}=e,r=n||t?new HM(t,n):HM.default;return s=>iOt(r,s)}const eHn=im.parser.configure({top:"SingleExpression"}),oOt=[{tag:"script",attrs:e=>e.type=="text/typescript"||e.lang=="ts",parser:EOe.parser},{tag:"script",attrs:e=>e.type=="text/babel"||e.type=="text/jsx",parser:TOe.parser},{tag:"script",attrs:e=>e.type=="text/typescript-jsx",parser:jOe.parser},{tag:"script",attrs(e){return/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(e.type)},parser:eHn},{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:aU.parser}],lOt=[{name:"style",parser:aU.parser.configure({top:"Styles"})}].concat(rOt.map(e=>({name:e,parser:im.parser}))),cOt=rC.define({name:"html",parser:Cqn.configure({props:[h_.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}}),p_.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}}}),HSt.add({"OpenTag CloseTag":e=>e.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:"<!--",close:"-->"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-_"}}),d9=cOt.configure({wrap:zkt(oOt,lOt)});function tHn(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=zkt((e.nestedLanguages||[]).concat(oOt),(e.nestedAttributes||[]).concat(lOt)));let r=n?cOt.configure({wrap:n,dialect:t}):t?d9.configure({dialect:t}):d9;return new aC(r,[d9.data.of({autocomplete:JVn(e)}),e.autoCloseTags!==!1?nHn:[],oU().support,oVn().support])}const U9e=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" ")),nHn=Rt.inputHandler.of((e,t,n,r,s)=>{if(e.composing||e.state.readOnly||t!=n||r!=">"&&r!="/"||!d9.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=yi(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=lN(i.doc,y.parent,p))&&!U9e.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=lN(i.doc,y,p))&&!U9e.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)}),uOt=SW({commentTokens:{block:{open:"<!--",close:"-->"}}}),dOt=new Mr,fOt=EUn.configure({props:[p_.add(e=>!e.is("Block")||e.is("Document")||Dve(e)!=null||rHn(e)?void 0:(t,n)=>({from:n.doc.lineAt(t.from).to,to:t.to})),dOt.add(Dve),h_.add({Document:()=>null}),Fw.add({Document:uOt})]});function Dve(e){let t=/^(?:ATX|Setext)Heading(\d)$/.exec(e.name);return t?+t[1]:void 0}function rHn(e){return e.name=="OrderedList"||e.name=="BulletList"}function sHn(e,t){let n=e;for(;;){let r=n.nextSibling,s;if(!r||(s=Dve(r.type))!=null&&s<=t)break;n=r}return n.to}const aHn=RSt.of((e,t,n)=>{for(let r=yi(e).resolveInner(n,-1);r&&!(r.from<t);r=r.parent){let s=r.type.prop(dOt);if(s==null)continue;let a=sHn(r,s);if(a>n)return{from:n,to:a}}return null});function IOe(e){return new Rh(uOt,e,[],"markdown")}const hOt=IOe(fOt),iHn=fOt.configure([LUn,zUn,FUn,BUn,{props:[p_.add({Table:(e,t)=>({from:t.doc.lineAt(e.from).to,to:e.to})})]}]),lC=IOe(iHn);function oHn(e,t){return n=>{if(n&&e){let r=null;if(n=/\S*/.exec(n)[0],typeof e=="function"?r=e(n):r=vg.matchLanguageName(e,n,!0),r instanceof vg)return r.support?r.support.language.parser:sC.getSkippingParser(r.load());if(r)return r.parser}return t?t.parser:null}}class kte{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(+mOt(this.item,t)[2]+n):"";return this.spaceBefore+r+this.type+this.spaceAfter}}function pOt(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 kte(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 kte(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 kte(a.parent,c,c+d,i[1],u,f,a))}}return r}function mOt(e,t){return/^(\s*)(\d+)(?=[.)])/.exec(t.sliceString(e.from,e.from+10))}function Ote(e,t,n,r=0){for(let s=-1,a=e;;){if(a.name=="ListItem"){let l=mOt(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 AOe(e,t){let n=/^[ \t]*/.exec(e)[0].length;if(!n||t.facet(NI)!=" ")return e;let r=Hg(e,4,n),s="";for(let a=r;a>0;)a>=4?(s+=" ",a-=4):(s+=" ",a--);return s+e.slice(n)}const gOt=(e={})=>({state:t,dispatch:n})=>{let r=yi(t),{doc:s}=t,a=null,i=t.changeByRange(l=>{if(!l.empty||!lC.isActiveAt(t,l.from,-1)&&!lC.isActiveAt(t,l.from,1))return a={range:l};let c=l.from,u=s.lineAt(c),d=pOt(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,O="";w&&w.item?(k=u.from+w.from,O=w.marker(s,1)):k=u.from+(w?w.to:0);let _=[{from:k,to:c,insert:O}];return f.node.name=="OrderedList"&&Ote(f.item,s,_,-2),w&&w.node.name=="OrderedList"&&Ote(w.item,s,_),{range:St.cursor(k+O.length),changes:_}}else{let w=V9e(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"&&Ote(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?Hg(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=AOe(v,t),lHn(f.node,t.doc)&&(v=V9e(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)},vOt=gOt();function q9e(e){return e.name=="QuoteMark"||e.name=="ListMark"}function lHn(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 V9e(e,t,n){let r="";for(let s=0,a=e.length-2;s<=a;s++)r+=e[s].blank(s<a?Hg(n.text,4,e[s+1].from)-r.length:null,s<a);return AOe(r,t)}function cHn(e,t){let n=e.resolveInner(t,-1),r=t;q9e(n)&&(r=n.from,n=n.parent);for(let s;s=n.childBefore(r);)if(q9e(s))r=s.from;else if(s.name=="OrderedList"||s.name=="BulletList")n=s.lastChild,r=n.to;else break;return n}const yOt=({state:e,dispatch:t})=>{let n=yi(e),r=null,s=e.changeByRange(a=>{let i=a.from,{doc:l}=e;if(a.empty&&lC.isActiveAt(e,a.from)){let c=l.lineAt(i),u=pOt(cHn(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(Hg(c.text,4,d.to)-Hg(c.text,4,d.from));return h==c.from&&(p=AOe(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)},bOt=[{key:"Enter",run:vOt},{key:"Backspace",run:yOt}],xOt=tHn({matchClosingTags:!1});function ROe(e={}){let{codeLanguages:t,defaultCodeLanguage:n,addKeymap:r=!0,base:{parser:s}=hOt,completeHTMLTags:a=!0,pasteURLAsLink:i=!0,htmlTagLanguage:l=xOt}=e;if(!(s instanceof _W))throw new RangeError("Base parser provided to `markdown` should be a Markdown parser");let c=e.extensions?[e.extensions]:[],u=[l.support,aHn],d;i&&u.push(wOt),n instanceof aC?(u.push(n.support),d=n.language):n&&(d=n);let f=t||d?oHn(t,d):void 0;c.push(jUn({codeParser:f,htmlParser:l.language.parser})),r&&u.push(ip.high(jI.of(bOt)));let h=IOe(s.configure(c));return a&&u.push(h.data.of({autocomplete:uHn})),new aC(h,u)}function uHn(e){let{state:t,pos:n}=e,r=/<[:\-\.\w\u00b7-\uffff]*$/.exec(t.sliceDoc(n-25,n));if(!r)return null;let s=yi(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:dHn(),validFor:/^<[:\-\.\w\u00b7-\uffff]*$/}}let Cte=null;function dHn(){if(Cte)return Cte;let e=XVn(new cOe(gs.create({extensions:xOt}),0,!0));return Cte=e?e.options:[]}const fHn=/code|horizontalrule|html|link|comment|processing|escape|entity|image|mark|url/i,wOt=Rt.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),!lC.isActiveAt(t.state,r.from,1)))return!1;let a=yi(t.state),i=!1;return a.iterate({from:r.from,to:r.to,enter:l=>{(l.from>r.from||fHn.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)}}),hHn=Object.freeze(Object.defineProperty({__proto__:null,commonmarkLanguage:hOt,deleteMarkupBackward:yOt,insertNewlineContinueMarkup:vOt,insertNewlineContinueMarkupCommand:gOt,markdown:ROe,markdownKeymap:bOt,markdownLanguage:lC,pasteURLAsLink:wOt},Symbol.toStringTag,{value:"Module"}));function cC(){return cC=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},cC.apply(null,arguments)}var pHn=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=Rt.theme(i,{dark:t==="dark"}),d=Jg.define(a),f=[u,pS(d)];return f},mHn={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)"},gHn=[{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"}],AI=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 pHn({theme:r,settings:cC({},mHn,a),styles:[...gHn,...l]})};AI();function SOt(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 vHn=e=>{let{state:t}=e,n=t.doc.lineAt(t.selection.main.from),r=$Oe(e.state,n.from);return r.line?yHn(e):r.block?xHn(e):!1};function POe(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 yHn=POe(kHn,0),bHn=POe(kOt,0),xHn=POe((e,t)=>kOt(e,t,SHn(t)),0);function $Oe(e,t){let n=e.languageDataAt("commentTokens",t,1);return n.length?n[0]:{}}const QR=50;function wHn(e,{open:t,close:n},r,s){let a=e.sliceDoc(r-QR,r),i=e.sliceDoc(s,s+QR),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*QR?d=f=e.sliceDoc(r,s):(d=e.sliceDoc(r,r+QR),f=e.sliceDoc(s-QR,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 SHn(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 kOt(e,t,n=t.selection.ranges){let r=n.map(a=>$Oe(t,a.from).block);if(!r.every(a=>a))return null;let s=n.map((a,i)=>wHn(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 kHn(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=$Oe(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 Lve=qy.define(),OHn=qy.define(),CHn=kn.define(),OOt=kn.define({combine(e){return Vy(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)})}}),COt=xl.define({create(){return sy.empty},update(e,t){let n=t.state.facet(OOt),r=t.annotation(Lve);if(r){let c=If.fromTransaction(t,r.selection),u=r.side,d=u==0?e.undone:e.done;return c?d=lU(d,d.length,n.minDepth,c):d=TOt(d,t.startState.selection),new sy(u==0?r.rest:d,u==0?d:r.rest)}let s=t.annotation(OHn);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=If.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 sy(e.done.map(If.fromJSON),e.undone.map(If.fromJSON))}});function _Hn(e={}){return[COt,OOt.of(e),Rt.domEventHandlers({beforeinput(t,n){let r=t.inputType=="historyUndo"?_Ot:t.inputType=="historyRedo"?Fve:null;return r?(t.preventDefault(),r(n)):!1}})]}function EW(e,t){return function({state:n,dispatch:r}){if(!t&&n.readOnly)return!1;let s=n.field(COt,!1);if(!s)return!1;let a=s.pop(e,n,t);return a?(r(a),!0):!1}}const _Ot=EW(0,!1),Fve=EW(1,!1),EHn=EW(0,!0),THn=EW(1,!0);class If{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 If(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 If(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=Yp;for(let s of t.startState.facet(CHn)){let a=s(t);a.length&&(r=r.concat(a))}return!r.length&&t.changes.empty?null:new If(t.changes.invert(t.startState.doc),r,void 0,n||t.startState.selection,Yp)}static selection(t){return new If(void 0,Yp,void 0,void 0,t)}}function lU(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 jHn(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 NHn(e,t){return e.ranges.length==t.ranges.length&&e.ranges.filter((n,r)=>n.empty!=t.ranges[r].empty).length===0}function EOt(e,t){return e.length?t.length?e.concat(t):e:t}const Yp=[],IHn=200;function TOt(e,t){if(e.length){let n=e[e.length-1],r=n.selectionsAfter.slice(Math.max(0,n.selectionsAfter.length-IHn));return r.length&&r[r.length-1].eq(t)?e:(r.push(t),lU(e,e.length-1,1e9,n.setSelAfter(r)))}else return[If.selection([t])]}function AHn(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 _te(e,t){if(!e.length)return e;let n=e.length,r=Yp;for(;n;){let s=RHn(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?[If.selection(r)]:Yp}function RHn(e,t,n){let r=EOt(e.selectionsAfter.length?e.selectionsAfter.map(l=>l.map(t)):Yp,n);if(!e.changes)return If.selection(r);let s=e.changes.map(t),a=t.mapDesc(e.changes,!0),i=e.mapped?e.mapped.composeDesc(a):a;return new If(s,vr.mapEffects(e.effects,t),i,e.startSelection.map(a),r)}const PHn=/^(input\.type|delete)($|\.)/;class sy{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 sy(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||PHn.test(r))&&(!l.selectionsAfter.length&&n-this.prevTime<s.newGroupDelay&&s.joinToEvent(a,jHn(l.changes,t.changes))||r=="input.type.compose")?i=lU(i,i.length-1,s.minDepth,new If(t.changes.compose(l.changes),EOt(vr.mapEffects(t.effects,l.changes),l.effects),l.mapped,l.startSelection,Yp)):i=lU(i,i.length,s.minDepth,t),new sy(i,Yp,n,r)}addSelection(t,n,r,s){let a=this.done.length?this.done[this.done.length-1].selectionsAfter:Yp;return a.length>0&&n-this.prevTime<s&&r==this.prevUserEvent&&r&&/^select($|\.)/.test(r)&&NHn(a[a.length-1],t)?this:new sy(TOt(this.done,t),this.undone,n,r)}addMapping(t){return new sy(_te(this.done,t),_te(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:Lve.of({side:t,rest:AHn(s),selection:i}),userEvent:t==0?"select.undo":"select.redo",scrollIntoView:!0});if(a.changes){let l=s.length==1?Yp:s.slice(0,s.length-1);return a.mapped&&(l=_te(l,a.mapped)),n.update({changes:a.changes,selection:a.startSelection,effects:a.effects,annotations:Lve.of({side:t,rest:l,selection:i}),filter:!1,userEvent:t==0?"undo":"redo",scrollIntoView:!0})}else return null}}sy.empty=new sy(Yp,Yp);const $Hn=[{key:"Mod-z",run:_Ot,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:Fve,preventDefault:!0},{linux:"Ctrl-Shift-z",run:Fve,preventDefault:!0},{key:"Mod-u",run:EHn,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:THn,preventDefault:!0}];function RI(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=RI(e.selection,n);return r.eq(e.selection,!0)?!1:(t(ev(e,r)),!0)}function TW(e,t){return St.cursor(t?e.to:e.from)}function jOt(e,t){return tv(e,n=>n.empty?e.moveByChar(n,t):TW(n,t))}function id(e){return e.textDirectionAt(e.state.selection.main.head)==Ci.LTR}const NOt=e=>jOt(e,!id(e)),IOt=e=>jOt(e,id(e));function AOt(e,t){return tv(e,n=>n.empty?e.moveByGroup(n,t):TW(n,t))}const MHn=e=>AOt(e,!id(e)),DHn=e=>AOt(e,id(e));function LHn(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 jW(e,t,n){let r=yi(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;LHn(e,u,s)?r=u:c=n?u.to:u.from}let a=r.type.prop(s),i,l;return a&&(i=n?ry(e,r.from,1):ry(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 FHn=e=>tv(e,t=>jW(e.state,t,!id(e))),zHn=e=>tv(e,t=>jW(e.state,t,id(e)));function ROt(e,t){return tv(e,n=>{if(!n.empty)return TW(n,t);let r=e.moveVertically(n,t);return r.head!=n.head?r:e.moveToLineBoundary(n,t)})}const POt=e=>ROt(e,!1),$Ot=e=>ROt(e,!0);function MOt(e){let t=e.scrollDOM.clientHeight<e.scrollDOM.scrollHeight-2,n=0,r=0,s;if(t){for(let a of e.state.facet(Rt.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 DOt(e,t){let n=MOt(e),{state:r}=e,s=RI(r.selection,i=>i.empty?e.moveVertically(i,t,n.height):TW(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=Rt.scrollIntoView(s.main.head,{y:"start",yMargin:i.top-c}))}return e.dispatch(ev(r,s),{effects:a}),!0}const H9e=e=>DOt(e,!1),zve=e=>DOt(e,!0);function mS(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 BHn=e=>tv(e,t=>mS(e,t,!0)),UHn=e=>tv(e,t=>mS(e,t,!1)),qHn=e=>tv(e,t=>mS(e,t,!id(e))),VHn=e=>tv(e,t=>mS(e,t,id(e))),HHn=e=>tv(e,t=>St.cursor(e.lineBlockAt(t.head).from,1)),WHn=e=>tv(e,t=>St.cursor(e.lineBlockAt(t.head).to,-1));function ZHn(e,t,n){let r=!1,s=RI(e.selection,a=>{let i=ry(e,a.head,-1)||ry(e,a.head,1)||a.head>0&&ry(e,a.head-1,1)||a.head<e.doc.length&&ry(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 GHn=({state:e,dispatch:t})=>ZHn(e,t);function Lm(e,t,n){let r=RI(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 LOt(e,t){return Lm(e,t,n=>e.moveByChar(n,t))}const FOt=e=>LOt(e,!id(e)),zOt=e=>LOt(e,id(e));function BOt(e,t){return Lm(e,t,n=>e.moveByGroup(n,t))}const QHn=e=>BOt(e,!id(e)),YHn=e=>BOt(e,id(e)),KHn=e=>{let t=!id(e);return Lm(e,t,n=>jW(e.state,n,t))},XHn=e=>{let t=id(e);return Lm(e,t,n=>jW(e.state,n,t))};function UOt(e,t){return Lm(e,t,n=>e.moveVertically(n,t))}const qOt=e=>UOt(e,!1),VOt=e=>UOt(e,!0);function HOt(e,t){return Lm(e,t,n=>e.moveVertically(n,t,MOt(e).height))}const W9e=e=>HOt(e,!1),Z9e=e=>HOt(e,!0),JHn=e=>Lm(e,!0,t=>mS(e,t,!0)),eWn=e=>Lm(e,!1,t=>mS(e,t,!1)),tWn=e=>{let t=!id(e);return Lm(e,t,n=>mS(e,n,t))},nWn=e=>{let t=id(e);return Lm(e,t,n=>mS(e,n,t))},rWn=e=>Lm(e,!1,t=>St.cursor(e.lineBlockAt(t.head).from)),sWn=e=>Lm(e,!0,t=>St.cursor(e.lineBlockAt(t.head).to)),G9e=({state:e,dispatch:t})=>(t(ev(e,{anchor:0})),!0),Q9e=({state:e,dispatch:t})=>(t(ev(e,{anchor:e.doc.length})),!0),Y9e=({state:e,dispatch:t})=>(t(ev(e,{anchor:e.selection.main.anchor,head:0})),!0),K9e=({state:e,dispatch:t})=>(t(ev(e,{anchor:e.selection.main.anchor,head:e.doc.length})),!0),aWn=({state:e,dispatch:t})=>(t(e.update({selection:{anchor:0,head:e.doc.length},userEvent:"select"})),!0),iWn=({state:e,dispatch:t})=>{let n=NW(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},oWn=({state:e,dispatch:t})=>{let n=RI(e.selection,r=>{let s=yi(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 WOt(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 lWn=e=>WOt(e,!1),cWn=e=>WOt(e,!0),uWn=({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 fL(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=NF(e,c,!1)):c>i&&(n="delete.forward",c=NF(e,c,!0)),i=Math.min(i,c),l=Math.max(l,c)}else i=NF(e,i,!1),l=NF(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"?Rt.announce.of(r.phrase("Selection deleted")):void 0})),!0)}function NF(e,t,n){if(e instanceof Rt)for(let r of e.state.facet(Rt.atomicRanges).map(s=>s(e)))r.between(t,t,(s,a)=>{s<t&&a>t&&(t=n?a:s)});return t}const ZOt=(e,t,n)=>fL(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=Hg(l,a.tabSize),d=u%iC(a)||iC(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}),Bve=e=>ZOt(e,!1,!0),GOt=e=>ZOt(e,!0,!1),QOt=(e,t)=>fL(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}),YOt=e=>QOt(e,!1),dWn=e=>QOt(e,!0),fWn=e=>fL(e,t=>{let n=e.lineBlockAt(t.head).to;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),hWn=e=>fL(e,t=>{let n=e.moveToLineBoundary(t,!1).head;return t.head>n?n:Math.max(0,t.head-1)}),pWn=e=>fL(e,t=>{let n=e.moveToLineBoundary(t,!0).head;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),mWn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(r=>({changes:{from:r.from,to:r.to,insert:na.of(["",""])},range:St.cursor(r.from)}));return t(e.update(n,{scrollIntoView:!0,userEvent:"input"})),!0},gWn=({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 NW(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 KOt(e,t,n){if(e.readOnly)return!1;let r=[],s=[];for(let a of NW(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 vWn=({state:e,dispatch:t})=>KOt(e,t,!1),yWn=({state:e,dispatch:t})=>KOt(e,t,!0);function XOt(e,t,n){if(e.readOnly)return!1;let r=[];for(let a of NW(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 bWn=({state:e,dispatch:t})=>XOt(e,t,!1),xWn=({state:e,dispatch:t})=>XOt(e,t,!0),wWn=e=>{if(e.state.readOnly)return!1;let{state:t}=e,n=t.changes(NW(t).map(({from:s,to:a})=>(s>0?s--:a<t.doc.length&&a++,{from:s,to:a}))),r=RI(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 SWn(e,t){if(/\(\)|\[\]|\{\}/.test(e.sliceDoc(t-1,t+1)))return{from:t,to:t};let n=yi(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 X9e=JOt(!1),kWn=JOt(!0);function JOt(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&&SWn(t,a);e&&(a=i=(i<=l.to?l:t.doc.lineAt(i)).to);let u=new kW(t,{simulateBreak:a,simulateDoubleBreak:!!c}),d=rOe(u,a);for(d==null&&(d=Hg(/^\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=["",DM(t,d)];return c&&f.push(DM(t,u.lineIndent(l.from,-1))),{changes:{from:a,to:i,insert:na.of(f)},range:St.cursor(a+1+f[1].length)}});return n(t.update(r,{scrollIntoView:!0,userEvent:"input"})),!0}}function MOe(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 OWn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=Object.create(null),r=new kW(e,{overrideIndentation:a=>{let i=n[a];return i??-1}}),s=MOe(e,(a,i,l)=>{let c=rOe(r,a.from);if(c==null)return;/\S/.test(a.text)||(c=0);let u=/^\s*/.exec(a.text)[0],d=DM(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},eCt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(MOe(e,(n,r)=>{r.push({from:n.from,insert:e.facet(NI)})}),{userEvent:"input.indent"})),!0),tCt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(MOe(e,(n,r)=>{let s=/^\s*/.exec(n.text)[0];if(!s)return;let a=Hg(s,e.tabSize),i=0,l=DM(e,Math.max(0,a-iC(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),CWn=e=>(e.setTabFocusMode(),!0),_Wn=[{key:"Ctrl-b",run:NOt,shift:FOt,preventDefault:!0},{key:"Ctrl-f",run:IOt,shift:zOt},{key:"Ctrl-p",run:POt,shift:qOt},{key:"Ctrl-n",run:$Ot,shift:VOt},{key:"Ctrl-a",run:HHn,shift:rWn},{key:"Ctrl-e",run:WHn,shift:sWn},{key:"Ctrl-d",run:GOt},{key:"Ctrl-h",run:Bve},{key:"Ctrl-k",run:fWn},{key:"Ctrl-Alt-h",run:YOt},{key:"Ctrl-o",run:mWn},{key:"Ctrl-t",run:gWn},{key:"Ctrl-v",run:zve}],EWn=[{key:"ArrowLeft",run:NOt,shift:FOt,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:MHn,shift:QHn,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:qHn,shift:tWn,preventDefault:!0},{key:"ArrowRight",run:IOt,shift:zOt,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:DHn,shift:YHn,preventDefault:!0},{mac:"Cmd-ArrowRight",run:VHn,shift:nWn,preventDefault:!0},{key:"ArrowUp",run:POt,shift:qOt,preventDefault:!0},{mac:"Cmd-ArrowUp",run:G9e,shift:Y9e},{mac:"Ctrl-ArrowUp",run:H9e,shift:W9e},{key:"ArrowDown",run:$Ot,shift:VOt,preventDefault:!0},{mac:"Cmd-ArrowDown",run:Q9e,shift:K9e},{mac:"Ctrl-ArrowDown",run:zve,shift:Z9e},{key:"PageUp",run:H9e,shift:W9e},{key:"PageDown",run:zve,shift:Z9e},{key:"Home",run:UHn,shift:eWn,preventDefault:!0},{key:"Mod-Home",run:G9e,shift:Y9e},{key:"End",run:BHn,shift:JHn,preventDefault:!0},{key:"Mod-End",run:Q9e,shift:K9e},{key:"Enter",run:X9e,shift:X9e},{key:"Mod-a",run:aWn},{key:"Backspace",run:Bve,shift:Bve,preventDefault:!0},{key:"Delete",run:GOt,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:YOt,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:dWn,preventDefault:!0},{mac:"Mod-Backspace",run:hWn,preventDefault:!0},{mac:"Mod-Delete",run:pWn,preventDefault:!0}].concat(_Wn.map(e=>({mac:e.key,run:e.run,shift:e.shift}))),TWn=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:FHn,shift:KHn},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:zHn,shift:XHn},{key:"Alt-ArrowUp",run:vWn},{key:"Shift-Alt-ArrowUp",run:bWn},{key:"Alt-ArrowDown",run:yWn},{key:"Shift-Alt-ArrowDown",run:xWn},{key:"Mod-Alt-ArrowUp",run:lWn},{key:"Mod-Alt-ArrowDown",run:cWn},{key:"Escape",run:uWn},{key:"Mod-Enter",run:kWn},{key:"Alt-l",mac:"Ctrl-l",run:iWn},{key:"Mod-i",run:oWn,preventDefault:!0},{key:"Mod-[",run:tCt},{key:"Mod-]",run:eCt},{key:"Mod-Alt-\\",run:OWn},{key:"Shift-Mod-k",run:wWn},{key:"Shift-Mod-\\",run:GHn},{key:"Mod-/",run:vHn},{key:"Alt-A",run:bHn},{key:"Ctrl-m",mac:"Shift-Alt-m",run:CWn}].concat(EWn),jWn={key:"Tab",run:eCt,shift:tCt},J9e=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class zx{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(J9e(l)):J9e,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 Sf(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=Lke(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"&&(zx.prototype[Symbol.iterator]=function(){return this});const nCt={from:-1,to:-1,match:/.*/.exec(""),precise:!0},DOe="gm"+(/x/.unicode==null?"":"u");class rCt{constructor(t,n,r,s=0,a=t.length){if(this.text=t,this.to=a,this.curLine="",this.done=!1,this.value=nCt,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new sCt(t,n,r,s,a);this.re=new RegExp(n,DOe+(r?.ignoreCase?"i":"")),this.test=r?.test,this.iter=t.iter();let i=t.lineAt(s);this.curLineStart=i.from,this.matchPos=cU(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=cU(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 Ete=new WeakMap;class vj{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let s=Ete.get(t);if(!s||s.from>=r||s.to<=n){let l=new vj(n,t.sliceString(n,r));return Ete.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)),Ete.set(t,new vj(i,a)),new vj(n,a.slice(n-i,r-i))}}class sCt{constructor(t,n,r,s,a){this.text=t,this.to=a,this.done=!1,this.value=nCt,this.matchPos=cU(t,s),this.re=new RegExp(n,DOe+(r?.ignoreCase?"i":"")),this.test=r?.test,this.flat=vj.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=cU(this.text,s+(r==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=vj.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(rCt.prototype[Symbol.iterator]=sCt.prototype[Symbol.iterator]=function(){return this});function NWn(e){try{return new RegExp(e,DOe),!0}catch{return!1}}function cU(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 IWn=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:s}=h7n(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,Rt.scrollIntoView(v.from,{y:"center"})],selection:v})}),!0},AWn={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},RWn=kn.define({combine(e){return Vy(e,AWn,{highlightWordAroundCursor:(t,n)=>t||n,minSelectionLength:Math.min,maxMatches:Math.min})}});function PWn(e){return[FWn,LWn]}const $Wn=Tn.mark({class:"cm-selectionMatch"}),MWn=Tn.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function e7e(e,t,n,r){return(n==0||e(t.sliceDoc(n-1,n))!=bo.Word)&&(r==t.doc.length||e(t.sliceDoc(r,r+1))!=bo.Word)}function DWn(e,t,n,r){return e(t.sliceDoc(n,n+1))==bo.Word&&e(t.sliceDoc(r-1,r))==bo.Word}const LWn=ko.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(RWn),{state:n}=e,r=n.selection;if(r.ranges.length>1)return Tn.none;let s=r.main,a,i=null;if(s.empty){if(!t.highlightWordAroundCursor)return Tn.none;let c=n.wordAt(s.head);if(!c)return Tn.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 Tn.none;if(t.wholeWords){if(a=n.sliceDoc(s.from,s.to),i=n.charCategorizer(s.head),!(e7e(i,n,s.from,s.to)&&DWn(i,n,s.from,s.to)))return Tn.none}else if(a=n.sliceDoc(s.from,s.to),!a)return Tn.none}let l=[];for(let c of e.visibleRanges){let u=new zx(n.doc,a,c.from,c.to);for(;!u.next().done;){let{from:d,to:f}=u.value;if((!i||e7e(i,n,d,f))&&(s.empty&&d<=s.from&&f>=s.to?l.push(MWn.range(d,f)):(d>=s.to||f<=s.from)&&l.push($Wn.range(d,f)),l.length>t.maxMatches))return Tn.none}}return Tn.set(l)}},{decorations:e=>e.decorations}),FWn=Rt.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),zWn=({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 BWn(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 zx(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(i)return null;l=new zx(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 UWn=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(a=>a.from===a.to))return zWn({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=BWn(e,r);return s?(t(e.update({selection:e.selection.addRange(St.range(s.from,s.to),!1),effects:Rt.scrollIntoView(s.to)})),!0):!1},PI=kn.define({combine(e){return Vy(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new nZn(t),scrollToMatch:t=>Rt.scrollIntoView(t)})}});class aCt{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||NWn(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 GWn(this):new HWn(this)}getCursor(t,n=0,r){let s=t.doc?t:gs.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?uT(this,s,n,r):cT(this,s,n,r)}}class iCt{constructor(t){this.spec=t}}function qWn(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 cT(e,t,n,r){let s;return e.wholeWord&&(s=VWn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=qWn(e.test,t,s)),new zx(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function VWn(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(uU(s,n-a))!=bo.Word||t(dU(s,n-a))!=bo.Word)&&(t(dU(s,r-a))!=bo.Word||t(uU(s,r-a))!=bo.Word))}class HWn extends iCt{constructor(t){super(t)}nextMatch(t,n,r){let s=cT(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=cT(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=cT(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=cT(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=cT(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 WWn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function uT(e,t,n,r){let s;return e.wholeWord&&(s=ZWn(t.charCategorizer(t.selection.main.head))),e.test&&(s=WWn(e.test,t,s)),new rCt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function uU(e,t){return e.slice(Ac(e,t,!1),t)}function dU(e,t){return e.slice(t,Ac(e,t))}function ZWn(e){return(t,n,r)=>!r[0].length||(e(uU(r.input,r.index))!=bo.Word||e(dU(r.input,r.index))!=bo.Word)&&(e(dU(r.input,r.index+r[0].length))!=bo.Word||e(uU(r.input,r.index+r[0].length))!=bo.Word)}class GWn extends iCt{nextMatch(t,n,r){let s=uT(this.spec,t,r,t.doc.length).next();return s.done&&(s=uT(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=uT(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=uT(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=uT(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 WM=vr.define(),LOe=vr.define(),t1=xl.define({create(e){return new Tte(Uve(e).create(),null)},update(e,t){for(let n of t.effects)n.is(WM)?e=new Tte(n.value.create(),e.panel):n.is(LOe)&&(e=new Tte(e.query,n.value?FOe:null));return e},provide:e=>MM.from(e,t=>t.panel)});class Tte{constructor(t,n){this.query=t,this.panel=n}}const QWn=Tn.mark({class:"cm-searchMatch"}),YWn=Tn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),KWn=ko.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(t1))}update(e){let t=e.state.field(t1);(t!=e.startState.field(t1)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return Tn.none;let{view:n}=this,r=new nd;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?YWn:QWn)})}return r.finish()}},{decorations:e=>e.decorations});function hL(e){return t=>{let n=t.state.field(t1,!1);return n&&n.query.spec.valid?e(t,n):cCt(t)}}const fU=hL((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(PI);return e.dispatch({selection:s,effects:[zOe(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),lCt(e),!0}),hU=hL((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(PI);return e.dispatch({selection:a,effects:[zOe(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),lCt(e),!0}),XWn=hL((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)}),JWn=({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 zx(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},t7e=hL((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(Rt.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(zOe(e,i)),d.push(n.facet(PI).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),eZn=hL((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:Rt.announce.of(r),userEvent:"input.replace.all"}),!0});function FOe(e){return e.state.facet(PI).createPanel(e)}function Uve(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(PI);return new aCt({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 oCt(e){let t=tOe(e,FOe);return t&&t.dom.querySelector("[main-field]")}function lCt(e){let t=oCt(e);t&&t==e.root.activeElement&&t.select()}const cCt=e=>{let t=e.state.field(t1,!1);if(t&&t.panel){let n=oCt(e);if(n&&n!=e.root.activeElement){let r=Uve(e.state,t.query.spec);r.valid&&e.dispatch({effects:WM.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[LOe.of(!0),t?WM.of(Uve(e.state,t.query.spec)):vr.appendConfig.of(sZn)]});return!0},uCt=e=>{let t=e.state.field(t1,!1);if(!t||!t.panel)return!1;let n=tOe(e,FOe);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:LOe.of(!1)}),!0},tZn=[{key:"Mod-f",run:cCt,scope:"editor search-panel"},{key:"F3",run:fU,shift:hU,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:fU,shift:hU,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:uCt,scope:"editor search-panel"},{key:"Mod-Shift-l",run:JWn},{key:"Mod-Alt-g",run:IWn},{key:"Mod-d",run:UWn,preventDefault:!0}];class nZn{constructor(t){this.view=t;let n=this.query=t.state.field(t1).query.spec;this.commit=this.commit.bind(this),this.searchField=hi("input",{value:n.search,placeholder:ph(t,"Find"),"aria-label":ph(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=hi("input",{value:n.replace,placeholder:ph(t,"Replace"),"aria-label":ph(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=hi("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=hi("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=hi("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return hi("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=hi("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>fU(t),[ph(t,"next")]),r("prev",()=>hU(t),[ph(t,"previous")]),r("select",()=>XWn(t),[ph(t,"all")]),hi("label",null,[this.caseField,ph(t,"match case")]),hi("label",null,[this.reField,ph(t,"regexp")]),hi("label",null,[this.wordField,ph(t,"by word")]),...t.state.readOnly?[]:[hi("br"),this.replaceField,r("replace",()=>t7e(t),[ph(t,"replace")]),r("replaceAll",()=>eZn(t),[ph(t,"replace all")])],hi("button",{name:"close",onclick:()=>uCt(t),"aria-label":ph(t,"close"),type:"button"},["×"])])}commit(){let t=new aCt({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:WM.of(t)}))}keydown(t){k9n(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?hU:fU)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),t7e(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(WM)&&!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(PI).top}}function ph(e,t){return e.state.phrase(t)}const IF=30,AF=/[\s\.,:;?!]/;function zOe(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-IF),i=Math.min(s,n+IF),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<IF;c++)if(!AF.test(l[c+1])&&AF.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-IF;c--)if(!AF.test(l[c-1])&&AF.test(l[c])){l=l.slice(0,c);break}}return Rt.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const rZn=Rt.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"}}),sZn=[t1,ip.low(KWn),rZn];class n7e{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class Fk{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(ZM).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new nd,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=vZn(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,Tn.widget({widget:new hZn(m),diagnostics:l.slice()}));else{let v=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(h,p,Tn.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 Fk(u,n,uN(u))}}function uN(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 n7e(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new n7e(r.from,a,r.diagnostic)}}),r}function aZn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(ZM).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(dCt))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function iZn(e,t){return e.field(Ph,!1)?t:t.concat(vr.appendConfig.of(yZn))}const dCt=vr.define(),BOe=vr.define(),fCt=vr.define(),Ph=xl.define({create(){return new Fk(Tn.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=uN(n,e.selected.diagnostic,a)||uN(n,null,a)}!n.size&&s&&t.state.facet(ZM).autoPanel&&(s=null),e=new Fk(n,s,r)}for(let n of t.effects)if(n.is(dCt)){let r=t.state.facet(ZM).autoPanel?n.value.length?GM.open:null:e.panel;e=Fk.init(n.value,r,t.state)}else n.is(BOe)?e=new Fk(e.diagnostics,n.value?GM.open:null,e.selected):n.is(fCt)&&(e=new Fk(e.diagnostics,e.panel,n.value));return e},provide:e=>[MM.from(e,t=>t.panel),Rt.decorations.from(e,t=>t.diagnostics)]}),oZn=Tn.mark({class:"cm-lintRange cm-lintRange-active"});function lZn(e,t,n){let{diagnostics:r}=e.state.field(Ph),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(ZM).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:cZn(e,s)}}}:null}function cZn(e,t){return hi("ul",{class:"cm-tooltip-lint"},t.map(n=>pCt(e,n,!1)))}const uZn=e=>{let t=e.state.field(Ph,!1);(!t||!t.panel)&&e.dispatch({effects:iZn(e.state,[BOe.of(!0)])});let n=tOe(e,GM.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},r7e=e=>{let t=e.state.field(Ph,!1);return!t||!t.panel?!1:(e.dispatch({effects:BOe.of(!1)}),!0)},dZn=e=>{let t=e.state.field(Ph,!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)},fZn=[{key:"Mod-Shift-m",run:uZn,preventDefault:!0},{key:"F8",run:dZn}],ZM=kn.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...Vy(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:s7e,tooltipFilter:s7e,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 s7e(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function hCt(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 pCt(e,t,n){var r;let s=n?hCt(t.actions):[];return hi("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},hi("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=uN(e.state.field(Ph).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),hi("u",u.slice(d,d+1)),u.slice(d+1)],h=a.markClass?" "+a.markClass:"";return hi("button",{type:"button",class:"cm-diagnosticAction"+h,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&hi("div",{class:"cm-diagnosticSource"},t.source))}class hZn extends op{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return hi("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class a7e{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=pCt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class GM{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)r7e(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=hCt(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=uN(this.view.state.field(Ph).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=hi("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=hi("div",{class:"cm-panel-lint"},this.list,hi("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>r7e(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Ph).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(Ph),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 a7e(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 a7e(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(Ph),r=uN(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:fCt.of(r)})}static open(t){return new GM(t)}}function pZn(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 RF(e){return pZn(`<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 mZn=Rt.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:RF("#d11")},".cm-lintRange-warning":{backgroundImage:RF("orange")},".cm-lintRange-info":{backgroundImage:RF("#999")},".cm-lintRange-hint":{backgroundImage:RF("#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 gZn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function vZn(e){let t="hint",n=1;for(let r of e){let s=gZn(r.severity);s>n&&(n=s,t=r.severity)}return t}const yZn=[Ph,Rt.decorations.compute([Ph],e=>{let{selected:t,panel:n}=e.field(Ph);return!t||!n||t.from==t.to?Tn.none:Tn.set([oZn.range(t.from,t.to)])}),d7n(lZn,{hideOn:aZn}),mZn];var i7e=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(oUn)),t.defaultKeymap!==!1&&(a=a.concat(TWn)),t.searchKeymap!==!1&&(a=a.concat(tZn)),t.historyKeymap!==!1&&(a=a.concat($Hn)),t.foldKeymap!==!1&&(a=a.concat(W7n)),t.completionKeymap!==!1&&(a=a.concat(lkt)),t.lintKeymap!==!1&&(a=a.concat(fZn));var i=[];return t.lineNumbers!==!1&&i.push(jSt()),t.highlightActiveLineGutter!==!1&&i.push(C7n()),t.highlightSpecialChars!==!1&&i.push(F9n()),t.history!==!1&&i.push(_Hn()),t.foldGutter!==!1&&i.push(Y7n()),t.drawSelection!==!1&&i.push(j9n()),t.dropCursor!==!1&&i.push(P9n()),t.allowMultipleSelections!==!1&&i.push(gs.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(L7n()),t.syntaxHighlighting!==!1&&i.push(pS(eBn,{fallback:!0})),t.bracketMatching!==!1&&i.push(oBn()),t.closeBrackets!==!1&&i.push(rUn()),t.autocompletion!==!1&&i.push(okt()),t.rectangularSelection!==!1&&i.push(J9n()),s!==!1&&i.push(n7n()),t.highlightActiveLine!==!1&&i.push(H9n()),t.highlightSelectionMatches!==!1&&i.push(PWn()),t.tabSize&&typeof t.tabSize=="number"&&i.push(NI.of(" ".repeat(t.tabSize))),i.concat([jI.of(a.flat())]).filter(Boolean)};const bZn="#e5c07b",o7e="#e06c75",xZn="#56b6c2",wZn="#ffffff",f9="#abb2bf",qve="#7d8799",SZn="#61afef",kZn="#98c379",l7e="#d19a66",OZn="#c678dd",CZn="#21252b",c7e="#2c313a",u7e="#282c34",jte="#353a42",_Zn="#3E4451",d7e="#528bff",EZn=Rt.theme({"&":{color:f9,backgroundColor:u7e},".cm-content":{caretColor:d7e},".cm-cursor, .cm-dropCursor":{borderLeftColor:d7e},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:_Zn},".cm-panels":{backgroundColor:CZn,color:f9},".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:u7e,color:qve,border:"none"},".cm-activeLineGutter":{backgroundColor:c7e},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:jte},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:jte,borderBottomColor:jte},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:c7e,color:f9}}},{dark:!0}),TZn=Jg.define([{tag:ue.keyword,color:OZn},{tag:[ue.name,ue.deleted,ue.character,ue.propertyName,ue.macroName],color:o7e},{tag:[ue.function(ue.variableName),ue.labelName],color:SZn},{tag:[ue.color,ue.constant(ue.name),ue.standard(ue.name)],color:l7e},{tag:[ue.definition(ue.name),ue.separator],color:f9},{tag:[ue.typeName,ue.className,ue.number,ue.changed,ue.annotation,ue.modifier,ue.self,ue.namespace],color:bZn},{tag:[ue.operator,ue.operatorKeyword,ue.url,ue.escape,ue.regexp,ue.link,ue.special(ue.string)],color:xZn},{tag:[ue.meta,ue.comment],color:qve},{tag:ue.strong,fontWeight:"bold"},{tag:ue.emphasis,fontStyle:"italic"},{tag:ue.strikethrough,textDecoration:"line-through"},{tag:ue.link,color:qve,textDecoration:"underline"},{tag:ue.heading,fontWeight:"bold",color:o7e},{tag:[ue.atom,ue.bool,ue.special(ue.variableName)],color:l7e},{tag:[ue.processingInstruction,ue.string,ue.inserted],color:kZn},{tag:ue.invalid,color:wZn}]),jZn=[EZn,pS(TZn)];var NZn=Rt.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),IZn=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(jI.of([jWn])),m&&(typeof m=="boolean"?v.unshift(i7e()):v.unshift(i7e(m))),h&&v.unshift(Q9n(h)),d){case"light":v.push(NZn);break;case"dark":v.push(jZn);break;case"none":break;default:v.push(d);break}return i===!1&&v.push(Rt.editable.of(!1)),c&&v.push(gs.readOnly.of(!0)),[...v]},AZn=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 RZn{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 f7e{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 Nte=null,PZn=()=>typeof window>"u"?new f7e:(Nte||(Nte=new f7e),Nte),$Zn=Rt.theme({"& .cm-scroller":{height:"100% !important"}}),h7e=null,Ite=null;function MZn(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===h7e||(h7e=i,Ite=Rt.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a}})),Ite}var p7e=qy.define(),DZn=200,LZn=[];function FZn(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?LZn: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,O=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,R=e.readOnly,L=R===void 0?!1:R,D=e.indentWithTab,B=D===void 0?!0:D,H=e.basicSetup,q=H===void 0?!0:H,F=e.root,V=e.initialState,M=g.useState(),G=M[0],z=M[1],P=g.useState(),U=P[0],W=P[1],Y=g.useState(),te=Y[0],J=Y[1],ee=g.useState(()=>({current:null}))[0],re=g.useState(()=>({current:null}))[0],oe=MZn(p,v,b,w,O,T),X=Rt.updateListener.of(ce=>{if(ce.docChanged&&typeof r=="function"&&!ce.transactions.some(he=>he.annotation(p7e))){ee.current?ee.current.reset():(ee.current=new RZn(()=>{if(re.current){var he=re.current;re.current=null,he()}ee.current=null},DZn),PZn().add(ee.current));var le=ce.state.doc,ye=le.toString();r(ye,ce)}s&&s(AZn(ce))}),ne=IZn({theme:f,editable:A,readOnly:L,placeholder:N,indentWithTab:B,basicSetup:q}),se=[X,...oe?[oe]:[],$Zn,...ne];return i&&typeof i=="function"&&se.push(Rt.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 ye=new Rt({state:le,parent:G,root:F});W(ye),a&&a(ye,le)}}return()=>{U&&(J(void 0),W(void 0))}},[G,te]),g.useEffect(()=>{e.container&&z(e.container)},[e.container]),g.useEffect(()=>()=>{U&&(U.destroy(),W(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,O,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,ye=()=>{U&&t!==U.state.doc.toString()&&U.dispatch({changes:{from:0,to:U.state.doc.toString().length,insert:t||""},annotations:[p7e.of(!0)]})};le?re.current=ye:ye()}}},[t,U]),{state:te,setState:J,view:U,setView:W,container:G,setContainer:z}}var zZn=["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,O=e.basicSetup,_=e.placeholder,T=e.indentWithTab,E=e.editable,N=e.readOnly,I=e.root,A=e.initialState,R=SOt(e,zZn),L=g.useRef(null),D=FZn({root:I,value:s,autoFocus:h,theme:m,height:v,minHeight:y,maxHeight:b,width:x,minWidth:w,maxWidth:k,basicSetup:O,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,F=D.setContainer;g.useImperativeHandle(t,()=>({editor:L.current,state:B,view:H}),[L,q,B,H]);var V=g.useCallback(G=>{L.current=G,F(G)},[F]);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",cC({ref:V,className:""+M+(n?" "+n:"")},R))});rd.displayName="CodeMirror";const mCt={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 Ate=null;function BZn(){return Ate||(Ate=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Ua(()=>import("./core-K44HqE7F.js"),__vite__mapDeps([0,1,2]),import.meta.url),Ua(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[Ua(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Ua(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Ua(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Ua(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Ua(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Ua(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Ua(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Ua(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Ua(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Ua(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Ua(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Ua(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Ua(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Ua(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([4,5,6]),import.meta.url),Ua(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Ua(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),Ate}async function UZn(e,t){const n=mCt[t?.toLowerCase()];if(!n)return null;const r=await BZn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function qZn(e){const t=e?.split(".").pop()?.toLowerCase();return t?mCt[t]:void 0}function VZn(e){return new aC(iOe.define(e))}const gCt=[vg.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return Ua(()=>Promise.resolve().then(()=>jF),void 0,import.meta.url).then(e=>e.javascript())}}),vg.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return Ua(()=>Promise.resolve().then(()=>bBn),void 0,import.meta.url).then(e=>e.json())}}),vg.of({name:"JSX",extensions:["jsx"],load(){return Ua(()=>Promise.resolve().then(()=>jF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),vg.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return Ua(()=>Promise.resolve().then(()=>hHn),void 0,import.meta.url).then(e=>e.markdown())}}),vg.of({name:"TSX",extensions:["tsx"],load(){return Ua(()=>Promise.resolve().then(()=>jF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),vg.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return Ua(()=>Promise.resolve().then(()=>jF),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),vg.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return Ua(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>VZn(e.shell))}})];function HZn(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 WZn(e){const t=HZn(e);return okt({override:[ZZn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function ZZn(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 GZn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,QZn=Tn.mark({class:"cm-variable-highlight"}),m7e=new xSt({regexp:GZn,decoration:()=>QZn}),YZn=ko.fromClass(class{decorations;constructor(e){this.decorations=m7e.createDeco(e)}update(e){this.decorations=m7e.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),KZn=YZn;function XZn(){const e=AI({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=Rt.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 JZn(){const e=Rt.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,pS(t)]}const c0=()=>{const e=d_().resolvedTheme==="dark";return g.useMemo(()=>e?XZn():JZn(),[e])},eGn=oo(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"}}),tGn=ip.highest(Rt.editorAttributes.of({style:"outline: none"})),nGn=ip.highest(Rt.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),rGn=[tGn,nGn],Hr=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=c0(),b=e?JSON.stringify(e,null,2):t??"",x=g.useMemo(()=>{const w=[...rGn];return f&&w.push(Rt.lineWrapping),a==="json"?w.push(Bh):a==="markdown"&&w.push(ROe({base:lC,codeLanguages:gCt})),i&&a==="markdown"&&w.push(KZn),c&&a==="markdown"&&w.push(WZn(c)),h===!1&&w.push(gs.readOnly.of(!0)),w},[a,i,c,h,f]);return o.jsxs("div",{className:K(eGn({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}})]})}),sGn=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},aGn=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=c0(),{settings:r,setSettings:s}=nW(),a=r?.tracingOptions,i=g.useMemo(()=>sGn(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(me,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),o.jsx(rd,{value:l,onChange:d,theme:n,extensions:[Bh],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(ae,{type:"button",onClick:f,children:"Save"})})]})},iGn=()=>{const[e,t]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(bn,{children:[o.jsx(mn,{asChild:!0,children:o.jsx(ae,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(Ke,{children:o.jsx(Q0e,{})})})}),o.jsx(gn,{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(Ts,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx(Nr,{children:o.jsx(aGn,{onSaved:()=>t(!1)})})]})})]})};function oGn({status:e}){switch(e){case"running":return o.jsx(Ht,{});case"failed":return o.jsx(tr,{className:"text-accent2"});case"canceled":return o.jsx(Cs,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(c1,{className:"text-neutral3"});case"suspended":return o.jsx(BV,{className:"text-accent3"});case"success":return o.jsx(Dr,{className:"text-accent1"});default:return o.jsx(c1,{className:"text-neutral3"})}}function vCt({status:e}){return o.jsxs(bn,{children:[o.jsx(mn,{asChild:!0,children:o.jsx(Ke,{"aria-label":e,className:"shrink-0",children:o.jsx(oGn,{status:e})})}),o.jsx(gn,{children:e})]})}var Rte,g7e;function UOe(){if(g7e)return Rte;g7e=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 Rte=r,Rte}var Pte,v7e;function lGn(){return v7e||(v7e=1,Pte="2.2.4"),Pte}var $te,y7e;function cGn(){return y7e||(y7e=1,$te={Graph:UOe(),version:lGn()}),$te}var Mte,b7e;function uGn(){if(b7e)return Mte;b7e=1;var e=UOe();Mte={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 Mte}var Dte,x7e;function dGn(){if(x7e)return Dte;x7e=1,Dte=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 Dte}var Lte,w7e;function yCt(){if(w7e)return Lte;w7e=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 Lte=e,Lte}var Fte,S7e;function bCt(){if(S7e)return Fte;S7e=1;var e=yCt();Fte=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 Fte}var zte,k7e;function fGn(){if(k7e)return zte;k7e=1;var e=bCt();zte=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return zte}var Bte,O7e;function xCt(){if(O7e)return Bte;O7e=1,Bte=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 Bte}var Ute,C7e;function hGn(){if(C7e)return Ute;C7e=1;var e=xCt();Ute=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return Ute}var qte,_7e;function pGn(){if(_7e)return qte;_7e=1,qte=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 qte}var Vte,E7e;function wCt(){if(E7e)return Vte;E7e=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 Vte=e,e.CycleException=t,Vte}var Hte,T7e;function mGn(){if(T7e)return Hte;T7e=1;var e=wCt();Hte=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return Hte}var Wte,j7e;function SCt(){if(j7e)return Wte;j7e=1,Wte=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 Wte}var Zte,N7e;function gGn(){if(N7e)return Zte;N7e=1;var e=SCt();Zte=t;function t(n,r){return e(n,r,"post")}return Zte}var Gte,I7e;function vGn(){if(I7e)return Gte;I7e=1;var e=SCt();Gte=t;function t(n,r){return e(n,r,"pre")}return Gte}var Qte,A7e;function yGn(){if(A7e)return Qte;A7e=1;var e=UOe(),t=yCt();Qte=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 Qte}var Yte,R7e;function bGn(){return R7e||(R7e=1,Yte={components:dGn(),dijkstra:bCt(),dijkstraAll:fGn(),findCycles:hGn(),floydWarshall:pGn(),isAcyclic:mGn(),postorder:gGn(),preorder:vGn(),prim:yGn(),tarjan:xCt(),topsort:wCt()}),Yte}var Kte,P7e;function Zg(){if(P7e)return Kte;P7e=1;var e=cGn();return Kte={Graph:e.Graph,json:uGn(),alg:bGn(),version:e.version},Kte}var Xte,$7e;function xGn(){if($7e)return Xte;$7e=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 Xte=e,Xte}var Jte,M7e;function wGn(){if(M7e)return Jte;M7e=1;let e=Zg().Graph,t=xGn();Jte=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 Jte}var ene,D7e;function Pl(){if(D7e)return ene;D7e=1;let e=Zg().Graph;ene={addBorderNode:d,addDummyNode:t,applyWithChunking:p,asNonCompoundGraph:r,buildLayerMatrix:l,intersectRect:i,mapValues:_,maxRank:m,normalizeRanks:c,notime:b,partition:v,pick:O,predecessorWeights:a,range:k,removeEmptyRanks:u,simplify:n,successorWeights:s,time:y,uniqueId:w,zipObject:T};function t(E,N,I,A){for(var R=A;E.hasNode(R);)R=w(A);return I.dummy=N,E.setNode(R,I),R}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},R=E.edge(I);N.setEdge(I.v,I.w,{weight:A.weight+R.weight,minlen:Math.max(A.minlen,R.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(R=>{A[R.w]=(A[R.w]||0)+E.edge(R).weight}),A});return T(E.nodes(),N)}function a(E){let N=E.nodes().map(I=>{let A={};return E.inEdges(I).forEach(R=>{A[R.v]=(A[R.v]||0)+E.edge(R).weight}),A});return T(E.nodes(),N)}function i(E,N){let I=E.x,A=E.y,R=N.x-I,L=N.y-A,D=E.width/2,B=E.height/2;if(!R&&!L)throw new Error("Not possible to find intersection inside of the rectangle");let H,q;return Math.abs(L)*D>Math.abs(R)*B?(L<0&&(B=-B),H=B*R/L,q=B):(R<0&&(D=-D),H=D,q=D*L/R),{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),R=A.rank;R!==void 0&&(N[R][A.order]=I)}),N}function c(E){let N=E.nodes().map(A=>{let R=E.node(A).rank;return R===void 0?Number.MAX_VALUE:R}),I=p(Math.min,N);E.nodes().forEach(A=>{let R=E.node(A);Object.hasOwn(R,"rank")&&(R.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 R=0,L=E.graph().nodeRankFactor;Array.from(A).forEach((D,B)=>{D===void 0&&B%L!==0?--R:D!==void 0&&R&&D.forEach(H=>E.node(H).rank+=R)})}function d(E,N,I,A){let R={width:0,height:0};return arguments.length>=4&&(R.rank=I,R.order=A),t(E,"border",R,N)}function f(E,N=h){const I=[];for(let A=0;A<E.length;A+=N){const R=E.slice(A,A+N);I.push(R)}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 R=E.node(A).rank;return R===void 0?Number.MIN_VALUE:R});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 R=[];for(let L=E;A(L);L+=I)R.push(L);return R}function O(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,[R,L])=>(A[R]=I(L,R),A),{})}function T(E,N){return E.reduce((I,A,R)=>(I[A]=N[R],I),{})}return ene}var tne,L7e;function SGn(){if(L7e)return tne;L7e=1;let e=wGn(),t=Pl().uniqueId;tne={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 tne}var nne,F7e;function kGn(){if(F7e)return nne;F7e=1;let e=Pl();nne={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 nne}var rne,z7e;function pU(){if(z7e)return rne;z7e=1;const{applyWithChunking:e}=Pl();rne={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 rne}var sne,B7e;function kCt(){if(B7e)return sne;B7e=1;var e=Zg().Graph,t=pU().slack;sne=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 sne}var ane,U7e;function OGn(){if(U7e)return ane;U7e=1;var e=kCt(),t=pU().slack,n=pU().longestPath,r=Zg().alg.preorder,s=Zg().alg.postorder,a=Pl().simplify;ane=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,O;k=h(w);)O=p(w,x,k),m(w,x,k,O)}function l(x,w){var k=s(x,x.nodes());k=k.slice(0,k.length-1),k.forEach(O=>c(x,w,O))}function c(x,w,k){var O=x.node(k),_=O.parent;x.edge(k,_).cutvalue=u(x,w,k)}function u(x,w,k){var O=x.node(k),_=O.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,R=A?I.w:I.v;if(R!==_){var L=A===T,D=w.edge(I).weight;if(N+=L?D:-D,y(x,k,R)){var B=x.edge(k,R).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,O,_){var T=k,E=x.node(O);return w[O]=!0,x.neighbors(O).forEach(N=>{Object.hasOwn(w,N)||(k=f(x,w,k,N,O))}),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 O=k.v,_=k.w;w.hasEdge(O,_)||(O=k.w,_=k.v);var T=x.node(O),E=x.node(_),N=T,I=!1;T.lim>E.lim&&(N=E,I=!0);var A=w.edges().filter(R=>I===b(x,x.node(R.v),N)&&I!==b(x,x.node(R.w),N));return A.reduce((R,L)=>t(w,L)<t(w,R)?L:R)}function m(x,w,k,O){var _=k.v,T=k.w;x.removeEdge(_,T),x.setEdge(O.v,O.w,{}),d(x),l(x,w),v(x,w)}function v(x,w){var k=x.nodes().find(_=>!w.node(_).parent),O=r(x,k);O=O.slice(1),O.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 ane}var ine,q7e;function CGn(){if(q7e)return ine;q7e=1;var e=pU(),t=e.longestPath,n=kCt(),r=OGn();ine=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 ine}var one,V7e;function _Gn(){if(V7e)return one;V7e=1,one=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 one}var lne,H7e;function EGn(){if(H7e)return lne;H7e=1;let e=Pl();lne={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,O=x.borderTop?u:2*u,_=w!==k?1:d-f[h]+1;i.setEdge(m,w,{weight:O,minlen:_,nestingEdge:!0}),i.setEdge(k,v,{weight:O,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 lne}var cne,W7e;function TGn(){if(W7e)return cne;W7e=1;let e=Pl();cne=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 cne}var une,Z7e;function jGn(){if(Z7e)return une;Z7e=1,une={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 une}var dne,G7e;function NGn(){if(G7e)return dne;G7e=1;let e=Pl();dne=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 dne}var fne,Q7e;function IGn(){if(Q7e)return fne;Q7e=1;let e=Pl().zipObject;fne=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 fne}var hne,Y7e;function AGn(){if(Y7e)return hne;Y7e=1,hne=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 hne}var pne,K7e;function RGn(){if(K7e)return pne;K7e=1;let e=Pl();pne=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 pne}var mne,X7e;function PGn(){if(X7e)return mne;X7e=1;let e=Pl();mne=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 mne}var gne,J7e;function $Gn(){if(J7e)return gne;J7e=1;let e=AGn(),t=RGn(),n=PGn();gne=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 gne}var vne,eBe;function MGn(){if(eBe)return vne;eBe=1;let e=Zg().Graph,t=Pl();vne=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 vne}var yne,tBe;function DGn(){if(tBe)return yne;tBe=1,yne=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 yne}var bne,nBe;function LGn(){if(nBe)return bne;nBe=1;let e=NGn(),t=IGn(),n=$Gn(),r=MGn(),s=DGn(),a=Zg().Graph,i=Pl();bne=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 O=t(f,y);O<b&&(k=0,x=Object.assign({},y),b=O)}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 bne}var xne,rBe;function FGn(){if(rBe)return xne;rBe=1;let e=Zg().Graph,t=Pl();xne={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,O){let _=0,T=0,E=k.length,N=O[O.length-1];return O.forEach((I,A)=>{let R=s(y,I),L=R?y.node(R).order:E;(R||I===N)&&(O.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)}),O}return b.length&&b.reduce(w),x}function r(y,b){let x={};function w(O,_,T,E,N){let I;t.range(_,T).forEach(A=>{I=O[A],y.node(I).dummy&&y.predecessors(I).forEach(R=>{let L=y.node(R);L.dummy&&(L.order<E||L.order>N)&&a(x,R,I)})})}function k(O,_){let T=-1,E,N=0;return _.forEach((I,A)=>{if(y.node(I).dummy==="border"){let R=y.predecessors(I);R.length&&(E=y.node(R[0]).order,w(_,N,A,T,E),N=A,T=E)}w(_,N,_.length,E,O.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={},O={},_={};return b.forEach(T=>{T.forEach((E,N)=>{k[E]=E,O[E]=E,_[E]=N})}),b.forEach(T=>{let E=-1;T.forEach(N=>{let I=w(N);if(I.length){I=I.sort((R,L)=>_[R]-_[L]);let A=(I.length-1)/2;for(let R=Math.floor(A),L=Math.ceil(A);R<=L;++R){let D=I[R];O[N]===N&&E<_[D]&&!i(x,N,D)&&(O[D]=N,O[N]=k[N]=k[D],E=_[D])}}})}),{root:k,align:O}}function c(y,b,x,w,k){let O={},_=u(y,b,x,k),T=k?"borderLeft":"borderRight";function E(A,R){let L=_.nodes(),D=L.pop(),B={};for(;D;)B[D]?A(D):(B[D]=!0,L.push(D),L=L.concat(R(D))),D=L.pop()}function N(A){O[A]=_.inEdges(A).reduce((R,L)=>Math.max(R,O[L.v]+_.edge(L)),0)}function I(A){let R=_.outEdges(A).reduce((D,B)=>Math.min(D,O[B.w]-_.edge(B)),Number.POSITIVE_INFINITY),L=y.node(A);R!==Number.POSITIVE_INFINITY&&L.borderType!==T&&(O[A]=Math.max(O[A],R))}return E(N,_.predecessors.bind(_)),E(I,_.successors.bind(_)),Object.keys(w).forEach(A=>O[A]=O[x[A]]),O}function u(y,b,x,w){let k=new e,O=y.graph(),_=m(O.nodesep,O.edgesep,w);return b.forEach(T=>{let E;T.forEach(N=>{let I=x[N];if(k.setNode(I),E){var A=x[E],R=k.edge(A,I);k.setEdge(A,I,Math.max(_(y,N,E),R||0))}E=N})}),k}function d(y,b){return Object.values(b).reduce((x,w)=>{let k=Number.NEGATIVE_INFINITY,O=Number.POSITIVE_INFINITY;Object.entries(w).forEach(([T,E])=>{let N=v(y,T)/2;k=Math.max(E+N,k),O=Math.min(E-N,O)});const _=k-O;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(O=>{["l","r"].forEach(_=>{let T=O+_,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(O=>O[w]).sort((O,_)=>O-_);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 O=d(y,w);return f(w,O),h(w,y.graph().align)}function m(y,b,x){return(w,k,O)=>{let _=w.node(k),T=w.node(O),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 xne}var wne,sBe;function zGn(){if(sBe)return wne;sBe=1;let e=Pl(),t=FGn().positionX;wne=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 wne}var Sne,aBe;function BGn(){if(aBe)return Sne;aBe=1;let e=SGn(),t=kGn(),n=CGn(),r=Pl().normalizeRanks,s=_Gn(),a=Pl().removeEmptyRanks,i=EGn(),l=TGn(),c=jGn(),u=LGn(),d=zGn(),f=Pl(),h=Zg().Graph;Sne=p;function p(P,U){let W=U&&U.debugTiming?f.time:f.notime;W("layout",()=>{let Y=W(" buildLayoutGraph",()=>E(P));W(" runLayout",()=>m(Y,W,U)),W(" updateInputGraph",()=>v(P,Y))})}function m(P,U,W){U(" makeSpaceForEdgeLabels",()=>N(P)),U(" removeSelfEdges",()=>F(P)),U(" acyclic",()=>e.run(P)),U(" nestingGraph.run",()=>i.run(P)),U(" rank",()=>n(f.asNonCompoundGraph(P))),U(" injectEdgeLabelProxies",()=>I(P)),U(" removeEmptyRanks",()=>a(P)),U(" nestingGraph.cleanup",()=>i.cleanup(P)),U(" normalizeRanks",()=>r(P)),U(" assignRankMinMax",()=>A(P)),U(" removeEdgeLabelProxies",()=>R(P)),U(" normalize.run",()=>t.run(P)),U(" parentDummyChains",()=>s(P)),U(" addBorderSegments",()=>l(P)),U(" order",()=>u(P,W)),U(" insertSelfEdges",()=>V(P)),U(" adjustCoordinateSystem",()=>c.adjust(P)),U(" position",()=>d(P)),U(" positionSelfEdges",()=>M(P)),U(" removeBorderNodes",()=>q(P)),U(" normalize.undo",()=>t.undo(P)),U(" fixupEdgeLabelCoords",()=>B(P)),U(" undoCoordinateSystem",()=>c.undo(P)),U(" translateGraph",()=>L(P)),U(" assignNodeIntersects",()=>D(P)),U(" reversePoints",()=>H(P)),U(" acyclic.undo",()=>e.undo(P))}function v(P,U){P.nodes().forEach(W=>{let Y=P.node(W),te=U.node(W);Y&&(Y.x=te.x,Y.y=te.y,Y.rank=te.rank,U.children(W).length&&(Y.width=te.width,Y.height=te.height))}),P.edges().forEach(W=>{let Y=P.edge(W),te=U.edge(W);Y.points=te.points,Object.hasOwn(te,"x")&&(Y.x=te.x,Y.y=te.y)}),P.graph().width=U.graph().width,P.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},O=["minlen","weight","width","height","labeloffset"],_={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},T=["labelpos"];function E(P){let U=new h({multigraph:!0,compound:!0}),W=z(P.graph());return U.setGraph(Object.assign({},b,G(W,y),f.pick(W,x))),P.nodes().forEach(Y=>{let te=z(P.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,P.parent(Y))}),P.edges().forEach(Y=>{let te=z(P.edge(Y));U.setEdge(Y,Object.assign({},_,G(te,O),f.pick(te,T)))}),U}function N(P){let U=P.graph();U.ranksep/=2,P.edges().forEach(W=>{let Y=P.edge(W);Y.minlen*=2,Y.labelpos.toLowerCase()!=="c"&&(U.rankdir==="TB"||U.rankdir==="BT"?Y.width+=Y.labeloffset:Y.height+=Y.labeloffset)})}function I(P){P.edges().forEach(U=>{let W=P.edge(U);if(W.width&&W.height){let Y=P.node(U.v),J={rank:(P.node(U.w).rank-Y.rank)/2+Y.rank,e:U};f.addDummyNode(P,"edge-proxy",J,"_ep")}})}function A(P){let U=0;P.nodes().forEach(W=>{let Y=P.node(W);Y.borderTop&&(Y.minRank=P.node(Y.borderTop).rank,Y.maxRank=P.node(Y.borderBottom).rank,U=Math.max(U,Y.maxRank))}),P.graph().maxRank=U}function R(P){P.nodes().forEach(U=>{let W=P.node(U);W.dummy==="edge-proxy"&&(P.edge(W.e).labelRank=W.rank,P.removeNode(U))})}function L(P){let U=Number.POSITIVE_INFINITY,W=0,Y=Number.POSITIVE_INFINITY,te=0,J=P.graph(),ee=J.marginx||0,re=J.marginy||0;function oe(X){let ne=X.x,se=X.y,ce=X.width,le=X.height;U=Math.min(U,ne-ce/2),W=Math.max(W,ne+ce/2),Y=Math.min(Y,se-le/2),te=Math.max(te,se+le/2)}P.nodes().forEach(X=>oe(P.node(X))),P.edges().forEach(X=>{let ne=P.edge(X);Object.hasOwn(ne,"x")&&oe(ne)}),U-=ee,Y-=re,P.nodes().forEach(X=>{let ne=P.node(X);ne.x-=U,ne.y-=Y}),P.edges().forEach(X=>{let ne=P.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=W-U+ee,J.height=te-Y+re}function D(P){P.edges().forEach(U=>{let W=P.edge(U),Y=P.node(U.v),te=P.node(U.w),J,ee;W.points?(J=W.points[0],ee=W.points[W.points.length-1]):(W.points=[],J=te,ee=Y),W.points.unshift(f.intersectRect(Y,J)),W.points.push(f.intersectRect(te,ee))})}function B(P){P.edges().forEach(U=>{let W=P.edge(U);if(Object.hasOwn(W,"x"))switch((W.labelpos==="l"||W.labelpos==="r")&&(W.width-=W.labeloffset),W.labelpos){case"l":W.x-=W.width/2+W.labeloffset;break;case"r":W.x+=W.width/2+W.labeloffset;break}})}function H(P){P.edges().forEach(U=>{let W=P.edge(U);W.reversed&&W.points.reverse()})}function q(P){P.nodes().forEach(U=>{if(P.children(U).length){let W=P.node(U),Y=P.node(W.borderTop),te=P.node(W.borderBottom),J=P.node(W.borderLeft[W.borderLeft.length-1]),ee=P.node(W.borderRight[W.borderRight.length-1]);W.width=Math.abs(ee.x-J.x),W.height=Math.abs(te.y-Y.y),W.x=J.x+W.width/2,W.y=Y.y+W.height/2}}),P.nodes().forEach(U=>{P.node(U).dummy==="border"&&P.removeNode(U)})}function F(P){P.edges().forEach(U=>{if(U.v===U.w){var W=P.node(U.v);W.selfEdges||(W.selfEdges=[]),W.selfEdges.push({e:U,label:P.edge(U)}),P.removeEdge(U)}})}function V(P){var U=f.buildLayerMatrix(P);U.forEach(W=>{var Y=0;W.forEach((te,J)=>{var ee=P.node(te);ee.order=J+Y,(ee.selfEdges||[]).forEach(re=>{f.addDummyNode(P,"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(P){P.nodes().forEach(U=>{var W=P.node(U);if(W.dummy==="selfedge"){var Y=P.node(W.e.v),te=Y.x+Y.width/2,J=Y.y,ee=W.x-te,re=Y.height/2;P.setEdge(W.e,W.label),P.removeNode(U),W.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}],W.label.x=W.x,W.label.y=W.y}})}function G(P,U){return f.mapValues(f.pick(P,U),Number)}function z(P){var U={};return P&&Object.entries(P).forEach(([W,Y])=>{typeof W=="string"&&(W=W.toLowerCase()),U[W]=Y}),U}return Sne}var kne,iBe;function UGn(){if(iBe)return kne;iBe=1;let e=Pl(),t=Zg().Graph;kne={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 kne}var One,oBe;function qGn(){return oBe||(oBe=1,One="1.1.8"),One}var Cne,lBe;function VGn(){return lBe||(lBe=1,Cne={graphlib:Zg(),layout:BGn(),debug:UGn(),util:{time:Pl().time,notime:Pl().notime},version:qGn()}),Cne}var HGn=VGn();const cBe=ql(HGn);function Zl(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=Zl(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var WGn={value:()=>{}};function IW(){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 h9(n)}function h9(e){this._=e}function ZGn(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}})}h9.prototype=IW.prototype={constructor:h9,on:function(e,t){var n=this._,r=ZGn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=GGn(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]=uBe(n[s],e.name,t);else if(t==null)for(s in n)n[s]=uBe(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 h9(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 GGn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function uBe(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=WGn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Vve="http://www.w3.org/1999/xhtml";const dBe={svg:"http://www.w3.org/2000/svg",xhtml:Vve,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function AW(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),dBe.hasOwnProperty(t)?{space:dBe[t],local:e}:e}function QGn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Vve&&t.documentElement.namespaceURI===Vve?t.createElement(e):t.createElementNS(n,e)}}function YGn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function OCt(e){var t=AW(e);return(t.local?YGn:QGn)(t)}function KGn(){}function qOe(e){return e==null?KGn:function(){return this.querySelector(e)}}function XGn(e){typeof e!="function"&&(e=qOe(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 JGn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function eQn(){return[]}function CCt(e){return e==null?eQn:function(){return this.querySelectorAll(e)}}function tQn(e){return function(){return JGn(e.apply(this,arguments))}}function nQn(e){typeof e=="function"?e=tQn(e):e=CCt(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 _Ct(e){return function(){return this.matches(e)}}function ECt(e){return function(t){return t.matches(e)}}var rQn=Array.prototype.find;function sQn(e){return function(){return rQn.call(this.children,e)}}function aQn(){return this.firstElementChild}function iQn(e){return this.select(e==null?aQn:sQn(typeof e=="function"?e:ECt(e)))}var oQn=Array.prototype.filter;function lQn(){return Array.from(this.children)}function cQn(e){return function(){return oQn.call(this.children,e)}}function uQn(e){return this.selectAll(e==null?lQn:cQn(typeof e=="function"?e:ECt(e)))}function dQn(e){typeof e!="function"&&(e=_Ct(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 TCt(e){return new Array(e.length)}function fQn(){return new tp(this._enter||this._groups.map(TCt),this._parents)}function mU(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}mU.prototype={constructor:mU,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 hQn(e){return function(){return e}}function pQn(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 mU(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function mQn(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 mU(e,a[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(h[l])===c&&(s[l]=c)}function gQn(e){return e.__data__}function vQn(e,t){if(!arguments.length)return Array.from(this,gQn);var n=t?mQn:pQn,r=this._parents,s=this._groups;typeof e!="function"&&(e=hQn(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=yQn(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,O;x<m;++x)if(k=v[x]){for(x>=w&&(w=x+1);!(O=y[w])&&++w<m;);k._next=O||null}}return i=new tp(i,r),i._enter=l,i._exit=c,i}function yQn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function bQn(){return new tp(this._exit||this._groups.map(TCt),this._parents)}function xQn(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 wQn(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 SQn(){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 kQn(e){e||(e=OQn);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 OQn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function CQn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function _Qn(){return Array.from(this)}function EQn(){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 TQn(){let e=0;for(const t of this)++e;return e}function jQn(){return!this.node()}function NQn(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 IQn(e){return function(){this.removeAttribute(e)}}function AQn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function RQn(e,t){return function(){this.setAttribute(e,t)}}function PQn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function $Qn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function MQn(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 DQn(e,t){var n=AW(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?AQn:IQn:typeof t=="function"?n.local?MQn:$Qn:n.local?PQn:RQn)(n,t))}function jCt(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function LQn(e){return function(){this.style.removeProperty(e)}}function FQn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function zQn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function BQn(e,t,n){return arguments.length>1?this.each((t==null?LQn:typeof t=="function"?zQn:FQn)(e,t,n??"")):dN(this.node(),e)}function dN(e,t){return e.style.getPropertyValue(t)||jCt(e).getComputedStyle(e,null).getPropertyValue(t)}function UQn(e){return function(){delete this[e]}}function qQn(e,t){return function(){this[e]=t}}function VQn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function HQn(e,t){return arguments.length>1?this.each((t==null?UQn:typeof t=="function"?VQn:qQn)(e,t)):this.node()[e]}function NCt(e){return e.trim().split(/^|\s+/)}function VOe(e){return e.classList||new ICt(e)}function ICt(e){this._node=e,this._names=NCt(e.getAttribute("class")||"")}ICt.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 ACt(e,t){for(var n=VOe(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function RCt(e,t){for(var n=VOe(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function WQn(e){return function(){ACt(this,e)}}function ZQn(e){return function(){RCt(this,e)}}function GQn(e,t){return function(){(t.apply(this,arguments)?ACt:RCt)(this,e)}}function QQn(e,t){var n=NCt(e+"");if(arguments.length<2){for(var r=VOe(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?GQn:t?WQn:ZQn)(n,t))}function YQn(){this.textContent=""}function KQn(e){return function(){this.textContent=e}}function XQn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function JQn(e){return arguments.length?this.each(e==null?YQn:(typeof e=="function"?XQn:KQn)(e)):this.node().textContent}function eYn(){this.innerHTML=""}function tYn(e){return function(){this.innerHTML=e}}function nYn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function rYn(e){return arguments.length?this.each(e==null?eYn:(typeof e=="function"?nYn:tYn)(e)):this.node().innerHTML}function sYn(){this.nextSibling&&this.parentNode.appendChild(this)}function aYn(){return this.each(sYn)}function iYn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function oYn(){return this.each(iYn)}function lYn(e){var t=typeof e=="function"?e:OCt(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function cYn(){return null}function uYn(e,t){var n=typeof e=="function"?e:OCt(e),r=t==null?cYn:typeof t=="function"?t:qOe(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function dYn(){var e=this.parentNode;e&&e.removeChild(this)}function fYn(){return this.each(dYn)}function hYn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function pYn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function mYn(e){return this.select(e?pYn:hYn)}function gYn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function vYn(e){return function(t){e.call(this,t,this.__data__)}}function yYn(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 bYn(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 xYn(e,t,n){return function(){var r=this.__on,s,a=vYn(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 wYn(e,t,n){var r=yYn(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?xYn:bYn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function PCt(e,t,n){var r=jCt(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 SYn(e,t){return function(){return PCt(this,e,t)}}function kYn(e,t){return function(){return PCt(this,e,t.apply(this,arguments))}}function OYn(e,t){return this.each((typeof t=="function"?kYn:SYn)(e,t))}function*CYn(){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 $Ct=[null];function tp(e,t){this._groups=e,this._parents=t}function pL(){return new tp([[document.documentElement]],$Ct)}function _Yn(){return this}tp.prototype=pL.prototype={constructor:tp,select:XGn,selectAll:nQn,selectChild:iQn,selectChildren:uQn,filter:dQn,data:vQn,enter:fQn,exit:bQn,join:xQn,merge:wQn,selection:_Yn,order:SQn,sort:kQn,call:CQn,nodes:_Qn,node:EQn,size:TQn,empty:jQn,each:NQn,attr:DQn,style:BQn,property:HQn,classed:QQn,text:JQn,html:rYn,raise:aYn,lower:oYn,append:lYn,insert:uYn,remove:fYn,clone:mYn,datum:gYn,on:wYn,dispatch:OYn,[Symbol.iterator]:CYn};function jh(e){return typeof e=="string"?new tp([[document.querySelector(e)]],[document.documentElement]):new tp([[e]],$Ct)}function EYn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function yg(e,t){if(e=EYn(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 TYn={passive:!1},QM={capture:!0,passive:!1};function _ne(e){e.stopImmediatePropagation()}function yj(e){e.preventDefault(),e.stopImmediatePropagation()}function MCt(e){var t=e.document.documentElement,n=jh(e).on("dragstart.drag",yj,QM);"onselectstart"in t?n.on("selectstart.drag",yj,QM):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function DCt(e,t){var n=e.document.documentElement,r=jh(e).on("dragstart.drag",null);t&&(r.on("click.drag",yj,QM),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 PF=e=>()=>e;function Hve(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}})}Hve.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function jYn(e){return!e.ctrlKey&&!e.button}function NYn(){return this.parentNode}function IYn(e,t){return t??{x:e.x,y:e.y}}function AYn(){return navigator.maxTouchPoints||"ontouchstart"in this}function LCt(){var e=jYn,t=NYn,n=IYn,r=AYn,s={},a=IW("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,TYn).on("touchend.drag touchcancel.drag",x).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function p(k,O){if(!(d||!e.call(this,k,O))){var _=w(this,t.call(this,k,O),k,O,"mouse");_&&(jh(k.view).on("mousemove.drag",m,QM).on("mouseup.drag",v,QM),MCt(k.view),_ne(k),u=!1,l=k.clientX,c=k.clientY,_("start",k))}}function m(k){if(yj(k),!u){var O=k.clientX-l,_=k.clientY-c;u=O*O+_*_>f}s.mouse("drag",k)}function v(k){jh(k.view).on("mousemove.drag mouseup.drag",null),DCt(k.view,u),yj(k),s.mouse("end",k)}function y(k,O){if(e.call(this,k,O)){var _=k.changedTouches,T=t.call(this,k,O),E=_.length,N,I;for(N=0;N<E;++N)(I=w(this,T,k,O,_[N].identifier,_[N]))&&(_ne(k),I("start",k,_[N]))}}function b(k){var O=k.changedTouches,_=O.length,T,E;for(T=0;T<_;++T)(E=s[O[T].identifier])&&(yj(k),E("drag",k,O[T]))}function x(k){var O=k.changedTouches,_=O.length,T,E;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),T=0;T<_;++T)(E=s[O[T].identifier])&&(_ne(k),E("end",k,O[T]))}function w(k,O,_,T,E,N){var I=a.copy(),A=yg(N||_,O),R,L,D;if((D=n.call(k,new Hve("beforestart",{sourceEvent:_,target:h,identifier:E,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),T))!=null)return R=D.x-A[0]||0,L=D.y-A[1]||0,function B(H,q,F){var V=A,M;switch(H){case"start":s[E]=B,M=i++;break;case"end":delete s[E],--i;case"drag":A=yg(F||q,O),M=i;break}I.call(H,k,new Hve(H,{sourceEvent:q,subject:D,target:h,identifier:E,active:M,x:A[0]+R,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:PF(!!k),h):e},h.container=function(k){return arguments.length?(t=typeof k=="function"?k:PF(k),h):t},h.subject=function(k){return arguments.length?(n=typeof k=="function"?k:PF(k),h):n},h.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:PF(!!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 HOe(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function FCt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function mL(){}var YM=.7,gU=1/YM,bj="\\s*([+-]?\\d+)\\s*",KM="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",my="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",RYn=/^#([0-9a-f]{3,8})$/,PYn=new RegExp(`^rgb\\(${bj},${bj},${bj}\\)$`),$Yn=new RegExp(`^rgb\\(${my},${my},${my}\\)$`),MYn=new RegExp(`^rgba\\(${bj},${bj},${bj},${KM}\\)$`),DYn=new RegExp(`^rgba\\(${my},${my},${my},${KM}\\)$`),LYn=new RegExp(`^hsl\\(${KM},${my},${my}\\)$`),FYn=new RegExp(`^hsla\\(${KM},${my},${my},${KM}\\)$`),fBe={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};HOe(mL,uC,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:hBe,formatHex:hBe,formatHex8:zYn,formatHsl:BYn,formatRgb:pBe,toString:pBe});function hBe(){return this.rgb().formatHex()}function zYn(){return this.rgb().formatHex8()}function BYn(){return zCt(this).formatHsl()}function pBe(){return this.rgb().formatRgb()}function uC(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=RYn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?mBe(t):n===3?new Af(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?$F(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?$F(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=PYn.exec(e))?new Af(t[1],t[2],t[3],1):(t=$Yn.exec(e))?new Af(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=MYn.exec(e))?$F(t[1],t[2],t[3],t[4]):(t=DYn.exec(e))?$F(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=LYn.exec(e))?yBe(t[1],t[2]/100,t[3]/100,1):(t=FYn.exec(e))?yBe(t[1],t[2]/100,t[3]/100,t[4]):fBe.hasOwnProperty(e)?mBe(fBe[e]):e==="transparent"?new Af(NaN,NaN,NaN,0):null}function mBe(e){return new Af(e>>16&255,e>>8&255,e&255,1)}function $F(e,t,n,r){return r<=0&&(e=t=n=NaN),new Af(e,t,n,r)}function UYn(e){return e instanceof mL||(e=uC(e)),e?(e=e.rgb(),new Af(e.r,e.g,e.b,e.opacity)):new Af}function Wve(e,t,n,r){return arguments.length===1?UYn(e):new Af(e,t,n,r??1)}function Af(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}HOe(Af,Wve,FCt(mL,{brighter(e){return e=e==null?gU:Math.pow(gU,e),new Af(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?YM:Math.pow(YM,e),new Af(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Af(mO(this.r),mO(this.g),mO(this.b),vU(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:gBe,formatHex:gBe,formatHex8:qYn,formatRgb:vBe,toString:vBe}));function gBe(){return`#${Qk(this.r)}${Qk(this.g)}${Qk(this.b)}`}function qYn(){return`#${Qk(this.r)}${Qk(this.g)}${Qk(this.b)}${Qk((isNaN(this.opacity)?1:this.opacity)*255)}`}function vBe(){const e=vU(this.opacity);return`${e===1?"rgb(":"rgba("}${mO(this.r)}, ${mO(this.g)}, ${mO(this.b)}${e===1?")":`, ${e})`}`}function vU(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function mO(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Qk(e){return e=mO(e),(e<16?"0":"")+e.toString(16)}function yBe(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Cg(e,t,n,r)}function zCt(e){if(e instanceof Cg)return new Cg(e.h,e.s,e.l,e.opacity);if(e instanceof mL||(e=uC(e)),!e)return new Cg;if(e instanceof Cg)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 Cg(i,l,c,e.opacity)}function VYn(e,t,n,r){return arguments.length===1?zCt(e):new Cg(e,t,n,r??1)}function Cg(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}HOe(Cg,VYn,FCt(mL,{brighter(e){return e=e==null?gU:Math.pow(gU,e),new Cg(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?YM:Math.pow(YM,e),new Cg(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 Af(Ene(e>=240?e-240:e+120,s,r),Ene(e,s,r),Ene(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new Cg(bBe(this.h),MF(this.s),MF(this.l),vU(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=vU(this.opacity);return`${e===1?"hsl(":"hsla("}${bBe(this.h)}, ${MF(this.s)*100}%, ${MF(this.l)*100}%${e===1?")":`, ${e})`}`}}));function bBe(e){return e=(e||0)%360,e<0?e+360:e}function MF(e){return Math.max(0,Math.min(1,e||0))}function Ene(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 WOe=e=>()=>e;function HYn(e,t){return function(n){return e+n*t}}function WYn(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 ZYn(e){return(e=+e)==1?BCt:function(t,n){return n-t?WYn(t,n,e):WOe(isNaN(t)?n:t)}}function BCt(e,t){var n=t-e;return n?HYn(e,n):WOe(isNaN(e)?t:e)}const yU=(function e(t){var n=ZYn(t);function r(s,a){var i=n((s=Wve(s)).r,(a=Wve(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=BCt(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 GYn(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 QYn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function YYn(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]=xx(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 KYn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function xg(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function XYn(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]=xx(e[s],t[s]):r[s]=t[s];return function(a){for(s in n)r[s]=n[s](a);return r}}var Zve=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Tne=new RegExp(Zve.source,"g");function JYn(e){return function(){return e}}function eKn(e){return function(t){return e(t)+""}}function UCt(e,t){var n=Zve.lastIndex=Tne.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Zve.exec(e))&&(s=Tne.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:xg(r,s)})),n=Tne.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?eKn(c[0].x):JYn(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 xx(e,t){var n=typeof t,r;return t==null||n==="boolean"?WOe(t):(n==="number"?xg:n==="string"?(r=uC(t))?(t=r,yU):UCt:t instanceof uC?yU:t instanceof Date?KYn:QYn(t)?GYn:Array.isArray(t)?YYn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?XYn:xg)(e,t)}function ZOe(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var xBe=180/Math.PI,Gve={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function qCt(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)*xBe,skewX:Math.atan(c)*xBe,scaleX:i,scaleY:l}}var DF;function tKn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Gve:qCt(t.a,t.b,t.c,t.d,t.e,t.f)}function nKn(e){return e==null||(DF||(DF=document.createElementNS("http://www.w3.org/2000/svg","g")),DF.setAttribute("transform",e),!(e=DF.transform.baseVal.consolidate()))?Gve:(e=e.matrix,qCt(e.a,e.b,e.c,e.d,e.e,e.f))}function VCt(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:xg(u,f)},{i:v-2,x:xg(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:xg(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:xg(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:xg(u,f)},{i:v-2,x:xg(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 rKn=VCt(tKn,"px, ","px)","deg)"),sKn=VCt(nKn,", ",")",")"),aKn=1e-12;function wBe(e){return((e=Math.exp(e))+1/e)/2}function iKn(e){return((e=Math.exp(e))-1/e)/2}function oKn(e){return((e=Math.exp(2*e))-1)/(e+1)}const p9=(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<aKn)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),O=Math.log(Math.sqrt(w*w+1)-w),_=Math.log(Math.sqrt(k*k+1)-k);b=(_-O)/t,y=function(T){var E=T*b,N=wBe(O),I=u/(n*x)*(N*oKn(t*E+O)-iKn(O));return[l+I*p,c+I*m,u*N/wBe(t*E+O)]}}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 lKn(e,t){t===void 0&&(t=e,e=xx);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 fN=0,d$=0,YR=0,HCt=1e3,bU,f$,xU=0,dC=0,RW=0,XM=typeof performance=="object"&&performance.now?performance:Date,WCt=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function GOe(){return dC||(WCt(cKn),dC=XM.now()+RW)}function cKn(){dC=0}function wU(){this._call=this._time=this._next=null}wU.prototype=ZCt.prototype={constructor:wU,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?GOe():+n)+(t==null?0:+t),!this._next&&f$!==this&&(f$?f$._next=this:bU=this,f$=this),this._call=e,this._time=n,Qve()},stop:function(){this._call&&(this._call=null,this._time=1/0,Qve())}};function ZCt(e,t,n){var r=new wU;return r.restart(e,t,n),r}function uKn(){GOe(),++fN;for(var e=bU,t;e;)(t=dC-e._time)>=0&&e._call.call(void 0,t),e=e._next;--fN}function SBe(){dC=(xU=XM.now())+RW,fN=d$=0;try{uKn()}finally{fN=0,fKn(),dC=0}}function dKn(){var e=XM.now(),t=e-xU;t>HCt&&(RW-=t,xU=e)}function fKn(){for(var e,t=bU,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:bU=n);f$=e,Qve(r)}function Qve(e){if(!fN){d$&&(d$=clearTimeout(d$));var t=e-dC;t>24?(e<1/0&&(d$=setTimeout(SBe,e-XM.now()-RW)),YR&&(YR=clearInterval(YR))):(YR||(xU=XM.now(),YR=setInterval(dKn,HCt)),fN=1,WCt(SBe))}}function kBe(e,t,n){var r=new wU;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var hKn=IW("start","end","cancel","interrupt"),pKn=[],GCt=0,OBe=1,Yve=2,m9=3,CBe=4,Kve=5,g9=6;function PW(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;mKn(e,n,{name:t,index:r,group:s,on:hKn,tween:pKn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:GCt})}function QOe(e,t){var n=nv(e,t);if(n.state>GCt)throw new Error("too late; already scheduled");return n}function Hy(e,t){var n=nv(e,t);if(n.state>m9)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 mKn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=ZCt(a,0,n.time);function a(u){n.state=OBe,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!==OBe)return c();for(d in r)if(p=r[d],p.name===n.name){if(p.state===m9)return kBe(i);p.state===CBe?(p.state=g9,p.timer.stop(),p.on.call("interrupt",e,e.__data__,p.index,p.group),delete r[d]):+d<t&&(p.state=g9,p.timer.stop(),p.on.call("cancel",e,e.__data__,p.index,p.group),delete r[d])}if(kBe(function(){n.state===m9&&(n.state=CBe,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Yve,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Yve){for(n.state=m9,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=Kve,1),f=-1,h=s.length;++f<h;)s[f].call(e,d);n.state===Kve&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=g9,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function v9(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>Yve&&r.state<Kve,r.state=g9,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function gKn(e){return this.each(function(){v9(this,e)})}function vKn(e,t){var n,r;return function(){var s=Hy(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 yKn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=Hy(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 bKn(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?vKn:yKn)(n,e,t))}function YOe(e,t,n){var r=e._id;return e.each(function(){var s=Hy(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return nv(s,r).value[t]}}function QCt(e,t){var n;return(typeof t=="number"?xg:t instanceof uC?yU:(n=uC(t))?(t=n,yU):UCt)(e,t)}function xKn(e){return function(){this.removeAttribute(e)}}function wKn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function SKn(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 kKn(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 OKn(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 CKn(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 _Kn(e,t){var n=AW(e),r=n==="transform"?sKn:QCt;return this.attrTween(e,typeof t=="function"?(n.local?CKn:OKn)(n,r,YOe(this,"attr."+e,t)):t==null?(n.local?wKn:xKn)(n):(n.local?kKn:SKn)(n,r,t))}function EKn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function TKn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function jKn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&TKn(e,a)),n}return s._value=t,s}function NKn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&EKn(e,a)),n}return s._value=t,s}function IKn(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=AW(e);return this.tween(n,(r.local?jKn:NKn)(r,t))}function AKn(e,t){return function(){QOe(this,e).delay=+t.apply(this,arguments)}}function RKn(e,t){return t=+t,function(){QOe(this,e).delay=t}}function PKn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?AKn:RKn)(t,e)):nv(this.node(),t).delay}function $Kn(e,t){return function(){Hy(this,e).duration=+t.apply(this,arguments)}}function MKn(e,t){return t=+t,function(){Hy(this,e).duration=t}}function DKn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?$Kn:MKn)(t,e)):nv(this.node(),t).duration}function LKn(e,t){if(typeof t!="function")throw new Error;return function(){Hy(this,e).ease=t}}function FKn(e){var t=this._id;return arguments.length?this.each(LKn(t,e)):nv(this.node(),t).ease}function zKn(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Hy(this,e).ease=n}}function BKn(e){if(typeof e!="function")throw new Error;return this.each(zKn(this._id,e))}function UKn(e){typeof e!="function"&&(e=_Ct(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 Bx(r,this._parents,this._name,this._id)}function qKn(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 Bx(i,this._parents,this._name,this._id)}function VKn(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 HKn(e,t,n){var r,s,a=VKn(t)?QOe:Hy;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function WKn(e,t){var n=this._id;return arguments.length<2?nv(this.node(),n).on.on(e):this.each(HKn(n,e,t))}function ZKn(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function GKn(){return this.on("end.remove",ZKn(this._id))}function QKn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=qOe(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,PW(u[h],t,n,h,u,nv(d,n)));return new Bx(a,this._parents,t,n)}function YKn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=CCt(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])&&PW(p,t,n,v,h,m);a.push(h),i.push(d)}return new Bx(a,i,t,n)}var KKn=pL.prototype.constructor;function XKn(){return new KKn(this._groups,this._parents)}function JKn(e,t){var n,r,s;return function(){var a=dN(this,e),i=(this.style.removeProperty(e),dN(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function YCt(e){return function(){this.style.removeProperty(e)}}function eXn(e,t,n){var r,s=n+"",a;return function(){var i=dN(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function tXn(e,t,n){var r,s,a;return function(){var i=dN(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),dN(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function nXn(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=Hy(this,e),u=c.on,d=c.value[a]==null?l||(l=YCt(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function rXn(e,t,n){var r=(e+="")=="transform"?rKn:QCt;return t==null?this.styleTween(e,JKn(e,r)).on("end.style."+e,YCt(e)):typeof t=="function"?this.styleTween(e,tXn(e,r,YOe(this,"style."+e,t))).each(nXn(this._id,e)):this.styleTween(e,eXn(e,r,t),n).on("end.style."+e,null)}function sXn(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function aXn(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&sXn(e,i,n)),r}return a._value=t,a}function iXn(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,aXn(e,t,n??""))}function oXn(e){return function(){this.textContent=e}}function lXn(e){return function(){var t=e(this);this.textContent=t??""}}function cXn(e){return this.tween("text",typeof e=="function"?lXn(YOe(this,"text",e)):oXn(e==null?"":e+""))}function uXn(e){return function(t){this.textContent=e.call(this,t)}}function dXn(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&uXn(s)),t}return r._value=e,r}function fXn(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,dXn(e))}function hXn(){for(var e=this._name,t=this._id,n=KCt(),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);PW(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new Bx(r,this._parents,e,n)}function pXn(){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=Hy(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 mXn=0;function Bx(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function KCt(){return++mXn}var Eb=pL.prototype;Bx.prototype={constructor:Bx,select:QKn,selectAll:YKn,selectChild:Eb.selectChild,selectChildren:Eb.selectChildren,filter:UKn,merge:qKn,selection:XKn,transition:hXn,call:Eb.call,nodes:Eb.nodes,node:Eb.node,size:Eb.size,empty:Eb.empty,each:Eb.each,on:WKn,attr:_Kn,attrTween:IKn,style:rXn,styleTween:iXn,text:cXn,textTween:fXn,remove:GKn,tween:bKn,delay:PKn,duration:DKn,ease:FKn,easeVarying:BKn,end:pXn,[Symbol.iterator]:Eb[Symbol.iterator]};function gXn(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var vXn={time:null,delay:0,duration:250,ease:gXn};function yXn(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 bXn(e){var t,n;e instanceof Bx?(t=e._id,e=e._name):(t=KCt(),(n=vXn).time=GOe(),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])&&PW(c,e,t,u,i,n||yXn(c,t));return new Bx(r,this._parents,e,t)}pL.prototype.interrupt=gKn;pL.prototype.transition=bXn;const LF=e=>()=>e;function xXn(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 $W=new ix(1,0,0);XCt.prototype=ix.prototype;function XCt(e){for(;!e.__zoom;)if(!(e=e.parentNode))return $W;return e.__zoom}function jne(e){e.stopImmediatePropagation()}function KR(e){e.preventDefault(),e.stopImmediatePropagation()}function wXn(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function SXn(){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 _Be(){return this.__zoom||$W}function kXn(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function OXn(){return navigator.maxTouchPoints||"ontouchstart"in this}function CXn(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 JCt(){var e=wXn,t=SXn,n=CXn,r=kXn,s=OXn,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=p9,u=IW("start","zoom","end"),d,f,h,p=500,m=150,v=0,y=10;function b(D){D.property("__zoom",_Be).on("wheel.zoom",E,{passive:!1}).on("mousedown.zoom",N).on("dblclick.zoom",I).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",R).on("touchend.zoom touchcancel.zoom",L).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(D,B,H,q){var F=D.selection?D.selection():D;F.property("__zoom",_Be),D!==F?O(D,B,H,q):F.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 F=this.__zoom.k,V=typeof B=="function"?B.apply(this,arguments):B;return F*V},H,q)},b.scaleTo=function(D,B,H,q){b.transform(D,function(){var F=t.apply(this,arguments),V=this.__zoom,M=H==null?k(F):typeof H=="function"?H.apply(this,arguments):H,G=V.invert(M),z=typeof B=="function"?B.apply(this,arguments):B;return n(w(x(V,z),M,G),F,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,F){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($W.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,F)};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,F=B[1]-H[1]*D.k;return q===D.x&&F===D.y?D:new ix(D.k,q,F)}function k(D){return[(+D[0][0]+ +D[1][0])/2,(+D[0][1]+ +D[1][1])/2]}function O(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 F=this,V=arguments,M=_(F,V).event(q),G=t.apply(F,V),z=H==null?k(G):typeof H=="function"?H.apply(F,V):H,P=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),U=F.__zoom,W=typeof B=="function"?B.apply(F,V):B,Y=c(U.invert(z).concat(P/U.k),W.invert(z).concat(P/W.k));return function(te){if(te===1)te=W;else{var J=Y(te),ee=P/J[2];te=new ix(ee,z[0]-J[0]*ee,z[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=jh(this.that).datum();u.call(D,this.that,new xXn(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,F=Math.max(a[0],Math.min(a[1],q.k*Math.pow(2,r.apply(this,arguments)))),V=yg(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===F)return;H.mouse=[V,q.invert(V)],v9(this),H.start()}KR(D),H.wheel=setTimeout(M,m),H.zoom("mouse",n(w(x(q,F),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),F=jh(D.view).on("mousemove.zoom",z,!0).on("mouseup.zoom",P,!0),V=yg(D,H),M=D.clientX,G=D.clientY;MCt(D.view),jne(D),q.mouse=[V,this.__zoom.invert(V)],v9(this),q.start();function z(U){if(KR(U),!q.moved){var W=U.clientX-M,Y=U.clientY-G;q.moved=W*W+Y*Y>v}q.event(U).zoom("mouse",n(w(q.that.__zoom,q.mouse[0]=yg(U,H),q.mouse[1]),q.extent,i))}function P(U){F.on("mousemove.zoom mouseup.zoom",null),DCt(U.view,q.moved),KR(U),q.event(U).end()}}function I(D,...B){if(e.apply(this,arguments)){var H=this.__zoom,q=yg(D.changedTouches?D.changedTouches[0]:D,this),F=H.invert(q),V=H.k*(D.shiftKey?.5:2),M=n(w(x(H,V),q,F),t.apply(this,B),i);KR(D),l>0?jh(this).transition().duration(l).call(O,M,q,D):jh(this).call(b.transform,M,q,D)}}function A(D,...B){if(e.apply(this,arguments)){var H=D.touches,q=H.length,F=_(this,B,D.changedTouches.length===q).event(D),V,M,G,z;for(jne(D),M=0;M<q;++M)G=H[M],z=yg(G,this),z=[z,this.__zoom.invert(z),G.identifier],F.touch0?!F.touch1&&F.touch0[2]!==z[2]&&(F.touch1=z,F.taps=0):(F.touch0=z,V=!0,F.taps=1+!!d);d&&(d=clearTimeout(d)),V&&(F.taps<2&&(f=z[0],d=setTimeout(function(){d=null},p)),v9(this),F.start())}}function R(D,...B){if(this.__zooming){var H=_(this,B).event(D),q=D.changedTouches,F=q.length,V,M,G,z;for(KR(D),V=0;V<F;++V)M=q[V],G=yg(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 P=H.touch0[0],U=H.touch0[1],W=H.touch1[0],Y=H.touch1[1],te=(te=W[0]-P[0])*te+(te=W[1]-P[1])*te,J=(J=Y[0]-U[0])*J+(J=Y[1]-U[1])*J;M=x(M,Math.sqrt(te/J)),G=[(P[0]+W[0])/2,(P[1]+W[1])/2],z=[(U[0]+Y[0])/2,(U[1]+Y[1])/2]}else if(H.touch0)G=H.touch0[0],z=H.touch0[1];else return;H.zoom("touch",n(w(M,G,z),H.extent,i))}}function L(D,...B){if(this.__zooming){var H=_(this,B).event(D),q=D.changedTouches,F=q.length,V,M;for(jne(D),h&&clearTimeout(h),h=setTimeout(function(){h=null},p),V=0;V<F;++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=yg(M,this),Math.hypot(f[0]-M[0],f[1]-M[1])<y)){var G=jh(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(D){return arguments.length?(r=typeof D=="function"?D:LF(+D),b):r},b.filter=function(D){return arguments.length?(e=typeof D=="function"?D:LF(!!D),b):e},b.touchable=function(D){return arguments.length?(s=typeof D=="function"?D:LF(!!D),b):s},b.extent=function(D){return arguments.length?(t=typeof D=="function"?D:LF([[+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."},JM=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],e_t=["Enter"," ","Escape"],t_t={"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 hN;(function(e){e.Strict="strict",e.Loose="loose"})(hN||(hN={}));var gO;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(gO||(gO={}));var eD;(function(e){e.Partial="partial",e.Full="full"})(eD||(eD={}));const n_t={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var Nw;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(Nw||(Nw={}));var tD;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(tD||(tD={}));var rr;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(rr||(rr={}));const EBe={[rr.Left]:rr.Right,[rr.Right]:rr.Left,[rr.Top]:rr.Bottom,[rr.Bottom]:rr.Top};function r_t(e){return e===null?null:e?"valid":"invalid"}const s_t=e=>"id"in e&&"source"in e&&"target"in e,_Xn=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),KOe=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),gL=(e,t=[0,0])=>{const{width:n,height:r}=u0(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},EXn=(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):KOe(s)?s:t.nodeLookup.get(s.id));const l=i?SU(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return MW(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return DW(n)},vL=(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=MW(n,SU(s)),r=!0)}),r?DW(n):{x:0,y:0,width:0,height:0}},XOe=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...bL(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=nD(l,mN(u)),y=(p??0)*(m??0),b=a&&v>0;(!u.internals.handleBounds||b||v>=y||u.dragging)&&c.push(u)}return c},TXn=(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 jXn(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 NXn({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=jXn(e,i),c=vL(l),u=JOe(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 a_t({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&&gN(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=gN(f)?fC(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 IXn({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=TXn(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 pN=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),fC=(e={x:0,y:0},t,n)=>({x:pN(e.x,t[0][0],t[1][0]-(n?.width??0)),y:pN(e.y,t[0][1],t[1][1]-(n?.height??0))});function i_t(e,t,n){const{width:r,height:s}=u0(n),{x:a,y:i}=n.internals.positionAbsolute;return fC(e,[[a,i],[a+r,i+s]],t)}const TBe=(e,t,n)=>e<t?pN(Math.abs(e-t),1,t)/t:e>n?-pN(Math.abs(e-n),1,t)/t:0,o_t=(e,t,n=15,r=40)=>{const s=TBe(e.x,r,t.width-r)*n,a=TBe(e.y,r,t.height-r)*n;return[s,a]},MW=(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)}),Xve=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),DW=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),mN=(e,t=[0,0])=>{const{x:n,y:r}=KOe(e)?e.internals.positionAbsolute:gL(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}},SU=(e,t=[0,0])=>{const{x:n,y:r}=KOe(e)?e.internals.positionAbsolute:gL(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)}},l_t=(e,t)=>DW(MW(Xve(e),Xve(t))),nD=(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)},jBe=e=>jg(e.width)&&jg(e.height)&&jg(e.x)&&jg(e.y),jg=e=>!isNaN(e)&&isFinite(e),AXn=(e,t)=>{},yL=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),bL=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?yL(l,i):l},kU=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function EE(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 RXn(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=EE(e,n),s=EE(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=EE(e.top??e.y??0,n),s=EE(e.bottom??e.y??0,n),a=EE(e.left??e.x??0,t),i=EE(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 PXn(e,t,n,r,s,a){const{x:i,y:l}=kU(e,[t,n,r]),{x:c,y:u}=kU({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 JOe=(e,t,n,r,s,a)=>{const i=RXn(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=pN(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=PXn(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}},rD=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function gN(e){return e!=null&&e!=="parent"}function u0(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function c_t(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function u_t(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 NBe(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function $Xn(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function MXn(e){return{...t_t,...e||{}}}function X$(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=Ng(e),l=bL({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?yL(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const eCe=e=>({width:e.offsetWidth,height:e.offsetHeight}),d_t=e=>e?.getRootNode?.()||window?.document,DXn=["INPUT","SELECT","TEXTAREA"];function f_t(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:DXn.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const h_t=e=>"clientX"in e,Ng=(e,t)=>{const n=h_t(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)}},IBe=(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,...eCe(i)}})};function p_t({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 FF(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function ABe({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case rr.Left:return[t-FF(t-r,a),n];case rr.Right:return[t+FF(r-t,a),n];case rr.Top:return[t,n-FF(n-s,a)];case rr.Bottom:return[t,n+FF(s-n,a)]}}function tCe({sourceX:e,sourceY:t,sourcePosition:n=rr.Bottom,targetX:r,targetY:s,targetPosition:a=rr.Top,curvature:i=.25}){const[l,c]=ABe({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=ABe({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,h,p,m]=p_t({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 m_t({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 LXn({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 FXn({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=MW(SU(e),SU(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 nD(i,DW(a))>0}const zXn=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,BXn=(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)),UXn=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||zXn;let s;return s_t(e)?s={...e}:s={...e,id:r(e)},BXn(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function g_t({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=m_t({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const RBe={[rr.Left]:{x:-1,y:0},[rr.Right]:{x:1,y:0},[rr.Top]:{x:0,y:-1},[rr.Bottom]:{x:0,y:1}},qXn=({source:e,sourcePosition:t=rr.Bottom,target:n})=>t===rr.Left||t===rr.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 VXn({source:e,sourcePosition:t=rr.Bottom,target:n,targetPosition:r=rr.Top,center:s,offset:a,stepPosition:i}){const l=RBe[t],c=RBe[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=qXn({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]=m_t({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},R=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));R>=L?(v=(I.x+A.x)/2,y=m[0].y):(v=m[0].x,y=(I.y+A.y)/2)}const O={x:u.x+b.x,y:u.y+b.y},_={x:d.x+x.x,y:d.y+x.y};return[[e,...O.x!==m[0].x||O.y!==m[0].y?[O]:[],...m,..._.x!==m[m.length-1].x||_.y!==m[m.length-1].y?[_]:[],n],v,y,w,k]}function HXn(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 Jve({sourceX:e,sourceY:t,sourcePosition:n=rr.Bottom,targetX:r,targetY:s,targetPosition:a=rr.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,h,p,m,v]=VXn({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+=HXn(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 $Be(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function WXn(e){const{sourceNode:t,targetNode:n}=e;if(!$Be(t)||!$Be(n))return null;const r=t.internals.handleBounds||MBe(t.handles),s=n.internals.handleBounds||MBe(n.handles),a=DBe(r?.source??[],e.sourceHandle),i=DBe(e.connectionMode===hN.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||rr.Bottom,c=i?.position||rr.Top,u=hC(t,a,l),d=hC(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function MBe(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 hC(e,t,n=rr.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??u0(e);if(r)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case rr.Top:return{x:s+i/2,y:a};case rr.Right:return{x:s+i,y:a+l/2};case rr.Bottom:return{x:s+i/2,y:a+l};case rr.Left:return{x:s,y:a+l/2}}}function DBe(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function eye(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function ZXn(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=eye(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 v_t=1e3,GXn=10,nCe={nodeOrigin:[0,0],nodeExtent:JM,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},QXn={...nCe,checkEquality:!0};function rCe(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function YXn(e,t,n){const r=rCe(nCe,n);for(const s of e.values())if(s.parentId)aCe(s,e,t,r);else{const a=gL(s,r.nodeOrigin),i=gN(s.extent)?s.extent:r.nodeExtent,l=fC(a,i,u0(s));s.internals.positionAbsolute=l}}function KXn(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 sCe(e){return e==="manual"}function tye(e,t,n,r={}){const s=rCe(QXn,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!sCe(s.zIndexMode)?v_t: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=gL(d,s.nodeOrigin),p=gN(d.extent)?d.extent:s.nodeExtent,m=fC(h,p,u0(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:KXn(d,f),z:y_t(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&&aCe(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function XXn(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 aCe(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=rCe(nCe,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}XXn(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*GXn),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!sCe(c)?v_t:0,{x:h,y:p,z:m}=JXn(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 y_t(e,t,n){const r=jg(e.zIndex)?e.zIndex:0;return sCe(n)?r:r+(e.selected?t:0)}function JXn(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=u0(e),u=gL(e,n),d=gN(e.extent)?fC(u,e.extent,c):u;let f=fC({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=i_t(f,c,t));const h=y_t(e,s,a),p=t.internals.z??0;return{x:f.x,y:f.y,z:p>=h?p+1:h}}function iCe(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??mN(l),u=l_t(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=u0(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 eJn(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=eCe(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=gN(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=i_t(k,v,t.get(m.parentId)):w&&(k=fC(k,w,v));const O={...m,measured:v,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:IBe("source",p.nodeElement,x,f,m.id),target:IBe("target",p.nodeElement,x,f,m.id)}}};t.set(m.id,O),m.parentId&&aCe(O,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:mN(O,s)}))}}if(h.length>0){const p=iCe(h,t,n,s);u.push(...p)}return{changes:u,updatedInternals:c}}async function tJn({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 LBe(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 b_t(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}`;LBe("source",c,d,e,s,i),LBe("target",c,u,e,a,l),t.set(r.id,r)}}function x_t(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:x_t(n,t):!1}function FBe(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 nJn(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!x_t(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 Nne({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 rJn({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=yL(a,t);return{x:i.x-a.x,y:i.y-a.y}}function sJn({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:O,nodeId:_,nodeClickDistance:T=0}){h=jh(k);function E({x:R,y:L}){const{nodeLookup:D,nodeExtent:B,snapGrid:H,snapToGrid:q,nodeOrigin:F,onNodeDrag:V,onSelectionDrag:M,onError:G,updateNodePositions:z}=t();a={x:R,y:L};let P=!1;const U=l.size>1,W=U&&B?Xve(vL(l)):null,Y=U&&q?rJn({dragItems:l,snapGrid:H,x:R,y:L}):null;for(const[te,J]of l){if(!D.has(te))continue;let ee={x:R-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)}:yL(ee,H));let re=null;if(U&&B&&!J.extent&&W){const{positionAbsolute:ne}=J.internals,se=ne.x-W.x+B[0][0],ce=ne.x+J.measured.width-W.x2+B[1][0],le=ne.y-W.y+B[0][1],ye=ne.y+J.measured.height-W.y2+B[1][1];re=[[se,le],[ce,ye]]}const{position:oe,positionAbsolute:X}=a_t({nodeId:te,nextPosition:ee,nodeLookup:D,nodeExtent:re||B,nodeOrigin:F,onError:G});P=P||J.position.x!==oe.x||J.position.y!==oe.y,J.position=oe,J.internals.positionAbsolute=X}if(m=m||P,!!P&&(z(l,!0),v&&(r||V||!_&&M))){const[te,J]=Nne({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:R,panBy:L,autoPanSpeed:D,autoPanOnNodeDrag:B}=t();if(!B){c=!1,cancelAnimationFrame(i);return}const[H,q]=o_t(u,d,D);(H!==0||q!==0)&&(a.x=(a.x??0)-H/R[2],a.y=(a.y??0)-q/R[2],await L({x:H,y:q})&&E(a)),i=requestAnimationFrame(N)}function I(R){const{nodeLookup:L,multiSelectionActive:D,nodesDraggable:B,transform:H,snapGrid:q,snapToGrid:F,selectNodesOnDrag:V,onNodeDragStart:M,onSelectionDragStart:G,unselectNodesAndEdges:z}=t();f=!0,(!V||!O)&&!D&&_&&(L.get(_)?.selected||z()),O&&V&&_&&e?.(_);const P=X$(R.sourceEvent,{transform:H,snapGrid:q,snapToGrid:F,containerBounds:d});if(a=P,l=nJn(L,B,P,_),l.size>0&&(n||M||!_&&G)){const[U,W]=Nne({nodeId:_,dragItems:l,nodeLookup:L});n?.(R.sourceEvent,l,U,W),M?.(R.sourceEvent,U,W),_||G?.(R.sourceEvent,W)}}const A=LCt().clickDistance(T).on("start",R=>{const{domNode:L,nodeDragThreshold:D,transform:B,snapGrid:H,snapToGrid:q}=t();d=L?.getBoundingClientRect()||null,p=!1,m=!1,v=R.sourceEvent,D===0&&I(R),a=X$(R.sourceEvent,{transform:B,snapGrid:H,snapToGrid:q,containerBounds:d}),u=Ng(R.sourceEvent,d)}).on("drag",R=>{const{autoPanOnNodeDrag:L,transform:D,snapGrid:B,snapToGrid:H,nodeDragThreshold:q,nodeLookup:F}=t(),V=X$(R.sourceEvent,{transform:D,snapGrid:B,snapToGrid:H,containerBounds:d});if(v=R.sourceEvent,(R.sourceEvent.type==="touchmove"&&R.sourceEvent.touches.length>1||_&&!F.has(_))&&(p=!0),!p){if(!c&&L&&f&&(c=!0,N()),!f){const M=Ng(R.sourceEvent,d),G=M.x-u.x,z=M.y-u.y;Math.sqrt(G*G+z*z)>q&&I(R)}(a.x!==V.xSnapped||a.y!==V.ySnapped)&&l&&f&&(u=Ng(R.sourceEvent,d),E(V))}}).on("end",R=>{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,F]=Nne({nodeId:_,dragItems:l,nodeLookup:L,dragging:!1});s?.(R.sourceEvent,l,q,F),B?.(R.sourceEvent,q,F),_||H?.(R.sourceEvent,F)}}}).filter(R=>{const L=R.target;return!R.button&&(!x||!FBe(L,`.${x}`,k))&&(!w||FBe(L,w,k))});h.call(A)}function b(){h?.on(".drag",null)}return{update:y,destroy:b}}function aJn(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())nD(s,mN(a))>0&&r.push(a);return r}const iJn=250;function oJn(e,t,n,r){let s=[],a=1/0;const i=aJn(e,n,t+iJn);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}=hC(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 w_t(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,...hC(i,c,c.position,!0)}:c}function S_t(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function lJn(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const k_t=()=>!0;function cJn(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=k_t,onReconnectEnd:x,updateConnection:w,getTransform:k,getFromHandle:O,autoPanSpeed:_,dragThreshold:T=1,handleDomNode:E}){const N=d_t(e.target);let I=0,A;const{x:R,y:L}=Ng(e),D=S_t(a,E),B=l?.getBoundingClientRect();let H=!1;if(!B||!D)return;const q=w_t(s,D,r,c,t);if(!q)return;let F=Ng(e,B),V=!1,M=null,G=!1,z=null;function P(){if(!d||!B)return;const[oe,X]=o_t(F,B,_);h({x:oe,y:X}),I=requestAnimationFrame(P)}const U={...q,nodeId:s,type:D,position:q.position},W=c.get(s);let te={inProgress:!0,isValid:null,from:hC(W,U,rr.Left,!0),fromHandle:U,fromPosition:U.position,fromNode:W,to:F,toHandle:null,toPosition:EBe[U.position],toNode:null,pointer:F};function J(){H=!0,w(te),m?.(e,{nodeId:s,handleId:r,handleType:D})}T===0&&J();function ee(oe){if(!H){const{x:ye,y:he}=Ng(oe),xe=ye-R,Ae=he-L;if(!(xe*xe+Ae*Ae>T*T))return;J()}if(!O()||!U){re(oe);return}const X=k();F=Ng(oe,B),A=oJn(bL(F,X,!1,[1,1]),n,c,U),V||(P(),V=!0);const ne=O_t(oe,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});z=ne.handleDomNode,M=ne.connection,G=lJn(!!A,ne.isValid);const se=c.get(s),ce=se?hC(se,U,rr.Left,!0):te.from,le={...te,from:ce,isValid:G,to:ne.toHandle&&G?kU({x:ne.toHandle.x,y:ne.toHandle.y},X):F,toHandle:ne.toHandle,toPosition:G&&ne.toHandle?ne.toHandle.position:EBe[U.position],toNode:ne.toHandle?c.get(ne.toHandle.nodeId):null,pointer:F};w(le),te=le}function re(oe){if(!("touches"in oe&&oe.touches.length>0)){if(H){(A||z)&&M&&G&&v?.(M);const{inProgress:X,...ne}=te,se={...ne,toPosition:te.toHandle?te.toPosition:null};y?.(oe,se),a&&x?.(oe,se)}p(),cancelAnimationFrame(I),V=!1,G=!1,M=null,z=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 O_t(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=k_t,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=S_t(void 0,y),w=y.getAttribute("data-nodeid"),k=y.getAttribute("data-handleid"),O=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=O&&_&&(n===hN.Strict?f&&x==="source"||!f&&x==="target":w!==r||k!==s);b.isValid=N&&u(T),b.toHandle=w_t(w,x,k,d,n,!0)}return b}const nye={onPointerDown:cJn,isValid:O_t};function uJn({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=jh(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(),O=w.sourceEvent.ctrlKey&&rD()?10:1,_=-w.sourceEvent.deltaY*(w.sourceEvent.deltaMode===1?.05:w.sourceEvent.deltaMode?1:.002)*d,T=k[2]*Math.pow(2,_*O);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 O=[w.sourceEvent.clientX??w.sourceEvent.touches[0].clientX,w.sourceEvent.clientY??w.sourceEvent.touches[0].clientY],_=[O[0]-v[0],O[1]-v[1]];v=O;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=JCt().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:yg}}const LW=e=>({x:e.x,y:e.y,zoom:e.k}),Ine=({x:e,y:t,zoom:n})=>$W.translate(e,t).scale(n),AT=(e,t)=>e.target.closest(`.${t}`),C_t=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),dJn=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,Ane=(e,t=0,n=dJn,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},__t=e=>{const t=e.ctrlKey&&rD()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function fJn({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(AT(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=yg(d),b=__t(d),x=f*Math.pow(2,b);r.scaleTo(n,x,y,d);return}const h=d.deltaMode===1?20:1;let p=s===gO.Vertical?0:d.deltaX*h,m=s===gO.Horizontal?0:d.deltaY*h;!rD()&&d.shiftKey&&s!==gO.Vertical&&(p=d.deltaY*h,m=0),r.translateBy(n,-(p/f)*a,-(m/f)*a,{internal:!0});const v=LW(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 hJn({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=AT(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function pJn({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=LW(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 mJn({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&C_t(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,LW(a.transform))}}function gJn({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&C_t(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=LW(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function vJn({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"&&(AT(f,`${u}-flow__node`)||AT(f,`${u}-flow__edge`)))return!0;if(!r&&!h&&!s&&!a&&!n||i||d&&!m||AT(f,l)&&m||AT(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 yJn({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=JCt().scaleExtent([t,n]).translateExtent(r),h=jh(e).call(f);x({x:s.x,y:s.y,zoom:pN(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const p=h.on("wheel.zoom"),m=h.on("dblclick.zoom");f.wheelDelta(__t);function v(A,R){return h?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?xx:p9).transform(Ane(h,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:R,onPaneContextMenu:L,userSelectionActive:D,panOnScroll:B,panOnDrag:H,panOnScrollMode:q,panOnScrollSpeed:F,preventScrolling:V,zoomOnPinch:M,zoomOnScroll:G,zoomOnDoubleClick:z,zoomActivationKeyPressed:P,lib:U,onTransformChange:W,connectionInProgress:Y,paneClickDistance:te,selectionOnDrag:J}){D&&!u.isZoomingOrPanning&&b();const ee=B&&!P&&!D;f.clickDistance(J?1/0:!jg(te)||te<0?0:te);const re=ee?fJn({zoomPanValues:u,noWheelClassName:A,d3Selection:h,d3Zoom:f,panOnScrollMode:q,panOnScrollSpeed:F,zoomOnPinch:M,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):hJn({noWheelClassName:A,preventScrolling:V,d3ZoomHandler:p});if(h.on("wheel.zoom",re,{passive:!1}),!D){const X=pJn({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",X);const ne=mJn({zoomPanValues:u,panOnDrag:H,onPaneContextMenu:!!L,onPanZoom:a,onTransformChange:W});f.on("zoom",ne);const se=gJn({zoomPanValues:u,panOnDrag:H,panOnScroll:B,onPaneContextMenu:L,onPanZoomEnd:l,onDraggingChange:c});f.on("end",se)}const oe=vJn({zoomActivationKeyPressed:P,panOnDrag:H,zoomOnScroll:G,panOnScroll:B,zoomOnDoubleClick:z,zoomOnPinch:M,userSelectionActive:D,noPanClassName:R,noWheelClassName:A,lib:U,connectionInProgress:Y});f.filter(oe),z?h.on("dblclick.zoom",m):h.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,R,L){const D=Ine(A),B=f?.constrain()(D,R,L);return B&&await v(B),new Promise(H=>H(B))}async function w(A,R){const L=Ine(A);return await v(L,R),new Promise(D=>D(L))}function k(A){if(h){const R=Ine(A),L=h.property("__zoom");(L.k!==A.zoom||L.x!==A.x||L.y!==A.y)&&f?.transform(h,R,null,{sync:!0})}}function O(){const A=h?XCt(h.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function _(A,R){return h?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?xx:p9).scaleTo(Ane(h,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function T(A,R){return h?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?xx:p9).scaleBy(Ane(h,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function E(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const R=!jg(A)||A<0?0:A;f?.clickDistance(R)}return{update:y,destroy:b,setViewport:w,setViewportConstrained:x,getViewport:O,scaleTo:_,scaleBy:T,setScaleExtent:E,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var vN;(function(e){e.Line="line",e.Handle="handle"})(vN||(vN={}));function bJn({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 zBe(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 aw(e,t){return Math.max(0,t-e)}function iw(e,t){return Math.max(0,e-t)}function zF(e,t,n){return Math.max(0,t-e,e-n)}function BBe(e,t){return e?!t:t}function xJn(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:O,height:_,aspectRatio:T}=e;let E=Math.floor(d?p-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=O+(c?-E:E),A=_+(u?-N:N),R=-a[0]*O,L=-a[1]*_;let D=zF(I,v,y),B=zF(A,b,x);if(i){let F=0,V=0;c&&E<0?F=aw(w+E+R,i[0][0]):!c&&E>0&&(F=iw(w+I+R,i[1][0])),u&&N<0?V=aw(k+N+L,i[0][1]):!u&&N>0&&(V=iw(k+A+L,i[1][1])),D=Math.max(D,F),B=Math.max(B,V)}if(l){let F=0,V=0;c&&E>0?F=iw(w+E,l[0][0]):!c&&E<0&&(F=aw(w+I,l[1][0])),u&&N>0?V=iw(k+N,l[0][1]):!u&&N<0&&(V=aw(k+A,l[1][1])),D=Math.max(D,F),B=Math.max(B,V)}if(s){if(d){const F=zF(I/T,b,x)*T;if(D=Math.max(D,F),i){let V=0;!c&&!u||c&&!u&&h?V=iw(k+L+I/T,i[1][1])*T:V=aw(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=aw(k+I/T,l[1][1])*T:V=iw(k+(c?E:-E)/T,l[0][1])*T,D=Math.max(D,V)}}if(f){const F=zF(A*T,v,y)/T;if(B=Math.max(B,F),i){let V=0;!c&&!u||u&&!c&&h?V=iw(w+A*T+R,i[1][0])/T:V=aw(w+(u?N:-N)*T+R,i[0][0])/T,B=Math.max(B,V)}if(l){let V=0;!c&&!u||u&&!c&&h?V=aw(w+A*T,l[1][0])/T:V=iw(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=(BBe(c,u)?-E:E)/T:E=(BBe(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:O+(c?-E:E),height:_+(u?-N:N),x:a[0]*E*(c?-1:1)+H,y:a[1]*N*(u?-1:1)+q}}const E_t={width:0,height:0,x:0,y:0},wJn={...E_t,pointerX:0,pointerY:0,aspectRatio:1};function SJn(e){return[[0,0],[e.measured.width,e.measured.height]]}function kJn(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 OJn({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=jh(e);let i={controlDirection:zBe("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={...E_t},x={...wJn};i={boundaries:d,resizeDirection:h,keepAspectRatio:f,controlDirection:zBe(u)};let w,k=null,O=[],_,T,E,N=!1;const I=LCt().on("start",A=>{const{nodeLookup:R,transform:L,snapGrid:D,snapToGrid:B,nodeOrigin:H,paneDomNode:q}=n();if(w=R.get(t),!w)return;k=q?.getBoundingClientRect()??null;const{xSnapped:F,ySnapped:V}=X$(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:F,pointerY:V,aspectRatio:b.width/b.height},_=void 0,w.parentId&&(w.extent==="parent"||w.expandParent)&&(_=R.get(w.parentId),T=_&&w.extent==="parent"?SJn(_):void 0),O=[],E=void 0;for(const[M,G]of R)if(G.parentId===t&&(O.push({id:M,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const z=kJn(G,w,G.origin??H);E?E=[[Math.min(z[0][0],E[0][0]),Math.min(z[0][1],E[0][1])],[Math.max(z[1][0],E[1][0]),Math.max(z[1][1],E[1][1])]]:E=z}p?.(A,{...b})}).on("drag",A=>{const{transform:R,snapGrid:L,snapToGrid:D,nodeOrigin:B}=n(),H=X$(A.sourceEvent,{transform:R,snapGrid:L,snapToGrid:D,containerBounds:k}),q=[];if(!w)return;const{x:F,y:V,width:M,height:G}=b,z={},P=w.origin??B,{width:U,height:W,x:Y,y:te}=xJn(x,i.controlDirection,H,i.boundaries,i.keepAspectRatio,P,T,E),J=U!==M,ee=W!==G,re=Y!==F&&J,oe=te!==V&&ee;if(!re&&!oe&&!J&&!ee)return;if((re||oe||P[0]===1||P[1]===1)&&(z.x=re?Y:b.x,z.y=oe?te:b.y,b.x=z.x,b.y=z.y,O.length>0)){const ce=Y-F,le=te-V;for(const ye of O)ye.position={x:ye.position.x-ce+P[0]*(U-M),y:ye.position.y-le+P[1]*(W-G)},q.push(ye)}if((J||ee)&&(z.width=J&&(!i.resizeDirection||i.resizeDirection==="horizontal")?U:b.width,z.height=ee&&(!i.resizeDirection||i.resizeDirection==="vertical")?W:b.height,b.width=z.width,b.height=z.height),_&&w.expandParent){const ce=P[0]*(z.width??0);z.x&&z.x<ce&&(b.x=ce,x.x=x.x-(z.x-ce));const le=P[1]*(z.height??0);z.y&&z.y<le&&(b.y=le,x.y=x.y-(z.y-le))}const X=bJn({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(z,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 CJn={},UBe=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:()=>{(CJn?"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},_Jn=e=>e?UBe(e):UBe,{useDebugValue:EJn}=qe,{useSyncExternalStoreWithSelector:TJn}=qIn,jJn=e=>e;function T_t(e,t=jJn,n){const r=TJn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return EJn(r),r}const qBe=(e,t)=>{const n=_Jn(e),r=(s,a=t)=>T_t(n,s,a);return Object.assign(r,n),r},NJn=(e,t)=>e?qBe(e,t):qBe;function so(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 FW=g.createContext(null),IJn=FW.Provider,j_t=Ty.error001();function Gs(e,t){const n=g.useContext(FW);if(n===null)throw new Error(j_t);return T_t(n,e,t)}function _o(){const e=g.useContext(FW);if(e===null)throw new Error(j_t);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const VBe={display:"none"},AJn={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},N_t="react-flow__node-desc",I_t="react-flow__edge-desc",RJn="react-flow__aria-live",PJn=e=>e.ariaLiveMessage,$Jn=e=>e.ariaLabelConfig;function MJn({rfId:e}){const t=Gs(PJn);return o.jsx("div",{id:`${RJn}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:AJn,children:t})}function DJn({rfId:e,disableKeyboardA11y:t}){const n=Gs($Jn);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${N_t}-${e}`,style:VBe,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${I_t}-${e}`,style:VBe,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(MJn,{rfId:e})]})}const xL=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:Zl(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});xL.displayName="Panel";function LJn({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(xL,{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 FJn=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}},BF=e=>e.id;function zJn(e,t){return so(e.selectedNodes.map(BF),t.selectedNodes.map(BF))&&so(e.selectedEdges.map(BF),t.selectedEdges.map(BF))}function BJn({onSelectionChange:e}){const t=_o(),{selectedNodes:n,selectedEdges:r}=Gs(FJn,zJn);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const UJn=e=>!!e.onSelectionChangeHandlers;function qJn({onSelectionChange:e}){const t=Gs(UJn);return e||t?o.jsx(BJn,{onSelectionChange:e}):null}const rye=typeof window<"u"?g.useLayoutEffect:g.useEffect,A_t=[0,0],VJn={x:0,y:0,zoom:1},HJn=["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"],HBe=[...HJn,"rfId"],WJn=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}),WBe={translateExtent:JM,nodeOrigin:A_t,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function ZJn(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Gs(WJn,so),u=_o();rye(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=WBe,l()}),[]);const d=g.useRef(WBe);return rye(()=>{for(const f of HBe){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:MXn(h)}):f==="fitView"?u.setState({fitViewQueued:h}):f==="fitViewOptions"?u.setState({fitViewOptions:h}):u.setState({[f]:h})))}d.current=e},HBe.map(f=>e[f])),null}function ZBe(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function GJn(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=ZBe(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:ZBe()?.matches?"dark":"light"}const GBe=typeof document<"u"?document:null;function sD(e=null,t={target:GBe,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 GWn(this):new HWn(this)}getCursor(t,n=0,r){let s=t.doc?t:gs.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?uT(this,s,n,r):cT(this,s,n,r)}}class iCt{constructor(t){this.spec=t}}function qWn(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 cT(e,t,n,r){let s;return e.wholeWord&&(s=VWn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=qWn(e.test,t,s)),new zx(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function VWn(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(uU(s,n-a))!=bo.Word||t(dU(s,n-a))!=bo.Word)&&(t(dU(s,r-a))!=bo.Word||t(uU(s,r-a))!=bo.Word))}class HWn extends iCt{constructor(t){super(t)}nextMatch(t,n,r){let s=cT(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=cT(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=cT(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=cT(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=cT(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 WWn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function uT(e,t,n,r){let s;return e.wholeWord&&(s=ZWn(t.charCategorizer(t.selection.main.head))),e.test&&(s=WWn(e.test,t,s)),new rCt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function uU(e,t){return e.slice(Ac(e,t,!1),t)}function dU(e,t){return e.slice(t,Ac(e,t))}function ZWn(e){return(t,n,r)=>!r[0].length||(e(uU(r.input,r.index))!=bo.Word||e(dU(r.input,r.index))!=bo.Word)&&(e(dU(r.input,r.index+r[0].length))!=bo.Word||e(uU(r.input,r.index+r[0].length))!=bo.Word)}class GWn extends iCt{nextMatch(t,n,r){let s=uT(this.spec,t,r,t.doc.length).next();return s.done&&(s=uT(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=uT(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=uT(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=uT(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 WM=vr.define(),LOe=vr.define(),t1=xl.define({create(e){return new Tte(Uve(e).create(),null)},update(e,t){for(let n of t.effects)n.is(WM)?e=new Tte(n.value.create(),e.panel):n.is(LOe)&&(e=new Tte(e.query,n.value?FOe:null));return e},provide:e=>MM.from(e,t=>t.panel)});class Tte{constructor(t,n){this.query=t,this.panel=n}}const QWn=Tn.mark({class:"cm-searchMatch"}),YWn=Tn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),KWn=ko.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(t1))}update(e){let t=e.state.field(t1);(t!=e.startState.field(t1)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return Tn.none;let{view:n}=this,r=new nd;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?YWn:QWn)})}return r.finish()}},{decorations:e=>e.decorations});function hL(e){return t=>{let n=t.state.field(t1,!1);return n&&n.query.spec.valid?e(t,n):cCt(t)}}const fU=hL((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(PI);return e.dispatch({selection:s,effects:[zOe(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),lCt(e),!0}),hU=hL((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(PI);return e.dispatch({selection:a,effects:[zOe(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),lCt(e),!0}),XWn=hL((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)}),JWn=({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 zx(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},t7e=hL((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(Rt.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(zOe(e,i)),d.push(n.facet(PI).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),eZn=hL((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:Rt.announce.of(r),userEvent:"input.replace.all"}),!0});function FOe(e){return e.state.facet(PI).createPanel(e)}function Uve(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(PI);return new aCt({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 oCt(e){let t=tOe(e,FOe);return t&&t.dom.querySelector("[main-field]")}function lCt(e){let t=oCt(e);t&&t==e.root.activeElement&&t.select()}const cCt=e=>{let t=e.state.field(t1,!1);if(t&&t.panel){let n=oCt(e);if(n&&n!=e.root.activeElement){let r=Uve(e.state,t.query.spec);r.valid&&e.dispatch({effects:WM.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[LOe.of(!0),t?WM.of(Uve(e.state,t.query.spec)):vr.appendConfig.of(sZn)]});return!0},uCt=e=>{let t=e.state.field(t1,!1);if(!t||!t.panel)return!1;let n=tOe(e,FOe);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:LOe.of(!1)}),!0},tZn=[{key:"Mod-f",run:cCt,scope:"editor search-panel"},{key:"F3",run:fU,shift:hU,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:fU,shift:hU,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:uCt,scope:"editor search-panel"},{key:"Mod-Shift-l",run:JWn},{key:"Mod-Alt-g",run:IWn},{key:"Mod-d",run:UWn,preventDefault:!0}];class nZn{constructor(t){this.view=t;let n=this.query=t.state.field(t1).query.spec;this.commit=this.commit.bind(this),this.searchField=hi("input",{value:n.search,placeholder:ph(t,"Find"),"aria-label":ph(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=hi("input",{value:n.replace,placeholder:ph(t,"Replace"),"aria-label":ph(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=hi("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=hi("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=hi("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return hi("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=hi("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>fU(t),[ph(t,"next")]),r("prev",()=>hU(t),[ph(t,"previous")]),r("select",()=>XWn(t),[ph(t,"all")]),hi("label",null,[this.caseField,ph(t,"match case")]),hi("label",null,[this.reField,ph(t,"regexp")]),hi("label",null,[this.wordField,ph(t,"by word")]),...t.state.readOnly?[]:[hi("br"),this.replaceField,r("replace",()=>t7e(t),[ph(t,"replace")]),r("replaceAll",()=>eZn(t),[ph(t,"replace all")])],hi("button",{name:"close",onclick:()=>uCt(t),"aria-label":ph(t,"close"),type:"button"},["×"])])}commit(){let t=new aCt({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:WM.of(t)}))}keydown(t){k9n(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?hU:fU)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),t7e(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(WM)&&!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(PI).top}}function ph(e,t){return e.state.phrase(t)}const IF=30,AF=/[\s\.,:;?!]/;function zOe(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-IF),i=Math.min(s,n+IF),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<IF;c++)if(!AF.test(l[c+1])&&AF.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-IF;c--)if(!AF.test(l[c-1])&&AF.test(l[c])){l=l.slice(0,c);break}}return Rt.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const rZn=Rt.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"}}),sZn=[t1,ip.low(KWn),rZn];class n7e{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class Fk{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(ZM).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new nd,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=vZn(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,Tn.widget({widget:new hZn(m),diagnostics:l.slice()}));else{let v=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(h,p,Tn.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 Fk(u,n,uN(u))}}function uN(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 n7e(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new n7e(r.from,a,r.diagnostic)}}),r}function aZn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(ZM).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(dCt))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function iZn(e,t){return e.field(Ph,!1)?t:t.concat(vr.appendConfig.of(yZn))}const dCt=vr.define(),BOe=vr.define(),fCt=vr.define(),Ph=xl.define({create(){return new Fk(Tn.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=uN(n,e.selected.diagnostic,a)||uN(n,null,a)}!n.size&&s&&t.state.facet(ZM).autoPanel&&(s=null),e=new Fk(n,s,r)}for(let n of t.effects)if(n.is(dCt)){let r=t.state.facet(ZM).autoPanel?n.value.length?GM.open:null:e.panel;e=Fk.init(n.value,r,t.state)}else n.is(BOe)?e=new Fk(e.diagnostics,n.value?GM.open:null,e.selected):n.is(fCt)&&(e=new Fk(e.diagnostics,e.panel,n.value));return e},provide:e=>[MM.from(e,t=>t.panel),Rt.decorations.from(e,t=>t.diagnostics)]}),oZn=Tn.mark({class:"cm-lintRange cm-lintRange-active"});function lZn(e,t,n){let{diagnostics:r}=e.state.field(Ph),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(ZM).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:cZn(e,s)}}}:null}function cZn(e,t){return hi("ul",{class:"cm-tooltip-lint"},t.map(n=>pCt(e,n,!1)))}const uZn=e=>{let t=e.state.field(Ph,!1);(!t||!t.panel)&&e.dispatch({effects:iZn(e.state,[BOe.of(!0)])});let n=tOe(e,GM.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},r7e=e=>{let t=e.state.field(Ph,!1);return!t||!t.panel?!1:(e.dispatch({effects:BOe.of(!1)}),!0)},dZn=e=>{let t=e.state.field(Ph,!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)},fZn=[{key:"Mod-Shift-m",run:uZn,preventDefault:!0},{key:"F8",run:dZn}],ZM=kn.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...Vy(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:s7e,tooltipFilter:s7e,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 s7e(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function hCt(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 pCt(e,t,n){var r;let s=n?hCt(t.actions):[];return hi("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},hi("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=uN(e.state.field(Ph).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),hi("u",u.slice(d,d+1)),u.slice(d+1)],h=a.markClass?" "+a.markClass:"";return hi("button",{type:"button",class:"cm-diagnosticAction"+h,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&hi("div",{class:"cm-diagnosticSource"},t.source))}class hZn extends op{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return hi("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class a7e{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=pCt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class GM{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)r7e(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=hCt(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=uN(this.view.state.field(Ph).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=hi("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=hi("div",{class:"cm-panel-lint"},this.list,hi("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>r7e(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Ph).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(Ph),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 a7e(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 a7e(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(Ph),r=uN(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:fCt.of(r)})}static open(t){return new GM(t)}}function pZn(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 RF(e){return pZn(`<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 mZn=Rt.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:RF("#d11")},".cm-lintRange-warning":{backgroundImage:RF("orange")},".cm-lintRange-info":{backgroundImage:RF("#999")},".cm-lintRange-hint":{backgroundImage:RF("#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 gZn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function vZn(e){let t="hint",n=1;for(let r of e){let s=gZn(r.severity);s>n&&(n=s,t=r.severity)}return t}const yZn=[Ph,Rt.decorations.compute([Ph],e=>{let{selected:t,panel:n}=e.field(Ph);return!t||!n||t.from==t.to?Tn.none:Tn.set([oZn.range(t.from,t.to)])}),d7n(lZn,{hideOn:aZn}),mZn];var i7e=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(oUn)),t.defaultKeymap!==!1&&(a=a.concat(TWn)),t.searchKeymap!==!1&&(a=a.concat(tZn)),t.historyKeymap!==!1&&(a=a.concat($Hn)),t.foldKeymap!==!1&&(a=a.concat(W7n)),t.completionKeymap!==!1&&(a=a.concat(lkt)),t.lintKeymap!==!1&&(a=a.concat(fZn));var i=[];return t.lineNumbers!==!1&&i.push(jSt()),t.highlightActiveLineGutter!==!1&&i.push(C7n()),t.highlightSpecialChars!==!1&&i.push(F9n()),t.history!==!1&&i.push(_Hn()),t.foldGutter!==!1&&i.push(Y7n()),t.drawSelection!==!1&&i.push(j9n()),t.dropCursor!==!1&&i.push(P9n()),t.allowMultipleSelections!==!1&&i.push(gs.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(L7n()),t.syntaxHighlighting!==!1&&i.push(pS(eBn,{fallback:!0})),t.bracketMatching!==!1&&i.push(oBn()),t.closeBrackets!==!1&&i.push(rUn()),t.autocompletion!==!1&&i.push(okt()),t.rectangularSelection!==!1&&i.push(J9n()),s!==!1&&i.push(n7n()),t.highlightActiveLine!==!1&&i.push(H9n()),t.highlightSelectionMatches!==!1&&i.push(PWn()),t.tabSize&&typeof t.tabSize=="number"&&i.push(NI.of(" ".repeat(t.tabSize))),i.concat([jI.of(a.flat())]).filter(Boolean)};const bZn="#e5c07b",o7e="#e06c75",xZn="#56b6c2",wZn="#ffffff",f9="#abb2bf",qve="#7d8799",SZn="#61afef",kZn="#98c379",l7e="#d19a66",OZn="#c678dd",CZn="#21252b",c7e="#2c313a",u7e="#282c34",jte="#353a42",_Zn="#3E4451",d7e="#528bff",EZn=Rt.theme({"&":{color:f9,backgroundColor:u7e},".cm-content":{caretColor:d7e},".cm-cursor, .cm-dropCursor":{borderLeftColor:d7e},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:_Zn},".cm-panels":{backgroundColor:CZn,color:f9},".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:u7e,color:qve,border:"none"},".cm-activeLineGutter":{backgroundColor:c7e},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:jte},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:jte,borderBottomColor:jte},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:c7e,color:f9}}},{dark:!0}),TZn=Jg.define([{tag:ue.keyword,color:OZn},{tag:[ue.name,ue.deleted,ue.character,ue.propertyName,ue.macroName],color:o7e},{tag:[ue.function(ue.variableName),ue.labelName],color:SZn},{tag:[ue.color,ue.constant(ue.name),ue.standard(ue.name)],color:l7e},{tag:[ue.definition(ue.name),ue.separator],color:f9},{tag:[ue.typeName,ue.className,ue.number,ue.changed,ue.annotation,ue.modifier,ue.self,ue.namespace],color:bZn},{tag:[ue.operator,ue.operatorKeyword,ue.url,ue.escape,ue.regexp,ue.link,ue.special(ue.string)],color:xZn},{tag:[ue.meta,ue.comment],color:qve},{tag:ue.strong,fontWeight:"bold"},{tag:ue.emphasis,fontStyle:"italic"},{tag:ue.strikethrough,textDecoration:"line-through"},{tag:ue.link,color:qve,textDecoration:"underline"},{tag:ue.heading,fontWeight:"bold",color:o7e},{tag:[ue.atom,ue.bool,ue.special(ue.variableName)],color:l7e},{tag:[ue.processingInstruction,ue.string,ue.inserted],color:kZn},{tag:ue.invalid,color:wZn}]),jZn=[EZn,pS(TZn)];var NZn=Rt.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),IZn=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(jI.of([jWn])),m&&(typeof m=="boolean"?v.unshift(i7e()):v.unshift(i7e(m))),h&&v.unshift(Q9n(h)),d){case"light":v.push(NZn);break;case"dark":v.push(jZn);break;case"none":break;default:v.push(d);break}return i===!1&&v.push(Rt.editable.of(!1)),c&&v.push(gs.readOnly.of(!0)),[...v]},AZn=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 RZn{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 f7e{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 Nte=null,PZn=()=>typeof window>"u"?new f7e:(Nte||(Nte=new f7e),Nte),$Zn=Rt.theme({"& .cm-scroller":{height:"100% !important"}}),h7e=null,Ite=null;function MZn(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===h7e||(h7e=i,Ite=Rt.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a}})),Ite}var p7e=qy.define(),DZn=200,LZn=[];function FZn(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?LZn: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,O=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,R=e.readOnly,L=R===void 0?!1:R,D=e.indentWithTab,B=D===void 0?!0:D,H=e.basicSetup,q=H===void 0?!0:H,F=e.root,V=e.initialState,M=g.useState(),G=M[0],z=M[1],P=g.useState(),U=P[0],W=P[1],Y=g.useState(),te=Y[0],J=Y[1],ee=g.useState(()=>({current:null}))[0],re=g.useState(()=>({current:null}))[0],oe=MZn(p,v,b,w,O,T),X=Rt.updateListener.of(ce=>{if(ce.docChanged&&typeof r=="function"&&!ce.transactions.some(he=>he.annotation(p7e))){ee.current?ee.current.reset():(ee.current=new RZn(()=>{if(re.current){var he=re.current;re.current=null,he()}ee.current=null},DZn),PZn().add(ee.current));var le=ce.state.doc,ye=le.toString();r(ye,ce)}s&&s(AZn(ce))}),ne=IZn({theme:f,editable:A,readOnly:L,placeholder:N,indentWithTab:B,basicSetup:q}),se=[X,...oe?[oe]:[],$Zn,...ne];return i&&typeof i=="function"&&se.push(Rt.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 ye=new Rt({state:le,parent:G,root:F});W(ye),a&&a(ye,le)}}return()=>{U&&(J(void 0),W(void 0))}},[G,te]),g.useEffect(()=>{e.container&&z(e.container)},[e.container]),g.useEffect(()=>()=>{U&&(U.destroy(),W(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,O,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,ye=()=>{U&&t!==U.state.doc.toString()&&U.dispatch({changes:{from:0,to:U.state.doc.toString().length,insert:t||""},annotations:[p7e.of(!0)]})};le?re.current=ye:ye()}}},[t,U]),{state:te,setState:J,view:U,setView:W,container:G,setContainer:z}}var zZn=["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,O=e.basicSetup,_=e.placeholder,T=e.indentWithTab,E=e.editable,N=e.readOnly,I=e.root,A=e.initialState,R=SOt(e,zZn),L=g.useRef(null),D=FZn({root:I,value:s,autoFocus:h,theme:m,height:v,minHeight:y,maxHeight:b,width:x,minWidth:w,maxWidth:k,basicSetup:O,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,F=D.setContainer;g.useImperativeHandle(t,()=>({editor:L.current,state:B,view:H}),[L,q,B,H]);var V=g.useCallback(G=>{L.current=G,F(G)},[F]);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",cC({ref:V,className:""+M+(n?" "+n:"")},R))});rd.displayName="CodeMirror";const mCt={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 Ate=null;function BZn(){return Ate||(Ate=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Ua(()=>import("./core-DHjfgEgY.js"),__vite__mapDeps([0,1,2]),import.meta.url),Ua(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[Ua(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Ua(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Ua(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Ua(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Ua(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Ua(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Ua(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Ua(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Ua(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Ua(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Ua(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Ua(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Ua(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Ua(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([4,5,6]),import.meta.url),Ua(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Ua(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),Ate}async function UZn(e,t){const n=mCt[t?.toLowerCase()];if(!n)return null;const r=await BZn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function qZn(e){const t=e?.split(".").pop()?.toLowerCase();return t?mCt[t]:void 0}function VZn(e){return new aC(iOe.define(e))}const gCt=[vg.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return Ua(()=>Promise.resolve().then(()=>jF),void 0,import.meta.url).then(e=>e.javascript())}}),vg.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return Ua(()=>Promise.resolve().then(()=>bBn),void 0,import.meta.url).then(e=>e.json())}}),vg.of({name:"JSX",extensions:["jsx"],load(){return Ua(()=>Promise.resolve().then(()=>jF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),vg.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return Ua(()=>Promise.resolve().then(()=>hHn),void 0,import.meta.url).then(e=>e.markdown())}}),vg.of({name:"TSX",extensions:["tsx"],load(){return Ua(()=>Promise.resolve().then(()=>jF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),vg.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return Ua(()=>Promise.resolve().then(()=>jF),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),vg.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return Ua(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>VZn(e.shell))}})];function HZn(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 WZn(e){const t=HZn(e);return okt({override:[ZZn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function ZZn(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 GZn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,QZn=Tn.mark({class:"cm-variable-highlight"}),m7e=new xSt({regexp:GZn,decoration:()=>QZn}),YZn=ko.fromClass(class{decorations;constructor(e){this.decorations=m7e.createDeco(e)}update(e){this.decorations=m7e.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),KZn=YZn;function XZn(){const e=AI({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=Rt.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 JZn(){const e=Rt.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,pS(t)]}const c0=()=>{const e=d_().resolvedTheme==="dark";return g.useMemo(()=>e?XZn():JZn(),[e])},eGn=oo(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"}}),tGn=ip.highest(Rt.editorAttributes.of({style:"outline: none"})),nGn=ip.highest(Rt.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),rGn=[tGn,nGn],Hr=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=c0(),b=e?JSON.stringify(e,null,2):t??"",x=g.useMemo(()=>{const w=[...rGn];return f&&w.push(Rt.lineWrapping),a==="json"?w.push(Bh):a==="markdown"&&w.push(ROe({base:lC,codeLanguages:gCt})),i&&a==="markdown"&&w.push(KZn),c&&a==="markdown"&&w.push(WZn(c)),h===!1&&w.push(gs.readOnly.of(!0)),w},[a,i,c,h,f]);return o.jsxs("div",{className:K(eGn({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}})]})}),sGn=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},aGn=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=c0(),{settings:r,setSettings:s}=nW(),a=r?.tracingOptions,i=g.useMemo(()=>sGn(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(me,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),o.jsx(rd,{value:l,onChange:d,theme:n,extensions:[Bh],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(ae,{type:"button",onClick:f,children:"Save"})})]})},iGn=()=>{const[e,t]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(bn,{children:[o.jsx(mn,{asChild:!0,children:o.jsx(ae,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(Ke,{children:o.jsx(Q0e,{})})})}),o.jsx(gn,{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(Ts,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx(Nr,{children:o.jsx(aGn,{onSaved:()=>t(!1)})})]})})]})};function oGn({status:e}){switch(e){case"running":return o.jsx(Ht,{});case"failed":return o.jsx(tr,{className:"text-accent2"});case"canceled":return o.jsx(Cs,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(c1,{className:"text-neutral3"});case"suspended":return o.jsx(BV,{className:"text-accent3"});case"success":return o.jsx(Dr,{className:"text-accent1"});default:return o.jsx(c1,{className:"text-neutral3"})}}function vCt({status:e}){return o.jsxs(bn,{children:[o.jsx(mn,{asChild:!0,children:o.jsx(Ke,{"aria-label":e,className:"shrink-0",children:o.jsx(oGn,{status:e})})}),o.jsx(gn,{children:e})]})}var Rte,g7e;function UOe(){if(g7e)return Rte;g7e=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 Rte=r,Rte}var Pte,v7e;function lGn(){return v7e||(v7e=1,Pte="2.2.4"),Pte}var $te,y7e;function cGn(){return y7e||(y7e=1,$te={Graph:UOe(),version:lGn()}),$te}var Mte,b7e;function uGn(){if(b7e)return Mte;b7e=1;var e=UOe();Mte={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 Mte}var Dte,x7e;function dGn(){if(x7e)return Dte;x7e=1,Dte=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 Dte}var Lte,w7e;function yCt(){if(w7e)return Lte;w7e=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 Lte=e,Lte}var Fte,S7e;function bCt(){if(S7e)return Fte;S7e=1;var e=yCt();Fte=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 Fte}var zte,k7e;function fGn(){if(k7e)return zte;k7e=1;var e=bCt();zte=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return zte}var Bte,O7e;function xCt(){if(O7e)return Bte;O7e=1,Bte=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 Bte}var Ute,C7e;function hGn(){if(C7e)return Ute;C7e=1;var e=xCt();Ute=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return Ute}var qte,_7e;function pGn(){if(_7e)return qte;_7e=1,qte=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 qte}var Vte,E7e;function wCt(){if(E7e)return Vte;E7e=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 Vte=e,e.CycleException=t,Vte}var Hte,T7e;function mGn(){if(T7e)return Hte;T7e=1;var e=wCt();Hte=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return Hte}var Wte,j7e;function SCt(){if(j7e)return Wte;j7e=1,Wte=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 Wte}var Zte,N7e;function gGn(){if(N7e)return Zte;N7e=1;var e=SCt();Zte=t;function t(n,r){return e(n,r,"post")}return Zte}var Gte,I7e;function vGn(){if(I7e)return Gte;I7e=1;var e=SCt();Gte=t;function t(n,r){return e(n,r,"pre")}return Gte}var Qte,A7e;function yGn(){if(A7e)return Qte;A7e=1;var e=UOe(),t=yCt();Qte=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 Qte}var Yte,R7e;function bGn(){return R7e||(R7e=1,Yte={components:dGn(),dijkstra:bCt(),dijkstraAll:fGn(),findCycles:hGn(),floydWarshall:pGn(),isAcyclic:mGn(),postorder:gGn(),preorder:vGn(),prim:yGn(),tarjan:xCt(),topsort:wCt()}),Yte}var Kte,P7e;function Zg(){if(P7e)return Kte;P7e=1;var e=cGn();return Kte={Graph:e.Graph,json:uGn(),alg:bGn(),version:e.version},Kte}var Xte,$7e;function xGn(){if($7e)return Xte;$7e=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 Xte=e,Xte}var Jte,M7e;function wGn(){if(M7e)return Jte;M7e=1;let e=Zg().Graph,t=xGn();Jte=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 Jte}var ene,D7e;function Pl(){if(D7e)return ene;D7e=1;let e=Zg().Graph;ene={addBorderNode:d,addDummyNode:t,applyWithChunking:p,asNonCompoundGraph:r,buildLayerMatrix:l,intersectRect:i,mapValues:_,maxRank:m,normalizeRanks:c,notime:b,partition:v,pick:O,predecessorWeights:a,range:k,removeEmptyRanks:u,simplify:n,successorWeights:s,time:y,uniqueId:w,zipObject:T};function t(E,N,I,A){for(var R=A;E.hasNode(R);)R=w(A);return I.dummy=N,E.setNode(R,I),R}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},R=E.edge(I);N.setEdge(I.v,I.w,{weight:A.weight+R.weight,minlen:Math.max(A.minlen,R.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(R=>{A[R.w]=(A[R.w]||0)+E.edge(R).weight}),A});return T(E.nodes(),N)}function a(E){let N=E.nodes().map(I=>{let A={};return E.inEdges(I).forEach(R=>{A[R.v]=(A[R.v]||0)+E.edge(R).weight}),A});return T(E.nodes(),N)}function i(E,N){let I=E.x,A=E.y,R=N.x-I,L=N.y-A,D=E.width/2,B=E.height/2;if(!R&&!L)throw new Error("Not possible to find intersection inside of the rectangle");let H,q;return Math.abs(L)*D>Math.abs(R)*B?(L<0&&(B=-B),H=B*R/L,q=B):(R<0&&(D=-D),H=D,q=D*L/R),{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),R=A.rank;R!==void 0&&(N[R][A.order]=I)}),N}function c(E){let N=E.nodes().map(A=>{let R=E.node(A).rank;return R===void 0?Number.MAX_VALUE:R}),I=p(Math.min,N);E.nodes().forEach(A=>{let R=E.node(A);Object.hasOwn(R,"rank")&&(R.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 R=0,L=E.graph().nodeRankFactor;Array.from(A).forEach((D,B)=>{D===void 0&&B%L!==0?--R:D!==void 0&&R&&D.forEach(H=>E.node(H).rank+=R)})}function d(E,N,I,A){let R={width:0,height:0};return arguments.length>=4&&(R.rank=I,R.order=A),t(E,"border",R,N)}function f(E,N=h){const I=[];for(let A=0;A<E.length;A+=N){const R=E.slice(A,A+N);I.push(R)}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 R=E.node(A).rank;return R===void 0?Number.MIN_VALUE:R});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 R=[];for(let L=E;A(L);L+=I)R.push(L);return R}function O(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,[R,L])=>(A[R]=I(L,R),A),{})}function T(E,N){return E.reduce((I,A,R)=>(I[A]=N[R],I),{})}return ene}var tne,L7e;function SGn(){if(L7e)return tne;L7e=1;let e=wGn(),t=Pl().uniqueId;tne={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 tne}var nne,F7e;function kGn(){if(F7e)return nne;F7e=1;let e=Pl();nne={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 nne}var rne,z7e;function pU(){if(z7e)return rne;z7e=1;const{applyWithChunking:e}=Pl();rne={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 rne}var sne,B7e;function kCt(){if(B7e)return sne;B7e=1;var e=Zg().Graph,t=pU().slack;sne=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 sne}var ane,U7e;function OGn(){if(U7e)return ane;U7e=1;var e=kCt(),t=pU().slack,n=pU().longestPath,r=Zg().alg.preorder,s=Zg().alg.postorder,a=Pl().simplify;ane=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,O;k=h(w);)O=p(w,x,k),m(w,x,k,O)}function l(x,w){var k=s(x,x.nodes());k=k.slice(0,k.length-1),k.forEach(O=>c(x,w,O))}function c(x,w,k){var O=x.node(k),_=O.parent;x.edge(k,_).cutvalue=u(x,w,k)}function u(x,w,k){var O=x.node(k),_=O.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,R=A?I.w:I.v;if(R!==_){var L=A===T,D=w.edge(I).weight;if(N+=L?D:-D,y(x,k,R)){var B=x.edge(k,R).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,O,_){var T=k,E=x.node(O);return w[O]=!0,x.neighbors(O).forEach(N=>{Object.hasOwn(w,N)||(k=f(x,w,k,N,O))}),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 O=k.v,_=k.w;w.hasEdge(O,_)||(O=k.w,_=k.v);var T=x.node(O),E=x.node(_),N=T,I=!1;T.lim>E.lim&&(N=E,I=!0);var A=w.edges().filter(R=>I===b(x,x.node(R.v),N)&&I!==b(x,x.node(R.w),N));return A.reduce((R,L)=>t(w,L)<t(w,R)?L:R)}function m(x,w,k,O){var _=k.v,T=k.w;x.removeEdge(_,T),x.setEdge(O.v,O.w,{}),d(x),l(x,w),v(x,w)}function v(x,w){var k=x.nodes().find(_=>!w.node(_).parent),O=r(x,k);O=O.slice(1),O.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 ane}var ine,q7e;function CGn(){if(q7e)return ine;q7e=1;var e=pU(),t=e.longestPath,n=kCt(),r=OGn();ine=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 ine}var one,V7e;function _Gn(){if(V7e)return one;V7e=1,one=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 one}var lne,H7e;function EGn(){if(H7e)return lne;H7e=1;let e=Pl();lne={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,O=x.borderTop?u:2*u,_=w!==k?1:d-f[h]+1;i.setEdge(m,w,{weight:O,minlen:_,nestingEdge:!0}),i.setEdge(k,v,{weight:O,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 lne}var cne,W7e;function TGn(){if(W7e)return cne;W7e=1;let e=Pl();cne=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 cne}var une,Z7e;function jGn(){if(Z7e)return une;Z7e=1,une={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 une}var dne,G7e;function NGn(){if(G7e)return dne;G7e=1;let e=Pl();dne=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 dne}var fne,Q7e;function IGn(){if(Q7e)return fne;Q7e=1;let e=Pl().zipObject;fne=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 fne}var hne,Y7e;function AGn(){if(Y7e)return hne;Y7e=1,hne=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 hne}var pne,K7e;function RGn(){if(K7e)return pne;K7e=1;let e=Pl();pne=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 pne}var mne,X7e;function PGn(){if(X7e)return mne;X7e=1;let e=Pl();mne=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 mne}var gne,J7e;function $Gn(){if(J7e)return gne;J7e=1;let e=AGn(),t=RGn(),n=PGn();gne=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 gne}var vne,eBe;function MGn(){if(eBe)return vne;eBe=1;let e=Zg().Graph,t=Pl();vne=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 vne}var yne,tBe;function DGn(){if(tBe)return yne;tBe=1,yne=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 yne}var bne,nBe;function LGn(){if(nBe)return bne;nBe=1;let e=NGn(),t=IGn(),n=$Gn(),r=MGn(),s=DGn(),a=Zg().Graph,i=Pl();bne=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 O=t(f,y);O<b&&(k=0,x=Object.assign({},y),b=O)}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 bne}var xne,rBe;function FGn(){if(rBe)return xne;rBe=1;let e=Zg().Graph,t=Pl();xne={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,O){let _=0,T=0,E=k.length,N=O[O.length-1];return O.forEach((I,A)=>{let R=s(y,I),L=R?y.node(R).order:E;(R||I===N)&&(O.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)}),O}return b.length&&b.reduce(w),x}function r(y,b){let x={};function w(O,_,T,E,N){let I;t.range(_,T).forEach(A=>{I=O[A],y.node(I).dummy&&y.predecessors(I).forEach(R=>{let L=y.node(R);L.dummy&&(L.order<E||L.order>N)&&a(x,R,I)})})}function k(O,_){let T=-1,E,N=0;return _.forEach((I,A)=>{if(y.node(I).dummy==="border"){let R=y.predecessors(I);R.length&&(E=y.node(R[0]).order,w(_,N,A,T,E),N=A,T=E)}w(_,N,_.length,E,O.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={},O={},_={};return b.forEach(T=>{T.forEach((E,N)=>{k[E]=E,O[E]=E,_[E]=N})}),b.forEach(T=>{let E=-1;T.forEach(N=>{let I=w(N);if(I.length){I=I.sort((R,L)=>_[R]-_[L]);let A=(I.length-1)/2;for(let R=Math.floor(A),L=Math.ceil(A);R<=L;++R){let D=I[R];O[N]===N&&E<_[D]&&!i(x,N,D)&&(O[D]=N,O[N]=k[N]=k[D],E=_[D])}}})}),{root:k,align:O}}function c(y,b,x,w,k){let O={},_=u(y,b,x,k),T=k?"borderLeft":"borderRight";function E(A,R){let L=_.nodes(),D=L.pop(),B={};for(;D;)B[D]?A(D):(B[D]=!0,L.push(D),L=L.concat(R(D))),D=L.pop()}function N(A){O[A]=_.inEdges(A).reduce((R,L)=>Math.max(R,O[L.v]+_.edge(L)),0)}function I(A){let R=_.outEdges(A).reduce((D,B)=>Math.min(D,O[B.w]-_.edge(B)),Number.POSITIVE_INFINITY),L=y.node(A);R!==Number.POSITIVE_INFINITY&&L.borderType!==T&&(O[A]=Math.max(O[A],R))}return E(N,_.predecessors.bind(_)),E(I,_.successors.bind(_)),Object.keys(w).forEach(A=>O[A]=O[x[A]]),O}function u(y,b,x,w){let k=new e,O=y.graph(),_=m(O.nodesep,O.edgesep,w);return b.forEach(T=>{let E;T.forEach(N=>{let I=x[N];if(k.setNode(I),E){var A=x[E],R=k.edge(A,I);k.setEdge(A,I,Math.max(_(y,N,E),R||0))}E=N})}),k}function d(y,b){return Object.values(b).reduce((x,w)=>{let k=Number.NEGATIVE_INFINITY,O=Number.POSITIVE_INFINITY;Object.entries(w).forEach(([T,E])=>{let N=v(y,T)/2;k=Math.max(E+N,k),O=Math.min(E-N,O)});const _=k-O;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(O=>{["l","r"].forEach(_=>{let T=O+_,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(O=>O[w]).sort((O,_)=>O-_);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 O=d(y,w);return f(w,O),h(w,y.graph().align)}function m(y,b,x){return(w,k,O)=>{let _=w.node(k),T=w.node(O),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 xne}var wne,sBe;function zGn(){if(sBe)return wne;sBe=1;let e=Pl(),t=FGn().positionX;wne=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 wne}var Sne,aBe;function BGn(){if(aBe)return Sne;aBe=1;let e=SGn(),t=kGn(),n=CGn(),r=Pl().normalizeRanks,s=_Gn(),a=Pl().removeEmptyRanks,i=EGn(),l=TGn(),c=jGn(),u=LGn(),d=zGn(),f=Pl(),h=Zg().Graph;Sne=p;function p(P,U){let W=U&&U.debugTiming?f.time:f.notime;W("layout",()=>{let Y=W(" buildLayoutGraph",()=>E(P));W(" runLayout",()=>m(Y,W,U)),W(" updateInputGraph",()=>v(P,Y))})}function m(P,U,W){U(" makeSpaceForEdgeLabels",()=>N(P)),U(" removeSelfEdges",()=>F(P)),U(" acyclic",()=>e.run(P)),U(" nestingGraph.run",()=>i.run(P)),U(" rank",()=>n(f.asNonCompoundGraph(P))),U(" injectEdgeLabelProxies",()=>I(P)),U(" removeEmptyRanks",()=>a(P)),U(" nestingGraph.cleanup",()=>i.cleanup(P)),U(" normalizeRanks",()=>r(P)),U(" assignRankMinMax",()=>A(P)),U(" removeEdgeLabelProxies",()=>R(P)),U(" normalize.run",()=>t.run(P)),U(" parentDummyChains",()=>s(P)),U(" addBorderSegments",()=>l(P)),U(" order",()=>u(P,W)),U(" insertSelfEdges",()=>V(P)),U(" adjustCoordinateSystem",()=>c.adjust(P)),U(" position",()=>d(P)),U(" positionSelfEdges",()=>M(P)),U(" removeBorderNodes",()=>q(P)),U(" normalize.undo",()=>t.undo(P)),U(" fixupEdgeLabelCoords",()=>B(P)),U(" undoCoordinateSystem",()=>c.undo(P)),U(" translateGraph",()=>L(P)),U(" assignNodeIntersects",()=>D(P)),U(" reversePoints",()=>H(P)),U(" acyclic.undo",()=>e.undo(P))}function v(P,U){P.nodes().forEach(W=>{let Y=P.node(W),te=U.node(W);Y&&(Y.x=te.x,Y.y=te.y,Y.rank=te.rank,U.children(W).length&&(Y.width=te.width,Y.height=te.height))}),P.edges().forEach(W=>{let Y=P.edge(W),te=U.edge(W);Y.points=te.points,Object.hasOwn(te,"x")&&(Y.x=te.x,Y.y=te.y)}),P.graph().width=U.graph().width,P.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},O=["minlen","weight","width","height","labeloffset"],_={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},T=["labelpos"];function E(P){let U=new h({multigraph:!0,compound:!0}),W=z(P.graph());return U.setGraph(Object.assign({},b,G(W,y),f.pick(W,x))),P.nodes().forEach(Y=>{let te=z(P.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,P.parent(Y))}),P.edges().forEach(Y=>{let te=z(P.edge(Y));U.setEdge(Y,Object.assign({},_,G(te,O),f.pick(te,T)))}),U}function N(P){let U=P.graph();U.ranksep/=2,P.edges().forEach(W=>{let Y=P.edge(W);Y.minlen*=2,Y.labelpos.toLowerCase()!=="c"&&(U.rankdir==="TB"||U.rankdir==="BT"?Y.width+=Y.labeloffset:Y.height+=Y.labeloffset)})}function I(P){P.edges().forEach(U=>{let W=P.edge(U);if(W.width&&W.height){let Y=P.node(U.v),J={rank:(P.node(U.w).rank-Y.rank)/2+Y.rank,e:U};f.addDummyNode(P,"edge-proxy",J,"_ep")}})}function A(P){let U=0;P.nodes().forEach(W=>{let Y=P.node(W);Y.borderTop&&(Y.minRank=P.node(Y.borderTop).rank,Y.maxRank=P.node(Y.borderBottom).rank,U=Math.max(U,Y.maxRank))}),P.graph().maxRank=U}function R(P){P.nodes().forEach(U=>{let W=P.node(U);W.dummy==="edge-proxy"&&(P.edge(W.e).labelRank=W.rank,P.removeNode(U))})}function L(P){let U=Number.POSITIVE_INFINITY,W=0,Y=Number.POSITIVE_INFINITY,te=0,J=P.graph(),ee=J.marginx||0,re=J.marginy||0;function oe(X){let ne=X.x,se=X.y,ce=X.width,le=X.height;U=Math.min(U,ne-ce/2),W=Math.max(W,ne+ce/2),Y=Math.min(Y,se-le/2),te=Math.max(te,se+le/2)}P.nodes().forEach(X=>oe(P.node(X))),P.edges().forEach(X=>{let ne=P.edge(X);Object.hasOwn(ne,"x")&&oe(ne)}),U-=ee,Y-=re,P.nodes().forEach(X=>{let ne=P.node(X);ne.x-=U,ne.y-=Y}),P.edges().forEach(X=>{let ne=P.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=W-U+ee,J.height=te-Y+re}function D(P){P.edges().forEach(U=>{let W=P.edge(U),Y=P.node(U.v),te=P.node(U.w),J,ee;W.points?(J=W.points[0],ee=W.points[W.points.length-1]):(W.points=[],J=te,ee=Y),W.points.unshift(f.intersectRect(Y,J)),W.points.push(f.intersectRect(te,ee))})}function B(P){P.edges().forEach(U=>{let W=P.edge(U);if(Object.hasOwn(W,"x"))switch((W.labelpos==="l"||W.labelpos==="r")&&(W.width-=W.labeloffset),W.labelpos){case"l":W.x-=W.width/2+W.labeloffset;break;case"r":W.x+=W.width/2+W.labeloffset;break}})}function H(P){P.edges().forEach(U=>{let W=P.edge(U);W.reversed&&W.points.reverse()})}function q(P){P.nodes().forEach(U=>{if(P.children(U).length){let W=P.node(U),Y=P.node(W.borderTop),te=P.node(W.borderBottom),J=P.node(W.borderLeft[W.borderLeft.length-1]),ee=P.node(W.borderRight[W.borderRight.length-1]);W.width=Math.abs(ee.x-J.x),W.height=Math.abs(te.y-Y.y),W.x=J.x+W.width/2,W.y=Y.y+W.height/2}}),P.nodes().forEach(U=>{P.node(U).dummy==="border"&&P.removeNode(U)})}function F(P){P.edges().forEach(U=>{if(U.v===U.w){var W=P.node(U.v);W.selfEdges||(W.selfEdges=[]),W.selfEdges.push({e:U,label:P.edge(U)}),P.removeEdge(U)}})}function V(P){var U=f.buildLayerMatrix(P);U.forEach(W=>{var Y=0;W.forEach((te,J)=>{var ee=P.node(te);ee.order=J+Y,(ee.selfEdges||[]).forEach(re=>{f.addDummyNode(P,"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(P){P.nodes().forEach(U=>{var W=P.node(U);if(W.dummy==="selfedge"){var Y=P.node(W.e.v),te=Y.x+Y.width/2,J=Y.y,ee=W.x-te,re=Y.height/2;P.setEdge(W.e,W.label),P.removeNode(U),W.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}],W.label.x=W.x,W.label.y=W.y}})}function G(P,U){return f.mapValues(f.pick(P,U),Number)}function z(P){var U={};return P&&Object.entries(P).forEach(([W,Y])=>{typeof W=="string"&&(W=W.toLowerCase()),U[W]=Y}),U}return Sne}var kne,iBe;function UGn(){if(iBe)return kne;iBe=1;let e=Pl(),t=Zg().Graph;kne={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 kne}var One,oBe;function qGn(){return oBe||(oBe=1,One="1.1.8"),One}var Cne,lBe;function VGn(){return lBe||(lBe=1,Cne={graphlib:Zg(),layout:BGn(),debug:UGn(),util:{time:Pl().time,notime:Pl().notime},version:qGn()}),Cne}var HGn=VGn();const cBe=ql(HGn);function Zl(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=Zl(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var WGn={value:()=>{}};function IW(){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 h9(n)}function h9(e){this._=e}function ZGn(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}})}h9.prototype=IW.prototype={constructor:h9,on:function(e,t){var n=this._,r=ZGn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=GGn(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]=uBe(n[s],e.name,t);else if(t==null)for(s in n)n[s]=uBe(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 h9(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 GGn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function uBe(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=WGn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Vve="http://www.w3.org/1999/xhtml";const dBe={svg:"http://www.w3.org/2000/svg",xhtml:Vve,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function AW(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),dBe.hasOwnProperty(t)?{space:dBe[t],local:e}:e}function QGn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Vve&&t.documentElement.namespaceURI===Vve?t.createElement(e):t.createElementNS(n,e)}}function YGn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function OCt(e){var t=AW(e);return(t.local?YGn:QGn)(t)}function KGn(){}function qOe(e){return e==null?KGn:function(){return this.querySelector(e)}}function XGn(e){typeof e!="function"&&(e=qOe(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 JGn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function eQn(){return[]}function CCt(e){return e==null?eQn:function(){return this.querySelectorAll(e)}}function tQn(e){return function(){return JGn(e.apply(this,arguments))}}function nQn(e){typeof e=="function"?e=tQn(e):e=CCt(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 _Ct(e){return function(){return this.matches(e)}}function ECt(e){return function(t){return t.matches(e)}}var rQn=Array.prototype.find;function sQn(e){return function(){return rQn.call(this.children,e)}}function aQn(){return this.firstElementChild}function iQn(e){return this.select(e==null?aQn:sQn(typeof e=="function"?e:ECt(e)))}var oQn=Array.prototype.filter;function lQn(){return Array.from(this.children)}function cQn(e){return function(){return oQn.call(this.children,e)}}function uQn(e){return this.selectAll(e==null?lQn:cQn(typeof e=="function"?e:ECt(e)))}function dQn(e){typeof e!="function"&&(e=_Ct(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 TCt(e){return new Array(e.length)}function fQn(){return new tp(this._enter||this._groups.map(TCt),this._parents)}function mU(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}mU.prototype={constructor:mU,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 hQn(e){return function(){return e}}function pQn(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 mU(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function mQn(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 mU(e,a[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(h[l])===c&&(s[l]=c)}function gQn(e){return e.__data__}function vQn(e,t){if(!arguments.length)return Array.from(this,gQn);var n=t?mQn:pQn,r=this._parents,s=this._groups;typeof e!="function"&&(e=hQn(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=yQn(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,O;x<m;++x)if(k=v[x]){for(x>=w&&(w=x+1);!(O=y[w])&&++w<m;);k._next=O||null}}return i=new tp(i,r),i._enter=l,i._exit=c,i}function yQn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function bQn(){return new tp(this._exit||this._groups.map(TCt),this._parents)}function xQn(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 wQn(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 SQn(){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 kQn(e){e||(e=OQn);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 OQn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function CQn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function _Qn(){return Array.from(this)}function EQn(){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 TQn(){let e=0;for(const t of this)++e;return e}function jQn(){return!this.node()}function NQn(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 IQn(e){return function(){this.removeAttribute(e)}}function AQn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function RQn(e,t){return function(){this.setAttribute(e,t)}}function PQn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function $Qn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function MQn(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 DQn(e,t){var n=AW(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?AQn:IQn:typeof t=="function"?n.local?MQn:$Qn:n.local?PQn:RQn)(n,t))}function jCt(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function LQn(e){return function(){this.style.removeProperty(e)}}function FQn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function zQn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function BQn(e,t,n){return arguments.length>1?this.each((t==null?LQn:typeof t=="function"?zQn:FQn)(e,t,n??"")):dN(this.node(),e)}function dN(e,t){return e.style.getPropertyValue(t)||jCt(e).getComputedStyle(e,null).getPropertyValue(t)}function UQn(e){return function(){delete this[e]}}function qQn(e,t){return function(){this[e]=t}}function VQn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function HQn(e,t){return arguments.length>1?this.each((t==null?UQn:typeof t=="function"?VQn:qQn)(e,t)):this.node()[e]}function NCt(e){return e.trim().split(/^|\s+/)}function VOe(e){return e.classList||new ICt(e)}function ICt(e){this._node=e,this._names=NCt(e.getAttribute("class")||"")}ICt.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 ACt(e,t){for(var n=VOe(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function RCt(e,t){for(var n=VOe(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function WQn(e){return function(){ACt(this,e)}}function ZQn(e){return function(){RCt(this,e)}}function GQn(e,t){return function(){(t.apply(this,arguments)?ACt:RCt)(this,e)}}function QQn(e,t){var n=NCt(e+"");if(arguments.length<2){for(var r=VOe(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?GQn:t?WQn:ZQn)(n,t))}function YQn(){this.textContent=""}function KQn(e){return function(){this.textContent=e}}function XQn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function JQn(e){return arguments.length?this.each(e==null?YQn:(typeof e=="function"?XQn:KQn)(e)):this.node().textContent}function eYn(){this.innerHTML=""}function tYn(e){return function(){this.innerHTML=e}}function nYn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function rYn(e){return arguments.length?this.each(e==null?eYn:(typeof e=="function"?nYn:tYn)(e)):this.node().innerHTML}function sYn(){this.nextSibling&&this.parentNode.appendChild(this)}function aYn(){return this.each(sYn)}function iYn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function oYn(){return this.each(iYn)}function lYn(e){var t=typeof e=="function"?e:OCt(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function cYn(){return null}function uYn(e,t){var n=typeof e=="function"?e:OCt(e),r=t==null?cYn:typeof t=="function"?t:qOe(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function dYn(){var e=this.parentNode;e&&e.removeChild(this)}function fYn(){return this.each(dYn)}function hYn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function pYn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function mYn(e){return this.select(e?pYn:hYn)}function gYn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function vYn(e){return function(t){e.call(this,t,this.__data__)}}function yYn(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 bYn(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 xYn(e,t,n){return function(){var r=this.__on,s,a=vYn(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 wYn(e,t,n){var r=yYn(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?xYn:bYn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function PCt(e,t,n){var r=jCt(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 SYn(e,t){return function(){return PCt(this,e,t)}}function kYn(e,t){return function(){return PCt(this,e,t.apply(this,arguments))}}function OYn(e,t){return this.each((typeof t=="function"?kYn:SYn)(e,t))}function*CYn(){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 $Ct=[null];function tp(e,t){this._groups=e,this._parents=t}function pL(){return new tp([[document.documentElement]],$Ct)}function _Yn(){return this}tp.prototype=pL.prototype={constructor:tp,select:XGn,selectAll:nQn,selectChild:iQn,selectChildren:uQn,filter:dQn,data:vQn,enter:fQn,exit:bQn,join:xQn,merge:wQn,selection:_Yn,order:SQn,sort:kQn,call:CQn,nodes:_Qn,node:EQn,size:TQn,empty:jQn,each:NQn,attr:DQn,style:BQn,property:HQn,classed:QQn,text:JQn,html:rYn,raise:aYn,lower:oYn,append:lYn,insert:uYn,remove:fYn,clone:mYn,datum:gYn,on:wYn,dispatch:OYn,[Symbol.iterator]:CYn};function jh(e){return typeof e=="string"?new tp([[document.querySelector(e)]],[document.documentElement]):new tp([[e]],$Ct)}function EYn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function yg(e,t){if(e=EYn(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 TYn={passive:!1},QM={capture:!0,passive:!1};function _ne(e){e.stopImmediatePropagation()}function yj(e){e.preventDefault(),e.stopImmediatePropagation()}function MCt(e){var t=e.document.documentElement,n=jh(e).on("dragstart.drag",yj,QM);"onselectstart"in t?n.on("selectstart.drag",yj,QM):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function DCt(e,t){var n=e.document.documentElement,r=jh(e).on("dragstart.drag",null);t&&(r.on("click.drag",yj,QM),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 PF=e=>()=>e;function Hve(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}})}Hve.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function jYn(e){return!e.ctrlKey&&!e.button}function NYn(){return this.parentNode}function IYn(e,t){return t??{x:e.x,y:e.y}}function AYn(){return navigator.maxTouchPoints||"ontouchstart"in this}function LCt(){var e=jYn,t=NYn,n=IYn,r=AYn,s={},a=IW("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,TYn).on("touchend.drag touchcancel.drag",x).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function p(k,O){if(!(d||!e.call(this,k,O))){var _=w(this,t.call(this,k,O),k,O,"mouse");_&&(jh(k.view).on("mousemove.drag",m,QM).on("mouseup.drag",v,QM),MCt(k.view),_ne(k),u=!1,l=k.clientX,c=k.clientY,_("start",k))}}function m(k){if(yj(k),!u){var O=k.clientX-l,_=k.clientY-c;u=O*O+_*_>f}s.mouse("drag",k)}function v(k){jh(k.view).on("mousemove.drag mouseup.drag",null),DCt(k.view,u),yj(k),s.mouse("end",k)}function y(k,O){if(e.call(this,k,O)){var _=k.changedTouches,T=t.call(this,k,O),E=_.length,N,I;for(N=0;N<E;++N)(I=w(this,T,k,O,_[N].identifier,_[N]))&&(_ne(k),I("start",k,_[N]))}}function b(k){var O=k.changedTouches,_=O.length,T,E;for(T=0;T<_;++T)(E=s[O[T].identifier])&&(yj(k),E("drag",k,O[T]))}function x(k){var O=k.changedTouches,_=O.length,T,E;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),T=0;T<_;++T)(E=s[O[T].identifier])&&(_ne(k),E("end",k,O[T]))}function w(k,O,_,T,E,N){var I=a.copy(),A=yg(N||_,O),R,L,D;if((D=n.call(k,new Hve("beforestart",{sourceEvent:_,target:h,identifier:E,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),T))!=null)return R=D.x-A[0]||0,L=D.y-A[1]||0,function B(H,q,F){var V=A,M;switch(H){case"start":s[E]=B,M=i++;break;case"end":delete s[E],--i;case"drag":A=yg(F||q,O),M=i;break}I.call(H,k,new Hve(H,{sourceEvent:q,subject:D,target:h,identifier:E,active:M,x:A[0]+R,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:PF(!!k),h):e},h.container=function(k){return arguments.length?(t=typeof k=="function"?k:PF(k),h):t},h.subject=function(k){return arguments.length?(n=typeof k=="function"?k:PF(k),h):n},h.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:PF(!!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 HOe(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function FCt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function mL(){}var YM=.7,gU=1/YM,bj="\\s*([+-]?\\d+)\\s*",KM="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",my="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",RYn=/^#([0-9a-f]{3,8})$/,PYn=new RegExp(`^rgb\\(${bj},${bj},${bj}\\)$`),$Yn=new RegExp(`^rgb\\(${my},${my},${my}\\)$`),MYn=new RegExp(`^rgba\\(${bj},${bj},${bj},${KM}\\)$`),DYn=new RegExp(`^rgba\\(${my},${my},${my},${KM}\\)$`),LYn=new RegExp(`^hsl\\(${KM},${my},${my}\\)$`),FYn=new RegExp(`^hsla\\(${KM},${my},${my},${KM}\\)$`),fBe={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};HOe(mL,uC,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:hBe,formatHex:hBe,formatHex8:zYn,formatHsl:BYn,formatRgb:pBe,toString:pBe});function hBe(){return this.rgb().formatHex()}function zYn(){return this.rgb().formatHex8()}function BYn(){return zCt(this).formatHsl()}function pBe(){return this.rgb().formatRgb()}function uC(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=RYn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?mBe(t):n===3?new Af(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?$F(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?$F(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=PYn.exec(e))?new Af(t[1],t[2],t[3],1):(t=$Yn.exec(e))?new Af(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=MYn.exec(e))?$F(t[1],t[2],t[3],t[4]):(t=DYn.exec(e))?$F(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=LYn.exec(e))?yBe(t[1],t[2]/100,t[3]/100,1):(t=FYn.exec(e))?yBe(t[1],t[2]/100,t[3]/100,t[4]):fBe.hasOwnProperty(e)?mBe(fBe[e]):e==="transparent"?new Af(NaN,NaN,NaN,0):null}function mBe(e){return new Af(e>>16&255,e>>8&255,e&255,1)}function $F(e,t,n,r){return r<=0&&(e=t=n=NaN),new Af(e,t,n,r)}function UYn(e){return e instanceof mL||(e=uC(e)),e?(e=e.rgb(),new Af(e.r,e.g,e.b,e.opacity)):new Af}function Wve(e,t,n,r){return arguments.length===1?UYn(e):new Af(e,t,n,r??1)}function Af(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}HOe(Af,Wve,FCt(mL,{brighter(e){return e=e==null?gU:Math.pow(gU,e),new Af(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?YM:Math.pow(YM,e),new Af(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Af(mO(this.r),mO(this.g),mO(this.b),vU(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:gBe,formatHex:gBe,formatHex8:qYn,formatRgb:vBe,toString:vBe}));function gBe(){return`#${Qk(this.r)}${Qk(this.g)}${Qk(this.b)}`}function qYn(){return`#${Qk(this.r)}${Qk(this.g)}${Qk(this.b)}${Qk((isNaN(this.opacity)?1:this.opacity)*255)}`}function vBe(){const e=vU(this.opacity);return`${e===1?"rgb(":"rgba("}${mO(this.r)}, ${mO(this.g)}, ${mO(this.b)}${e===1?")":`, ${e})`}`}function vU(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function mO(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Qk(e){return e=mO(e),(e<16?"0":"")+e.toString(16)}function yBe(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Cg(e,t,n,r)}function zCt(e){if(e instanceof Cg)return new Cg(e.h,e.s,e.l,e.opacity);if(e instanceof mL||(e=uC(e)),!e)return new Cg;if(e instanceof Cg)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 Cg(i,l,c,e.opacity)}function VYn(e,t,n,r){return arguments.length===1?zCt(e):new Cg(e,t,n,r??1)}function Cg(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}HOe(Cg,VYn,FCt(mL,{brighter(e){return e=e==null?gU:Math.pow(gU,e),new Cg(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?YM:Math.pow(YM,e),new Cg(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 Af(Ene(e>=240?e-240:e+120,s,r),Ene(e,s,r),Ene(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new Cg(bBe(this.h),MF(this.s),MF(this.l),vU(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=vU(this.opacity);return`${e===1?"hsl(":"hsla("}${bBe(this.h)}, ${MF(this.s)*100}%, ${MF(this.l)*100}%${e===1?")":`, ${e})`}`}}));function bBe(e){return e=(e||0)%360,e<0?e+360:e}function MF(e){return Math.max(0,Math.min(1,e||0))}function Ene(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 WOe=e=>()=>e;function HYn(e,t){return function(n){return e+n*t}}function WYn(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 ZYn(e){return(e=+e)==1?BCt:function(t,n){return n-t?WYn(t,n,e):WOe(isNaN(t)?n:t)}}function BCt(e,t){var n=t-e;return n?HYn(e,n):WOe(isNaN(e)?t:e)}const yU=(function e(t){var n=ZYn(t);function r(s,a){var i=n((s=Wve(s)).r,(a=Wve(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=BCt(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 GYn(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 QYn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function YYn(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]=xx(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 KYn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function xg(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function XYn(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]=xx(e[s],t[s]):r[s]=t[s];return function(a){for(s in n)r[s]=n[s](a);return r}}var Zve=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Tne=new RegExp(Zve.source,"g");function JYn(e){return function(){return e}}function eKn(e){return function(t){return e(t)+""}}function UCt(e,t){var n=Zve.lastIndex=Tne.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Zve.exec(e))&&(s=Tne.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:xg(r,s)})),n=Tne.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?eKn(c[0].x):JYn(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 xx(e,t){var n=typeof t,r;return t==null||n==="boolean"?WOe(t):(n==="number"?xg:n==="string"?(r=uC(t))?(t=r,yU):UCt:t instanceof uC?yU:t instanceof Date?KYn:QYn(t)?GYn:Array.isArray(t)?YYn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?XYn:xg)(e,t)}function ZOe(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var xBe=180/Math.PI,Gve={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function qCt(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)*xBe,skewX:Math.atan(c)*xBe,scaleX:i,scaleY:l}}var DF;function tKn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Gve:qCt(t.a,t.b,t.c,t.d,t.e,t.f)}function nKn(e){return e==null||(DF||(DF=document.createElementNS("http://www.w3.org/2000/svg","g")),DF.setAttribute("transform",e),!(e=DF.transform.baseVal.consolidate()))?Gve:(e=e.matrix,qCt(e.a,e.b,e.c,e.d,e.e,e.f))}function VCt(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:xg(u,f)},{i:v-2,x:xg(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:xg(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:xg(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:xg(u,f)},{i:v-2,x:xg(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 rKn=VCt(tKn,"px, ","px)","deg)"),sKn=VCt(nKn,", ",")",")"),aKn=1e-12;function wBe(e){return((e=Math.exp(e))+1/e)/2}function iKn(e){return((e=Math.exp(e))-1/e)/2}function oKn(e){return((e=Math.exp(2*e))-1)/(e+1)}const p9=(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<aKn)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),O=Math.log(Math.sqrt(w*w+1)-w),_=Math.log(Math.sqrt(k*k+1)-k);b=(_-O)/t,y=function(T){var E=T*b,N=wBe(O),I=u/(n*x)*(N*oKn(t*E+O)-iKn(O));return[l+I*p,c+I*m,u*N/wBe(t*E+O)]}}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 lKn(e,t){t===void 0&&(t=e,e=xx);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 fN=0,d$=0,YR=0,HCt=1e3,bU,f$,xU=0,dC=0,RW=0,XM=typeof performance=="object"&&performance.now?performance:Date,WCt=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function GOe(){return dC||(WCt(cKn),dC=XM.now()+RW)}function cKn(){dC=0}function wU(){this._call=this._time=this._next=null}wU.prototype=ZCt.prototype={constructor:wU,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?GOe():+n)+(t==null?0:+t),!this._next&&f$!==this&&(f$?f$._next=this:bU=this,f$=this),this._call=e,this._time=n,Qve()},stop:function(){this._call&&(this._call=null,this._time=1/0,Qve())}};function ZCt(e,t,n){var r=new wU;return r.restart(e,t,n),r}function uKn(){GOe(),++fN;for(var e=bU,t;e;)(t=dC-e._time)>=0&&e._call.call(void 0,t),e=e._next;--fN}function SBe(){dC=(xU=XM.now())+RW,fN=d$=0;try{uKn()}finally{fN=0,fKn(),dC=0}}function dKn(){var e=XM.now(),t=e-xU;t>HCt&&(RW-=t,xU=e)}function fKn(){for(var e,t=bU,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:bU=n);f$=e,Qve(r)}function Qve(e){if(!fN){d$&&(d$=clearTimeout(d$));var t=e-dC;t>24?(e<1/0&&(d$=setTimeout(SBe,e-XM.now()-RW)),YR&&(YR=clearInterval(YR))):(YR||(xU=XM.now(),YR=setInterval(dKn,HCt)),fN=1,WCt(SBe))}}function kBe(e,t,n){var r=new wU;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var hKn=IW("start","end","cancel","interrupt"),pKn=[],GCt=0,OBe=1,Yve=2,m9=3,CBe=4,Kve=5,g9=6;function PW(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;mKn(e,n,{name:t,index:r,group:s,on:hKn,tween:pKn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:GCt})}function QOe(e,t){var n=nv(e,t);if(n.state>GCt)throw new Error("too late; already scheduled");return n}function Hy(e,t){var n=nv(e,t);if(n.state>m9)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 mKn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=ZCt(a,0,n.time);function a(u){n.state=OBe,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!==OBe)return c();for(d in r)if(p=r[d],p.name===n.name){if(p.state===m9)return kBe(i);p.state===CBe?(p.state=g9,p.timer.stop(),p.on.call("interrupt",e,e.__data__,p.index,p.group),delete r[d]):+d<t&&(p.state=g9,p.timer.stop(),p.on.call("cancel",e,e.__data__,p.index,p.group),delete r[d])}if(kBe(function(){n.state===m9&&(n.state=CBe,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Yve,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Yve){for(n.state=m9,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=Kve,1),f=-1,h=s.length;++f<h;)s[f].call(e,d);n.state===Kve&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=g9,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function v9(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>Yve&&r.state<Kve,r.state=g9,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function gKn(e){return this.each(function(){v9(this,e)})}function vKn(e,t){var n,r;return function(){var s=Hy(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 yKn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=Hy(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 bKn(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?vKn:yKn)(n,e,t))}function YOe(e,t,n){var r=e._id;return e.each(function(){var s=Hy(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return nv(s,r).value[t]}}function QCt(e,t){var n;return(typeof t=="number"?xg:t instanceof uC?yU:(n=uC(t))?(t=n,yU):UCt)(e,t)}function xKn(e){return function(){this.removeAttribute(e)}}function wKn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function SKn(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 kKn(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 OKn(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 CKn(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 _Kn(e,t){var n=AW(e),r=n==="transform"?sKn:QCt;return this.attrTween(e,typeof t=="function"?(n.local?CKn:OKn)(n,r,YOe(this,"attr."+e,t)):t==null?(n.local?wKn:xKn)(n):(n.local?kKn:SKn)(n,r,t))}function EKn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function TKn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function jKn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&TKn(e,a)),n}return s._value=t,s}function NKn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&EKn(e,a)),n}return s._value=t,s}function IKn(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=AW(e);return this.tween(n,(r.local?jKn:NKn)(r,t))}function AKn(e,t){return function(){QOe(this,e).delay=+t.apply(this,arguments)}}function RKn(e,t){return t=+t,function(){QOe(this,e).delay=t}}function PKn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?AKn:RKn)(t,e)):nv(this.node(),t).delay}function $Kn(e,t){return function(){Hy(this,e).duration=+t.apply(this,arguments)}}function MKn(e,t){return t=+t,function(){Hy(this,e).duration=t}}function DKn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?$Kn:MKn)(t,e)):nv(this.node(),t).duration}function LKn(e,t){if(typeof t!="function")throw new Error;return function(){Hy(this,e).ease=t}}function FKn(e){var t=this._id;return arguments.length?this.each(LKn(t,e)):nv(this.node(),t).ease}function zKn(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Hy(this,e).ease=n}}function BKn(e){if(typeof e!="function")throw new Error;return this.each(zKn(this._id,e))}function UKn(e){typeof e!="function"&&(e=_Ct(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 Bx(r,this._parents,this._name,this._id)}function qKn(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 Bx(i,this._parents,this._name,this._id)}function VKn(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 HKn(e,t,n){var r,s,a=VKn(t)?QOe:Hy;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function WKn(e,t){var n=this._id;return arguments.length<2?nv(this.node(),n).on.on(e):this.each(HKn(n,e,t))}function ZKn(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function GKn(){return this.on("end.remove",ZKn(this._id))}function QKn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=qOe(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,PW(u[h],t,n,h,u,nv(d,n)));return new Bx(a,this._parents,t,n)}function YKn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=CCt(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])&&PW(p,t,n,v,h,m);a.push(h),i.push(d)}return new Bx(a,i,t,n)}var KKn=pL.prototype.constructor;function XKn(){return new KKn(this._groups,this._parents)}function JKn(e,t){var n,r,s;return function(){var a=dN(this,e),i=(this.style.removeProperty(e),dN(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function YCt(e){return function(){this.style.removeProperty(e)}}function eXn(e,t,n){var r,s=n+"",a;return function(){var i=dN(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function tXn(e,t,n){var r,s,a;return function(){var i=dN(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),dN(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function nXn(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=Hy(this,e),u=c.on,d=c.value[a]==null?l||(l=YCt(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function rXn(e,t,n){var r=(e+="")=="transform"?rKn:QCt;return t==null?this.styleTween(e,JKn(e,r)).on("end.style."+e,YCt(e)):typeof t=="function"?this.styleTween(e,tXn(e,r,YOe(this,"style."+e,t))).each(nXn(this._id,e)):this.styleTween(e,eXn(e,r,t),n).on("end.style."+e,null)}function sXn(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function aXn(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&sXn(e,i,n)),r}return a._value=t,a}function iXn(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,aXn(e,t,n??""))}function oXn(e){return function(){this.textContent=e}}function lXn(e){return function(){var t=e(this);this.textContent=t??""}}function cXn(e){return this.tween("text",typeof e=="function"?lXn(YOe(this,"text",e)):oXn(e==null?"":e+""))}function uXn(e){return function(t){this.textContent=e.call(this,t)}}function dXn(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&uXn(s)),t}return r._value=e,r}function fXn(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,dXn(e))}function hXn(){for(var e=this._name,t=this._id,n=KCt(),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);PW(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new Bx(r,this._parents,e,n)}function pXn(){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=Hy(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 mXn=0;function Bx(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function KCt(){return++mXn}var Eb=pL.prototype;Bx.prototype={constructor:Bx,select:QKn,selectAll:YKn,selectChild:Eb.selectChild,selectChildren:Eb.selectChildren,filter:UKn,merge:qKn,selection:XKn,transition:hXn,call:Eb.call,nodes:Eb.nodes,node:Eb.node,size:Eb.size,empty:Eb.empty,each:Eb.each,on:WKn,attr:_Kn,attrTween:IKn,style:rXn,styleTween:iXn,text:cXn,textTween:fXn,remove:GKn,tween:bKn,delay:PKn,duration:DKn,ease:FKn,easeVarying:BKn,end:pXn,[Symbol.iterator]:Eb[Symbol.iterator]};function gXn(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var vXn={time:null,delay:0,duration:250,ease:gXn};function yXn(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 bXn(e){var t,n;e instanceof Bx?(t=e._id,e=e._name):(t=KCt(),(n=vXn).time=GOe(),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])&&PW(c,e,t,u,i,n||yXn(c,t));return new Bx(r,this._parents,e,t)}pL.prototype.interrupt=gKn;pL.prototype.transition=bXn;const LF=e=>()=>e;function xXn(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 $W=new ix(1,0,0);XCt.prototype=ix.prototype;function XCt(e){for(;!e.__zoom;)if(!(e=e.parentNode))return $W;return e.__zoom}function jne(e){e.stopImmediatePropagation()}function KR(e){e.preventDefault(),e.stopImmediatePropagation()}function wXn(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function SXn(){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 _Be(){return this.__zoom||$W}function kXn(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function OXn(){return navigator.maxTouchPoints||"ontouchstart"in this}function CXn(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 JCt(){var e=wXn,t=SXn,n=CXn,r=kXn,s=OXn,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=p9,u=IW("start","zoom","end"),d,f,h,p=500,m=150,v=0,y=10;function b(D){D.property("__zoom",_Be).on("wheel.zoom",E,{passive:!1}).on("mousedown.zoom",N).on("dblclick.zoom",I).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",R).on("touchend.zoom touchcancel.zoom",L).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(D,B,H,q){var F=D.selection?D.selection():D;F.property("__zoom",_Be),D!==F?O(D,B,H,q):F.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 F=this.__zoom.k,V=typeof B=="function"?B.apply(this,arguments):B;return F*V},H,q)},b.scaleTo=function(D,B,H,q){b.transform(D,function(){var F=t.apply(this,arguments),V=this.__zoom,M=H==null?k(F):typeof H=="function"?H.apply(this,arguments):H,G=V.invert(M),z=typeof B=="function"?B.apply(this,arguments):B;return n(w(x(V,z),M,G),F,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,F){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($W.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,F)};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,F=B[1]-H[1]*D.k;return q===D.x&&F===D.y?D:new ix(D.k,q,F)}function k(D){return[(+D[0][0]+ +D[1][0])/2,(+D[0][1]+ +D[1][1])/2]}function O(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 F=this,V=arguments,M=_(F,V).event(q),G=t.apply(F,V),z=H==null?k(G):typeof H=="function"?H.apply(F,V):H,P=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),U=F.__zoom,W=typeof B=="function"?B.apply(F,V):B,Y=c(U.invert(z).concat(P/U.k),W.invert(z).concat(P/W.k));return function(te){if(te===1)te=W;else{var J=Y(te),ee=P/J[2];te=new ix(ee,z[0]-J[0]*ee,z[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=jh(this.that).datum();u.call(D,this.that,new xXn(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,F=Math.max(a[0],Math.min(a[1],q.k*Math.pow(2,r.apply(this,arguments)))),V=yg(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===F)return;H.mouse=[V,q.invert(V)],v9(this),H.start()}KR(D),H.wheel=setTimeout(M,m),H.zoom("mouse",n(w(x(q,F),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),F=jh(D.view).on("mousemove.zoom",z,!0).on("mouseup.zoom",P,!0),V=yg(D,H),M=D.clientX,G=D.clientY;MCt(D.view),jne(D),q.mouse=[V,this.__zoom.invert(V)],v9(this),q.start();function z(U){if(KR(U),!q.moved){var W=U.clientX-M,Y=U.clientY-G;q.moved=W*W+Y*Y>v}q.event(U).zoom("mouse",n(w(q.that.__zoom,q.mouse[0]=yg(U,H),q.mouse[1]),q.extent,i))}function P(U){F.on("mousemove.zoom mouseup.zoom",null),DCt(U.view,q.moved),KR(U),q.event(U).end()}}function I(D,...B){if(e.apply(this,arguments)){var H=this.__zoom,q=yg(D.changedTouches?D.changedTouches[0]:D,this),F=H.invert(q),V=H.k*(D.shiftKey?.5:2),M=n(w(x(H,V),q,F),t.apply(this,B),i);KR(D),l>0?jh(this).transition().duration(l).call(O,M,q,D):jh(this).call(b.transform,M,q,D)}}function A(D,...B){if(e.apply(this,arguments)){var H=D.touches,q=H.length,F=_(this,B,D.changedTouches.length===q).event(D),V,M,G,z;for(jne(D),M=0;M<q;++M)G=H[M],z=yg(G,this),z=[z,this.__zoom.invert(z),G.identifier],F.touch0?!F.touch1&&F.touch0[2]!==z[2]&&(F.touch1=z,F.taps=0):(F.touch0=z,V=!0,F.taps=1+!!d);d&&(d=clearTimeout(d)),V&&(F.taps<2&&(f=z[0],d=setTimeout(function(){d=null},p)),v9(this),F.start())}}function R(D,...B){if(this.__zooming){var H=_(this,B).event(D),q=D.changedTouches,F=q.length,V,M,G,z;for(KR(D),V=0;V<F;++V)M=q[V],G=yg(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 P=H.touch0[0],U=H.touch0[1],W=H.touch1[0],Y=H.touch1[1],te=(te=W[0]-P[0])*te+(te=W[1]-P[1])*te,J=(J=Y[0]-U[0])*J+(J=Y[1]-U[1])*J;M=x(M,Math.sqrt(te/J)),G=[(P[0]+W[0])/2,(P[1]+W[1])/2],z=[(U[0]+Y[0])/2,(U[1]+Y[1])/2]}else if(H.touch0)G=H.touch0[0],z=H.touch0[1];else return;H.zoom("touch",n(w(M,G,z),H.extent,i))}}function L(D,...B){if(this.__zooming){var H=_(this,B).event(D),q=D.changedTouches,F=q.length,V,M;for(jne(D),h&&clearTimeout(h),h=setTimeout(function(){h=null},p),V=0;V<F;++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=yg(M,this),Math.hypot(f[0]-M[0],f[1]-M[1])<y)){var G=jh(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(D){return arguments.length?(r=typeof D=="function"?D:LF(+D),b):r},b.filter=function(D){return arguments.length?(e=typeof D=="function"?D:LF(!!D),b):e},b.touchable=function(D){return arguments.length?(s=typeof D=="function"?D:LF(!!D),b):s},b.extent=function(D){return arguments.length?(t=typeof D=="function"?D:LF([[+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."},JM=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],e_t=["Enter"," ","Escape"],t_t={"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 hN;(function(e){e.Strict="strict",e.Loose="loose"})(hN||(hN={}));var gO;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(gO||(gO={}));var eD;(function(e){e.Partial="partial",e.Full="full"})(eD||(eD={}));const n_t={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var Nw;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(Nw||(Nw={}));var tD;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(tD||(tD={}));var rr;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(rr||(rr={}));const EBe={[rr.Left]:rr.Right,[rr.Right]:rr.Left,[rr.Top]:rr.Bottom,[rr.Bottom]:rr.Top};function r_t(e){return e===null?null:e?"valid":"invalid"}const s_t=e=>"id"in e&&"source"in e&&"target"in e,_Xn=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),KOe=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),gL=(e,t=[0,0])=>{const{width:n,height:r}=u0(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},EXn=(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):KOe(s)?s:t.nodeLookup.get(s.id));const l=i?SU(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return MW(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return DW(n)},vL=(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=MW(n,SU(s)),r=!0)}),r?DW(n):{x:0,y:0,width:0,height:0}},XOe=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...bL(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=nD(l,mN(u)),y=(p??0)*(m??0),b=a&&v>0;(!u.internals.handleBounds||b||v>=y||u.dragging)&&c.push(u)}return c},TXn=(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 jXn(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 NXn({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=jXn(e,i),c=vL(l),u=JOe(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 a_t({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&&gN(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=gN(f)?fC(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 IXn({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=TXn(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 pN=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),fC=(e={x:0,y:0},t,n)=>({x:pN(e.x,t[0][0],t[1][0]-(n?.width??0)),y:pN(e.y,t[0][1],t[1][1]-(n?.height??0))});function i_t(e,t,n){const{width:r,height:s}=u0(n),{x:a,y:i}=n.internals.positionAbsolute;return fC(e,[[a,i],[a+r,i+s]],t)}const TBe=(e,t,n)=>e<t?pN(Math.abs(e-t),1,t)/t:e>n?-pN(Math.abs(e-n),1,t)/t:0,o_t=(e,t,n=15,r=40)=>{const s=TBe(e.x,r,t.width-r)*n,a=TBe(e.y,r,t.height-r)*n;return[s,a]},MW=(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)}),Xve=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),DW=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),mN=(e,t=[0,0])=>{const{x:n,y:r}=KOe(e)?e.internals.positionAbsolute:gL(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}},SU=(e,t=[0,0])=>{const{x:n,y:r}=KOe(e)?e.internals.positionAbsolute:gL(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)}},l_t=(e,t)=>DW(MW(Xve(e),Xve(t))),nD=(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)},jBe=e=>jg(e.width)&&jg(e.height)&&jg(e.x)&&jg(e.y),jg=e=>!isNaN(e)&&isFinite(e),AXn=(e,t)=>{},yL=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),bL=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?yL(l,i):l},kU=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function EE(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 RXn(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=EE(e,n),s=EE(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=EE(e.top??e.y??0,n),s=EE(e.bottom??e.y??0,n),a=EE(e.left??e.x??0,t),i=EE(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 PXn(e,t,n,r,s,a){const{x:i,y:l}=kU(e,[t,n,r]),{x:c,y:u}=kU({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 JOe=(e,t,n,r,s,a)=>{const i=RXn(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=pN(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=PXn(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}},rD=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function gN(e){return e!=null&&e!=="parent"}function u0(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function c_t(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function u_t(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 NBe(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function $Xn(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function MXn(e){return{...t_t,...e||{}}}function X$(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=Ng(e),l=bL({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?yL(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const eCe=e=>({width:e.offsetWidth,height:e.offsetHeight}),d_t=e=>e?.getRootNode?.()||window?.document,DXn=["INPUT","SELECT","TEXTAREA"];function f_t(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:DXn.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const h_t=e=>"clientX"in e,Ng=(e,t)=>{const n=h_t(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)}},IBe=(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,...eCe(i)}})};function p_t({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 FF(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function ABe({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case rr.Left:return[t-FF(t-r,a),n];case rr.Right:return[t+FF(r-t,a),n];case rr.Top:return[t,n-FF(n-s,a)];case rr.Bottom:return[t,n+FF(s-n,a)]}}function tCe({sourceX:e,sourceY:t,sourcePosition:n=rr.Bottom,targetX:r,targetY:s,targetPosition:a=rr.Top,curvature:i=.25}){const[l,c]=ABe({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=ABe({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,h,p,m]=p_t({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 m_t({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 LXn({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 FXn({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=MW(SU(e),SU(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 nD(i,DW(a))>0}const zXn=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,BXn=(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)),UXn=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||zXn;let s;return s_t(e)?s={...e}:s={...e,id:r(e)},BXn(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function g_t({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=m_t({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const RBe={[rr.Left]:{x:-1,y:0},[rr.Right]:{x:1,y:0},[rr.Top]:{x:0,y:-1},[rr.Bottom]:{x:0,y:1}},qXn=({source:e,sourcePosition:t=rr.Bottom,target:n})=>t===rr.Left||t===rr.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 VXn({source:e,sourcePosition:t=rr.Bottom,target:n,targetPosition:r=rr.Top,center:s,offset:a,stepPosition:i}){const l=RBe[t],c=RBe[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=qXn({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]=m_t({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},R=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));R>=L?(v=(I.x+A.x)/2,y=m[0].y):(v=m[0].x,y=(I.y+A.y)/2)}const O={x:u.x+b.x,y:u.y+b.y},_={x:d.x+x.x,y:d.y+x.y};return[[e,...O.x!==m[0].x||O.y!==m[0].y?[O]:[],...m,..._.x!==m[m.length-1].x||_.y!==m[m.length-1].y?[_]:[],n],v,y,w,k]}function HXn(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 Jve({sourceX:e,sourceY:t,sourcePosition:n=rr.Bottom,targetX:r,targetY:s,targetPosition:a=rr.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,h,p,m,v]=VXn({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+=HXn(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 $Be(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function WXn(e){const{sourceNode:t,targetNode:n}=e;if(!$Be(t)||!$Be(n))return null;const r=t.internals.handleBounds||MBe(t.handles),s=n.internals.handleBounds||MBe(n.handles),a=DBe(r?.source??[],e.sourceHandle),i=DBe(e.connectionMode===hN.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||rr.Bottom,c=i?.position||rr.Top,u=hC(t,a,l),d=hC(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function MBe(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 hC(e,t,n=rr.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??u0(e);if(r)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case rr.Top:return{x:s+i/2,y:a};case rr.Right:return{x:s+i,y:a+l/2};case rr.Bottom:return{x:s+i/2,y:a+l};case rr.Left:return{x:s,y:a+l/2}}}function DBe(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function eye(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function ZXn(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=eye(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 v_t=1e3,GXn=10,nCe={nodeOrigin:[0,0],nodeExtent:JM,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},QXn={...nCe,checkEquality:!0};function rCe(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function YXn(e,t,n){const r=rCe(nCe,n);for(const s of e.values())if(s.parentId)aCe(s,e,t,r);else{const a=gL(s,r.nodeOrigin),i=gN(s.extent)?s.extent:r.nodeExtent,l=fC(a,i,u0(s));s.internals.positionAbsolute=l}}function KXn(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 sCe(e){return e==="manual"}function tye(e,t,n,r={}){const s=rCe(QXn,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!sCe(s.zIndexMode)?v_t: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=gL(d,s.nodeOrigin),p=gN(d.extent)?d.extent:s.nodeExtent,m=fC(h,p,u0(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:KXn(d,f),z:y_t(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&&aCe(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function XXn(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 aCe(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=rCe(nCe,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}XXn(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*GXn),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!sCe(c)?v_t:0,{x:h,y:p,z:m}=JXn(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 y_t(e,t,n){const r=jg(e.zIndex)?e.zIndex:0;return sCe(n)?r:r+(e.selected?t:0)}function JXn(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=u0(e),u=gL(e,n),d=gN(e.extent)?fC(u,e.extent,c):u;let f=fC({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=i_t(f,c,t));const h=y_t(e,s,a),p=t.internals.z??0;return{x:f.x,y:f.y,z:p>=h?p+1:h}}function iCe(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??mN(l),u=l_t(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=u0(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 eJn(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=eCe(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=gN(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=i_t(k,v,t.get(m.parentId)):w&&(k=fC(k,w,v));const O={...m,measured:v,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:IBe("source",p.nodeElement,x,f,m.id),target:IBe("target",p.nodeElement,x,f,m.id)}}};t.set(m.id,O),m.parentId&&aCe(O,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:mN(O,s)}))}}if(h.length>0){const p=iCe(h,t,n,s);u.push(...p)}return{changes:u,updatedInternals:c}}async function tJn({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 LBe(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 b_t(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}`;LBe("source",c,d,e,s,i),LBe("target",c,u,e,a,l),t.set(r.id,r)}}function x_t(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:x_t(n,t):!1}function FBe(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 nJn(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!x_t(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 Nne({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 rJn({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=yL(a,t);return{x:i.x-a.x,y:i.y-a.y}}function sJn({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:O,nodeId:_,nodeClickDistance:T=0}){h=jh(k);function E({x:R,y:L}){const{nodeLookup:D,nodeExtent:B,snapGrid:H,snapToGrid:q,nodeOrigin:F,onNodeDrag:V,onSelectionDrag:M,onError:G,updateNodePositions:z}=t();a={x:R,y:L};let P=!1;const U=l.size>1,W=U&&B?Xve(vL(l)):null,Y=U&&q?rJn({dragItems:l,snapGrid:H,x:R,y:L}):null;for(const[te,J]of l){if(!D.has(te))continue;let ee={x:R-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)}:yL(ee,H));let re=null;if(U&&B&&!J.extent&&W){const{positionAbsolute:ne}=J.internals,se=ne.x-W.x+B[0][0],ce=ne.x+J.measured.width-W.x2+B[1][0],le=ne.y-W.y+B[0][1],ye=ne.y+J.measured.height-W.y2+B[1][1];re=[[se,le],[ce,ye]]}const{position:oe,positionAbsolute:X}=a_t({nodeId:te,nextPosition:ee,nodeLookup:D,nodeExtent:re||B,nodeOrigin:F,onError:G});P=P||J.position.x!==oe.x||J.position.y!==oe.y,J.position=oe,J.internals.positionAbsolute=X}if(m=m||P,!!P&&(z(l,!0),v&&(r||V||!_&&M))){const[te,J]=Nne({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:R,panBy:L,autoPanSpeed:D,autoPanOnNodeDrag:B}=t();if(!B){c=!1,cancelAnimationFrame(i);return}const[H,q]=o_t(u,d,D);(H!==0||q!==0)&&(a.x=(a.x??0)-H/R[2],a.y=(a.y??0)-q/R[2],await L({x:H,y:q})&&E(a)),i=requestAnimationFrame(N)}function I(R){const{nodeLookup:L,multiSelectionActive:D,nodesDraggable:B,transform:H,snapGrid:q,snapToGrid:F,selectNodesOnDrag:V,onNodeDragStart:M,onSelectionDragStart:G,unselectNodesAndEdges:z}=t();f=!0,(!V||!O)&&!D&&_&&(L.get(_)?.selected||z()),O&&V&&_&&e?.(_);const P=X$(R.sourceEvent,{transform:H,snapGrid:q,snapToGrid:F,containerBounds:d});if(a=P,l=nJn(L,B,P,_),l.size>0&&(n||M||!_&&G)){const[U,W]=Nne({nodeId:_,dragItems:l,nodeLookup:L});n?.(R.sourceEvent,l,U,W),M?.(R.sourceEvent,U,W),_||G?.(R.sourceEvent,W)}}const A=LCt().clickDistance(T).on("start",R=>{const{domNode:L,nodeDragThreshold:D,transform:B,snapGrid:H,snapToGrid:q}=t();d=L?.getBoundingClientRect()||null,p=!1,m=!1,v=R.sourceEvent,D===0&&I(R),a=X$(R.sourceEvent,{transform:B,snapGrid:H,snapToGrid:q,containerBounds:d}),u=Ng(R.sourceEvent,d)}).on("drag",R=>{const{autoPanOnNodeDrag:L,transform:D,snapGrid:B,snapToGrid:H,nodeDragThreshold:q,nodeLookup:F}=t(),V=X$(R.sourceEvent,{transform:D,snapGrid:B,snapToGrid:H,containerBounds:d});if(v=R.sourceEvent,(R.sourceEvent.type==="touchmove"&&R.sourceEvent.touches.length>1||_&&!F.has(_))&&(p=!0),!p){if(!c&&L&&f&&(c=!0,N()),!f){const M=Ng(R.sourceEvent,d),G=M.x-u.x,z=M.y-u.y;Math.sqrt(G*G+z*z)>q&&I(R)}(a.x!==V.xSnapped||a.y!==V.ySnapped)&&l&&f&&(u=Ng(R.sourceEvent,d),E(V))}}).on("end",R=>{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,F]=Nne({nodeId:_,dragItems:l,nodeLookup:L,dragging:!1});s?.(R.sourceEvent,l,q,F),B?.(R.sourceEvent,q,F),_||H?.(R.sourceEvent,F)}}}).filter(R=>{const L=R.target;return!R.button&&(!x||!FBe(L,`.${x}`,k))&&(!w||FBe(L,w,k))});h.call(A)}function b(){h?.on(".drag",null)}return{update:y,destroy:b}}function aJn(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())nD(s,mN(a))>0&&r.push(a);return r}const iJn=250;function oJn(e,t,n,r){let s=[],a=1/0;const i=aJn(e,n,t+iJn);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}=hC(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 w_t(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,...hC(i,c,c.position,!0)}:c}function S_t(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function lJn(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const k_t=()=>!0;function cJn(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=k_t,onReconnectEnd:x,updateConnection:w,getTransform:k,getFromHandle:O,autoPanSpeed:_,dragThreshold:T=1,handleDomNode:E}){const N=d_t(e.target);let I=0,A;const{x:R,y:L}=Ng(e),D=S_t(a,E),B=l?.getBoundingClientRect();let H=!1;if(!B||!D)return;const q=w_t(s,D,r,c,t);if(!q)return;let F=Ng(e,B),V=!1,M=null,G=!1,z=null;function P(){if(!d||!B)return;const[oe,X]=o_t(F,B,_);h({x:oe,y:X}),I=requestAnimationFrame(P)}const U={...q,nodeId:s,type:D,position:q.position},W=c.get(s);let te={inProgress:!0,isValid:null,from:hC(W,U,rr.Left,!0),fromHandle:U,fromPosition:U.position,fromNode:W,to:F,toHandle:null,toPosition:EBe[U.position],toNode:null,pointer:F};function J(){H=!0,w(te),m?.(e,{nodeId:s,handleId:r,handleType:D})}T===0&&J();function ee(oe){if(!H){const{x:ye,y:he}=Ng(oe),xe=ye-R,Ae=he-L;if(!(xe*xe+Ae*Ae>T*T))return;J()}if(!O()||!U){re(oe);return}const X=k();F=Ng(oe,B),A=oJn(bL(F,X,!1,[1,1]),n,c,U),V||(P(),V=!0);const ne=O_t(oe,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});z=ne.handleDomNode,M=ne.connection,G=lJn(!!A,ne.isValid);const se=c.get(s),ce=se?hC(se,U,rr.Left,!0):te.from,le={...te,from:ce,isValid:G,to:ne.toHandle&&G?kU({x:ne.toHandle.x,y:ne.toHandle.y},X):F,toHandle:ne.toHandle,toPosition:G&&ne.toHandle?ne.toHandle.position:EBe[U.position],toNode:ne.toHandle?c.get(ne.toHandle.nodeId):null,pointer:F};w(le),te=le}function re(oe){if(!("touches"in oe&&oe.touches.length>0)){if(H){(A||z)&&M&&G&&v?.(M);const{inProgress:X,...ne}=te,se={...ne,toPosition:te.toHandle?te.toPosition:null};y?.(oe,se),a&&x?.(oe,se)}p(),cancelAnimationFrame(I),V=!1,G=!1,M=null,z=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 O_t(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=k_t,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=S_t(void 0,y),w=y.getAttribute("data-nodeid"),k=y.getAttribute("data-handleid"),O=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=O&&_&&(n===hN.Strict?f&&x==="source"||!f&&x==="target":w!==r||k!==s);b.isValid=N&&u(T),b.toHandle=w_t(w,x,k,d,n,!0)}return b}const nye={onPointerDown:cJn,isValid:O_t};function uJn({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=jh(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(),O=w.sourceEvent.ctrlKey&&rD()?10:1,_=-w.sourceEvent.deltaY*(w.sourceEvent.deltaMode===1?.05:w.sourceEvent.deltaMode?1:.002)*d,T=k[2]*Math.pow(2,_*O);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 O=[w.sourceEvent.clientX??w.sourceEvent.touches[0].clientX,w.sourceEvent.clientY??w.sourceEvent.touches[0].clientY],_=[O[0]-v[0],O[1]-v[1]];v=O;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=JCt().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:yg}}const LW=e=>({x:e.x,y:e.y,zoom:e.k}),Ine=({x:e,y:t,zoom:n})=>$W.translate(e,t).scale(n),AT=(e,t)=>e.target.closest(`.${t}`),C_t=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),dJn=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,Ane=(e,t=0,n=dJn,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},__t=e=>{const t=e.ctrlKey&&rD()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function fJn({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(AT(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=yg(d),b=__t(d),x=f*Math.pow(2,b);r.scaleTo(n,x,y,d);return}const h=d.deltaMode===1?20:1;let p=s===gO.Vertical?0:d.deltaX*h,m=s===gO.Horizontal?0:d.deltaY*h;!rD()&&d.shiftKey&&s!==gO.Vertical&&(p=d.deltaY*h,m=0),r.translateBy(n,-(p/f)*a,-(m/f)*a,{internal:!0});const v=LW(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 hJn({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=AT(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function pJn({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=LW(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 mJn({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&C_t(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,LW(a.transform))}}function gJn({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&C_t(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=LW(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function vJn({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"&&(AT(f,`${u}-flow__node`)||AT(f,`${u}-flow__edge`)))return!0;if(!r&&!h&&!s&&!a&&!n||i||d&&!m||AT(f,l)&&m||AT(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 yJn({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=JCt().scaleExtent([t,n]).translateExtent(r),h=jh(e).call(f);x({x:s.x,y:s.y,zoom:pN(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const p=h.on("wheel.zoom"),m=h.on("dblclick.zoom");f.wheelDelta(__t);function v(A,R){return h?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?xx:p9).transform(Ane(h,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:R,onPaneContextMenu:L,userSelectionActive:D,panOnScroll:B,panOnDrag:H,panOnScrollMode:q,panOnScrollSpeed:F,preventScrolling:V,zoomOnPinch:M,zoomOnScroll:G,zoomOnDoubleClick:z,zoomActivationKeyPressed:P,lib:U,onTransformChange:W,connectionInProgress:Y,paneClickDistance:te,selectionOnDrag:J}){D&&!u.isZoomingOrPanning&&b();const ee=B&&!P&&!D;f.clickDistance(J?1/0:!jg(te)||te<0?0:te);const re=ee?fJn({zoomPanValues:u,noWheelClassName:A,d3Selection:h,d3Zoom:f,panOnScrollMode:q,panOnScrollSpeed:F,zoomOnPinch:M,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):hJn({noWheelClassName:A,preventScrolling:V,d3ZoomHandler:p});if(h.on("wheel.zoom",re,{passive:!1}),!D){const X=pJn({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",X);const ne=mJn({zoomPanValues:u,panOnDrag:H,onPaneContextMenu:!!L,onPanZoom:a,onTransformChange:W});f.on("zoom",ne);const se=gJn({zoomPanValues:u,panOnDrag:H,panOnScroll:B,onPaneContextMenu:L,onPanZoomEnd:l,onDraggingChange:c});f.on("end",se)}const oe=vJn({zoomActivationKeyPressed:P,panOnDrag:H,zoomOnScroll:G,panOnScroll:B,zoomOnDoubleClick:z,zoomOnPinch:M,userSelectionActive:D,noPanClassName:R,noWheelClassName:A,lib:U,connectionInProgress:Y});f.filter(oe),z?h.on("dblclick.zoom",m):h.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,R,L){const D=Ine(A),B=f?.constrain()(D,R,L);return B&&await v(B),new Promise(H=>H(B))}async function w(A,R){const L=Ine(A);return await v(L,R),new Promise(D=>D(L))}function k(A){if(h){const R=Ine(A),L=h.property("__zoom");(L.k!==A.zoom||L.x!==A.x||L.y!==A.y)&&f?.transform(h,R,null,{sync:!0})}}function O(){const A=h?XCt(h.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function _(A,R){return h?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?xx:p9).scaleTo(Ane(h,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function T(A,R){return h?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?xx:p9).scaleBy(Ane(h,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function E(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const R=!jg(A)||A<0?0:A;f?.clickDistance(R)}return{update:y,destroy:b,setViewport:w,setViewportConstrained:x,getViewport:O,scaleTo:_,scaleBy:T,setScaleExtent:E,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var vN;(function(e){e.Line="line",e.Handle="handle"})(vN||(vN={}));function bJn({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 zBe(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 aw(e,t){return Math.max(0,t-e)}function iw(e,t){return Math.max(0,e-t)}function zF(e,t,n){return Math.max(0,t-e,e-n)}function BBe(e,t){return e?!t:t}function xJn(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:O,height:_,aspectRatio:T}=e;let E=Math.floor(d?p-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=O+(c?-E:E),A=_+(u?-N:N),R=-a[0]*O,L=-a[1]*_;let D=zF(I,v,y),B=zF(A,b,x);if(i){let F=0,V=0;c&&E<0?F=aw(w+E+R,i[0][0]):!c&&E>0&&(F=iw(w+I+R,i[1][0])),u&&N<0?V=aw(k+N+L,i[0][1]):!u&&N>0&&(V=iw(k+A+L,i[1][1])),D=Math.max(D,F),B=Math.max(B,V)}if(l){let F=0,V=0;c&&E>0?F=iw(w+E,l[0][0]):!c&&E<0&&(F=aw(w+I,l[1][0])),u&&N>0?V=iw(k+N,l[0][1]):!u&&N<0&&(V=aw(k+A,l[1][1])),D=Math.max(D,F),B=Math.max(B,V)}if(s){if(d){const F=zF(I/T,b,x)*T;if(D=Math.max(D,F),i){let V=0;!c&&!u||c&&!u&&h?V=iw(k+L+I/T,i[1][1])*T:V=aw(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=aw(k+I/T,l[1][1])*T:V=iw(k+(c?E:-E)/T,l[0][1])*T,D=Math.max(D,V)}}if(f){const F=zF(A*T,v,y)/T;if(B=Math.max(B,F),i){let V=0;!c&&!u||u&&!c&&h?V=iw(w+A*T+R,i[1][0])/T:V=aw(w+(u?N:-N)*T+R,i[0][0])/T,B=Math.max(B,V)}if(l){let V=0;!c&&!u||u&&!c&&h?V=aw(w+A*T,l[1][0])/T:V=iw(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=(BBe(c,u)?-E:E)/T:E=(BBe(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:O+(c?-E:E),height:_+(u?-N:N),x:a[0]*E*(c?-1:1)+H,y:a[1]*N*(u?-1:1)+q}}const E_t={width:0,height:0,x:0,y:0},wJn={...E_t,pointerX:0,pointerY:0,aspectRatio:1};function SJn(e){return[[0,0],[e.measured.width,e.measured.height]]}function kJn(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 OJn({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=jh(e);let i={controlDirection:zBe("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={...E_t},x={...wJn};i={boundaries:d,resizeDirection:h,keepAspectRatio:f,controlDirection:zBe(u)};let w,k=null,O=[],_,T,E,N=!1;const I=LCt().on("start",A=>{const{nodeLookup:R,transform:L,snapGrid:D,snapToGrid:B,nodeOrigin:H,paneDomNode:q}=n();if(w=R.get(t),!w)return;k=q?.getBoundingClientRect()??null;const{xSnapped:F,ySnapped:V}=X$(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:F,pointerY:V,aspectRatio:b.width/b.height},_=void 0,w.parentId&&(w.extent==="parent"||w.expandParent)&&(_=R.get(w.parentId),T=_&&w.extent==="parent"?SJn(_):void 0),O=[],E=void 0;for(const[M,G]of R)if(G.parentId===t&&(O.push({id:M,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const z=kJn(G,w,G.origin??H);E?E=[[Math.min(z[0][0],E[0][0]),Math.min(z[0][1],E[0][1])],[Math.max(z[1][0],E[1][0]),Math.max(z[1][1],E[1][1])]]:E=z}p?.(A,{...b})}).on("drag",A=>{const{transform:R,snapGrid:L,snapToGrid:D,nodeOrigin:B}=n(),H=X$(A.sourceEvent,{transform:R,snapGrid:L,snapToGrid:D,containerBounds:k}),q=[];if(!w)return;const{x:F,y:V,width:M,height:G}=b,z={},P=w.origin??B,{width:U,height:W,x:Y,y:te}=xJn(x,i.controlDirection,H,i.boundaries,i.keepAspectRatio,P,T,E),J=U!==M,ee=W!==G,re=Y!==F&&J,oe=te!==V&&ee;if(!re&&!oe&&!J&&!ee)return;if((re||oe||P[0]===1||P[1]===1)&&(z.x=re?Y:b.x,z.y=oe?te:b.y,b.x=z.x,b.y=z.y,O.length>0)){const ce=Y-F,le=te-V;for(const ye of O)ye.position={x:ye.position.x-ce+P[0]*(U-M),y:ye.position.y-le+P[1]*(W-G)},q.push(ye)}if((J||ee)&&(z.width=J&&(!i.resizeDirection||i.resizeDirection==="horizontal")?U:b.width,z.height=ee&&(!i.resizeDirection||i.resizeDirection==="vertical")?W:b.height,b.width=z.width,b.height=z.height),_&&w.expandParent){const ce=P[0]*(z.width??0);z.x&&z.x<ce&&(b.x=ce,x.x=x.x-(z.x-ce));const le=P[1]*(z.height??0);z.y&&z.y<le&&(b.y=le,x.y=x.y-(z.y-le))}const X=bJn({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(z,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 CJn={},UBe=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:()=>{(CJn?"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},_Jn=e=>e?UBe(e):UBe,{useDebugValue:EJn}=qe,{useSyncExternalStoreWithSelector:TJn}=qIn,jJn=e=>e;function T_t(e,t=jJn,n){const r=TJn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return EJn(r),r}const qBe=(e,t)=>{const n=_Jn(e),r=(s,a=t)=>T_t(n,s,a);return Object.assign(r,n),r},NJn=(e,t)=>e?qBe(e,t):qBe;function so(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 FW=g.createContext(null),IJn=FW.Provider,j_t=Ty.error001();function Gs(e,t){const n=g.useContext(FW);if(n===null)throw new Error(j_t);return T_t(n,e,t)}function _o(){const e=g.useContext(FW);if(e===null)throw new Error(j_t);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const VBe={display:"none"},AJn={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},N_t="react-flow__node-desc",I_t="react-flow__edge-desc",RJn="react-flow__aria-live",PJn=e=>e.ariaLiveMessage,$Jn=e=>e.ariaLabelConfig;function MJn({rfId:e}){const t=Gs(PJn);return o.jsx("div",{id:`${RJn}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:AJn,children:t})}function DJn({rfId:e,disableKeyboardA11y:t}){const n=Gs($Jn);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${N_t}-${e}`,style:VBe,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${I_t}-${e}`,style:VBe,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(MJn,{rfId:e})]})}const xL=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:Zl(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});xL.displayName="Panel";function LJn({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(xL,{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 FJn=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}},BF=e=>e.id;function zJn(e,t){return so(e.selectedNodes.map(BF),t.selectedNodes.map(BF))&&so(e.selectedEdges.map(BF),t.selectedEdges.map(BF))}function BJn({onSelectionChange:e}){const t=_o(),{selectedNodes:n,selectedEdges:r}=Gs(FJn,zJn);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const UJn=e=>!!e.onSelectionChangeHandlers;function qJn({onSelectionChange:e}){const t=Gs(UJn);return e||t?o.jsx(BJn,{onSelectionChange:e}):null}const rye=typeof window<"u"?g.useLayoutEffect:g.useEffect,A_t=[0,0],VJn={x:0,y:0,zoom:1},HJn=["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"],HBe=[...HJn,"rfId"],WJn=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}),WBe={translateExtent:JM,nodeOrigin:A_t,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function ZJn(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Gs(WJn,so),u=_o();rye(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=WBe,l()}),[]);const d=g.useRef(WBe);return rye(()=>{for(const f of HBe){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:MXn(h)}):f==="fitView"?u.setState({fitViewQueued:h}):f==="fitViewOptions"?u.setState({fitViewOptions:h}):u.setState({[f]:h})))}d.current=e},HBe.map(f=>e[f])),null}function ZBe(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function GJn(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=ZBe(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:ZBe()?.matches?"dark":"light"}const GBe=typeof document<"u"?document:null;function sD(e=null,t={target:GBe,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
  `,`
@@ -514,7 +514,7 @@ Ask one simple question at a time.`;function qBr(e,t){const n=g.useRef(e);n.curr
514
514
  `):e,H=s||u;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:[!H&&o.jsx(_C,{name:"code-section-search",label:"Search code",labelIsHidden:!0,placeholder:"Search...",value:p,onChange:N,onReset:I,size:"sm",isMinimized:f,onMinimizedChange:h}),o.jsxs(ps,{children:[o.jsx(_a,{content:e||"No content",size:"sm"}),T&&o.jsx(ae,{size:"sm","aria-label":u?"Show escaped newlines":"Show multiline text",tooltip:u?"Show escaped newlines":"Show multiline text",onClick:()=>d(q=>!q),children:u?o.jsx(h1,{}):o.jsx(J9,{})}),o.jsx(ae,{size:"sm","aria-label":"Expand",tooltip:"Expand",onClick:()=>y(!0),children:o.jsx(NXt,{})})]})]})]}),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:H?o.jsx("div",{className:"text-neutral4 font-mono break-all",children:o.jsx("pre",{className:"text-wrap",children:D})}):o.jsx(rd,{ref:O,extensions:[iN(),Rt.lineWrapping,zXe(),c],theme:l,value:e,editable:!1})}),o.jsx(pr,{open:v,onOpenChange:y,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(Ts,{children:"Expanded code view"}),o.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[!w&&o.jsx(_C,{name:"expanded-code-search",label:"Search code",labelIsHidden:!0,placeholder:"Search...",value:b,onChange:R,onReset:L,size:"sm"}),o.jsxs(ps,{children:[o.jsx(_a,{content:e||"No content",size:"sm"}),T&&o.jsx(ae,{size:"sm","aria-label":w?"Show escaped newlines":"Show multiline text",tooltip:w?"Show escaped newlines":"Show multiline text",onClick:()=>k(q=>!q),children:w?o.jsx(h1,{}):o.jsx(J9,{})}),o.jsx(a0t,{asChild:!0,children:o.jsx(ae,{size:"sm","aria-label":"Close",tooltip:"Close",children:o.jsx(tr,{})})})]})]})]}),o.jsx("div",{className:"overflow-auto px-6 pb-6",children:w?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:B})})}):o.jsx(rd,{ref:_,extensions:[iN(),Rt.lineWrapping,zXe(),c],theme:l,value:e,editable:!1})})]})})]})}function Exe(e){if(typeof e=="string"){const t=e.indexOf(`
515
515
  `);return t!==-1&&t!==e.length-1}else{if(Array.isArray(e))return e.some(t=>Exe(t));if(e&&typeof e=="object")return Object.values(e).some(t=>Exe(t))}return!1}function jVr({onClick:e,tooltip:t="Close panel",className:n}){return o.jsx(ae,{size:"md",onClick:e,"aria-label":"Close Panel",tooltip:t,className:n,children:o.jsx(tr,{})})}function NVr({children:e,ref:t}){return o.jsx("div",{ref:t,className:"min-h-0 flex-1 overflow-y-auto p-4",children:e})}function IVr({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 AVr({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 RVr({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(Ht,{size:"sm",variant:"pulse",className:"text-neutral1"})," ",e??"Loading..."]})}function PVr({onPrevious:e,onNext:t,previousLabel:n="Previous",nextLabel:r="Next"}){return o.jsxs(ps,{spacing:"close",children:[o.jsx(ae,{size:"md",tooltip:n,onClick:e,disabled:!e,children:o.jsx(J1,{})}),o.jsx(ae,{size:"md",tooltip:r,onClick:t,disabled:!t,children:o.jsx(FV,{})})]})}function $Vr({children:e}){return o.jsx("p",{className:"text-ui-sm text-neutral2 px-4 py-6",children:e??"No data found."})}function MVr({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 fn=Object.assign(MVr,{Header:IVr,Heading:AVr,CloseButton:jVr,NextPrevNav:PVr,LoadingData:RVr,NoData:$Vr,Content:NVr,CodeSection:TVr,SectionHeading:Q4t});function kO(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 DVr({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 LVr({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 FVr({className:e,...t}){return o.jsx("div",{role:"separator","aria-orientation":"horizontal",className:K("h-px bg-border1",e),...t})}function zVr({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 BVr({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 UVr({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 T_({children:e,className:t,...n}){return o.jsx("section",{className:K("grid gap-2",t),...n,children:e})}function Aje({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(XJt,{className:"size-4 shrink-0","aria-hidden":!0}),o.jsx("span",{className:"sr-only",children:"View only: "})]}):null,r]}):null]})}function qVr(e){return o.jsx(Aje,{...e})}function VVr(e){return o.jsx(Aje,{viewOnly:!0,...e})}function HVr(e){return o.jsx(Aje,{tone:"destructive",...e})}function Lc(e){return o.jsx(Y4t,{...e})}Lc.Header=zVr;Lc.HeaderText=BVr;Lc.Heading=UVr;Lc.Description=LVr;Lc.Content=DVr;Lc.Row=qVr;Lc.ViewOnlyRow=VVr;Lc.DestructiveRow=HVr;Lc.Divider=FVr;function WVr(){return AI({settings:{fontFamily:"var(--font-mono)",fontSize:"0.8125rem",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"#939393",background:"transparent"},styles:[{tag:[ue.className,ue.propertyName]}]})}function ZVr(){const e=Rt.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,pS(t)]}const GVr=()=>{const e=d_().resolvedTheme==="dark";return g.useMemo(()=>e?WVr():ZVr(),[e])};function QVr({codeStr:e="",title:t,icon:n,simplified:r=!1}){const s=GVr(),[a,i]=g.useState(!1),l=g.useMemo(()=>{try{const u=JSON.parse(e);return Txe(u||"")}catch{return!1}},[e]),c=a?e?.replace(/\\n/g,`
516
516
  `):e;return o.jsxs(Lc,{children:[o.jsxs(Lc.Header,{children:[o.jsxs(Lc.Heading,{children:[n,t]}),o.jsxs(ps,{children:[o.jsx(_a,{content:e||"No content"}),l&&o.jsx(ae,{onClick:()=>i(!a),children:a?o.jsx(h1,{}):o.jsx(J9,{})})]})]}),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:[iN(),Rt.lineWrapping],theme:s,value:c})})]})}function Txe(e){if(typeof e=="string"){const t=e.indexOf(`
517
- `);return t!==-1&&t!==e.length-1}else{if(Array.isArray(e))return e.some(t=>Txe(t));if(e&&typeof e=="object")return Object.values(e).some(t=>Txe(t))}return!1}function YVr({children:e,className:t}){return o.jsx(wTt,{render:o.jsx("div",{className:K("grid content-start gap-6 overflow-y-scroll p-6 pb-8 pl-9",t),children:e})})}function KVr({children:e,className:t}){return o.jsx("div",{className:K("flex items-center justify-between pb-4",t),children:e})}function XVr({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 JVr({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(ae,{onClick:s,disabled:!t,children:["Previous",o.jsx(J1,{})]}),o.jsxs(ae,{onClick:r,disabled:!e,children:["Next",o.jsx(FV,{})]})]})})}function eHr({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($I,{side:"right",open:n,onOpenChange:f=>{f||r?.()},children:o.jsxs(kCe,{children:[!c&&o.jsx(qW,{className:"backdrop-blur-sm"}),o.jsx(VW,{className:c?"pointer-events-none":void 0,children:o.jsxs(HW,{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(MI,{className:"sr-only",children:e}),o.jsx(OL,{className:"sr-only",children:t}),!c&&o.jsx(SCe,{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(cut,{})})}),o.jsx(wTt,{render:o.jsx("div",{ref:d,className:"absolute"})}),o.jsx(c$n,{container:u,children:o.jsx("div",{className:K("grid h-full",{"grid-rows-[auto_1fr]":!c}),children:s})})]})})]})})}function tHr({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 Oi=Object.assign(eHr,{Top:tHr,Header:KVr,Heading:XVr,Content:YVr,CodeSection:QVr,Nav:JVr}),La=()=>{const e=Qe(),t=Er(),n=wn({mutationFn:b=>e.createDataset(b),onSuccess:()=>{t.invalidateQueries({queryKey:["datasets"]})}}),r=wn({mutationFn:b=>e.updateDataset(b),onSuccess:(b,x)=>{t.invalidateQueries({queryKey:["datasets"]}),t.invalidateQueries({queryKey:["dataset",x.datasetId]})}}),s=wn({mutationFn:b=>e.deleteDataset(b),onSuccess:()=>{t.invalidateQueries({queryKey:["datasets"]})}}),a=wn({mutationFn:b=>e.addDatasetItem(b),onSuccess:(b,x)=>{t.invalidateQueries({queryKey:["dataset-items",x.datasetId]}),t.invalidateQueries({queryKey:["dataset",x.datasetId]}),t.invalidateQueries({queryKey:["dataset-versions",x.datasetId]})}}),i=wn({mutationFn:b=>e.updateDatasetItem(b),onSuccess:(b,x)=>{t.invalidateQueries({queryKey:["dataset-items",x.datasetId]}),t.invalidateQueries({queryKey:["dataset-item",x.datasetId,x.itemId]}),t.invalidateQueries({queryKey:["dataset-item-versions",x.datasetId,x.itemId]}),t.invalidateQueries({queryKey:["dataset-versions",x.datasetId]})}}),l=wn({mutationFn:({datasetId:b,itemId:x})=>e.deleteDatasetItem(b,x),onSuccess:(b,x)=>{t.invalidateQueries({queryKey:["dataset-items",x.datasetId]}),t.invalidateQueries({queryKey:["dataset",x.datasetId]}),t.invalidateQueries({queryKey:["dataset-versions",x.datasetId]})}}),c=wn({mutationFn:({datasetId:b,itemId:x})=>e.purgeDatasetItem(b,x),onSuccess:(b,x)=>{t.invalidateQueries({queryKey:["dataset-items",x.datasetId]}),t.invalidateQueries({queryKey:["dataset-item",x.datasetId,x.itemId]}),t.invalidateQueries({queryKey:["dataset-item-versions",x.datasetId,x.itemId]}),t.invalidateQueries({queryKey:["dataset-experiment-results"]}),t.invalidateQueries({queryKey:["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"]})}}),u=wn({mutationFn:b=>e.batchInsertDatasetItems(b),onSuccess:(b,x)=>{t.invalidateQueries({queryKey:["dataset-items",x.datasetId]}),t.invalidateQueries({queryKey:["dataset",x.datasetId]}),t.invalidateQueries({queryKey:["dataset-versions",x.datasetId]})}}),d=wn({mutationFn:b=>e.batchDeleteDatasetItems(b),onSuccess:(b,x)=>{t.invalidateQueries({queryKey:["dataset-items",x.datasetId]}),t.invalidateQueries({queryKey:["dataset",x.datasetId]}),t.invalidateQueries({queryKey:["dataset-versions",x.datasetId]})}}),f=wn({mutationFn:async({datasetId:b,itemIds:x})=>e.batchDeleteDatasetItems({datasetId:b,itemIds:x}),onSuccess:(b,x)=>{t.invalidateQueries({queryKey:["dataset-items",x.datasetId]}),t.invalidateQueries({queryKey:["dataset",x.datasetId]}),t.invalidateQueries({queryKey:["dataset-versions",x.datasetId]})}}),h=wn({mutationFn:b=>e.generateDatasetItems(b)}),p=wn({mutationFn:b=>e.triggerDatasetExperiment(b),onSuccess:(b,x)=>{t.invalidateQueries({queryKey:["dataset-experiments",x.datasetId]})}}),m=wn({mutationFn:b=>e.deleteExperiment(b),onSuccess:()=>{t.invalidateQueries({queryKey:["experiments"]}),t.invalidateQueries({queryKey:["dataset-experiments"]}),t.invalidateQueries({queryKey:["experiment-review-summary"]})}}),v=wn({mutationFn:b=>e.updateDatasetExperiment(b),onSuccess:(b,x)=>{t.invalidateQueries({queryKey:["experiments"]}),t.invalidateQueries({queryKey:["dataset-experiments",x.datasetId]}),t.invalidateQueries({queryKey:["dataset-experiment",x.datasetId,x.experimentId]})}}),y=wn({mutationFn:b=>e.updateDatasetExperimentResult(b),onSuccess:(b,x)=>{t.invalidateQueries({queryKey:["experiment-results",x.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,purgeItem:c,deleteItems:f,batchInsertItems:u,batchDeleteItems:d,generateItems:h,triggerExperiment:p,deleteExperiment:m,updateExperiment:v,updateExperimentResult:y}};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:O}=Pm(),{addItem:_}=La(),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 R=F=>{I.current=!0,p(F)},L=F=>{A.current=!0,v(F)},D=F=>{N.current=!0,b(F)},B=F=>{w(F)};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 F=>{if(F.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 z;if(x.trim())try{const P=JSON.parse(x);if(!Array.isArray(P)){Ve.error("Tool Mocks must be a JSON array");return}z=P}catch{Ve.error("Tool Mocks must be valid JSON");return}try{await _.mutateAsync({datasetId:d,input:V,groundTruth:M,expectedTrajectory:G,toolMocks:z,...u?{source:u}:{}});const P=T.find(U=>U.id===d);Ve.success(`Item saved to "${P?.name}"`),f(""),p("{}"),v(""),b(""),w(""),l()}catch(P){Ve.error(`Failed to save item: ${P instanceof Error?P.message:"Unknown error"}`)}},q=()=>{f(""),l()};return o.jsxs(Oi,{dialogTitle:"Save as Dataset Item",dialogDescription:"Save data as a dataset item",isOpen:i,onClose:l,level:c,children:[o.jsxs(Oi.Top,{children:[a,"›",o.jsxs(Rc,{children:[o.jsx(Lg,{})," Save as Dataset Item"]})]}),o.jsxs(Oi.Content,{children:[o.jsx(Oi.Header,{children:o.jsxs(Oi.Heading,{children:[o.jsx(Lg,{})," 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(da,{value:d,onValueChange:f,disabled:_.isPending||O,children:[o.jsx(ha,{id:"target-dataset",children:o.jsx(fa,{placeholder:O?"Loading datasets...":"Select a dataset"})}),o.jsx(pa,{children:T.length===0?o.jsx("div",{className:"text-neutral4 px-2 py-4 text-center text-sm",children:"No datasets available"}):T.map(F=>o.jsx(xr,{value:F.id,children:F.name},F.id))})]})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Hr,{value:h,onChange:R,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(Hr,{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(Hr,{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(Hr,{value:x,onChange:B,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ae,{type:"button",variant:"outline",onClick:q,children:"Cancel"}),o.jsx(ae,{type:"submit",variant:"default",disabled:_.isPending||r||!d||T.length===0,children:_.isPending?"Saving...":r?"Loading...":"Save Item"})]})]})]})]})}function nHr(e){return e?kO({input:e.input,output:e.output,groundTruth:null},2):"{}"}function rHr(e){return e?kO({score:e.score,reason:e.reason??null},2):""}function sHr({score:e,isOpen:t,onClose:n,level:r=2}){return o.jsx(K4t,{initialInput:nHr(e),initialGroundTruth:rHr(e),breadcrumb:o.jsxs(Rc,{children:[o.jsx(mKt,{})," ",w0(e?.id)]}),isOpen:t,onClose:n,level:r,source:e?.traceId?{type:"trace",referenceId:e.traceId}:void 0})}function aHr(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 qE(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}=un(),[a,i]=g.useState(!1),l=aHr(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(fn,{children:[o.jsxs(fn.Header,{children:[o.jsxs(fn.Heading,{children:["Score ",o.jsxs("b",{children:["# ",e.id]})]}),o.jsxs(ps,{className:"ml-auto shrink-0",children:[o.jsx(fn.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Previous score",nextLabel:"Next score"}),o.jsx(fn.CloseButton,{onClick:t})]})]}),o.jsxs(fn.Content,{children:[o.jsxs(Jn,{children:[e.scorer?.name!=null&&o.jsxs(o.Fragment,{children:[o.jsx(Jn.Key,{children:"Scorer"}),o.jsx(Jn.Value,{children:String(e.scorer.name)})]}),e.createdAt&&o.jsxs(o.Fragment,{children:[o.jsx(Jn.Key,{children:"Created"}),o.jsx(Jn.Value,{children:dr(new Date(e.createdAt),"MMM dd, HH:mm:ss.SSS")})]}),e.traceId&&o.jsxs(o.Fragment,{children:[o.jsx(Jn.Key,{children:"Trace Id"}),o.jsx(Jn.ValueLink,{href:`/traces?traceId=${encodeURIComponent(e.traceId)}`,as:s,children:e.traceId})]}),e.spanId&&e.traceId&&o.jsxs(o.Fragment,{children:[o.jsx(Jn.Key,{children:"Span Id"}),o.jsx(Jn.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(ae,{size:"sm",onClick:()=>i(!0),children:[o.jsx(Ke,{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(fm,{}),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(fn.CodeSection,{title:"Input",dialogTitle:qE("Input",o.jsx(u1,{}),e),icon:o.jsx(u1,{}),codeStr:JSON.stringify(e.input??null,null,2)}),o.jsx(fn.CodeSection,{title:"Output",dialogTitle:qE("Output",o.jsx(Rg,{}),e),icon:o.jsx(Rg,{}),codeStr:JSON.stringify(e.output??null,null,2)}),o.jsx(fn.CodeSection,{title:"Preprocess Prompt",dialogTitle:qE("Preprocess Prompt",o.jsx(Mp,{}),e),icon:o.jsx(Mp,{}),codeStr:e.preprocessPrompt||c,simplified:!0}),o.jsx(fn.CodeSection,{title:"Analyze Prompt",dialogTitle:qE("Analyze Prompt",o.jsx(Mp,{}),e),icon:o.jsx(Mp,{}),codeStr:e.analyzePrompt||c,simplified:!0}),o.jsx(fn.CodeSection,{title:"Generate Score Prompt",dialogTitle:qE("Generate Score Prompt",o.jsx(Mp,{}),e),icon:o.jsx(Mp,{}),codeStr:e.generateScorePrompt||c,simplified:!0}),o.jsx(fn.CodeSection,{title:"Generate Reason Prompt",dialogTitle:qE("Generate Reason Prompt",o.jsx(Mp,{}),e),icon:o.jsx(Mp,{}),codeStr:e.generateReasonPrompt||c,simplified:!0})]})]})]}),o.jsx(sHr,{score:e,isOpen:a,onClose:()=>i(!1)})]})}const BXe=["input","entity"],iHr={input:"Input",entity:"Entity"};function oHr(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 lHr(e){return{...e,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt)}}function cHr({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(BXe.filter(I=>!f.has(I))),[f]),m=g.useMemo(()=>oHr(p),[p]),v=g.useCallback(I=>{h(A=>{const R=new Set(A);return R.has(I)?R.delete(I):R.add(I),R})},[]);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:O,getRowProps:_}=no({count:e?.length??0}),T=g.useCallback(()=>{u(void 0),t?.("")},[t]);if(r)return o.jsx(Lo,{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(ae,{variant:"outline",size:"sm",children:[o.jsx(fut,{className:"size-3.5"}),"Columns"]})}),o.jsxs(at.Content,{align:"end",children:[o.jsx(at.Label,{children:"Toggle columns"}),BXe.map(I=>o.jsx(at.CheckboxItem,{checked:p.has(I),onClick:()=>v(I),children:iHr[I]},I))]})]})}),o.jsxs(Ru,{columns:m,className:"min-h-0 flex-1",scrollRef:O,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:lHr(b),onClose:T,onPrevious:w,onNext:k})})]})}const uHr=({onRunExperiment:e})=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(yr,{iconSlot:o.jsx(Cs,{}),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(ae,{variant:"primary",onClick:e,children:[o.jsx(Fc,{}),"Run Experiment"]}),o.jsxs(ae,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/evals/overview",target:"_blank",rel:"noopener noreferrer",children:["Scorers Documentation ",o.jsx(Fs,{})]})]})})});function Rje({data:e,className:t,labelsAreHidden:n,isLoading:r,LinkComponent:s}){const a=({children:i})=>n?o.jsx(N1,{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(UXe,{description:p.description,children:o.jsxs(s,{href:p.path,children:[p?.name," ",o.jsx(Fr,{})]})},p.id):p.path?o.jsx(UXe,{description:p.description,children:o.jsxs("a",{href:p.path,children:[p?.name," ",o.jsx(Fr,{})]})},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 UXe({description:e,children:t}){return e?o.jsxs(uA,{children:[o.jsx(C_,{render:qe.isValidElement(t)?t:void 0}),o.jsx(__,{className:"max-w-60 text-center",children:e})]}):t}function dHr({onEntityChange:e,onReset:t,selectedEntity:n,entityOptions:r,isLoading:s}){return o.jsxs(ps,{children:[o.jsx(Om,{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(ae,{onClick:t,disabled:s,size:"md",children:["Reset",o.jsx(Ke,{children:o.jsx(tr,{})})]})]})}const fHr=25,hHr=5e3;function pHr(e){return KL(e.state.error,"scores")||XL(e.state.error)?!1:hHr}function mHr(e,t,n){if(e?.pagination?.hasMore)return n+1}function gHr(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 vHr=({scorerId:e,entityId:t,entityType:n})=>{const r=Qe(),{inView:s,setRef:a}=i0(),i=Fy({queryKey:["scores",e,t,n],queryFn:({pageParam:d})=>r.listScoresByScorerId({scorerId:e,page:d,perPage:fHr,entityId:t,entityType:n}),initialPageParam:0,getNextPageParam:mHr,select:gHr,refetchInterval:pHr}),{hasNextPage:l,isFetchingNextPage:c,fetchNextPage:u}=i;return g.useEffect(()=>{s&&l&&!c&&u()},[s,l,c,u]),{...i,setEndOfListElement:a}},yHr=e=>{const t=Qe(),[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=Qe(),t=Hl();return gt({queryKey:["scorers",t],queryFn:()=>e.listScorers(t),staleTime:0,gcTime:0})};function bHr({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}=un();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(zo,{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 xHr({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(cnn,{}):o.jsx(onn,{})}),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 wHr({message:e="Failed to load data",className:t}){return o.jsx("span",{className:K("text-ui-sm text-accent2",t),children:e})}function SHr({children:e,className:t}){return o.jsx("span",{className:K("text-ui-md leading-relaxed text-neutral3",t),children:e})}function kHr({className:e}){return o.jsx("span",{className:K("text-sm",e),children:o.jsx(Ht,{size:"md",variant:"pulse",className:"text-neutral1"})})}function OHr({message:e="No previous value to compare",className:t}){return o.jsx("span",{className:K("text-sm text-neutral1",t),children:e})}function CHr({message:e="No data yet",className:t}){return o.jsx("span",{className:K("text-sm text-neutral1",t),children:e})}function _Hr({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 EHr({children:e,className:t}){return o.jsx("strong",{className:K("text-header-lg font-semibold text-neutral4",t),children:e})}const Xr=Object.assign(_Hr,{Label:SHr,Value:EHr,Change:xHr,NoChange:OHr,NoData:CHr,Error:wHr,Loading:kHr});function THr({children:e,className:t}){return o.jsx("div",{className:K("flex shrink-0 items-center gap-1",t),children:e})}function jHr({children:e,className:t}){return o.jsx("div",{className:K("overflow-x-auto ",t),children:e})}function e5t({children:e,className:t}){return o.jsx("p",{className:K("mt-0.5 text-ui-md leading-tight text-neutral2",t),children:e})}function NHr({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 IHr({className:e}){return o.jsx("div",{className:K("flex items-center justify-center",e),children:o.jsx(Ht,{size:"md",variant:"pulse",className:"text-neutral1"})})}function AHr({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 qXe({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 RHr({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 t5t({children:e,className:t,as:n="h2"}){return o.jsx(n,{className:K("text-ui-md font-normal text-neutral4",t),children:e})}function PHr(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(t5t,{as:r,children:t}),n&&o.jsx(e5t,{children:n})]})}function $Hr({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 Vt=Object.assign(qXe,{Root:qXe,Kpi:Xr,TopBar:$Hr,Actions:THr,TitleAndDescription:PHr,Title:t5t,Description:e5t,Summary:RHr,Loading:IHr,Error:NHr,Content:jHr,NoData:AHr});function MHr({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 VXe="#a1a1aa";function LD({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(RL,{width:"100%",height:"100%",children:o.jsxs(JTr,{data:e,children:[o.jsx(NPt,{stroke:"currentColor",strokeOpacity:.08,vertical:!1,className:"text-black dark:text-white"}),o.jsx(HL,{dataKey:"time",tick:{fontSize:10,fill:VXe,fontFamily:"var(--font-mono)"},tickLine:!1,axisLine:!1,interval:a,minTickGap:i}),o.jsx(WL,{tick:{fontSize:10,fill:VXe,fontFamily:"var(--font-mono)"},tickLine:!1,axisLine:!1,width:30,domain:r}),o.jsx(HZ,{content:o.jsx(MHr,{})}),t.map(u=>o.jsx(FPt,{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 HXe=["#22c55e","#4f83f1","#8b5cf6","#fb923c","#f472b6","#facc15"];function DHr({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:HXe[u%HXe.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(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Scores",description:"Evaluation scorer performance across all scorers."}),i&&o.jsx(Vt.Summary,{value:r!=null?`avg ${r}`:"—",label:"Across all scorers"})]}),s?o.jsx(Vt.Loading,{}):a?o.jsx(Vt.Error,{message:"Failed to load scores data"}):o.jsx(Vt.Content,{children:i?o.jsxs(vc,{defaultTab:"over-time",className:"overflow-visible",children:[o.jsxs(gc,{children:[o.jsx(zr,{value:"over-time",children:"Over Time"}),o.jsx(zr,{value:"summary",children:"Summary"})]}),o.jsx(vs,{value:"over-time",children:t.length>0?o.jsx(LD,{data:t,series:l,yDomain:[0,1]}):o.jsx(Vt.NoData,{message:"No time series data yet"})}),o.jsx(vs,{value:"summary",children:o.jsxs(fe,{columns:"auto auto auto auto auto",className:"max-h-80",mask:{left:!1},children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{sticky:"start",children:"Scorer"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Avg"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Min"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Max"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Count"})]}),e.map(c=>o.jsxs(fe.RowStatic,{children:[o.jsx(fe.RowHeaderCell,{className:"text-ui-sm",children:c.scorer}),o.jsx(fe.NumberCell,{highlight:!0,children:c.avg.toFixed(2)}),o.jsx(fe.NumberCell,{children:c.min.toFixed(2)}),o.jsx(fe.NumberCell,{children:c.max.toFixed(2)}),o.jsx(fe.NumberCell,{children:c.count.toLocaleString()})]},c.scorer))]})})]}):o.jsx(Vt.NoData,{message:"No scores data yet"})})]})}const WXe="minmax(0,1fr) minmax(0,1.5fr) auto auto auto";function LHr({scorers:e,isLoading:t,search:n="",sourceFilter:r="all"}){const{paths:s,Link:a}=un(),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}=no({count:l.length});return t?o.jsx(Lo,{columns:WXe}):o.jsxs(fe,{columns:WXe,scrollRef:c,children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{children:"Name"}),o.jsx(fe.TopCell,{children:"Description"}),o.jsx(fe.TopCell,{children:"Source"}),o.jsx(fe.TopCellSmart,{long:"Agents",short:o.jsx(uo,{}),tooltip:"Number of attached Agents",className:"text-center"}),o.jsx(fe.TopCellSmart,{long:"Workflows",short:o.jsx(pI,{}),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(fe.RowLink,{to:s.scorerLink(d.id),LinkComponent:a,...u(f),children:[o.jsx(fe.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(mt,{size:"xs",variant:"purple",className:"shrink-0",children:"trajectory"})]})}),o.jsx(fe.DescriptionCell,{children:p}),o.jsx(fe.Cell,{children:o.jsx(mt,{size:"xs",variant:d.source==="code"?"blue":"neutral",children:d.source})}),o.jsx(fe.TextCell,{className:"text-center",children:m||""}),o.jsx(fe.TextCell,{className:"text-center",children:v||""})]},d.id)})]})}const FHr=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(yr,{iconSlot:o.jsx(Cs,{}),titleSlot:"No Scorers yet",descriptionSlot:"Configure scorers in code to get started. More info in the documentation.",actionSlot:o.jsxs(ae,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/evals/overview",target:"_blank",rel:"noopener noreferrer",children:["Scorers Documentation ",o.jsx(Fs,{})]})})}),zHr=[{value:"all",label:"All sources"},{value:"code",label:"Code"},{value:"stored",label:"Stored"}];function BHr({search:e,onSearchChange:t,sourceFilter:n,onSourceFilterChange:r,onReset:s,hasActiveFilters:a}){const[i,l]=g.useState(e),c=g.useRef(e),u=By(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(ps,{spacing:"close",className:"min-w-0 flex-1",children:[o.jsxs(uu,{variant:"outline",size:"default",children:[o.jsx(Ic,{align:"inline-start",children:o.jsx(ra,{})}),o.jsx(du,{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(gje,{"aria-label":"Clear search",onClick:f,children:o.jsx(tr,{})})})]}),o.jsxs(da,{value:n,onValueChange:r,children:[o.jsx(ha,{"aria-label":"Filter by source",className:"rounded-full",children:o.jsx(fa,{placeholder:"All sources"})}),o.jsx(pa,{align:"end",children:zHr.map(p=>o.jsx(xr,{value:p.value,children:p.label},p.value))})]})]}),s&&a&&o.jsxs(ae,{onClick:h,variant:"outline",children:[o.jsx(tr,{})," Reset"]})]})}const jxe={checked(e){return e?{"data-checked":""}:{"data-unchecked":""}},...Nm,...c_},n5t=g.createContext(void 0);function UHr(){return g.useContext(n5t)}const r5t=g.createContext(void 0);function qHr(){const e=g.useContext(r5t);if(e===void 0)throw new Error(Ar(52));return e}const VHr=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=UHr(),{disabled:y,readOnly:b,required:x,form:w,checkedValue:k,touched:O=!1,validation:_,name:T,setCheckedValue:E=ia,setTouched:N=ia,registerInputRef:I=ia}=v??{},{setTouched:A,setFilled:R,state:L,disabled:D}=Rm(),B=S0t(),{labelId:H,getDescriptionProps:q}=s0(),F=D||B.disabled||y||a,V=b||i,M=x||l,G=w,z=v?k===u:u==="",P=g.useRef(null),U=g.useRef(null),W=_?.registerInput,Y=g.useCallback(Me=>W?.(Me,{controlRef:P,value:void 0}),[W]),te=Hd(d,U,I,Y);jt(()=>{U.current?.checked&&R(!0)},[R]),jt(()=>{if(U.current){if(F&&z){I(null);return}I(U.current)}},[z,F,I]);const J=Bi(),ee=u_({id:h,implicit:!1,controlRef:P}),re=f?void 0:ee,oe=HSe(c,H,U,!f,re),X={role:"radio","aria-checked":z,"aria-labelledby":oe,[nTe]:z?"":void 0,id:f?ee:J,onKeyDown(Me){Me.key==="Enter"&&Me.preventDefault()},onClick(Me){if(Me.defaultPrevented||F||V)return;Me.preventDefault();const $e=U.current;$e&&uO($e,Me)},onFocus(Me){Me.defaultPrevented||F||V||!O||(U.current?.click(),N(!1))}},{getButtonProps:ne,buttonRef:se}=Jd({disabled:F,native:f,composite:!1}),ce={type:"radio",ref:te,form:G,id:re,name:T,tabIndex:-1,style:T?yI:C1,"aria-hidden":!0,...u!==void 0?{value:cB(u)}:xa,disabled:F,checked:z,required:M,readOnly:V,onChange(Me){if(Me.nativeEvent.defaultPrevented||F||V||u===void 0)return;const $e=tn(Yi,Me.nativeEvent);E(u,$e),!$e.isCanceled&&A(!0)},onClick(Me){Me.stopPropagation()},onFocus(){P.current?.focus()}},le=g.useMemo(()=>({...L,required:M,disabled:F,readOnly:V,checked:z}),[L,F,V,z,M]),ye=le,he=v!==void 0,xe=[n,P,se],Ae=[X,m,ne,q,_?Me=>_.getValidationProps(F,Me):xa],De=Nn("span",t,{enabled:!he,state:le,ref:xe,props:Ae,stateAttributesMapping:jxe});return o.jsxs(r5t.Provider,{value:ye,children:[he?o.jsx(f2t,{tag:"span",render:r,className:s,style:p,state:le,refs:xe,props:Ae,stateAttributesMapping:jxe}):De,o.jsx("input",{...ce,suppressHydrationWarning:!0})]})}),HHr=g.forwardRef(function(t,n){const{render:r,className:s,style:a,keepMounted:i=!1,...l}=t,c=qHr(),u=c.checked,{mounted:d,transitionStatus:f,setMounted:h}=Xg(u),p={...c,transitionStatus:f},m=g.useRef(null),v=i||d,y=Nn("span",t,{ref:[n,m],state:p,props:l,stateAttributesMapping:jxe});return dc({open:u,ref:m,onComplete(){u||h(!1)}}),v?y:null});function WHr(e,t){return e.matches(":disabled")?!1:!t||e.form===t?!0:e.form===null&&!e.hasAttribute("form")}const ZHr=g.createContext(void 0);function GHr(e=!1){const t=g.useContext(ZHr);if(!t&&!e)throw new Error(Ar(86));return t}const QHr=[n0t],YHr=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:O,state:_,validation:T,setDirty:E,setFilled:N,validityData:I}=Rm(),{labelId:A}=s0(),{clearErrors:R,elementRef:L}=CI(),D=GHr(!0),B=O||a,H=k??h,q=Bi(m),[F,V]=Mf({controlled:u,default:d,name:"RadioGroup",state:"value"}),[M,G]=g.useState(!1),z=bt((se,ce)=>{c?.(se,ce),!ce.isCanceled&&V(se)}),P=T.getInputControl,U=g.useMemo(()=>({get current(){return P()}}),[P]),W=g.useRef(null),Y=g.useRef(null);function te(se){let ce;return p&&(typeof p=="function"?ce=p(se):p.current=se),W.current=se,ce}const J=bt(se=>{if(!se||se.disabled)return;Y.current||(Y.current=se);const ce=W.current,le=se.checked||ce==null||ce.disabled?te(se):void 0;return()=>{Y.current===se&&(Y.current=null),W.current===se?le?(le(),W.current=null):te(null):le?.()}}),ee=bt(()=>{const se=L.current;if(!se)return F??null;for(const ce of T.registeredInputs.keys())if(ce.checked&&WHr(ce,se))return F??null;return null});OI(U,q,F??null,ee,!B,h),Jv(F,()=>{R(H),E(F!==I.initialValue),N(F!=null),T.change(F);const se=Y.current;F==null&&se&&!se.disabled&&te(se)});const re=A??D?.legendId,oe={..._,disabled:B??!1,required:l??!1,readOnly:i??!1},X=g.useMemo(()=>({checkedValue:F,disabled:B,form:f,validation:T,name:H,readOnly:i,registerInputRef:J,required:l,setCheckedValue:z,setTouched:G,touched:M}),[F,B,f,T,H,i,J,l,z,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){ln(se.currentTarget,se.relatedTarget)||(b(!0),x(!1),w==="onBlur"&&T.commit(F))},onKeyDownCapture(se){se.key.startsWith("Arrow")&&(G(!0),x(!0))}};return o.jsx(n5t.Provider,{value:X,children:o.jsx(R$t,{render:r,className:s,style:v,state:oe,props:[ne,y,se=>T.getValidationProps(B??!1,se)],refs:[n],stateAttributesMapping:c_,enableHomeAndEndKeys:!1,modifierKeys:QHr})})}),d4=g.forwardRef(({className:e,...t},n)=>o.jsx(YHr,{ref:n,"data-slot":"radio-group",className:K("grid gap-2",e),...t}));d4.displayName="RadioGroup";const Lh=g.forwardRef(({className:e,...t},n)=>o.jsx(VHr,{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(HHr,{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"})})}));Lh.displayName="RadioGroupItem";function zd({title:e,subtitle:t,icon:n,className:r}){return o.jsxs("header",{className:K("flex flex-col w-fit",r),children:[o.jsxs(me,{as:"h2",variant:"header-md",className:"flex items-center gap-2",children:[n&&o.jsx(Ke,{size:"lg",className:"text-accent1",children:n}),e]}),t&&o.jsx(me,{className:"text-ui-md text-neutral3 !font-light",children:t})]})}function S0({title:e,icon:t}){return o.jsxs(me,{as:"h4",variant:"ui-sm",className:"text-neutral2 flex items-center gap-1 uppercase",children:[t&&o.jsx(Ke,{size:"sm",className:"text-neutral1",children:t}),e]})}const Nxe=e=>"field"in e,s5t=e=>e?e.conditions.reduce((t,n)=>Nxe(n)?t+1:t+s5t(n),0):0,Pje=()=>({field:"",operator:"equals",value:""}),KHr=(e="AND")=>({operator:e,conditions:[Pje()]}),FD=e=>Array.isArray(e.type)?e.type.find(t=>t!=="null")||"string":e.type||"string",a5t=e=>{const t=FD(e);return t==="object"&&e.properties?Object.keys(e.properties).length>0:t==="array"&&e.items?FD(e.items)==="object"&&!!e.items.properties:!1},Ixe=(e,t="")=>e?Object.entries(e).map(([n,r])=>{const s=t?`${t}.${n}`:n,a=FD(r),i=a5t(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}}):[],XHr=e=>Ixe(e.properties),JHr=(e,t)=>e.type==="object"&&e.children?Ixe(e.children,t):e.type==="array"&&e.items&&FD(e.items)==="object"&&e.items.properties?Ixe(e.items.properties,t):[],i5t=e=>e.split(".").filter(Boolean),o5t=(e,t)=>{const n=i5t(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=FD(c),d=a5t(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},eWr=e=>{switch(e){case"object":return o.jsx(nc,{});case"array":return o.jsx(d1,{});case"number":case"integer":return o.jsx(c3,{});case"boolean":return o.jsx(X0e,{});default:return o.jsx(ewe,{})}},tWr=({options:e,value:t,onChange:n,placeholder:r="Select field",className:s})=>o.jsx("div",{className:K("relative",s),children:o.jsxs(da,{value:t,onValueChange:n,children:[o.jsx(ha,{className:"bg-surface4 text-neutral6 min-w-35",size:"sm",children:o.jsx(fa,{placeholder:r})}),o.jsx(pa,{children:e.map(a=>o.jsx(xr,{value:a.path,children:o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(Ke,{size:"sm",className:"text-neutral3",children:eWr(a.type)}),a.label,a.hasChildren&&o.jsx("span",{className:"text-neutral3",children:"..."})]})},a.path))})]})}),nWr=({schema:e,value:t,onChange:n,className:r})=>{const s=g.useMemo(()=>i5t(t),[t]),a=g.useMemo(()=>{const l=[],c=XHr(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=o5t(e,u);if(!h||!h.hasChildren)break;const p=JHr(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(tWr,{options:l.options,value:l.value,onChange:u=>i(c,u),placeholder:c===0?"Select field":"Select property"})]},`${l.basePath}-${c}`))})},rWr={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"},sWr=["equals","not_equals","contains","not_contains","greater_than","less_than","greater_than_or_equal","less_than_or_equal","in","not_in","exists","not_exists"],aWr={equals:o.jsx(put,{}),not_equals:o.jsx(_Xt,{}),contains:o.jsx(Jtn,{}),not_contains:o.jsx(h1,{}),greater_than:o.jsx(Fr,{}),less_than:o.jsx(a3,{}),greater_than_or_equal:o.jsx(cut,{}),less_than_or_equal:o.jsx(IKt,{}),in:o.jsx(d1,{}),not_in:o.jsx(GJt,{}),exists:o.jsx(Dr,{}),not_exists:o.jsx(D0e,{})},iWr=({value:e,onChange:t,operators:n,className:r})=>{const s=n??sWr;return o.jsx("div",{className:K("relative",r),children:o.jsxs(da,{value:e,onValueChange:t,children:[o.jsx(ha,{className:"bg-surface4 text-neutral6 min-w-[150px]",size:"sm",children:o.jsx(fa,{placeholder:"Select operator"})}),o.jsx(pa,{children:s.map(a=>o.jsx(xr,{value:a,children:o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(Ke,{size:"sm",className:"text-neutral3",children:aWr[a]}),rWr[a]]})},a))})]})})},l5t=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},oWr=e=>e.trim()===""?[]:e.split(",").map(t=>l5t(t.trim())),cV=e=>e===null?"null":e===void 0?"":Array.isArray(e)?e.map(cV).join(", "):String(e),lWr=e=>e===!0?"true":e===!1?"false":"",cWr=({value:e,onChange:t,className:n})=>{const r=lWr(e),s=g.useCallback(a=>{t(a==="true")},[t]);return o.jsxs("div",{className:K("relative",n),children:[o.jsx(Ke,{size:"sm",className:"text-neutral3 pointer-events-none absolute top-1/2 left-2 z-10 -translate-y-1/2",children:o.jsx(X0e,{})}),o.jsxs(da,{value:r,onValueChange:s,children:[o.jsx(ha,{className:"bg-surface4 min-w-35 pl-7",size:"sm",children:o.jsx(fa,{placeholder:"Select value"})}),o.jsxs(pa,{children:[o.jsx(xr,{value:"true",children:"true"}),o.jsx(xr,{value:"false",children:"false"})]})]})]})},uWr=({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(Ke,{size:"sm",className:"text-neutral3 pointer-events-none absolute top-1/2 left-2 -translate-y-1/2",children:o.jsx(c3,{})}),o.jsx(jn,{type:"number",value:s,onChange:a,placeholder:n||"Enter number",className:"bg-surface4 min-w-35 pl-7",size:"sm"})]})},dWr=({value:e,onChange:t,placeholder:n,className:r})=>{const s=cV(e),a=g.useCallback(i=>{t(l5t(i.target.value))},[t]);return o.jsxs("div",{className:K("relative",r),children:[o.jsx(Ke,{size:"sm",className:"text-neutral3 pointer-events-none absolute top-1/2 left-2 -translate-y-1/2",children:o.jsx(ewe,{})}),o.jsx(jn,{value:s,onChange:a,placeholder:n||"Enter value",className:"bg-surface4 min-w-35 pl-7",size:"sm"})]})},fWr=({value:e,onChange:t,placeholder:n,className:r})=>{const s=g.useMemo(()=>Array.isArray(e)?e.map(cV).join(", "):cV(e),[e]),a=g.useCallback(i=>{t(oWr(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"})},hWr=({value:e,onChange:t,operator:n,fieldType:r,placeholder:s,className:a})=>n==="in"||n==="not_in"?o.jsx(fWr,{value:e,onChange:t,placeholder:s,className:a}):r==="boolean"?o.jsx(cWr,{value:e,onChange:t,placeholder:s,className:a}):r==="number"||r==="integer"?o.jsx(uWr,{value:e,onChange:t,placeholder:s,className:a}):o.jsx(dWr,{value:e,onChange:t,placeholder:s,className:a}),pWr=new Set(["string","number","boolean","integer"]),mWr=({schema:e,rule:t,onChange:n,onRemove:r,className:s})=>{const a=g.useMemo(()=>o5t(e,t.field)?.type,[e,t.field]),i=a!==void 0&&pWr.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(nWr,{schema:e,value:t.field,onChange:h}),d&&o.jsxs(o.Fragment,{children:[o.jsx(iWr,{value:t.operator,onChange:p,operators:l?["in","not_in"]:void 0}),f&&o.jsx(hWr,{value:t.value,onChange:m,operator:t.operator,fieldType:a})]})]}),o.jsx(ae,{type:"button",onClick:r,tooltip:"Remove rule",size:"icon-sm",variant:"ghost",children:o.jsx(tr,{})})]})},gWr=3,c5t=({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,Pje()]})},f=()=>{n({...t,conditions:[...t.conditions,KHr(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(ae,{type:"button",onClick:r,tooltip:"Remove group",size:"icon-sm",variant:"ghost",children:o.jsx(tr,{})})]}),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",Nxe(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()}),Nxe(h)?o.jsx(mWr,{schema:e,rule:h,onChange:m=>c(p,m),onRemove:()=>u(p)}):o.jsx(c5t,{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(ae,{type:"button",onClick:d,variant:"ghost",size:"sm",children:[o.jsx(Ke,{children:o.jsx(Ir,{})}),"Add rule"]}),s<a-1&&o.jsxs(ae,{type:"button",onClick:f,variant:"ghost",size:"sm",children:[o.jsx(Ke,{children:o.jsx(fXt,{})}),"Add group"]})]})]})},vWr=({schema:e,ruleGroup:t,onChange:n,maxDepth:r=gWr,className:s})=>{const a=g.useCallback(l=>{n(l)},[n]),i=g.useCallback(()=>{n({operator:"AND",conditions:[Pje()]})},[n]);return t?o.jsx("div",{className:s,children:o.jsx(c5t,{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(Ke,{children:o.jsx(Ir,{})}),"Add conditional rule"]})};function fA({entityName:e,schema:t,rules:n,onRulesChange:r}){const s=Object.keys(t?.properties??{}).length>0;if(!t||!s)return null;const a=s5t(n);return o.jsxs(pr,{children:[o.jsx(XSe,{asChild:!0,children:o.jsxs(ae,{tooltip:a>0?`${a} rules`:"Display Conditions",size:"icon-sm",variant:"ghost",className:"relative",children:[o.jsx(btn,{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(Ts,{children:"Configure when this entity should be displayed based on variable values."})]}),o.jsx(Nr,{children:o.jsx(vWr,{schema:t,ruleGroup:n,onChange:r})})]})]})}function u5t({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=$n({control:c,name:"defaultSampling.type"}),f=$n({control:c,name:"model.provider"});return o.jsxs("div",{className:"flex h-full flex-col",children:[o.jsx(Sr,{className:"min-h-0 flex-1",children:o.jsxs("div",{className:"flex flex-col gap-6 p-4",children:[o.jsx(zd,{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(So,{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(Ms,{name:"model.provider",control:c,render:({field:h})=>o.jsx(Qy,{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(Ms,{name:"model.name",control:c,render:({field:h})=>o.jsx(Yy,{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(Ms,{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(Ms,{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(Ms,{name:"defaultSampling.type",control:c,render:({field:h})=>o.jsxs(d4,{value:h.value??"none",onValueChange:h.onChange,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Lh,{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(Lh,{value:"ratio",id:"sampling-ratio"}),o.jsx(Dt,{htmlFor:"sampling-ratio",className:"text-neutral5 text-xs",children:"Ratio"})]})]})}),d==="ratio"&&o.jsx(Ms,{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(ae,{variant:"outline",onClick:n,disabled:s||r,className:"flex-1",children:s?o.jsxs(o.Fragment,{children:[o.jsx(Ht,{className:"h-4 w-4"}),"Saving..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Ke,{children:o.jsx(Qu,{})}),"Save"]})}),o.jsx(ae,{variant:"primary",onClick:t,disabled:r||s,className:"flex-1",children:r?o.jsxs(o.Fragment,{children:[o.jsx(Ht,{className:"h-4 w-4"}),"Publishing..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Ke,{children:o.jsx(Dr,{})}),"Publish"]})})]}):o.jsx(ae,{variant:"primary",onClick:t,disabled:r,className:"w-full",children:r?o.jsxs(o.Fragment,{children:[o.jsx(Ht,{className:"h-4 w-4"}),"Creating..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Ke,{children:o.jsx(Dr,{})}),"Create scorer"]})})})]})}function d5t({form:e}){const{control:t}=e;return o.jsxs("div",{className:"flex h-full flex-col gap-3 px-4",children:[o.jsx(zd,{title:"Instructions",subtitle:"Write your scorer's system prompt."}),o.jsx(Ms,{name:"instructions",control:t,render:({field:n})=>o.jsx("div",{className:"flex flex-1 flex-col",children:o.jsx(Hr,{value:n.value??"",onChange:n.onChange,language:"markdown",showCopyButton:!1,placeholder:"Enter scorer instructions...",className:"min-h-[200px] flex-1"})})})]})}const yWr=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 f5t(e={}){const{initialValues:t}=e;return{form:hS({resolver:yWr,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 bWr=["llm-judge"],xWr=Rke("type",[Ss({type:Dx("none")}),Ss({type:Dx("ratio"),rate:vf().min(0).max(1)})]);Ss({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:Uy(bWr),model:Ss({provider:cr(),name:cr()}),instructions:cr(),scoreRange:Ss({min:vf(),max:vf()}),defaultSampling:xWr.optional()});const h5t=(e,t)=>{const n=Qe(),{requestContext:r}=bs();return gt({queryKey:["stored-scorer",e,t?.status,r],queryFn:()=>e?n.getStoredScorer(e).details(r,t):null,enabled:!!e})},$je=e=>{const t=Qe(),n=Er(),{requestContext:r}=bs(),s=wn({mutationFn:l=>t.createStoredScorer(l),onSuccess:()=>{n.invalidateQueries({queryKey:["stored-scorers"]}),n.invalidateQueries({queryKey:["scorers"]})}}),a=wn({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=wn({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}},W1=({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 wWr({onSuccess:e}){const{createStoredScorer:t}=$je(),n=g.useRef(null),{form:r}=f5t(),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(W1,{leftSlot:o.jsx(u5t,{form:r,onPublish:s,isSubmitting:t.isPending,formRef:n}),children:o.jsx("form",{ref:n,className:"h-full",children:o.jsx(d5t,{form:r})})})}const SWr=3e3;function kWr(e){return KL(e.state.error,"scores")||XL(e.state.error)?!1:SWr}const Mje=({traceId:e="",spanId:t="",page:n})=>{const r=Qe();return gt({queryKey:["trace-span-scores",e,t,n],queryFn:()=>r.listScoresBySpan({traceId:e,spanId:t,page:n||0,perPage:10}),enabled:!!e&&!!t,refetchInterval:kWr,gcTime:0,staleTime:0})},p5t=({scorerId:e,params:t})=>{const n=Qe(),{requestContext:r}=bs();return gt({queryKey:["scorer-versions",e,t,r],queryFn:()=>n.getStoredScorer(e).listVersions(t,r),enabled:!!e})},OWr=({scorerId:e,versionId:t})=>{const n=Qe(),{requestContext:r}=bs();return gt({queryKey:["scorer-version",e,t,r],queryFn:()=>n.getStoredScorer(e).getVersion(t,r),enabled:!!e&&!!t})};function CWr(e){const t=Qe(),n=Hl(),r=e?.start||e?.end?e:void 0;return gt({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 R=await t.listScores({filters:{scorerId:N,timestamp:r},pagination:{page:A,perPage:100},orderBy:{field:"timestamp",direction:"DESC"}});if(I.push(...R.scores),!R.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,R)=>A+R,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((R,L)=>R+L,0)/A.length);v=I.reduce((A,R)=>A+R,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 R=w.get(A);R.has(N.scorerId)||R.set(N.scorerId,[]),R.get(N.scorerId).push(N.score)}const k=Array.from(w.entries()).sort(([N],[I])=>N-I),O=k.length>0?k[0][0]:0,T=((k.length>0?k[k.length-1][0]:0)-O)/864e5,E=k.map(([N,I])=>{const A=new Date(N);let R;T>1?R=A.toLocaleDateString("en-US",{month:"short",day:"numeric"})+" "+A.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}):R=A.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1});const L={time:R};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 _Wr(e){return new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})}function EWr({scorerId:e,value:t,onValueChange:n,className:r,disabled:s=!1,variant:a,activeVersionId:i}){const{data:l,isLoading:c}=p5t({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:_Wr(p.createdAt),end:m?o.jsx(mt,{variant:"green",children:"Published"}):v?o.jsx(mt,{variant:"blue",children:"Draft"}):void 0}})];return o.jsx(zo,{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 xh="mastra_workspace",Uv={FILESYSTEM:{READ_FILE:`${xh}_read_file`,WRITE_FILE:`${xh}_write_file`,EDIT_FILE:`${xh}_edit_file`,LIST_FILES:`${xh}_list_files`,DELETE:`${xh}_delete`,FILE_STAT:`${xh}_file_stat`,MKDIR:`${xh}_mkdir`},SANDBOX:{EXECUTE_COMMAND:`${xh}_execute_command`,GET_PROCESS_OUTPUT:`${xh}_get_process_output`,KILL_PROCESS:`${xh}_kill_process`},SEARCH:{SEARCH:`${xh}_search`,INDEX:`${xh}_index`}};function Pd(e,t){return e.length<=t?e:e.slice(0,t)+"…"}const TWr=/[\u001b\u009b][[\]()#;?]*(?:(?:[a-zA-Z\d]*(?:;[-a-zA-Z\d/#&.:=?%@~_]*)*)?\u0007|(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~])/g,jWr=new RegExp("(?<!\\\\)((?:\\\\\\\\)*)\\\\u001[bB](?:\\[[0-9;?<=>]*[a-zA-Z]|\\][\\s\\S]*?(?:\\\\u0007|\\\\u001[bB]\\\\\\\\))","g");function NWr(e){return e.replace(TWr,"")}function IWr(e){return NWr(e).replace(jWr,"$1")}const AWr=3;function RWr(e,{key:t,joins:n,min:r=AWr}){const s=new Map,a=new Set;let i=[];const l=()=>{if(i.length>=r)for(const[c,u]of i.entries())c===0?s.set(t(u),i):a.add(t(u));i=[]};for(const c of e)n(c)?i.push(c):l();return l(),{byFirstKey:s,memberKeys:a}}const m5t=g.createContext(void 0),PWr=()=>{};function Dje(){const e=g.useContext(m5t);if(!e)throw new Error("ToolCall compounds must be rendered within ToolCall");return e}function g5t({open:e,defaultOpen:t=!1,onOpenChange:n=PWr,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(m5t.Provider,{value:{open:u,status:r},children:o.jsxs(cc,{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 v5t=({className:e,...t})=>o.jsx(Bl,{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}),Lje=({className:e,children:t,...n})=>{const{status:r}=Dje();return o.jsx(vLt,{active:r==="running",className:K("flex w-full min-w-0 items-center gap-2 px-1.5 py-1",e),...n,children:t})},Fje=({className:e,...t})=>o.jsx("span",{className:K("flex size-4 shrink-0 items-center justify-center",e),...t}),zje=({className:e,...t})=>o.jsx(me,{as:"span",variant:"ui-sm",className:K("text-icon3 max-w-[55%] shrink-0 truncate",e),...t}),Bje=({className:e,...t})=>{const n=nLt();return o.jsx(me,{as:"span",variant:"ui-xs",font:"mono",className:K("text-icon3 min-w-0 truncate",n,e),...t})},$Wr=({className:e,...t})=>o.jsx("span",{className:K("flex min-w-0 items-center gap-1",e),...t}),Uje=({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}),uV=({className:e,...t})=>o.jsx("span",{className:K("flex shrink-0 items-center",e),...t}),qje=({className:e,children:t,...n})=>{const{open:r}=Dje();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(Fr,{size:13})})})},MWr=({leading:e,icon:t,label:n,detail:r,disclosure:s=!0,...a})=>{const{status:i}=Dje();return o.jsxs(Lje,{...a,children:[e,o.jsx(Fje,{children:o.jsx(t,{size:14,strokeWidth:1.75,"aria-hidden":!0,className:i==="error"?"text-error/80":"text-icon2"})}),o.jsx(zje,{children:n}),r&&o.jsx(Bje,{children:r}),o.jsx(Uje,{}),i==="error"&&o.jsx(uV,{children:o.jsx(tr,{size:13,role:"img","aria-label":"Failed",className:"text-error shrink-0"})}),s&&o.jsx(qje,{})]})},y5t=({className:e,children:t,...n})=>o.jsx(Ul,{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})}),g2=({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"})]}),ZXe=200,DWr=2e3,LWr={removed:{sign:"-",row:"bg-error/10",gutter:"text-error"},added:{sign:"+",row:"bg-accent1/10",gutter:"text-accent1"}};function GXe(e){const t=e.split(`
517
+ `);return t!==-1&&t!==e.length-1}else{if(Array.isArray(e))return e.some(t=>Txe(t));if(e&&typeof e=="object")return Object.values(e).some(t=>Txe(t))}return!1}function YVr({children:e,className:t}){return o.jsx(wTt,{render:o.jsx("div",{className:K("grid content-start gap-6 overflow-y-scroll p-6 pb-8 pl-9",t),children:e})})}function KVr({children:e,className:t}){return o.jsx("div",{className:K("flex items-center justify-between pb-4",t),children:e})}function XVr({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 JVr({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(ae,{onClick:s,disabled:!t,children:["Previous",o.jsx(J1,{})]}),o.jsxs(ae,{onClick:r,disabled:!e,children:["Next",o.jsx(FV,{})]})]})})}function eHr({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($I,{side:"right",open:n,onOpenChange:f=>{f||r?.()},children:o.jsxs(kCe,{children:[!c&&o.jsx(qW,{className:"backdrop-blur-sm"}),o.jsx(VW,{className:c?"pointer-events-none":void 0,children:o.jsxs(HW,{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(MI,{className:"sr-only",children:e}),o.jsx(OL,{className:"sr-only",children:t}),!c&&o.jsx(SCe,{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(cut,{})})}),o.jsx(wTt,{render:o.jsx("div",{ref:d,className:"absolute"})}),o.jsx(c$n,{container:u,children:o.jsx("div",{className:K("grid h-full",{"grid-rows-[auto_1fr]":!c}),children:s})})]})})]})})}function tHr({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 Oi=Object.assign(eHr,{Top:tHr,Header:KVr,Heading:XVr,Content:YVr,CodeSection:QVr,Nav:JVr}),La=()=>{const e=Qe(),t=Er(),n=wn({mutationFn:b=>e.createDataset(b),onSuccess:()=>{t.invalidateQueries({queryKey:["datasets"]})}}),r=wn({mutationFn:b=>e.updateDataset(b),onSuccess:(b,x)=>{t.invalidateQueries({queryKey:["datasets"]}),t.invalidateQueries({queryKey:["dataset",x.datasetId]})}}),s=wn({mutationFn:b=>e.deleteDataset(b),onSuccess:()=>{t.invalidateQueries({queryKey:["datasets"]})}}),a=wn({mutationFn:b=>e.addDatasetItem(b),onSuccess:(b,x)=>{t.invalidateQueries({queryKey:["dataset-items",x.datasetId]}),t.invalidateQueries({queryKey:["dataset",x.datasetId]}),t.invalidateQueries({queryKey:["dataset-versions",x.datasetId]})}}),i=wn({mutationFn:b=>e.updateDatasetItem(b),onSuccess:(b,x)=>{t.invalidateQueries({queryKey:["dataset-items",x.datasetId]}),t.invalidateQueries({queryKey:["dataset-item",x.datasetId,x.itemId]}),t.invalidateQueries({queryKey:["dataset-item-versions",x.datasetId,x.itemId]}),t.invalidateQueries({queryKey:["dataset-versions",x.datasetId]})}}),l=wn({mutationFn:({datasetId:b,itemId:x})=>e.deleteDatasetItem(b,x),onSuccess:(b,x)=>{t.invalidateQueries({queryKey:["dataset-items",x.datasetId]}),t.invalidateQueries({queryKey:["dataset",x.datasetId]}),t.invalidateQueries({queryKey:["dataset-versions",x.datasetId]})}}),c=wn({mutationFn:({datasetId:b,itemId:x})=>e.purgeDatasetItem(b,x),onSuccess:(b,x)=>{t.invalidateQueries({queryKey:["dataset-items",x.datasetId]}),t.invalidateQueries({queryKey:["dataset-item",x.datasetId,x.itemId]}),t.invalidateQueries({queryKey:["dataset-item-versions",x.datasetId,x.itemId]}),t.invalidateQueries({queryKey:["dataset-experiment-results"]}),t.invalidateQueries({queryKey:["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"]})}}),u=wn({mutationFn:b=>e.batchInsertDatasetItems(b),onSuccess:(b,x)=>{t.invalidateQueries({queryKey:["dataset-items",x.datasetId]}),t.invalidateQueries({queryKey:["dataset",x.datasetId]}),t.invalidateQueries({queryKey:["dataset-versions",x.datasetId]})}}),d=wn({mutationFn:b=>e.batchDeleteDatasetItems(b),onSuccess:(b,x)=>{t.invalidateQueries({queryKey:["dataset-items",x.datasetId]}),t.invalidateQueries({queryKey:["dataset",x.datasetId]}),t.invalidateQueries({queryKey:["dataset-versions",x.datasetId]})}}),f=wn({mutationFn:async({datasetId:b,itemIds:x})=>e.batchDeleteDatasetItems({datasetId:b,itemIds:x}),onSuccess:(b,x)=>{t.invalidateQueries({queryKey:["dataset-items",x.datasetId]}),t.invalidateQueries({queryKey:["dataset",x.datasetId]}),t.invalidateQueries({queryKey:["dataset-versions",x.datasetId]})}}),h=wn({mutationFn:b=>e.generateDatasetItems(b)}),p=wn({mutationFn:b=>e.triggerDatasetExperiment(b),onSuccess:(b,x)=>{t.invalidateQueries({queryKey:["dataset-experiments",x.datasetId]})}}),m=wn({mutationFn:b=>e.deleteExperiment(b),onSuccess:()=>{t.invalidateQueries({queryKey:["experiments"]}),t.invalidateQueries({queryKey:["dataset-experiments"]}),t.invalidateQueries({queryKey:["dataset-experiment"]}),t.invalidateQueries({queryKey:["dataset-experiment-results"]}),t.invalidateQueries({queryKey:["review-items"]}),t.invalidateQueries({queryKey:["completed-items"]}),t.invalidateQueries({queryKey:["experiment-review-summary"]}),t.invalidateQueries({queryKey:["inbox-dataset-review-items"]}),t.invalidateQueries({queryKey:["inbox-dataset-review-count"]})}}),v=wn({mutationFn:b=>e.updateDatasetExperiment(b),onSuccess:(b,x)=>{t.invalidateQueries({queryKey:["experiments"]}),t.invalidateQueries({queryKey:["dataset-experiments",x.datasetId]}),t.invalidateQueries({queryKey:["dataset-experiment",x.datasetId,x.experimentId]})}}),y=wn({mutationFn:b=>e.updateDatasetExperimentResult(b),onSuccess:(b,x)=>{t.invalidateQueries({queryKey:["experiment-results",x.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,purgeItem:c,deleteItems:f,batchInsertItems:u,batchDeleteItems:d,generateItems:h,triggerExperiment:p,deleteExperiment:m,updateExperiment:v,updateExperimentResult:y}};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:O}=Pm(),{addItem:_}=La(),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 R=F=>{I.current=!0,p(F)},L=F=>{A.current=!0,v(F)},D=F=>{N.current=!0,b(F)},B=F=>{w(F)};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 F=>{if(F.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 z;if(x.trim())try{const P=JSON.parse(x);if(!Array.isArray(P)){Ve.error("Tool Mocks must be a JSON array");return}z=P}catch{Ve.error("Tool Mocks must be valid JSON");return}try{await _.mutateAsync({datasetId:d,input:V,groundTruth:M,expectedTrajectory:G,toolMocks:z,...u?{source:u}:{}});const P=T.find(U=>U.id===d);Ve.success(`Item saved to "${P?.name}"`),f(""),p("{}"),v(""),b(""),w(""),l()}catch(P){Ve.error(`Failed to save item: ${P instanceof Error?P.message:"Unknown error"}`)}},q=()=>{f(""),l()};return o.jsxs(Oi,{dialogTitle:"Save as Dataset Item",dialogDescription:"Save data as a dataset item",isOpen:i,onClose:l,level:c,children:[o.jsxs(Oi.Top,{children:[a,"›",o.jsxs(Rc,{children:[o.jsx(Lg,{})," Save as Dataset Item"]})]}),o.jsxs(Oi.Content,{children:[o.jsx(Oi.Header,{children:o.jsxs(Oi.Heading,{children:[o.jsx(Lg,{})," 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(da,{value:d,onValueChange:f,disabled:_.isPending||O,children:[o.jsx(ha,{id:"target-dataset",children:o.jsx(fa,{placeholder:O?"Loading datasets...":"Select a dataset"})}),o.jsx(pa,{children:T.length===0?o.jsx("div",{className:"text-neutral4 px-2 py-4 text-center text-sm",children:"No datasets available"}):T.map(F=>o.jsx(xr,{value:F.id,children:F.name},F.id))})]})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Hr,{value:h,onChange:R,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(Hr,{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(Hr,{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(Hr,{value:x,onChange:B,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ae,{type:"button",variant:"outline",onClick:q,children:"Cancel"}),o.jsx(ae,{type:"submit",variant:"default",disabled:_.isPending||r||!d||T.length===0,children:_.isPending?"Saving...":r?"Loading...":"Save Item"})]})]})]})]})}function nHr(e){return e?kO({input:e.input,output:e.output,groundTruth:null},2):"{}"}function rHr(e){return e?kO({score:e.score,reason:e.reason??null},2):""}function sHr({score:e,isOpen:t,onClose:n,level:r=2}){return o.jsx(K4t,{initialInput:nHr(e),initialGroundTruth:rHr(e),breadcrumb:o.jsxs(Rc,{children:[o.jsx(mKt,{})," ",w0(e?.id)]}),isOpen:t,onClose:n,level:r,source:e?.traceId?{type:"trace",referenceId:e.traceId}:void 0})}function aHr(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 qE(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}=un(),[a,i]=g.useState(!1),l=aHr(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(fn,{children:[o.jsxs(fn.Header,{children:[o.jsxs(fn.Heading,{children:["Score ",o.jsxs("b",{children:["# ",e.id]})]}),o.jsxs(ps,{className:"ml-auto shrink-0",children:[o.jsx(fn.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Previous score",nextLabel:"Next score"}),o.jsx(fn.CloseButton,{onClick:t})]})]}),o.jsxs(fn.Content,{children:[o.jsxs(Jn,{children:[e.scorer?.name!=null&&o.jsxs(o.Fragment,{children:[o.jsx(Jn.Key,{children:"Scorer"}),o.jsx(Jn.Value,{children:String(e.scorer.name)})]}),e.createdAt&&o.jsxs(o.Fragment,{children:[o.jsx(Jn.Key,{children:"Created"}),o.jsx(Jn.Value,{children:dr(new Date(e.createdAt),"MMM dd, HH:mm:ss.SSS")})]}),e.traceId&&o.jsxs(o.Fragment,{children:[o.jsx(Jn.Key,{children:"Trace Id"}),o.jsx(Jn.ValueLink,{href:`/traces?traceId=${encodeURIComponent(e.traceId)}`,as:s,children:e.traceId})]}),e.spanId&&e.traceId&&o.jsxs(o.Fragment,{children:[o.jsx(Jn.Key,{children:"Span Id"}),o.jsx(Jn.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(ae,{size:"sm",onClick:()=>i(!0),children:[o.jsx(Ke,{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(fm,{}),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(fn.CodeSection,{title:"Input",dialogTitle:qE("Input",o.jsx(u1,{}),e),icon:o.jsx(u1,{}),codeStr:JSON.stringify(e.input??null,null,2)}),o.jsx(fn.CodeSection,{title:"Output",dialogTitle:qE("Output",o.jsx(Rg,{}),e),icon:o.jsx(Rg,{}),codeStr:JSON.stringify(e.output??null,null,2)}),o.jsx(fn.CodeSection,{title:"Preprocess Prompt",dialogTitle:qE("Preprocess Prompt",o.jsx(Mp,{}),e),icon:o.jsx(Mp,{}),codeStr:e.preprocessPrompt||c,simplified:!0}),o.jsx(fn.CodeSection,{title:"Analyze Prompt",dialogTitle:qE("Analyze Prompt",o.jsx(Mp,{}),e),icon:o.jsx(Mp,{}),codeStr:e.analyzePrompt||c,simplified:!0}),o.jsx(fn.CodeSection,{title:"Generate Score Prompt",dialogTitle:qE("Generate Score Prompt",o.jsx(Mp,{}),e),icon:o.jsx(Mp,{}),codeStr:e.generateScorePrompt||c,simplified:!0}),o.jsx(fn.CodeSection,{title:"Generate Reason Prompt",dialogTitle:qE("Generate Reason Prompt",o.jsx(Mp,{}),e),icon:o.jsx(Mp,{}),codeStr:e.generateReasonPrompt||c,simplified:!0})]})]})]}),o.jsx(sHr,{score:e,isOpen:a,onClose:()=>i(!1)})]})}const BXe=["input","entity"],iHr={input:"Input",entity:"Entity"};function oHr(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 lHr(e){return{...e,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt)}}function cHr({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(BXe.filter(I=>!f.has(I))),[f]),m=g.useMemo(()=>oHr(p),[p]),v=g.useCallback(I=>{h(A=>{const R=new Set(A);return R.has(I)?R.delete(I):R.add(I),R})},[]);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:O,getRowProps:_}=no({count:e?.length??0}),T=g.useCallback(()=>{u(void 0),t?.("")},[t]);if(r)return o.jsx(Lo,{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(ae,{variant:"outline",size:"sm",children:[o.jsx(fut,{className:"size-3.5"}),"Columns"]})}),o.jsxs(at.Content,{align:"end",children:[o.jsx(at.Label,{children:"Toggle columns"}),BXe.map(I=>o.jsx(at.CheckboxItem,{checked:p.has(I),onClick:()=>v(I),children:iHr[I]},I))]})]})}),o.jsxs(Ru,{columns:m,className:"min-h-0 flex-1",scrollRef:O,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:lHr(b),onClose:T,onPrevious:w,onNext:k})})]})}const uHr=({onRunExperiment:e})=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(yr,{iconSlot:o.jsx(Cs,{}),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(ae,{variant:"primary",onClick:e,children:[o.jsx(Fc,{}),"Run Experiment"]}),o.jsxs(ae,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/evals/overview",target:"_blank",rel:"noopener noreferrer",children:["Scorers Documentation ",o.jsx(Fs,{})]})]})})});function Rje({data:e,className:t,labelsAreHidden:n,isLoading:r,LinkComponent:s}){const a=({children:i})=>n?o.jsx(N1,{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(UXe,{description:p.description,children:o.jsxs(s,{href:p.path,children:[p?.name," ",o.jsx(Fr,{})]})},p.id):p.path?o.jsx(UXe,{description:p.description,children:o.jsxs("a",{href:p.path,children:[p?.name," ",o.jsx(Fr,{})]})},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 UXe({description:e,children:t}){return e?o.jsxs(uA,{children:[o.jsx(C_,{render:qe.isValidElement(t)?t:void 0}),o.jsx(__,{className:"max-w-60 text-center",children:e})]}):t}function dHr({onEntityChange:e,onReset:t,selectedEntity:n,entityOptions:r,isLoading:s}){return o.jsxs(ps,{children:[o.jsx(Om,{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(ae,{onClick:t,disabled:s,size:"md",children:["Reset",o.jsx(Ke,{children:o.jsx(tr,{})})]})]})}const fHr=25,hHr=5e3;function pHr(e){return KL(e.state.error,"scores")||XL(e.state.error)?!1:hHr}function mHr(e,t,n){if(e?.pagination?.hasMore)return n+1}function gHr(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 vHr=({scorerId:e,entityId:t,entityType:n})=>{const r=Qe(),{inView:s,setRef:a}=i0(),i=Fy({queryKey:["scores",e,t,n],queryFn:({pageParam:d})=>r.listScoresByScorerId({scorerId:e,page:d,perPage:fHr,entityId:t,entityType:n}),initialPageParam:0,getNextPageParam:mHr,select:gHr,refetchInterval:pHr}),{hasNextPage:l,isFetchingNextPage:c,fetchNextPage:u}=i;return g.useEffect(()=>{s&&l&&!c&&u()},[s,l,c,u]),{...i,setEndOfListElement:a}},yHr=e=>{const t=Qe(),[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=Qe(),t=Hl();return gt({queryKey:["scorers",t],queryFn:()=>e.listScorers(t),staleTime:0,gcTime:0})};function bHr({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}=un();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(zo,{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 xHr({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(cnn,{}):o.jsx(onn,{})}),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 wHr({message:e="Failed to load data",className:t}){return o.jsx("span",{className:K("text-ui-sm text-accent2",t),children:e})}function SHr({children:e,className:t}){return o.jsx("span",{className:K("text-ui-md leading-relaxed text-neutral3",t),children:e})}function kHr({className:e}){return o.jsx("span",{className:K("text-sm",e),children:o.jsx(Ht,{size:"md",variant:"pulse",className:"text-neutral1"})})}function OHr({message:e="No previous value to compare",className:t}){return o.jsx("span",{className:K("text-sm text-neutral1",t),children:e})}function CHr({message:e="No data yet",className:t}){return o.jsx("span",{className:K("text-sm text-neutral1",t),children:e})}function _Hr({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 EHr({children:e,className:t}){return o.jsx("strong",{className:K("text-header-lg font-semibold text-neutral4",t),children:e})}const Xr=Object.assign(_Hr,{Label:SHr,Value:EHr,Change:xHr,NoChange:OHr,NoData:CHr,Error:wHr,Loading:kHr});function THr({children:e,className:t}){return o.jsx("div",{className:K("flex shrink-0 items-center gap-1",t),children:e})}function jHr({children:e,className:t}){return o.jsx("div",{className:K("overflow-x-auto ",t),children:e})}function e5t({children:e,className:t}){return o.jsx("p",{className:K("mt-0.5 text-ui-md leading-tight text-neutral2",t),children:e})}function NHr({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 IHr({className:e}){return o.jsx("div",{className:K("flex items-center justify-center",e),children:o.jsx(Ht,{size:"md",variant:"pulse",className:"text-neutral1"})})}function AHr({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 qXe({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 RHr({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 t5t({children:e,className:t,as:n="h2"}){return o.jsx(n,{className:K("text-ui-md font-normal text-neutral4",t),children:e})}function PHr(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(t5t,{as:r,children:t}),n&&o.jsx(e5t,{children:n})]})}function $Hr({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 Vt=Object.assign(qXe,{Root:qXe,Kpi:Xr,TopBar:$Hr,Actions:THr,TitleAndDescription:PHr,Title:t5t,Description:e5t,Summary:RHr,Loading:IHr,Error:NHr,Content:jHr,NoData:AHr});function MHr({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 VXe="#a1a1aa";function LD({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(RL,{width:"100%",height:"100%",children:o.jsxs(JTr,{data:e,children:[o.jsx(NPt,{stroke:"currentColor",strokeOpacity:.08,vertical:!1,className:"text-black dark:text-white"}),o.jsx(HL,{dataKey:"time",tick:{fontSize:10,fill:VXe,fontFamily:"var(--font-mono)"},tickLine:!1,axisLine:!1,interval:a,minTickGap:i}),o.jsx(WL,{tick:{fontSize:10,fill:VXe,fontFamily:"var(--font-mono)"},tickLine:!1,axisLine:!1,width:30,domain:r}),o.jsx(HZ,{content:o.jsx(MHr,{})}),t.map(u=>o.jsx(FPt,{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 HXe=["#22c55e","#4f83f1","#8b5cf6","#fb923c","#f472b6","#facc15"];function DHr({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:HXe[u%HXe.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(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Scores",description:"Evaluation scorer performance across all scorers."}),i&&o.jsx(Vt.Summary,{value:r!=null?`avg ${r}`:"—",label:"Across all scorers"})]}),s?o.jsx(Vt.Loading,{}):a?o.jsx(Vt.Error,{message:"Failed to load scores data"}):o.jsx(Vt.Content,{children:i?o.jsxs(vc,{defaultTab:"over-time",className:"overflow-visible",children:[o.jsxs(gc,{children:[o.jsx(zr,{value:"over-time",children:"Over Time"}),o.jsx(zr,{value:"summary",children:"Summary"})]}),o.jsx(vs,{value:"over-time",children:t.length>0?o.jsx(LD,{data:t,series:l,yDomain:[0,1]}):o.jsx(Vt.NoData,{message:"No time series data yet"})}),o.jsx(vs,{value:"summary",children:o.jsxs(fe,{columns:"auto auto auto auto auto",className:"max-h-80",mask:{left:!1},children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{sticky:"start",children:"Scorer"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Avg"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Min"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Max"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Count"})]}),e.map(c=>o.jsxs(fe.RowStatic,{children:[o.jsx(fe.RowHeaderCell,{className:"text-ui-sm",children:c.scorer}),o.jsx(fe.NumberCell,{highlight:!0,children:c.avg.toFixed(2)}),o.jsx(fe.NumberCell,{children:c.min.toFixed(2)}),o.jsx(fe.NumberCell,{children:c.max.toFixed(2)}),o.jsx(fe.NumberCell,{children:c.count.toLocaleString()})]},c.scorer))]})})]}):o.jsx(Vt.NoData,{message:"No scores data yet"})})]})}const WXe="minmax(0,1fr) minmax(0,1.5fr) auto auto auto";function LHr({scorers:e,isLoading:t,search:n="",sourceFilter:r="all"}){const{paths:s,Link:a}=un(),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}=no({count:l.length});return t?o.jsx(Lo,{columns:WXe}):o.jsxs(fe,{columns:WXe,scrollRef:c,children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{children:"Name"}),o.jsx(fe.TopCell,{children:"Description"}),o.jsx(fe.TopCell,{children:"Source"}),o.jsx(fe.TopCellSmart,{long:"Agents",short:o.jsx(uo,{}),tooltip:"Number of attached Agents",className:"text-center"}),o.jsx(fe.TopCellSmart,{long:"Workflows",short:o.jsx(pI,{}),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(fe.RowLink,{to:s.scorerLink(d.id),LinkComponent:a,...u(f),children:[o.jsx(fe.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(mt,{size:"xs",variant:"purple",className:"shrink-0",children:"trajectory"})]})}),o.jsx(fe.DescriptionCell,{children:p}),o.jsx(fe.Cell,{children:o.jsx(mt,{size:"xs",variant:d.source==="code"?"blue":"neutral",children:d.source})}),o.jsx(fe.TextCell,{className:"text-center",children:m||""}),o.jsx(fe.TextCell,{className:"text-center",children:v||""})]},d.id)})]})}const FHr=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(yr,{iconSlot:o.jsx(Cs,{}),titleSlot:"No Scorers yet",descriptionSlot:"Configure scorers in code to get started. More info in the documentation.",actionSlot:o.jsxs(ae,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/evals/overview",target:"_blank",rel:"noopener noreferrer",children:["Scorers Documentation ",o.jsx(Fs,{})]})})}),zHr=[{value:"all",label:"All sources"},{value:"code",label:"Code"},{value:"stored",label:"Stored"}];function BHr({search:e,onSearchChange:t,sourceFilter:n,onSourceFilterChange:r,onReset:s,hasActiveFilters:a}){const[i,l]=g.useState(e),c=g.useRef(e),u=By(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(ps,{spacing:"close",className:"min-w-0 flex-1",children:[o.jsxs(uu,{variant:"outline",size:"default",children:[o.jsx(Ic,{align:"inline-start",children:o.jsx(ra,{})}),o.jsx(du,{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(gje,{"aria-label":"Clear search",onClick:f,children:o.jsx(tr,{})})})]}),o.jsxs(da,{value:n,onValueChange:r,children:[o.jsx(ha,{"aria-label":"Filter by source",className:"rounded-full",children:o.jsx(fa,{placeholder:"All sources"})}),o.jsx(pa,{align:"end",children:zHr.map(p=>o.jsx(xr,{value:p.value,children:p.label},p.value))})]})]}),s&&a&&o.jsxs(ae,{onClick:h,variant:"outline",children:[o.jsx(tr,{})," Reset"]})]})}const jxe={checked(e){return e?{"data-checked":""}:{"data-unchecked":""}},...Nm,...c_},n5t=g.createContext(void 0);function UHr(){return g.useContext(n5t)}const r5t=g.createContext(void 0);function qHr(){const e=g.useContext(r5t);if(e===void 0)throw new Error(Ar(52));return e}const VHr=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=UHr(),{disabled:y,readOnly:b,required:x,form:w,checkedValue:k,touched:O=!1,validation:_,name:T,setCheckedValue:E=ia,setTouched:N=ia,registerInputRef:I=ia}=v??{},{setTouched:A,setFilled:R,state:L,disabled:D}=Rm(),B=S0t(),{labelId:H,getDescriptionProps:q}=s0(),F=D||B.disabled||y||a,V=b||i,M=x||l,G=w,z=v?k===u:u==="",P=g.useRef(null),U=g.useRef(null),W=_?.registerInput,Y=g.useCallback(Me=>W?.(Me,{controlRef:P,value:void 0}),[W]),te=Hd(d,U,I,Y);jt(()=>{U.current?.checked&&R(!0)},[R]),jt(()=>{if(U.current){if(F&&z){I(null);return}I(U.current)}},[z,F,I]);const J=Bi(),ee=u_({id:h,implicit:!1,controlRef:P}),re=f?void 0:ee,oe=HSe(c,H,U,!f,re),X={role:"radio","aria-checked":z,"aria-labelledby":oe,[nTe]:z?"":void 0,id:f?ee:J,onKeyDown(Me){Me.key==="Enter"&&Me.preventDefault()},onClick(Me){if(Me.defaultPrevented||F||V)return;Me.preventDefault();const $e=U.current;$e&&uO($e,Me)},onFocus(Me){Me.defaultPrevented||F||V||!O||(U.current?.click(),N(!1))}},{getButtonProps:ne,buttonRef:se}=Jd({disabled:F,native:f,composite:!1}),ce={type:"radio",ref:te,form:G,id:re,name:T,tabIndex:-1,style:T?yI:C1,"aria-hidden":!0,...u!==void 0?{value:cB(u)}:xa,disabled:F,checked:z,required:M,readOnly:V,onChange(Me){if(Me.nativeEvent.defaultPrevented||F||V||u===void 0)return;const $e=tn(Yi,Me.nativeEvent);E(u,$e),!$e.isCanceled&&A(!0)},onClick(Me){Me.stopPropagation()},onFocus(){P.current?.focus()}},le=g.useMemo(()=>({...L,required:M,disabled:F,readOnly:V,checked:z}),[L,F,V,z,M]),ye=le,he=v!==void 0,xe=[n,P,se],Ae=[X,m,ne,q,_?Me=>_.getValidationProps(F,Me):xa],De=Nn("span",t,{enabled:!he,state:le,ref:xe,props:Ae,stateAttributesMapping:jxe});return o.jsxs(r5t.Provider,{value:ye,children:[he?o.jsx(f2t,{tag:"span",render:r,className:s,style:p,state:le,refs:xe,props:Ae,stateAttributesMapping:jxe}):De,o.jsx("input",{...ce,suppressHydrationWarning:!0})]})}),HHr=g.forwardRef(function(t,n){const{render:r,className:s,style:a,keepMounted:i=!1,...l}=t,c=qHr(),u=c.checked,{mounted:d,transitionStatus:f,setMounted:h}=Xg(u),p={...c,transitionStatus:f},m=g.useRef(null),v=i||d,y=Nn("span",t,{ref:[n,m],state:p,props:l,stateAttributesMapping:jxe});return dc({open:u,ref:m,onComplete(){u||h(!1)}}),v?y:null});function WHr(e,t){return e.matches(":disabled")?!1:!t||e.form===t?!0:e.form===null&&!e.hasAttribute("form")}const ZHr=g.createContext(void 0);function GHr(e=!1){const t=g.useContext(ZHr);if(!t&&!e)throw new Error(Ar(86));return t}const QHr=[n0t],YHr=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:O,state:_,validation:T,setDirty:E,setFilled:N,validityData:I}=Rm(),{labelId:A}=s0(),{clearErrors:R,elementRef:L}=CI(),D=GHr(!0),B=O||a,H=k??h,q=Bi(m),[F,V]=Mf({controlled:u,default:d,name:"RadioGroup",state:"value"}),[M,G]=g.useState(!1),z=bt((se,ce)=>{c?.(se,ce),!ce.isCanceled&&V(se)}),P=T.getInputControl,U=g.useMemo(()=>({get current(){return P()}}),[P]),W=g.useRef(null),Y=g.useRef(null);function te(se){let ce;return p&&(typeof p=="function"?ce=p(se):p.current=se),W.current=se,ce}const J=bt(se=>{if(!se||se.disabled)return;Y.current||(Y.current=se);const ce=W.current,le=se.checked||ce==null||ce.disabled?te(se):void 0;return()=>{Y.current===se&&(Y.current=null),W.current===se?le?(le(),W.current=null):te(null):le?.()}}),ee=bt(()=>{const se=L.current;if(!se)return F??null;for(const ce of T.registeredInputs.keys())if(ce.checked&&WHr(ce,se))return F??null;return null});OI(U,q,F??null,ee,!B,h),Jv(F,()=>{R(H),E(F!==I.initialValue),N(F!=null),T.change(F);const se=Y.current;F==null&&se&&!se.disabled&&te(se)});const re=A??D?.legendId,oe={..._,disabled:B??!1,required:l??!1,readOnly:i??!1},X=g.useMemo(()=>({checkedValue:F,disabled:B,form:f,validation:T,name:H,readOnly:i,registerInputRef:J,required:l,setCheckedValue:z,setTouched:G,touched:M}),[F,B,f,T,H,i,J,l,z,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){ln(se.currentTarget,se.relatedTarget)||(b(!0),x(!1),w==="onBlur"&&T.commit(F))},onKeyDownCapture(se){se.key.startsWith("Arrow")&&(G(!0),x(!0))}};return o.jsx(n5t.Provider,{value:X,children:o.jsx(R$t,{render:r,className:s,style:v,state:oe,props:[ne,y,se=>T.getValidationProps(B??!1,se)],refs:[n],stateAttributesMapping:c_,enableHomeAndEndKeys:!1,modifierKeys:QHr})})}),d4=g.forwardRef(({className:e,...t},n)=>o.jsx(YHr,{ref:n,"data-slot":"radio-group",className:K("grid gap-2",e),...t}));d4.displayName="RadioGroup";const Lh=g.forwardRef(({className:e,...t},n)=>o.jsx(VHr,{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(HHr,{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"})})}));Lh.displayName="RadioGroupItem";function zd({title:e,subtitle:t,icon:n,className:r}){return o.jsxs("header",{className:K("flex flex-col w-fit",r),children:[o.jsxs(me,{as:"h2",variant:"header-md",className:"flex items-center gap-2",children:[n&&o.jsx(Ke,{size:"lg",className:"text-accent1",children:n}),e]}),t&&o.jsx(me,{className:"text-ui-md text-neutral3 !font-light",children:t})]})}function S0({title:e,icon:t}){return o.jsxs(me,{as:"h4",variant:"ui-sm",className:"text-neutral2 flex items-center gap-1 uppercase",children:[t&&o.jsx(Ke,{size:"sm",className:"text-neutral1",children:t}),e]})}const Nxe=e=>"field"in e,s5t=e=>e?e.conditions.reduce((t,n)=>Nxe(n)?t+1:t+s5t(n),0):0,Pje=()=>({field:"",operator:"equals",value:""}),KHr=(e="AND")=>({operator:e,conditions:[Pje()]}),FD=e=>Array.isArray(e.type)?e.type.find(t=>t!=="null")||"string":e.type||"string",a5t=e=>{const t=FD(e);return t==="object"&&e.properties?Object.keys(e.properties).length>0:t==="array"&&e.items?FD(e.items)==="object"&&!!e.items.properties:!1},Ixe=(e,t="")=>e?Object.entries(e).map(([n,r])=>{const s=t?`${t}.${n}`:n,a=FD(r),i=a5t(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}}):[],XHr=e=>Ixe(e.properties),JHr=(e,t)=>e.type==="object"&&e.children?Ixe(e.children,t):e.type==="array"&&e.items&&FD(e.items)==="object"&&e.items.properties?Ixe(e.items.properties,t):[],i5t=e=>e.split(".").filter(Boolean),o5t=(e,t)=>{const n=i5t(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=FD(c),d=a5t(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},eWr=e=>{switch(e){case"object":return o.jsx(nc,{});case"array":return o.jsx(d1,{});case"number":case"integer":return o.jsx(c3,{});case"boolean":return o.jsx(X0e,{});default:return o.jsx(ewe,{})}},tWr=({options:e,value:t,onChange:n,placeholder:r="Select field",className:s})=>o.jsx("div",{className:K("relative",s),children:o.jsxs(da,{value:t,onValueChange:n,children:[o.jsx(ha,{className:"bg-surface4 text-neutral6 min-w-35",size:"sm",children:o.jsx(fa,{placeholder:r})}),o.jsx(pa,{children:e.map(a=>o.jsx(xr,{value:a.path,children:o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(Ke,{size:"sm",className:"text-neutral3",children:eWr(a.type)}),a.label,a.hasChildren&&o.jsx("span",{className:"text-neutral3",children:"..."})]})},a.path))})]})}),nWr=({schema:e,value:t,onChange:n,className:r})=>{const s=g.useMemo(()=>i5t(t),[t]),a=g.useMemo(()=>{const l=[],c=XHr(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=o5t(e,u);if(!h||!h.hasChildren)break;const p=JHr(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(tWr,{options:l.options,value:l.value,onChange:u=>i(c,u),placeholder:c===0?"Select field":"Select property"})]},`${l.basePath}-${c}`))})},rWr={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"},sWr=["equals","not_equals","contains","not_contains","greater_than","less_than","greater_than_or_equal","less_than_or_equal","in","not_in","exists","not_exists"],aWr={equals:o.jsx(put,{}),not_equals:o.jsx(_Xt,{}),contains:o.jsx(Jtn,{}),not_contains:o.jsx(h1,{}),greater_than:o.jsx(Fr,{}),less_than:o.jsx(a3,{}),greater_than_or_equal:o.jsx(cut,{}),less_than_or_equal:o.jsx(IKt,{}),in:o.jsx(d1,{}),not_in:o.jsx(GJt,{}),exists:o.jsx(Dr,{}),not_exists:o.jsx(D0e,{})},iWr=({value:e,onChange:t,operators:n,className:r})=>{const s=n??sWr;return o.jsx("div",{className:K("relative",r),children:o.jsxs(da,{value:e,onValueChange:t,children:[o.jsx(ha,{className:"bg-surface4 text-neutral6 min-w-[150px]",size:"sm",children:o.jsx(fa,{placeholder:"Select operator"})}),o.jsx(pa,{children:s.map(a=>o.jsx(xr,{value:a,children:o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(Ke,{size:"sm",className:"text-neutral3",children:aWr[a]}),rWr[a]]})},a))})]})})},l5t=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},oWr=e=>e.trim()===""?[]:e.split(",").map(t=>l5t(t.trim())),cV=e=>e===null?"null":e===void 0?"":Array.isArray(e)?e.map(cV).join(", "):String(e),lWr=e=>e===!0?"true":e===!1?"false":"",cWr=({value:e,onChange:t,className:n})=>{const r=lWr(e),s=g.useCallback(a=>{t(a==="true")},[t]);return o.jsxs("div",{className:K("relative",n),children:[o.jsx(Ke,{size:"sm",className:"text-neutral3 pointer-events-none absolute top-1/2 left-2 z-10 -translate-y-1/2",children:o.jsx(X0e,{})}),o.jsxs(da,{value:r,onValueChange:s,children:[o.jsx(ha,{className:"bg-surface4 min-w-35 pl-7",size:"sm",children:o.jsx(fa,{placeholder:"Select value"})}),o.jsxs(pa,{children:[o.jsx(xr,{value:"true",children:"true"}),o.jsx(xr,{value:"false",children:"false"})]})]})]})},uWr=({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(Ke,{size:"sm",className:"text-neutral3 pointer-events-none absolute top-1/2 left-2 -translate-y-1/2",children:o.jsx(c3,{})}),o.jsx(jn,{type:"number",value:s,onChange:a,placeholder:n||"Enter number",className:"bg-surface4 min-w-35 pl-7",size:"sm"})]})},dWr=({value:e,onChange:t,placeholder:n,className:r})=>{const s=cV(e),a=g.useCallback(i=>{t(l5t(i.target.value))},[t]);return o.jsxs("div",{className:K("relative",r),children:[o.jsx(Ke,{size:"sm",className:"text-neutral3 pointer-events-none absolute top-1/2 left-2 -translate-y-1/2",children:o.jsx(ewe,{})}),o.jsx(jn,{value:s,onChange:a,placeholder:n||"Enter value",className:"bg-surface4 min-w-35 pl-7",size:"sm"})]})},fWr=({value:e,onChange:t,placeholder:n,className:r})=>{const s=g.useMemo(()=>Array.isArray(e)?e.map(cV).join(", "):cV(e),[e]),a=g.useCallback(i=>{t(oWr(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"})},hWr=({value:e,onChange:t,operator:n,fieldType:r,placeholder:s,className:a})=>n==="in"||n==="not_in"?o.jsx(fWr,{value:e,onChange:t,placeholder:s,className:a}):r==="boolean"?o.jsx(cWr,{value:e,onChange:t,placeholder:s,className:a}):r==="number"||r==="integer"?o.jsx(uWr,{value:e,onChange:t,placeholder:s,className:a}):o.jsx(dWr,{value:e,onChange:t,placeholder:s,className:a}),pWr=new Set(["string","number","boolean","integer"]),mWr=({schema:e,rule:t,onChange:n,onRemove:r,className:s})=>{const a=g.useMemo(()=>o5t(e,t.field)?.type,[e,t.field]),i=a!==void 0&&pWr.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(nWr,{schema:e,value:t.field,onChange:h}),d&&o.jsxs(o.Fragment,{children:[o.jsx(iWr,{value:t.operator,onChange:p,operators:l?["in","not_in"]:void 0}),f&&o.jsx(hWr,{value:t.value,onChange:m,operator:t.operator,fieldType:a})]})]}),o.jsx(ae,{type:"button",onClick:r,tooltip:"Remove rule",size:"icon-sm",variant:"ghost",children:o.jsx(tr,{})})]})},gWr=3,c5t=({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,Pje()]})},f=()=>{n({...t,conditions:[...t.conditions,KHr(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(ae,{type:"button",onClick:r,tooltip:"Remove group",size:"icon-sm",variant:"ghost",children:o.jsx(tr,{})})]}),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",Nxe(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()}),Nxe(h)?o.jsx(mWr,{schema:e,rule:h,onChange:m=>c(p,m),onRemove:()=>u(p)}):o.jsx(c5t,{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(ae,{type:"button",onClick:d,variant:"ghost",size:"sm",children:[o.jsx(Ke,{children:o.jsx(Ir,{})}),"Add rule"]}),s<a-1&&o.jsxs(ae,{type:"button",onClick:f,variant:"ghost",size:"sm",children:[o.jsx(Ke,{children:o.jsx(fXt,{})}),"Add group"]})]})]})},vWr=({schema:e,ruleGroup:t,onChange:n,maxDepth:r=gWr,className:s})=>{const a=g.useCallback(l=>{n(l)},[n]),i=g.useCallback(()=>{n({operator:"AND",conditions:[Pje()]})},[n]);return t?o.jsx("div",{className:s,children:o.jsx(c5t,{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(Ke,{children:o.jsx(Ir,{})}),"Add conditional rule"]})};function fA({entityName:e,schema:t,rules:n,onRulesChange:r}){const s=Object.keys(t?.properties??{}).length>0;if(!t||!s)return null;const a=s5t(n);return o.jsxs(pr,{children:[o.jsx(XSe,{asChild:!0,children:o.jsxs(ae,{tooltip:a>0?`${a} rules`:"Display Conditions",size:"icon-sm",variant:"ghost",className:"relative",children:[o.jsx(btn,{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(Ts,{children:"Configure when this entity should be displayed based on variable values."})]}),o.jsx(Nr,{children:o.jsx(vWr,{schema:t,ruleGroup:n,onChange:r})})]})]})}function u5t({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=$n({control:c,name:"defaultSampling.type"}),f=$n({control:c,name:"model.provider"});return o.jsxs("div",{className:"flex h-full flex-col",children:[o.jsx(Sr,{className:"min-h-0 flex-1",children:o.jsxs("div",{className:"flex flex-col gap-6 p-4",children:[o.jsx(zd,{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(So,{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(Ms,{name:"model.provider",control:c,render:({field:h})=>o.jsx(Qy,{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(Ms,{name:"model.name",control:c,render:({field:h})=>o.jsx(Yy,{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(Ms,{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(Ms,{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(Ms,{name:"defaultSampling.type",control:c,render:({field:h})=>o.jsxs(d4,{value:h.value??"none",onValueChange:h.onChange,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Lh,{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(Lh,{value:"ratio",id:"sampling-ratio"}),o.jsx(Dt,{htmlFor:"sampling-ratio",className:"text-neutral5 text-xs",children:"Ratio"})]})]})}),d==="ratio"&&o.jsx(Ms,{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(ae,{variant:"outline",onClick:n,disabled:s||r,className:"flex-1",children:s?o.jsxs(o.Fragment,{children:[o.jsx(Ht,{className:"h-4 w-4"}),"Saving..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Ke,{children:o.jsx(Qu,{})}),"Save"]})}),o.jsx(ae,{variant:"primary",onClick:t,disabled:r||s,className:"flex-1",children:r?o.jsxs(o.Fragment,{children:[o.jsx(Ht,{className:"h-4 w-4"}),"Publishing..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Ke,{children:o.jsx(Dr,{})}),"Publish"]})})]}):o.jsx(ae,{variant:"primary",onClick:t,disabled:r,className:"w-full",children:r?o.jsxs(o.Fragment,{children:[o.jsx(Ht,{className:"h-4 w-4"}),"Creating..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Ke,{children:o.jsx(Dr,{})}),"Create scorer"]})})})]})}function d5t({form:e}){const{control:t}=e;return o.jsxs("div",{className:"flex h-full flex-col gap-3 px-4",children:[o.jsx(zd,{title:"Instructions",subtitle:"Write your scorer's system prompt."}),o.jsx(Ms,{name:"instructions",control:t,render:({field:n})=>o.jsx("div",{className:"flex flex-1 flex-col",children:o.jsx(Hr,{value:n.value??"",onChange:n.onChange,language:"markdown",showCopyButton:!1,placeholder:"Enter scorer instructions...",className:"min-h-[200px] flex-1"})})})]})}const yWr=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 f5t(e={}){const{initialValues:t}=e;return{form:hS({resolver:yWr,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 bWr=["llm-judge"],xWr=Rke("type",[Ss({type:Dx("none")}),Ss({type:Dx("ratio"),rate:vf().min(0).max(1)})]);Ss({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:Uy(bWr),model:Ss({provider:cr(),name:cr()}),instructions:cr(),scoreRange:Ss({min:vf(),max:vf()}),defaultSampling:xWr.optional()});const h5t=(e,t)=>{const n=Qe(),{requestContext:r}=bs();return gt({queryKey:["stored-scorer",e,t?.status,r],queryFn:()=>e?n.getStoredScorer(e).details(r,t):null,enabled:!!e})},$je=e=>{const t=Qe(),n=Er(),{requestContext:r}=bs(),s=wn({mutationFn:l=>t.createStoredScorer(l),onSuccess:()=>{n.invalidateQueries({queryKey:["stored-scorers"]}),n.invalidateQueries({queryKey:["scorers"]})}}),a=wn({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=wn({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}},W1=({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 wWr({onSuccess:e}){const{createStoredScorer:t}=$je(),n=g.useRef(null),{form:r}=f5t(),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(W1,{leftSlot:o.jsx(u5t,{form:r,onPublish:s,isSubmitting:t.isPending,formRef:n}),children:o.jsx("form",{ref:n,className:"h-full",children:o.jsx(d5t,{form:r})})})}const SWr=3e3;function kWr(e){return KL(e.state.error,"scores")||XL(e.state.error)?!1:SWr}const Mje=({traceId:e="",spanId:t="",page:n})=>{const r=Qe();return gt({queryKey:["trace-span-scores",e,t,n],queryFn:()=>r.listScoresBySpan({traceId:e,spanId:t,page:n||0,perPage:10}),enabled:!!e&&!!t,refetchInterval:kWr,gcTime:0,staleTime:0})},p5t=({scorerId:e,params:t})=>{const n=Qe(),{requestContext:r}=bs();return gt({queryKey:["scorer-versions",e,t,r],queryFn:()=>n.getStoredScorer(e).listVersions(t,r),enabled:!!e})},OWr=({scorerId:e,versionId:t})=>{const n=Qe(),{requestContext:r}=bs();return gt({queryKey:["scorer-version",e,t,r],queryFn:()=>n.getStoredScorer(e).getVersion(t,r),enabled:!!e&&!!t})};function CWr(e){const t=Qe(),n=Hl(),r=e?.start||e?.end?e:void 0;return gt({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 R=await t.listScores({filters:{scorerId:N,timestamp:r},pagination:{page:A,perPage:100},orderBy:{field:"timestamp",direction:"DESC"}});if(I.push(...R.scores),!R.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,R)=>A+R,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((R,L)=>R+L,0)/A.length);v=I.reduce((A,R)=>A+R,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 R=w.get(A);R.has(N.scorerId)||R.set(N.scorerId,[]),R.get(N.scorerId).push(N.score)}const k=Array.from(w.entries()).sort(([N],[I])=>N-I),O=k.length>0?k[0][0]:0,T=((k.length>0?k[k.length-1][0]:0)-O)/864e5,E=k.map(([N,I])=>{const A=new Date(N);let R;T>1?R=A.toLocaleDateString("en-US",{month:"short",day:"numeric"})+" "+A.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}):R=A.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1});const L={time:R};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 _Wr(e){return new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})}function EWr({scorerId:e,value:t,onValueChange:n,className:r,disabled:s=!1,variant:a,activeVersionId:i}){const{data:l,isLoading:c}=p5t({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:_Wr(p.createdAt),end:m?o.jsx(mt,{variant:"green",children:"Published"}):v?o.jsx(mt,{variant:"blue",children:"Draft"}):void 0}})];return o.jsx(zo,{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 xh="mastra_workspace",Uv={FILESYSTEM:{READ_FILE:`${xh}_read_file`,WRITE_FILE:`${xh}_write_file`,EDIT_FILE:`${xh}_edit_file`,LIST_FILES:`${xh}_list_files`,DELETE:`${xh}_delete`,FILE_STAT:`${xh}_file_stat`,MKDIR:`${xh}_mkdir`},SANDBOX:{EXECUTE_COMMAND:`${xh}_execute_command`,GET_PROCESS_OUTPUT:`${xh}_get_process_output`,KILL_PROCESS:`${xh}_kill_process`},SEARCH:{SEARCH:`${xh}_search`,INDEX:`${xh}_index`}};function Pd(e,t){return e.length<=t?e:e.slice(0,t)+"…"}const TWr=/[\u001b\u009b][[\]()#;?]*(?:(?:[a-zA-Z\d]*(?:;[-a-zA-Z\d/#&.:=?%@~_]*)*)?\u0007|(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~])/g,jWr=new RegExp("(?<!\\\\)((?:\\\\\\\\)*)\\\\u001[bB](?:\\[[0-9;?<=>]*[a-zA-Z]|\\][\\s\\S]*?(?:\\\\u0007|\\\\u001[bB]\\\\\\\\))","g");function NWr(e){return e.replace(TWr,"")}function IWr(e){return NWr(e).replace(jWr,"$1")}const AWr=3;function RWr(e,{key:t,joins:n,min:r=AWr}){const s=new Map,a=new Set;let i=[];const l=()=>{if(i.length>=r)for(const[c,u]of i.entries())c===0?s.set(t(u),i):a.add(t(u));i=[]};for(const c of e)n(c)?i.push(c):l();return l(),{byFirstKey:s,memberKeys:a}}const m5t=g.createContext(void 0),PWr=()=>{};function Dje(){const e=g.useContext(m5t);if(!e)throw new Error("ToolCall compounds must be rendered within ToolCall");return e}function g5t({open:e,defaultOpen:t=!1,onOpenChange:n=PWr,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(m5t.Provider,{value:{open:u,status:r},children:o.jsxs(cc,{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 v5t=({className:e,...t})=>o.jsx(Bl,{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}),Lje=({className:e,children:t,...n})=>{const{status:r}=Dje();return o.jsx(vLt,{active:r==="running",className:K("flex w-full min-w-0 items-center gap-2 px-1.5 py-1",e),...n,children:t})},Fje=({className:e,...t})=>o.jsx("span",{className:K("flex size-4 shrink-0 items-center justify-center",e),...t}),zje=({className:e,...t})=>o.jsx(me,{as:"span",variant:"ui-sm",className:K("text-icon3 max-w-[55%] shrink-0 truncate",e),...t}),Bje=({className:e,...t})=>{const n=nLt();return o.jsx(me,{as:"span",variant:"ui-xs",font:"mono",className:K("text-icon3 min-w-0 truncate",n,e),...t})},$Wr=({className:e,...t})=>o.jsx("span",{className:K("flex min-w-0 items-center gap-1",e),...t}),Uje=({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}),uV=({className:e,...t})=>o.jsx("span",{className:K("flex shrink-0 items-center",e),...t}),qje=({className:e,children:t,...n})=>{const{open:r}=Dje();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(Fr,{size:13})})})},MWr=({leading:e,icon:t,label:n,detail:r,disclosure:s=!0,...a})=>{const{status:i}=Dje();return o.jsxs(Lje,{...a,children:[e,o.jsx(Fje,{children:o.jsx(t,{size:14,strokeWidth:1.75,"aria-hidden":!0,className:i==="error"?"text-error/80":"text-icon2"})}),o.jsx(zje,{children:n}),r&&o.jsx(Bje,{children:r}),o.jsx(Uje,{}),i==="error"&&o.jsx(uV,{children:o.jsx(tr,{size:13,role:"img","aria-label":"Failed",className:"text-error shrink-0"})}),s&&o.jsx(qje,{})]})},y5t=({className:e,children:t,...n})=>o.jsx(Ul,{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})}),g2=({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"})]}),ZXe=200,DWr=2e3,LWr={removed:{sign:"-",row:"bg-error/10",gutter:"text-error"},added:{sign:"+",row:"bg-accent1/10",gutter:"text-accent1"}};function GXe(e){const t=e.split(`
518
518
  `);return{lines:t.slice(0,ZXe),hidden:Math.max(0,t.length-ZXe)}}function QXe({lines:e,side:t,lang:n}){const{sign:r,row:s,gutter:a}=LWr[t],i=e.join(`
519
519
  `),l=rLt(i,n),c=l?.code===i?l.tokens:void 0;return o.jsx(o.Fragment,{children:e.map((u,d)=>o.jsxs("div",{className:K("flex whitespace-pre",s),children:[o.jsx("span",{className:K("w-5 shrink-0 text-center opacity-70 select-none",a),children:r}),o.jsx("span",{className:"text-icon6 flex-1 pr-2.5",children:c?.[d]?.map((f,h)=>o.jsx("span",{className:"shiki-token",style:sLt(f),children:f.content},h))??u})]},d))})}function FWr({edit:e}){const t=qZn(e.path);if("content"in e)return o.jsx(SG,{code:Pd(e.content,DWr),lang:t,fileName:e.path??"Change",overflow:"scroll"});const n=GXe(e.oldText),r=GXe(e.newText),s=n.hidden+r.hidden;return o.jsxs("div",{className:"border-border1 bg-neutral6/5 max-w-full min-w-0 overflow-x-auto rounded-md border font-mono text-xs leading-normal",role:"group","aria-label":"File change",children:[o.jsx(QXe,{lines:n.lines,side:"removed",lang:t}),o.jsx(QXe,{lines:r.lines,side:"added",lang:t}),s>0&&o.jsxs("div",{className:"text-icon3 px-2.5 py-1 select-none",children:["… ",s," more lines"]})]})}function Axe(e){if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}function b5t(e,t){return t in e}function zWr(e,t){if(!e||typeof e!="object"||!b5t(e,t))return;const n=e[t];return typeof n=="number"?String(n):typeof n=="string"&&n.length>0?n:void 0}function BWr(e,t){for(const n of t){const r=zWr(e,n);if(r)return r}}const UWr={view:{icon:rc,label:"Read",detailKeys:["path"]},read_file:{icon:rc,label:"Read",detailKeys:["path"]},write_file:{icon:gE,label:"Write",detailKeys:["path"]},create_file:{icon:gE,label:"Write",detailKeys:["path"]},edit_file:{icon:gE,label:"Edit",detailKeys:["path"]},string_replace:{icon:gE,label:"Edit",detailKeys:["path"]},str_replace:{icon:gE,label:"Edit",detailKeys:["path"]},ast_edit:{icon:gE,label:"Edit",detailKeys:["path"]},execute_command:{icon:Aut,label:"Run",detailKeys:["command"],isCommand:!0},get_process_output:{icon:Otn,label:"Process output",detailKeys:["pid"]},kill_process:{icon:F0e,label:"Stop process",detailKeys:["pid"]},find_files:{icon:HMe,label:"Find files",detailKeys:["pattern","path"]},list_files:{icon:HMe,label:"List files",detailKeys:["pattern","path"]},grep:{icon:ra,label:"Search",detailKeys:["pattern","path"]},search_content:{icon:ra,label:"Search",detailKeys:["pattern","query"]},search:{icon:ra,label:"Search",detailKeys:["query"]},web_search:{icon:Py,label:"Search the web",detailKeys:["query"]},lsp_inspect:{icon:nc,label:"Inspect code",detailKeys:["path"]},file_stat:{icon:ZXt,label:"File info",detailKeys:["path"]},delete:{icon:cl,label:"Delete",detailKeys:["path"]},delete_file:{icon:cl,label:"Delete",detailKeys:["path"]},mkdir:{icon:o3,label:"New folder",detailKeys:["path"]},skill:{icon:I$,label:"Skill",detailKeys:["name"]},skill_search:{icon:I$,label:"Search skills",detailKeys:["query"]},skill_read:{icon:I$,label:"Skill file",detailKeys:["path"]}};function qWr(e){const t=e.replace(/[_-]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):e}function VWr(e){return e.replace(/^\s*cd\s+(?:'[^']*'|"[^"]*"|[^\s&|;]+)\s*&&\s*/,"")||e}function Vje(e,t){const n=UWr[e.replace(/^mastra_workspace_/,"")];if(!n)return{icon:Vd,label:qWr(e)};const r=n.detailKeys?BWr(t,n.detailKeys):void 0;return r?n.isCommand?{icon:n.icon,label:n.label,detail:VWr(r),command:r}:{icon:n.icon,label:n.label,detail:r}:{icon:n.icon,label:n.label}}function zz(e,t){if(!(!e||typeof e!="object"||!b5t(e,t)))return typeof e[t]=="string"?e[t]:void 0}function HWr(e,t){const n=zz(t,"path"),r=zz(t,"new_string");if(/string_replace|str_replace|edit_file/i.test(e)&&r!==void 0)return{path:n,oldText:zz(t,"old_string")??"",newText:r};const s=zz(t,"content");if(/write_file|create_file/i.test(e)&&s!==void 0)return{path:n,content:s}}const WWr=new Set(["task_write","task_update","task_complete","task_check"]);function ZWr(e){return WWr.has(e)}const GWr=4;function QWr({steps:e,leading:t,children:n}){const r=e.find(a=>a.status==="running"),s=r&&Vje(r.toolName,r.args).detail;return o.jsxs(g5t,{status:r?"running":"idle","aria-label":`Tool group: ${e.length} steps`,children:[o.jsx(v5t,{children:o.jsxs(Lje,{children:[t,o.jsx(Fje,{children:o.jsx(gut,{size:14,strokeWidth:1.75,"aria-hidden":!0,className:"text-icon2"})}),o.jsxs(zje,{children:[e.length," steps"]}),s&&o.jsx(Bje,{children:s}),o.jsx(KWr,{steps:e}),o.jsx(Uje,{rule:!0}),o.jsx(uV,{children:o.jsx(YWr,{steps:e})}),o.jsx(qje,{})]})}),o.jsx(y5t,{className:"py-0.5 pr-0 pl-2.5",children:o.jsx(Sr,{maxHeight:"18rem",autoScroll:!!r,revealScrollbarOnHover:!1,children:n})})]})}function YWr({steps:e}){const t=e.filter(n=>n.status!=="running").length;return t<e.length?o.jsxs(me,{as:"span",variant:"ui-xs",className:"text-icon3 shrink-0 tabular-nums",children:[t,"/",e.length]}):e.some(n=>n.status==="error")?o.jsx(tr,{size:13,role:"img","aria-label":"Failed",className:"text-error shrink-0"}):null}function KWr({steps:e}){const n=[...new Map(e.map(r=>Vje(r.toolName,r.args)).map(({label:r,icon:s})=>[r,s]))].slice(0,GWr);return o.jsx($Wr,{role:"img","aria-label":n.map(([r])=>r).join(", "),className:"shrink-0 gap-1.5",children:n.map(([r,s])=>o.jsx(s,{size:12,strokeWidth:1.75,className:"text-icon2"},r))})}const x5t=g.createContext({}),XWr=({onToolOpen:e,children:t})=>{const n=g.useMemo(()=>({onToolOpen:e}),[e]);return o.jsx(x5t.Provider,{value:n,children:t})},JWr=()=>g.useContext(x5t),w5t=g.createContext({messages:[]}),S5t=g.createContext({isRunning:!1,cancelRun:()=>{},canSendWhileStreaming:!1}),k5t=g.createContext({send:()=>{}}),O5t=g.createContext({tasks:[]}),C5t=g.createContext(void 0),eZr=()=>g.useContext(w5t).messages,hA=()=>g.useContext(S5t),Hje=()=>g.useContext(k5t).send,tZr=()=>g.useContext(O5t).tasks,f4=({children:e,initialCollapsed:t=!0,icon:n,title:r,detail:s,collapsible:a=!0,extraInfo:i,header:l,status:c="idle",toolCallId:u,"data-testid":d})=>{const[f,h]=g.useState(!t),{isRunning:p}=hA(),{onToolOpen:m}=JWr(),v=w=>{h(w),w&&u&&m?.(u)},[y]=g.useState(()=>p);g.useEffect(()=>{h(!t)},[t]);const b=l??o.jsxs(Lje,{children:[o.jsx(Fje,{children:n}),o.jsx(zje,{children:r}),s&&o.jsx(Bje,{children:s}),o.jsx(Uje,{}),c==="error"&&o.jsx(uV,{children:o.jsx(tr,{size:13,role:"img","aria-label":"Failed",className:"text-error shrink-0"})}),a&&o.jsx(qje,{})]}),x=!a||f;return o.jsxs(g5t,{open:x,onOpenChange:v,status:c,className:K(y&&"motion-safe:animate-in fade-in-0 slide-in-from-bottom-1"),"data-testid":d,children:[o.jsxs("span",{className:"flex w-full min-w-0 items-center",children:[a?o.jsx(v5t,{className:"min-w-0 flex-1",children:b}):o.jsx("span",{className:"min-w-0 flex-1",children:b}),i&&o.jsx(uV,{className:"gap-1 pr-1",children:i})]}),o.jsx(y5t,{children:e})]})},Wje=()=>o.jsx(f4,{icon:o.jsx(Ht,{className:"text-neutral3"}),title:o.jsx(Et,{className:"ml-2 h-2 w-12"}),collapsible:!1}),nZr=({agents:e})=>{const{Link:t,paths:n}=un();return e.length===0?o.jsx(OS,{children:"No agents"}):o.jsx(kS,{children:e.map(r=>o.jsx(Gx,{children:o.jsx(t,{href:n.agentLink(r.id),"data-testid":"agent-badge",children:o.jsx(mt,{variant:"green",icon:o.jsx(uo,{}),children:r.name})})},r.id))})},rZr=({agentId:e})=>{const{data:t,isLoading:n}=Gl(e),{mutate:r}=iMr(e),{mutateAsync:s}=oMr(e),a=c0(),{isCmsAvailable:i,isLoading:l}=CS();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(Mc,{className:"bg-surface3",children:[o.jsx(wx,{children:o.jsx(om,{children:"Models"})}),o.jsx(Dd,{children:o.jsx(tqr,{modelList:t.modelList,updateModelInModelList:s,reorderModelList:r})})]}),o.jsxs(Mc,{className:"bg-surface3",children:[o.jsxs(wx,{className:"flex-row items-baseline gap-2 space-y-0",children:[o.jsx(om,{children:"Capabilities"}),o.jsx(r1,{children:"Everything this agent can call at runtime"})]}),o.jsxs(Dd,{children:[u.length>0&&o.jsx(cw,{title:o.jsx(VE,{title:"Agents",count:u.length}),hint:{link:"https://mastra.ai/en/docs/agents/overview",title:"Agents documentation"},children:o.jsx(nZr,{agents:u})}),o.jsx(cw,{title:o.jsx(VE,{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(sZr,{tools:f,agentId:e})}),o.jsx(cw,{title:o.jsx(VE,{title:"Workflows",count:p.length}),hint:{link:"https://mastra.ai/en/docs/workflows/overview",title:"Workflows documentation"},children:o.jsx(aZr,{workflows:p})}),v.length>0&&o.jsx(cw,{title:o.jsx(VE,{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(cZr,{tools:v})}),y.length>0&&o.jsx(cw,{title:o.jsx(VE,{title:"Browser Tools",count:y.length}),hint:{link:"https://mastra.ai/en/docs/agents/adding-browser-control",title:"Browser tools documentation"},children:o.jsx(uZr,{tools:y})}),(x.length>0||w.length>0)&&o.jsx(cw,{title:"Processors",hint:{link:"https://mastra.ai/docs/agents/processors",title:"Processors documentation"},children:o.jsx(dZr,{inputProcessors:x,outputProcessors:w})}),o.jsx(cw,{title:o.jsx(VE,{title:"Skills",count:m.length}),hint:{link:"https://mastra.ai/en/docs/workspace/skills",title:"Skills documentation"},children:o.jsx(oZr,{skills:m,agentId:e,workspaceId:b})}),o.jsx(cw,{title:"Scorers",children:o.jsx(iZr,{entityId:t.name,entityType:"AGENT"})})]})]}),o.jsxs(Mc,{className:"bg-surface3",children:[o.jsx(wx,{children:o.jsx(om,{children:"System Prompt"})}),o.jsxs(Dd,{className:"space-y-3",children:[o.jsx(rd,{className:"border-border1 rounded-md border",value:l4(t.instructions),editable:!1,extensions:[ROe({base:lC,codeLanguages:gCt}),Rt.lineWrapping],theme:a}),!l&&!i&&o.jsx(An,{variant:"warning",title:"Read-only",children:o.jsxs(An.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"}),"."]})})]})]})]})},VE=({title:e,count:t})=>o.jsxs("span",{className:"flex items-center gap-1.5",children:[e,o.jsx(mt,{variant:"neutral",children:t})]}),sZr=({tools:e,agentId:t})=>{const{Link:n,paths:r}=un();return e.length===0?o.jsx(OS,{children:"No tools"}):o.jsx(kS,{children:e.map(s=>o.jsx(Gx,{children:o.jsx(n,{href:r.agentToolLink(t,s.id),"data-testid":"tool-badge",children:o.jsx(mt,{icon:o.jsx(qf,{className:"text-accent6"}),children:s.id})})},s.id))})},aZr=({workflows:e})=>{const{Link:t,paths:n}=un();return e.length===0?o.jsx(OS,{children:"No workflows"}):o.jsx(kS,{children:e.map(r=>o.jsx(Gx,{children:o.jsx(t,{href:n.workflowLink(r.id),"data-testid":"workflow-badge",children:o.jsx(mt,{icon:o.jsx(_u,{className:"text-accent3"}),children:r.name})})},r.id))})},iZr=({entityId:e,entityType:t})=>{const{Link:n,paths:r}=un(),{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(Wje,{}):i.length===0?o.jsx(OS,{children:"No Scorers"}):o.jsx(kS,{children:i.map(l=>o.jsx(Gx,{children:o.jsx(n,{href:r.scorerLink(l.id),"data-testid":"scorer-badge",children:o.jsx(mt,{icon:o.jsx(fm,{className:"text-neutral3"}),children:l.scorer.config.name})})},l.id))})},oZr=({skills:e,agentId:t,workspaceId:n})=>{const{Link:r,paths:s}=un(),{isSkillActivated:a}=T4t();return e.length===0?o.jsx(OS,{children:"No skills"}):o.jsx(kS,{children:e.map(i=>{const l=a(i.name),c=o.jsxs(mt,{icon:o.jsx(lA,{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(Gx,{children:l?o.jsx(Vl,{children:o.jsxs(bn,{children:[o.jsx(mn,{asChild:!0,children:o.jsx(r,{href:s.agentSkillLink(t,i.name,i.path,n),"data-testid":"skill-badge",children:c})}),o.jsx(gn,{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 lZr(e){const t=`${xh}_`;return e.startsWith(t)?e.slice(t.length):e}const cZr=({tools:e})=>e.length===0?o.jsx(OS,{children:"No workspace tools"}):o.jsx(kS,{children:e.map(t=>o.jsx(Gx,{children:o.jsx(mt,{icon:o.jsx(fI,{className:"text-accent1 h-3 w-3"}),children:lZr(t)})},t))}),uZr=({tools:e})=>e.length===0?o.jsx(OS,{children:"No browser tools"}):o.jsx(kS,{children:e.map(t=>o.jsx(Gx,{children:o.jsx(mt,{icon:o.jsx(Py,{className:"h-3 w-3 text-cyan-500"}),children:t})},t))}),dZr=({inputProcessors:e,outputProcessors:t})=>{const{Link:n,paths:r}=un();if(e.length===0&&t.length===0)return o.jsx(OS,{children:"No processors"});const s=e[0]?.id,a=t[0]?.id;return o.jsxs(kS,{children:[e.length>0&&s&&o.jsx(Gx,{children:o.jsx(n,{href:`${r.workflowLink(s)}/graph`,"data-testid":"processor-badge",children:o.jsx(mt,{icon:o.jsx(oV,{className:"text-accent4"}),children:"input"})})}),t.length>0&&a&&o.jsx(Gx,{children:o.jsx(n,{href:`${r.workflowLink(a)}/graph`,"data-testid":"processor-badge",children:o.jsx(mt,{icon:o.jsx(oV,{className:"text-accent5"}),children:"output"})})})]})},j_=e=>{const t=Qe(),n=Hl();return gt({queryKey:["memory",e,n],queryFn:()=>e?t.getMemoryStatus(e,n):null,enabled:!!e,staleTime:300*1e3,gcTime:600*1e3,retry:!1})},_S=e=>{const t=Qe(),n=Hl();return gt({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})},Zje=({threadId:e,agentId:t})=>{const n=Qe(),r=Hl();return gt({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})},_5t=({resourceId:e,agentId:t,isMemoryEnabled:n})=>{const r=Qe(),s=Hl();return gt({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})},fZr=()=>{const e=Qe(),t=Er(),n=Hl();return wn({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")}})},hZr=({agentId:e,resourceId:t,threadId:n})=>{const r=Hl(),s=Qe();return wn({mutationFn:async({searchQuery:a,memoryConfig:i})=>s.searchMemory({agentId:e,resourceId:t,threadId:n,searchQuery:a,memoryConfig:i,requestContext:r})})},pZr=()=>{const e=Qe(),t=Er(),n=Hl();return wn({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")}})},mZr=({agentId:e,resourceId:t,threadId:n,enabled:r=!0,isActive:s=!1})=>{const a=Qe(),i=Hl();return gt({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})},E5t=({agentId:e,resourceId:t,threadId:n,pollWhenActive:r=!0})=>{const s=Qe(),a=Hl(),[i,l]=g.useState(!1),c=gt({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},YXe=e=>e===void 0?"Default":typeof e=="number"?`${e.toLocaleString()} tokens`:`${e.min.toLocaleString()}-${e.max.toLocaleString()} tokens`,KXe={success:"green",info:"blue",warning:"yellow"};function gZr({value:e,badge:t}){return typeof e=="boolean"?o.jsx(mt,{size:"xs",indicator:"dot",variant:e?t?KXe[t]:"green":"red",children:e?"Yes":"No"}):t?o.jsx(mt,{size:"xs",variant:KXe[t],children:e}):o.jsx(o.Fragment,{children:e})}const vZr=({agentId:e})=>{const{data:t,isLoading:n}=_S(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:YXe(c?l.observation?.messageTokens:void 0)},{label:"Observation Tokens",value:YXe(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(me,{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(cc,{defaultOpen:a.title!=="Observational Memory",children:[o.jsxs(Bl,{className:"text-neutral5 flex w-full items-center justify-between px-4 py-2.5",children:[o.jsx(me,{as:"span",variant:"ui-md",className:"font-medium text-inherit",children:a.title}),o.jsx(Fr,{className:"text-neutral3 size-4"})]}),o.jsx(Ul,{className:"px-4 pb-3",children:o.jsx(Rje,{data:a.items.map(i=>({key:`${a.title}-${i.label}`,label:i.label,value:o.jsx(gZr,{value:i.value??"",badge:i.badge})}))})})]},a.title))})};function yZr({agentId:e}){const{data:t}=pG(),n=!!t?.length;return o.jsx("div",{className:"h-full w-full min-w-0","data-testid":"agent-settings-view",children:o.jsx(Sr,{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(rZr,{agentId:e}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs(Mc,{className:"bg-surface3",children:[o.jsx(wx,{children:o.jsx(om,{children:"Memory"})}),o.jsx(Dd,{className:"p-0",children:o.jsx(vZr,{agentId:e})})]}),n&&o.jsxs(Mc,{className:"bg-surface3",children:[o.jsx(wx,{children:o.jsx(om,{children:"Channels"})}),o.jsx(Dd,{children:o.jsx(YUr,{agentId:e})})]})]})]})})})}const bZr=({agentId:e})=>{const{data:t,isLoading:n}=Gl(e),{handleCopy:r,isCopied:s}=Wd({text:e}),a=t?.name||"";return o.jsx(Vl,{children:o.jsx("div",{className:"min-w-0 overflow-x-hidden p-3",children:o.jsxs(bn,{children:[o.jsx(mn,{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(Ke,{size:"lg",children:o.jsx(uo,{})})}),n?o.jsx(Et,{className:"h-3 w-32"}):o.jsx(me,{variant:"header-md",as:"h2",className:"truncate font-medium",children:a}),s?o.jsx(Dr,{className:"text-neutral3 h-4 w-4 shrink-0"}):o.jsx(Ud,{className:"text-neutral3 h-4 w-4 shrink-0"})]})}),o.jsx(gn,{children:"Copy Agent ID for use in code"})]})})})};function AG(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 xZr({agentId:e}){const{data:t}=Gl(e),{canCreateAgent:n}=dDt(),{Link:r,paths:s}=un(),a=`${window.location.origin}${AG(`/agents/${encodeURIComponent(e)}/session`)}`,{handleCopy:i,isCopied:l}=Wd({text:a,copyMessage:"Session URL copied to clipboard!"}),c=t?.source==="stored",u=s.cmsAgentEditLink(e),d=n&&c&&!!u;return o.jsx(Vl,{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(bZr,{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(ae,{variant:"outline",size:"sm",as:r,to:u,children:[o.jsx(Ke,{size:"sm",children:o.jsx(Yh,{})}),"Edit"]}),o.jsxs(ae,{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(Ke,{size:"sm",children:l?o.jsx(Dr,{}):o.jsx(xut,{})}),"Share"]}),o.jsxs(ae,{variant:"primary",size:"sm",as:r,to:s.agentNewThreadLink(e),"data-testid":"agent-view-header-new-chat",children:[o.jsx(Ke,{size:"sm",children:o.jsx(fen,{})}),"Open chat"]})]})]})})}function wZr(){const{agentId:e}=fr(),{data:t,isLoading:n,error:r}=Gl(e);return r&&rs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(_s,{})}):r&&is(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ys,{resource:"agents"})}):n?o.jsx(ZUr,{}):r&&m0(r)?o.jsx("div",{className:"py-4 text-center",children:"Agent not found"}):r?o.jsx(Bs,{title:"Failed to load agent",message:r.message}):t?o.jsx(EG,{children:o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[o.jsx(xZr,{agentId:e}),o.jsx("div",{className:"min-h-0 overflow-hidden",children:o.jsx(yZr,{agentId:e})})]})},e):o.jsx("div",{className:"py-4 text-center",children:"Agent not found"})}function ks({children:e,className:t,style:n}){const r=T5t("MainContentLayout"),s=$$t();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=T5t("MainContentContent"),l=SZr({isCentered:n,isDivided:r,hasLeftServiceColumn:s,className:t});return o.jsx("div",{className:l,style:{...a,...i?{border:"3px dotted orange"}:{}},children:e})}const SZr=({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 T5t(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 j5t({config:e,redirectUri:t,className:n,loginUrl:r="/login"}){const{mutate:s,isPending:a}=BDt();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(ae,{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(AG(r),window.location.origin);t&&l.searchParams.set("redirect",t),window.location.href=l.toString()};return o.jsx(ae,{onClick:i,className:n,children:"Sign in"})}function XXe({user:e,size:t="sm"}){if(!e)return null;const n=e.name||e.email||"User";return o.jsx(Iy,{src:e.avatarUrl,name:n,size:t})}function kZr({user:e}){const[t,n]=g.useState(!1),{mutate:r,isPending:s}=WMr(),{data:a}=fc(),{isImpersonating:i,impersonatedRole:l,startImpersonation:c,stopImpersonation:u,isSwitching:d}=HH();if(!e)return null;const f=()=>{r(void 0,{onSuccess:m=>{m.redirectTo?window.location.href=m.redirectTo:window.location.reload()}})},h=a&&Im(a)?a.availableRoles:void 0,p=e.name||e.email||"User";return o.jsxs(Wf,{open:t,onOpenChange:n,children:[o.jsx(tf,{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(XXe,{user:e,size:"sm"})})}),o.jsxs(nf,{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(XXe,{user:e,size:"md"}),o.jsxs("div",{className:"flex flex-col overflow-hidden",children:[o.jsx(me,{variant:"ui-md",className:"truncate font-medium",children:p}),e.email&&o.jsx(me,{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(me,{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(Ws,{className:"h-3.5 w-3.5 animate-spin"}),o.jsx("span",{className:"flex-1 capitalize",children:m.name}),v&&o.jsx(tr,{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(ae,{as:gi,to:"/settings",variant:"ghost",className:"w-full justify-start",onClick:()=>n(!1),children:[o.jsx(Mj,{className:"h-4 w-4"}),"Settings"]}),o.jsx(ae,{variant:"ghost",onClick:f,disabled:s,className:"w-full justify-start",children:s?"Signing out...":"Sign out"})]})]})]})}function zD({className:e}){const{data:t,isLoading:n,error:r}=fc();return n||r||!t?.enabled?null:Im(t)?o.jsx(kZr,{user:t.user}):o.jsx(j5t,{config:t.login,redirectUri:typeof window<"u"?window.location.href:void 0,className:e})}const Bz="__custom__",N5t=()=>{const e=Hwt(),{requestContext:t,setRequestContext:n}=bs(),r=g.useMemo(()=>{if(!e)return Bz;const a=JSON.stringify(t??{});for(const[i,l]of Object.entries(e))if(JSON.stringify(l)===a)return i;return Bz},[e,t]),s=a=>{if(a===Bz){n({});return}if(!e)return;const i=e[a];i&&n(i)};return o.jsxs(eW,{children:[o.jsxs(FSe,{children:[o.jsx(Zh,{className:"h-5 w-8 shrink-0"}),"Mastra Studio",o.jsx(zD,{})]}),e&&Object.keys(e).length>0&&o.jsx(Pxt,{children:o.jsxs(da,{value:r,onValueChange:s,children:[o.jsx(ha,{size:"sm",className:"w-[200px]",children:o.jsx(fa,{placeholder:"Select a preset..."})}),o.jsxs(pa,{children:[o.jsx(xr,{value:Bz,children:"Custom"}),Object.keys(e).map(a=>o.jsx(xr,{value:a,children:a},a))]})]})})]})},JXe={modelSettings:{maxRetries:2,maxSteps:15,chatWithGenerateLegacy:!1,chatWithGenerate:!1,chatWithLegacyStream:!1}};function OZr({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:{...JXe.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:{...JXe.modelSettings,...t?.modelSettings??{}}};r(l),localStorage.removeItem(s)}}}const I5t=g.createContext({});function Gje({children:e,agentId:t,defaultSettings:n}){const{settings:r,setSettings:s,resetAll:a}=OZr({agentId:t,defaultSettings:n});return o.jsx(I5t.Provider,{value:{settings:r,setSettings:s,resetAll:a},children:e})}const Qje=()=>g.useContext(I5t),Rxe=(e,t)=>["memory","status",e,t],dV=(e,t)=>["memory","thread",e,"messages",t??0];function CZr(e,t){const n=Qe(),r=0,s=100;return gt({queryKey:dV(e,r),queryFn:e?()=>n.getMemoryThread({threadId:e}).listMessages({page:r,perPage:s}):l_})}const fV=(e,t)=>["memory","observational-memory",e,t];function A5t(e,t,n){const r=Qe();return gt({queryKey:fV(e,t),queryFn:e&&t?()=>r.getObservationalMemory({agentId:e,threadId:t,resourceId:n}):l_,staleTime:5e3})}const R5t="mastra-memory-om-observation",eJe={"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"},P5t=(e,t)=>{for(const n of e){if(!(n.type in eJe))continue;const r=n,s=r.data?.cycleId;if(!s)continue;const a=eJe[r.type],i=t.get(s)||{};i[a]=r,t.set(s,i)}return t},Yje=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0,Kje=e=>Array.isArray(e)&&e.length>0,nO=e=>({...Yje(e?.extractedValues)?{extractedValues:e.extractedValues}:{},...Kje(e?.extractionFailures)?{extractionFailures:e.extractionFailures}:{}}),BT=e=>Object.keys(nO(e)).length>0,Uz=(e,t)=>{if(!e?.data||!t)return e;const n=nO(e.data),r=nO(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}}},_Zr=(e,t)=>{for(const[n,r]of e){const s=t.get(n);s&&(r.end=Uz(r.end,s.end),r.failed=Uz(r.failed,s.failed),r.bufferingEnd=Uz(r.bufferingEnd,s.bufferingEnd),r.bufferingFailed=Uz(r.bufferingFailed,s.bufferingFailed));const a={...s??{}};BT(r.end?.data)&&(a.end=nO(r.end?.data)),BT(r.failed?.data)&&(a.failed=nO(r.failed?.data)),BT(r.bufferingEnd?.data)&&(a.bufferingEnd=nO(r.bufferingEnd?.data)),BT(r.bufferingFailed?.data)&&(a.bufferingFailed=nO(r.bufferingFailed?.data)),Object.keys(a).length>0&&t.set(n,a)}return e},EZr=(e,t)=>{const n=new Map;for(const r of e){const s=r?.content?.parts;Array.isArray(s)&&P5t(s,n)}return t?_Zr(n,t):n},TZr=(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:Yje(u.extractedValues)?u.extractedValues:void 0,extractionFailures:Kje(u.extractionFailures)?u.extractionFailures:void 0,omData:u,isLoading:c==="observing"}},jZr=(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:Yje(f.extractedValues)?f.extractedValues:void 0,extractionFailures:Kje(f.extractionFailures)?f.extractionFailures:void 0,omData:f,isLoading:d==="buffering"}},qz=(e,t,n)=>n==="observation"?TZr(e,t):jZr(e,t),Vz=(e,t,n)=>({type:"dynamic-tool",toolCallId:`om-${t}-${e}`,toolName:R5t,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"}),tJe=(e,t)=>t==="observation"?!!e?.end||!!e?.failed:!!e?.bufferingEnd||!!e?.bufferingFailed,nJe=(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",rJe=e=>e.type.startsWith("data-om-"),NZr=(e,t)=>{if(!e||!Array.isArray(e.content?.parts)||!e.content.parts.some(rJe))return e;const n=P5t(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=tJe(c,"observation")?c??l:{start:l.start},d=qz(a,u,"observation");if(!d)continue;r.push(Vz(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=tJe(c,"buffering")?c??l:{bufferingStart:l.bufferingStart},d=qz(a,u,"buffering");if(!d)continue;r.push(Vz(a,"buffering",d))}else if(a&&nJe(i,"observation")){const l=n.get(a),c=t.get(a);if(l?.start||c?.start||!c)continue;const u=qz(a,c,"observation");if(!u)continue;r.push(Vz(a,"observation",u))}else if(a&&nJe(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=qz(a,c,"buffering");if(!u)continue;r.push(Vz(a,"buffering",u))}else{if(rJe(s))continue;r.push(s)}}return{...e,content:{...e.content,parts:r}}},$5t=(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}),Xje=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}},sJe=e=>{const t=Xje(e),n=new Set([...t.buffering,...t.activatedBuffering]);return $5t(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===R5t){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}})},IZr=e=>{const{buffering:t,activatedBuffering:n}=Xje(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"&&!BT(i.data))return!0}}return!1},M5t=(e,t)=>{const n=new Map,r=Xje(e).buffering;if(t?.bufferedObservationChunks)for(const s of t.bufferedObservationChunks)s.cycleId&&n.set(s.cycleId,s);return $5t(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&&!BT(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}})},AZr=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}},RZr="tool-calls",PZr=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.`,$Zr=e=>{if(e.type!=="finish")return;const t=e.payload?.stepResult?.reason;return typeof t=="string"?t:void 0},MZr=e=>$Zr(e)===RZr,Pxe=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"}}}},DZr=(e,t)=>Pxe({runId:e.runId,payload:{error:PZr(t)}}),aJe=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},LZr=e=>{const t=new WC;return Object.entries(e.requestContext??{}).forEach(([n,r])=>{t.set(n,r)}),e.agentVersionId&&t.set("agentVersionId",e.agentVersionId),t},iJe=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,FZr=({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:O,handleActivation:_,resetObservationalMemoryStreamState:T,signalTimelineRefresh:E})=>{const N=Qe(),I=Er(),A=g.useRef(null),R=g.useRef({requestContext:t,agentVersionId:n,threadId:r,modelSettingsArgs:s,model:a,chatWithNetwork:i,chatWithGenerate:l,maxSteps:c,isOMEnabled:u,tracingOptions:d});R.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(F=>{F&&(I.refetchQueries({queryKey:fV(e,F)}),I.refetchQueries({queryKey:dV(F)}),I.refetchQueries({queryKey:Rxe(e,F)}),E())},[e,I,E]),D=g.useCallback(F=>{!F||!R.current.isOMEnabled||N.awaitBufferStatus({agentId:e,resourceId:e,threadId:F}).then(V=>{v(M=>M5t(M,V?.record)),I.invalidateQueries({queryKey:["observational-memory",e]}),I.invalidateQueries({queryKey:["memory-status",e]}),L(F)}).catch(()=>{})},[e,N,I,L,v]),B=g.useCallback(F=>{F?.type==="error"&&y(V=>[...V,Pxe(F)]),F?.type==="data-om-observation-start"&&w(F.data?.operationType),F?.type==="data-om-status"&&k(F.data),(F?.type==="data-om-observation-end"||F?.type==="data-om-observation-failed"||F?.type==="data-om-activation")&&O(F.data?.operationType),F?.type==="data-om-activation"&&_(F.data)},[_,w,k,O,y]),H=g.useCallback(async({message:F,attachments:V=[]})=>{const M=R.current;if(f.current&&(h||A.current))return;y([]);const G=new AbortController;A.current=G;const z=LZr(M);try{if(M.chatWithNetwork)await p({message:F,mode:"network",coreUserMessages:V,requestContext:z,threadId:M.threadId,modelSettings:M.modelSettingsArgs,model:M.model,signal:G.signal,tracingOptions:M.tracingOptions,onNetworkChunk:async P=>{iJe(P)&&x?.(),P.type==="network-execution-event-step-finish"&&b?.(),B(aJe(P))}});else if(M.chatWithGenerate){await p({message:F,mode:"generate",coreUserMessages:V,requestContext:z,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:F,mode:"stream",coreUserMessages:V,requestContext:z,threadId:M.threadId,modelSettings:M.modelSettingsArgs,model:M.model,tracingOptions:M.tracingOptions,onChunk:async P=>{P.type==="finish"&&(MZr(P)&&y(U=>[...U,DZr(P,M.maxSteps)]),await b?.()),iJe(P)&&x?.(),B(aJe(P))},signal:G.signal}),L(M.threadId),D(M.threadId);return}setTimeout(()=>{b?.()},500),L(M.threadId),D(M.threadId)}catch(P){if(console.error("Error occurred in ChatProvider",P),P.name==="AbortError")return;y(U=>[...U,Pxe({runId:"thrown",payload:{error:P}})]),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(R.current.threadId)},[m,D,T]);return{send:H,cancel:q}};function oJe(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function zZr(e,t,n){const r=Qe(),[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}=bs(),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:O,workingMemoryTemplate:_,threadExists:T}=w;if(a(T),l(k),u(O),f(_?.format||"markdown"),_?.format==="json"){let E="";k?E=oJe(k):_?.content?E=oJe(_.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 D5t=g.createContext({threadExists:!1,workingMemoryData:null,workingMemorySource:"thread",isLoading:!1,isUpdating:!1,updateWorkingMemory:()=>Promise.resolve(),refetch:()=>Promise.resolve()});function L5t({agentId:e,threadId:t,resourceId:n,children:r}){const s=zZr(e,t,n);return o.jsx(D5t.Provider,{value:s,children:r})}function F5t(){const e=g.useContext(D5t);if(!e)throw new Error("useWorkingMemory must be used within a WorkingMemoryProvider");return e}const z5t=g.createContext(null);function B5t({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(z5t.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 RG(){const e=g.useContext(z5t);return e||{isObservingFromStream:!1,setIsObservingFromStream:()=>{},isReflectingFromStream:!1,setIsReflectingFromStream:()=>{},observationsUpdatedAt:0,signalObservationsUpdated:()=>{},streamProgress:null,setStreamProgress:()=>{},activatedCycleIds:new Set,markCycleIdActivated:()=>{},clearProgress:()=>{}}}const U5t=g.createContext(null),BZr={isPanelOpen:!1,openPanel:()=>{},closePanel:()=>{},selectedTimestamp:null,setSelectedTimestamp:()=>{}};function UZr({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(U5t.Provider,{value:l,children:e})}function PG(){return g.useContext(U5t)??BZr}const Jje=g.createContext(null);function eNe({children:e,...t}){return o.jsx(Jje.Provider,{value:t,children:e})}function Ho(){const e=g.useContext(Jje);if(!e)throw new Error("useAgentEditFormContext must be used within an AgentEditFormProvider");return e}function q5t(){return g.useContext(Jje)}const tNe=g.createContext(null);function V5t({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(tNe.Provider,{value:{provider:l,model:c,modelOverride:d,setProvider:a,setModel:i},children:e})}function nNe(){const e=g.useContext(tNe);if(!e)throw new Error("usePlaygroundModel must be used within a PlaygroundModelProvider");return e}function rNe(){return g.useContext(tNe)??void 0}const H5t=g.createContext(null);function qZr({children:e}){const[t,n]=g.useState([]),[r,s]=g.useState([]),[a,i]=g.useState(null),{updateExperimentResult:l}=La(),c=Qe(),u=g.useCallback(x=>{n(w=>{const k=new Set(w.map(_=>_.itemId)),O=x.filter(_=>!k.has(_.itemId));return[...w,...O.map((_,T)=>({..._,id:_.id||`review-${Date.now()}-${T}`,tags:_.tags??[]}))]})},[]),d=g.useCallback(x=>{n(w=>{const k=new Map(x.map(_=>[_.id,_])),O=w.filter(_=>!k.has(_.id));return[...x,...O]})},[]),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(O=>O.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(O=>O.id!==x))},[t,l]),p=g.useCallback((x,w)=>{const k=t.find(O=>O.id===x);k?.experimentId&&k?.datasetId&&l.mutate({datasetId:k.datasetId,experimentId:k.experimentId,resultId:k.id,tags:w}),n(O=>O.map(_=>_.id===x?{..._,tags:w}:_))},[t,l]),m=g.useCallback((x,w)=>{const k=t.find(O=>O.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(O=>O.map(_=>_.id===x?{..._,rating:w}:_))},[t,c]),v=g.useCallback((x,w)=>{const k=t.find(O=>O.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(O=>O.map(_=>_.id===x?{..._,comment:w}:_))},[t,c,l]),y=g.useCallback((x,w)=>{n(k=>k.map(O=>O.id===x?{...O,clusterId:w}:O))},[]),b=g.useCallback(()=>{n([]),s([]),i(null)},[]);return o.jsx(H5t.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 W5t(){const e=g.useContext(H5t);if(!e)throw new Error("useReviewQueue must be used within ReviewQueueProvider");return e}function VZr({isSupportedModel:e,threadSignalsEnabled:t,threadId:n,threadSignalsUnsupported:r}){return e&&t&&!!n&&!r}const Z5t=g.createContext(void 0);function G5t({children:e,approveToolcall:t,declineToolcall:n,approveToolcallGenerate:r,declineToolcallGenerate:s,approveNetworkToolcall:a,declineNetworkToolcall:i,isRunning:l,toolCallApprovals:c,networkToolCallApprovals:u}){return o.jsx(Z5t.Provider,{value:{approveToolcall:t,declineToolcall:n,approveToolcallGenerate:r,declineToolcallGenerate:s,approveNetworkToolcall:a,declineNetworkToolcall:i,isRunning:l,toolCallApprovals:c,networkToolCallApprovals:u},children:e})}function sNe(){const e=g.useContext(Z5t);if(!e)throw new Error("useToolCall must be used within a ToolCallProvider");return e}function HZr({children:e,agentId:t,initialMessages:n,threadId:r,refreshThreadList:s,settings:a,requestContext:i,modelVersion:l,agentVersionId:c,supportsMemory:u}){const{settings:d}=nW(),f=rNe()?.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 Ee=new WC;return Object.entries(i??{}).forEach(([et,dt])=>{Ee.set(et,dt)}),c&&Ee.set("agentVersionId",c),Ee},[c,i]),{messages:k,tasks:O,sendMessage:_,cancelRun:T,isRunning:E,isAwaitingToolApproval:N,setMessages:I,approveToolCall:A,declineToolCall:R,approveToolCallGenerate:L,declineToolCallGenerate:D,toolCallApprovals:B,approveNetworkToolCall:H,declineNetworkToolCall:q,networkToolCallApprovals:F}=E1e({agentId:t,threadId:r,initialMessages:n,requestContext:w,enableThreadSignals:x,onThreadSignalsUnsupported:()=>{y.current=!0,v(!0)}}),{refetch:V}=F5t(),M=Er(),G=Qe(),{data:z}=_S(t),P=z?.config?.observationalMemory,U=P===!0||typeof P=="object"&&P!==null&&(!("enabled"in P)||P.enabled!==!1),{setIsObservingFromStream:W,setIsReflectingFromStream:Y,signalObservationsUpdated:te,setStreamProgress:J,markCycleIdActivated:ee}=RG(),re=g.useCallback(Ee=>{Ee==="reflection"?Y(!0):W(!0)},[W,Y]),oe=g.useCallback(Ee=>{Ee.threadId&&Ee.threadId!==r||J({windows:Ee.windows,recordId:Ee.recordId,threadId:Ee.threadId,stepNumber:Ee.stepNumber,generationCount:Ee.generationCount})},[J,r]),X=g.useCallback(Ee=>{Ee==="reflection"?Y(!1):W(!1),te(),M.invalidateQueries({queryKey:["observational-memory",t]}),M.invalidateQueries({queryKey:["memory-status",t]}),M.refetchQueries({queryKey:fV(t,r)}),M.refetchQueries({queryKey:dV(r)}),M.refetchQueries({queryKey:Rxe(t,r)})},[t,M,W,Y,te,r]),ne=g.useCallback(Ee=>{const et=Ee?.cycleId;et&&ee(et)},[ee]),se=g.useCallback(()=>{W(!1),Y(!1),I(Ee=>sJe(Ee)),M.invalidateQueries({queryKey:["observational-memory",t]}),M.invalidateQueries({queryKey:["memory-status",t]}),M.refetchQueries({queryKey:fV(t,r)}),M.refetchQueries({queryKey:dV(r)}),M.refetchQueries({queryKey:Rxe(t,r)})},[t,M,W,Y,I,r]);g.useEffect(()=>{const{activatedCycleIds:Ee,lastProgress:et}=AZr(n||[]);for(const dt of Ee)ee(dt);et&&oe(et)},[oe,n,ee]),g.useEffect(()=>{if(!r||!IZr(n||[]))return;let Ee=!1;return G.awaitBufferStatus({agentId:t,resourceId:t,threadId:r}).then(et=>{Ee||I(dt=>M5t(dt,et?.record))}).catch(()=>{Ee||I(et=>sJe(et))}),()=>{Ee=!0}},[t,G,n,I,r]);const{frequencyPenalty:ce,presencePenalty:le,maxRetries:ye,maxSteps:he,maxTokens:xe,temperature:Ae,topK:De,topP:Me,seed:$e,chatWithGenerate:Re,chatWithNetwork:Le,chatWithLegacyStream:Te,providerOptions:je,requireToolApproval:ze}=b,_e={frequencyPenalty:ce,presencePenalty:le,maxRetries:ye,temperature:Ae,topK:De,topP:Me,seed:$e,maxTokens:xe,providerOptions:je,maxSteps:he,requireToolApproval:ze},{send:Fe,cancel:tt}=FZr({agentId:t,requestContext:i,agentVersionId:c,threadId:r,modelSettingsArgs:_e,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:oe,refreshObservationalMemory:X,handleActivation:ne,resetObservationalMemoryStreamState:se,signalTimelineRefresh:te}),Ge=l==="v2"||l==="v3",ge=g.useRef(new Map),Se=g.useMemo(()=>EZr(k,ge.current),[k]),de=g.useMemo(()=>[...k.filter(Ee=>Ee.content?.metadata?.status!=="error"),...h].map(Ee=>NZr(Ee,Se)),[k,h,Se]),Oe=E||N,be=VZr({isSupportedModel:Ge,threadSignalsEnabled:x&&(!Re&&!Le&&!Te),threadId:r,threadSignalsUnsupported:m}),ve=g.useMemo(()=>({messages:de}),[de]),ke=g.useMemo(()=>({isRunning:Oe,cancelRun:tt,canSendWhileStreaming:be}),[Oe,tt,be]),Pe=g.useMemo(()=>({send:Fe}),[Fe]),He=g.useMemo(()=>({tasks:O}),[O]),yt=g.useMemo(()=>({agentId:t,agentVersionId:c,requestContext:i}),[t,c,i]);return o.jsx(C5t.Provider,{value:yt,children:o.jsx(S5t.Provider,{value:ke,children:o.jsx(w5t.Provider,{value:ve,children:o.jsx(O5t.Provider,{value:He,children:o.jsx(k5t.Provider,{value:Pe,children:o.jsx(G5t,{approveToolcall:A,declineToolcall:R,approveToolcallGenerate:L,declineToolcallGenerate:D,approveNetworkToolcall:H,declineNetworkToolcall:q,isRunning:E,toolCallApprovals:B,networkToolCallApprovals:F,children:e})})})})})})}function Q5t({children:e}){const t=g.useRef(!1);return g.useEffect(()=>{t.current=!0},[]),o.jsx(eLt,{value:t,children:e})}function _ie({children:e,className:t}){const n=nLt();return o.jsx("div",{className:K(n,t),children:o.jsx(Q5t,{children:e})})}const lJe={start:!1,end:!1},cJe={currentAnchorId:void 0,visibleMessageIds:[]},WZr=8,ZZr=0,GZr=64,QZr=160,YZr=160,$G=g.createContext(null),Y5t=g.createContext(null),K5t=g.createContext(null),X5t=(e,t)=>{const n=g.useContext(e);if(!n)throw new Error(`${t} must be used within MessageScrollerProvider.`);return n},MG=e=>X5t($G,e),KZr=e=>X5t(Y5t,e),UT=.5,XZr=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}},J5t=e=>Math.max(0,e.scrollHeight-e.clientHeight),$xe=(e,t)=>{const n=e.getBoundingClientRect(),r=t.getBoundingClientRect();return n.top-r.top+t.scrollTop},uJe=({align:e,contentElement:t,element:n,scrollMargin:r,viewportElement:s})=>{const a=XZr(t),i=$xe(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},JZr=({contentElement:e,items:t,viewportElement:n})=>{const r=J5t(n),s=t.at(-1)?.[1].element;if(!s||!e)return r;const a=$xe(e,n)+e.getBoundingClientRect().height,i=Math.max(0,n.scrollHeight-a),l=$xe(s,n)+s.getBoundingClientRect().height;return Math.min(r,Math.max(0,l+i-n.clientHeight))},eGr=({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+UT&&(c=u);return c||(l.find(([u])=>s.has(u))?.[0]??e)},tGr=240,nGr=220,rGr="cubic-bezier(0.33, 1, 0.68, 1)";function dJe(e){if(typeof DOMMatrixReadOnly>"u")return 0;const{transform:t}=getComputedStyle(e);return!t||t==="none"?0:new DOMMatrixReadOnly(t).m42}const hV=new WeakMap;function fJe(e){hV.get(e)?.abort(),hV.delete(e),e.style.transition="",e.style.transform=""}function sGr(){return typeof window>"u"||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function aGr(e,t){if(!e||t<=0||sGr())return;const n=dJe(e)+t;if(n>tGr){fJe(e);return}e.style.transition="none",e.style.transform=`translateY(${n}px)`,e.offsetHeight,e.style.transition=`transform ${nGr}ms ${rGr}`,e.style.transform="translateY(0)",hV.get(e)?.abort();const r=new AbortController;hV.set(e,r);const s=a=>{a.target===e&&dJe(e)===0&&fJe(e)};e.addEventListener("transitionend",s,{signal:r.signal}),e.addEventListener("transitioncancel",s,{signal:r.signal})}const iGr=560,oGr=240,lGr=e=>1-(1-e)**5;function cGr(e,t,n){const s=typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches?0:iGr,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)*lGr(m),l=e.scrollTop,m===1&&Math.abs(l-h)<=UT)return d("arrived");if(p>=s+oGr)return d("expired");c=window.requestAnimationFrame(f)};return c=window.requestAnimationFrame(f),{cancel:()=>{u||(u=!0,window.cancelAnimationFrame(c))}}}const DG=(...e)=>t=>{e.forEach(n=>{if(n){if(typeof n=="function"){n(t);return}n.current=t}})},uGr=(e,t)=>e.start===t.start&&e.end===t.end,dGr=(e,t)=>e.currentAnchorId===t.currentAnchorId&&e.visibleMessageIds.length===t.visibleMessageIds.length&&e.visibleMessageIds.every((n,r)=>n===t.visibleMessageIds[r]),fGr=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}),EP=(e,t,n)=>{if(typeof e.scrollTo=="function"){e.scrollTo({top:t,behavior:n});return}e.scrollTop=t},TP=e=>{if(typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(e);return}window.setTimeout(e,0)};function hGr({autoScroll:e=!1,children:t,defaultScrollPosition:n="end",onReachStart:r,preserveScrollOnPrepend:s=!1,reachStartThreshold:a=QZr,scrollEdgeThreshold:i=WZr,scrollMargin:l=ZZr,scrollPreviousItemPeek:c=GZr}){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,O]=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 R=A.current,L=g.useRef(!1),[D,B]=g.useState(lJe),[H,q]=g.useState(cJe),F=g.useRef(!0),V=g.useRef(!0),M=g.useRef(null),G=g.useRef(null),z=g.useRef(0),P=g.useRef(!1),U=g.useRef(!1),W=g.useRef(null),Y=g.useRef(void 0),te=g.useRef(r);g.useEffect(()=>{te.current=r},[r]);const J=g.useCallback(_e=>{const Fe=[_e.start&&"start",_e.end&&"end"].filter(Boolean).join(" ");for(const tt of[y,x])tt&&(Fe?tt.setAttribute("data-scrollable",Fe):tt.removeAttribute("data-scrollable"));B(tt=>uGr(tt,_e)?tt:_e)},[y,x]),ee=g.useCallback(_e=>{q(Fe=>dGr(Fe,_e)?Fe:_e)},[]),re=g.useCallback(()=>(f.current??=fGr(Array.from(d.entries())),f.current),[d]),oe=g.useCallback(()=>x?JZr({contentElement:k,items:re(),viewportElement:x}):0,[k,re,x]),X=g.useCallback(_e=>{const Fe=d.get(_e);if(!(!Fe||!x))return Math.max(0,uJe({align:"start",contentElement:k,element:Fe.element,scrollMargin:l,viewportElement:x}))},[k,d,l,x]),ne=g.useCallback(_e=>{const Fe=X(_e);return Fe===void 0||!x?Fe:Math.min(Fe,J5t(x))},[X,x]),se=g.useCallback(()=>{G.current?.cancel(),G.current=null},[]),ce=g.useCallback(({fromScroll:_e=!1}={})=>{if(!x){F.current=!0,J(lJe);return}const{scrollTop:Fe}=x,tt=oe()-Fe,Ge=Fe<z.current;F.current=tt<YZr,M.current==="end"&&(Ge||F.current)&&(M.current=null),z.current=Fe,_e&&M.current===null&&(Ge||F.current)&&(V.current=F.current),J({start:Fe>i,end:tt>i&&!(e&&V.current)})},[e,oe,J,i,x]),le=g.useCallback(()=>re().filter(([,_e])=>_e.scrollAnchor).at(-1)?.[0],[re]),ye=g.useCallback(()=>{const _e=re(),Fe=le()??_e.at(-1)?.[0];if(_e.length===0){ee(cJe);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;_e.forEach(([de,Oe])=>{const Ne=Oe.element.getBoundingClientRect();Ne.bottom>Se&&Ne.top<tt.bottom&&Ge.add(de)})}else p.forEach(Se=>Ge.add(Se));const ge=_e.flatMap(([Se])=>Ge.has(Se)?[Se]:[]);ee({currentAnchorId:eGr({fallbackAnchorId:Fe,items:_e,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(),ye()},[ce,ye]),xe=g.useCallback(()=>{const _e=!!(x&&x.scrollHeight>x.clientHeight);if(ce({fromScroll:!0}),ye(),!!x&&(F.current&&_e&&(P.current=!0),!!P.current&&_e)){if(x.scrollTop>a){U.current=!1;return}U.current||te.current&&(U.current=!0,s&&(W.current={scrollHeight:x.scrollHeight,scrollTop:x.scrollTop}),te.current())}},[s,a,ce,ye,x]),Ae=g.useCallback((_e,{align:Fe="start",behavior:tt="auto",scrollMargin:Ge=l}={})=>{if(!x||!k?.contains(_e))return!1;const ge=Math.max(0,uJe({align:Fe,contentElement:k,element:_e,scrollMargin:Ge,viewportElement:x}));return Math.abs(x.scrollTop-ge)<=UT?(EP(x,ge,"auto"),he(),!0):(EP(x,ge,tt),TP(he),!0)},[k,l,he,x]),De=g.useCallback(({behavior:_e="auto"}={})=>x?(se(),M.current=null,EP(x,0,_e),TP(he),!0):!1,[se,he,x]),Me=g.useCallback(({behavior:_e="auto"}={})=>x?(se(),V.current=!0,M.current=_e==="smooth"?"end":null,EP(x,oe(),_e),he(),TP(he),!0):!1,[se,oe,he,x]),$e=g.useCallback((_e,Fe)=>{const tt=d.get(_e);return tt?Ae(tt.element,Fe):!1},[d,Ae]),Re=g.useCallback(()=>{const _e=M.current;if(!(_e!==null&&_e!=="end")&&e&&_.current&&V.current&&x){const tt=oe()-x.scrollTop;if(tt>UT){const Ge=_e==="end";EP(x,oe(),Ge?"smooth":"auto"),Ge||aGr(k,tt)}}he()},[e,k,oe,he,x]),Le=g.useCallback((_e,Fe,tt)=>(d.set(_e,{element:Fe,scrollAnchor:tt}),f.current=null,v(Ge=>Ge+1),()=>{d.get(_e)?.element===Fe&&(d.delete(_e),p.delete(_e),f.current=null,v(ge=>ge+1))}),[p,d]);g.useEffect(()=>{if(!k||!x||typeof IntersectionObserver>"u"){ye();return}const _e=new Map;for(const[tt,Ge]of d)_e.set(Ge.element,tt);const Fe=new IntersectionObserver(tt=>{for(const Ge of tt){const ge=_e.get(Ge.target);ge&&(Ge.isIntersecting?p.add(ge):p.delete(ge))}ye()},{root:x,rootMargin:`${-(l+c)}px 0px 0px 0px`,threshold:[0,.01,.5,1]});for(const[,tt]of d)Fe.observe(tt.element);return ye(),()=>Fe.disconnect()},[k,p,d,m,l,c,ye,x]),g.useEffect(()=>{if(!x||typeof ResizeObserver>"u")return;const _e=new ResizeObserver(he);return _e.observe(x),()=>_e.disconnect()},[he,x]),g.useLayoutEffect(()=>{ce(),ye()},[m,ce,ye]),g.useLayoutEffect(()=>{if(_.current||!x)return;if(d.size===0){T.current=!0;return}const _e=()=>{const tt=le();V.current=!1;let Ge=!1;if(n==="start"?Ge=De({behavior:"auto"}):n==="last-anchor"?Ge=tt?$e(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),R.add(Se.element));L.current=!0}};if(!T.current){_e();return}if(E.current)return;E.current=!0;let Fe=!1;return TP(()=>{TP(()=>{E.current=!1,!Fe&&!_.current&&_e()})}),()=>{Fe=!0,E.current=!1}},[n,le,re,d,m,Me,$e,De,R,I,x]),g.useLayoutEffect(()=>{const _e=le(),Fe=_e?d.get(_e):void 0,tt=L.current&&_e!==void 0&&Fe!==void 0&&!I.has(_e)&&!R.has(Fe.element);for(const[Ge,ge]of re())ge.scrollAnchor&&(I.add(Ge),R.add(ge.element));if(L.current=_.current,tt&&_e){e&&(V.current=!0),se();const Ge=x?X(_e):void 0;Ge===void 0||!x||Math.abs(Ge-x.scrollTop)<=UT?M.current=null:(M.current={anchorId:_e},G.current=cGr(x,()=>ne(_e),ge=>{G.current=null,M.current=null,ge==="interrupted"&&(V.current=F.current),he()})),he();return}!e||!_.current||!V.current||M.current!==null&&M.current!=="end"||x&&oe()-x.scrollTop<=UT||Me({behavior:M.current==="end"?"smooth":"auto"})},[X,e,se,oe,le,re,d,m,ne,Me,R,I,he,x]),g.useEffect(()=>()=>{se(),M.current=null},[se,x]),g.useLayoutEffect(()=>{const _e=Y.current,Fe=k?.querySelector('[data-slot="message-scroller-item"]')?.dataset.messageId;Y.current=Fe;const tt=W.current;if(W.current=null,!tt||!x||Fe===_e)return;U.current=!1;const Ge=x.scrollHeight-tt.scrollHeight;Ge>0&&(x.scrollTop=tt.scrollTop+Ge)},[k,m,x]);const Te=g.useMemo(()=>({notifyContentResize:Re,notifyScroll:xe,registerItem:Le,scrollToEnd:Me,scrollToMessage:$e,scrollToStart:De,setContentElement:O,setRootElement:b,setViewportElement:w,syncAfterScroll:he}),[Re,xe,Le,Me,$e,De,he]),je=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($G.Provider,{value:Te,children:o.jsx(Y5t.Provider,{value:je,children:o.jsx(K5t.Provider,{value:ze,children:t})})})}const e6t=g.forwardRef(({className:e,...t},n)=>{const{setRootElement:r}=MG("MessageScroller");return o.jsx("div",{ref:DG(r,n),"data-slot":"message-scroller",className:K("group/message-scroller relative flex size-full min-h-0 flex-col overflow-hidden",e),...t})});e6t.displayName="MessageScroller";const t6t=g.forwardRef(({className:e,onScroll:t,role:n,tabIndex:r,...s},a)=>{const{setViewportElement:i,notifyScroll:l}=MG("MessageScrollerViewport"),c=g.useMemo(()=>DG(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})});t6t.displayName="MessageScrollerViewport";const n6t=g.forwardRef(({children:e,className:t,spacerClassName:n,role:r,"aria-relevant":s="additions",...a},i)=>{const{setContentElement:l,notifyContentResize:c,syncAfterScroll:u}=MG("MessageScrollerContent"),[d,f]=g.useState(null),h=g.useMemo(()=>DG(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})]})});n6t.displayName="MessageScrollerContent";const r6t=g.forwardRef(({className:e,messageId:t,scrollAnchor:n=!1,...r},s)=>{const a=g.useContext($G)?.registerItem,i=g.useRef(void 0),l=g.useCallback(c=>{i.current?.(),i.current=void 0,DG(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})});r6t.displayName="MessageScrollerItem";const s6t=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}=MG("MessageScrollerButton"),{start:f,end:h}=KZr("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(FV,{className:"size-4","aria-hidden":!0}),o.jsx("span",{className:"sr-only",children:t==="end"?"Scroll to end":"Scroll to start"})]})})});s6t.displayName="MessageScrollerButton";function pGr({className:e,scroller:t,...n}){return o.jsx(hGr,{...t,children:o.jsx("div",{"data-slot":"chat-shell",className:K("@container relative isolate flex min-h-0 min-w-0 flex-col bg-(--chat-surface)","[--chat-column:48rem] [--chat-fade:1.5rem] [--chat-gutter:0.75rem] [--chat-inset-end:0px]","[--chat-surface:var(--color-surface2)] [--chat-veil:70%]",e),...n})})}function mGr({className:e,...t}){return o.jsx("div",{"data-slot":"chat-shell-bar",className:K("min-w-0 shrink-0",e),...t})}function gGr({className:e,...t}){return o.jsx(e6t,{className:K("h-auto min-h-0 flex-1",e),...t})}function vGr({className:e,children:t,...n}){return o.jsx(t6t,{className:K("h-auto min-h-0 flex-1 pe-(--chat-inset-end)","transition-[padding] duration-360 ease-out-custom motion-reduce:transition-none",e),...n,children:o.jsx("div",{"data-slot":"chat-shell-track",className:"relative flex min-h-full min-w-0 flex-col",children:t})})}function yGr({className:e,...t}){return o.jsx(n6t,{className:K("flex-1",e),...t})}function a6t({className:e,...t}){return o.jsx("div",{"data-slot":"chat-shell-column",className:K("mx-auto flex w-full max-w-(--chat-column) min-w-0 flex-col px-3 md:px-5",e),...t})}function bGr({opensTurn:e,holdsRoom:t,restored:n,className:r,...s}){return o.jsx("div",{"data-slot":"chat-shell-turn","data-opens-turn":e?"true":void 0,"data-holds-room":t?"true":void 0,className:K("flex flex-col",e&&"min-h-0 transition-[min-height] duration-[1500ms] ease-[cubic-bezier(0.3,0,0.2,1)] motion-reduce:transition-none",t&&"min-h-[70cqh] duration-[440ms] ease-[cubic-bezier(0.2,0,0.2,1)] starting:min-h-0",t&&n&&"transition-none",r),...s})}function xGr({className:e,...t}){return o.jsx("div",{"data-slot":"chat-shell-dock",className:K("sticky bottom-0 z-10 mt-(--chat-fade) shrink-0 pb-(--chat-gutter)","before:pointer-events-none before:absolute before:inset-x-0 before:-top-(--chat-fade) before:bottom-0 before:-z-10","before:bg-(--chat-surface) before:[mask-image:linear-gradient(to_bottom,transparent,rgb(0_0_0/var(--chat-veil))_calc(var(--chat-fade)*3))]",e),...t})}function wGr({className:e,...t}){return o.jsx("div",{"data-slot":"chat-shell-scroll-button",className:"pointer-events-none absolute inset-x-0 bottom-[calc(100%+0.5rem)] flex",children:o.jsx(a6t,{className:"flex-row justify-center",children:o.jsx(s6t,{className:K("pointer-events-auto static translate-x-0 rtl:translate-x-0",e),...t})})})}const Ib=Object.assign(pGr,{Bar:mGr,Column:a6t,Content:yGr,Dock:xGr,ScrollButton:wGr,Stage:gGr,Turn:bGr,Viewport:vGr});function SGr(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 i6t=g.forwardRef(({children:e,...t},n)=>o.jsx("form",{ref:n,"data-slot":"composer",...t,children:e}));i6t.displayName="Composer";const o6t=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(kGr,{pulseKey:n}),o.jsx("div",{className:"relative z-10",children:e})]}));o6t.displayName="ComposerBox";const l6t=({busy:e=!1,className:t,...n})=>{const r=SGr(!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})};l6t.displayName="ComposerRing";const c6t=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}));c6t.displayName="ComposerAttachments";const u6t=g.forwardRef(({className:e,maxHeight:t="212px",...n},r)=>o.jsx(Sr,{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})}));u6t.displayName="ComposerInput";const d6t=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}));d6t.displayName="ComposerActions";const Eie=({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"})]}),kGr=({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(Eie,{}),o.jsx(Eie,{className:"-translate-y-2"}),o.jsx(Eie,{})]},e),OGr=()=>{const e=g.useContext($G);return g.useMemo(()=>{if(e)return{scrollToEnd:e.scrollToEnd,scrollToMessage:e.scrollToMessage,scrollToStart:e.scrollToStart}},[e])},CGr=()=>{const e=g.useContext(K5t);return g.useMemo(()=>e?{currentAnchorId:e.currentAnchorId,visibleMessageIds:e.visibleMessageIds}:void 0,[e])},LG=typeof window>"u"?g.useEffect:g.useLayoutEffect,_Gr=e=>{const t=e.getBoundingClientRect().height,n=t>0?t:e.scrollHeight;return Math.ceil(n)};function Mxe(){const[e,t]=g.useState(null),[n,r]=g.useState(null),s=g.useRef(null),a=g.useCallback(()=>{if(!e)return null;const l=_Gr(e);return r(c=>c===l?c:l),l},[e]);LG(()=>{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 EGr=360,hJe=EGr+80,pJe={currentTurn:void 0,previousTurn:void 0,index:null,phase:"hidden",top:0,transitionKey:0};function f6t({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(pJe),h=OGr(),p=CGr(),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]),O=(T,E)=>{const N=c.current?.getBoundingClientRect().top??0,I=E.getBoundingClientRect(),A=e[T];A&&f(R=>{const L=I.top+I.height/2-N;if(R.index===T&&R.phase!=="hidden"&&R.phase!=="exiting")return{...R,top:L};const D=R.currentTurn&&R.currentTurn.key!==A.key&&R.phase!=="hidden"?R.currentTurn:void 0;return{currentTurn:A,previousTurn:D,index:T,phase:"entering",top:L,transitionKey:R.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)},hJe);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?pJe:E)},hJe);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(Sr,{"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),R=w===E;return o.jsx(NGr,{turn:T,index:E,distance:N,active:I,inView:A,previewId:R?u:void 0,onHoverChange:O,onSelect:k},T.key)})})}),d.currentTurn&&o.jsx(IGr,{id:u,currentTurn:d.currentTurn,previousTurn:d.previousTurn,phase:d.phase,top:d.top})]})}const TGr=e=>e===0?"w-4":e===1?"w-3":"w-2",jGr=({distance:e,active:t,inView:n})=>e===0||t?"bg-neutral6":n?"bg-neutral5":e===1?"bg-neutral4":"bg-neutral3/60";function NGr({turn:e,index:t,distance:n,active:r,inView:s,previewId:a,onHoverChange:i,onSelect:l}){const c=TGr(n),u=jGr({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 IGr({id:e,currentTurn:t,previousTurn:n,phase:r,top:s}){const{ref:a,heightStyle:i,measure:l}=Mxe(),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(Tie,{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(Tie,{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(Tie,{turn:t,className:"p-3.5"})},t.key)]})})]})}function Tie({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(Dl,{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 mJe=120,AGr=2,RGr="clientMessageId",FG=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Dxe=e=>{const t=e.content.metadata,n=FG(t)?t[RGr]:void 0;return typeof n=="string"&&n.length>0?n:e.id},h6t=(e,t)=>{const n=e.replace(/\s+/g," ").trim();return n.length===0?t:n.length<=mJe?n:`${n.slice(0,mJe-3).trimEnd()}...`},p6t=e=>e.content.parts.flatMap(t=>!FG(t)||t.type!=="text"||typeof t.text!="string"?[]:[t.text]).join(`
520
520
  `),D9=(e,t)=>{for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim().length>0)return r}},PGr=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}},$Gr=e=>{const t=D9(e,["mimeType","mediaType"])??"";return e.type==="image"||t.startsWith("image/")?"Image":t==="application/pdf"?"PDF":t.startsWith("video/")?"Video":t.startsWith("audio/")?"Audio":"File"},MGr=e=>{if(!FG(e))return;const t=D9(e,["type"]);if(t!=="file"&&t!=="image")return;const n=D9(e,["filename","name"]);if(n)return n;const r=D9(e,["url","image","data"]);return(r?PGr(r):void 0)??$Gr(e)},DGr=e=>e.content.parts.map(MGr).filter(t=>!!t),LGr=e=>{const t=e.content.metadata?.signal,n=FG(t)?t.type:void 0;return typeof n=="string"?n:e.type},m6t=e=>{if(e.role==="user")return!0;if(e.role!=="signal")return!1;const t=LGr(e);return t==="user"||t==="user-message"},FGr=(e,t)=>{for(let n=t+1;n<e.length;n+=1){const r=e[n];if(!r)continue;if(m6t(r))return;if(r.role!=="assistant")continue;const s=h6t(p6t(r),"");if(s)return s}},g6t=e=>e.flatMap((t,n)=>{if(!m6t(t))return[];const r=DGr(t),s=r.slice(0,AGr);return[{key:Dxe(t),messageId:t.id,prompt:h6t(p6t(t),r.length>0?"Attached file":"User message"),reply:FGr(e,n),files:s,hiddenFileCount:r.length-s.length}]}),zGr=()=>!1;function BGr(e,{key:t,opensTurn:n,introduces:r=zGr}){const s=[];for(const a of e){const i=n(a),l=s.at(-1);if(!i&&l){l.entries.push(a);continue}const c=l?.entries.at(-1),u=l&&c!==void 0&&r(c)?l.entries.splice(-1):[];l?.entries.length===0&&s.pop(),s.push({key:t(a),entries:[...u,a],opensTurn:i})}return s}const UGr=(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)},gJe={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"},v6t=["https://","http://"],aNe=["gs://","s3://"],qGr=[...v6t,...aNe],VGr=e=>qGr.some(t=>e.startsWith(t)),y6t=e=>v6t.some(t=>e.startsWith(t)),HGr=e=>aNe.some(t=>e.startsWith(t)),vJe=e=>{try{const{pathname:t}=new URL(e),n=t.split(".").pop();return n?gJe[n.toLowerCase()]:void 0}catch{const t=e.split(".").pop()?.split(/[?#]/)[0];return t?gJe[t.toLowerCase()]:void 0}},WGr=async e=>{if(aNe.some(t=>e.startsWith(t)))return vJe(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 vJe(e)}},L9=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)}),b6t=g.createContext(null),ZGr=e=>e.startsWith("image/")?"image":e==="application/pdf"?"pdf":e.startsWith("video/")||e.startsWith("audio/")?"video":"text";let GGr=0;const QGr=()=>`att-${Date.now()}-${++GGr}`,YGr=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)}),yJe=e=>{const t=VGr(e.name),n=e.type||"text/plain";return{id:QGr(),file:e,name:e.name,contentType:n,kind:ZGr(n),isUrl:t}},KGr=async e=>e.kind==="image"?{role:"user",content:[{type:"image",image:e.isUrl?e.name:await L9(e.file),mimeType:e.contentType}]}:e.kind==="pdf"?{role:"user",content:[{type:"file",data:e.isUrl?e.name:await L9(e.file),mimeType:e.contentType,filename:e.name}]}:e.kind==="video"?{role:"user",content:[{type:"file",data:e.isUrl?e.name:await L9(e.file),mimeType:e.contentType,filename:e.name}]}:{role:"user",content:await YGr(e.file)},XGr=({children:e})=>{const[t,n]=g.useState([]),r=g.useCallback(u=>{const d=Array.from(u);d.length!==0&&n(f=>[...f,...d.map(yJe)])},[]),s=g.useCallback(async u=>{const d=await WGr(u)??"application/octet-stream",f=new File([],u,{type:d});n(h=>[...h,yJe(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(KGr)),[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(b6t.Provider,{value:c,children:e})},zG=()=>{const e=g.useContext(b6t);if(!e)throw new Error("useComposerAttachments must be used within a ComposerAttachmentsProvider");return e},JGr=()=>{const[e,t]=g.useState(!1),{addFiles:n,addUrl:r}=zG(),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(Wf,{open:e,onOpenChange:t,children:[o.jsx(tf,{asChild:!0,children:o.jsx(ae,{variant:"default",size:"icon-md",type:"button",tooltip:"Add attachment",children:o.jsx(Ir,{className:"text-neutral3 hover:text-neutral6 h-5 w-5"})})}),o.jsxs(nf,{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(ae,{type:"submit",className:"h-8!",variant:"default",children:[o.jsx(Ke,{children:o.jsx(xut,{})}),"Add"]})]}),o.jsx("hr",{className:"border-border1 my-3"}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(me,{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(dut,{className:"size-8"}),o.jsx(me,{variant:"ui-lg",children:"Add a local file"})]})]})]})]})},eQr=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},qN="h-full w-full flex items-center justify-center",x6t=({data:e,url:t})=>{const[n,r]=g.useState(!1);return t?o.jsx("a",{href:t,className:qN,target:"_blank",rel:"noreferrer noopener",children:o.jsx(Dl,{className:"text-accent2","aria-label":"View PDF"})}):o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>r(!0),className:qN,type:"button",children:o.jsx(Dl,{className:"text-accent2","aria-label":"View PDF"})}),o.jsx(tQr,{data:e,open:n,onOpenChange:r})]})},tQr=({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(Ts,{children:"Preview of the PDF document"})]}),o.jsx(Nr,{children:t&&o.jsx("iframe",{src:e,width:"100%",height:"600px"})})]})}),nQr=e=>e?.startsWith("video/")?{Icon:HXt,label:"Video file"}:e?.startsWith("audio/")?{Icon:BXt,label:"Audio file"}:e?.startsWith("text/")||e==="application/pdf"?{Icon:Dl,label:"Document file"}:{Icon:HV,label:"File"},w6t=({name:e,url:t,contentType:n})=>{const{Icon:r,label:s}=nQr(n),a=o.jsx(r,{className:"text-accent2","aria-label":s});return t?o.jsx("a",{href:t,className:qN,target:"_blank",rel:"noreferrer noopener",title:e,children:a}):o.jsx("div",{className:qN,title:e,children:a})},S6t=({src:e})=>{const[t,n]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>n(!0),type:"button",className:qN,children:o.jsx("img",{src:e,className:"aspect-ratio max-h-[140px] max-w-[320px] object-cover",alt:"Preview"})}),o.jsx(rQr,{src:e,open:t,onOpenChange:n})]})},rQr=({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(Ts,{children:"Preview of the image"})]}),o.jsx(Nr,{children:t&&o.jsx("img",{src:e,alt:"Image"})})]})}),k6t=({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:qN,type:"button",children:o.jsx(Dl,{className:"text-neutral3"})}),o.jsx(sQr,{data:r,open:t,onOpenChange:n})]})},sQr=({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(Ts,{children:"Preview of the text file"})]}),o.jsx(Nr,{children:t&&o.jsx("div",{className:"whitespace-pre-wrap",children:e})})]})}),aQr=({file:e})=>{const{isLoading:t,text:n}=eQr(e);return o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:t?o.jsx(Ht,{}):o.jsx(k6t,{data:n})})},iQr=({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 L9(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(Ht,{}):o.jsx(x6t,{data:t.text,url:e.isUrl?e.name:void 0})})},oQr=({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(S6t,{src:t})},lQr=({attachment:e})=>{const{remove:t}=zG();return o.jsxs("div",{className:"relative",children:[o.jsx(Idt,{children:o.jsxs(bn,{children:[o.jsx(mn,{asChild:!0,children:o.jsx("div",{className:"bg-surface3 border-border1 size-16 overflow-hidden rounded-lg border",children:e.kind==="image"?o.jsx(oQr,{attachment:e}):e.kind==="pdf"?o.jsx(iQr,{attachment:e}):e.kind==="video"?o.jsx(w6t,{name:e.name,url:e.isUrl&&y6t(e.name)?e.name:void 0,contentType:e.contentType}):o.jsx(aQr,{file:e.file})})}),o.jsx(gn,{side:"top",children:e.name})]})}),o.jsx(ae,{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(Ke,{children:o.jsx(tr,{})})})]})},cQr=()=>{const{attachments:e}=zG();return e.length===0?null:o.jsx("div",{className:"flex flex-row items-center gap-4 overflow-x-auto px-3 pt-3 pb-1","data-testid":"composer-attachments",children:e.map(t=>o.jsx(lQr,{attachment:t},t.id))})},uQr=(e,t)=>{const n=Qe(),[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 Z_n(h.body,()=>i(!1));l.current=p??null;return}catch(f){i(!1),vu.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}},bJe=12;function dQr({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 O=fQr(f,m,x);O?k=O.getBoundingClientRect().bottom+bJe-d.top:k=0;const T=w.bottom+bJe-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(hQr,{highlight:u,visible:h},u.cycleId)})})}function fQr(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 hQr({highlight:e,visible:t}){const n=pQr(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 pQr(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 O6t=g.createContext(null);function mQr({children:e,...t}){return o.jsx(O6t.Provider,{value:t,children:e})}function BG(){return g.useContext(O6t)}function C6t({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}=Pm(),{addItem:h}=La(),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(Ts,{children:"Save as a dataset item for evaluation."})]}),o.jsxs(Nr,{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(da,{value:c,onValueChange:u,disabled:h.isPending||f,children:[o.jsx(ha,{id:"ds-target",children:o.jsx(fa,{placeholder:f?"Loading...":"Select a dataset"})}),o.jsx(pa,{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(Hr,{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(Hr,{value:i,onChange:l,showCopyButton:!1,className:"max-h-[160px] min-h-[80px]"})]})]}),o.jsxs(Fl,{className:"px-6",children:[o.jsx(ae,{variant:"default",size:"sm",onClick:()=>t(!1),children:"Cancel"}),o.jsxs(ae,{variant:"primary",size:"sm",onClick:m,disabled:h.isPending||!c||p.length===0,children:[o.jsx(Ke,{size:"sm",children:o.jsx(Qu,{})}),h.isPending?"Saving...":"Save Item"]})]})]})})}function gQr({messageText:e}){return BG()?.enabled?o.jsx(vQr,{messageText:e}):null}function vQr({messageText:e}){const t=BG(),[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(ae,{variant:"default",size:"icon-md",tooltip:"Save to dataset",className:"text-neutral3 hover:text-neutral6 bg-transparent",onClick:i,children:o.jsx(Lg,{className:"h-4 w-4"})}),o.jsx(C6t,{open:n,onOpenChange:r,input:s,onInputChange:a,requestContext:t?.requestContext})]})}function yQr(){return BG()?.enabled?o.jsx(bQr,{}):null}function bQr(){const e=BG(),t=Qe(),[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(Ht,{className:"h-3.5 w-3.5"}):o.jsx(Lg,{className:"h-3.5 w-3.5"}),"Save full conversation to dataset"]}),o.jsx(C6t,{open:n,onOpenChange:r,input:s,onInputChange:a,requestContext:e.requestContext,initialGroundTruth:i})]})}const _6t=`
@@ -670,7 +670,7 @@ Token usage: ${n} input + ${r} output = ${s} total`:`The model stopped generatin
670
670
  }
671
671
  ]`,nxs=[{name:"input",description:"What the agent receives. A string or any JSON value.",required:!0},{name:"groundTruth",description:"Expected answer used by scorers.",required:!1},{name:"metadata",description:"Any object, useful for filtering and grouping.",required:!1}];function rxs(){const{isCopied:e,handleCopy:t}=Wd({text:nnt,showToast:!1});return o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsx("p",{className:"text-ui-sm text-neutral5 flex h-8 items-center font-medium",children:"Each item looks like this"}),o.jsx("dl",{className:"border-border1 divide-border1 divide-y rounded-lg border",children:nxs.map(n=>o.jsxs("div",{className:"grid grid-cols-[7rem_1fr] gap-3 px-3 py-2.5",children:[o.jsx("dt",{className:"text-ui-xs text-neutral6 font-mono",children:n.name}),o.jsxs("dd",{className:"text-ui-xs text-neutral4 flex flex-col items-start gap-1.5",children:[o.jsx("span",{children:n.description}),n.required?o.jsx(mt,{variant:"green",size:"xs",children:"required"}):o.jsx(mt,{variant:"neutral",emphasis:"muted",size:"xs",children:"optional"})]})]},n.name))}),o.jsxs("div",{className:"border-border1 overflow-hidden rounded-lg border",children:[o.jsxs("div",{className:"border-border1 bg-surface3 flex items-center justify-between border-b py-1.5 pr-1.5 pl-3",children:[o.jsx("span",{className:"text-ui-xs text-neutral4 font-mono",children:"example.json"}),o.jsx(ae,{variant:"ghost",size:"xs",onClick:t,children:e?"Copied":"Copy"})]}),o.jsx(Hr,{variant:"embedded",language:"json",editable:!1,lineNumbers:!1,showCopyButton:!1,value:nnt,className:"p-3"})]}),o.jsxs(ae,{variant:"ghost",as:"a",href:txs,target:"_blank",rel:"noopener noreferrer",className:"self-start",children:["Datasets documentation ",o.jsx(Fs,{})]})]})}const aoe=10,sxs=`[
672
672
  { "input": "…", "groundTruth": "…" }
673
- ]`,rnt="flex min-h-0 flex-1 flex-col py-0";function axs({tab:e,onTabChange:t,file:n,onFileSelect:r,onReplace:s,pastedText:a,onPastedTextChange:i,validation:l,isImporting:c}){return o.jsxs(vc,{value:e,defaultTab:"upload",onValueChange:t,className:"flex h-full flex-col gap-3",children:[o.jsxs(gc,{variant:"pill",children:[o.jsx(zr,{value:"upload",children:"Upload file"}),o.jsx(zr,{value:"paste",children:"Paste JSON"})]}),o.jsx(vs,{value:"upload",className:rnt,children:n?o.jsx(cxs,{file:n,validation:l,onReplace:s,isImporting:c}):o.jsx(ixs,{onFileSelect:r,disabled:c})}),o.jsx(vs,{value:"paste",className:rnt,children:o.jsx(So,{"aria-label":"JSON items",className:"text-ui-sm min-h-[200px] flex-1 resize-none font-mono",placeholder:sxs,spellCheck:!1,value:a,onChange:u=>i(u.target.value),disabled:c})})]})}function ixs({onFileSelect:e,disabled:t}){const[n,r]=g.useState(!1),s=g.useCallback(c=>{const u=c.target.files?.[0];u&&e(u),c.target.value=""},[e]),a=g.useCallback(c=>{c.preventDefault(),c.stopPropagation(),r(!0)},[]),i=g.useCallback(c=>{c.preventDefault(),c.stopPropagation(),r(!1)},[]),l=g.useCallback(c=>{if(c.preventDefault(),c.stopPropagation(),r(!1),t)return;const u=c.dataTransfer.files?.[0];u&&e(u)},[t,e]);return o.jsxs("div",{"data-testid":"json-dropzone",onDragOver:a,onDragLeave:i,onDrop:l,className:K("border-border1 bg-surface3 relative flex flex-1 flex-col items-center justify-center gap-3 rounded-lg border border-dashed px-6 py-10 text-center transition-colors","hover:border-accent1/50 hover:bg-accent1/5",n&&"border-accent1/50 bg-accent1/5",t&&"cursor-wait opacity-60"),children:[o.jsx("input",{type:"file",accept:".json,application/json","aria-label":"Choose a JSON file",onChange:s,disabled:t,className:"absolute inset-0 cursor-pointer opacity-0"}),o.jsx("div",{className:"border-border1 bg-surface2 text-neutral4 flex size-9 items-center justify-center rounded-md border",children:o.jsx(h3,{className:"size-4"})}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("p",{className:"text-ui-md text-neutral6",children:"Drop a JSON file here"}),o.jsxs("p",{className:"text-ui-sm text-neutral4",children:["or ",o.jsx("span",{className:"underline",children:"choose a file"})," from your computer"]})]}),o.jsxs("p",{className:"text-ui-xs text-neutral3",children:[".json · an array of items · up to ",PRe]})]})}function oxs(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function lxs(e){return typeof e=="string"?e:JSON.stringify(e)??""}function cxs({file:e,validation:t,onReplace:n,isImporting:r}){const s="rows"in t?t.rows:[],a="total"in t?t.total:0,i=s.slice(0,aoe);return o.jsxs("div",{"data-testid":"json-file-card",className:"border-border1 rounded-lg border",children:[o.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[o.jsx(uI,{className:"text-neutral4 size-4 shrink-0"}),o.jsx("span",{className:"text-ui-sm text-neutral6 min-w-0 flex-1 truncate font-mono",children:e.name}),o.jsx("span",{className:"text-ui-xs text-neutral3 shrink-0",children:oxs(e.size)}),o.jsx(ae,{variant:"ghost",size:"xs",onClick:n,disabled:r,children:"Replace"})]}),i.map(l=>o.jsxs("div",{className:"border-border1 grid grid-cols-[2rem_1fr_auto] items-center gap-2 border-t px-3 py-1.5",children:[o.jsx("span",{className:"text-ui-xs text-neutral3",children:l.index}),o.jsx("span",{className:"text-ui-sm text-neutral5 truncate font-mono",children:lxs(l.input)}),l.hasInput?l.hasGroundTruth?null:o.jsx(mt,{variant:"yellow",size:"xs",children:"no groundTruth"}):o.jsx(mt,{variant:"red",size:"xs",children:"no input"})]},l.index)),a>aoe&&o.jsxs("div",{className:"border-border1 text-ui-xs text-neutral3 border-t px-3 py-1.5",children:["+ ",a-aoe," more"]})]})}const uxs=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)});function dxs({datasetId:e,datasetName:t,open:n,onOpenChange:r,onSuccess:s}){const[a,i]=g.useState("upload"),[l,c]=g.useState(null),[u,d]=g.useState(""),[f,h]=g.useState(null),[p,m]=g.useState(""),[v,y]=g.useState(!1),b=g.useRef(0),{batchInsertItems:x}=La(),w=a==="upload"?u:p,k=g.useMemo(()=>a==="upload"&&f?{status:"error",kind:"parse",message:f}:nbs(w),[a,f,w]),O=g.useCallback(async I=>{const A=++b.current;if(!I.name.toLowerCase().endsWith(".json")){h("Only .json files are supported");return}if(I.size>dWt){h(`File is larger than ${PRe}`);return}try{const R=await uxs(I);if(A!==b.current)return;c({name:I.name,size:I.size}),d(R),h(null)}catch{if(A!==b.current)return;h("Could not read the file")}},[]),_=g.useCallback(()=>{b.current++,c(null),d(""),h(null)},[]),T=g.useCallback(()=>{b.current++,i("upload"),c(null),d(""),h(null),m("")},[]),E=g.useCallback(()=>{v||(r(!1),setTimeout(T,150))},[v,r,T]),N=g.useCallback(async()=>{if(k.status==="ready"){y(!0);try{await x.mutateAsync({datasetId:e,items:k.items}),Ve.success(`Imported ${k.total} item${k.total!==1?"s":""}`),s?.(),r(!1),setTimeout(T,150)}catch(I){Ve.error(I instanceof Error?I.message:"Failed to import items")}finally{y(!1)}}},[k,x,e,s,r,T]);return o.jsx(pr,{open:n,onOpenChange:E,children:o.jsxs(mr,{className:"flex max-h-[90vh] w-[960px] max-w-[calc(100vw-2rem)] flex-col gap-0 p-0",children:[o.jsxs(gr,{className:"border-border1 border-b px-6 py-4",children:[o.jsx(ur,{children:"Import into dataset"}),o.jsxs(Ts,{className:"text-ui-sm text-neutral3 not-sr-only",children:["Add items to"," ",t?o.jsx("code",{className:"bg-surface3 text-ui-xs text-neutral6 rounded px-1 font-mono",children:t}):"this dataset"," ","from a JSON file or paste them directly."]})]}),o.jsx(Nr,{className:"max-h-none min-h-0 flex-1 overflow-y-auto p-0",children:o.jsxs("div",{className:"divide-border1 grid divide-y md:grid-cols-[1.15fr_1fr] md:divide-x md:divide-y-0",children:[o.jsx("div",{className:"flex min-h-[360px] flex-col p-6",children:o.jsx(axs,{tab:a,onTabChange:i,file:l,onFileSelect:O,onReplace:_,pastedText:p,onPastedTextChange:m,validation:k,isImporting:v})}),o.jsx("div",{className:"p-6",children:o.jsx(rxs,{})})]})}),o.jsxs(Fl,{className:"border-border1 items-center border-t px-6 py-3 sm:justify-between",children:[o.jsx(fxs,{validation:k}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(ae,{onClick:E,disabled:v,children:"Cancel"}),o.jsxs(ae,{variant:"primary",onClick:N,disabled:k.status!=="ready"||v,children:[v&&o.jsx(Ht,{}),k.status==="ready"?`Import ${k.total} item${k.total!==1?"s":""}`:"Import"]})]})]})]})})}function fxs({validation:e}){const t=K("size-1.5 shrink-0 rounded-full",e.status==="idle"&&"bg-neutral3",e.status==="ready"&&"bg-accent1",e.status==="error"&&"bg-accent2");let n;switch(e.status){case"idle":n="No items yet";break;case"ready":n=o.jsxs(o.Fragment,{children:[o.jsx("b",{className:"text-neutral6 font-medium",children:e.total})," item",e.total!==1?"s":""," ready",e.missingGroundTruthCount>0&&` · ${e.missingGroundTruthCount} without groundTruth`]});break;case"error":switch(e.kind){case"parse":n=`Not valid JSON — ${e.message}`;break;case"not-array":n="Top level must be an array of items";break;case"empty":n="The array has no items";break;case"too-large":n=`JSON is larger than ${PRe}`;break;case"missing-input":n=o.jsxs(o.Fragment,{children:[o.jsx("b",{className:"text-neutral6 font-medium",children:e.missingInputCount})," of ",e.total," item",e.total!==1?"s":""," ",e.missingInputCount!==1?"have":"has"," no"," ",o.jsx("code",{className:"font-mono",children:"input"})]});break}break}return o.jsxs("div",{role:"status",className:"text-ui-sm text-neutral4 flex min-w-0 items-center gap-2",children:[o.jsx("span",{className:t}),o.jsx("span",{className:"truncate",children:n})]})}function hxs(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 gWt({active:e,onPrevious:t,onNext:n,onClose:r}){g.useEffect(()=>{if(!e)return;const s=a=>{a.defaultPrevented||hxs(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 vWt=g.createContext(null);function pxs({datasetId:e,items:t,isLoadingItems:n,children:r}){const s=Br(),i=Qvt("/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]);gWt({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(vWt.Provider,{value:h,children:r})}function yWt(){const e=g.useContext(vWt);if(!e)throw new Error("useDatasetItemPanel must be used within a DatasetItemPanelProvider");return e}function mxs({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,leftSlot:r,rightSlot:s,belowToolbarSlot:a}){const[i,l]=Ta(),{activeVersion:c}=$Re(i,l),[u,d]=g.useState(!1),[f,h]=g.useState(!1),[p,m]=g.useState(!1),[v,y]=g.useState([]),[b,x]=g.useState(!1),[w,k]=g.useState([]),[O,_]=g.useState(!1),[T,E]=g.useState([]),[N,I]=g.useState(0),[A,R]=g.useState(""),[L]=lW(A,300),{data:D}=$m(e),{data:B=[],isLoading:H,setEndOfListElement:q,isFetchingNextPage:F,hasNextPage:V}=Yx(e,L||void 0,c),{deleteItems:M}=La(),{currentItemId:G,openItem:z,close:P}=yWt(),U=X=>{G===X?P():z(X)},W=X=>{y(X),m(!0)},Y=X=>{k(X),x(!0)},te=X=>{x(X),X||(k([]),I(ne=>ne+1))},J=X=>{E(X),_(!0)},ee=async()=>{await M.mutateAsync({datasetId:e,itemIds:T}),Ve.success(`Deleted ${T.length} items`),_(!1),E([]),I(X=>X+1)},re=X=>{m(!1),y([]),I(ne=>ne+1),n?.(X)},oe=X=>{m(X),X||(y([]),I(ne=>ne+1))};return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"grid h-full overflow-auto",children:o.jsx(exs,{items:B,leftSlot:r,rightSlot:s,belowToolbarSlot:a,isLoading:H,onItemClick:U,featuredItemId:G,onAddClick:t??(()=>{}),onImportClick:()=>d(!0),onImportJsonClick:()=>h(!0),onBulkDeleteClick:J,onCreateDatasetClick:W,onAddToDatasetClick:Y,datasetName:D?.name,clearSelectionTrigger:N,setEndOfListElement:q,isFetchingNextPage:F,hasNextPage:V,searchQuery:A,activeSearchQuery:L,onSearchChange:R,currentDatasetVersion:D?.version})}),o.jsx(Qbs,{datasetId:e,open:u,onOpenChange:d}),o.jsx(dxs,{datasetId:e,datasetName:D?.name,open:f,onOpenChange:h}),o.jsx(jbs,{open:p,onOpenChange:oe,items:v,onSuccess:re}),o.jsx(Nbs,{open:b,onOpenChange:te,items:w,currentDatasetId:e}),o.jsx(Tt,{open:O,onOpenChange:_,children:o.jsxs(Tt.Content,{children:[o.jsxs(Tt.Header,{children:[o.jsx(Tt.Title,{children:"Delete Items"}),o.jsxs(Tt.Description,{children:["Are you sure you want to delete ",T.length," item",T.length!==1?"s":"","? This action cannot be undone."]})]}),o.jsxs(Tt.Footer,{children:[o.jsx(Tt.Cancel,{children:"Cancel"}),o.jsx(Tt.Action,{onClick:ee,children:M.isPending?"Deleting...":"Delete"})]})]})})]})}const snt="__create_tag__";function gxs({datasetId:e}){const{data:t}=$m(e),{data:n}=Pm(),{updateDataset:r}=La(),[s,a]=g.useState(""),i=g.useMemo(()=>Array.isArray(t?.tags)?t.tags:[],[t?.tags]),l=g.useMemo(()=>fWt(n?.datasets??[]),[n?.datasets]),c=g.useMemo(()=>{const h=l.map(v=>({label:v,value:v,end:i.includes(v)?o.jsx(Dr,{"data-testid":"tag-applied",className:"size-3.5"}):void 0})),p=s.trim();return p.length>0&&!l.includes(p)&&!i.includes(p)?[{label:`Create "${p}"`,value:snt},...h]:h},[l,i,s]),u=h=>{r.mutate({datasetId:e,tags:h},{onError:()=>Ve.error("Failed to update tags")})},d=h=>{const p=h===snt?s.trim():h;!p||i.includes(p)||u([...i,p])},f=h=>{u(i.filter(p=>p!==h))};return o.jsxs("div",{"data-testid":"dataset-tags-editor",className:"flex flex-wrap items-center gap-2 px-4 py-2",children:[i.map(h=>o.jsxs(bA,{value:h,size:"md",className:"gap-1 pr-1",children:[h,o.jsx("button",{type:"button","aria-label":`Remove tag ${h}`,disabled:r.isPending,onClick:()=>f(h),className:"cursor-pointer rounded-sm hover:opacity-70 disabled:opacity-50",children:o.jsx(tr,{className:"size-3"})})]},h)),o.jsx(zo,{options:c,value:void 0,onValueChange:d,onInputValueChange:a,placeholder:o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(hI,{className:"size-3.5"}),"Add tag"]}),searchPlaceholder:"Search or create tag...",emptyText:"Type to create a tag",variant:"ghost",size:"xs",className:"w-auto min-w-0",disabled:r.isPending})]})}function bWt({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(zo,{multiple:!0,options:c,value:e,onValueChange:t,placeholder:"Select scorers...",searchPlaceholder:"Search scorers...",emptyText:"No scorers available",disabled:n||l,container:r})]})}function xWt({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(bl,{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(bWt,{selectedScorers:n,setSelectedScorers:r,disabled:s,label:"Item scorers",helperText:"Choose from scorers that can be resolved by this Mastra instance."}):null]})}function vxs(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 ioe({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 yxs({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}=La(),O=()=>{a("{}"),l(""),u(""),f(""),p(!1),v([]),b(""),w(null)},_=R=>{O(),n(R)},T=async R=>{R.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 F=JSON.parse(d);if(!Array.isArray(F)){Ve.error("Tool Mocks must be a JSON array");return}H=F}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(F){const V=vxs(F);V?w(V):Ve.error(`Failed to add item: ${F instanceof Error?F.message:"Unknown error"}`)}},E=R=>{a(R),x?.field==="input"&&w(null)},N=R=>{l(R),x?.field==="groundTruth"&&w(null)},I=R=>{f(R),x?.field==="toolMocks"&&w(null)},A=()=>{_(!1)};return o.jsxs(Oi,{dialogTitle:"Add Item",dialogDescription:"Create a new dataset item",isOpen:t,onClose:A,level:1,children:[o.jsx(Oi.Top,{children:"Add Item"}),o.jsxs(Oi.Content,{children:[o.jsx(Oi.Header,{children:o.jsx(Oi.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(Hr,{value:s,onChange:E,showCopyButton:!1,className:"min-h-[240px]"}),x?.field==="input"&&o.jsx(ioe,{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(Hr,{value:i,onChange:N,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="groundTruth"&&o.jsx(ioe,{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(Hr,{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(Hr,{value:d,onChange:I,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="toolMocks"&&o.jsx(ioe,{field:"toolMocks",errors:x.errors})]}),o.jsx(xWt,{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(Hr,{value:y,onChange:b,showCopyButton:!1,className:"min-h-[200px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ae,{type:"button",onClick:A,children:"Cancel"}),o.jsx(ae,{type:"submit",variant:"primary",disabled:k.isPending,children:k.isPending?"Adding...":"Add Item"})]})]})]})]})}function bxs({item:e}){return o.jsx(al,{withMargins:!1,children:o.jsxs(al.Column,{children:[o.jsxs(al.Title,{size:"smaller",children:[o.jsx(VV,{}),o.jsx("span",{className:"truncate",children:e.id}),o.jsx(_a,{content:e.id,tooltip:`Copy item ID: ${e.id}`})]}),o.jsxs(al.Description,{children:[o.jsxs(Rc,{children:[o.jsx(vKt,{})," Created ",dr(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")]}),e.datasetVersion!=null&&o.jsxs(Rc,{children:[o.jsx(d3,{})," Version v",e.datasetVersion]})]})]})})}const Sk=e=>JSON.stringify(e??null,null,2),xxs=[{key:"input",title:"Input",icon:o.jsx(u1,{}),value:e=>Sk(e.input)},{key:"groundTruth",title:"Ground Truth",icon:o.jsx(Rg,{}),value:e=>Sk(e.groundTruth)},{key:"expectedTrajectory",title:"Expected Trajectory",icon:o.jsx(jut,{}),value:e=>e.expectedTrajectory!=null?Sk(e.expectedTrajectory):void 0},{key:"toolMocks",title:"Tool Mocks",icon:o.jsx(Vd,{}),value:e=>Sk(e.toolMocks??[])},{key:"scorerIds",title:"Scorers",icon:o.jsx(V0e,{}),value:e=>e.scorerIds===void 0?"Inherited from dataset":Sk(e.scorerIds)},{key:"requestContext",title:"Request Context",icon:o.jsx(nc,{}),value:e=>e.requestContext!=null?Sk(e.requestContext):void 0},{key:"metadata",title:"Metadata",icon:o.jsx(hI,{}),value:e=>Sk(e.metadata)}];function MV({item:e,diff:t}){return o.jsxs(o.Fragment,{children:[o.jsxs(Jn,{children:[o.jsx(Jn.Key,{children:"Dataset Id"}),o.jsx(Jn.ValueWithCopyBtn,{copyTooltip:"Copy Dataset Id to clipboard",copyValue:e.datasetId,children:e.datasetId}),o.jsx(Jn.Key,{children:"Version"}),o.jsxs(Jn.Value,{children:["v",e.datasetVersion]}),o.jsx(Jn.Key,{children:"Created"}),o.jsx(Jn.Value,{children:dr(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")}),o.jsx(Jn.Key,{children:"Updated"}),o.jsx(Jn.Value,{children:e.updatedAt&&new Date(e.updatedAt).getTime()!==new Date(e.createdAt).getTime()?dr(new Date(e.updatedAt),"MMM d, yyyy h:mm aaa"):"n/a"})]}),o.jsx("div",{className:"mt-3 grid gap-3",children:xxs.map(n=>{const r=n.value(e),s=t?n.value(t.against):void 0;return r===void 0&&s===void 0?null:o.jsx(fn.CodeSection,{title:n.title,icon:n.icon,codeStr:r??"",diff:t?{against:s??"",side:t.side}:void 0},n.key)})})]})}function ooe({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 wxs({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(Hr,{value:e,onChange:t,showCopyButton:!1,className:"min-h-[120px]"}),y?.field==="input"&&o.jsx(ooe,{field:"input",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Ground Truth (JSON, optional)"}),o.jsx(Hr,{value:n,onChange:r,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="groundTruth"&&o.jsx(ooe,{field:"groundTruth",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Expected Trajectory (JSON, optional)"}),o.jsx(Hr,{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(Hr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="toolMocks"&&o.jsx(ooe,{field:"toolMocks",errors:y.errors})]}),o.jsx(xWt,{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(Hr,{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(Hr,{value:s,onChange:a,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex gap-2 pt-4",children:[o.jsx(ae,{variant:"primary",onClick:b,disabled:w,children:w?"Saving...":"Save Changes"}),o.jsx(ae,{onClick:x,disabled:w,children:"Cancel"})]})]})]})}const Sxs={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)]"},kxs={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"},WT=({children:e,theme:t="dark",size:n="default",className:r})=>o.jsx("kbd",{className:K("inline-flex items-center justify-center border font-mono",kxs[n],Yr.transform,"active:scale-95 active:shadow-none",Sxs[t],r),children:e}),Oxs=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function Cxs({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:a,isLoading:i}=Um(),{data:l,isLoading:c}=Ky(),{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(zo,{options:Oxs,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(zo,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:h,container:s})]})]})}const _xs=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform);function Exs({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return bm(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(iL,{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 loe({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 yY({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??""),[O,_]=g.useState(s??""),[T,E]=g.useState(n??[]),[N,I]=g.useState({}),[A,R]=g.useState(""),{triggerExperiment:L}=La(),{data:D}=$m(v),{total:B}=Yx(v,void 0,b),H=D?.requestContextSchema,q=!!(H&&Object.keys(H).length>0),F=!!(v&&w&&O&&f.trim()),V=L.isPending,M=[!f.trim()&&"name",!v&&"dataset",!O&&"target"].filter(Boolean),G=q?Object.values(N).some(J=>J!==void 0&&J!==""):A.trim().length>0,z=J=>{y(J),x(null),I({})},P=()=>{h(a??""),m(i??""),y(e??""),x(t??null),k(r??""),_(s??""),E(n??[]),I({}),R("")},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}},W=async()=>{if(!v||!w||!O||!f.trim())return;let J;try{J=U()}catch(ee){const re=ee instanceof Error?ee.message:"Request Context must be valid JSON";vu.error(re);return}try{const ee=await L.mutateAsync({datasetId:v,name:f.trim(),description:p.trim()||void 0,targetType:w,targetId:O,scorerIds:T.length>0?T:void 0,version:b??void 0,requestContext:J});vu.success("Experiment triggered successfully"),c(!1),u?.(ee.experimentId),P()}catch(ee){const re=ee instanceof Error?ee.message:"Failed to trigger experiment";vu.error(re)}},Y=()=>{V||(c(!1),P())},te=J=>{(J.metaKey||J.ctrlKey)&&J.key==="Enter"&&F&&!V&&(J.preventDefault(),W())};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(Ts,{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(Nr,{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(So,{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(loe,{index:1,title:"Dataset",done:!!v,children:[o.jsxs("div",{className:"grid grid-cols-[1fr_140px] gap-3",children:[o.jsx(Mbs,{value:v,onValueChange:z,container:d}),v&&o.jsx(pWt,{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(loe,{index:2,title:"Target",done:!!O,children:[o.jsx(Cxs,{targetType:w,setTargetType:k,targetId:O,setTargetId:_,container:d}),w&&!O&&o.jsxs("p",{className:"text-ui-xs text-neutral3",children:["Choose ",w==="agent"?"an":"a"," ",w," to run"]})]}),o.jsx(loe,{index:3,title:"Scorers (Optional)",done:T.length>0,isLast:!0,children:o.jsx(bWt,{label:"",selectedScorers:T,setSelectedScorers:E,disabled:V,container:d,helperText:"Scores are computed after each item runs."})})]}),o.jsxs(cc,{children:[o.jsxs(Bl,{className:"text-ui-sm flex items-center gap-2",children:[o.jsx(Fr,{className:"size-4"}),"Request Context (JSON, optional)",G&&o.jsx(mt,{size:"xs",variant:"blue",children:"set"})]}),o.jsx(Ul,{className:"pt-3",children:q?o.jsx(Exs,{requestContextSchema:H,onChange:I}):o.jsx(Hr,{value:A,onChange:R,showCopyButton:!1,"aria-label":"Request context JSON",className:"min-h-[160px]"})})]})]}),o.jsxs(Fl,{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(mt,{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(mt,{variant:"neutral",indicator:"dot",children:["Missing ",M.join(", ")]})}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ae,{onClick:Y,disabled:V,children:"Cancel"}),o.jsx(ae,{variant:"primary",onClick:W,disabled:!F||V,children:V?o.jsxs(o.Fragment,{children:[o.jsx(Ht,{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(WT,{size:"xs",children:_xs?"⌘":"Ctrl"}),o.jsx(WT,{size:"xs",children:"↵"})]})]})})]})]})]})})}const wWt=g.createContext(null);function Txs({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:a,children:i}){const l=Br(),u=Qvt("/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(RTe(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]);gWt({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(wWt.Provider,{value:y,children:i})}function SWt(){const e=g.useContext(wWt);if(!e)throw new Error("useExperimentItemPanel must be used within an ExperimentItemPanelProvider");return e}function jxs({datasetId:e,experimentId:t}){const[n,r]=g.useState(!1),{updateExperimentResult:s}=La();return{addTag:g.useCallback(async(i,l)=>{const c=l.filter(d=>!(d.tags??[]).includes(i));if(n||c.length===0)return;r(!0);let u=0;try{u=(await Promise.allSettled(c.map(f=>s.mutateAsync({datasetId:e,experimentId:t,resultId:f.id,tags:[...f.tags??[],i]})))).filter(f=>f.status==="fulfilled").length}finally{r(!1)}u>0?Ve(`Tag "${i}" added to ${u} result${u>1?"s":""}`):Ve.error("Failed to add tag")},[e,t,n,s]),isPending:n}}function kWt(e,t){const{data:n}=$m(e);return g.useMemo(()=>[...new Set([...n?.tags??[],...t.flatMap(r=>r.tags??[])])].sort(),[n?.tags,t])}const EA=e=>o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 8.94379 8.92126",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{d:"M6.13251 5.43413C6.51629 5.43413 6.82744 5.74533 6.82748 6.1291C6.82748 6.5129 6.51631 6.82407 6.13251 6.82407C5.74877 6.824 5.43754 6.51286 5.43754 6.1291C5.43759 5.74537 5.74879 5.4342 6.13251 5.43413Z",fill:"currentColor"}),o.jsx("path",{d:"M5.92771 2.29722C6.13122 2.09376 6.46147 2.09379 6.665 2.29722C6.86843 2.50075 6.86846 2.831 6.665 3.03451L3.03724 6.66227C2.83373 6.86578 2.5035 6.86572 2.29995 6.66227C2.0965 6.45872 2.09644 6.12849 2.29995 5.92498L5.92771 2.29722Z",fill:"currentColor"}),o.jsx("path",{d:"M2.842 2.12791C3.22572 2.12799 3.53694 2.43914 3.53696 2.82288C3.53696 3.20664 3.22573 3.51777 2.842 3.51785C2.45819 3.51785 2.14703 3.20668 2.14703 2.82288C2.14705 2.4391 2.45821 2.12791 2.842 2.12791Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.38455 0.00887484C8.26052 0.0979278 8.94379 0.837945 8.94379 1.73742V7.18384C8.94369 8.08322 8.26046 8.82334 7.38455 8.91238L7.20705 8.92126H1.73742L1.55992 8.91238C0.683828 8.82351 0.000101213 8.08336 0 7.18384V1.73742C0 0.837813 0.683761 0.0977507 1.55992 0.00887484L1.73742 0H7.20705L7.38455 0.00887484ZM1.73742 0.839013C1.24121 0.839013 0.839013 1.24121 0.839013 1.73742V7.18384C0.839121 7.67996 1.24128 8.08293 1.73742 8.08293H7.20705C7.70305 8.08276 8.10535 7.67985 8.10546 7.18384V1.73742C8.10546 1.24131 7.70312 0.83918 7.20705 0.839013H1.73742Z",fill:"currentColor"})]});function Nxs({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}=un(),m=!!(d&&f),v=[m?"2rem":"",...s.map(O=>O.size)].filter(Boolean).join(" "),y=s.some(O=>O.name==="input"),b=s.some(O=>O.name==="tags"),{containerRef:x,getRowProps:w}=no({count:e.length}),k=O=>i?.includes(O.name)?o.jsx(fe.TopCell,{children:o.jsxs(h,{href:p.scorerLink(O.name),className:"flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[o.jsx(EA,{}),o.jsx("span",{className:"min-w-0 truncate",children:O.label})]})},O.name):o.jsx(fe.TopCell,{children:O.label},O.name);return t?o.jsx(Lo,{columns:v}):o.jsxs(fe,{columns:v,className:"min-w-0",scrollRef:x,children:[o.jsxs(fe.Top,{hasLeadingCell:m,children:[m&&o.jsx(fe.TopCell,{children:" "}),m?o.jsx(fe.TopCells,{colStart:2,children:s.map(k)}):s.map(k)]}),e.length===0?o.jsx(fe.NoMatch,{message:"No results yet"}):o.jsxs(o.Fragment,{children:[e.map((O,_)=>{const T=!!O.error,E=O.id===n,N=o.jsxs(o.Fragment,{children:[o.jsxs(fe.Cell,{className:"text-ui-smd text-neutral3 flex items-center gap-1.5 tracking-wide",children:[o.jsx("span",{children:O.itemId?.slice(0,8)??""}),T&&o.jsxs(bn,{children:[o.jsx(mn,{render:o.jsx(_O,{role:"img","aria-label":"Error",className:"text-error size-3.5"})}),o.jsx(gn,{children:O.error?.message||"Error"})]})]}),y&&o.jsx(fe.TextCell,{font:"mono",children:Axs(Ixs(O.input),200)}),b&&o.jsx(fe.Cell,{className:"flex items-center gap-1 overflow-hidden","data-testid":`result-tags-${O.id}`,children:O.tags?.map(I=>o.jsx(bA,{value:I,className:"shrink-0"},I))}),i?.map(I=>{const R=a?.[O.itemId]?.find(L=>L.scorerId===I);return o.jsx(fe.Cell,{className:"text-neutral3 text-ui-smd font-mono",children:R!=null?R.score.toFixed(3):"-"},I)})]});return m?o.jsxs(fe.RowWrapper,{children:[o.jsx(fe.SelectCell,{checked:d.has(O.id),onToggle:()=>f(O.id),"aria-label":`Select result ${O.itemId}`}),o.jsx(fe.RowButton,{colStart:2,featured:E,"data-selected":E||void 0,onClick:()=>r(O.id),...w(_),children:N})]},O.id):o.jsx(fe.RowButton,{featured:E,"data-selected":E||void 0,onClick:()=>r(O.id),...w(_),children:N},O.id)}),o.jsx(fe.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function Ixs(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Axs(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}const ant="__create_tag__";function OWt({selectedResults:e,vocabulary:t,onAddTag:n,disabled:r,appearance:s="toolbar"}){const[a,i]=g.useState(""),l=g.useMemo(()=>[...t].sort(),[t]),c=g.useMemo(()=>{if(e.length===0)return new Set;const[f,...h]=e;return new Set((f.tags??[]).filter(p=>h.every(m=>(m.tags??[]).includes(p))))},[e]),u=g.useMemo(()=>{const f=l.map(m=>({label:m,value:m,end:c.has(m)?o.jsx(Dr,{"data-testid":"tag-applied",className:"size-3.5"}):void 0})),h=a.trim();return h.length>0&&!l.includes(h)?[{label:`Create "${h}"`,value:ant},...f]:f},[l,c,a]),d=f=>{const h=f===ant?a.trim():f;!h||c.has(h)||n(h)};return o.jsx(zo,{"data-testid":"experiment-results-tag-picker",options:u,value:void 0,onValueChange:d,onInputValueChange:i,placeholder:o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(hI,{className:"size-3.5"}),"Add tag"]}),searchPlaceholder:"Search or create tag...",emptyText:"Type to create a tag",variant:s==="inline"?"ghost":"outline",size:s==="inline"?"xs":"sm",className:"w-auto min-w-0",disabled:r})}function Rxs({scoresByItemId:e,experimentStatus:t}){const{Link:n,paths:r}=un(),{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(fm,{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(bn,{children:[o.jsx(mn,{render:o.jsx(EA,{role:"img","aria-label":"Scorer"})}),o.jsx(gn,{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 Pxs({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoading:s,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l}){const{currentItemId:c,openItem:u,close:d}=SWt(),[f,h]=g.useState(new Set),[p,m]=g.useState(!1),{updateExperimentResult:v}=La(),{addTag:y,isPending:b}=jxs({datasetId:t,experimentId:e}),x=kWt(t,r),w=g.useMemo(()=>r.filter(R=>f.has(R.id)),[r,f]),k=g.useCallback(R=>{h(L=>{const D=new Set(L);return D.has(R)?D.delete(R):D.add(R),D})},[]),O=g.useCallback(()=>h(new Set),[]),_=g.useCallback(async R=>{if(p||R.length===0)return;m(!0);let L=0;const D=new Set;try{for(const B of R)try{await v.mutateAsync({datasetId:t,experimentId:e,resultId:B,status:"needs-review"}),L++,D.add(B)}catch{}}finally{m(!1)}D.size>0&&h(B=>{const H=new Set(B);for(const q of D)H.delete(q);return H}),L>0&&Ve(`${L} result${L>1?"s":""} flagged for review`)},[t,e,p,v]),T=g.useMemo(()=>c?r.find(R=>R.itemId===c)?.id??null:null,[r,c]),{data:E}=PC(e,n),N=g.useMemo(()=>{if(!E)return[];const R=new Set;for(const L of Object.values(E))for(const D of L)R.add(D.scorerId);return[...R].sort()},[E]),I=g.useCallback(R=>{const L=r.find(D=>D.id===R);L&&(L.itemId===c?d():u(L.itemId))},[r,c,d,u]),A=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"7rem"},{name:"input",label:"Input",size:"minmax(200px,1fr)"},{name:"tags",label:"Tags",size:"max-content"},...N.map(R=>({name:R,label:R,size:"12rem"}))],[N]);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(Rxs,{scoresByItemId:E,experimentStatus:n}),f.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(ae,{variant:"outline",size:"sm",disabled:p||b,onClick:()=>_([...f]),children:[o.jsx(Ke,{size:"sm",children:o.jsx(LC,{})}),"Flag ",f.size," to review"]}),o.jsx(OWt,{selectedResults:w,vocabulary:x,onAddTag:R=>y(R,w),disabled:b||p}),o.jsx(ae,{variant:"ghost",size:"sm",onClick:O,children:"Clear"})]}),o.jsx("div",{className:"min-h-0 overflow-y-auto",children:o.jsx(Nxs,{results:r,isLoading:s,featuredResultId:T,onResultClick:I,columns:A,scoresByItemId:E,scorerIds:N,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l,selectedIds:f,onToggleSelect:k})})]})}const int={pending:{icon:o.jsx(c1,{className:"text-warning1 size-4"}),label:"Pending"},running:{icon:o.jsx(Ht,{size:"sm"}),label:"Running"},completed:{icon:o.jsx(i3,{className:"text-neutral3 size-4"}),label:"Completed"},failed:{icon:o.jsx(TO,{className:"text-error size-4"}),label:"Failed"}};function $xs({status:e,className:t}){const n=int[e]??int.pending;return o.jsxs(bn,{children:[o.jsx(mn,{render:o.jsx("span",{tabIndex:0,className:K("flex shrink-0 items-center",t),children:n.icon})}),o.jsx(gn,{children:n.label})]})}const Mxs=e=>{const t=Qe();return gt({queryKey:["experiment-trace-light",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return t.getTraceLight(e)},select:oRe,enabled:!!e})};function Dxs(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 Lxs({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=YAe(e),a=(s??[]).map(i=>({value:String(i.version),label:`${Dxs(i.version,i.createdAt)}${i.isCurrent?" (current)":""}`}));return o.jsxs(el.Toolbar,{className:"grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4",children:[o.jsx("div",{}),o.jsx(Om,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:a,value:t??"",onValueChange:i=>r?.(i,n??"")}),o.jsx(Om,{label:"Version B",labelIsHidden:!0,name:"version-b",options:a,value:n??"",onValueChange:i=>r?.(t??"",i)}),o.jsx("div",{})]})}function CWt({children:e,className:t}){return o.jsx("div",{className:K("",t),children:e})}function Fxs({date:e,className:t,withTime:n=!1}){const r=e?M0t(new Date(e)):!1,s=e?J3(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 MRe(e){return!e||e.length===0?"":e?.map(t=>t.size).join(" ")}function zxs({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:MRe(e)},children:n})})}function Bxs({children:e,className:t}){return o.jsx("span",{className:K("py-3",t),children:e})}function Uxs({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 qxs({children:e}){return o.jsx("ul",{className:"grid content-start",children:e})}function Vxs({children:e}){const t=g.useRef(null);return o.jsx("div",{ref:t,className:K("overflow-y-auto"),children:e})}function Hxs({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 Wxs({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,G3.visible,n),children:e});return s==null?a:o.jsxs(bn,{children:[o.jsx(mn,{render:a}),o.jsx(gn,{children:s})]})}function Zxs({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(Pc,{}):o.jsx(_m,{})," ",t]}):e})}function Gxs({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 Qxs({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(uc,{}),"Previous"]}),t&&o.jsxs("button",{onClick:n,children:["Next",o.jsx(Bd,{})]})]})]})}function Yxs({children:e,className:t}){return o.jsx("div",{className:K("grid grid-rows-[auto_1fr] overflow-y-auto",t),children:e})}function Kxs({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:MRe(n)},children:t})}function Xxs({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,G3.visible,{"bg-surface4":t,"hover:bg-surface4":e&&!t&&!i},a),style:{gridTemplateColumns:MRe(s)},disabled:i,children:r});return l==null?d:o.jsxs(bn,{children:[o.jsx(mn,{render:d}),o.jsx(gn,{children:l})]})}function Jxs(e){return e.charAt(0).toUpperCase()+e.slice(1)}function e0s({status:e}){return e?o.jsxs(bn,{children:[o.jsx(mn,{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(gn,{children:Jxs(e)})]}):null}function t0s({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 ont={latest:"Latest version",deleted:"Deleted in this version"};function n0s({version:e,date:t,isLatest:n,isDeleted:r}){return o.jsxs(CWt,{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":ont.latest,children:o.jsx(mt,{variant:"blue",size:"sm",icon:o.jsx(c1,{})})}),r&&o.jsx("span",{className:"inline-flex",role:"img","aria-label":ont.deleted,children:o.jsx(mt,{variant:"red",size:"sm",icon:o.jsx(D0e,{})})})]})]})}const Ap=Object.assign(Yxs,{Header:zxs,HeaderCol:Bxs,Items:qxs,Scroller:Vxs,Row:Kxs,RowButton:Xxs,Message:Zxs,NextPageLoading:Gxs,Pagination:Qxs,Cell:CWt,TextCell:t0s,StatusCell:e0s,VersionCell:n0s,IdCell:Uxs,DateCell:Fxs,LinkCell:Wxs,LabelCell:Hxs}),r0s=[{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"}],Z9={added:{badgeVariant:"blue",borderColor:"border-blue-900",icon:o.jsx(Ir,{}),tooltip:"Added in this version"},changed:{badgeVariant:"yellow",borderColor:"border-yellow-900",icon:o.jsx(Wen,{}),tooltip:"Changed in this version"},same:{badgeVariant:"green",borderColor:"border-green-900",icon:o.jsx(put,{}),tooltip:"Same in both versions"}};function coe({red:e=!1,tooltip:t}){return o.jsxs(bn,{children:[o.jsx(mn,{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(D0e,{className:K("text-neutral3/40 w-5 h-5 ",{"text-red-900":e})})}),o.jsx(gn,{children:t})]})}function uoe({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}=Z9[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(mt,{variant:n,size:"xs",icon:r})})]})}function s0s(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function lnt({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return"added";if(t==="changed"&&n)return"changed"}function a0s({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:a}){const{Link:i}=un(),l=t>n;return o.jsx(Ap,{children:o.jsx(Ap.Scroller,{children:o.jsx(Ap.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=a.get(c),f=s0s(u,d),h=lnt({otherVersionExists:d!==void 0,status:f,isNewer:l}),p=lnt({otherVersionExists:u!==void 0,status:f,isNewer:!l});return o.jsxs(Ap.Row,{columns:r0s,children:[o.jsx(Ap.IdCell,{id:c,isShortened:!1}),f!=="same"?o.jsxs(o.Fragment,{children:[u?.datasetVersion?o.jsx(Ap.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:h?Z9[h].tooltip:void 0,children:o.jsx(uoe,{variant:h,version:u.datasetVersion})}):o.jsx(Ap.Cell,{className:"flex items-center justify-center",children:o.jsx(coe,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?o.jsx(Ap.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:p?Z9[p].tooltip:void 0,children:o.jsx(uoe,{variant:p,version:d.datasetVersion})}):o.jsx(Ap.Cell,{className:"flex items-center justify-center",children:o.jsx(coe,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):o.jsx(Ap.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",tooltip:Z9.same.tooltip,children:o.jsx(uoe,{variant:"same",version:d?.datasetVersion})}),f==="changed"?o.jsx(Ap.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}/versions?version=${u?.datasetVersion}&compare=${d?.datasetVersion}`,children:"Compare"}):o.jsx(Ap.Cell,{children:o.jsx(coe,{tooltip:"Comparing is available only for changed items"})})]},c)})})})})}function i0s(){const e=Br(),[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}=p$n(),{data:p,isLoading:m,error:v}=JH(),y=g.useMemo(()=>p?.experiments??[],[p?.experiments]),b=g.useMemo(()=>ubs(l),[l]),x=c||m,w=u||v,k=()=>{e("/datasets/new")};if(w&&rs(w))return o.jsx(Wn,{children:o.jsx(_s,{})});if(w&&is(w))return o.jsx(Wn,{children:o.jsx(ys,{resource:"datasets"})});if(w)return o.jsx(Wn,{children:o.jsx(Bs,{title:"Failed to load datasets",message:w.message})});if(l.length===0&&!x)return o.jsx(Wn,{children:o.jsx(dbs,{onCreateClick:k})});const O=r!=="all"||a!=="all"||t!=="",_=()=>{n(""),s("all"),i("all")};return o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(gbs,{search:t,onSearchChange:n,experimentFilter:r,onExperimentFilterChange:s,tagFilter:a,onTagFilterChange:i,tagOptions:b,onReset:_,hasActiveFilters:O,onCreateClick:k})}),o.jsx(lbs,{datasets:l,experiments:y,isLoading:x,search:t,experimentFilter:r,tagFilter:a,isFetchingNextPage:d,hasNextPage:f,setEndOfListElement:h})]})}function h8({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function o0s(){const{datasetId:e}=fr(),t=Br(),[n,r]=Ta(),{activeVersion:s,handleVersionChange:a}=$Re(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}=$m(e),{data:b=[],isLoading:x}=Yx(e,void 0,s),w=!x&&b.length===0;if(y)return null;if(v&&rs(v))return o.jsx(h8,{children:o.jsx(_s,{})});if(v&&is(v))return o.jsx(h8,{children:o.jsx(ys,{resource:"datasets"})});if(v&&m0(v)||!y&&!v&&!m)return o.jsx(h8,{children:o.jsx(yr,{iconSlot:o.jsx(Lg,{}),titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:o.jsxs(ae,{as:gi,to:"/datasets",children:[o.jsx(uc,{}),"Back to Datasets"]})})});if(v)return o.jsx(h8,{children:o.jsx(Bs,{title:"Failed to load dataset",message:v instanceof Error?v.message:"An unexpected error occurred. Please try again."})});const k=_=>{t(`/experiments/${_}`)},O=()=>{t("/datasets")};return o.jsxs(pxs,{datasetId:e,items:b,isLoadingItems:x,children:[o.jsxs("div",{className:"h-full",children:[o.jsx(Lt,{height:"full",className:"grid-rows-[1fr] p-0",children:o.jsx(Lt.MainArea,{children:o.jsx(mxs,{datasetId:e,onAddItemClick:()=>u(!0),belowToolbarSlot:o.jsx(gxs,{datasetId:e}),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(ps,{children:[o.jsxs(ae,{as:gi,to:`/experiments?dataset=${e}`,children:[o.jsx(mut,{}),"View experiments"]}),o.jsx(pWt,{datasetId:e,value:s,onValueChange:a,currentVersion:m?.version,className:"w-36"}),w?o.jsxs(bn,{children:[o.jsx(mn,{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(ae,{variant:"primary",children:[o.jsx(Fc,{}),"Run Experiment"]})})})}),o.jsx(gn,{children:"Add items to the dataset before running an experiment"})]}):o.jsxs(ae,{variant:"primary",onClick:()=>l(!0),children:[o.jsx(Fc,{}),"Run Experiment"]}),o.jsxs(at,{children:[o.jsx(at.Trigger,{asChild:!0,children:o.jsx(ae,{size:"lg","aria-label":"Dataset actions menu",children:o.jsx(cI,{})})}),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(Ud,{})," Duplicate Dataset"]}),o.jsxs(at.Item,{onSelect:()=>f(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(cl,{})," Delete Dataset"]})]})]})]})})})}),o.jsx(Ug,{})]}),o.jsx(yY,{initialDatasetId:e,initialDatasetVersion:s??void 0,open:i,onOpenChange:l,onSuccess:k},`${e}:${s??"latest"}`),o.jsx(yxs,{datasetId:e,open:c,onOpenChange:u}),m&&o.jsx(Ibs,{open:h,onOpenChange:p,sourceDatasetId:m.id,sourceDatasetName:m.name,sourceDatasetDescription:m.description,sourceDatasetTargetType:m.targetType}),m&&o.jsx($bs,{open:d,onOpenChange:f,datasetId:m.id,datasetName:m.name,onSuccess:O})]})}function doe({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function l0s(){const{datasetId:e}=fr(),t=Br(),{data:n,error:r,isLoading:s}=$m(e),a=()=>{t(`/datasets/${e}`)};return s?null:r&&rs(r)?o.jsx(doe,{children:o.jsx(_s,{})}):r&&is(r)?o.jsx(doe,{children:o.jsx(ys,{resource:"datasets"})}):r||!n?o.jsx(doe,{children:o.jsx(Bs,{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(al,{className:"mb-6 p-0",children:o.jsxs(al.Column,{children:[o.jsxs(al.Title,{children:[o.jsx(Lg,{})," Edit dataset"]}),o.jsx(al.Description,{children:n.name})]})}),o.jsx(Mc,{className:"p-6",children:o.jsx(Pbs,{dataset:{id:n.id,name:n.name,description:n.description||"",inputSchema:n.inputSchema,groundTruthSchema:n.groundTruthSchema,requestContextSchema:n.requestContextSchema},onSuccess:a,onCancel:a})})]})})]})}function bY({label:e,wide:t=!1,children:n}){return o.jsxs("div",{className:K("pointer-events-none absolute inset-0 z-50","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 p8=()=>{},c0s=new Set,u0s=[{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 d0s({datasetId:e,currentItemId:t,open:n,onOpenChange:r}){const{navigate:s,paths:a}=un(),[i,l]=g.useState(""),[c]=lW(i,300),{data:u,isLoading:d,setEndOfListElement:f,isFetchingNextPage:h,hasNextPage:p}=Yx(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(Ts,{children:"Pick an item to compare with the current one."})]}),o.jsxs(Nr,{className:"grid max-h-[70vh] min-h-[24rem] grid-rows-[auto_1fr] gap-3",children:[o.jsx(_C,{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(mWt,{items:m,isLoading:d,onItemClick:v,selectOnNavigate:!1,columns:u0s,searchQuery:c||" ",setEndOfListElement:f,isFetchingNextPage:h,hasNextPage:p,isSelectionActive:!1,selectedIds:c0s,onToggleSelection:p8,onSelectAll:p8,onClearSelection:p8,onAddClick:p8})})]})]})})}function f0s(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 h0s({datasetId:e,item:t,items:n,onItemChange:r,onClose:s}){const{Link:a}=un(),{updateItem:i,deleteItem:l}=La(),[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,O]=g.useState(t.scorerIds!==void 0),[_,T]=g.useState(t.scorerIds??[]),[E,N]=g.useState(""),[I,A]=g.useState(null),[R,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):""),O(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,F=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 W;if(h.trim())try{W=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 oe=JSON.parse(x);if(!Array.isArray(oe)){Ve.error("Tool Mocks must be a JSON array");return}J=oe}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 oe=await i.mutateAsync({datasetId:e,itemId:t.id,input:U,groundTruth:W,metadata:Y,expectedTrajectory:te,toolMocks:J,scorerIds:re,requestContext:ee});Ve.success("Item updated successfully"),O(oe.scorerIds!==void 0),T(oe.scorerIds??[]),u(!1),A(null)}catch(oe){const X=f0s(oe);X?A(X):Ve.error(`Failed to update item: ${oe instanceof Error?oe.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):""),O(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)},z=U=>{p(U),I?.field==="groundTruth"&&A(null)},P=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(fn,{children:[o.jsxs(fn.Header,{children:[o.jsxs(fn.Heading,{children:["Item ",o.jsxs("b",{children:["# ",t.id.length>12?`${t.id.slice(0,12)}…`:t.id]})]}),o.jsxs(ps,{className:"ml-auto shrink-0",children:[o.jsx(fn.NextPrevNav,{onPrevious:q,onNext:F,previousLabel:"Previous item",nextLabel:"Next item"}),!c&&o.jsxs(o.Fragment,{children:[o.jsx(ae,{as:a,href:`/datasets/${e}/items/${t.id}/versions?version=${t.datasetVersion}`,size:"md",tooltip:"Go to item versions history","aria-label":"Go to item versions history",children:o.jsx(d3,{})}),o.jsxs(at,{children:[o.jsx(at.Trigger,{asChild:!0,children:o.jsx(ae,{size:"md","aria-label":"Actions menu",children:o.jsx(cI,{})})}),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(S2,{}),"Compare with…"]}),o.jsxs(at.Item,{onSelect:()=>L(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(cl,{}),"Delete Item"]})]})]})]}),o.jsx(fn.CloseButton,{onClick:s,tooltip:"Close detail panel"})]})]}),o.jsx(fn.Content,{children:c?o.jsx(wxs,{inputValue:d,setInputValue:G,groundTruthValue:h,setGroundTruthValue:z,metadataValue:m,setMetadataValue:v,trajectoryValue:y,setTrajectoryValue:b,toolMocksValue:x,setToolMocksValue:w,scorerOverrideEnabled:k,setScorerOverrideEnabled:O,selectedScorerIds:_,setSelectedScorerIds:T,requestContextValue:E,setRequestContextValue:N,validationErrors:I,onSave:V,onCancel:M,isSaving:i.isPending}):o.jsx(MV,{item:t})})]}),o.jsx(d0s,{datasetId:e,currentItemId:t.id,open:D,onOpenChange:B}),o.jsx(Tt,{open:R,onOpenChange:L,children:o.jsxs(Tt.Content,{children:[o.jsxs(Tt.Header,{children:[o.jsx(Tt.Title,{children:"Delete Item"}),o.jsx(Tt.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),o.jsxs(Tt.Footer,{children:[o.jsx(Tt.Cancel,{children:"Cancel"}),o.jsx(Tt.Action,{onClick:P,children:l.isPending?"Deleting...":"Yes, Delete"})]})]})})]})}function p0s(){const{itemId:e}=fr(),{datasetId:t,items:n,isLoadingItems:r,openItem:s,close:a}=yWt(),i=g.useMemo(()=>n.find(d=>d.id===e)??null,[n,e]),{data:l,isLoading:c}=e3(i?"":t,!i&&e?e:""),u=i??l??null;return e?o.jsx(bY,{label:`Dataset item ${e}`,children:u?o.jsx("div",{className:"[&>section]:bg-surface3 flex h-full min-h-0 flex-col p-3 [&>section]:min-h-0 [&>section]:flex-1 [&>section]:rounded-lg [&>section]:shadow-lg",children:o.jsx(h0s,{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(Ht,{})})}):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(yr,{iconSlot:o.jsx(Lg,{}),titleSlot:"Item not found",descriptionSlot:`No loaded item "${e}".`,actionSlot:o.jsx(ae,{onClick:a,children:"Close"})})})})}):null}function cnt(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,expectedTrajectory:e.expectedTrajectory??null,toolMocks:e.toolMocks??null,scorerIds:e.scorerIds??null,requestContext:e.requestContext??null,metadata:e.metadata??null},null,2)}function m0s(){const{datasetId:e,itemId:t,secondItemId:n}=fr(),r=Br(),s=[t,n].filter(p=>!!p),{data:a,error:i}=$m(e??""),{Link:l,paths:c}=un(),[u,d]=g.useState(!1),{data:f}=e3(e??"",s[0]??""),{data:h}=e3(e??"",s[1]??"");return i&&rs(i)?o.jsx(ks,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(_s,{})})}):i&&is(i)?o.jsx(ks,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ys,{resource:"datasets"})})}):!e||s.length<2?o.jsx(ks,{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(ks,{children:[o.jsx(o0,{owner:"dataset-items-compare",children:o.jsxs(ae,{as:gi,to:`/datasets/${e}`,variant:"outline",children:[o.jsx(uc,{}),"Back to Dataset"]})}),o.jsxs(Lt,{height:"full",className:K({"grid-rows-[auto_auto_minmax(0,1fr)]":u}),children:[o.jsx(Lt.TopArea,{children:o.jsxs(al,{withMargins:!1,children:[o.jsxs(al.Column,{children:[o.jsxs(al.Title,{size:"smaller",children:[o.jsx(S2,{}),"Compare Dataset Items"]}),o.jsx(al.Description,{children:o.jsxs(Rc,{children:["Comparing ",s.length," items of"," ",o.jsx(gi,{to:`/datasets/${e}`,className:"text-info1 hover:underline",children:a?.name||e?.slice(0,8)})]})})]}),o.jsx(al.Column,{children:o.jsx(ps,{children:o.jsx(ae,{variant:"primary",onClick:()=>d(p=>!p),children:u?o.jsxs(o.Fragment,{children:[o.jsx(UV,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(yXt,{})," Diff View"]})})})})]})}),o.jsx(Ij,{className:"grid-cols-2 gap-6",children:s.map((p,m)=>o.jsx(g0s,{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]))}},p))}),u&&f&&h&&o.jsx("div",{className:"mt-6 min-h-0 overflow-y-auto",children:o.jsx(LVt,{codeA:cnt(f),codeB:cnt(h)})})]})]})}function g0s({datasetId:e,itemId:t,Link:n,idx:r,itemIds:s,onItemChange:a,showContent:i=!0}){const{data:l,isLoading:c}=e3(e,t),{data:u}=Yx(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(Mc,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[o.jsxs(wx,{className:"flex items-center gap-4",children:[o.jsxs(da,{name:`compare-item-${r}`,value:t,onValueChange:a,children:[o.jsx(ha,{"aria-label":"Item",className:"w-full",children:o.jsx(fa,{placeholder:"Select item"})}),o.jsx(pa,{children:f.map(h=>o.jsx(xr,{value:h.value,disabled:h.disabled,children:h.label},h.value))})]}),o.jsxs(ae,{as:n,to:`/datasets/${e}/items/${t}`,children:[o.jsx(d3,{}),"Versions"]})]}),i&&o.jsx(Dd,{className:"grid content-start gap-8 overflow-y-auto",children:c?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):l?o.jsxs(o.Fragment,{children:[o.jsx(bxs,{item:l}),o.jsx(MV,{item:l})]}):o.jsxs("div",{className:"text-neutral4 text-sm",children:["Item ",t.slice(0,8)," not found"]})})]})}function unt(e,t){return{id:e.id,datasetId:t,datasetVersion:e.datasetVersion,input:e.input,groundTruth:e.groundTruth,expectedTrajectory:e.expectedTrajectory,toolMocks:e.toolMocks,scorerIds:e.scorerIds,requestContext:e.requestContext,metadata:e.metadata,createdAt:e.createdAt,updatedAt:e.updatedAt}}function dnt(e,t){return e.map(n=>{const r=typeof n.updatedAt=="string"?new Date(n.updatedAt):n.updatedAt;return{value:String(n.datasetVersion),label:o.jsxs("span",{className:"flex w-full items-center gap-2",children:[o.jsxs("span",{children:[o.jsxs("b",{children:["v. ",n.datasetVersion]})," · ",dr(r,"MMM d, HH:mm")]}),n.isLatest?o.jsx(mt,{variant:"blue",size:"xs",className:"ml-auto",children:"Latest"}):null]}),disabled:t?.has(n.datasetVersion)??!1}})}function fnt(e){const t=Number(e);return e!=null&&Number.isFinite(t)&&t>0?t:null}function v0s(){const{datasetId:e,itemId:t}=fr(),[n,r]=Ta(),s=fnt(n.get("version")),a=fnt(n.get("compare")),i=n.get("view")==="diff",{data:l,error:c}=$m(e??""),{data:u,isLoading:d}=Hys(e??"",t??""),f=(s!=null?u?.find(_=>_.datasetVersion===s):void 0)??u?.[0],h=f?.datasetVersion??null,p=a!=null&&a!==h?a:null,{data:m,isLoading:v}=Wys(e??"",t??"",p??0,l?.version),y=(_,T)=>r(E=>{const N=new URLSearchParams(E);return T==null?N.delete(_):N.set(_,String(T)),N},{replace:!0});if(c&&rs(c))return o.jsx(ks,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(_s,{})})});if(c&&is(c))return o.jsx(ks,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ys,{resource:"datasets"})})});if(!e||!t)return o.jsx(ks,{children:o.jsx(by,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Item not found."})})})});const b=!!(f&&m),x=i&&b,w=f?unt(f,e):null,k=m?unt(m,e):null,O=(f?.datasetVersion??0)<(m?.datasetVersion??0);return o.jsxs(ks,{children:[o.jsx(o0,{owner:"dataset-item-versions",children:b&&o.jsx(ae,{variant:"outline",onClick:()=>y("view",i?null:"diff"),children:i?o.jsxs(o.Fragment,{children:[o.jsx(UV,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(fJt,{})," Diff View"]})})}),o.jsx(Lt,{height:"full",className:"grid-rows-[minmax(0,1fr)]",children:o.jsxs("div",{className:"grid min-h-0 grid-cols-1 gap-6 md:grid-cols-2",children:[o.jsxs(Mc,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[o.jsx(wx,{children:o.jsx(hnt,{name:"version",value:h!=null?String(h):"",options:dnt(u??[],p!=null?new Set([p]):void 0),onValueChange:_=>y("version",Number(_))})}),o.jsx(Dd,{className:"grid content-start gap-8 overflow-y-auto",children:d?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):w?o.jsx(MV,{item:w,diff:x&&k?{against:k,side:O?"a":"b"}:void 0}):o.jsx("div",{className:"text-neutral4 text-sm",children:"Item data not available"})})]}),o.jsxs(Mc,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[o.jsx(wx,{children:o.jsx(hnt,{name:"compare",value:p!=null?String(p):"",placeholder:"Select a version to compare",options:dnt(u??[],h!=null?new Set([h]):void 0),onValueChange:_=>y("compare",Number(_))})}),o.jsx(Dd,{className:"grid content-start gap-8 overflow-y-auto",children:p==null?o.jsx(yr,{className:"h-full",iconSlot:o.jsx(S2,{className:"text-neutral3 size-8"}),titleSlot:"No version selected",descriptionSlot:"Pick a version above to compare it with the one on the left."}):v?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):k?o.jsx(MV,{item:k,diff:x&&w?{against:w,side:O?"b":"a"}:void 0}):o.jsxs("div",{className:"text-neutral4 text-sm",children:["Version ",p," not found"]})})]})]})})]})}function hnt({name:e,value:t,options:n,placeholder:r="Select version",onValueChange:s}){return o.jsxs("div",{className:"grid grid-cols-[auto_1fr] items-center gap-4",children:[o.jsx(d3,{className:"size-4 opacity-50"}),o.jsxs(da,{name:e,value:t,onValueChange:s,children:[o.jsx(ha,{"aria-label":e==="compare"?"Compare version":"Version",className:"w-full",children:o.jsx(fa,{placeholder:r,className:"flex-1"})}),o.jsx(pa,{children:n.map(a=>o.jsx(xr,{value:a.value,disabled:a.disabled,children:a.label},a.value))})]})]})}function y0s(){const{datasetId:e}=fr(),[t]=Ta(),n=t.get("ids")?.split(",").map(Number).filter(m=>!isNaN(m)&&m>0)??[],r=Br(),{data:s,error:a}=$m(e??""),i=Yx(e??"",void 0,n[0]??null),l=Yx(e??"",void 0,n[1]??null),c=g.useMemo(()=>i.data??[],[i.data]),u=g.useMemo(()=>l.data??[],[l.data]),d=g.useMemo(()=>{const m=new Map;for(const v of[...c,...u])m.has(v.id)||m.set(v.id,{id:v.id,createdAt:new Date(v.createdAt)});return[...m.values()].sort((v,y)=>y.createdAt.getTime()-v.createdAt.getTime())},[c,u]),f=g.useMemo(()=>new Map(c.map(m=>[m.id,m])),[c]),h=g.useMemo(()=>new Map(u.map(m=>[m.id,m])),[u]);if(a&&rs(a))return o.jsx(ks,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(_s,{})})});if(a&&is(a))return o.jsx(ks,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ys,{resource:"datasets"})})});if(!e||n.length<2)return o.jsx(ks,{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=(m,v)=>{r(`/datasets/${e}/versions?ids=${m},${v}`,{replace:!0})};return o.jsx(ks,{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(al,{children:[o.jsxs(al.Column,{children:[o.jsxs(al.Title,{children:[o.jsx(Stn,{})," Compare Dataset Versions"]}),o.jsx(al.Description,{children:o.jsxs(Rc,{children:[o.jsx(d3,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),o.jsx(al.Column,{children:o.jsxs(ae,{as:gi,to:`/datasets/${e}`,children:[o.jsx(uc,{}),"Back to Dataset"]})})]}),o.jsx(Ij,{children:o.jsxs(el,{children:[o.jsx(Lxs,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:p}),o.jsx(a0s,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:h})]})})]})})})}const b0s=["agent","workflow","scorer","processor"],x0s=new Set(b0s);function w0s(e){return typeof e=="string"&&x0s.has(e)}function S0s(){const e=Br(),[t]=Ta(),n=t.get("targetType"),r=w0s(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(al,{className:"mb-6 p-0",children:o.jsxs(al.Column,{children:[o.jsxs(al.Title,{children:[o.jsx(Lg,{})," Create new dataset"]}),o.jsx(al.Description,{children:"Datasets group test cases used to evaluate your agents and workflows."})]})}),o.jsx(Mc,{className:"p-6",children:o.jsx(Tbs,{targetType:r,targetIds:a,onSuccess:i=>{e(`/datasets/${i}`)},onCancel:()=>{e(-1)}})})]})})]})}function w0e({children:e,className:t}){return o.jsx("div",{className:K("flex flex-wrap gap-8",t),children:e})}function k0s(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 O0s({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=k0s(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 _Wt({open:e,onOpenChange:t,experimentId:n,experimentName:r,onSuccess:s}){const{deleteExperiment:a}=La(),i=async()=>{try{await a.mutateAsync(n),Ve.success("Experiment deleted successfully"),t(!1),s?.()}catch(l){Ve.error(`Failed to delete experiment: ${l instanceof Error?l.message:"Unknown error"}`)}};return o.jsx(Tt,{open:e,onOpenChange:t,children:o.jsxs(Tt.Content,{children:[o.jsxs(Tt.Header,{children:[o.jsx(Tt.Title,{children:"Delete Experiment"}),o.jsxs(Tt.Description,{children:['Are you sure you want to delete "',r||n,'"? This will permanently delete the experiment, all its results, and the traces it produced, including their spans and any scores, feedback, metrics and logs attached to those traces. This action cannot be undone.']})]}),o.jsxs(Tt.Footer,{children:[o.jsx(ae,{variant:"primary",size:"lg",onClick:i,disabled:a.isPending,children:a.isPending?"Deleting...":"Delete"}),o.jsx(Tt.Cancel,{children:"Cancel"})]})]})})}function EWt(e){const t=w0(e.id)??e.id;return e.name||`Experiment #${t}`}const C0s=60;function _0s({experiment:e}){return o.jsx("span",{className:"text-neutral4 block min-w-0 truncate text-left",children:EWt(e)})}function E0s({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<=C0s?n:o.jsxs(bn,{children:[o.jsx(mn,{asChild:!0,children:n}),o.jsx(gn,{children:t})]})}const xY=()=>{const{requestContext:e}=bs(),t=Qe();return gt({queryKey:["processors"],queryFn:()=>t.listProcessors(e)})},TWt=(e,t)=>{const n=Qe(),{requestContext:r}=bs();return gt({queryKey:["processor",e],queryFn:()=>n.getProcessor(e).details(r),enabled:!!e})},T0s=()=>{const e=Qe(),{requestContext:t}=bs();return wn({mutationFn:async({processorId:n,phase:r,messages:s,agentId:a})=>e.getProcessor(n).execute({phase:r,messages:s,agentId:a,requestContext:t})})};function jWt(){const{data:e}=Um(),{data:t}=Ky(),{data:n}=up(),{data:r}=xY();return{agents:e,workflows:t,scorers:n,processors:r}}const NWt={agent:uo,workflow:_u,scorer:EA,processor:oV},IWt={agent:"Agent",workflow:"Workflow",scorer:"Scorer",processor:"Processor"},j0s="External (caller-run)";function AWt(e,{agents:t,workflows:n,scorers:r,processors:s}){const{targetType:a,targetId:i}=e;if(!i)return j0s;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 N0s({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(fe.Cell,{children:o.jsx(_0s,{experiment:e})}),o.jsx(fe.Cell,{children:o.jsx(E0s,{experiment:e})}),t!==void 0&&o.jsx(fe.TextCell,{children:t}),o.jsx(fe.Cell,{children:o.jsx(I0s,{experiment:e})}),o.jsx(fe.Cell,{children:o.jsx(mt,{variant:vVt[r]??"neutral",indicator:"dot",children:qT[r]??r})}),o.jsx(fe.TextCell,{className:"text-center",children:i}),o.jsx(fe.TextCell,{className:"text-center",children:s}),o.jsx(fe.TextCell,{className:"text-center",children:o.jsx("span",{className:a>0?"text-accent2":"",children:a})}),o.jsx(fe.Cell,{className:"text-center",children:o.jsx(A0s,{review:n})}),o.jsx(fe.TextCell,{children:vfs(e.createdAt)})]})}function I0s({experiment:e}){const t=jWt(),n=AWt(e,t),r=e.targetId?e.targetType:null,s=r?NWt[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":IWt[r],children:o.jsx(s,{})}),o.jsx("span",{className:r?"truncate":"text-neutral2 truncate",children:n})]})}function A0s({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(mt,{size:"xs",variant:"yellow",children:[e.needsReview," pending"]}):o.jsxs(mt,{size:"xs",variant:"green",children:[e.complete,"/",t," reviewed"]})}const RWt=`${hfs} ${pfs} ${mfs} ${gfs}`,pnt=`${RWt} auto`,R0s=[{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 P0s({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}=un(),f=g.useMemo(()=>{const k=new Map;return t?.forEach(O=>k.set(O.id,O.name)),k},[t]),h=g.useMemo(()=>[...e].sort((k,O)=>{const _=k.createdAt?new Date(k.createdAt).getTime():0;return(O.createdAt?new Date(O.createdAt).getTime():0)-_}),[e]),p=g.useMemo(()=>{const k=s.toLowerCase();return h.filter(O=>{const _=O.datasetId?f.get(O.datasetId)??"":"",T=!k||O.id.toLowerCase().includes(k)||(O.name??"").toLowerCase().includes(k)||_.toLowerCase().includes(k)||(O.targetId??"").toLowerCase().includes(k),E=a==="all"||O.status===a,N=i==="all"||O.datasetId===i;return T&&E&&N})},[h,s,f,a,i]),{containerRef:m,getRowProps:v}=no({count:p.length}),[y,b]=g.useState(null);if(r)return o.jsx(Lo,{columns:pnt});const x=c?`auto ${RWt}`:pnt,w=R0s.map(k=>o.jsx(fe.TopCell,{className:k.className,children:k.label},k.label));return o.jsxs(fe,{columns:x,scrollRef:m,children:[o.jsx(fe.Top,{hasLeadingCell:c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(fe.TopCell,{children:" "}),o.jsx(fe.TopCells,{colStart:2,children:w})]}):o.jsxs(o.Fragment,{children:[w,o.jsx(fe.TopCell,{"aria-hidden":!0,children:null})]})}),p.map((k,O)=>{const _=k.datasetId?f.get(k.datasetId)??w0(k.datasetId)??k.datasetId:"—",T=o.jsx(N0s,{experiment:k,datasetName:_,review:n?.get(k.id)});if(!l)return o.jsxs(fe.RowWrapper,{children:[o.jsx(fe.RowLink,{colEnd:-2,to:u.experimentLink(k.id),LinkComponent:d,...v(O),children:T}),o.jsx(fe.ActionsCell,{className:"pl-2",children:o.jsx(ae,{type:"button",variant:"ghost",size:"icon-xs",tooltip:"Delete experiment","aria-label":`Delete experiment ${k.name??k.id}`,onClick:I=>{I.stopPropagation(),b(k)},children:o.jsx(cl,{className:"size-4"})})})]},k.id);const E=l.selectedExperimentIds.includes(k.id),N=()=>l.onToggleSelection(k.id);return o.jsxs(fe.RowWrapper,{children:[o.jsx(fe.SelectCell,{checked:E,onToggle:N,"aria-label":`Select experiment ${k.id}`}),o.jsx(fe.RowButton,{colStart:2,featured:E,onClick:N,...v(O),children:T})]},k.id)}),y&&o.jsx(_Wt,{open:!0,onOpenChange:k=>{k||b(null)},experimentId:y.id,experimentName:y.name??void 0})]})}const $0s=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function M0s(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const m8={completed:Y7.neutral3,running:"#facc15",pending:"#fb923c",failed:"#f87171"},D0s=[{label:"Completed",color:m8.completed},{label:"Running",color:m8.running},{label:"Pending",color:m8.pending},{label:"Failed",color:m8.failed}];function L0s({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(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Experiments by Dataset",description:"Experiment status breakdown per dataset."}),i&&o.jsx(Vt.Summary,{value:String(e?.length??0),label:"Total experiments"})]}),n?o.jsx(Vt.Loading,{}):r?o.jsx(Vt.Error,{message:"Failed to load experiments data"}):o.jsx(Vt.Content,{children:i?o.jsx(tI,{data:s,segments:D0s,maxVal:a,fmt:l=>String(l)}):o.jsx(Vt.NoData,{message:"No experiments have been run yet"})})]})}const F0s=({onRunExperiment:e})=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(yr,{iconSlot:o.jsx(Cs,{}),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(ae,{variant:"primary",onClick:e,children:[o.jsx(Fc,{}),"Run Experiment"]}),o.jsxs(ae,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/evals/experiments",target:"_blank",rel:"noopener noreferrer",children:["Experiments Documentation ",o.jsx(Fs,{})]})]})})});function z0s({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(mt,{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(_ut,{})]}),o.jsxs(ps,{children:[o.jsxs(ae,{variant:"primary",disabled:!b,onClick:m,children:[o.jsx(S2,{className:"h-4 w-4"}),"Compare Experiments"]}),o.jsx(ae,{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(ps,{children:[o.jsx(Om,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...$0s],value:n,onValueChange:r,className:"whitespace-nowrap"}),o.jsx(Om,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:i,value:s,onValueChange:a,className:"whitespace-nowrap"}),l&&c&&o.jsxs(ae,{onClick:l,size:"sm",variant:"default",children:[o.jsx(tr,{className:"size-3"})," Reset"]})]}),o.jsxs(ps,{className:"ml-auto shrink-0",children:[f&&o.jsxs(ae,{onClick:f,tooltip:"Select two experiments of the same dataset to compare",children:[o.jsx(S2,{}),"Compare"]}),u&&o.jsxs(ae,{onClick:u,tooltip:d,variant:"primary",children:[o.jsx(Fc,{}),"Run Experiment"]})]})]})}const B0s={present:!1,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},mnt=e=>e?e instanceof Date?e.toISOString():e:null,gnt=e=>{const t=new Map;for(const n of e??[])t.set(n.itemId,n);return t},vnt=(e,t,n)=>{if(!e)return B0s;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:mnt(t?.startedAt),completedAt:mnt(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))}},U0s=({comparison:e,baselineId:t,contenderId:n,baselineResults:r,contenderResults:s,baselineScores:a,contenderScores:i})=>{if(!e)return[];const l=gnt(r),c=gnt(s);return e.items.map(u=>{const d=vnt(u.results[t],l.get(u.itemId),a?.[u.itemId]),f=vnt(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 Uk({title:e,actions:t,tone:n="default",defaultOpen:r=!0,children:s}){return o.jsxs(cc,{defaultOpen:r,className:"grid gap-2",children:[o.jsxs("div",{className:"flex min-h-6 items-center justify-between gap-2",children:[o.jsxs(Bl,{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(Fr,{}),e]}),t]}),o.jsx(Ul,{role:"region","aria-label":e,children:s})]})}function ynt({label:e,value:t}){return t==null?null:o.jsx(Uk,{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 PWt({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(GYt,{className:"size-3.5"}):e<0?o.jsx(LYt,{className:"size-3.5"}):null]})}function $Wt({scorerId:e,value:t,delta:n,reason:r}){const{Link:s,paths:a}=un();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(EA,{}),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(PWt,{delta:n})]})]}),r&&o.jsx("p",{className:"text-neutral3 text-sm",children:r})]})}function bnt(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function q0s(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 V0s="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 xnt({side:e,row:t,showDeltas:n,isLoading:r}){const s=t[e],a=q0s(s);if(r)return o.jsx("div",{className:"flex h-32 items-center justify-center",children:o.jsx(Ht,{})});if(!s.present)return o.jsx("p",{className:"text-neutral3 py-8 text-center text-sm",children:"Not present in this experiment"});const i=bnt(s.output);return o.jsxs("div",{className:"grid content-start gap-5",children:[a&&o.jsxs(bn,{children:[o.jsx(mn,{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(gn,{children:"Run duration"})]}),s.error?o.jsx(Uk,{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(Uk,{title:"Output",actions:o.jsx(_a,{content:i}),children:o.jsx("pre",{className:V0s,children:i})}),s.scores.length>0&&o.jsx(Uk,{title:"Scores",children:o.jsx("div",{className:"grid gap-2",children:s.scores.map(l=>o.jsx($Wt,{scorerId:l.scorerId,value:l.value,delta:n?t.deltas[l.scorerId]:null,reason:l.reason},l.scorerId))})}),s.comment&&o.jsx(Uk,{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(Uk,{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:bnt(c)})]},l))})})]})}const H0s={baseline:"Baseline",contender:"Contender"},W0s={baseline:"purple",contender:"blue"},Z0s="flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0";function wnt({side:e,experiment:t,summary:n,showDeltas:r,versionMismatch:s}){const{Link:a,paths:i}=un(),l=H0s[e],c=t?w0(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(mt,{variant:W0s[e],size:"xs",children:l}),t&&o.jsx(ae,{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(Rc,{children:[o.jsx(c3,{})," ",c]}),t.targetType==="agent"&&t.targetId?o.jsxs(a,{href:i.agentLink(t.targetId),className:Z0s,children:[o.jsx(uo,{}),o.jsx("span",{className:"min-w-0 truncate",children:t.targetId})]}):o.jsxs(Rc,{children:[o.jsx(Put,{})," ",t.targetId]}),o.jsx("span",{className:K(s&&"text-accent6"),children:o.jsxs(Rc,{children:[o.jsx(WV,{})," v",t.datasetVersion??"—",s&&" · different dataset version"]})}),u&&o.jsxs(Rc,{children:[o.jsx(X9,{})," ",dr(u,"MMM d, yyyy HH:mm")]})]}),d.length>0&&o.jsx(Uk,{title:"Overall score",children:o.jsx("div",{className:"grid gap-2",children:d.map(({scorerId:f,average:h,delta:p})=>o.jsx($Wt,{scorerId:f,value:h,delta:r?p:null},f))})})]})}const YE="min-w-0 px-4 py-3";function G0s({datasetId:e,experimentIdA:t,experimentIdB:n}){const{Link:r,paths:s}=un(),{data:a,isLoading:i,error:l}=Zys(e,t,n),{data:c}=XD(e,t),{data:u}=XD(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}=JD({datasetId:e,experimentId:f,experimentStatus:p?.status}),{data:b,isLoading:x}=JD({datasetId:e,experimentId:h,experimentStatus:m?.status}),{data:w}=PC(f,p?.status),{data:k}=PC(h,m?.status),O=g.useMemo(()=>U0s({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(O.flatMap(E=>Object.keys(E.deltas)))].sort(),[O]),T=g.useMemo(()=>{const E=(A,R)=>{const L=O.map(D=>D[A].scores.find(B=>B.scorerId===R)?.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 R=E("baseline",A),L=E("contender",A);return{scorerId:A,average:L,delta:R!=null&&L!=null?L-R:null}});return{baseline:N,contender:I}},[O,_]);return i?o.jsx("div",{className:"flex h-64 items-center justify-center",children:o.jsx(Ht,{})}):l?o.jsx(An,{variant:"warning",title:"Error loading comparison",children:o.jsx(An.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:`${YE} text-neutral3 text-ui-sm uppercase`,children:"Items"}),o.jsx("div",{role:"columnheader","aria-label":"Baseline",className:YE,children:o.jsx(wnt,{side:"baseline",experiment:p,summary:T.baseline,versionMismatch:d})}),o.jsx("div",{role:"columnheader","aria-label":"Contender",className:YE,children:o.jsx(wnt,{side:"contender",experiment:m,summary:T.contender,versionMismatch:d,showDeltas:!0})})]}),O.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:`${YE} 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(PWt,{delta:A},I))}),o.jsxs("div",{className:"grid pt-3",children:[o.jsx(ynt,{label:"Input",value:E.input}),o.jsx(ynt,{label:"Ground truth",value:E.groundTruth})]})]}),o.jsx("div",{role:"cell","aria-label":"Baseline",className:YE,children:o.jsx(xnt,{side:"baseline",row:E,isLoading:y})}),o.jsx("div",{role:"cell","aria-label":"Contender",className:YE,children:o.jsx(xnt,{side:"contender",row:E,isLoading:x,showDeltas:!0})})]},E.itemId)})]})})}const Q0s=100;function wY(e){const t=Qe(),n={perPage:Q0s};return gt({queryKey:e?["dataset-experiments",e,n]:["experiments",n],queryFn:()=>e?t.listDatasetExperiments(e,n):t.listExperiments(n)})}const MWt=(e,t)=>{const n=Qe(),{data:r,isLoading:s}=wY(void 0),a=r?.experiments,i=t?a?.filter(c=>c.id===t):a,l=gt({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}},Y0s=({experimentId:e}={})=>MWt("needs-review",e),K0s=({experimentId:e}={})=>MWt("complete",e);function X0s(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 J0s({datasetId:e,experimentId:t,featuredItemId:n,detailPanelVariant:r="inline"}){const s=Qe(),{data:a}=$m(e??""),{data:i,isLoading:l}=Y0s({experimentId:t}),{data:c,isLoading:u}=K0s({experimentId:t}),{updateExperimentResult:d}=La(),[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),[O,_]=g.useState(!1),[T,E]=g.useState(""),[N,I]=g.useState(""),[A,R]=g.useState(""),[L,D]=g.useState([]),[B,H]=g.useState(!1),[q,F]=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 Oe of a.tags)de.add(Oe);for(const Oe of V)for(const Ne of Oe.tags)de.add(Ne);return[...de].sort()},[a,V]),G=g.useCallback(de=>{!a||!e||(a.tags??[]).includes(de)},[a,e]),z=g.useMemo(()=>p?p==="__untagged__"?V.filter(de=>de.tags.length===0):V.filter(de=>de.tags.includes(p)):V,[V,p]),P=g.useMemo(()=>{const de=new Map;for(const Oe of V)for(const Ne of Oe.tags)de.set(Ne,(de.get(Ne)??0)+1);return[...de.entries()].sort((Oe,Ne)=>Ne[1]-Oe[1])},[V]),U=g.useMemo(()=>V.filter(de=>de.tags.length===0).length,[V]),W=g.useMemo(()=>{let de=0;return p&&de++,b&&de++,de},[p,b]),Y=g.useCallback((de,Oe)=>{const Ne=V.find(be=>be.id===de);Ne?.experimentId&&Ne?.datasetId&&d.mutate({datasetId:Ne.datasetId,experimentId:Ne.experimentId,resultId:Ne.id,tags:Oe})},[V,d]),te=g.useCallback((de,Oe)=>{const Ne=V.find(be=>be.id===de);Ne?.traceId&&Oe!==void 0&&s.createFeedback({feedback:{traceId:Ne.traceId,source:"studio",feedbackSource:"studio",feedbackType:"rating",value:Oe==="positive"?1:-1,reviewStatus:"reviewed",experimentId:Ne.experimentId??void 0,sourceId:Ne.id}}).catch(()=>{}),F(be=>({...be,[de]:Oe}))},[V,s]),J=g.useCallback((de,Oe)=>{const Ne=V.find(be=>be.id===de);Ne?.experimentId&&Ne?.datasetId&&d.mutate({datasetId:Ne.datasetId,experimentId:Ne.experimentId,resultId:Ne.id,comment:Oe}),Ne?.traceId&&s.createFeedback({feedback:{traceId:Ne.traceId,source:"studio",feedbackSource:"studio",feedbackType:"comment",value:Oe,comment:Oe,reviewStatus:"reviewed",experimentId:Ne.experimentId??void 0,sourceId:Ne.id}}).catch(()=>{})},[V,s,d]),ee=g.useCallback(de=>{const Oe=V.find(Ne=>Ne.id===de);y(Ne=>{const be=new Set(Ne);return be.delete(de),be}),f===de&&h(null),Oe?.experimentId&&Oe?.datasetId&&d.mutate({datasetId:Oe.datasetId,experimentId:Oe.experimentId,resultId:Oe.id,status:null})},[V,d,f]),re=g.useCallback(de=>{const Oe=V.find(Ne=>Ne.id===de);y(Ne=>{const be=new Set(Ne);return be.delete(de),be}),f===de&&h(null),Oe?.experimentId&&Oe?.datasetId&&d.mutate({datasetId:Oe.datasetId,experimentId:Oe.experimentId,resultId:Oe.id,status:"complete"})},[V,d,f]),oe=g.useMemo(()=>{const de=b?c??[]:z;return!b||!p?de:p==="__untagged__"?de.filter(Oe=>Oe.tags.length===0):de.filter(Oe=>Oe.tags.includes(p))},[b,c,z,p]),X=b?u:!1,ne=g.useMemo(()=>new Set(oe.map(de=>de.id)),[oe]),se=g.useMemo(()=>[...v].filter(de=>ne.has(de)).length,[v,ne]),ce=oe.length>0&&se===oe.length,le=se>0&&!ce,ye=g.useCallback(de=>{y(Oe=>{const Ne=new Set(Oe);return Ne.has(de)?Ne.delete(de):Ne.add(de),Ne})},[]),he=g.useCallback(()=>{y(ce?new Set:new Set(oe.map(de=>de.id)))},[ce,oe]),xe=g.useCallback(de=>{for(const Oe of v){const Ne=V.find(be=>be.id===Oe);Ne&&!Ne.tags.includes(de)&&Y(Oe,[...Ne.tags,de])}},[V,v,Y]),Ae=g.useCallback(de=>{for(const Oe of v){const Ne=V.find(be=>be.id===Oe);Ne&&Ne.tags.includes(de)&&Y(Oe,Ne.tags.filter(be=>be!==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]),$e=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 Oe=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});Oe.proposedTags&&Oe.proposedTags.length>0&&(D(Oe.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 Oe=V.find(Ne=>Ne.id===de.itemId);if(Oe){const Ne=[...new Set([...Oe.tags,...de.tags])];Y(Oe.id,Ne)}}H(!1)},[L,V,Y]),Te=g.useCallback(de=>{h(Oe=>Oe===de?null:de)},[]),je=g.useMemo(()=>f?oe.find(de=>de.id===f)??null:null,[f,oe]),ze=f?oe.findIndex(de=>de.id===f):-1,_e=ze>0?()=>h(oe[ze-1].id):void 0,Fe=ze>=0&&ze<oe.length-1?()=>h(oe[ze+1].id):void 0,tt="auto minmax(0,20rem) minmax(0,1fr) minmax(0,8rem) 6rem 6rem",{containerRef:Ge,getRowProps:ge}=no({count:oe.length});if(l)return o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(Ht,{className:"h-6 w-6"})});const Se=je?o.jsx(xVt,{className:"h-full",item:je,isCompleted:b,tagVocabulary:M,onRate:de=>te(je.id,de),onSetTags:de=>{Y(je.id,de);for(const Oe of de)M.includes(Oe)||G(Oe)},onComment:de=>J(je.id,de),onRemove:()=>ee(je.id),onComplete:b?void 0:()=>re(je.id),onPrevious:_e,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:O,onOpenChange:_,children:o.jsxs(mr,{children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Analyze Items"}),o.jsx(Ts,{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(Qy,{value:N,onValueChange:I})]}),o.jsxs("div",{children:[o.jsx(Dt,{className:"mb-1 block text-xs",children:"Model"}),o.jsx(Yy,{llmId:N,value:A,onValueChange:R})]})]}),o.jsxs(me,{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(So,{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(Fl,{children:[o.jsx(ae,{variant:"outline",onClick:()=>_(!1),children:"Cancel"}),o.jsxs(ae,{onClick:Re,disabled:!N||!A||w,children:[w?o.jsx(Ht,{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(Ts,{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,Oe)=>{const Ne=V.find(be=>be.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(Bo,{checked:de.accepted,onCheckedChange:be=>D(ve=>ve.map((ke,Pe)=>Pe===Oe?{...ke,accepted:!!be}:ke))}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(me,{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((be,ve)=>o.jsx(SVt,{tag:be,onRename:ke=>D(Pe=>Pe.map((He,yt)=>yt===Oe?{...He,tags:He.tags.map((Ee,et)=>et===ve?ke:Ee)}:He)),onRemove:()=>D(ke=>ke.map((Pe,He)=>He===Oe?{...Pe,tags:Pe.tags.filter((yt,Ee)=>Ee!==ve)}:Pe))},`${be}-${ve}`))}),de.reason&&o.jsx(me,{variant:"ui-xs",className:"text-neutral3 mt-1 block italic",children:de.reason})]})]})},de.itemId)})}),o.jsxs(Fl,{children:[o.jsx(ae,{variant:"outline",onClick:()=>H(!1),children:"Cancel"}),o.jsxs(ae,{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",je&&r==="inline"&&"grid-cols-[1fr_1fr]"),children:[o.jsxs("div",{className:K("grid min-h-0 w-full gap-3 overflow-hidden pt-3",V.length>0||W>0?"grid-rows-[auto_minmax(0,1fr)]":"grid-rows-1"),children:[(V.length>0||W>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(ae,{size:"sm",children:[o.jsx(z0e,{}),"Filter",W>0&&o.jsx(mt,{size:"xs",children:W})]})}),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"}),P.length>0&&o.jsx(at.Separator,{}),P.map(([de])=>o.jsx(at.CheckboxItem,{checked:p===de,onCheckedChange:()=>m(p===de?null:de),onSelect:Oe=>Oe.preventDefault(),children:de},de))]})]}),W>0&&o.jsxs(o.Fragment,{children:[o.jsx(at.Separator,{}),o.jsxs(at.Item,{onSelect:()=>{m(null),x(!1),h(null)},children:[o.jsx(tr,{}),"Clear all filters"]})]})]})]}),W>0&&o.jsxs(ae,{size:"sm",onClick:()=>{m(null),x(!1),h(null)},children:[o.jsx(tr,{}),"Reset"]})]}),!b&&v.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(wVt,{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(ae,{size:"sm",disabled:w,children:[w?o.jsx(Ht,{className:"h-4 w-4"}):o.jsx(Ke,{size:"sm",children:o.jsx(ta,{})}),"Actions"]})}),o.jsxs(at.Content,{align:"end",children:[o.jsxs(at.Item,{onSelect:De,children:[o.jsx(Ke,{size:"sm",children:o.jsx(EO,{})}),"Complete"]}),o.jsxs(at.Item,{onSelect:Me,children:[o.jsx(Ke,{size:"sm",children:o.jsx(cl,{})}),"Remove"]}),o.jsx(at.Separator,{}),o.jsxs(at.Item,{onSelect:$e,children:[o.jsx(Ke,{size:"sm",children:o.jsx(f1,{})}),"Analyze"]})]})]})]})]}),X?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(Ht,{className:"h-6 w-6"})}):oe.length===0?o.jsx("div",{className:"flex h-full items-center-safe justify-center-safe overflow-auto py-12",children:o.jsx(yr,{iconSlot:o.jsx(Cs,{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(fe,{columns:tt,fit:"container",className:"min-w-0",scrollRef:Ge,children:[o.jsxs(fe.Top,{hasLeadingCell:!0,children:[b?o.jsx(fe.TopCell,{children:" "}):o.jsx(fe.TopSelectCell,{checked:ce?!0:le?"indeterminate":!1,onToggle:()=>he(),"aria-label":"Select all"}),o.jsxs(fe.TopCells,{colStart:2,children:[o.jsx(fe.TopCell,{children:"Input"}),o.jsx(fe.TopCell,{children:"Comment"}),o.jsx(fe.TopCell,{children:"Tags"}),o.jsx(fe.TopCell,{children:"Rating"}),o.jsx(fe.TopCell,{children:"Scores"})]})]}),oe.map((de,Oe)=>{const Ne=de.scores?Object.entries(de.scores):[],be=f===de.id,ve=o.jsxs(o.Fragment,{children:[o.jsx(fe.Cell,{className:"text-neutral4 min-w-0",children:o.jsx("span",{className:"block truncate",children:X0s(de.input,200)})}),o.jsx(fe.Cell,{className:"min-w-0",children:de.comment?o.jsx(me,{variant:"ui-xs",className:"text-neutral3 truncate",children:de.comment}):o.jsx(me,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsx(fe.Cell,{className:"min-w-0",children:de.tags.length>0?o.jsx(me,{variant:"ui-xs",className:"text-neutral4 truncate",children:de.tags.join(", ")}):o.jsx(me,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsxs(fe.Cell,{children:[de.rating==="positive"&&o.jsx(Ke,{size:"sm",className:"text-positive1",children:o.jsx(K0e,{})}),de.rating==="negative"&&o.jsx(Ke,{size:"sm",className:"text-negative1",children:o.jsx(Y0e,{})}),!de.rating&&o.jsx(me,{variant:"ui-xs",className:"text-neutral2",children:"—"})]}),o.jsx(fe.Cell,{children:Ne.length>0?o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Ke,{size:"sm",className:"text-neutral3",children:o.jsx(fm,{})}),o.jsx(me,{variant:"ui-xs",className:"text-neutral4 font-mono",children:Ne[0][1].toFixed(2)}),Ne.length>1&&o.jsxs(mt,{children:["+",Ne.length-1]})]}):o.jsx(me,{variant:"ui-xs",className:"text-neutral2",children:"—"})})]});return o.jsxs(fe.RowWrapper,{children:[b?o.jsx(fe.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(fe.SelectCell,{checked:v.has(de.id),onToggle:()=>ye(de.id),"aria-label":`Select item ${de.id}`}),o.jsx(fe.RowButton,{colStart:2,featured:be,onClick:()=>Te(de.id),...ge(Oe),children:ve})]},de.id)})]})]}),Se&&(r==="overlay"?o.jsx(bY,{label:`Review item ${je?.id??""}`,children:o.jsx("div",{className:"[&>section]:bg-surface3 h-full min-h-0 p-3 [&>section]:rounded-lg [&>section]:shadow-lg",children:Se})}):Se)]})]})}const Snt={needsReview:"#facc15",complete:"#22c55e"},ews=[{label:"Needs Review",color:Snt.needsReview},{label:"Reviewed",color:Snt.complete}];function tws({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(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Review Pipeline",description:"Items in review across experiments."}),c&&o.jsx(Vt.Summary,{value:String(l),label:"Items in pipeline"})]}),r?o.jsx(Vt.Loading,{}):s?o.jsx(Vt.Error,{message:"Failed to load review data"}):o.jsx(Vt.Content,{children:c?o.jsx(tI,{data:a,segments:ews,maxVal:i,fmt:u=>String(u)}):o.jsx(Vt.NoData,{message:"No items have been sent to review yet"})})]})}function DWt(){const e=Qe();return gt({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function nws(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 rws(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 sws(){const[e,t]=g.useState("all"),[n,r]=g.useState({}),{data:s,isLoading:a,error:i}=up(),{data:l,isLoading:c,error:u}=Pm(),{data:d,isLoading:f,error:h}=JH(),{data:p,isLoading:m,isError:v,error:y}=CWr(n),{data:b,isLoading:x,isError:w,error:k}=DWt(),O=l?.datasets,_=d?.experiments,T=g.useMemo(()=>rws(b),[b]),E=i||u||h||y||k;return E&&rs(E)?o.jsx(Wn,{children:o.jsx(_s,{})}):E&&is(E)?o.jsx(Wn,{children:o.jsx(ys,{resource:"evaluation"})}):E?o.jsx(Wn,{children:o.jsx(Bs,{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(e4,{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(w0e,{children:o.jsx(O0s,{scorers:s,datasets:O,experiments:_,avgScore:p?.avgScore??null,prevAvgScore:p?.prevAvgScore??null,totalNeedsReview:T.needsReview,isLoadingScorers:a,isLoadingDatasets:c,isLoadingExperiments:f,isLoadingScores:m,isLoadingReview:x})}),o.jsx(DHr,{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(mbs,{experiments:_,isLoading:f,isError:!!h}),o.jsx(L0s,{experiments:_,datasets:O,isLoading:f,isError:!!h})]}),o.jsx(tws,{reviewSummary:b,experiments:_,datasets:O,isLoading:x,isError:!!w})]})]})}function aws(){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=Br(),[f,h]=Ta(),p=f.get("dataset")??"all",m=g.useCallback(G=>{h(z=>{const P=new URLSearchParams(z);return G==="all"?P.delete("dataset"):P.set("dataset",G),P},{replace:!0})},[h]),{data:v,isLoading:y,error:b}=Pm(),{data:x,isLoading:w,error:k}=wY(p==="all"?void 0:p),{data:O}=DWt(),_=g.useMemo(()=>v?.datasets??[],[v?.datasets]),T=g.useMemo(()=>x?.experiments??[],[x?.experiments]),E=g.useMemo(()=>M0s(_),[_]),N=g.useMemo(()=>nws(O),[O]),I=y||w,A=k||b,R=G=>{u(z=>z.includes(G)?z.filter(P=>P!==G):z.length>=2?[z[0],G]:[...z,G])},L=()=>{u([]),l(!1)},{selectedIds:D,selectedDatasetIds:B}=g.useMemo(()=>{const G=new Map(T.map(P=>[P.id,P.datasetId])),z=c.filter(P=>G.has(P));return{selectedIds:z,selectedDatasetIds:new Set(z.map(P=>G.get(P)))}},[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,z]=D,[P]=B;if(!P)return;const U=new URLSearchParams({dataset:P,baseline:G,contender:z});d(`/experiments/compare?${U.toString()}`)};if(A&&rs(A))return o.jsx(Wn,{children:o.jsx(_s,{})});if(k&&is(k))return o.jsx(Wn,{children:o.jsx(ys,{resource:"experiments"})});if(b&&is(b))return o.jsx(Wn,{children:o.jsx(ys,{resource:"datasets"})});if(A)return o.jsx(Wn,{children:o.jsx(Bs,{title:"Failed to load experiments",message:A.message})});const F=o.jsx(yY,{open:s,onOpenChange:a,onSuccess:G=>{d(`/experiments/${G}`)}});if(T.length===0&&!I&&p==="all")return o.jsxs(Wn,{children:[o.jsx(F0s,{onRunExperiment:()=>a(!0)}),F]});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(z0s,{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(P0s,{experiments:T,datasets:_,reviewByExperiment:N,isLoading:I,search:e,statusFilter:n,datasetFilter:p,selection:i?{selectedExperimentIds:D,onToggleSelection:R}:void 0}),F]})}function g8({experimentId:e}){const{Link:t,paths:n}=un();return o.jsx(ae,{as:t,href:n.experimentLink(e),size:"sm","aria-label":`Open experiment ${e}`,children:e.slice(0,8)})}function iws(){const[e,t]=Ta(),n=e.get("dataset")??"",r=e.get("baseline")??"",s=e.get("contender")??"",a=XD(n,r),i=XD(n,s),l=a.isLoading||i.isLoading,c=a.error??i.error;return c&&rs(c)?o.jsx(ks,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(_s,{})})}):c&&is(c)?o.jsx(ks,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ys,{resource:"experiments"})})}):!n||!r||!s?o.jsx(ks,{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&&!m0(c)?o.jsx(ks,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Bs,{title:"Failed to load experiments",message:c.message})})}):c||!a.data||!i.data?o.jsx(ks,{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(g8,{experimentId:r}),"and",o.jsx(g8,{experimentId:s}),"was not found in it."]})]})})}):o.jsx(ks,{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(me,{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(g8,{experimentId:r}),"and",o.jsx(g8,{experimentId:s})]})]}),o.jsxs(bn,{children:[o.jsx(mn,{asChild:!0,children:o.jsxs(ae,{onClick:()=>t({dataset:n,baseline:s,contender:r}),children:[o.jsx(aut,{}),"Swap sides"]})}),o.jsx(gn,{children:"Switch baseline and contender"})]})]}),o.jsx(G0s,{datasetId:n,experimentIdA:r,experimentIdB:s})]})})})}const LWt=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 FWt(e){const{data:t}=PC(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 foe({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(bn,{children:[o.jsx(mn,{render:o.jsx("span",{className:"text-neutral3 flex",role:"img","aria-label":t}),children:e}),o.jsx(gn,{children:t})]}),n]})}function hoe({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(Bd,{className:"size-3.5 shrink-0","aria-hidden":!0})]})}const knt="text-neutral5 inline-flex items-center gap-1.5 hover:underline";function ows({experiment:e,className:t}){const{Link:n,paths:r}=un(),s=jWt(),{scorers:a}=s,{data:i,isLoading:l}=$m(e.datasetId??""),c=FWt(e),u=c.map(b=>a?.[b]?.scorer?.config?.name??b),d=e.targetType,f=e.targetId,h=()=>AWt(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&&NWt[d]||uo,v=d&&IWt[d]||"Evaluation target",y=p();return o.jsxs("div",{className:K("flex items-center gap-3 overflow-x-auto",t),children:[o.jsx(foe,{icon:o.jsx(LWt,{}),typeLabel:"Dataset",children:e.datasetId?o.jsxs(n,{href:r.datasetLink(e.datasetId),className:knt,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(hoe,{label:"each item"}),o.jsx(foe,{icon:o.jsx(m,{}),typeLabel:v,children:y?o.jsx(n,{href:y,className:knt,children:h()}):o.jsx("span",{className:"text-neutral3",children:h()})}),o.jsx(hoe,{label:"output"}),o.jsxs(bn,{children:[o.jsx(mn,{render:o.jsx("div",{tabIndex:0,className:"flex outline-offset-4",children:o.jsx(foe,{icon:o.jsx(EA,{}),typeLabel:"Scorers",children:c.length===0?"Scorers":`${c.length} scorer${c.length===1?"":"s"}`})})}),o.jsx(gn,{children:u.length>0?u.join(", "):"No scorer has produced a score yet"})]}),o.jsx(hoe,{label:"comparing ground truth"}),o.jsx("div",{className:"text-ui-sm text-neutral5 flex-none whitespace-nowrap",children:"Score"})]})}function v8({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 lws(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 cws({experiment:e,className:t}){const{data:n}=PC(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?"—":lws(l)})();return o.jsxs("div",{className:K("flex w-full items-stretch divide-x divide-border1 border-y border-border1",t),children:[o.jsx(v8,{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(v8,{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(v8,{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:["· ",PDn(a,{addSuffix:!0})]})]}):o.jsx("span",{children:"—"})}),o.jsx(v8,{label:"Duration",children:o.jsx("span",{children:i})})]})}function uws({experiment:e,open:t,onOpenChange:n}){const[r,s]=g.useState(e.name??""),[a,i]=g.useState(e.description??""),{updateExperiment:l}=La(),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(Nr,{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(ae,{type:"button",onClick:()=>n(!1),disabled:l.isPending,children:"Cancel"}),o.jsx(ae,{type:"submit",variant:"primary",disabled:!c,children:l.isPending?"Saving...":"Save"})]})]})})]})})}function dws({experiment:e}){const[t,n]=g.useState(!1);return e.datasetId?o.jsxs(o.Fragment,{children:[o.jsx(ae,{onClick:()=>n(!0),tooltip:"Rename this experiment",variant:"ghost",size:"icon-sm",children:o.jsx(Yh,{})}),t&&o.jsx(uws,{experiment:e,open:!0,onOpenChange:n})]}):null}const fws=["agent","workflow","scorer"];function hws({experiment:e}){const[t,n]=g.useState(!1),r=Br(),{paths:s}=un(),a=FWt(e),i=fws.find(l=>l===e.targetType);return!e.datasetId||!i||!e.targetId?null:o.jsxs(o.Fragment,{children:[o.jsxs(ae,{variant:"primary",onClick:()=>n(!0),tooltip:"Run this experiment again with the same configuration",children:[o.jsx(Fc,{}),"Rerun"]}),t&&o.jsx(yY,{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 pws({experiment:e,onDeleteClick:t}){const{Link:n,paths:r}=un(),s=e.agentVersion&&e.targetType==="agent"&&e.targetId?`${r.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($xs,{status:e.status,className:"h-7"}),o.jsxs(Ml,{children:[o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Ml.Title,{children:e.name||`Experiment #${e.id.slice(0,8)}`}),o.jsx(dws,{experiment:e})]}),e.description&&o.jsx(Ml.Description,{children:e.description}),o.jsx(ows,{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(ae,{as:n,to:RTe(e.id),children:[o.jsx(LC,{}),"View items to review"]}),o.jsx(hws,{experiment:e}),t&&o.jsxs(ae,{size:"sm",variant:"ghost",onClick:t,"aria-label":"Delete experiment",children:[o.jsx(cl,{})," Delete Experiment"]})]}),e.agentVersion&&o.jsxs(Jn,{numOfCol:1,children:[o.jsx(Jn.Key,{children:"Version"}),s?o.jsx(Jn.ValueLink,{href:s,as:n,children:e.agentVersion}):o.jsx(Jn.Value,{children:e.agentVersion})]})]})]}),o.jsx(cws,{experiment:e,className:"-mx-6 w-auto"})]})}function y8({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function mws(){const{experimentId:e}=fr(),t=Br(),[n,r]=g.useState(!1),{data:s,isLoading:a}=JH(),l=s?.experiments?.find(y=>y.id===e)?.datasetId??"",{data:c,isLoading:u,error:d}=XD(l,e??""),{data:f,isLoading:h,setEndOfListElement:p,isFetchingNextPage:m,hasNextPage:v}=JD({datasetId:l,experimentId:e??"",experimentStatus:c?.status});return!e||a||u?null:d&&rs(d)?o.jsx(y8,{children:o.jsx(_s,{})}):d&&is(d)?o.jsx(y8,{children:o.jsx(ys,{resource:"datasets"})}):d&&m0(d)||!a&&!l||!u&&!d&&!c?o.jsx(y8,{children:o.jsx(yr,{iconSlot:o.jsx(L0e,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:o.jsxs(ae,{as:gi,to:"/experiments",children:[o.jsx(uc,{}),"Back to Experiments"]})})}):d?o.jsx(y8,{children:o.jsx(Bs,{title:"Failed to load experiment",message:d instanceof Error?d.message:"An unexpected error occurred. Please try again."})}):o.jsx(Txs,{experimentId:e,datasetId:l,experimentStatus:c.status,results:f??[],isLoadingResults:h,hasNextPage:v,children:o.jsxs("div",{className:"h-full",children:[o.jsxs(Lt,{height:"full",children:[o.jsx(pws,{experiment:c,onDeleteClick:()=>r(!0)}),o.jsx(Lt.MainArea,{className:"overflow-visible",children:o.jsx(Pxs,{experimentId:e,datasetId:l,experimentStatus:c.status,results:f??[],isLoading:h,setEndOfListElement:p,isFetchingNextPage:m,hasNextPage:v})})]}),o.jsx(Ug,{}),o.jsx(_Wt,{open:n,onOpenChange:r,experimentId:e,experimentName:c.name??void 0,onSuccess:()=>t("/experiments")})]})})}function poe(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function gws({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(fn.SectionHeading,{icon:o.jsx(Vd,{}),className:"mb-2",children:"Tool Mocks"}),s&&o.jsx(An,{variant:"destructive",title:"Mock mismatch",children:o.jsxs(An.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: ",poe(s.args)]}),n.length>0&&o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Unconsumed mocks: ",n.map(i=>poe(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:poe(i.args)})]}),o.jsx("span",{className:`shrink-0 rounded px-2 py-0.5 text-xs ${vws(i.outcome)}`,children:i.outcome})]},`${i.outcome}-${i.toolName}-${l}`))})]})}function vws(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 yws({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,onTagsChange:h,tagVocabulary:p=[],isUpdatingTags:m=!1}){const v=!!e?.error,y=b8(e?.input),b=b8(e?.output),x=b8(e?.groundTruth),w=u&&e.status!=="needs-review"&&e.status!=="complete",k=Array.isArray(e.tags)?e.tags:[],O=g.useMemo(()=>[e],[e]),_=!!h||k.length>0;return o.jsxs(fn,{collapsed:d,children:[o.jsxs(fn.Header,{children:[o.jsxs(fn.Heading,{children:["Result ",o.jsxs("b",{children:["# ",e.id.length>12?`${e.id.slice(0,12)}…`:e.id]})]}),o.jsxs(ps,{className:"ml-auto shrink-0",children:[o.jsx(fn.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Previous result",nextLabel:"Next result"}),e.traceId&&o.jsxs(ae,{size:"md",onClick:a,children:[o.jsx(eY,{}),"Trace"]}),w&&o.jsxs(ae,{size:"md",variant:"primary",onClick:()=>u(e.id),children:[o.jsx(LC,{}),"Flag for Review"]}),e.status==="needs-review"&&i&&o.jsxs(ae,{size:"md",variant:"primary",onClick:i,children:[o.jsx(Fs,{}),"Review"]}),o.jsx(fn.CloseButton,{onClick:s,tooltip:"Close result panel"})]})]}),!d&&o.jsx(bws,{scorePanelSlot:f,children:o.jsxs(fn.Content,{children:[o.jsxs("div",{className:"mb-6 grid gap-4",children:[o.jsxs(Jn,{children:[o.jsx(Jn.Key,{children:"Item Id"}),o.jsx(Jn.ValueWithCopyBtn,{copyTooltip:"Copy Item Id to clipboard",copyValue:e.itemId,children:e.itemId}),o.jsx(Jn.Key,{children:"Created"}),o.jsx(Jn.Value,{children:dr(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")}),e.status&&o.jsxs(o.Fragment,{children:[o.jsx(Jn.Key,{children:"Status"}),o.jsx(Jn.Value,{children:o.jsx(mt,{size:"xs",variant:e.status==="needs-review"?"orange":e.status==="complete"?"green":"neutral",children:e.status})})]}),_&&o.jsxs(o.Fragment,{children:[o.jsx(Jn.Key,{children:"Tags"}),o.jsx(Jn.Value,{children:o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[k.map(T=>o.jsxs(bA,{value:T,className:h?"gap-1 pr-1":void 0,children:[T,h&&o.jsx("button",{type:"button","aria-label":`Remove tag ${T}`,disabled:m,onClick:()=>h(k.filter(E=>E!==T)),className:"cursor-pointer rounded-sm hover:opacity-70 disabled:opacity-50",children:o.jsx(tr,{className:"size-3"})})]},T)),h&&o.jsx(OWt,{appearance:"inline",selectedResults:O,vocabulary:p,onAddTag:T=>h([...k,T]),disabled:m})]})})]})]}),v&&o.jsx(An,{variant:"destructive",title:"Error",children:o.jsx(An.Message,{children:b8(e?.error&&typeof e.error=="object"?e.error.message:e?.error)})}),t&&t.length>0&&o.jsxs(fe,{columns:"1fr 1fr",children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{children:"Scorer"}),o.jsx(fe.TopCell,{children:"Score"})]}),t.map(T=>o.jsxs(fe.RowButton,{featured:c===T.id,onClick:()=>l?.(T.id),children:[o.jsx(fe.Cell,{children:T.scorerId}),o.jsx(fe.TextCell,{font:"mono",children:T.score.toFixed(3)})]},T.id))]}),e.toolMockReport&&o.jsx(gws,{report:e.toolMockReport})]}),o.jsxs("div",{className:"grid gap-3",children:[o.jsx(fn.CodeSection,{title:"Input",icon:o.jsx(VV,{}),codeStr:y}),o.jsx(fn.CodeSection,{title:"Output",icon:o.jsx(Rg,{}),codeStr:b}),o.jsx(fn.CodeSection,{title:"Ground Truth",icon:o.jsx(Put,{}),codeStr:x})]})]})})]})}function bws({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 b8(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function xws(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function wws({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=xws(e),p=h?"N/A — code-based scorer":"N/A — step not configured";return o.jsxs(fn,{collapsed:d,className:l,children:[o.jsxs(fn.Header,{children:[o.jsxs(fn.Heading,{children:["Score ",o.jsx("b",{children:e.scorerId})]}),o.jsxs(ps,{className:"ml-auto shrink-0",children:[i&&o.jsx(ae,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(lI,{}):o.jsx(zV,{})}),(n||t)&&o.jsx(fn.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:"Previous score",nextLabel:"Next score"}),s&&e.traceId&&o.jsxs(ae,{size:"md",onClick:s,children:[o.jsx(eY,{}),"Trace"]}),o.jsx(fn.CloseButton,{onClick:r,tooltip:"Close score panel"})]})]}),!d&&o.jsx(fn.Content,{children:o.jsxs("div",{className:"grid gap-3",children:[o.jsx(fn.CodeSection,{title:`Score: ${e.score}`,icon:o.jsx(fm,{}),codeStr:e.reason||p,simplified:!0}),!h&&o.jsxs(o.Fragment,{children:[o.jsx(fn.CodeSection,{title:"Preprocess Prompt",icon:o.jsx(Mp,{}),codeStr:e.preprocessPrompt||p,simplified:!0}),o.jsx(fn.CodeSection,{title:"Analyze Prompt",icon:o.jsx(Mp,{}),codeStr:e.analyzePrompt||p,simplified:!0}),o.jsx(fn.CodeSection,{title:"Generate Score Prompt",icon:o.jsx(Mp,{}),codeStr:e.generateScorePrompt||p,simplified:!0}),o.jsx(fn.CodeSection,{title:"Generate Reason Prompt",icon:o.jsx(Mp,{}),codeStr:e.generateReasonPrompt||p,simplified:!0})]})]})})]})}function Sws(){const{itemId:e}=fr();return e?o.jsx(kws,{itemId:e},e):null}function kws({itemId:e}){const{experimentId:t,datasetId:n,experimentStatus:r,results:s,isLoadingResults:a,hasNextPage:i,close:l,openInReview:c,goToPreviousItem:u,goToNextItem:d}=SWt(),f=g.useMemo(()=>s.find(W=>W.itemId===e)??null,[s,e]),{data:h}=PC(t,r),{updateExperimentResult:p}=La(),m=g.useCallback(async W=>{try{await p.mutateAsync({datasetId:n,experimentId:t,resultId:W,status:"needs-review"}),Ve("Result flagged for review")}catch{Ve.error("Failed to flag result for review")}},[n,t,p]),v=kWt(n,s),y=g.useCallback(async(W,Y)=>{try{await p.mutateAsync({datasetId:n,experimentId:t,resultId:W,tags:Y})}catch{Ve.error("Failed to update tags")}},[n,t,p]),b=f?h?.[f.itemId]:void 0,[x,w]=g.useState(null),[k,O]=g.useState(void 0),[_,T]=g.useState(null),[E,N]=g.useState(!1),[I,A]=g.useState(!1),R=b?.find(W=>W.id===_)??null,L=g.useCallback(W=>{T(Y=>W===Y?null:W),w(null),O(void 0)},[]),D=()=>{if(!_||!b)return;const W=b.findIndex(Y=>Y.id===_);if(W>=0&&W<b.length-1)return()=>T(b[W+1].id)},B=()=>{if(!_||!b)return;const W=b.findIndex(Y=>Y.id===_);if(W>0)return()=>T(b[W-1].id)},{data:H,isLoading:q}=Mxs(x),F=H?.spans,V=F?.find(W=>!W.parentSpanId),M=V?.entityType==="agent"?"Agent":V?.entityType==="workflow_run"?"Workflow":void 0,{data:G}=cRe({traceId:x??void 0}),{data:z}=IRe({traceId:x??void 0,spanId:k}),{data:P}=Mje({traceId:x??void 0,spanId:V?.spanId,page:0}),U=(()=>{const W=[],Y=!!x;return W.push(E?"auto":Y?"2fr":"1fr"),Y&&W.push(I?"auto":"3fr"),W.join(" ")})();return o.jsx(bY,{label:`Experiment item ${e}`,wide:!!k||!!R&&!E,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:U},children:[o.jsx(yws,{result:f,scores:b,onPrevious:u,onNext:d,onClose:l,onScoreClick:L,featuredScoreId:_,onShowTrace:()=>{f.traceId&&(w(f.traceId),O(void 0),T(null),N(!0),A(!1))},onOpenInReview:()=>c(f.id),onFlagForReview:()=>{m(f.id)},onTagsChange:W=>{y(f.id,W)},tagVocabulary:v,isUpdatingTags:p.isPending,collapsed:E,scorePanelSlot:R?o.jsx(wws,{score:R,onNext:D(),onPrevious:B(),onClose:()=>T(null),onShowTrace:()=>{R.traceId&&(w(R.traceId),O(void 0),N(!0),A(!1))},className:"rounded-none border-0 bg-transparent"}):null}),x&&o.jsx(RRe,{traceId:x,spans:F,isLoadingSpans:q,selectedSpanId:k??null,onClose:()=>{w(null),O(void 0),N(!1)},onSpanSelect:O,showUnavailableFeaturesMsg:!1,collapsed:I,onCollapsedChange:A,traceHref:`/traces?traceId=${encodeURIComponent(x)}`,anchorSpanId:V?.spanId,feedbackTabBadge:G?.pagination?.total??void 0,feedbackTabSlot:({traceId:W})=>o.jsx(tY,{traceId:W}),scoresTabBadge:P?.pagination?.total??void 0,scoresTabSlot:({traceId:W,rootSpanId:Y})=>Y?o.jsx(sWt,{traceId:W,spanId:Y,isTopLevelSpan:!V?.parentSpanId,entityType:M,onScoreSelect:te=>{b?.some(J=>J.id===te)&&(T(te),N(!1))}}):null,spanFeedbackTabBadge:z?.pagination?.total??void 0,spanFeedbackTabSlot:({traceId:W,spanId:Y})=>W&&Y?o.jsx(ARe,{traceId:W,spanId:Y},`${W}:${Y}`):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(Ht,{})})}):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(yr,{iconSlot:o.jsx(L0e,{}),titleSlot:"Item not found",descriptionSlot:`No loaded result for item "${e}".`,actionSlot:o.jsx(ae,{onClick:l,children:"Close"})})})})})}const DRe=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"})}),DV="all",Ont=60,Ows=e=>e.length>Ont?`${e.slice(0,Ont)}…`:e;function Cws({value:e,onValueChange:t,className:n,variant:r,allOption:s}){const{data:a,isLoading:i,isError:l}=wY(void 0),c=(a?.experiments??[]).map(d=>({label:EWt(d),value:d.id,start:o.jsx(DRe,{className:"text-neutral3 size-4 shrink-0","data-testid":"experiments-icon"}),description:d.description?Ows(d.description):w0(d.id)??d.id})),u=s?[{label:"All experiments",value:DV},...c]:c;return o.jsx(zo,{options:u,value:e??(s?DV:""),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 _ws(){const[e,t]=Ta(),n=e.get("experiment"),r=e.get("review"),{data:s,error:a}=wY(void 0),i=s?.experiments.find(c=>c.id===n),l=c=>{t(c===DV?{}:{experiment:c},{replace:!0})};return a&&rs(a)?o.jsx(Wn,{children:o.jsx(_s,{})}):a&&is(a)?o.jsx(Wn,{children:o.jsx(ys,{resource:"experiments"})}):a?o.jsx(Wn,{children:o.jsx(Bs,{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(Cws,{allOption:!0,value:n??void 0,onValueChange:l,className:"w-80"})})})}),o.jsx(Lt.MainArea,{className:"overflow-visible",children:o.jsx(J0s,{datasetId:i?.datasetId??void 0,experimentId:n??void 0,featuredItemId:r,detailPanelVariant:"overlay"},n??DV)})]})}const Ews=20;function Tws({reviewStatus:e}){const t=Qe(),n=Fy({queryKey:["feedback","list",e],queryFn:({pageParam:r})=>t.listFeedback({filters:{reviewStatus:e},pagination:{page:r,perPage:Ews},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 jws({enabled:e}){const t=Qe();return gt({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 Nws(){const e=Qe(),t=Er();return wn({mutationFn:({feedbackId:n,reviewStatus:r})=>e.updateFeedbackReviewStatus({feedbackId:n,reviewStatus:r}),onSuccess:()=>t.invalidateQueries({queryKey:["feedback"]})})}const Cnt="minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) auto";function Iws({items:e,isLoading:t,error:n}){const r=Br(),[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}=no({count:l.length});return t?o.jsx(Lo,{columns:Cnt}):n?o.jsx(Bs,{title:"Failed to load dataset items",message:n.message}):e.length===0?o.jsx(yr,{iconSlot:o.jsx(Cs,{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(fe,{columns:Cnt,fit:"container",scrollRef:c,children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{children:"Item"}),o.jsx(fe.TopCell,{children:"Experiment"}),o.jsx(fe.TopCell,{children:"Dataset"}),o.jsx(fe.TopCell,{children:"Trace"}),o.jsx(fe.TopCell,{children:" "})]}),l.length===0?o.jsx(fe.NoMatch,{message:"No dataset items match your search"}):l.map((d,f)=>{const h=RTe(d.experimentId,d.id);return o.jsxs(fe.RowWrapper,{children:[o.jsxs(fe.RowButton,{colEnd:-2,onClick:()=>r(h),...u(f),children:[o.jsx(fe.TextCell,{font:"mono",children:d.itemId}),o.jsx(fe.TextCell,{font:"mono",children:d.experimentId}),o.jsx(fe.TextCell,{font:"mono",children:d.datasetId}),o.jsx(fe.TextCell,{font:"mono",children:d.traceId??"—"})]}),o.jsx(fe.ActionsCell,{className:"pl-2",children:d.traceId?o.jsx(ae,{as:gi,to:`/traces?traceId=${encodeURIComponent(d.traceId)}`,variant:"ghost",size:"sm",children:"Open trace"}):null})]},d.id)})]})})]})}function Aws(){return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(yr,{iconSlot:o.jsx(Cs,{}),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(ae,{as:gi,to:"/experiments",variant:"outline",children:"Go to experiments"}),o.jsx(ae,{as:gi,to:"/traces",variant:"outline",children:"Go to traces"})]})})})}function S0e(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 _nt="minmax(0, 2fr) minmax(0, 1fr) auto minmax(0, 1fr) auto auto";function Rws({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=>S0e(x).toLowerCase().includes(h)||(IV(x)??"").toLowerCase().includes(h)||(x.traceId??"").toLowerCase().includes(h)||(x.feedbackSource??"").toLowerCase().includes(h)):e,{containerRef:m,getRowProps:v}=no({count:p.length}),{inView:y,setRef:b}=i0({root:m});return g.useEffect(()=>{y&&r&&!s&&a()},[y,r,s,a]),t?o.jsx(Lo,{columns:_nt}):n?o.jsx(Bs,{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, author, trace or source"})}),o.jsx("div",{className:"min-h-0 overflow-hidden",children:o.jsxs(fe,{columns:_nt,fit:"container",scrollRef:m,children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{children:"Feedback"}),o.jsx(fe.TopCell,{children:"Author"}),o.jsx(fe.TopCell,{children:"Source"}),o.jsx(fe.TopCell,{children:"Trace"}),o.jsx(fe.TopCell,{children:"Date"}),o.jsx(fe.TopCell,{children:" "})]}),p.length===0?o.jsx(fe.NoMatch,{message:h?"No feedback matches your search":"No feedback needs review"}):p.map((x,w)=>{const k=x.feedbackId,O=IV(x);return o.jsxs(fe.RowWrapper,{children:[o.jsxs(fe.RowButton,{colEnd:-2,disabled:!x.traceId,featured:k!==void 0&&k===u,onClick:()=>c(x),...v(w),children:[o.jsx(fe.TextCell,{className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:S0e(x)})}),o.jsx(fe.Cell,{className:"flex gap-2",children:O&&o.jsxs(o.Fragment,{children:[o.jsx(Iy,{name:O,src:x.author?.avatarUrl,size:"sm"}),o.jsx("span",{className:"truncate",children:O})]})}),o.jsx(fe.Cell,{children:o.jsx(mt,{size:"sm",children:x.feedbackSource})}),o.jsx(fe.TextCell,{font:"mono",className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:x.traceId??"—"})}),o.jsx(fe.TextCell,{children:dr(x.timestamp,"MMM d, h:mm a")})]}),o.jsx(fe.ActionsCell,{className:"pl-2",children:k?o.jsx(ae,{variant:"ghost",size:"sm",onClick:()=>i(k),disabled:l===k,children:"Mark reviewed"}):null})]},k??`${String(x.timestamp)}-${x.traceId}`)}),o.jsx(fe.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:b})]})})]})}function Pws({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}=JHt({traceId:t,anchorSpanId:null,listMode:"traces"}),h=IV(e)??e.feedbackUserId;return o.jsx(bY,{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(fn,{className:"max-h-[33vh]",children:[o.jsxs(fn.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(fn.Heading,{children:"Feedback"}),o.jsx(mt,{variant:"neutral",emphasis:"muted",children:e.feedbackType}),e.feedbackSource&&o.jsx(mt,{variant:"neutral",emphasis:"muted",children:e.feedbackSource})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[h&&o.jsxs(o.Fragment,{children:[o.jsx(Iy,{name:h,src:e.author?.avatarUrl,size:"sm"}),o.jsx(me,{as:"span",variant:"ui-sm",className:"text-neutral5 truncate",children:h}),o.jsx(me,{as:"span",variant:"ui-sm",className:"text-neutral3",children:"·"})]}),o.jsx(me,{as:"span",variant:"ui-sm",className:"text-neutral3",children:dr(new Date(e.timestamp),"MMM dd, yyyy HH:mm:ss")})]})]}),o.jsx(ps,{className:"ml-auto shrink-0",children:o.jsxs(ae,{variant:"primary",size:"sm",onClick:i,disabled:l,children:[o.jsx(Ke,{children:o.jsx(Dr,{})}),"Mark as reviewed"]})})]}),o.jsx(fn.Content,{children:o.jsx(me,{as:"p",variant:"ui-md",className:"text-neutral5 whitespace-pre-wrap",children:S0e(e)})})]}),o.jsx("section",{className:"min-h-0 overflow-hidden",children:o.jsx(RRe,{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:p})=>o.jsx(tY,{traceId:p}),spanFeedbackTabSlot:({traceId:p,spanId:m})=>p&&m?o.jsx(ARe,{traceId:p,spanId:m},`${p}:${m}`):null})})]})})}const zWt=100;async function $ws(e){const t=[];let n=0,r=!0;for(;r;){const s=await e.listExperiments({page:n,perPage:zWt});t.push(...s.experiments),r=s.pagination.hasMore,n+=1}return t}async function Mws(e,t,n){const r=[];let s=0,a=!0;for(;a;){const i=await e.listDatasetExperimentResults(t,n,{page:s,perPage:zWt});r.push(...i.results),a=i.pagination.hasMore,s+=1}return r}function Dws(){const e=Qe();return gt({queryKey:["inbox-dataset-review-items"],queryFn:async()=>{const t=await $ws(e);return(await Promise.all(t.map(async r=>{const s=r.datasetId;return s?(await Mws(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 Lws({enabled:e}){const t=Qe();return gt({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 Fws(e){return e==="dataset"||e==="feedback"}function zws(){const[e,t]=Ta(),n=e.get("tab"),r=Fws(n)?n:"feedback",s=Tws({reviewStatus:"needs-review"}),a=Nws(),i=Dws(),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,O=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(Ml,{children:[o.jsx(Ml.Title,{children:"Inbox"}),o.jsx(Ml.Description,{children:"Items waiting for review"})]})}),o.jsx(Lt.MainArea,{className:"min-h-0 overflow-hidden",children:u?o.jsx(Aws,{}):o.jsxs(vc,{defaultTab:"feedback",value:r,onValueChange:_,className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[o.jsxs(gc,{variant:"pill-ghost",children:[o.jsxs(zr,{value:"feedback",className:"px-3 py-2.5",children:[o.jsx(Ke,{size:"sm",children:o.jsx(u3,{})}),o.jsx(me,{variant:"ui-sm",className:"text-inherit",children:"Feedback"}),c>0&&o.jsx(mt,{variant:"yellow",size:"sm",children:c})]}),o.jsxs(zr,{value:"dataset",className:"px-3 py-2.5",children:[o.jsx(Ke,{size:"sm",children:o.jsx(LC,{})}),o.jsx(me,{variant:"ui-sm",className:"text-inherit",children:"Dataset items"}),l.length>0&&o.jsx(mt,{variant:"yellow",size:"sm",children:l.length})]})]}),o.jsx(vs,{value:"feedback",className:"h-full min-h-0 pt-4",children:o.jsx(Rws,{items:s.items,isLoading:s.isLoading,error:s.error??void 0,hasNextPage:s.hasNextPage,isFetchingNextPage:s.isFetchingNextPage,fetchNextPage:s.fetchNextPage,onMarkReviewed:O,pendingFeedbackId:a.isPending?a.variables?.feedbackId:void 0,onSelect:v,selectedFeedbackId:d})}),o.jsx(vs,{value:"dataset",className:"h-full min-h-0 pt-4",children:o.jsx(Iws,{items:l,isLoading:i.isLoading,error:i.error??void 0})})]})})]}),k&&f&&b&&o.jsx(Pws,{feedback:b,traceId:f,initialSpanId:h,onClose:m,onPrevious:x?()=>v(x):void 0,onNext:w?()=>v(w):void 0,onMarkReviewed:()=>d&&O(d),isMarkingReviewed:a.isPending},`${d}:${f}`)]})}function Bws({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 BWt({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("ul",{className:"space-y-1",children:e.map(s=>o.jsx(Bws,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function Uws({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(BWt,{connections:a,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function qws({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(Uws,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):o.jsx(BWt,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?o.jsx("p",{className:"text-red-600",children:String(c)}):null]})}function Vws({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 Ent=e=>e.authorId?.trim()||"shared",Hws=(e,t)=>{if(!t||new Set(e.map(Ent)).size<=1)return null;const r=new Map;for(const a of e){const i=Ent(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},Wws=["*","tool-providers:*","tool-providers:admin"];function Zws(){const{data:e}=Bm();return e?.permissions?.some(t=>Wws.includes(t))??!1}function Gws(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,a]=g.useState(""),i=iA(),l=kG(e||null),c=ULt(e||null,n||null),u=BLt(),d=LLt(),f=Zws(),h=i.data?.providers??[],p=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),v=g.useMemo(()=>Hws(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(Vws,{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(qws,{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 Qws({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(Zh,{className:"h-10 w-10"}),o.jsx("h1",{className:"text-neutral6 text-xl font-semibold",children:e})]}),t,n,r]})})}function UWt({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:a}=fc(),{mutate:i,isPending:l,error:c}=GMr(),{mutate:u,isPending:d,error:f}=YMr(),{mutate:h,isPending:p}=BDt(),[m,v]=g.useState(n),[y,b]=g.useState(""),[x,w]=g.useState(""),[k,O]=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,R=A?l:d,L=A?c:f,D=()=>{t?t():e?window.location.href=e:window.location.href=AG("/")},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")},F=_.description?o.jsxs("div",{className:"border-border1 bg-surface1 flex items-start gap-2.5 rounded-md border p-3",children:[o.jsx(qd,{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(Qws,{title:A?"Sign in to Mastra Studio":"Create your account",description:F,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=>O(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(ae,{type:"submit",disabled:R,className:"w-full",size:"lg",children:R?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(ae,{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 Yws(){const[e]=Ta(),t=Br(),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(UWt,{redirectUri:n,onSuccess:i,initialMode:s,errorMessage:a})}const yh=Ra.KeyValueList;function Kws(e){return e instanceof Date?e:new Date(e)}function Xws({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=Kws(e.timestamp),p=e.traceId,m=e.spanId;return o.jsxs(Ra,{collapsed:d,children:[o.jsxs(Ra.Header,{children:[o.jsxs(Ra.Heading,{children:["Log ",o.jsx("b",{children:dr(h,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(ps,{className:"ml-auto shrink-0",children:[l&&o.jsx(ae,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(lI,{}):o.jsx(zV,{})}),o.jsxs(ps,{spacing:"close",children:[o.jsx(ae,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(J1,{})}),o.jsx(ae,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(FV,{})})]}),o.jsx(Ra.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(Ra.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(ps,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(ae,{size:"md",className:"min-w-0 flex-1 overflow-hidden",onClick:()=>n?.(p),children:[o.jsx(Bd,{}),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(ps,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(ae,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!p||!r,onClick:()=>p&&r?.(p,m),children:[o.jsx(Bd,{}),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(yh,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(yh.Key,{children:"Entity Type"}),o.jsx(yh.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(yh.Key,{children:"Entity Name"}),o.jsx(yh.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(yh.Key,{children:"Service"}),o.jsx(yh.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(yh.Key,{children:"Environment"}),o.jsx(yh.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(yh.Key,{children:"Source"}),o.jsx(yh.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(yh.Key,{children:v}),o.jsx(yh.Value,{children:String(y)})]},v))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(Ra.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function Jws({error:e,resource:t,errorTitle:n}){if(rs(e))return o.jsx(_s,{});if(is(e))return o.jsx(ys,{resource:t});if(XL(e))return o.jsx(yr,{iconSlot:o.jsx(Cs,{}),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(KL(e,"logs"))return o.jsx(yr,{iconSlot:o.jsx(Cs,{}),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(Bs,{title:n,message:r??"Unknown error"})}function e1s({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 t1s={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 n1s({level:e}){const t=t1s[e];return o.jsx(co,{children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function r1s({entityType:e,className:t}){const n=K("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case"agent":return o.jsx(uo,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return o.jsx(_u,{className:n,"aria-hidden":!0});case"tool":return o.jsx(qf,{className:n,"aria-hidden":!0});default:return null}}function s1s({entityType:e,entityName:t}){const n=e??"";return o.jsxs(co,{className:"flex min-w-0 items-center gap-2",children:[o.jsx(r1s,{entityType:n}),t?o.jsx("span",{className:"text-ui-smd min-w-0 truncate",children:t}):"-"]})}function a1s({message:e}){return o.jsx(co,{className:"text-ui-smd text-neutral4 min-w-0 truncate font-mono",children:e})}function i1s({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(co,{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(aTe,{font:"mono",children:t})}const Jl=Object.assign(GL,{Top:YL,TopCell:bS,TopCellWithTooltip:lG,TopCellSmart:Z$t,RowWrapper:lTe,RowButton:QL,RowLink:W$t,Spacer:cTe,NoMatch:oG,DateCell:q$t,TimeCell:V$t,LevelCell:n1s,EntityCell:s1s,MessageCell:a1s,DataCell:i1s,NextPageLoading:iG}),Tnt="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",o1s=36,l1s=8;function c1s({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=g.useRef(null),u=XHt({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>o1s,overscan:l1s}),{getRowProps:d}=no({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(Lo,{columns:Tnt});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(Jl,{columns:Tnt,scrollRef:c,className:"min-w-0",children:[o.jsxs(Jl.Top,{children:[o.jsx(Jl.TopCell,{children:"Date"}),o.jsx(Jl.TopCell,{children:"Time"}),o.jsx(Jl.TopCell,{children:"Level"}),o.jsx(Jl.TopCell,{children:"Entity"}),o.jsx(Jl.TopCell,{children:"Message"}),o.jsx(Jl.TopCell,{children:"Data"})]}),e.length===0?o.jsx(Jl.NoMatch,{message:"No logs match your search"}):o.jsxs(o.Fragment,{children:[o.jsx(Jl.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(Jl.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(Jl.DateCell,{timestamp:b.timestamp}),o.jsx(Jl.TimeCell,{timestamp:b.timestamp}),o.jsx(Jl.LevelCell,{level:b.level}),o.jsx(Jl.EntityCell,{entityType:b.entityType,entityName:b.entityName}),o.jsx(Jl.MessageCell,{message:b.message}),o.jsx(Jl.DataCell,{data:b.data})]},x)}),o.jsx(Jl.Spacer,{height:v})]}),o.jsx(Jl.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function u1s({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=>d1s(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(kRe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(wRe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function d1s(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 f1s={"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"},moe="MMM d, yyyy HH:mm",goe="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function h1s({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${f1s[e]}`,description:goe}:t&&n?{title:`No logs between ${dr(t,moe)} and ${dr(n,moe)}`,description:goe}:t?{title:`No logs since ${dr(t,moe)}`,description:goe}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const p1s=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=h1s({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(yr,{iconSlot:o.jsx(Cs,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(ae,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",children:["Logging Documentation ",o.jsx(Fs,{})]})})})},m1s=20,g1s=1e4;function v1s(e,t,n){if(e?.pagination?.hasMore)return n+1}function y1s(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 b1s(e){return KL(e.state.error,"logs")||XL(e.state.error)?!1:g1s}const x1s=({filters:e}={})=>{const t=Qe(),{inView:n,setRef:r}=i0(),s=Fy({queryKey:["logs",e],queryFn:({pageParam:h})=>t.listLogsVNext({pagination:{page:h,perPage:m1s},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:v1s,select:y1s,retry:!1,refetchInterval:b1s}),{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}},x8={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},qWt=[{label:"Agent",entityType:x8.AGENT},{label:"Workflow",entityType:x8.WORKFLOW},{label:"Scorer",entityType:x8.SCORER},{label:"Ingest",entityType:x8.INGEST}],w1s=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],Jx="rootEntityType",rx="datePreset",sx="dateFrom",ax="dateTo",S1s=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"},a5=Object.keys(jl),LRe=new Set(["tags"]),FRe="mastra:logs:saved-filters";function k1s(e,t=FRe){const n=T1s(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 O1s(e=FRe){try{localStorage.removeItem(e)}catch{}}function jnt(e=FRe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function C1s(e){if(e.has(rx)||e.has(sx)||e.has(ax)||e.has(Jx))return!0;for(const t of a5)if(e.has(jl[t]))return!0;return!1}function _1s({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:qWt.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:w1s.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 E1s(e){const t=[],n=new Map([[Jx,"rootEntityType"]]);for(const s of a5)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),LRe.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 T1s(e){const t=new URLSearchParams,n=e.get(Jx);n&&t.set(Jx,n);for(const r of a5){const s=jl[r];if(LRe.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 j1s(e,t){e.delete(Jx);for(const n of a5)e.delete(jl[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(Jx,n.value);continue}const r=jl[n.fieldId];if(r){if(LRe.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 N1s({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 I1s(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 A1s="Filters setting for Logs saved",R1s="Filters setting for Logs cleared up";function P1s(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=g.useState(()=>jnt(r)!==null),c=g.useCallback(()=>{k1s(e,r),l(!0);const f=s?.saved??A1s;f!==!1&&Ve.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{O1s(r),l(!1);const f=s?.cleared??R1s;f!==!1&&Ve.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(a||d.current||(d.current=!0,C1s(e)))return;const f=jnt(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 $1s(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 M1s(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,$1s(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function D1s(e,t,n,r){const s=g.useMemo(()=>M1s(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 k0e="logId",O0e="traceId",C0e="spanId",FP=1440*60*1e3,L1s={"last-24h":FP,"last-3d":3*FP,"last-7d":7*FP,"last-14d":14*FP,"last-30d":30*FP};function w8(e){e.delete(k0e),e.delete(O0e),e.delete(C0e)}function F1s(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const O=e.get(rx);return O&&S1s.has(O)?O:"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 O=L1s[s];return O?new Date(Date.now()-O):void 0},[s,a]),c=g.useMemo(()=>{if(s!=="custom"||!i)return;const O=new Date(i);return Number.isNaN(O.getTime())?void 0:O},[s,i]),u=g.useRef(s);u.current=s;const d=e.get(k0e),f=e.get(O0e),h=e.get(C0e),p=g.useMemo(()=>qWt.find(O=>O.entityType===e.get(Jx)),[e]),m=g.useMemo(()=>E1s(e),[e]),v=g.useCallback(O=>{t(_=>{const T=new URLSearchParams(_);for(const[E,N]of Object.entries(O)){const I=E==="logId"?k0e:E==="traceId"?O0e:C0e;N?T.set(I,N):T.delete(I)}return T},{replace:!0})},[t]),y=g.useCallback(O=>{t(_=>{const T=new URLSearchParams(_);return j1s(T,O),w8(T),T},{replace:!0})},[t]),b=y,x=g.useCallback((O,_)=>{if(u.current!=="custom")return;const T=_==="from"?sx:ax;t(E=>{const N=new URLSearchParams(E);return O?N.set(T,O.toISOString()):N.delete(T),w8(N),N},{replace:!0})},[t]),w=g.useCallback(O=>{u.current=O,t(_=>{const T=new URLSearchParams(_);return O==="last-24h"?(T.delete(rx),T.delete(sx),T.delete(ax)):O==="custom"?T.set(rx,"custom"):(T.set(rx,O),T.delete(sx),T.delete(ax)),w8(T),T},{replace:!0})},[t]),k=g.useCallback(()=>{t(O=>{const _=new URLSearchParams(O);_.delete(Jx);for(const T of a5)_.delete(jl[T]);return _.delete(rx),_.delete(sx),_.delete(ax),w8(_),_},{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=Ra.KeyValueList;function z1s({spanId:e,span:t,isLoading:n,onClose:r}){const s=sRe(t?.startedAt,t?.endedAt),a=_tt(t?.startedAt),i=_tt(t?.endedAt);return o.jsxs(Ra,{children:[o.jsxs(Ra.Header,{children:[o.jsxs(Ra.Heading,{children:["Span ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Ra.CloseButton,{onClick:r})]}),n?o.jsx(Ra.LoadingData,{children:"Loading span..."}):t?o.jsxs(Ra.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(Ra.CodeSection,{title:"Input",icon:o.jsx(u1,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(Ra.CodeSection,{title:"Output",icon:o.jsx(Rg,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(Ra.CodeSection,{title:"Metadata",icon:o.jsx(nc,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(Ra.CodeSection,{title:"Attributes",icon:o.jsx(nc,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(Ra.NoData,{children:"Span not found."})]})}function B1s({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:a}){const i=g.useMemo(()=>X4(t??[]),[t]),[l,c]=g.useState([]);g.useEffect(()=>{i.length>0&&c(XQ(i))},[i]);const u=d=>{s?.(a===d?void 0:d)};return o.jsxs(Ra,{children:[o.jsxs(Ra.Header,{children:[o.jsxs(Ra.Heading,{children:["Trace ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Ra.CloseButton,{onClick:r})]}),n?o.jsx(Ra.LoadingData,{children:"Loading trace..."}):i.length===0?o.jsx(Ra.NoData,{children:"No spans found for this trace."}):o.jsx(Ra.Content,{children:o.jsx(aRe,{hierarchicalSpans:i,onSpanClick:u,selectedSpanId:a??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}function U1s(){const[e,t]=Ta(),n=F1s(e,t),r=P1s(e,t),[s,a]=g.useState(),[i,l]=g.useState(!1),{data:c=[],isPending:u}=NRe(),{data:d=[],isPending:f}=ERe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:h=[],isPending:p}=TRe(),{data:m=[],isPending:v}=jRe(),y=g.useMemo(()=>_1s({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(()=>N1s({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:O,hasNextPage:_,setEndOfListElement:T}=x1s({filters:b}),{logIdMap:E,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:R}=D1s(x,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:L,isLoading:D}=J4(n.featuredTraceId??null),{data:B,isLoading:H}=JQ(n.featuredTraceId??"",n.featuredSpanId??""),q=g.useCallback(()=>n.applyFilterTokens(I1s(y,n.filterTokens)),[y,n]),F=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]),z=g.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),P=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(e4,{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(ORe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:w,onStartTextFilter:a})]})}),o.jsx(u1s,{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(Jws,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const W=!!n.selectedEntityOption||n.filterTokens.length>0;return x.length===0&&!w&&!W?o.jsxs(Lt,{width:"wide",height:"full",children:[U,o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(p1s,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Lt,{width:"wide",height:"full",children:[U,o.jsx(e1s,{logCollapsed:i,listSlot:o.jsx(c1s,{logs:x,isLoading:w,isFetchingNextPage:O,hasNextPage:_,setEndOfListElement:T,logIdMap:E,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(Xws,{log:N,onClose:F,onTraceClick:V,onSpanClick:M,onPrevious:A,onNext:R,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(B1s,{traceId:n.featuredTraceId,spans:L?.spans,isLoading:D,onClose:G,onSpanSelect:P,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(z1s,{spanId:n.featuredSpanId,span:B?.span,isLoading:H,onClose:z}):null})]})}function q1s({server:e,rowProps:t}){const{paths:n,Link:r}=un(),a=Qe().options.baseUrl,i=a?`${a}/api/mcp/${e.id}/sse`:"",{data:l}=dqt(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=Pd(e.name,50);return o.jsxs(fe.RowLink,{to:n.mcpServerLink(e.id),LinkComponent:r,...t,children:[o.jsx(fe.NameCell,{children:h}),o.jsx(fe.DescriptionCell,{children:i}),o.jsx(fe.TextCell,{className:"text-center",children:d||""}),o.jsx(fe.TextCell,{className:"text-center",children:u||""}),o.jsx(fe.TextCell,{className:"text-center",children:f||""})]})}function V1s({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}=no({count:r.length});return t?o.jsx(Lo,{columns:"auto 1fr auto auto auto"}):o.jsxs(fe,{columns:"auto 1fr auto auto auto",scrollRef:s,children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{children:"Name"}),o.jsx(fe.TopCell,{children:"URL"}),o.jsx(fe.TopCellSmart,{long:"Agents",short:o.jsx(uo,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(fe.TopCellSmart,{long:"Tools",short:o.jsx(qf,{}),tooltip:"Tools",className:"text-center"}),o.jsx(fe.TopCellSmart,{long:"Workflows",short:o.jsx(_u,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(fe.NoMatch,{message:"No MCP Servers match your search"}):null,r.map((i,l)=>o.jsx(q1s,{server:i,rowProps:a(l)},i.id))]})}const H1s=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(yr,{iconSlot:o.jsx(Cs,{}),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(ae,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(Fs,{})]})})}),W1s=()=>{const{data:e=[],isLoading:t,error:n}=qQ(),[r,s]=g.useState("");return n&&rs(n)?o.jsx(Wn,{children:o.jsx(_s,{})}):n&&is(n)?o.jsx(Wn,{children:o.jsx(ys,{resource:"MCP servers"})}):n?o.jsx(Wn,{children:o.jsx(Bs,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(Wn,{children:o.jsx(H1s,{})}):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(V1s,{mcpServers:e,isLoading:t,search:r})]})},Z1s=(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 G1s({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=un(),i=g.useMemo(()=>Z1s(e,t),[e,t]),l=g.useMemo(()=>i.filter(d=>d.id.toLowerCase().includes(r.toLowerCase())),[i,r]),{containerRef:c,getRowProps:u}=no({count:l.length});return n?o.jsx(Lo,{columns:"auto 1fr auto"}):o.jsxs(fe,{columns:"auto 1fr auto",scrollRef:c,children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{children:"Name"}),o.jsx(fe.TopCell,{children:"Description"}),o.jsx(fe.TopCellSmart,{long:"Agents",short:o.jsx(uo,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(fe.NoMatch,{message:"No Tools match your search"}):null,l.map((d,f)=>{const h=Pd(d.id,50),p=Pd(d.description??"",200),m=d.agents.length;return o.jsxs(fe.RowLink,{to:s.toolLink(d.id),LinkComponent:a,...u(f),children:[o.jsx(fe.NameCell,{children:h}),o.jsx(fe.DescriptionCell,{children:p}),o.jsx(fe.TextCell,{className:"text-center",children:m||""})]},d.id)})]})}const Q1s=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(yr,{iconSlot:o.jsx(Cs,{}),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(ae,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(Fs,{})]})})}),Y1s=()=>{const e=Qe();return wn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new WC;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}}})},K1s=({toolId:e})=>{const{canExecute:t}=Co(),n=t("tools"),{data:r={}}=Um(),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}=lMr(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=Y1s(),{requestContext:h}=bs();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?bm(Rx(c?.inputSchema)):Ss({});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(LAe,{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(me,{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(me,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function X1s({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}=sA(),{data:p={},isLoading:m,isError:v,error:y}=Um(),{navigate:b,paths:x}=un();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})),O=_=>{t?t(_):_&&_!==e&&b(x.toolLink(_))};return o.jsx(zo,{options:k,value:e,onValueChange:O,placeholder:d||m?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||d||m||f||v,variant:l,size:c})}const J1s=({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(me,{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(me,{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(mt,{icon:o.jsx(BVt,{}),size:"sm",children:"Version"}),o.jsx(mt,{size:"sm",children:t.version_detail.version})]}),o.jsx(me,{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(mt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"HTTP"}),children:"Regular HTTP Endpoint"}),o.jsx(me,{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(me,{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(mt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"SSE"}),children:"Server-Sent Events"}),o.jsx(me,{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(me,{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(mt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"CLI"}),children:"Command Line"}),o.jsx(me,{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(me,{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(eSs,{server:t})})]})},eSs=({server:e})=>{const{data:t={},isLoading:n}=dqt(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(Ke,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx($_,{})}),o.jsx(me,{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(nSs,{tool:a,serverId:e.id},s)})})]})};function tSs(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 nSs=({tool:e,serverId:t})=>{const n=g.useRef(null),{Link:r,paths:s}=un(),a=xqt[e.toolType||"tool"],i=tSs(e._meta);return o.jsxs(Gf,{onClick:()=>n.current?.click(),children:[o.jsx(zLt,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Yf,{children:[o.jsx(Qf,{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(mt,{size:"xs",children:"App"})]})}),o.jsx(cp,{children:e.description})]})]})},rSs=()=>{const{serverId:e}=fr(),{data:t=[],isLoading:n}=qQ(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(J1s,{isLoading:n,server:r})})};function sSs(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 aSs=({toolId:e,serverId:t})=>{const{canExecute:n}=Co(),r=n("tools"),s=Qe(),{data:a,isLoading:i,error:l}=DAe(t,e),{mutateAsync:c,isPending:u,data:d}=dls(t,e),f=a?sSs(a._meta):void 0,{data:h}=gt({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(me,{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(me,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let v;try{v=bm(a.inputSchema)}catch(y){console.error("Error processing input schema:",y),Ve.error("Failed to process tool input schema."),v=Ss({})}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(uqt,{html:h,toolName:a.name??a.id,onToolCall:p})}),o.jsx(LAe,{executionResult:d,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},iSs=()=>{const{serverId:e,toolId:t}=fr(),{data:n,isLoading:r}=DAe(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(aSs,{toolId:t,serverId:e})})},VWt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],nI="rootEntityType",rI={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"},SY=Object.keys(rI),zRe="mastra:metrics:saved-filters";function oSs(e){const t=fSs(e);try{localStorage.setItem(zRe,t.toString())}catch{}}function lSs(){try{localStorage.removeItem(zRe)}catch{}}function HWt(){try{const e=localStorage.getItem(zRe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function cSs(e){if(e.has(nI))return!0;for(const t of SY)if(e.has(rI[t]))return!0;return!1}function uSs({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:VWt.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 dSs(e){const t=[],n=new Map([[nI,"rootEntityType"]]);for(const s of SY)n.set(rI[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 fSs(e){const t=new URLSearchParams,n=e.getAll(nI);for(const r of n)t.append(nI,r);for(const r of SY){const s=rI[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function hSs(e,t){e.delete(nI);for(const n of SY)e.delete(rI[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?nI:rI[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 pSs="Any";function Nnt(e){const t=e.trim();return t===""||t===pSs}const mSs=new Set(VWt.map(e=>e.entityType));function Int(e){const t=e.trim();return mSs.has(t)?t:void 0}function gSs(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=>!Nnt(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?Int(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(Nnt(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=Int(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const WWt=[{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"}],vSs=new Set(WWt.map(e=>e.value));function ySs(e){return typeof e=="string"&&(vSs.has(e)||e==="custom")}const ZWt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function kY(){return g.useContext(ZWt)}function bSs(e,t){return e!=="custom"?WWt.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 xSs({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(()=>gSs(d),[d]),h=g.useMemo(()=>JSON.stringify(f),[f]),p=bSs(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(ZWt.Provider,{value:m,children:e})}const wSs=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function SSs(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 kSs(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 OSs(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=kY(),s=g.useRef(e);s.current=e;const a=g.useRef(n);return a.current=n,o.jsx(e4,{preset:SSs(e),onPresetChange:i=>{const l=kSs(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:wSs})}const _0e=1440*60*1e3,CSs={"24h":_0e,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function _Ss(e,t,n){if(e!=="custom"){const r=CSs[e]??_0e;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-_0e),end:t?.to??new Date(n)}}function Wm(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=kY(),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(()=>_Ss(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 GWt(){const e=Qe(),{filters:t,filterKey:n}=Wm();return gt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function i5({href:e,LinkComponent:t="a"}){return o.jsx(ae,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(rc,{})})}function ESs({href:e,LinkComponent:t="a"}){return o.jsx(ae,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(ren,{})})}function TSs(e){return e==="agents"||e==="workflows"||e==="tools"}function Ant(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 jSs(e){const t=e;return typeof t?.tsMs=="number"&&Number.isFinite(t.tsMs)}const NSs=[{dataKey:"p50",label:"p50",color:Qh.blue,aggregate:e=>({value:Ant(e,"p50"),suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:Qh.yellow,aggregate:e=>({value:Ant(e,"p95"),suffix:"avg ms"})}];function voe({data:e,onPointClick:t}){return e.length===0?o.jsx(Vt.NoData,{message:"No latency data yet"}):o.jsx(LD,{data:e,series:NSs,onPointClick:t?n=>jSs(n)?t(n):void 0:void 0})}function ISs({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(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(Vt.Summary,{value:y,label:"Avg p50"}),p?o.jsx(Vt.Actions,{children:p}):null]}),t?o.jsx(Vt.Loading,{}):n?o.jsx(Vt.Error,{message:"Failed to load latency data"}):o.jsx(Vt.Content,{children:m?o.jsxs(vc,{value:h,onValueChange:b=>{TSs(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(gc,{children:[o.jsx(zr,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(zr,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(zr,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(vs,{value:"agents",children:o.jsx(voe,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(vs,{value:"workflows",children:o.jsx(voe,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(vs,{value:"tools",children:o.jsx(voe,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Vt.NoData,{message:"No latency data yet"})})]})}function ASs(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 RSs(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 QWt(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=ASs(s);l&&e.set(t,l)}function Ro(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function YWt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function Rnt({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const a=new URLSearchParams;a.set(qw,"branches"),QWt(a,Vw,VT,HT,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Kx,i),r.status&&a.set(Xx,r.status),Ro(a,Tl.entityName,r.entityName??n.entityName),Ro(a,Tl.threadId,r.threadId??n.threadId),Ro(a,Tl.resourceId,r.resourceId??n.resourceId),Ro(a,Tl.entityId,n.entityId),Ro(a,Tl.runId,n.runId),Ro(a,Tl.sessionId,n.sessionId),Ro(a,Tl.requestId,n.requestId),Ro(a,Tl.userId,n.userId),Ro(a,Tl.organizationId,n.organizationId),Ro(a,Tl.experimentId,n.experimentId),Ro(a,Tl.serviceName,n.serviceName),Ro(a,Tl.environment,n.environment),YWt(a,Tl.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function PSs({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;QWt(a,rx,sx,ax,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Jx,i),Ro(a,jl.entityName,r.entityName??n.entityName),Ro(a,jl.threadId,r.threadId??n.threadId),Ro(a,jl.resourceId,r.resourceId??n.resourceId),Ro(a,jl.runId,n.runId),Ro(a,jl.sessionId,n.sessionId),Ro(a,jl.requestId,n.requestId),Ro(a,jl.userId,n.userId),Ro(a,jl.organizationId,n.organizationId),Ro(a,jl.experimentId,n.experimentId),Ro(a,jl.serviceName,n.serviceName),Ro(a,jl.environment,n.environment),YWt(a,jl.tags,n.tags),r.status==="error"&&a.append(jl.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function TA(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=kY(),a=g.useCallback((c={})=>Rnt({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=g.useCallback((c={})=>PSs({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=RSs(u,d);return Rnt({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const KWt="1h";async function yoe(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:KWt,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 $Ss(){const e=Qe(),{filters:t,filterKey:n}=Wm();return gt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([yoe(e,"mastra_agent_duration_ms",t),yoe(e,"mastra_workflow_duration_ms",t),yoe(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:KWt}}})}const Pnt={agents:Ku.AGENT,workflows:Ku.WORKFLOW_RUN,tools:Ku.TOOL};function MSs(){const{data:e,isLoading:t,isError:n}=$Ss(),{getTracesHref:r,getBucketTracesHref:s}=TA(),{Link:a}=un(),i=Br();return o.jsx(ISs,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:Pnt[l]},c.tsMs,"1h"))},actions:l=>o.jsx(i5,{href:r({rootEntityType:Pnt[l]}),LinkComponent:a})})}function DSs(e){return e==="threads"||e==="resources"}function boe(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function LSs({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(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&o.jsx(Vt.Summary,{value:h.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&o.jsx(Vt.Summary,{value:p.toLocaleString(),label:"Total threads"}),v?o.jsx(Vt.Actions,{children:v}):null]}),m.isLoading?o.jsx(Vt.Loading,{}):m.isError?o.jsx(Vt.Error,{message:"Failed to load memory data"}):o.jsx(Vt.Content,{children:o.jsxs(vc,{defaultTab:"threads",value:i,onValueChange:y=>{DSs(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(gc,{children:[o.jsx(zr,{value:"threads",children:"Threads"}),o.jsx(zr,{value:"resources",children:"Resources"})]}),o.jsx(vs,{value:"threads",children:d?o.jsxs(fe,{columns:"auto auto auto auto auto",...v0e,children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(fe.RowHeaderCell,{className:"text-ui-sm",children:boe(y.threadId)}),o.jsx(fe.NumberCell,{children:y.resourceId?boe(y.resourceId):"—"}),o.jsx(fe.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(fe.NumberCell,{children:y.tokens>0?ol(y.tokens):"—"}),o.jsx(fe.NumberCell,{children:y.cost!=null?Gh(y.cost,y.costUnit):"—"})]});return b?o.jsx(fe.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(fe.RowStatic,{children:x},y.key)})]}):o.jsx(Vt.NoData,{message:"No thread activity yet"})}),o.jsx(vs,{value:"resources",children:f?o.jsxs(fe,{columns:"auto auto auto auto",...v0e,children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(fe.RowHeaderCell,{className:"text-ui-sm",children:boe(y.resourceId)}),o.jsx(fe.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(fe.NumberCell,{children:y.tokens>0?ol(y.tokens):"—"}),o.jsx(fe.NumberCell,{children:y.cost!=null?Gh(y.cost,y.costUnit):"—"})]});return b?o.jsx(fe.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(fe.RowStatic,{children:x},y.key)})]}):o.jsx(Vt.NoData,{message:"No resource activity yet"})})]})})]})}const xoe=20;function FSs(){const e=Qe(),{filters:t,filterKey:n}=Wm();return gt({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:xoe}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:xoe}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:xoe})]),l=new Map,c=d=>_A(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 woe=20;function zSs(){const e=Qe(),{filters:t,filterKey:n}=Wm();return gt({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:woe}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:woe}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:woe})]),l=new Map,c=d=>_A(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 BSs(){const e=FSs(),t=zSs(),{getTracesHref:n}=TA(),{Link:r}=un();return o.jsx(LSs,{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 o5({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 USs(){const e=Qe(),{filters:t,filterKey:n}=Wm();return gt({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 qSs(){const e=Qe(),{filters:t,filterKey:n}=Wm();return gt({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 VSs(){const e=Qe(),{filters:t,filterKey:n}=Wm();return gt({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 HSs(){const e=Qe(),{filters:t,filterKey:n}=Wm();return gt({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 WSs(){const{data:e,isLoading:t,isError:n}=GWt();return o.jsx(o5,{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 ZSs(){const{data:e,isLoading:t,isError:n}=VSs();return o.jsx(o5,{label:"Total Model Cost",value:e?.cost!=null?Gh(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?Gh(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function GSs(){const{data:e,isLoading:t,isError:n}=HSs();return o.jsx(o5,{label:"Total Tokens",value:e?.value!=null?ol(e.value):null,prevValue:e?.previousValue!=null?ol(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function QSs(){const{data:e,isLoading:t,isError:n}=qSs();return o.jsx(o5,{label:"Total Threads",value:e?.value!=null?ol(e.value):null,prevValue:e?.previousValue!=null?ol(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function YSs(){const{data:e,isLoading:t,isError:n}=USs();return o.jsx(o5,{label:"Total Resources",value:e?.value!=null?ol(e.value):null,prevValue:e?.previousValue!=null?ol(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function KSs({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=>XSs(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(kRe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(wRe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function XSs(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 JSs({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const i=!!e&&e.length>0;return o.jsxs(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.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?Gh(l):"—":c.size===1?u=l>0?Gh(l,[...c][0]):"—":u="Mixed",o.jsx(Vt.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(Vt.Actions,{children:s}):null]}),t?o.jsx(Vt.Loading,{}):n?o.jsx(Vt.Error,{message:"Failed to load model usage data"}):o.jsx(Vt.Content,{children:i?o.jsxs(fe,{columns:"auto auto auto auto auto auto",...v0e,children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{sticky:"start",children:"Model"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(fe.RowHeaderCell,{className:"text-ui-sm",children:l.model}),o.jsx(fe.NumberCell,{children:l.input}),o.jsx(fe.NumberCell,{children:l.output}),o.jsx(fe.NumberCell,{children:l.cacheRead}),o.jsx(fe.NumberCell,{children:l.cacheWrite}),o.jsx(fe.NumberCell,{highlight:!0,children:l.cost!=null?Gh(l.cost,l.costUnit):"—"})]});return c?o.jsx(fe.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(fe.RowStatic,{children:u},l.model)})]}):o.jsx(Vt.NoData,{message:"No model usage data yet"})})]})}function eks(){const e=Qe(),{filters:t,filterKey:n}=Wm();return gt({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=>_A(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:ol(f.input),output:ol(f.output),cacheRead:ol(f.cacheRead),cacheWrite:ol(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function tks(){const{data:e,isLoading:t,isError:n}=eks(),{getTracesHref:r}=TA(),{Link:s}=un();return o.jsx(JSs,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:Ku.AGENT}),actions:o.jsx(i5,{href:r({rootEntityType:Ku.AGENT}),LinkComponent:s})})}function nks(e){return e==="tokens"||e==="cost"}function rks({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(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&y?o.jsx(Vt.Summary,{value:Gh(v,m),label:"Total cost"}):o.jsx(Vt.Summary,{value:ol(d),label:"Total tokens"})),u&&s?o.jsx(Vt.Actions,{children:s}):null]}),t?o.jsx(Vt.Loading,{}):n?o.jsx(Vt.Error,{message:"Failed to load token usage data"}):o.jsx(Vt.Content,{children:u?o.jsxs(vc,{defaultTab:"tokens",value:i,onValueChange:b=>{nks(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(gc,{children:[o.jsx(zr,{value:"tokens",children:"Tokens"}),o.jsx(zr,{value:"cost",children:"Cost"})]}),o.jsx(vs,{value:"tokens",children:o.jsx(tI,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:Qh.blueDark},{label:"Output",color:Qh.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:ol})}),o.jsx(vs,{value:"cost",children:y?o.jsx(tI,{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:Qh.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>Gh(b,m)}):o.jsx(Vt.NoData,{message:"No cost data yet"})})]}):o.jsx(Vt.NoData,{message:"No token usage data yet"})})]})}function sks(){const e=Qe(),{filters:t,filterKey:n}=Wm();return gt({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=>_A(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 aks(){const{data:e,isLoading:t,isError:n}=sks(),{getTracesHref:r}=TA(),{Link:s}=un();return o.jsx(rks,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:Ku.AGENT,entityName:a.name}),actions:o.jsx(i5,{href:r({rootEntityType:Ku.AGENT}),LinkComponent:s})})}function E0e(e,t=ol){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const iks=[{dataKey:"input",label:"Input tokens",color:Qh.blue,aggregate:E0e("input")},{dataKey:"output",label:"Output tokens",color:Qh.yellow,aggregate:E0e("output")}];function oks(e){return e==="tokens"||e==="cost"}function lks({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,O)=>k+O.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,O)=>k+(O.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:Qh.purple,aggregate:E0e("cost",k=>Gh(k,v))}];return o.jsxs(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Token usage over time",description:x}),u&&(a==="cost"&&b?o.jsx(Vt.Summary,{value:Gh(y,v),label:"Total cost"}):o.jsx(Vt.Summary,{value:ol(d),label:"Total tokens"})),u&&s?o.jsx(Vt.Actions,{children:s}):null]}),n?o.jsx(Vt.Loading,{}):r?o.jsx(Vt.Error,{message:"Failed to load token usage timeline"}):o.jsx(Vt.Content,{children:u?o.jsxs(vc,{defaultTab:"tokens",value:a,onValueChange:k=>{oks(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(gc,{children:[o.jsx(zr,{value:"tokens",children:"Tokens"}),o.jsx(zr,{value:"cost",children:"Cost"})]}),o.jsx(vs,{value:"tokens",children:o.jsx(LD,{data:c,series:iks})}),o.jsx(vs,{value:"cost",children:b?o.jsx(LD,{data:h,series:w}):o.jsx(Vt.NoData,{message:"No cost data yet"})})]}):o.jsx(Vt.NoData,{message:"No token usage data yet"})})]})}function cks(e){return e==="24h"?"1h":"1d"}function uks(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 $nt(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 dks(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function fks(){const e=Qe(),{datePreset:t,filters:n,filterKey:r}=Wm(),s=cks(t);return gt({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 $nt(l,a.series[0],"input"),$nt(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:uks(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:dks(u)}}),interval:s}}})}function hks(){const{data:e,isLoading:t,isError:n}=fks(),{getTracesHref:r}=TA(),{Link:s}=un();return o.jsx(lks,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(i5,{href:r(),LinkComponent:s})})}function Soe({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(tI,{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:Qh.blueDark},{label:"Errors",color:Qh.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:ol})}function pks({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(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(Vt.Summary,{value:ol(f),label:"Total runs"}),u?o.jsx(Vt.Actions,{children:u}):null]}),t?o.jsx(Vt.Loading,{}):n?o.jsx(Vt.Error,{message:"Failed to load trace volume data"}):o.jsx(Vt.Content,{children:d?o.jsxs(vc,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(gc,{children:[o.jsx(zr,{value:"agents",children:"Agents"}),o.jsx(zr,{value:"workflows",children:"Workflows"}),o.jsx(zr,{value:"tools",children:"Tools"})]}),o.jsx(vs,{value:"agents",children:e.agentData.length>0?o.jsx(Soe,{data:e.agentData,rowHrefs:h("agents"),errorHrefs:p("agents"),LinkComponent:i}):o.jsx(Vt.NoData,{message:"No agent data yet"})}),o.jsx(vs,{value:"workflows",children:e.workflowData.length>0?o.jsx(Soe,{data:e.workflowData,rowHrefs:h("workflows"),errorHrefs:p("workflows"),LinkComponent:i}):o.jsx(Vt.NoData,{message:"No workflow data yet"})}),o.jsx(vs,{value:"tools",children:e.toolData.length>0?o.jsx(Soe,{data:e.toolData,rowHrefs:h("tools"),errorHrefs:p("tools"),LinkComponent:i}):o.jsx(Vt.NoData,{message:"No tool data yet"})})]}):o.jsx(Vt.NoData,{message:"No trace volume data yet"})})]})}async function koe(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=_A(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 mks(){const e=Qe(),{filters:t,filterKey:n}=Wm();return gt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([koe(e,"mastra_agent_duration_ms",t),koe(e,"mastra_workflow_duration_ms",t),koe(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const S8={agents:Ku.AGENT,workflows:Ku.WORKFLOW_RUN,tools:Ku.TOOL};function gks(){const{data:e,isLoading:t,isError:n}=mks(),{getTracesHref:r,getLogsHref:s}=TA(),{Link:a}=un();return o.jsx(pks,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:S8[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:S8[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(i5,{href:r({rootEntityType:S8[i]}),LinkComponent:a}),o.jsx(ESs,{href:s({rootEntityType:S8[i],status:"error"}),LinkComponent:a})]})})}const Ooe="period",k8="dateFrom",O8="dateTo";function vks(){const[e,t]=Ta(),n=e.get(Ooe),r=ySs(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(k8)),h=d(e.get(O8));if(!(!f&&!h))return{from:f,to:h}},[r,e.toString()]),a=g.useMemo(()=>dSs(e),[e.toString()]),i=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d==="24h"?h.delete(Ooe):h.set(Ooe,d),d!=="custom"&&(h.delete(k8),h.delete(O8)),h},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d?.from?h.set(k8,d.from.toISOString()):h.delete(k8),d?.to?h.set(O8,d.to.toISOString()):h.delete(O8),h},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return hSs(h,d),h},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,cSs(e)))return;const d=HWt();d&&t(f=>{const h=new URLSearchParams(f);for(const[p,m]of d)h.append(p,m);return h},{replace:!0})},[]),o.jsx(xSs,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(yks,{})})}function yks(){const[e]=Ta(),{error:t,isLoading:n}=GWt(),{filterTokens:r,setFilterTokens:s}=kY(),[a,i]=g.useState(),{supportsMetrics:l,isInMemory:c,isLoading:u}=tWt(),{data:d,isLoading:f}=NRe(),{data:h,isLoading:p}=ERe(),{data:m,isLoading:v}=jRe(),{data:y,isLoading:b}=TRe(),x=g.useMemo(()=>uSs({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(()=>HWt()!==null),O=g.useCallback(()=>{oSs(e),k(!0),Ve.success("Filters setting for Metrics saved")},[e]),_=g.useCallback(()=>{lSs(),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(R=>R.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&&rs(t)?o.jsx(Wn,{children:o.jsx(_s,{})}):t&&is(t)?o.jsx(Wn,{children:o.jsx(ys,{resource:"metrics"})}):t?o.jsx(Wn,{children:o.jsx(Bs,{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(OSs,{}),o.jsx(ORe,{fields:x,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(KSs,{isLoading:n,filterFields:x,filterTokens:r,onFilterTokensChange:s,onClear:E,onRemoveAll:T,onSave:O,onRemoveSaved:w?_:void 0,autoFocusFilterFieldId:a})]}),u?null:l?o.jsxs("div",{className:"grid content-start gap-8 pb-10",children:[c&&o.jsx(An,{variant:"info",title:"Metrics are not persisted",children:o.jsx(An.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(w0e,{children:[o.jsx(WSs,{}),o.jsx(ZSs,{}),o.jsx(GSs,{}),o.jsx(QSs,{}),o.jsx(YSs,{})]}),o.jsxs(w0e,{children:[o.jsx(tks,{}),o.jsx(aks,{}),o.jsx(hks,{}),o.jsx(BSs,{}),o.jsx(gks,{}),o.jsx(MSs,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(yr,{iconSlot:o.jsx(Cs,{}),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(ae,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(Fs,{})]})})})]})}const bks=50;function xks(){const{paths:e}=un(),{isCmsAvailable:t}=CS(),[n,r]=g.useState(""),[s,a]=g.useState(0),{data:i,isLoading:l,error:c,isPlaceholderData:u}=Oqt({page:s,perPage:bks}),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&&rs(c)?o.jsx(Wn,{children:o.jsx(_s,{})}):c&&is(c)?o.jsx(Wn,{children:o.jsx(ys,{resource:"prompt blocks"})}):c?o.jsx(Wn,{children:o.jsx(Bs,{title:"Failed to load prompt blocks",message:c.message})}):d.length===0&&!l&&s===0?o.jsx(Wn,{children:o.jsx(yus,{})}):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(ae,{as:gi,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(Ir,{}),"Create Prompt"]})]})}),o.jsx(vus,{promptBlocks:d,isLoading:l,search:n,currentPage:s,hasMore:f,onNextPage:h,onPrevPage:p})]})}function wks(){return o.jsx(Lt,{width:"narrow",children:o.jsx(Lt.MainArea,{children:o.jsx(rcs,{children:o.jsx(Xxe,{})})})})}const Sks=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:wXt,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:out,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Fs,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:u3,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:dut,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:lut,href:"https://mastra.ai/contact?ref=studio",external:!0}];function kks(){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:Sks.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(Fs,{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 Oks(){const{data:e={},isLoading:t,error:n}=up(),[r,s]=g.useState(""),[a,i]=g.useState("all");if(n&&rs(n))return o.jsx(Wn,{children:o.jsx(_s,{})});if(n&&is(n))return o.jsx(Wn,{children:o.jsx(ys,{resource:"scorers"})});if(n)return o.jsx(Wn,{children:o.jsx(Bs,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(Wn,{children:o.jsx(FHr,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(BHr,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(LHr,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}function Cks(){const{scorerId:e}=fr(),[t,n]=Ta(),r=t.get("scoreId")??void 0,[s,a]=g.useState(r),[i,l]=g.useState(!1),c=Br(),[u,d]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:f,error:h}=yHr(e),{data:p={},isLoading:m,error:v}=Um(),{isLoading:y,error:b}=Ky(),{data:x=[],isLoading:w,error:k,isFetchingNextPage:O,hasNextPage:_,setEndOfListElement:T}=vHr({scorerId:e,entityId:u?.value==="all"?void 0:u?.value,entityType:u?.type==="ALL"?void 0:u?.type}),E=g.useMemo(()=>f?.agentIds?.filter(P=>p[P]).map(P=>({value:P,label:p[P].name,type:"AGENT"}))||[],[f?.agentIds,p]),N=g.useMemo(()=>f?.workflowIds?.map(P=>({value:P,label:P,type:"WORKFLOW"}))||[],[f?.workflowIds]),I=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...E,...N],[E,N]),A=t.get("entity")??"all",R=I.find(P=>P.value===A);R&&R.value!==u?.value&&d(R),g.useEffect(()=>{if(h){const P=h instanceof Error?h.message:"Failed to load scorer";Ve.error(`Error loading scorer: ${P}`)}},[h]),g.useEffect(()=>{if(v){const P=v instanceof Error?v.message:"Failed to load agents";Ve.error(`Error loading agents: ${P}`)}},[v]),g.useEffect(()=>{if(b){const P=b instanceof Error?b.message:"Failed to load workflows";Ve.error(`Error loading workflows: ${P}`)}},[b]);const L=P=>{P?.value&&n(U=>{const W=new URLSearchParams(U);return W.set("entity",P.value),W})};g.useEffect(()=>{const P=t.get("scoreId")??void 0;if(P===s)return;if(!P){a(void 0);return}x.find(W=>W.id===P)&&a(P)},[t,x]);const D=g.useCallback(P=>{a(P||void 0),n(U=>{const W=new URLSearchParams(U);return P?W.set("scoreId",P):W.delete("scoreId"),W})},[n]);if(!f)return null;const B=rs(h)||rs(v)||rs(b),H=h&&is(h),q=!B&&!H&&(h||v||b),F=!w&&x.length===0,V=u?.value!=="all",M=f?.scorer?.source==="stored"?o.jsx(o0,{owner:"scorer-detail",children:o.jsxs(ae,{variant:"default",as:gi,to:`/cms/scorers/${e}/edit`,size:"sm",children:[o.jsx(Yh,{})," Edit"]})}):null,G=e?o.jsx(yY,{open:i,onOpenChange:l,initialScorerIds:[e],onSuccess:P=>{c(`/experiments/${P}`)}}):null;if(B||H||q||F&&!V){const P=(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(_s,{}):H?o.jsx(ys,{resource:"scorers"}):q?o.jsx(Bs,{title:"Failed to load scorer",message:P}):o.jsx(uHr,{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(dHr,{selectedEntity:u,entityOptions:I,onEntityChange:L,onReset:()=>{n(P=>{const U=new URLSearchParams(P);return U.set("entity","all"),U})},isLoading:w||m||y}),o.jsxs(ae,{variant:"primary",onClick:()=>l(!0),children:[o.jsx(Fc,{}),"Run Experiment"]})]})}),o.jsx(cHr,{scores:x,isLoading:w,selectedScoreId:s,isFetchingNextPage:O,hasNextPage:_,setEndOfListElement:T,onScoreClick:D,errorMsg:k?.message}),G]})}const _ks=oo("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"}}),Eks=oo("flex min-w-0 flex-col",{variants:{variant:{default:"",factory:"gap-0.5"}},defaultVariants:{variant:"default"}}),Mnt=oo("",{variants:{variant:{default:"text-sm font-medium",factory:"text-ui-md leading-ui-md text-neutral5"}},defaultVariants:{variant:"default"}}),Tks=oo("flex flex-col gap-0.5",{variants:{variant:{default:"text-sm text-neutral3",factory:"text-ui-sm text-neutral3"}},defaultVariants:{variant:"default"}});function jks({label:e,description:t,htmlFor:n,variant:r,className:s,children:a}){return o.jsxs("div",{className:K(_ks({variant:r}),s),"data-slot":"settings-row",children:[o.jsxs("div",{className:Eks({variant:r}),children:[n?o.jsx(Dt,{htmlFor:n,className:Mnt({variant:r}),children:e}):o.jsx("span",{className:Mnt({variant:r}),children:e}),t&&o.jsx("div",{className:Tks({variant:r}),children:t})]}),a]})}const XWt=[{value:"dark",label:"Dark",Icon:Sen},{value:"light",label:"Light",Icon:Ztn},{value:"system",label:"System",Icon:Cut}],Nks=e=>XWt.some(t=>t.value===e);function Iks({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 Aks=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=WH(),{theme:r,setTheme:s}=d_();return o.jsx(Lt,{width:"narrow",children:o.jsxs(Lt.MainArea,{className:"mt-6 flex flex-col gap-5",children:[o.jsx(wxe,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(jks,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(da,{value:r,onValueChange:a=>{Nks(a)&&s(a)},children:[o.jsx(ha,{id:"theme",className:"w-full sm:w-48",children:o.jsx(fa,{className:"inline-flex max-w-full min-w-0 items-center"})}),o.jsx(pa,{children:XWt.map(a=>o.jsx(xr,{value:a.value,children:o.jsx(Iks,{option:a})},a.value))})]})})}),o.jsx(wxe,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(N4t,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function Rks(){const[e]=Ta(),t=Br(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(UWt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}function Pks(e){return e.replace(/\/$/,"").split("/").pop()}function OY({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 $ks({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(uo,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(qf,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(Eut,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(pI,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx($_,{})," ",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(_G,{})," ",Pks(a.githubUrl)]})})]},a.slug)})})}function Mks({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(_C,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(Om,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(Om,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(ae,{onClick:c,children:["Reset ",o.jsx(tr,{})]})]})}function Dks(){const{data:e,isLoading:t}=zsr(),{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(ks,{children:[o.jsx(eW,{children:o.jsxs(FSe,{children:[o.jsx(Ke,{children:o.jsx(dx,{})}),"Templates"]})}),o.jsxs("div",{className:K("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(Mks,{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($ks,{templates:y,linkComponent:gi,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const Lks="1.65.0-alpha.11";function Fks({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(Pc,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx($Xt,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(OY,{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 zks({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(OY,{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(Tut,{})]}),o.jsx(Om,{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(Ht,{})," 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(j4t,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(ae,{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(Ht,{className:"h-4 w-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(Bd,{})]})})]})})}function Bks({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(dx,{}),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(_m,{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(B0e,{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(_G,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(Rje,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function Dnt(e){switch(e){case"running":return o.jsx(Ht,{size:"sm","aria-hidden":!0});case"success":return o.jsx(Dr,{"aria-hidden":!0});case"failed":return o.jsx(tr,{"aria-hidden":!0});default:return null}}function Uks(){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 qks({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(Uks,{}):Dnt(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:Dnt(e)})}function Vks({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(qks,{status:e.status,variant:r})]})}function Hks({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:K(n),children:t.map((r,s)=>o.jsx(Vks,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function Wks({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(Ht,{}):s+1})},r.id))}),o.jsxs("div",{className:K("text-center text-xs text-neutral3",Yr.colors),children:[n," of ",t," steps completed"]})]})}function Zks({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(OY,{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(Wks,{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(Pen,{}),l||"Something went wrong"]}),u&&o.jsx(Hks,{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(Ht,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function Gks({name:e,installedEntities:t}){return o.jsxs(OY,{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(Tut,{}),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(Rje,{data:t})]})}function Qks(){const{templateSlug:e}=fr(),[t,n]=Ta(),[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),[O,_]=g.useState(!1),[T,E]=g.useState([]),{data:N,isLoading:I}=Bsr({repoOrSlug:e,owner:"mastra-ai"}),R=Lks?.includes("beta")??!1?"beta":"main",{data:L,isLoading:D}=Usr({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:R}),{data:B,isLoading:H}=qsr(),{mutateAsync:q,isPending:F}=Vsr(),{mutateAsync:V}=Hsr(),{streamInstall:M,streamResult:G,isStreaming:z}=Zsr(B),{observeInstall:P,streamResult:U,isStreaming:W}=Gsr(B);g.useEffect(()=>{const ne=t.get("runId");ne&&!v&&!p&&!z&&!W&&(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:ye,errors:he}=ce.result.validationResults,xe=`Template installation completed but ${ye} validation issue${ye>1?"s":""} remain unresolved.`;m(xe),E(he||[])}else{const ye=ce?.result?.message||ce?.result?.error||"Template installation failed";m(typeof ye=="string"?ye:String(ye))}}).catch(se=>{console.error("❌ Failed to fetch run details:",se),m("Failed to retrieve installation status after reload")}))},[t,v,p,z,W,V]),g.useEffect(()=>{const ne=t.get("runId"),se=t.get("resume"),ce=t.get("provider");if(ne&&se==="true"&&ce&&!z&&!W&&!w&&!O&&B){x(ne),k(!0);try{V({runId:ne}).then(le=>{if(le.snapshot?.status==="running")return P.mutateAsync({runId:ne})}).then(()=>{n(le=>{const ye=new URLSearchParams(le);return ye.delete("resume"),ye})}).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,z,W,w,O,B,V,P,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(qf,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(ne=>ne).join(", "):"n/a",icon:o.jsx(uo,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(ne=>ne).join(", "):"n/a",icon:o.jsx(pI,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(Yv,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(hI,{})}],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"}),oe=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:R,slug:N.slug,variables:u},{runId:le}=await q({});x(le),n(ye=>{const he=new URLSearchParams(ye);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(ye=>ye!==se)),d(le=>({...le,[se]:ce}))};return o.jsx(ks,{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(Bks,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:te,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(z||W)&&o.jsx(Zks,{name:N.title,streamResult:W?U:G,runId:b,workflowInfo:B}),v&&o.jsx(Gks,{name:N.title,installedEntities:J,linkComponent:gi}),p&&o.jsx(Fks,{errorMsg:p,validationErrors:T.length>0?T:G?.validationResults?.errors||U?.validationResults?.errors}),!z&&!W&&!v&&!p&&o.jsx(zks,{providerOptions:Y,selectedProvider:r,onProviderChange:ee,variables:u,setVariables:d,errors:f,setErrors:h,handleInstallTemplate:oe,handleVariableChange:X,isLoadingEnvVars:D||H,isInstalling:F,defaultModelProvider:a,defaultModelId:l,onModelUpdate:re})]})]})})})}const Yks=()=>{const{toolId:e,agentId:t}=fr();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(xcs,{toolId:e,agentId:t})})},Kks=()=>{const{toolId:e}=fr();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(K1s,{toolId:e})})};function Xks(){const{data:e,isLoading:t,error:n}=Ky(),[r,s]=g.useState("");return n&&rs(n)?o.jsx(Wn,{children:o.jsx(_s,{})}):n&&is(n)?o.jsx(Wn,{children:o.jsx(ys,{resource:"workflows"})}):n?o.jsx(Wn,{children:o.jsx(Bs,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(Wn,{children:o.jsx(oXr,{})}):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(ae,{as:gi,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(MC,{}),"Schedules"]})]})}),o.jsx(iXr,{workflows:e||{},isLoading:t,search:r})]})}const Jks={active:"bg-accent1",paused:"bg-accent3"},eOs={active:"text-accent1",paused:"text-accent3"},JWt=({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 ${Jks[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${eOs[e]}`,children:e})]}),Rj=e=>!e||e<=0?"—":new Date(e).toLocaleString(),w2=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 eZt({status:e}){const{icon:t,color:n}=tOs(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 tOs(e){switch(e){case"success":return{icon:o.jsx(Dr,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(tr,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(Ht,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(BV,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(Cs,{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 Lnt="auto auto auto auto 1fr";function nOs(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 rOs(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 sOs=3e4,aOs=5*6e4;function iOs({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=un(),c=p=>!!(n&&p.runId&&p.outcome!=="failed"),u=e.filter(c).length,{containerRef:d,getRowProps:f}=no({count:u});let h=-1;return t?o.jsx(Lo,{columns:Lnt}):e.length===0?o.jsx(me,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(fe,{columns:Lnt,className:"min-w-0",scrollRef:d,children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{children:"Run"}),o.jsx(fe.TopCell,{children:"Status"}),o.jsx(fe.TopCell,{children:"Started"}),o.jsx(fe.TopCell,{children:"Duration"}),o.jsx(fe.TopCell,{children:" "})]}),e.map(p=>{const m=p.actualFireAt-p.scheduledFireAt,v=rOs(m),y=`Scheduled ${Rj(p.scheduledFireAt)} — published ${Rj(p.actualFireAt)} (drift ${v})`,b=p.outcome==="failed",x=b?p.error:p.run?.error,w=Math.abs(m),k=!b&&w>sOs&&w<=aOs,O=`${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(fe.Cell,{children:T}),o.jsx(fe.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(Pc,{size:14}),"publish failed"]}):p.run?o.jsx(eZt,{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(bn,{children:[o.jsx(mn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(Pc,{size:14})})}),o.jsx(gn,{children:x})]}):null]})}),o.jsx(fe.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:y,children:w2(p.actualFireAt)}),k?o.jsxs(bn,{children:[o.jsx(mn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(Pc,{size:14})})}),o.jsxs(gn,{children:["Published ",v," after the scheduled fire time"]})]}):null]})}),o.jsx(fe.Cell,{children:p.run?o.jsx("span",{children:nOs(p.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(fe.Cell,{children:" "})]});return _?o.jsx(fe.RowLink,{to:l.workflowRunLink(n,p.runId),LinkComponent:i,...f(h),children:E},O):o.jsx(fe.RowStatic,{children:E},O)}),o.jsx(fe.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const oOs=e=>{const t=Qe();return gt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},Fnt=25,lOs=e=>{const t=Qe(),{inView:n,setRef:r}=i0(),s=Fy({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:Fnt,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<Fnt))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}},cOs=e=>{const t=Qe(),n=Er();return wn({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 C8({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral4 tracking-wide uppercase",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function uOs(){const{scheduleId:e}=fr(),{paths:t}=un(),{data:n,error:r}=oOs(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=lOs(e),d=cOs(e);if(r&&rs(r))return o.jsx(Wn,{children:o.jsx(_s,{})});if(r&&is(r))return o.jsx(Wn,{children:o.jsx(ys,{resource:"schedules"})});if(r)return o.jsx(Wn,{children:o.jsx(Bs,{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(ae,{as:gi,to:t.schedulesLink(),variant:"ghost",children:[o.jsx(uc,{}),"Back to schedules"]}),f?o.jsx(ae,{as:gi,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(ae,{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(GV,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(Fc,{}),"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(C8,{label:h?"Agent":"Workflow",children:f?o.jsx(gi,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):h?o.jsx(gi,{to:t.agentLink(h),className:"text-accent1 hover:underline",children:h}):"—"}),o.jsxs(C8,{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(C8,{label:"Status",children:o.jsx(JWt,{status:n.status})}),o.jsx(C8,{label:"Next fire",children:o.jsx("span",{title:Rj(n.nextFireAt),children:w2(n.nextFireAt)})})]}),o.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[o.jsx(me,{variant:"ui-md",className:"mb-3",children:"Trigger history"}),i?o.jsx(Bs,{title:"Failed to load trigger history",message:i.message}):o.jsx(iOs,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const znt="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function dOs({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=un(),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}=no({count:a.length});return t?o.jsx(Lo,{columns:znt}):o.jsxs(fe,{columns:znt,className:"min-w-0",scrollRef:i,children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{children:"Target"}),o.jsx(fe.TopCell,{children:"Schedule ID"}),o.jsx(fe.TopCell,{children:"Cron"}),o.jsx(fe.TopCell,{children:"Status"}),o.jsx(fe.TopCell,{children:"Next fire"}),o.jsx(fe.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(fe.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(fe.NoMatch,{message:"No schedules configured"}):null,a.map((c,u)=>o.jsxs(fe.RowLink,{to:r.scheduleLink(c.id),LinkComponent:s,...l(u),children:[o.jsx(fe.NameCell,{children:c.workflowId??c.agentId}),o.jsx(fe.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(fe.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(fe.Cell,{children:o.jsx(JWt,{status:c.status})}),o.jsx(fe.Cell,{children:o.jsx("span",{className:"whitespace-nowrap",title:Rj(c.nextFireAt),children:w2(c.nextFireAt)})}),o.jsx(fe.Cell,{children:c.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(eZt,{status:c.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:Rj(c.lastFireAt),children:c.lastFireAt?w2(c.lastFireAt):""})]}):c.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:Rj(c.lastFireAt),children:w2(c.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},c.id))]})}function fOs({workflowId:e}={}){const{data:t,isLoading:n,error:r}=DSe(e?{workflowId:e}:{}),[s,a]=g.useState("");return r?o.jsx(Bs,{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(dOs,{schedules:t??[],isLoading:n,search:s})})]})}function hOs(){const[e]=Ta(),t=e.get("workflowId")??void 0,{error:n}=DSe(t?{workflowId:t}:{});return n&&rs(n)?o.jsx(Wn,{children:o.jsx(_s,{})}):n&&is(n)?o.jsx(Wn,{children:o.jsx(ys,{resource:"schedules"})}):o.jsx(Lt,{children:o.jsx("div",{className:"h-full",children:o.jsx(fOs,{workflowId:t})})})}function pOs({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=cCe({stepGraph:e}),[a,i]=g.useState(!1),[l,c,u]=oEt(r),[d]=lEt(s),{edgeTypes:f,nodeTypes:h,styledEdges:p}=G6t({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(iEt,{nodes:l,edges:p,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:h,onNodesChange:u,children:[o.jsx(hNe,{position:"bottom-left"}),o.jsx(uEt,{variant:gy.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:o.jsx(Ht,{})})})}function mOs(){const{stepDetail:e,closeStepDetail:t}=GW();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(d1,{className:"h-4 w-4",style:{color:Bu.map}}),e.type==="nested-graph"&&o.jsx(_u,{className:"h-4 w-4",style:{color:Bu.workflow}}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx(me,{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(me,{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(tr,{className:"text-neutral3 h-4 w-4"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(v2,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(lCe,{children:o.jsx(pOs,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function gOs(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function vOs(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 yOs({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(me,{as:"p",variant:"ui-md",className:"text-neutral6 flex items-center gap-2 font-semibold",children:[o.jsx(Ke,{children:o.jsx(BV,{})}),"Step suspended"]}),o.jsx(mt,{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?bm(Rx(i.resumeSchema)):yf(cr(),jf());return o.jsx(bOs,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function bOs({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(me,{as:"p",variant:"ui-md",className:"text-neutral6 truncate font-medium",children:e.stepId}),n&&o.jsx(me,{as:"p",variant:"ui-sm",className:"text-neutral3",children:n})]}),e.suspendPayload&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs(me,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(Ke,{children:o.jsx(Oen,{})}),"The step is asking"]}),o.jsxs(cc,{open:a,onOpenChange:i,children:[o.jsxs(Bl,{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(Ke,{children:o.jsx(Fr,{className:K("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(me,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:vOs(e.suspendPayload,e.stepId)})]}),o.jsx(me,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:gOs(e.suspendPayload)})]}),o.jsx(Ul,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Hr,{data:e.suspendPayload,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs(me,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(Ke,{children:o.jsx(Een,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(_U,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(Fc,{}),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 xOs(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext(Wl),{runId:a}=fr(),i=vEt(e,r??""),l=enr(),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(yOs,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const wOs=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"})]}),SOs=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"})]}),kOs=e=>e.includes("."),OOs=e=>e==="input"||e.endsWith(".input"),COs=1;function _Os(e){return`${Number((e/1e3).toPrecision(3))}s`}function EOs(e,t){const n=Object.entries(e).filter(([i])=>!OOs(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,COs);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:h,durationMs:d,isRunning:c,isNestedEntry:kOs(i)}})}const TOs=({status:e})=>o.jsxs(Ke,{children:[e==="success"&&o.jsx(wOs,{className:"text-accent1"}),e==="failed"&&o.jsx(SOs,{className:"text-accent2"}),e==="suspended"&&o.jsx(BV,{className:"text-accent3"}),e==="waiting"&&o.jsx(hpe,{className:"text-accent5"}),e==="skipped"&&o.jsx(hpe,{className:"text-icon3"}),e==="running"&&o.jsx(Ws,{className:"text-accent6 animate-spin"})]}),jOs={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function tZt(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const Bnt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},NOs=e=>{const t=e;return F6t({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},IOs=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=NOs(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(TOs,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ae,{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(Btn,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(pV,{indicators:c,className:"shrink-0"})}),o.jsx(me,{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:tZt(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 ${jOs[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ae,{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(Ftn,{})})}),o.jsx(me,{as:"span",variant:"ui-sm",className:"text-neutral3 w-20 justify-self-end text-right tabular-nums",children:_Os(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function AOs(){const{steps:e}=h4(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=sW(),[a,i]=g.useState(()=>Date.now()),[l,c]=g.useState(!1),[u,d]=g.useState(null),f=g.useRef(null);Zxt(f,{enabled:!l});const h=EOs(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(me,{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(ta,{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(IOs,{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:Bnt(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:Bnt(y.step.output)})},`timeline-item-${m.stepId}-${v}`))})]})}),o.jsx(pr,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(bEt,{data:u.data,title:`${tZt(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const ROs=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=GW();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(tFt,{workflowId:e,workflow:t,isLoading:n}),o.jsx(xOs,{}),o.jsx(AOs,{})]})}),r&&o.jsx("div",{className:"border-border1 min-h-0 w-[420px] overflow-hidden border-l",children:o.jsx(mOs,{})})]})},Unt=()=>{const{workflowId:e}=fr(),{data:t,isLoading:n,error:r}=kL(e);return r&&rs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(_s,{})}):r&&is(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ys,{resource:"workflows"})}):o.jsx(ECe,{children:o.jsx(ROs,{workflowId:e,workflow:t??void 0,isLoading:n})})};function POs(e,t){if(e==null)return{};var n,r,s=SOt(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 T0e(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 $Os(e){if(Array.isArray(e))return T0e(e)}function MOs(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function DOs(e,t){if(e){if(typeof e=="string")return T0e(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)?T0e(e,t):void 0}}function LOs(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
673
+ ]`,rnt="flex min-h-0 flex-1 flex-col py-0";function axs({tab:e,onTabChange:t,file:n,onFileSelect:r,onReplace:s,pastedText:a,onPastedTextChange:i,validation:l,isImporting:c}){return o.jsxs(vc,{value:e,defaultTab:"upload",onValueChange:t,className:"flex h-full flex-col gap-3",children:[o.jsxs(gc,{variant:"pill",children:[o.jsx(zr,{value:"upload",children:"Upload file"}),o.jsx(zr,{value:"paste",children:"Paste JSON"})]}),o.jsx(vs,{value:"upload",className:rnt,children:n?o.jsx(cxs,{file:n,validation:l,onReplace:s,isImporting:c}):o.jsx(ixs,{onFileSelect:r,disabled:c})}),o.jsx(vs,{value:"paste",className:rnt,children:o.jsx(So,{"aria-label":"JSON items",className:"text-ui-sm min-h-[200px] flex-1 resize-none font-mono",placeholder:sxs,spellCheck:!1,value:a,onChange:u=>i(u.target.value),disabled:c})})]})}function ixs({onFileSelect:e,disabled:t}){const[n,r]=g.useState(!1),s=g.useCallback(c=>{const u=c.target.files?.[0];u&&e(u),c.target.value=""},[e]),a=g.useCallback(c=>{c.preventDefault(),c.stopPropagation(),r(!0)},[]),i=g.useCallback(c=>{c.preventDefault(),c.stopPropagation(),r(!1)},[]),l=g.useCallback(c=>{if(c.preventDefault(),c.stopPropagation(),r(!1),t)return;const u=c.dataTransfer.files?.[0];u&&e(u)},[t,e]);return o.jsxs("div",{"data-testid":"json-dropzone",onDragOver:a,onDragLeave:i,onDrop:l,className:K("border-border1 bg-surface3 relative flex flex-1 flex-col items-center justify-center gap-3 rounded-lg border border-dashed px-6 py-10 text-center transition-colors","hover:border-accent1/50 hover:bg-accent1/5",n&&"border-accent1/50 bg-accent1/5",t&&"cursor-wait opacity-60"),children:[o.jsx("input",{type:"file",accept:".json,application/json","aria-label":"Choose a JSON file",onChange:s,disabled:t,className:"absolute inset-0 cursor-pointer opacity-0"}),o.jsx("div",{className:"border-border1 bg-surface2 text-neutral4 flex size-9 items-center justify-center rounded-md border",children:o.jsx(h3,{className:"size-4"})}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("p",{className:"text-ui-md text-neutral6",children:"Drop a JSON file here"}),o.jsxs("p",{className:"text-ui-sm text-neutral4",children:["or ",o.jsx("span",{className:"underline",children:"choose a file"})," from your computer"]})]}),o.jsxs("p",{className:"text-ui-xs text-neutral3",children:[".json · an array of items · up to ",PRe]})]})}function oxs(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function lxs(e){return typeof e=="string"?e:JSON.stringify(e)??""}function cxs({file:e,validation:t,onReplace:n,isImporting:r}){const s="rows"in t?t.rows:[],a="total"in t?t.total:0,i=s.slice(0,aoe);return o.jsxs("div",{"data-testid":"json-file-card",className:"border-border1 rounded-lg border",children:[o.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[o.jsx(uI,{className:"text-neutral4 size-4 shrink-0"}),o.jsx("span",{className:"text-ui-sm text-neutral6 min-w-0 flex-1 truncate font-mono",children:e.name}),o.jsx("span",{className:"text-ui-xs text-neutral3 shrink-0",children:oxs(e.size)}),o.jsx(ae,{variant:"ghost",size:"xs",onClick:n,disabled:r,children:"Replace"})]}),i.map(l=>o.jsxs("div",{className:"border-border1 grid grid-cols-[2rem_1fr_auto] items-center gap-2 border-t px-3 py-1.5",children:[o.jsx("span",{className:"text-ui-xs text-neutral3",children:l.index}),o.jsx("span",{className:"text-ui-sm text-neutral5 truncate font-mono",children:lxs(l.input)}),l.hasInput?l.hasGroundTruth?null:o.jsx(mt,{variant:"yellow",size:"xs",children:"no groundTruth"}):o.jsx(mt,{variant:"red",size:"xs",children:"no input"})]},l.index)),a>aoe&&o.jsxs("div",{className:"border-border1 text-ui-xs text-neutral3 border-t px-3 py-1.5",children:["+ ",a-aoe," more"]})]})}const uxs=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)});function dxs({datasetId:e,datasetName:t,open:n,onOpenChange:r,onSuccess:s}){const[a,i]=g.useState("upload"),[l,c]=g.useState(null),[u,d]=g.useState(""),[f,h]=g.useState(null),[p,m]=g.useState(""),[v,y]=g.useState(!1),b=g.useRef(0),{batchInsertItems:x}=La(),w=a==="upload"?u:p,k=g.useMemo(()=>a==="upload"&&f?{status:"error",kind:"parse",message:f}:nbs(w),[a,f,w]),O=g.useCallback(async I=>{const A=++b.current;if(!I.name.toLowerCase().endsWith(".json")){h("Only .json files are supported");return}if(I.size>dWt){h(`File is larger than ${PRe}`);return}try{const R=await uxs(I);if(A!==b.current)return;c({name:I.name,size:I.size}),d(R),h(null)}catch{if(A!==b.current)return;h("Could not read the file")}},[]),_=g.useCallback(()=>{b.current++,c(null),d(""),h(null)},[]),T=g.useCallback(()=>{b.current++,i("upload"),c(null),d(""),h(null),m("")},[]),E=g.useCallback(()=>{v||(r(!1),setTimeout(T,150))},[v,r,T]),N=g.useCallback(async()=>{if(k.status==="ready"){y(!0);try{await x.mutateAsync({datasetId:e,items:k.items}),Ve.success(`Imported ${k.total} item${k.total!==1?"s":""}`),s?.(),r(!1),setTimeout(T,150)}catch(I){Ve.error(I instanceof Error?I.message:"Failed to import items")}finally{y(!1)}}},[k,x,e,s,r,T]);return o.jsx(pr,{open:n,onOpenChange:E,children:o.jsxs(mr,{className:"flex max-h-[90vh] w-[960px] max-w-[calc(100vw-2rem)] flex-col gap-0 p-0",children:[o.jsxs(gr,{className:"border-border1 border-b px-6 py-4",children:[o.jsx(ur,{children:"Import into dataset"}),o.jsxs(Ts,{className:"text-ui-sm text-neutral3 not-sr-only",children:["Add items to"," ",t?o.jsx("code",{className:"bg-surface3 text-ui-xs text-neutral6 rounded px-1 font-mono",children:t}):"this dataset"," ","from a JSON file or paste them directly."]})]}),o.jsx(Nr,{className:"max-h-none min-h-0 flex-1 overflow-y-auto p-0",children:o.jsxs("div",{className:"divide-border1 grid divide-y md:grid-cols-[1.15fr_1fr] md:divide-x md:divide-y-0",children:[o.jsx("div",{className:"flex min-h-[360px] flex-col p-6",children:o.jsx(axs,{tab:a,onTabChange:i,file:l,onFileSelect:O,onReplace:_,pastedText:p,onPastedTextChange:m,validation:k,isImporting:v})}),o.jsx("div",{className:"p-6",children:o.jsx(rxs,{})})]})}),o.jsxs(Fl,{className:"border-border1 items-center border-t px-6 py-3 sm:justify-between",children:[o.jsx(fxs,{validation:k}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(ae,{onClick:E,disabled:v,children:"Cancel"}),o.jsxs(ae,{variant:"primary",onClick:N,disabled:k.status!=="ready"||v,children:[v&&o.jsx(Ht,{}),k.status==="ready"?`Import ${k.total} item${k.total!==1?"s":""}`:"Import"]})]})]})]})})}function fxs({validation:e}){const t=K("size-1.5 shrink-0 rounded-full",e.status==="idle"&&"bg-neutral3",e.status==="ready"&&"bg-accent1",e.status==="error"&&"bg-accent2");let n;switch(e.status){case"idle":n="No items yet";break;case"ready":n=o.jsxs(o.Fragment,{children:[o.jsx("b",{className:"text-neutral6 font-medium",children:e.total})," item",e.total!==1?"s":""," ready",e.missingGroundTruthCount>0&&` · ${e.missingGroundTruthCount} without groundTruth`]});break;case"error":switch(e.kind){case"parse":n=`Not valid JSON — ${e.message}`;break;case"not-array":n="Top level must be an array of items";break;case"empty":n="The array has no items";break;case"too-large":n=`JSON is larger than ${PRe}`;break;case"missing-input":n=o.jsxs(o.Fragment,{children:[o.jsx("b",{className:"text-neutral6 font-medium",children:e.missingInputCount})," of ",e.total," item",e.total!==1?"s":""," ",e.missingInputCount!==1?"have":"has"," no"," ",o.jsx("code",{className:"font-mono",children:"input"})]});break}break}return o.jsxs("div",{role:"status",className:"text-ui-sm text-neutral4 flex min-w-0 items-center gap-2",children:[o.jsx("span",{className:t}),o.jsx("span",{className:"truncate",children:n})]})}function hxs(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 gWt({active:e,onPrevious:t,onNext:n,onClose:r}){g.useEffect(()=>{if(!e)return;const s=a=>{a.defaultPrevented||hxs(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 vWt=g.createContext(null);function pxs({datasetId:e,items:t,isLoadingItems:n,children:r}){const s=Br(),i=Qvt("/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]);gWt({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(vWt.Provider,{value:h,children:r})}function yWt(){const e=g.useContext(vWt);if(!e)throw new Error("useDatasetItemPanel must be used within a DatasetItemPanelProvider");return e}function mxs({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,leftSlot:r,rightSlot:s,belowToolbarSlot:a}){const[i,l]=Ta(),{activeVersion:c}=$Re(i,l),[u,d]=g.useState(!1),[f,h]=g.useState(!1),[p,m]=g.useState(!1),[v,y]=g.useState([]),[b,x]=g.useState(!1),[w,k]=g.useState([]),[O,_]=g.useState(!1),[T,E]=g.useState([]),[N,I]=g.useState(0),[A,R]=g.useState(""),[L]=lW(A,300),{data:D}=$m(e),{data:B=[],isLoading:H,setEndOfListElement:q,isFetchingNextPage:F,hasNextPage:V}=Yx(e,L||void 0,c),{deleteItems:M}=La(),{currentItemId:G,openItem:z,close:P}=yWt(),U=X=>{G===X?P():z(X)},W=X=>{y(X),m(!0)},Y=X=>{k(X),x(!0)},te=X=>{x(X),X||(k([]),I(ne=>ne+1))},J=X=>{E(X),_(!0)},ee=async()=>{await M.mutateAsync({datasetId:e,itemIds:T}),Ve.success(`Deleted ${T.length} items`),_(!1),E([]),I(X=>X+1)},re=X=>{m(!1),y([]),I(ne=>ne+1),n?.(X)},oe=X=>{m(X),X||(y([]),I(ne=>ne+1))};return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"grid h-full overflow-auto",children:o.jsx(exs,{items:B,leftSlot:r,rightSlot:s,belowToolbarSlot:a,isLoading:H,onItemClick:U,featuredItemId:G,onAddClick:t??(()=>{}),onImportClick:()=>d(!0),onImportJsonClick:()=>h(!0),onBulkDeleteClick:J,onCreateDatasetClick:W,onAddToDatasetClick:Y,datasetName:D?.name,clearSelectionTrigger:N,setEndOfListElement:q,isFetchingNextPage:F,hasNextPage:V,searchQuery:A,activeSearchQuery:L,onSearchChange:R,currentDatasetVersion:D?.version})}),o.jsx(Qbs,{datasetId:e,open:u,onOpenChange:d}),o.jsx(dxs,{datasetId:e,datasetName:D?.name,open:f,onOpenChange:h}),o.jsx(jbs,{open:p,onOpenChange:oe,items:v,onSuccess:re}),o.jsx(Nbs,{open:b,onOpenChange:te,items:w,currentDatasetId:e}),o.jsx(Tt,{open:O,onOpenChange:_,children:o.jsxs(Tt.Content,{children:[o.jsxs(Tt.Header,{children:[o.jsx(Tt.Title,{children:"Delete Items"}),o.jsxs(Tt.Description,{children:["Are you sure you want to delete ",T.length," item",T.length!==1?"s":"","? This action cannot be undone."]})]}),o.jsxs(Tt.Footer,{children:[o.jsx(Tt.Cancel,{children:"Cancel"}),o.jsx(Tt.Action,{onClick:ee,children:M.isPending?"Deleting...":"Delete"})]})]})})]})}const snt="__create_tag__";function gxs({datasetId:e}){const{data:t}=$m(e),{data:n}=Pm(),{updateDataset:r}=La(),[s,a]=g.useState(""),i=g.useMemo(()=>Array.isArray(t?.tags)?t.tags:[],[t?.tags]),l=g.useMemo(()=>fWt(n?.datasets??[]),[n?.datasets]),c=g.useMemo(()=>{const h=l.map(v=>({label:v,value:v,end:i.includes(v)?o.jsx(Dr,{"data-testid":"tag-applied",className:"size-3.5"}):void 0})),p=s.trim();return p.length>0&&!l.includes(p)&&!i.includes(p)?[{label:`Create "${p}"`,value:snt},...h]:h},[l,i,s]),u=h=>{r.mutate({datasetId:e,tags:h},{onError:()=>Ve.error("Failed to update tags")})},d=h=>{const p=h===snt?s.trim():h;!p||i.includes(p)||u([...i,p])},f=h=>{u(i.filter(p=>p!==h))};return o.jsxs("div",{"data-testid":"dataset-tags-editor",className:"flex flex-wrap items-center gap-2 px-4 py-2",children:[i.map(h=>o.jsxs(bA,{value:h,size:"md",className:"gap-1 pr-1",children:[h,o.jsx("button",{type:"button","aria-label":`Remove tag ${h}`,disabled:r.isPending,onClick:()=>f(h),className:"cursor-pointer rounded-sm hover:opacity-70 disabled:opacity-50",children:o.jsx(tr,{className:"size-3"})})]},h)),o.jsx(zo,{options:c,value:void 0,onValueChange:d,onInputValueChange:a,placeholder:o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(hI,{className:"size-3.5"}),"Add tag"]}),searchPlaceholder:"Search or create tag...",emptyText:"Type to create a tag",variant:"ghost",size:"xs",className:"w-auto min-w-0",disabled:r.isPending})]})}function bWt({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(zo,{multiple:!0,options:c,value:e,onValueChange:t,placeholder:"Select scorers...",searchPlaceholder:"Search scorers...",emptyText:"No scorers available",disabled:n||l,container:r})]})}function xWt({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(bl,{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(bWt,{selectedScorers:n,setSelectedScorers:r,disabled:s,label:"Item scorers",helperText:"Choose from scorers that can be resolved by this Mastra instance."}):null]})}function vxs(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 ioe({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 yxs({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}=La(),O=()=>{a("{}"),l(""),u(""),f(""),p(!1),v([]),b(""),w(null)},_=R=>{O(),n(R)},T=async R=>{R.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 F=JSON.parse(d);if(!Array.isArray(F)){Ve.error("Tool Mocks must be a JSON array");return}H=F}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(F){const V=vxs(F);V?w(V):Ve.error(`Failed to add item: ${F instanceof Error?F.message:"Unknown error"}`)}},E=R=>{a(R),x?.field==="input"&&w(null)},N=R=>{l(R),x?.field==="groundTruth"&&w(null)},I=R=>{f(R),x?.field==="toolMocks"&&w(null)},A=()=>{_(!1)};return o.jsxs(Oi,{dialogTitle:"Add Item",dialogDescription:"Create a new dataset item",isOpen:t,onClose:A,level:1,children:[o.jsx(Oi.Top,{children:"Add Item"}),o.jsxs(Oi.Content,{children:[o.jsx(Oi.Header,{children:o.jsx(Oi.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(Hr,{value:s,onChange:E,showCopyButton:!1,className:"min-h-[240px]"}),x?.field==="input"&&o.jsx(ioe,{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(Hr,{value:i,onChange:N,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="groundTruth"&&o.jsx(ioe,{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(Hr,{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(Hr,{value:d,onChange:I,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="toolMocks"&&o.jsx(ioe,{field:"toolMocks",errors:x.errors})]}),o.jsx(xWt,{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(Hr,{value:y,onChange:b,showCopyButton:!1,className:"min-h-[200px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ae,{type:"button",onClick:A,children:"Cancel"}),o.jsx(ae,{type:"submit",variant:"primary",disabled:k.isPending,children:k.isPending?"Adding...":"Add Item"})]})]})]})]})}function bxs({item:e}){return o.jsx(al,{withMargins:!1,children:o.jsxs(al.Column,{children:[o.jsxs(al.Title,{size:"smaller",children:[o.jsx(VV,{}),o.jsx("span",{className:"truncate",children:e.id}),o.jsx(_a,{content:e.id,tooltip:`Copy item ID: ${e.id}`})]}),o.jsxs(al.Description,{children:[o.jsxs(Rc,{children:[o.jsx(vKt,{})," Created ",dr(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")]}),e.datasetVersion!=null&&o.jsxs(Rc,{children:[o.jsx(d3,{})," Version v",e.datasetVersion]})]})]})})}const Sk=e=>JSON.stringify(e??null,null,2),xxs=[{key:"input",title:"Input",icon:o.jsx(u1,{}),value:e=>Sk(e.input)},{key:"groundTruth",title:"Ground Truth",icon:o.jsx(Rg,{}),value:e=>Sk(e.groundTruth)},{key:"expectedTrajectory",title:"Expected Trajectory",icon:o.jsx(jut,{}),value:e=>e.expectedTrajectory!=null?Sk(e.expectedTrajectory):void 0},{key:"toolMocks",title:"Tool Mocks",icon:o.jsx(Vd,{}),value:e=>Sk(e.toolMocks??[])},{key:"scorerIds",title:"Scorers",icon:o.jsx(V0e,{}),value:e=>e.scorerIds===void 0?"Inherited from dataset":Sk(e.scorerIds)},{key:"requestContext",title:"Request Context",icon:o.jsx(nc,{}),value:e=>e.requestContext!=null?Sk(e.requestContext):void 0},{key:"metadata",title:"Metadata",icon:o.jsx(hI,{}),value:e=>Sk(e.metadata)}];function MV({item:e,diff:t}){return o.jsxs(o.Fragment,{children:[o.jsxs(Jn,{children:[o.jsx(Jn.Key,{children:"Dataset Id"}),o.jsx(Jn.ValueWithCopyBtn,{copyTooltip:"Copy Dataset Id to clipboard",copyValue:e.datasetId,children:e.datasetId}),o.jsx(Jn.Key,{children:"Version"}),o.jsxs(Jn.Value,{children:["v",e.datasetVersion]}),o.jsx(Jn.Key,{children:"Created"}),o.jsx(Jn.Value,{children:dr(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")}),o.jsx(Jn.Key,{children:"Updated"}),o.jsx(Jn.Value,{children:e.updatedAt&&new Date(e.updatedAt).getTime()!==new Date(e.createdAt).getTime()?dr(new Date(e.updatedAt),"MMM d, yyyy h:mm aaa"):"n/a"})]}),o.jsx("div",{className:"mt-3 grid gap-3",children:xxs.map(n=>{const r=n.value(e),s=t?n.value(t.against):void 0;return r===void 0&&s===void 0?null:o.jsx(fn.CodeSection,{title:n.title,icon:n.icon,codeStr:r??"",diff:t?{against:s??"",side:t.side}:void 0},n.key)})})]})}function ooe({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 wxs({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(Hr,{value:e,onChange:t,showCopyButton:!1,className:"min-h-[120px]"}),y?.field==="input"&&o.jsx(ooe,{field:"input",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Ground Truth (JSON, optional)"}),o.jsx(Hr,{value:n,onChange:r,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="groundTruth"&&o.jsx(ooe,{field:"groundTruth",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Expected Trajectory (JSON, optional)"}),o.jsx(Hr,{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(Hr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="toolMocks"&&o.jsx(ooe,{field:"toolMocks",errors:y.errors})]}),o.jsx(xWt,{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(Hr,{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(Hr,{value:s,onChange:a,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex gap-2 pt-4",children:[o.jsx(ae,{variant:"primary",onClick:b,disabled:w,children:w?"Saving...":"Save Changes"}),o.jsx(ae,{onClick:x,disabled:w,children:"Cancel"})]})]})]})}const Sxs={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)]"},kxs={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"},WT=({children:e,theme:t="dark",size:n="default",className:r})=>o.jsx("kbd",{className:K("inline-flex items-center justify-center border font-mono",kxs[n],Yr.transform,"active:scale-95 active:shadow-none",Sxs[t],r),children:e}),Oxs=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function Cxs({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:a,isLoading:i}=Um(),{data:l,isLoading:c}=Ky(),{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(zo,{options:Oxs,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(zo,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:h,container:s})]})]})}const _xs=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform);function Exs({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return bm(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(iL,{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 loe({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 yY({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??""),[O,_]=g.useState(s??""),[T,E]=g.useState(n??[]),[N,I]=g.useState({}),[A,R]=g.useState(""),{triggerExperiment:L}=La(),{data:D}=$m(v),{total:B}=Yx(v,void 0,b),H=D?.requestContextSchema,q=!!(H&&Object.keys(H).length>0),F=!!(v&&w&&O&&f.trim()),V=L.isPending,M=[!f.trim()&&"name",!v&&"dataset",!O&&"target"].filter(Boolean),G=q?Object.values(N).some(J=>J!==void 0&&J!==""):A.trim().length>0,z=J=>{y(J),x(null),I({})},P=()=>{h(a??""),m(i??""),y(e??""),x(t??null),k(r??""),_(s??""),E(n??[]),I({}),R("")},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}},W=async()=>{if(!v||!w||!O||!f.trim())return;let J;try{J=U()}catch(ee){const re=ee instanceof Error?ee.message:"Request Context must be valid JSON";vu.error(re);return}try{const ee=await L.mutateAsync({datasetId:v,name:f.trim(),description:p.trim()||void 0,targetType:w,targetId:O,scorerIds:T.length>0?T:void 0,version:b??void 0,requestContext:J});vu.success("Experiment triggered successfully"),c(!1),u?.(ee.experimentId),P()}catch(ee){const re=ee instanceof Error?ee.message:"Failed to trigger experiment";vu.error(re)}},Y=()=>{V||(c(!1),P())},te=J=>{(J.metaKey||J.ctrlKey)&&J.key==="Enter"&&F&&!V&&(J.preventDefault(),W())};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(Ts,{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(Nr,{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(So,{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(loe,{index:1,title:"Dataset",done:!!v,children:[o.jsxs("div",{className:"grid grid-cols-[1fr_140px] gap-3",children:[o.jsx(Mbs,{value:v,onValueChange:z,container:d}),v&&o.jsx(pWt,{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(loe,{index:2,title:"Target",done:!!O,children:[o.jsx(Cxs,{targetType:w,setTargetType:k,targetId:O,setTargetId:_,container:d}),w&&!O&&o.jsxs("p",{className:"text-ui-xs text-neutral3",children:["Choose ",w==="agent"?"an":"a"," ",w," to run"]})]}),o.jsx(loe,{index:3,title:"Scorers (Optional)",done:T.length>0,isLast:!0,children:o.jsx(bWt,{label:"",selectedScorers:T,setSelectedScorers:E,disabled:V,container:d,helperText:"Scores are computed after each item runs."})})]}),o.jsxs(cc,{children:[o.jsxs(Bl,{className:"text-ui-sm flex items-center gap-2",children:[o.jsx(Fr,{className:"size-4"}),"Request Context (JSON, optional)",G&&o.jsx(mt,{size:"xs",variant:"blue",children:"set"})]}),o.jsx(Ul,{className:"pt-3",children:q?o.jsx(Exs,{requestContextSchema:H,onChange:I}):o.jsx(Hr,{value:A,onChange:R,showCopyButton:!1,"aria-label":"Request context JSON",className:"min-h-[160px]"})})]})]}),o.jsxs(Fl,{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(mt,{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(mt,{variant:"neutral",indicator:"dot",children:["Missing ",M.join(", ")]})}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ae,{onClick:Y,disabled:V,children:"Cancel"}),o.jsx(ae,{variant:"primary",onClick:W,disabled:!F||V,children:V?o.jsxs(o.Fragment,{children:[o.jsx(Ht,{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(WT,{size:"xs",children:_xs?"⌘":"Ctrl"}),o.jsx(WT,{size:"xs",children:"↵"})]})]})})]})]})]})})}const wWt=g.createContext(null);function Txs({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:a,children:i}){const l=Br(),u=Qvt("/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(RTe(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]);gWt({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(wWt.Provider,{value:y,children:i})}function SWt(){const e=g.useContext(wWt);if(!e)throw new Error("useExperimentItemPanel must be used within an ExperimentItemPanelProvider");return e}function jxs({datasetId:e,experimentId:t}){const[n,r]=g.useState(!1),{updateExperimentResult:s}=La();return{addTag:g.useCallback(async(i,l)=>{const c=l.filter(d=>!(d.tags??[]).includes(i));if(n||c.length===0)return;r(!0);let u=0;try{u=(await Promise.allSettled(c.map(f=>s.mutateAsync({datasetId:e,experimentId:t,resultId:f.id,tags:[...f.tags??[],i]})))).filter(f=>f.status==="fulfilled").length}finally{r(!1)}u>0?Ve(`Tag "${i}" added to ${u} result${u>1?"s":""}`):Ve.error("Failed to add tag")},[e,t,n,s]),isPending:n}}function kWt(e,t){const{data:n}=$m(e);return g.useMemo(()=>[...new Set([...n?.tags??[],...t.flatMap(r=>r.tags??[])])].sort(),[n?.tags,t])}const EA=e=>o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 8.94379 8.92126",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{d:"M6.13251 5.43413C6.51629 5.43413 6.82744 5.74533 6.82748 6.1291C6.82748 6.5129 6.51631 6.82407 6.13251 6.82407C5.74877 6.824 5.43754 6.51286 5.43754 6.1291C5.43759 5.74537 5.74879 5.4342 6.13251 5.43413Z",fill:"currentColor"}),o.jsx("path",{d:"M5.92771 2.29722C6.13122 2.09376 6.46147 2.09379 6.665 2.29722C6.86843 2.50075 6.86846 2.831 6.665 3.03451L3.03724 6.66227C2.83373 6.86578 2.5035 6.86572 2.29995 6.66227C2.0965 6.45872 2.09644 6.12849 2.29995 5.92498L5.92771 2.29722Z",fill:"currentColor"}),o.jsx("path",{d:"M2.842 2.12791C3.22572 2.12799 3.53694 2.43914 3.53696 2.82288C3.53696 3.20664 3.22573 3.51777 2.842 3.51785C2.45819 3.51785 2.14703 3.20668 2.14703 2.82288C2.14705 2.4391 2.45821 2.12791 2.842 2.12791Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.38455 0.00887484C8.26052 0.0979278 8.94379 0.837945 8.94379 1.73742V7.18384C8.94369 8.08322 8.26046 8.82334 7.38455 8.91238L7.20705 8.92126H1.73742L1.55992 8.91238C0.683828 8.82351 0.000101213 8.08336 0 7.18384V1.73742C0 0.837813 0.683761 0.0977507 1.55992 0.00887484L1.73742 0H7.20705L7.38455 0.00887484ZM1.73742 0.839013C1.24121 0.839013 0.839013 1.24121 0.839013 1.73742V7.18384C0.839121 7.67996 1.24128 8.08293 1.73742 8.08293H7.20705C7.70305 8.08276 8.10535 7.67985 8.10546 7.18384V1.73742C8.10546 1.24131 7.70312 0.83918 7.20705 0.839013H1.73742Z",fill:"currentColor"})]});function Nxs({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}=un(),m=!!(d&&f),v=[m?"2rem":"",...s.map(O=>O.size)].filter(Boolean).join(" "),y=s.some(O=>O.name==="input"),b=s.some(O=>O.name==="tags"),{containerRef:x,getRowProps:w}=no({count:e.length}),k=O=>i?.includes(O.name)?o.jsx(fe.TopCell,{children:o.jsxs(h,{href:p.scorerLink(O.name),className:"flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[o.jsx(EA,{}),o.jsx("span",{className:"min-w-0 truncate",children:O.label})]})},O.name):o.jsx(fe.TopCell,{children:O.label},O.name);return t?o.jsx(Lo,{columns:v}):o.jsxs(fe,{columns:v,className:"min-w-0",scrollRef:x,children:[o.jsxs(fe.Top,{hasLeadingCell:m,children:[m&&o.jsx(fe.TopCell,{children:" "}),m?o.jsx(fe.TopCells,{colStart:2,children:s.map(k)}):s.map(k)]}),e.length===0?o.jsx(fe.NoMatch,{message:"No results yet"}):o.jsxs(o.Fragment,{children:[e.map((O,_)=>{const T=!!O.error,E=O.id===n,N=o.jsxs(o.Fragment,{children:[o.jsxs(fe.Cell,{className:"text-ui-smd text-neutral3 flex items-center gap-1.5 tracking-wide",children:[o.jsx("span",{children:O.itemId?.slice(0,8)??""}),T&&o.jsxs(bn,{children:[o.jsx(mn,{render:o.jsx(_O,{role:"img","aria-label":"Error",className:"text-error size-3.5"})}),o.jsx(gn,{children:O.error?.message||"Error"})]})]}),y&&o.jsx(fe.TextCell,{font:"mono",children:Axs(Ixs(O.input),200)}),b&&o.jsx(fe.Cell,{className:"flex items-center gap-1 overflow-hidden","data-testid":`result-tags-${O.id}`,children:O.tags?.map(I=>o.jsx(bA,{value:I,className:"shrink-0"},I))}),i?.map(I=>{const R=a?.[O.itemId]?.find(L=>L.scorerId===I);return o.jsx(fe.Cell,{className:"text-neutral3 text-ui-smd font-mono",children:R!=null?R.score.toFixed(3):"-"},I)})]});return m?o.jsxs(fe.RowWrapper,{children:[o.jsx(fe.SelectCell,{checked:d.has(O.id),onToggle:()=>f(O.id),"aria-label":`Select result ${O.itemId}`}),o.jsx(fe.RowButton,{colStart:2,featured:E,"data-selected":E||void 0,onClick:()=>r(O.id),...w(_),children:N})]},O.id):o.jsx(fe.RowButton,{featured:E,"data-selected":E||void 0,onClick:()=>r(O.id),...w(_),children:N},O.id)}),o.jsx(fe.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function Ixs(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Axs(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}const ant="__create_tag__";function OWt({selectedResults:e,vocabulary:t,onAddTag:n,disabled:r,appearance:s="toolbar"}){const[a,i]=g.useState(""),l=g.useMemo(()=>[...t].sort(),[t]),c=g.useMemo(()=>{if(e.length===0)return new Set;const[f,...h]=e;return new Set((f.tags??[]).filter(p=>h.every(m=>(m.tags??[]).includes(p))))},[e]),u=g.useMemo(()=>{const f=l.map(m=>({label:m,value:m,end:c.has(m)?o.jsx(Dr,{"data-testid":"tag-applied",className:"size-3.5"}):void 0})),h=a.trim();return h.length>0&&!l.includes(h)?[{label:`Create "${h}"`,value:ant},...f]:f},[l,c,a]),d=f=>{const h=f===ant?a.trim():f;!h||c.has(h)||n(h)};return o.jsx(zo,{"data-testid":"experiment-results-tag-picker",options:u,value:void 0,onValueChange:d,onInputValueChange:i,placeholder:o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(hI,{className:"size-3.5"}),"Add tag"]}),searchPlaceholder:"Search or create tag...",emptyText:"Type to create a tag",variant:s==="inline"?"ghost":"outline",size:s==="inline"?"xs":"sm",className:"w-auto min-w-0",disabled:r})}function Rxs({scoresByItemId:e,experimentStatus:t}){const{Link:n,paths:r}=un(),{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(fm,{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(bn,{children:[o.jsx(mn,{render:o.jsx(EA,{role:"img","aria-label":"Scorer"})}),o.jsx(gn,{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 Pxs({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoading:s,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l}){const{currentItemId:c,openItem:u,close:d}=SWt(),[f,h]=g.useState(new Set),[p,m]=g.useState(!1),{updateExperimentResult:v}=La(),{addTag:y,isPending:b}=jxs({datasetId:t,experimentId:e}),x=kWt(t,r),w=g.useMemo(()=>r.filter(R=>f.has(R.id)),[r,f]),k=g.useCallback(R=>{h(L=>{const D=new Set(L);return D.has(R)?D.delete(R):D.add(R),D})},[]),O=g.useCallback(()=>h(new Set),[]),_=g.useCallback(async R=>{if(p||R.length===0)return;m(!0);let L=0;const D=new Set;try{for(const B of R)try{await v.mutateAsync({datasetId:t,experimentId:e,resultId:B,status:"needs-review"}),L++,D.add(B)}catch{}}finally{m(!1)}D.size>0&&h(B=>{const H=new Set(B);for(const q of D)H.delete(q);return H}),L>0&&Ve(`${L} result${L>1?"s":""} flagged for review`)},[t,e,p,v]),T=g.useMemo(()=>c?r.find(R=>R.itemId===c)?.id??null:null,[r,c]),{data:E}=PC(e,n),N=g.useMemo(()=>{if(!E)return[];const R=new Set;for(const L of Object.values(E))for(const D of L)R.add(D.scorerId);return[...R].sort()},[E]),I=g.useCallback(R=>{const L=r.find(D=>D.id===R);L&&(L.itemId===c?d():u(L.itemId))},[r,c,d,u]),A=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"7rem"},{name:"input",label:"Input",size:"minmax(200px,1fr)"},{name:"tags",label:"Tags",size:"max-content"},...N.map(R=>({name:R,label:R,size:"12rem"}))],[N]);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(Rxs,{scoresByItemId:E,experimentStatus:n}),f.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(ae,{variant:"outline",size:"sm",disabled:p||b,onClick:()=>_([...f]),children:[o.jsx(Ke,{size:"sm",children:o.jsx(LC,{})}),"Flag ",f.size," to review"]}),o.jsx(OWt,{selectedResults:w,vocabulary:x,onAddTag:R=>y(R,w),disabled:b||p}),o.jsx(ae,{variant:"ghost",size:"sm",onClick:O,children:"Clear"})]}),o.jsx("div",{className:"min-h-0 overflow-y-auto",children:o.jsx(Nxs,{results:r,isLoading:s,featuredResultId:T,onResultClick:I,columns:A,scoresByItemId:E,scorerIds:N,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l,selectedIds:f,onToggleSelect:k})})]})}const int={pending:{icon:o.jsx(c1,{className:"text-warning1 size-4"}),label:"Pending"},running:{icon:o.jsx(Ht,{size:"sm"}),label:"Running"},completed:{icon:o.jsx(i3,{className:"text-neutral3 size-4"}),label:"Completed"},failed:{icon:o.jsx(TO,{className:"text-error size-4"}),label:"Failed"}};function $xs({status:e,className:t}){const n=int[e]??int.pending;return o.jsxs(bn,{children:[o.jsx(mn,{render:o.jsx("span",{tabIndex:0,className:K("flex shrink-0 items-center",t),children:n.icon})}),o.jsx(gn,{children:n.label})]})}const Mxs=e=>{const t=Qe();return gt({queryKey:["experiment-trace-light",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return t.getTraceLight(e)},select:oRe,enabled:!!e})};function Dxs(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 Lxs({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=YAe(e),a=(s??[]).map(i=>({value:String(i.version),label:`${Dxs(i.version,i.createdAt)}${i.isCurrent?" (current)":""}`}));return o.jsxs(el.Toolbar,{className:"grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4",children:[o.jsx("div",{}),o.jsx(Om,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:a,value:t??"",onValueChange:i=>r?.(i,n??"")}),o.jsx(Om,{label:"Version B",labelIsHidden:!0,name:"version-b",options:a,value:n??"",onValueChange:i=>r?.(t??"",i)}),o.jsx("div",{})]})}function CWt({children:e,className:t}){return o.jsx("div",{className:K("",t),children:e})}function Fxs({date:e,className:t,withTime:n=!1}){const r=e?M0t(new Date(e)):!1,s=e?J3(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 MRe(e){return!e||e.length===0?"":e?.map(t=>t.size).join(" ")}function zxs({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:MRe(e)},children:n})})}function Bxs({children:e,className:t}){return o.jsx("span",{className:K("py-3",t),children:e})}function Uxs({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 qxs({children:e}){return o.jsx("ul",{className:"grid content-start",children:e})}function Vxs({children:e}){const t=g.useRef(null);return o.jsx("div",{ref:t,className:K("overflow-y-auto"),children:e})}function Hxs({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 Wxs({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,G3.visible,n),children:e});return s==null?a:o.jsxs(bn,{children:[o.jsx(mn,{render:a}),o.jsx(gn,{children:s})]})}function Zxs({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(Pc,{}):o.jsx(_m,{})," ",t]}):e})}function Gxs({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 Qxs({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(uc,{}),"Previous"]}),t&&o.jsxs("button",{onClick:n,children:["Next",o.jsx(Bd,{})]})]})]})}function Yxs({children:e,className:t}){return o.jsx("div",{className:K("grid grid-rows-[auto_1fr] overflow-y-auto",t),children:e})}function Kxs({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:MRe(n)},children:t})}function Xxs({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,G3.visible,{"bg-surface4":t,"hover:bg-surface4":e&&!t&&!i},a),style:{gridTemplateColumns:MRe(s)},disabled:i,children:r});return l==null?d:o.jsxs(bn,{children:[o.jsx(mn,{render:d}),o.jsx(gn,{children:l})]})}function Jxs(e){return e.charAt(0).toUpperCase()+e.slice(1)}function e0s({status:e}){return e?o.jsxs(bn,{children:[o.jsx(mn,{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(gn,{children:Jxs(e)})]}):null}function t0s({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 ont={latest:"Latest version",deleted:"Deleted in this version"};function n0s({version:e,date:t,isLatest:n,isDeleted:r}){return o.jsxs(CWt,{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":ont.latest,children:o.jsx(mt,{variant:"blue",size:"sm",icon:o.jsx(c1,{})})}),r&&o.jsx("span",{className:"inline-flex",role:"img","aria-label":ont.deleted,children:o.jsx(mt,{variant:"red",size:"sm",icon:o.jsx(D0e,{})})})]})]})}const Ap=Object.assign(Yxs,{Header:zxs,HeaderCol:Bxs,Items:qxs,Scroller:Vxs,Row:Kxs,RowButton:Xxs,Message:Zxs,NextPageLoading:Gxs,Pagination:Qxs,Cell:CWt,TextCell:t0s,StatusCell:e0s,VersionCell:n0s,IdCell:Uxs,DateCell:Fxs,LinkCell:Wxs,LabelCell:Hxs}),r0s=[{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"}],Z9={added:{badgeVariant:"blue",borderColor:"border-blue-900",icon:o.jsx(Ir,{}),tooltip:"Added in this version"},changed:{badgeVariant:"yellow",borderColor:"border-yellow-900",icon:o.jsx(Wen,{}),tooltip:"Changed in this version"},same:{badgeVariant:"green",borderColor:"border-green-900",icon:o.jsx(put,{}),tooltip:"Same in both versions"}};function coe({red:e=!1,tooltip:t}){return o.jsxs(bn,{children:[o.jsx(mn,{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(D0e,{className:K("text-neutral3/40 w-5 h-5 ",{"text-red-900":e})})}),o.jsx(gn,{children:t})]})}function uoe({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}=Z9[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(mt,{variant:n,size:"xs",icon:r})})]})}function s0s(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function lnt({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return"added";if(t==="changed"&&n)return"changed"}function a0s({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:a}){const{Link:i}=un(),l=t>n;return o.jsx(Ap,{children:o.jsx(Ap.Scroller,{children:o.jsx(Ap.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=a.get(c),f=s0s(u,d),h=lnt({otherVersionExists:d!==void 0,status:f,isNewer:l}),p=lnt({otherVersionExists:u!==void 0,status:f,isNewer:!l});return o.jsxs(Ap.Row,{columns:r0s,children:[o.jsx(Ap.IdCell,{id:c,isShortened:!1}),f!=="same"?o.jsxs(o.Fragment,{children:[u?.datasetVersion?o.jsx(Ap.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:h?Z9[h].tooltip:void 0,children:o.jsx(uoe,{variant:h,version:u.datasetVersion})}):o.jsx(Ap.Cell,{className:"flex items-center justify-center",children:o.jsx(coe,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?o.jsx(Ap.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:p?Z9[p].tooltip:void 0,children:o.jsx(uoe,{variant:p,version:d.datasetVersion})}):o.jsx(Ap.Cell,{className:"flex items-center justify-center",children:o.jsx(coe,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):o.jsx(Ap.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",tooltip:Z9.same.tooltip,children:o.jsx(uoe,{variant:"same",version:d?.datasetVersion})}),f==="changed"?o.jsx(Ap.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}/versions?version=${u?.datasetVersion}&compare=${d?.datasetVersion}`,children:"Compare"}):o.jsx(Ap.Cell,{children:o.jsx(coe,{tooltip:"Comparing is available only for changed items"})})]},c)})})})})}function i0s(){const e=Br(),[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}=p$n(),{data:p,isLoading:m,error:v}=JH(),y=g.useMemo(()=>p?.experiments??[],[p?.experiments]),b=g.useMemo(()=>ubs(l),[l]),x=c||m,w=u||v,k=()=>{e("/datasets/new")};if(w&&rs(w))return o.jsx(Wn,{children:o.jsx(_s,{})});if(w&&is(w))return o.jsx(Wn,{children:o.jsx(ys,{resource:"datasets"})});if(w)return o.jsx(Wn,{children:o.jsx(Bs,{title:"Failed to load datasets",message:w.message})});if(l.length===0&&!x)return o.jsx(Wn,{children:o.jsx(dbs,{onCreateClick:k})});const O=r!=="all"||a!=="all"||t!=="",_=()=>{n(""),s("all"),i("all")};return o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(gbs,{search:t,onSearchChange:n,experimentFilter:r,onExperimentFilterChange:s,tagFilter:a,onTagFilterChange:i,tagOptions:b,onReset:_,hasActiveFilters:O,onCreateClick:k})}),o.jsx(lbs,{datasets:l,experiments:y,isLoading:x,search:t,experimentFilter:r,tagFilter:a,isFetchingNextPage:d,hasNextPage:f,setEndOfListElement:h})]})}function h8({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function o0s(){const{datasetId:e}=fr(),t=Br(),[n,r]=Ta(),{activeVersion:s,handleVersionChange:a}=$Re(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}=$m(e),{data:b=[],isLoading:x}=Yx(e,void 0,s),w=!x&&b.length===0;if(y)return null;if(v&&rs(v))return o.jsx(h8,{children:o.jsx(_s,{})});if(v&&is(v))return o.jsx(h8,{children:o.jsx(ys,{resource:"datasets"})});if(v&&m0(v)||!y&&!v&&!m)return o.jsx(h8,{children:o.jsx(yr,{iconSlot:o.jsx(Lg,{}),titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:o.jsxs(ae,{as:gi,to:"/datasets",children:[o.jsx(uc,{}),"Back to Datasets"]})})});if(v)return o.jsx(h8,{children:o.jsx(Bs,{title:"Failed to load dataset",message:v instanceof Error?v.message:"An unexpected error occurred. Please try again."})});const k=_=>{t(`/experiments/${_}`)},O=()=>{t("/datasets")};return o.jsxs(pxs,{datasetId:e,items:b,isLoadingItems:x,children:[o.jsxs("div",{className:"h-full",children:[o.jsx(Lt,{height:"full",className:"grid-rows-[1fr] p-0",children:o.jsx(Lt.MainArea,{children:o.jsx(mxs,{datasetId:e,onAddItemClick:()=>u(!0),belowToolbarSlot:o.jsx(gxs,{datasetId:e}),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(ps,{children:[o.jsxs(ae,{as:gi,to:`/experiments?dataset=${e}`,children:[o.jsx(mut,{}),"View experiments"]}),o.jsx(pWt,{datasetId:e,value:s,onValueChange:a,currentVersion:m?.version,className:"w-36"}),w?o.jsxs(bn,{children:[o.jsx(mn,{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(ae,{variant:"primary",children:[o.jsx(Fc,{}),"Run Experiment"]})})})}),o.jsx(gn,{children:"Add items to the dataset before running an experiment"})]}):o.jsxs(ae,{variant:"primary",onClick:()=>l(!0),children:[o.jsx(Fc,{}),"Run Experiment"]}),o.jsxs(at,{children:[o.jsx(at.Trigger,{asChild:!0,children:o.jsx(ae,{size:"lg","aria-label":"Dataset actions menu",children:o.jsx(cI,{})})}),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(Ud,{})," Duplicate Dataset"]}),o.jsxs(at.Item,{onSelect:()=>f(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(cl,{})," Delete Dataset"]})]})]})]})})})}),o.jsx(Ug,{})]}),o.jsx(yY,{initialDatasetId:e,initialDatasetVersion:s??void 0,open:i,onOpenChange:l,onSuccess:k},`${e}:${s??"latest"}`),o.jsx(yxs,{datasetId:e,open:c,onOpenChange:u}),m&&o.jsx(Ibs,{open:h,onOpenChange:p,sourceDatasetId:m.id,sourceDatasetName:m.name,sourceDatasetDescription:m.description,sourceDatasetTargetType:m.targetType}),m&&o.jsx($bs,{open:d,onOpenChange:f,datasetId:m.id,datasetName:m.name,onSuccess:O})]})}function doe({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function l0s(){const{datasetId:e}=fr(),t=Br(),{data:n,error:r,isLoading:s}=$m(e),a=()=>{t(`/datasets/${e}`)};return s?null:r&&rs(r)?o.jsx(doe,{children:o.jsx(_s,{})}):r&&is(r)?o.jsx(doe,{children:o.jsx(ys,{resource:"datasets"})}):r||!n?o.jsx(doe,{children:o.jsx(Bs,{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(al,{className:"mb-6 p-0",children:o.jsxs(al.Column,{children:[o.jsxs(al.Title,{children:[o.jsx(Lg,{})," Edit dataset"]}),o.jsx(al.Description,{children:n.name})]})}),o.jsx(Mc,{className:"p-6",children:o.jsx(Pbs,{dataset:{id:n.id,name:n.name,description:n.description||"",inputSchema:n.inputSchema,groundTruthSchema:n.groundTruthSchema,requestContextSchema:n.requestContextSchema},onSuccess:a,onCancel:a})})]})})]})}function bY({label:e,wide:t=!1,children:n}){return o.jsxs("div",{className:K("pointer-events-none absolute inset-0 z-50","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 p8=()=>{},c0s=new Set,u0s=[{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 d0s({datasetId:e,currentItemId:t,open:n,onOpenChange:r}){const{navigate:s,paths:a}=un(),[i,l]=g.useState(""),[c]=lW(i,300),{data:u,isLoading:d,setEndOfListElement:f,isFetchingNextPage:h,hasNextPage:p}=Yx(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(Ts,{children:"Pick an item to compare with the current one."})]}),o.jsxs(Nr,{className:"grid max-h-[70vh] min-h-[24rem] grid-rows-[auto_1fr] gap-3",children:[o.jsx(_C,{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(mWt,{items:m,isLoading:d,onItemClick:v,selectOnNavigate:!1,columns:u0s,searchQuery:c||" ",setEndOfListElement:f,isFetchingNextPage:h,hasNextPage:p,isSelectionActive:!1,selectedIds:c0s,onToggleSelection:p8,onSelectAll:p8,onClearSelection:p8,onAddClick:p8})})]})]})})}function f0s(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 h0s({datasetId:e,item:t,items:n,onItemChange:r,onClose:s}){const{Link:a}=un(),{updateItem:i,deleteItem:l}=La(),[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,O]=g.useState(t.scorerIds!==void 0),[_,T]=g.useState(t.scorerIds??[]),[E,N]=g.useState(""),[I,A]=g.useState(null),[R,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):""),O(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,F=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 W;if(h.trim())try{W=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 oe=JSON.parse(x);if(!Array.isArray(oe)){Ve.error("Tool Mocks must be a JSON array");return}J=oe}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 oe=await i.mutateAsync({datasetId:e,itemId:t.id,input:U,groundTruth:W,metadata:Y,expectedTrajectory:te,toolMocks:J,scorerIds:re,requestContext:ee});Ve.success("Item updated successfully"),O(oe.scorerIds!==void 0),T(oe.scorerIds??[]),u(!1),A(null)}catch(oe){const X=f0s(oe);X?A(X):Ve.error(`Failed to update item: ${oe instanceof Error?oe.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):""),O(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)},z=U=>{p(U),I?.field==="groundTruth"&&A(null)},P=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(fn,{children:[o.jsxs(fn.Header,{children:[o.jsxs(fn.Heading,{children:["Item ",o.jsxs("b",{children:["# ",t.id.length>12?`${t.id.slice(0,12)}…`:t.id]})]}),o.jsxs(ps,{className:"ml-auto shrink-0",children:[o.jsx(fn.NextPrevNav,{onPrevious:q,onNext:F,previousLabel:"Previous item",nextLabel:"Next item"}),!c&&o.jsxs(o.Fragment,{children:[o.jsx(ae,{as:a,href:`/datasets/${e}/items/${t.id}/versions?version=${t.datasetVersion}`,size:"md",tooltip:"Go to item versions history","aria-label":"Go to item versions history",children:o.jsx(d3,{})}),o.jsxs(at,{children:[o.jsx(at.Trigger,{asChild:!0,children:o.jsx(ae,{size:"md","aria-label":"Actions menu",children:o.jsx(cI,{})})}),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(S2,{}),"Compare with…"]}),o.jsxs(at.Item,{onSelect:()=>L(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(cl,{}),"Delete Item"]})]})]})]}),o.jsx(fn.CloseButton,{onClick:s,tooltip:"Close detail panel"})]})]}),o.jsx(fn.Content,{children:c?o.jsx(wxs,{inputValue:d,setInputValue:G,groundTruthValue:h,setGroundTruthValue:z,metadataValue:m,setMetadataValue:v,trajectoryValue:y,setTrajectoryValue:b,toolMocksValue:x,setToolMocksValue:w,scorerOverrideEnabled:k,setScorerOverrideEnabled:O,selectedScorerIds:_,setSelectedScorerIds:T,requestContextValue:E,setRequestContextValue:N,validationErrors:I,onSave:V,onCancel:M,isSaving:i.isPending}):o.jsx(MV,{item:t})})]}),o.jsx(d0s,{datasetId:e,currentItemId:t.id,open:D,onOpenChange:B}),o.jsx(Tt,{open:R,onOpenChange:L,children:o.jsxs(Tt.Content,{children:[o.jsxs(Tt.Header,{children:[o.jsx(Tt.Title,{children:"Delete Item"}),o.jsx(Tt.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),o.jsxs(Tt.Footer,{children:[o.jsx(Tt.Cancel,{children:"Cancel"}),o.jsx(Tt.Action,{onClick:P,children:l.isPending?"Deleting...":"Yes, Delete"})]})]})})]})}function p0s(){const{itemId:e}=fr(),{datasetId:t,items:n,isLoadingItems:r,openItem:s,close:a}=yWt(),i=g.useMemo(()=>n.find(d=>d.id===e)??null,[n,e]),{data:l,isLoading:c}=e3(i?"":t,!i&&e?e:""),u=i??l??null;return e?o.jsx(bY,{label:`Dataset item ${e}`,children:u?o.jsx("div",{className:"[&>section]:bg-surface3 flex h-full min-h-0 flex-col p-3 [&>section]:min-h-0 [&>section]:flex-1 [&>section]:rounded-lg [&>section]:shadow-lg",children:o.jsx(h0s,{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(Ht,{})})}):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(yr,{iconSlot:o.jsx(Lg,{}),titleSlot:"Item not found",descriptionSlot:`No loaded item "${e}".`,actionSlot:o.jsx(ae,{onClick:a,children:"Close"})})})})}):null}function cnt(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,expectedTrajectory:e.expectedTrajectory??null,toolMocks:e.toolMocks??null,scorerIds:e.scorerIds??null,requestContext:e.requestContext??null,metadata:e.metadata??null},null,2)}function m0s(){const{datasetId:e,itemId:t,secondItemId:n}=fr(),r=Br(),s=[t,n].filter(p=>!!p),{data:a,error:i}=$m(e??""),{Link:l,paths:c}=un(),[u,d]=g.useState(!1),{data:f}=e3(e??"",s[0]??""),{data:h}=e3(e??"",s[1]??"");return i&&rs(i)?o.jsx(ks,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(_s,{})})}):i&&is(i)?o.jsx(ks,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ys,{resource:"datasets"})})}):!e||s.length<2?o.jsx(ks,{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(ks,{children:[o.jsx(o0,{owner:"dataset-items-compare",children:o.jsxs(ae,{as:gi,to:`/datasets/${e}`,variant:"outline",children:[o.jsx(uc,{}),"Back to Dataset"]})}),o.jsxs(Lt,{height:"full",className:K({"grid-rows-[auto_auto_minmax(0,1fr)]":u}),children:[o.jsx(Lt.TopArea,{children:o.jsxs(al,{withMargins:!1,children:[o.jsxs(al.Column,{children:[o.jsxs(al.Title,{size:"smaller",children:[o.jsx(S2,{}),"Compare Dataset Items"]}),o.jsx(al.Description,{children:o.jsxs(Rc,{children:["Comparing ",s.length," items of"," ",o.jsx(gi,{to:`/datasets/${e}`,className:"text-info1 hover:underline",children:a?.name||e?.slice(0,8)})]})})]}),o.jsx(al.Column,{children:o.jsx(ps,{children:o.jsx(ae,{variant:"primary",onClick:()=>d(p=>!p),children:u?o.jsxs(o.Fragment,{children:[o.jsx(UV,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(yXt,{})," Diff View"]})})})})]})}),o.jsx(Ij,{className:"grid-cols-2 gap-6",children:s.map((p,m)=>o.jsx(g0s,{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]))}},p))}),u&&f&&h&&o.jsx("div",{className:"mt-6 min-h-0 overflow-y-auto",children:o.jsx(LVt,{codeA:cnt(f),codeB:cnt(h)})})]})]})}function g0s({datasetId:e,itemId:t,Link:n,idx:r,itemIds:s,onItemChange:a,showContent:i=!0}){const{data:l,isLoading:c}=e3(e,t),{data:u}=Yx(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(Mc,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[o.jsxs(wx,{className:"flex items-center gap-4",children:[o.jsxs(da,{name:`compare-item-${r}`,value:t,onValueChange:a,children:[o.jsx(ha,{"aria-label":"Item",className:"w-full",children:o.jsx(fa,{placeholder:"Select item"})}),o.jsx(pa,{children:f.map(h=>o.jsx(xr,{value:h.value,disabled:h.disabled,children:h.label},h.value))})]}),o.jsxs(ae,{as:n,to:`/datasets/${e}/items/${t}`,children:[o.jsx(d3,{}),"Versions"]})]}),i&&o.jsx(Dd,{className:"grid content-start gap-8 overflow-y-auto",children:c?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):l?o.jsxs(o.Fragment,{children:[o.jsx(bxs,{item:l}),o.jsx(MV,{item:l})]}):o.jsxs("div",{className:"text-neutral4 text-sm",children:["Item ",t.slice(0,8)," not found"]})})]})}function unt(e,t){return{id:e.id,datasetId:t,datasetVersion:e.datasetVersion,input:e.input,groundTruth:e.groundTruth,expectedTrajectory:e.expectedTrajectory,toolMocks:e.toolMocks,scorerIds:e.scorerIds,requestContext:e.requestContext,metadata:e.metadata,createdAt:e.createdAt,updatedAt:e.updatedAt}}function dnt(e,t){return e.map(n=>{const r=typeof n.updatedAt=="string"?new Date(n.updatedAt):n.updatedAt;return{value:String(n.datasetVersion),label:o.jsxs("span",{className:"flex w-full items-center gap-2",children:[o.jsxs("span",{children:[o.jsxs("b",{children:["v. ",n.datasetVersion]})," · ",dr(r,"MMM d, HH:mm")]}),n.isLatest?o.jsx(mt,{variant:"blue",size:"xs",className:"ml-auto",children:"Latest"}):null]}),disabled:t?.has(n.datasetVersion)??!1}})}function fnt(e){const t=Number(e);return e!=null&&Number.isFinite(t)&&t>0?t:null}function v0s(){const{datasetId:e,itemId:t}=fr(),[n,r]=Ta(),s=fnt(n.get("version")),a=fnt(n.get("compare")),i=n.get("view")==="diff",{data:l,error:c}=$m(e??""),{data:u,isLoading:d}=Hys(e??"",t??""),f=(s!=null?u?.find(_=>_.datasetVersion===s):void 0)??u?.[0],h=f?.datasetVersion??null,p=a!=null&&a!==h?a:null,{data:m,isLoading:v}=Wys(e??"",t??"",p??0,l?.version),y=(_,T)=>r(E=>{const N=new URLSearchParams(E);return T==null?N.delete(_):N.set(_,String(T)),N},{replace:!0});if(c&&rs(c))return o.jsx(ks,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(_s,{})})});if(c&&is(c))return o.jsx(ks,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ys,{resource:"datasets"})})});if(!e||!t)return o.jsx(ks,{children:o.jsx(by,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Item not found."})})})});const b=!!(f&&m),x=i&&b,w=f?unt(f,e):null,k=m?unt(m,e):null,O=(f?.datasetVersion??0)<(m?.datasetVersion??0);return o.jsxs(ks,{children:[o.jsx(o0,{owner:"dataset-item-versions",children:b&&o.jsx(ae,{variant:"outline",onClick:()=>y("view",i?null:"diff"),children:i?o.jsxs(o.Fragment,{children:[o.jsx(UV,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(fJt,{})," Diff View"]})})}),o.jsx(Lt,{height:"full",className:"grid-rows-[minmax(0,1fr)]",children:o.jsxs("div",{className:"grid min-h-0 grid-cols-1 gap-6 md:grid-cols-2",children:[o.jsxs(Mc,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[o.jsx(wx,{children:o.jsx(hnt,{name:"version",value:h!=null?String(h):"",options:dnt(u??[],p!=null?new Set([p]):void 0),onValueChange:_=>y("version",Number(_))})}),o.jsx(Dd,{className:"grid content-start gap-8 overflow-y-auto",children:d?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):w?o.jsx(MV,{item:w,diff:x&&k?{against:k,side:O?"a":"b"}:void 0}):o.jsx("div",{className:"text-neutral4 text-sm",children:"Item data not available"})})]}),o.jsxs(Mc,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[o.jsx(wx,{children:o.jsx(hnt,{name:"compare",value:p!=null?String(p):"",placeholder:"Select a version to compare",options:dnt(u??[],h!=null?new Set([h]):void 0),onValueChange:_=>y("compare",Number(_))})}),o.jsx(Dd,{className:"grid content-start gap-8 overflow-y-auto",children:p==null?o.jsx(yr,{className:"h-full",iconSlot:o.jsx(S2,{className:"text-neutral3 size-8"}),titleSlot:"No version selected",descriptionSlot:"Pick a version above to compare it with the one on the left."}):v?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):k?o.jsx(MV,{item:k,diff:x&&w?{against:w,side:O?"b":"a"}:void 0}):o.jsxs("div",{className:"text-neutral4 text-sm",children:["Version ",p," not found"]})})]})]})})]})}function hnt({name:e,value:t,options:n,placeholder:r="Select version",onValueChange:s}){return o.jsxs("div",{className:"grid grid-cols-[auto_1fr] items-center gap-4",children:[o.jsx(d3,{className:"size-4 opacity-50"}),o.jsxs(da,{name:e,value:t,onValueChange:s,children:[o.jsx(ha,{"aria-label":e==="compare"?"Compare version":"Version",className:"w-full",children:o.jsx(fa,{placeholder:r,className:"flex-1"})}),o.jsx(pa,{children:n.map(a=>o.jsx(xr,{value:a.value,disabled:a.disabled,children:a.label},a.value))})]})]})}function y0s(){const{datasetId:e}=fr(),[t]=Ta(),n=t.get("ids")?.split(",").map(Number).filter(m=>!isNaN(m)&&m>0)??[],r=Br(),{data:s,error:a}=$m(e??""),i=Yx(e??"",void 0,n[0]??null),l=Yx(e??"",void 0,n[1]??null),c=g.useMemo(()=>i.data??[],[i.data]),u=g.useMemo(()=>l.data??[],[l.data]),d=g.useMemo(()=>{const m=new Map;for(const v of[...c,...u])m.has(v.id)||m.set(v.id,{id:v.id,createdAt:new Date(v.createdAt)});return[...m.values()].sort((v,y)=>y.createdAt.getTime()-v.createdAt.getTime())},[c,u]),f=g.useMemo(()=>new Map(c.map(m=>[m.id,m])),[c]),h=g.useMemo(()=>new Map(u.map(m=>[m.id,m])),[u]);if(a&&rs(a))return o.jsx(ks,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(_s,{})})});if(a&&is(a))return o.jsx(ks,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ys,{resource:"datasets"})})});if(!e||n.length<2)return o.jsx(ks,{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=(m,v)=>{r(`/datasets/${e}/versions?ids=${m},${v}`,{replace:!0})};return o.jsx(ks,{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(al,{children:[o.jsxs(al.Column,{children:[o.jsxs(al.Title,{children:[o.jsx(Stn,{})," Compare Dataset Versions"]}),o.jsx(al.Description,{children:o.jsxs(Rc,{children:[o.jsx(d3,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),o.jsx(al.Column,{children:o.jsxs(ae,{as:gi,to:`/datasets/${e}`,children:[o.jsx(uc,{}),"Back to Dataset"]})})]}),o.jsx(Ij,{children:o.jsxs(el,{children:[o.jsx(Lxs,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:p}),o.jsx(a0s,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:h})]})})]})})})}const b0s=["agent","workflow","scorer","processor"],x0s=new Set(b0s);function w0s(e){return typeof e=="string"&&x0s.has(e)}function S0s(){const e=Br(),[t]=Ta(),n=t.get("targetType"),r=w0s(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(al,{className:"mb-6 p-0",children:o.jsxs(al.Column,{children:[o.jsxs(al.Title,{children:[o.jsx(Lg,{})," Create new dataset"]}),o.jsx(al.Description,{children:"Datasets group test cases used to evaluate your agents and workflows."})]})}),o.jsx(Mc,{className:"p-6",children:o.jsx(Tbs,{targetType:r,targetIds:a,onSuccess:i=>{e(`/datasets/${i}`)},onCancel:()=>{e(-1)}})})]})})]})}function w0e({children:e,className:t}){return o.jsx("div",{className:K("flex flex-wrap gap-8",t),children:e})}function k0s(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 O0s({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=k0s(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 _Wt({open:e,onOpenChange:t,experimentId:n,experimentName:r,onSuccess:s}){const{deleteExperiment:a}=La(),i=async()=>{try{await a.mutateAsync(n),Ve.success("Experiment deleted successfully"),t(!1),s?.()}catch(l){Ve.error(`Failed to delete experiment: ${l instanceof Error?l.message:"Unknown error"}`)}};return o.jsx(Tt,{open:e,onOpenChange:t,children:o.jsxs(Tt.Content,{children:[o.jsxs(Tt.Header,{children:[o.jsx(Tt.Title,{children:"Delete Experiment"}),o.jsxs(Tt.Description,{children:['Are you sure you want to delete "',r||n,'"? This will permanently delete the experiment, all its results, and the traces it produced, including their spans and any scores, feedback, metrics and logs attached to those traces. This action cannot be undone.']})]}),o.jsxs(Tt.Footer,{children:[o.jsx(ae,{variant:"primary",size:"lg",onClick:i,disabled:a.isPending,children:a.isPending?"Deleting...":"Delete"}),o.jsx(Tt.Cancel,{children:"Cancel"})]})]})})}function EWt(e){const t=w0(e.id)??e.id;return e.name||`Experiment #${t}`}const C0s=60;function _0s({experiment:e}){return o.jsx("span",{className:"text-neutral4 block min-w-0 truncate text-left",children:EWt(e)})}function E0s({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<=C0s?n:o.jsxs(bn,{children:[o.jsx(mn,{asChild:!0,children:n}),o.jsx(gn,{children:t})]})}const xY=()=>{const{requestContext:e}=bs(),t=Qe();return gt({queryKey:["processors"],queryFn:()=>t.listProcessors(e)})},TWt=(e,t)=>{const n=Qe(),{requestContext:r}=bs();return gt({queryKey:["processor",e],queryFn:()=>n.getProcessor(e).details(r),enabled:!!e})},T0s=()=>{const e=Qe(),{requestContext:t}=bs();return wn({mutationFn:async({processorId:n,phase:r,messages:s,agentId:a})=>e.getProcessor(n).execute({phase:r,messages:s,agentId:a,requestContext:t})})};function jWt(){const{data:e}=Um(),{data:t}=Ky(),{data:n}=up(),{data:r}=xY();return{agents:e,workflows:t,scorers:n,processors:r}}const NWt={agent:uo,workflow:_u,scorer:EA,processor:oV},IWt={agent:"Agent",workflow:"Workflow",scorer:"Scorer",processor:"Processor"},j0s="External (caller-run)";function AWt(e,{agents:t,workflows:n,scorers:r,processors:s}){const{targetType:a,targetId:i}=e;if(!i)return j0s;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 N0s({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(fe.Cell,{children:o.jsx(_0s,{experiment:e})}),o.jsx(fe.Cell,{children:o.jsx(E0s,{experiment:e})}),t!==void 0&&o.jsx(fe.TextCell,{children:t}),o.jsx(fe.Cell,{children:o.jsx(I0s,{experiment:e})}),o.jsx(fe.Cell,{children:o.jsx(mt,{variant:vVt[r]??"neutral",indicator:"dot",children:qT[r]??r})}),o.jsx(fe.TextCell,{className:"text-center",children:i}),o.jsx(fe.TextCell,{className:"text-center",children:s}),o.jsx(fe.TextCell,{className:"text-center",children:o.jsx("span",{className:a>0?"text-accent2":"",children:a})}),o.jsx(fe.Cell,{className:"text-center",children:o.jsx(A0s,{review:n})}),o.jsx(fe.TextCell,{children:vfs(e.createdAt)})]})}function I0s({experiment:e}){const t=jWt(),n=AWt(e,t),r=e.targetId?e.targetType:null,s=r?NWt[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":IWt[r],children:o.jsx(s,{})}),o.jsx("span",{className:r?"truncate":"text-neutral2 truncate",children:n})]})}function A0s({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(mt,{size:"xs",variant:"yellow",children:[e.needsReview," pending"]}):o.jsxs(mt,{size:"xs",variant:"green",children:[e.complete,"/",t," reviewed"]})}const RWt=`${hfs} ${pfs} ${mfs} ${gfs}`,pnt=`${RWt} auto`,R0s=[{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 P0s({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}=un(),f=g.useMemo(()=>{const k=new Map;return t?.forEach(O=>k.set(O.id,O.name)),k},[t]),h=g.useMemo(()=>[...e].sort((k,O)=>{const _=k.createdAt?new Date(k.createdAt).getTime():0;return(O.createdAt?new Date(O.createdAt).getTime():0)-_}),[e]),p=g.useMemo(()=>{const k=s.toLowerCase();return h.filter(O=>{const _=O.datasetId?f.get(O.datasetId)??"":"",T=!k||O.id.toLowerCase().includes(k)||(O.name??"").toLowerCase().includes(k)||_.toLowerCase().includes(k)||(O.targetId??"").toLowerCase().includes(k),E=a==="all"||O.status===a,N=i==="all"||O.datasetId===i;return T&&E&&N})},[h,s,f,a,i]),{containerRef:m,getRowProps:v}=no({count:p.length}),[y,b]=g.useState(null);if(r)return o.jsx(Lo,{columns:pnt});const x=c?`auto ${RWt}`:pnt,w=R0s.map(k=>o.jsx(fe.TopCell,{className:k.className,children:k.label},k.label));return o.jsxs(fe,{columns:x,scrollRef:m,children:[o.jsx(fe.Top,{hasLeadingCell:c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(fe.TopCell,{children:" "}),o.jsx(fe.TopCells,{colStart:2,children:w})]}):o.jsxs(o.Fragment,{children:[w,o.jsx(fe.TopCell,{"aria-hidden":!0,children:null})]})}),p.map((k,O)=>{const _=k.datasetId?f.get(k.datasetId)??w0(k.datasetId)??k.datasetId:"—",T=o.jsx(N0s,{experiment:k,datasetName:_,review:n?.get(k.id)});if(!l)return o.jsxs(fe.RowWrapper,{children:[o.jsx(fe.RowLink,{colEnd:-2,to:u.experimentLink(k.id),LinkComponent:d,...v(O),children:T}),o.jsx(fe.ActionsCell,{className:"pl-2",children:o.jsx(ae,{type:"button",variant:"ghost",size:"icon-xs",tooltip:"Delete experiment","aria-label":`Delete experiment ${k.name??k.id}`,onClick:I=>{I.stopPropagation(),b(k)},children:o.jsx(cl,{className:"size-4"})})})]},k.id);const E=l.selectedExperimentIds.includes(k.id),N=()=>l.onToggleSelection(k.id);return o.jsxs(fe.RowWrapper,{children:[o.jsx(fe.SelectCell,{checked:E,onToggle:N,"aria-label":`Select experiment ${k.id}`}),o.jsx(fe.RowButton,{colStart:2,featured:E,onClick:N,...v(O),children:T})]},k.id)}),y&&o.jsx(_Wt,{open:!0,onOpenChange:k=>{k||b(null)},experimentId:y.id,experimentName:y.name??void 0})]})}const $0s=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function M0s(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const m8={completed:Y7.neutral3,running:"#facc15",pending:"#fb923c",failed:"#f87171"},D0s=[{label:"Completed",color:m8.completed},{label:"Running",color:m8.running},{label:"Pending",color:m8.pending},{label:"Failed",color:m8.failed}];function L0s({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(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Experiments by Dataset",description:"Experiment status breakdown per dataset."}),i&&o.jsx(Vt.Summary,{value:String(e?.length??0),label:"Total experiments"})]}),n?o.jsx(Vt.Loading,{}):r?o.jsx(Vt.Error,{message:"Failed to load experiments data"}):o.jsx(Vt.Content,{children:i?o.jsx(tI,{data:s,segments:D0s,maxVal:a,fmt:l=>String(l)}):o.jsx(Vt.NoData,{message:"No experiments have been run yet"})})]})}const F0s=({onRunExperiment:e})=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(yr,{iconSlot:o.jsx(Cs,{}),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(ae,{variant:"primary",onClick:e,children:[o.jsx(Fc,{}),"Run Experiment"]}),o.jsxs(ae,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/evals/experiments",target:"_blank",rel:"noopener noreferrer",children:["Experiments Documentation ",o.jsx(Fs,{})]})]})})});function z0s({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(mt,{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(_ut,{})]}),o.jsxs(ps,{children:[o.jsxs(ae,{variant:"primary",disabled:!b,onClick:m,children:[o.jsx(S2,{className:"h-4 w-4"}),"Compare Experiments"]}),o.jsx(ae,{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(ps,{children:[o.jsx(Om,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...$0s],value:n,onValueChange:r,className:"whitespace-nowrap"}),o.jsx(Om,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:i,value:s,onValueChange:a,className:"whitespace-nowrap"}),l&&c&&o.jsxs(ae,{onClick:l,size:"sm",variant:"default",children:[o.jsx(tr,{className:"size-3"})," Reset"]})]}),o.jsxs(ps,{className:"ml-auto shrink-0",children:[f&&o.jsxs(ae,{onClick:f,tooltip:"Select two experiments of the same dataset to compare",children:[o.jsx(S2,{}),"Compare"]}),u&&o.jsxs(ae,{onClick:u,tooltip:d,variant:"primary",children:[o.jsx(Fc,{}),"Run Experiment"]})]})]})}const B0s={present:!1,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},mnt=e=>e?e instanceof Date?e.toISOString():e:null,gnt=e=>{const t=new Map;for(const n of e??[])t.set(n.itemId,n);return t},vnt=(e,t,n)=>{if(!e)return B0s;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:mnt(t?.startedAt),completedAt:mnt(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))}},U0s=({comparison:e,baselineId:t,contenderId:n,baselineResults:r,contenderResults:s,baselineScores:a,contenderScores:i})=>{if(!e)return[];const l=gnt(r),c=gnt(s);return e.items.map(u=>{const d=vnt(u.results[t],l.get(u.itemId),a?.[u.itemId]),f=vnt(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 Uk({title:e,actions:t,tone:n="default",defaultOpen:r=!0,children:s}){return o.jsxs(cc,{defaultOpen:r,className:"grid gap-2",children:[o.jsxs("div",{className:"flex min-h-6 items-center justify-between gap-2",children:[o.jsxs(Bl,{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(Fr,{}),e]}),t]}),o.jsx(Ul,{role:"region","aria-label":e,children:s})]})}function ynt({label:e,value:t}){return t==null?null:o.jsx(Uk,{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 PWt({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(GYt,{className:"size-3.5"}):e<0?o.jsx(LYt,{className:"size-3.5"}):null]})}function $Wt({scorerId:e,value:t,delta:n,reason:r}){const{Link:s,paths:a}=un();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(EA,{}),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(PWt,{delta:n})]})]}),r&&o.jsx("p",{className:"text-neutral3 text-sm",children:r})]})}function bnt(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function q0s(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 V0s="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 xnt({side:e,row:t,showDeltas:n,isLoading:r}){const s=t[e],a=q0s(s);if(r)return o.jsx("div",{className:"flex h-32 items-center justify-center",children:o.jsx(Ht,{})});if(!s.present)return o.jsx("p",{className:"text-neutral3 py-8 text-center text-sm",children:"Not present in this experiment"});const i=bnt(s.output);return o.jsxs("div",{className:"grid content-start gap-5",children:[a&&o.jsxs(bn,{children:[o.jsx(mn,{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(gn,{children:"Run duration"})]}),s.error?o.jsx(Uk,{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(Uk,{title:"Output",actions:o.jsx(_a,{content:i}),children:o.jsx("pre",{className:V0s,children:i})}),s.scores.length>0&&o.jsx(Uk,{title:"Scores",children:o.jsx("div",{className:"grid gap-2",children:s.scores.map(l=>o.jsx($Wt,{scorerId:l.scorerId,value:l.value,delta:n?t.deltas[l.scorerId]:null,reason:l.reason},l.scorerId))})}),s.comment&&o.jsx(Uk,{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(Uk,{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:bnt(c)})]},l))})})]})}const H0s={baseline:"Baseline",contender:"Contender"},W0s={baseline:"purple",contender:"blue"},Z0s="flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0";function wnt({side:e,experiment:t,summary:n,showDeltas:r,versionMismatch:s}){const{Link:a,paths:i}=un(),l=H0s[e],c=t?w0(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(mt,{variant:W0s[e],size:"xs",children:l}),t&&o.jsx(ae,{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(Rc,{children:[o.jsx(c3,{})," ",c]}),t.targetType==="agent"&&t.targetId?o.jsxs(a,{href:i.agentLink(t.targetId),className:Z0s,children:[o.jsx(uo,{}),o.jsx("span",{className:"min-w-0 truncate",children:t.targetId})]}):o.jsxs(Rc,{children:[o.jsx(Put,{})," ",t.targetId]}),o.jsx("span",{className:K(s&&"text-accent6"),children:o.jsxs(Rc,{children:[o.jsx(WV,{})," v",t.datasetVersion??"—",s&&" · different dataset version"]})}),u&&o.jsxs(Rc,{children:[o.jsx(X9,{})," ",dr(u,"MMM d, yyyy HH:mm")]})]}),d.length>0&&o.jsx(Uk,{title:"Overall score",children:o.jsx("div",{className:"grid gap-2",children:d.map(({scorerId:f,average:h,delta:p})=>o.jsx($Wt,{scorerId:f,value:h,delta:r?p:null},f))})})]})}const YE="min-w-0 px-4 py-3";function G0s({datasetId:e,experimentIdA:t,experimentIdB:n}){const{Link:r,paths:s}=un(),{data:a,isLoading:i,error:l}=Zys(e,t,n),{data:c}=XD(e,t),{data:u}=XD(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}=JD({datasetId:e,experimentId:f,experimentStatus:p?.status}),{data:b,isLoading:x}=JD({datasetId:e,experimentId:h,experimentStatus:m?.status}),{data:w}=PC(f,p?.status),{data:k}=PC(h,m?.status),O=g.useMemo(()=>U0s({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(O.flatMap(E=>Object.keys(E.deltas)))].sort(),[O]),T=g.useMemo(()=>{const E=(A,R)=>{const L=O.map(D=>D[A].scores.find(B=>B.scorerId===R)?.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 R=E("baseline",A),L=E("contender",A);return{scorerId:A,average:L,delta:R!=null&&L!=null?L-R:null}});return{baseline:N,contender:I}},[O,_]);return i?o.jsx("div",{className:"flex h-64 items-center justify-center",children:o.jsx(Ht,{})}):l?o.jsx(An,{variant:"warning",title:"Error loading comparison",children:o.jsx(An.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:`${YE} text-neutral3 text-ui-sm uppercase`,children:"Items"}),o.jsx("div",{role:"columnheader","aria-label":"Baseline",className:YE,children:o.jsx(wnt,{side:"baseline",experiment:p,summary:T.baseline,versionMismatch:d})}),o.jsx("div",{role:"columnheader","aria-label":"Contender",className:YE,children:o.jsx(wnt,{side:"contender",experiment:m,summary:T.contender,versionMismatch:d,showDeltas:!0})})]}),O.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:`${YE} 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(PWt,{delta:A},I))}),o.jsxs("div",{className:"grid pt-3",children:[o.jsx(ynt,{label:"Input",value:E.input}),o.jsx(ynt,{label:"Ground truth",value:E.groundTruth})]})]}),o.jsx("div",{role:"cell","aria-label":"Baseline",className:YE,children:o.jsx(xnt,{side:"baseline",row:E,isLoading:y})}),o.jsx("div",{role:"cell","aria-label":"Contender",className:YE,children:o.jsx(xnt,{side:"contender",row:E,isLoading:x,showDeltas:!0})})]},E.itemId)})]})})}const Q0s=100;function wY(e){const t=Qe(),n={perPage:Q0s};return gt({queryKey:e?["dataset-experiments",e,n]:["experiments",n],queryFn:()=>e?t.listDatasetExperiments(e,n):t.listExperiments(n)})}const MWt=(e,t)=>{const n=Qe(),{data:r,isLoading:s}=wY(void 0),a=r?.experiments,i=t?a?.filter(c=>c.id===t):a,l=gt({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}},Y0s=({experimentId:e}={})=>MWt("needs-review",e),K0s=({experimentId:e}={})=>MWt("complete",e);function X0s(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 J0s({datasetId:e,experimentId:t,featuredItemId:n,detailPanelVariant:r="inline"}){const s=Qe(),{data:a}=$m(e??""),{data:i,isLoading:l}=Y0s({experimentId:t}),{data:c,isLoading:u}=K0s({experimentId:t}),{updateExperimentResult:d}=La(),[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),[O,_]=g.useState(!1),[T,E]=g.useState(""),[N,I]=g.useState(""),[A,R]=g.useState(""),[L,D]=g.useState([]),[B,H]=g.useState(!1),[q,F]=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 Oe of a.tags)de.add(Oe);for(const Oe of V)for(const Ne of Oe.tags)de.add(Ne);return[...de].sort()},[a,V]),G=g.useCallback(de=>{!a||!e||(a.tags??[]).includes(de)},[a,e]),z=g.useMemo(()=>p?p==="__untagged__"?V.filter(de=>de.tags.length===0):V.filter(de=>de.tags.includes(p)):V,[V,p]),P=g.useMemo(()=>{const de=new Map;for(const Oe of V)for(const Ne of Oe.tags)de.set(Ne,(de.get(Ne)??0)+1);return[...de.entries()].sort((Oe,Ne)=>Ne[1]-Oe[1])},[V]),U=g.useMemo(()=>V.filter(de=>de.tags.length===0).length,[V]),W=g.useMemo(()=>{let de=0;return p&&de++,b&&de++,de},[p,b]),Y=g.useCallback((de,Oe)=>{const Ne=V.find(be=>be.id===de);Ne?.experimentId&&Ne?.datasetId&&d.mutate({datasetId:Ne.datasetId,experimentId:Ne.experimentId,resultId:Ne.id,tags:Oe})},[V,d]),te=g.useCallback((de,Oe)=>{const Ne=V.find(be=>be.id===de);Ne?.traceId&&Oe!==void 0&&s.createFeedback({feedback:{traceId:Ne.traceId,source:"studio",feedbackSource:"studio",feedbackType:"rating",value:Oe==="positive"?1:-1,reviewStatus:"reviewed",experimentId:Ne.experimentId??void 0,sourceId:Ne.id}}).catch(()=>{}),F(be=>({...be,[de]:Oe}))},[V,s]),J=g.useCallback((de,Oe)=>{const Ne=V.find(be=>be.id===de);Ne?.experimentId&&Ne?.datasetId&&d.mutate({datasetId:Ne.datasetId,experimentId:Ne.experimentId,resultId:Ne.id,comment:Oe}),Ne?.traceId&&s.createFeedback({feedback:{traceId:Ne.traceId,source:"studio",feedbackSource:"studio",feedbackType:"comment",value:Oe,comment:Oe,reviewStatus:"reviewed",experimentId:Ne.experimentId??void 0,sourceId:Ne.id}}).catch(()=>{})},[V,s,d]),ee=g.useCallback(de=>{const Oe=V.find(Ne=>Ne.id===de);y(Ne=>{const be=new Set(Ne);return be.delete(de),be}),f===de&&h(null),Oe?.experimentId&&Oe?.datasetId&&d.mutate({datasetId:Oe.datasetId,experimentId:Oe.experimentId,resultId:Oe.id,status:null})},[V,d,f]),re=g.useCallback(de=>{const Oe=V.find(Ne=>Ne.id===de);y(Ne=>{const be=new Set(Ne);return be.delete(de),be}),f===de&&h(null),Oe?.experimentId&&Oe?.datasetId&&d.mutate({datasetId:Oe.datasetId,experimentId:Oe.experimentId,resultId:Oe.id,status:"complete"})},[V,d,f]),oe=g.useMemo(()=>{const de=b?c??[]:z;return!b||!p?de:p==="__untagged__"?de.filter(Oe=>Oe.tags.length===0):de.filter(Oe=>Oe.tags.includes(p))},[b,c,z,p]),X=b?u:!1,ne=g.useMemo(()=>new Set(oe.map(de=>de.id)),[oe]),se=g.useMemo(()=>[...v].filter(de=>ne.has(de)).length,[v,ne]),ce=oe.length>0&&se===oe.length,le=se>0&&!ce,ye=g.useCallback(de=>{y(Oe=>{const Ne=new Set(Oe);return Ne.has(de)?Ne.delete(de):Ne.add(de),Ne})},[]),he=g.useCallback(()=>{y(ce?new Set:new Set(oe.map(de=>de.id)))},[ce,oe]),xe=g.useCallback(de=>{for(const Oe of v){const Ne=V.find(be=>be.id===Oe);Ne&&!Ne.tags.includes(de)&&Y(Oe,[...Ne.tags,de])}},[V,v,Y]),Ae=g.useCallback(de=>{for(const Oe of v){const Ne=V.find(be=>be.id===Oe);Ne&&Ne.tags.includes(de)&&Y(Oe,Ne.tags.filter(be=>be!==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]),$e=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 Oe=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});Oe.proposedTags&&Oe.proposedTags.length>0&&(D(Oe.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 Oe=V.find(Ne=>Ne.id===de.itemId);if(Oe){const Ne=[...new Set([...Oe.tags,...de.tags])];Y(Oe.id,Ne)}}H(!1)},[L,V,Y]),Te=g.useCallback(de=>{h(Oe=>Oe===de?null:de)},[]),je=g.useMemo(()=>f?oe.find(de=>de.id===f)??null:null,[f,oe]),ze=f?oe.findIndex(de=>de.id===f):-1,_e=ze>0?()=>h(oe[ze-1].id):void 0,Fe=ze>=0&&ze<oe.length-1?()=>h(oe[ze+1].id):void 0,tt="auto minmax(0,20rem) minmax(0,1fr) minmax(0,8rem) 6rem 6rem",{containerRef:Ge,getRowProps:ge}=no({count:oe.length});if(l)return o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(Ht,{className:"h-6 w-6"})});const Se=je?o.jsx(xVt,{className:"h-full",item:je,isCompleted:b,tagVocabulary:M,onRate:de=>te(je.id,de),onSetTags:de=>{Y(je.id,de);for(const Oe of de)M.includes(Oe)||G(Oe)},onComment:de=>J(je.id,de),onRemove:()=>ee(je.id),onComplete:b?void 0:()=>re(je.id),onPrevious:_e,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:O,onOpenChange:_,children:o.jsxs(mr,{children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Analyze Items"}),o.jsx(Ts,{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(Qy,{value:N,onValueChange:I})]}),o.jsxs("div",{children:[o.jsx(Dt,{className:"mb-1 block text-xs",children:"Model"}),o.jsx(Yy,{llmId:N,value:A,onValueChange:R})]})]}),o.jsxs(me,{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(So,{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(Fl,{children:[o.jsx(ae,{variant:"outline",onClick:()=>_(!1),children:"Cancel"}),o.jsxs(ae,{onClick:Re,disabled:!N||!A||w,children:[w?o.jsx(Ht,{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(Ts,{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,Oe)=>{const Ne=V.find(be=>be.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(Bo,{checked:de.accepted,onCheckedChange:be=>D(ve=>ve.map((ke,Pe)=>Pe===Oe?{...ke,accepted:!!be}:ke))}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(me,{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((be,ve)=>o.jsx(SVt,{tag:be,onRename:ke=>D(Pe=>Pe.map((He,yt)=>yt===Oe?{...He,tags:He.tags.map((Ee,et)=>et===ve?ke:Ee)}:He)),onRemove:()=>D(ke=>ke.map((Pe,He)=>He===Oe?{...Pe,tags:Pe.tags.filter((yt,Ee)=>Ee!==ve)}:Pe))},`${be}-${ve}`))}),de.reason&&o.jsx(me,{variant:"ui-xs",className:"text-neutral3 mt-1 block italic",children:de.reason})]})]})},de.itemId)})}),o.jsxs(Fl,{children:[o.jsx(ae,{variant:"outline",onClick:()=>H(!1),children:"Cancel"}),o.jsxs(ae,{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",je&&r==="inline"&&"grid-cols-[1fr_1fr]"),children:[o.jsxs("div",{className:K("grid min-h-0 w-full gap-3 overflow-hidden pt-3",V.length>0||W>0?"grid-rows-[auto_minmax(0,1fr)]":"grid-rows-1"),children:[(V.length>0||W>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(ae,{size:"sm",children:[o.jsx(z0e,{}),"Filter",W>0&&o.jsx(mt,{size:"xs",children:W})]})}),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"}),P.length>0&&o.jsx(at.Separator,{}),P.map(([de])=>o.jsx(at.CheckboxItem,{checked:p===de,onCheckedChange:()=>m(p===de?null:de),onSelect:Oe=>Oe.preventDefault(),children:de},de))]})]}),W>0&&o.jsxs(o.Fragment,{children:[o.jsx(at.Separator,{}),o.jsxs(at.Item,{onSelect:()=>{m(null),x(!1),h(null)},children:[o.jsx(tr,{}),"Clear all filters"]})]})]})]}),W>0&&o.jsxs(ae,{size:"sm",onClick:()=>{m(null),x(!1),h(null)},children:[o.jsx(tr,{}),"Reset"]})]}),!b&&v.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(wVt,{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(ae,{size:"sm",disabled:w,children:[w?o.jsx(Ht,{className:"h-4 w-4"}):o.jsx(Ke,{size:"sm",children:o.jsx(ta,{})}),"Actions"]})}),o.jsxs(at.Content,{align:"end",children:[o.jsxs(at.Item,{onSelect:De,children:[o.jsx(Ke,{size:"sm",children:o.jsx(EO,{})}),"Complete"]}),o.jsxs(at.Item,{onSelect:Me,children:[o.jsx(Ke,{size:"sm",children:o.jsx(cl,{})}),"Remove"]}),o.jsx(at.Separator,{}),o.jsxs(at.Item,{onSelect:$e,children:[o.jsx(Ke,{size:"sm",children:o.jsx(f1,{})}),"Analyze"]})]})]})]})]}),X?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(Ht,{className:"h-6 w-6"})}):oe.length===0?o.jsx("div",{className:"flex h-full items-center-safe justify-center-safe overflow-auto py-12",children:o.jsx(yr,{iconSlot:o.jsx(Cs,{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(fe,{columns:tt,fit:"container",className:"min-w-0",scrollRef:Ge,children:[o.jsxs(fe.Top,{hasLeadingCell:!0,children:[b?o.jsx(fe.TopCell,{children:" "}):o.jsx(fe.TopSelectCell,{checked:ce?!0:le?"indeterminate":!1,onToggle:()=>he(),"aria-label":"Select all"}),o.jsxs(fe.TopCells,{colStart:2,children:[o.jsx(fe.TopCell,{children:"Input"}),o.jsx(fe.TopCell,{children:"Comment"}),o.jsx(fe.TopCell,{children:"Tags"}),o.jsx(fe.TopCell,{children:"Rating"}),o.jsx(fe.TopCell,{children:"Scores"})]})]}),oe.map((de,Oe)=>{const Ne=de.scores?Object.entries(de.scores):[],be=f===de.id,ve=o.jsxs(o.Fragment,{children:[o.jsx(fe.Cell,{className:"text-neutral4 min-w-0",children:o.jsx("span",{className:"block truncate",children:X0s(de.input,200)})}),o.jsx(fe.Cell,{className:"min-w-0",children:de.comment?o.jsx(me,{variant:"ui-xs",className:"text-neutral3 truncate",children:de.comment}):o.jsx(me,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsx(fe.Cell,{className:"min-w-0",children:de.tags.length>0?o.jsx(me,{variant:"ui-xs",className:"text-neutral4 truncate",children:de.tags.join(", ")}):o.jsx(me,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsxs(fe.Cell,{children:[de.rating==="positive"&&o.jsx(Ke,{size:"sm",className:"text-positive1",children:o.jsx(K0e,{})}),de.rating==="negative"&&o.jsx(Ke,{size:"sm",className:"text-negative1",children:o.jsx(Y0e,{})}),!de.rating&&o.jsx(me,{variant:"ui-xs",className:"text-neutral2",children:"—"})]}),o.jsx(fe.Cell,{children:Ne.length>0?o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Ke,{size:"sm",className:"text-neutral3",children:o.jsx(fm,{})}),o.jsx(me,{variant:"ui-xs",className:"text-neutral4 font-mono",children:Ne[0][1].toFixed(2)}),Ne.length>1&&o.jsxs(mt,{children:["+",Ne.length-1]})]}):o.jsx(me,{variant:"ui-xs",className:"text-neutral2",children:"—"})})]});return o.jsxs(fe.RowWrapper,{children:[b?o.jsx(fe.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(fe.SelectCell,{checked:v.has(de.id),onToggle:()=>ye(de.id),"aria-label":`Select item ${de.id}`}),o.jsx(fe.RowButton,{colStart:2,featured:be,onClick:()=>Te(de.id),...ge(Oe),children:ve})]},de.id)})]})]}),Se&&(r==="overlay"?o.jsx(bY,{label:`Review item ${je?.id??""}`,children:o.jsx("div",{className:"[&>section]:bg-surface3 h-full min-h-0 p-3 [&>section]:rounded-lg [&>section]:shadow-lg",children:Se})}):Se)]})]})}const Snt={needsReview:"#facc15",complete:"#22c55e"},ews=[{label:"Needs Review",color:Snt.needsReview},{label:"Reviewed",color:Snt.complete}];function tws({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(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Review Pipeline",description:"Items in review across experiments."}),c&&o.jsx(Vt.Summary,{value:String(l),label:"Items in pipeline"})]}),r?o.jsx(Vt.Loading,{}):s?o.jsx(Vt.Error,{message:"Failed to load review data"}):o.jsx(Vt.Content,{children:c?o.jsx(tI,{data:a,segments:ews,maxVal:i,fmt:u=>String(u)}):o.jsx(Vt.NoData,{message:"No items have been sent to review yet"})})]})}function DWt(){const e=Qe();return gt({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function nws(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 rws(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 sws(){const[e,t]=g.useState("all"),[n,r]=g.useState({}),{data:s,isLoading:a,error:i}=up(),{data:l,isLoading:c,error:u}=Pm(),{data:d,isLoading:f,error:h}=JH(),{data:p,isLoading:m,isError:v,error:y}=CWr(n),{data:b,isLoading:x,isError:w,error:k}=DWt(),O=l?.datasets,_=d?.experiments,T=g.useMemo(()=>rws(b),[b]),E=i||u||h||y||k;return E&&rs(E)?o.jsx(Wn,{children:o.jsx(_s,{})}):E&&is(E)?o.jsx(Wn,{children:o.jsx(ys,{resource:"evaluation"})}):E?o.jsx(Wn,{children:o.jsx(Bs,{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(e4,{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(w0e,{children:o.jsx(O0s,{scorers:s,datasets:O,experiments:_,avgScore:p?.avgScore??null,prevAvgScore:p?.prevAvgScore??null,totalNeedsReview:T.needsReview,isLoadingScorers:a,isLoadingDatasets:c,isLoadingExperiments:f,isLoadingScores:m,isLoadingReview:x})}),o.jsx(DHr,{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(mbs,{experiments:_,isLoading:f,isError:!!h}),o.jsx(L0s,{experiments:_,datasets:O,isLoading:f,isError:!!h})]}),o.jsx(tws,{reviewSummary:b,experiments:_,datasets:O,isLoading:x,isError:!!w})]})]})}function aws(){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=Br(),[f,h]=Ta(),p=f.get("dataset")??"all",m=g.useCallback(G=>{h(z=>{const P=new URLSearchParams(z);return G==="all"?P.delete("dataset"):P.set("dataset",G),P},{replace:!0})},[h]),{data:v,isLoading:y,error:b}=Pm(),{data:x,isLoading:w,error:k}=wY(p==="all"?void 0:p),{data:O}=DWt(),_=g.useMemo(()=>v?.datasets??[],[v?.datasets]),T=g.useMemo(()=>x?.experiments??[],[x?.experiments]),E=g.useMemo(()=>M0s(_),[_]),N=g.useMemo(()=>nws(O),[O]),I=y||w,A=k||b,R=G=>{u(z=>z.includes(G)?z.filter(P=>P!==G):z.length>=2?[z[0],G]:[...z,G])},L=()=>{u([]),l(!1)},{selectedIds:D,selectedDatasetIds:B}=g.useMemo(()=>{const G=new Map(T.map(P=>[P.id,P.datasetId])),z=c.filter(P=>G.has(P));return{selectedIds:z,selectedDatasetIds:new Set(z.map(P=>G.get(P)))}},[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,z]=D,[P]=B;if(!P)return;const U=new URLSearchParams({dataset:P,baseline:G,contender:z});d(`/experiments/compare?${U.toString()}`)};if(A&&rs(A))return o.jsx(Wn,{children:o.jsx(_s,{})});if(k&&is(k))return o.jsx(Wn,{children:o.jsx(ys,{resource:"experiments"})});if(b&&is(b))return o.jsx(Wn,{children:o.jsx(ys,{resource:"datasets"})});if(A)return o.jsx(Wn,{children:o.jsx(Bs,{title:"Failed to load experiments",message:A.message})});const F=o.jsx(yY,{open:s,onOpenChange:a,onSuccess:G=>{d(`/experiments/${G}`)}});if(T.length===0&&!I&&p==="all")return o.jsxs(Wn,{children:[o.jsx(F0s,{onRunExperiment:()=>a(!0)}),F]});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(z0s,{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(P0s,{experiments:T,datasets:_,reviewByExperiment:N,isLoading:I,search:e,statusFilter:n,datasetFilter:p,selection:i?{selectedExperimentIds:D,onToggleSelection:R}:void 0}),F]})}function g8({experimentId:e}){const{Link:t,paths:n}=un();return o.jsx(ae,{as:t,href:n.experimentLink(e),size:"sm","aria-label":`Open experiment ${e}`,children:e.slice(0,8)})}function iws(){const[e,t]=Ta(),n=e.get("dataset")??"",r=e.get("baseline")??"",s=e.get("contender")??"",a=XD(n,r),i=XD(n,s),l=a.isLoading||i.isLoading,c=a.error??i.error;return c&&rs(c)?o.jsx(ks,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(_s,{})})}):c&&is(c)?o.jsx(ks,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ys,{resource:"experiments"})})}):!n||!r||!s?o.jsx(ks,{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&&!m0(c)?o.jsx(ks,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Bs,{title:"Failed to load experiments",message:c.message})})}):c||!a.data||!i.data?o.jsx(ks,{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(g8,{experimentId:r}),"and",o.jsx(g8,{experimentId:s}),"was not found in it."]})]})})}):o.jsx(ks,{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(me,{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(g8,{experimentId:r}),"and",o.jsx(g8,{experimentId:s})]})]}),o.jsxs(bn,{children:[o.jsx(mn,{asChild:!0,children:o.jsxs(ae,{onClick:()=>t({dataset:n,baseline:s,contender:r}),children:[o.jsx(aut,{}),"Swap sides"]})}),o.jsx(gn,{children:"Switch baseline and contender"})]})]}),o.jsx(G0s,{datasetId:n,experimentIdA:r,experimentIdB:s})]})})})}const LWt=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 FWt(e){const{data:t}=PC(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 foe({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(bn,{children:[o.jsx(mn,{render:o.jsx("span",{className:"text-neutral3 flex",role:"img","aria-label":t}),children:e}),o.jsx(gn,{children:t})]}),n]})}function hoe({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(Bd,{className:"size-3.5 shrink-0","aria-hidden":!0})]})}const knt="text-neutral5 inline-flex items-center gap-1.5 hover:underline";function ows({experiment:e,className:t}){const{Link:n,paths:r}=un(),s=jWt(),{scorers:a}=s,{data:i,isLoading:l}=$m(e.datasetId??""),c=FWt(e),u=c.map(b=>a?.[b]?.scorer?.config?.name??b),d=e.targetType,f=e.targetId,h=()=>AWt(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&&NWt[d]||uo,v=d&&IWt[d]||"Evaluation target",y=p();return o.jsxs("div",{className:K("flex items-center gap-3 overflow-x-auto",t),children:[o.jsx(foe,{icon:o.jsx(LWt,{}),typeLabel:"Dataset",children:e.datasetId?o.jsxs(n,{href:r.datasetLink(e.datasetId),className:knt,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(hoe,{label:"each item"}),o.jsx(foe,{icon:o.jsx(m,{}),typeLabel:v,children:y?o.jsx(n,{href:y,className:knt,children:h()}):o.jsx("span",{className:"text-neutral3",children:h()})}),o.jsx(hoe,{label:"output"}),o.jsxs(bn,{children:[o.jsx(mn,{render:o.jsx("div",{tabIndex:0,className:"flex outline-offset-4",children:o.jsx(foe,{icon:o.jsx(EA,{}),typeLabel:"Scorers",children:c.length===0?"Scorers":`${c.length} scorer${c.length===1?"":"s"}`})})}),o.jsx(gn,{children:u.length>0?u.join(", "):"No scorer has produced a score yet"})]}),o.jsx(hoe,{label:"comparing ground truth"}),o.jsx("div",{className:"text-ui-sm text-neutral5 flex-none whitespace-nowrap",children:"Score"})]})}function v8({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 lws(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 cws({experiment:e,className:t}){const{data:n}=PC(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?"—":lws(l)})();return o.jsxs("div",{className:K("flex w-full items-stretch divide-x divide-border1 border-y border-border1",t),children:[o.jsx(v8,{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(v8,{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(v8,{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:["· ",PDn(a,{addSuffix:!0})]})]}):o.jsx("span",{children:"—"})}),o.jsx(v8,{label:"Duration",children:o.jsx("span",{children:i})})]})}function uws({experiment:e,open:t,onOpenChange:n}){const[r,s]=g.useState(e.name??""),[a,i]=g.useState(e.description??""),{updateExperiment:l}=La(),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(Nr,{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(ae,{type:"button",onClick:()=>n(!1),disabled:l.isPending,children:"Cancel"}),o.jsx(ae,{type:"submit",variant:"primary",disabled:!c,children:l.isPending?"Saving...":"Save"})]})]})})]})})}function dws({experiment:e}){const[t,n]=g.useState(!1);return e.datasetId?o.jsxs(o.Fragment,{children:[o.jsx(ae,{onClick:()=>n(!0),tooltip:"Rename this experiment",variant:"ghost",size:"icon-sm",children:o.jsx(Yh,{})}),t&&o.jsx(uws,{experiment:e,open:!0,onOpenChange:n})]}):null}const fws=["agent","workflow","scorer"];function hws({experiment:e}){const[t,n]=g.useState(!1),r=Br(),{paths:s}=un(),a=FWt(e),i=fws.find(l=>l===e.targetType);return!e.datasetId||!i||!e.targetId?null:o.jsxs(o.Fragment,{children:[o.jsxs(ae,{variant:"primary",onClick:()=>n(!0),tooltip:"Run this experiment again with the same configuration",children:[o.jsx(Fc,{}),"Rerun"]}),t&&o.jsx(yY,{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 pws({experiment:e,onDeleteClick:t}){const{Link:n,paths:r}=un(),s=e.agentVersion&&e.targetType==="agent"&&e.targetId?`${r.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($xs,{status:e.status,className:"h-7"}),o.jsxs(Ml,{children:[o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Ml.Title,{children:e.name||`Experiment #${e.id.slice(0,8)}`}),o.jsx(dws,{experiment:e})]}),e.description&&o.jsx(Ml.Description,{children:e.description}),o.jsx(ows,{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(ae,{as:n,to:RTe(e.id),children:[o.jsx(LC,{}),"View items to review"]}),o.jsx(hws,{experiment:e}),t&&o.jsxs(ae,{size:"sm",variant:"ghost",onClick:t,"aria-label":"Delete experiment",children:[o.jsx(cl,{})," Delete Experiment"]})]}),e.agentVersion&&o.jsxs(Jn,{numOfCol:1,children:[o.jsx(Jn.Key,{children:"Version"}),s?o.jsx(Jn.ValueLink,{href:s,as:n,children:e.agentVersion}):o.jsx(Jn.Value,{children:e.agentVersion})]})]})]}),o.jsx(cws,{experiment:e,className:"-mx-6 w-auto"})]})}function y8({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function mws(){const{experimentId:e}=fr(),t=Br(),[n,r]=g.useState(!1),{data:s,isLoading:a}=JH(),l=s?.experiments?.find(y=>y.id===e)?.datasetId??"",{data:c,isLoading:u,error:d}=XD(l,e??""),{data:f,isLoading:h,setEndOfListElement:p,isFetchingNextPage:m,hasNextPage:v}=JD({datasetId:l,experimentId:e??"",experimentStatus:c?.status});return!e||a||u?null:d&&rs(d)?o.jsx(y8,{children:o.jsx(_s,{})}):d&&is(d)?o.jsx(y8,{children:o.jsx(ys,{resource:"datasets"})}):d&&m0(d)||!a&&!l||!u&&!d&&!c?o.jsx(y8,{children:o.jsx(yr,{iconSlot:o.jsx(L0e,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:o.jsxs(ae,{as:gi,to:"/experiments",children:[o.jsx(uc,{}),"Back to Experiments"]})})}):d?o.jsx(y8,{children:o.jsx(Bs,{title:"Failed to load experiment",message:d instanceof Error?d.message:"An unexpected error occurred. Please try again."})}):o.jsx(Txs,{experimentId:e,datasetId:l,experimentStatus:c.status,results:f??[],isLoadingResults:h,hasNextPage:v,children:o.jsxs("div",{className:"h-full",children:[o.jsxs(Lt,{height:"full",children:[o.jsx(pws,{experiment:c,onDeleteClick:()=>r(!0)}),o.jsx(Lt.MainArea,{className:"overflow-visible",children:o.jsx(Pxs,{experimentId:e,datasetId:l,experimentStatus:c.status,results:f??[],isLoading:h,setEndOfListElement:p,isFetchingNextPage:m,hasNextPage:v})})]}),o.jsx(Ug,{}),o.jsx(_Wt,{open:n,onOpenChange:r,experimentId:e,experimentName:c.name??void 0,onSuccess:()=>t("/experiments")})]})})}function poe(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function gws({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(fn.SectionHeading,{icon:o.jsx(Vd,{}),className:"mb-2",children:"Tool Mocks"}),s&&o.jsx(An,{variant:"destructive",title:"Mock mismatch",children:o.jsxs(An.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: ",poe(s.args)]}),n.length>0&&o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Unconsumed mocks: ",n.map(i=>poe(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:poe(i.args)})]}),o.jsx("span",{className:`shrink-0 rounded px-2 py-0.5 text-xs ${vws(i.outcome)}`,children:i.outcome})]},`${i.outcome}-${i.toolName}-${l}`))})]})}function vws(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 yws({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,onTagsChange:h,tagVocabulary:p=[],isUpdatingTags:m=!1}){const v=!!e?.error,y=b8(e?.input),b=b8(e?.output),x=b8(e?.groundTruth),w=u&&e.status!=="needs-review"&&e.status!=="complete",k=Array.isArray(e.tags)?e.tags:[],O=g.useMemo(()=>[e],[e]),_=!!h||k.length>0;return o.jsxs(fn,{collapsed:d,children:[o.jsxs(fn.Header,{children:[o.jsxs(fn.Heading,{children:["Result ",o.jsxs("b",{children:["# ",e.id.length>12?`${e.id.slice(0,12)}…`:e.id]})]}),o.jsxs(ps,{className:"ml-auto shrink-0",children:[o.jsx(fn.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Previous result",nextLabel:"Next result"}),e.traceId&&o.jsxs(ae,{size:"md",onClick:a,children:[o.jsx(eY,{}),"Trace"]}),w&&o.jsxs(ae,{size:"md",variant:"primary",onClick:()=>u(e.id),children:[o.jsx(LC,{}),"Flag for Review"]}),e.status==="needs-review"&&i&&o.jsxs(ae,{size:"md",variant:"primary",onClick:i,children:[o.jsx(Fs,{}),"Review"]}),o.jsx(fn.CloseButton,{onClick:s,tooltip:"Close result panel"})]})]}),!d&&o.jsx(bws,{scorePanelSlot:f,children:o.jsxs(fn.Content,{children:[o.jsxs("div",{className:"mb-6 grid gap-4",children:[o.jsxs(Jn,{children:[o.jsx(Jn.Key,{children:"Item Id"}),o.jsx(Jn.ValueWithCopyBtn,{copyTooltip:"Copy Item Id to clipboard",copyValue:e.itemId,children:e.itemId}),o.jsx(Jn.Key,{children:"Created"}),o.jsx(Jn.Value,{children:dr(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")}),e.status&&o.jsxs(o.Fragment,{children:[o.jsx(Jn.Key,{children:"Status"}),o.jsx(Jn.Value,{children:o.jsx(mt,{size:"xs",variant:e.status==="needs-review"?"orange":e.status==="complete"?"green":"neutral",children:e.status})})]}),_&&o.jsxs(o.Fragment,{children:[o.jsx(Jn.Key,{children:"Tags"}),o.jsx(Jn.Value,{children:o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[k.map(T=>o.jsxs(bA,{value:T,className:h?"gap-1 pr-1":void 0,children:[T,h&&o.jsx("button",{type:"button","aria-label":`Remove tag ${T}`,disabled:m,onClick:()=>h(k.filter(E=>E!==T)),className:"cursor-pointer rounded-sm hover:opacity-70 disabled:opacity-50",children:o.jsx(tr,{className:"size-3"})})]},T)),h&&o.jsx(OWt,{appearance:"inline",selectedResults:O,vocabulary:p,onAddTag:T=>h([...k,T]),disabled:m})]})})]})]}),v&&o.jsx(An,{variant:"destructive",title:"Error",children:o.jsx(An.Message,{children:b8(e?.error&&typeof e.error=="object"?e.error.message:e?.error)})}),t&&t.length>0&&o.jsxs(fe,{columns:"1fr 1fr",children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{children:"Scorer"}),o.jsx(fe.TopCell,{children:"Score"})]}),t.map(T=>o.jsxs(fe.RowButton,{featured:c===T.id,onClick:()=>l?.(T.id),children:[o.jsx(fe.Cell,{children:T.scorerId}),o.jsx(fe.TextCell,{font:"mono",children:T.score.toFixed(3)})]},T.id))]}),e.toolMockReport&&o.jsx(gws,{report:e.toolMockReport})]}),o.jsxs("div",{className:"grid gap-3",children:[o.jsx(fn.CodeSection,{title:"Input",icon:o.jsx(VV,{}),codeStr:y}),o.jsx(fn.CodeSection,{title:"Output",icon:o.jsx(Rg,{}),codeStr:b}),o.jsx(fn.CodeSection,{title:"Ground Truth",icon:o.jsx(Put,{}),codeStr:x})]})]})})]})}function bws({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 b8(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function xws(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function wws({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=xws(e),p=h?"N/A — code-based scorer":"N/A — step not configured";return o.jsxs(fn,{collapsed:d,className:l,children:[o.jsxs(fn.Header,{children:[o.jsxs(fn.Heading,{children:["Score ",o.jsx("b",{children:e.scorerId})]}),o.jsxs(ps,{className:"ml-auto shrink-0",children:[i&&o.jsx(ae,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(lI,{}):o.jsx(zV,{})}),(n||t)&&o.jsx(fn.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:"Previous score",nextLabel:"Next score"}),s&&e.traceId&&o.jsxs(ae,{size:"md",onClick:s,children:[o.jsx(eY,{}),"Trace"]}),o.jsx(fn.CloseButton,{onClick:r,tooltip:"Close score panel"})]})]}),!d&&o.jsx(fn.Content,{children:o.jsxs("div",{className:"grid gap-3",children:[o.jsx(fn.CodeSection,{title:`Score: ${e.score}`,icon:o.jsx(fm,{}),codeStr:e.reason||p,simplified:!0}),!h&&o.jsxs(o.Fragment,{children:[o.jsx(fn.CodeSection,{title:"Preprocess Prompt",icon:o.jsx(Mp,{}),codeStr:e.preprocessPrompt||p,simplified:!0}),o.jsx(fn.CodeSection,{title:"Analyze Prompt",icon:o.jsx(Mp,{}),codeStr:e.analyzePrompt||p,simplified:!0}),o.jsx(fn.CodeSection,{title:"Generate Score Prompt",icon:o.jsx(Mp,{}),codeStr:e.generateScorePrompt||p,simplified:!0}),o.jsx(fn.CodeSection,{title:"Generate Reason Prompt",icon:o.jsx(Mp,{}),codeStr:e.generateReasonPrompt||p,simplified:!0})]})]})})]})}function Sws(){const{itemId:e}=fr();return e?o.jsx(kws,{itemId:e},e):null}function kws({itemId:e}){const{experimentId:t,datasetId:n,experimentStatus:r,results:s,isLoadingResults:a,hasNextPage:i,close:l,openInReview:c,goToPreviousItem:u,goToNextItem:d}=SWt(),f=g.useMemo(()=>s.find(W=>W.itemId===e)??null,[s,e]),{data:h}=PC(t,r),{updateExperimentResult:p}=La(),m=g.useCallback(async W=>{try{await p.mutateAsync({datasetId:n,experimentId:t,resultId:W,status:"needs-review"}),Ve("Result flagged for review")}catch{Ve.error("Failed to flag result for review")}},[n,t,p]),v=kWt(n,s),y=g.useCallback(async(W,Y)=>{try{await p.mutateAsync({datasetId:n,experimentId:t,resultId:W,tags:Y})}catch{Ve.error("Failed to update tags")}},[n,t,p]),b=f?h?.[f.itemId]:void 0,[x,w]=g.useState(null),[k,O]=g.useState(void 0),[_,T]=g.useState(null),[E,N]=g.useState(!1),[I,A]=g.useState(!1),R=b?.find(W=>W.id===_)??null,L=g.useCallback(W=>{T(Y=>W===Y?null:W),w(null),O(void 0)},[]),D=()=>{if(!_||!b)return;const W=b.findIndex(Y=>Y.id===_);if(W>=0&&W<b.length-1)return()=>T(b[W+1].id)},B=()=>{if(!_||!b)return;const W=b.findIndex(Y=>Y.id===_);if(W>0)return()=>T(b[W-1].id)},{data:H,isLoading:q}=Mxs(x),F=H?.spans,V=F?.find(W=>!W.parentSpanId),M=V?.entityType==="agent"?"Agent":V?.entityType==="workflow_run"?"Workflow":void 0,{data:G}=cRe({traceId:x??void 0}),{data:z}=IRe({traceId:x??void 0,spanId:k}),{data:P}=Mje({traceId:x??void 0,spanId:V?.spanId,page:0}),U=(()=>{const W=[],Y=!!x;return W.push(E?"auto":Y?"2fr":"1fr"),Y&&W.push(I?"auto":"3fr"),W.join(" ")})();return o.jsx(bY,{label:`Experiment item ${e}`,wide:!!k||!!R&&!E,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:U},children:[o.jsx(yws,{result:f,scores:b,onPrevious:u,onNext:d,onClose:l,onScoreClick:L,featuredScoreId:_,onShowTrace:()=>{f.traceId&&(w(f.traceId),O(void 0),T(null),N(!0),A(!1))},onOpenInReview:()=>c(f.id),onFlagForReview:()=>{m(f.id)},onTagsChange:W=>{y(f.id,W)},tagVocabulary:v,isUpdatingTags:p.isPending,collapsed:E,scorePanelSlot:R?o.jsx(wws,{score:R,onNext:D(),onPrevious:B(),onClose:()=>T(null),onShowTrace:()=>{R.traceId&&(w(R.traceId),O(void 0),N(!0),A(!1))},className:"rounded-none border-0 bg-transparent"}):null}),x&&o.jsx(RRe,{traceId:x,spans:F,isLoadingSpans:q,selectedSpanId:k??null,onClose:()=>{w(null),O(void 0),N(!1)},onSpanSelect:O,showUnavailableFeaturesMsg:!1,collapsed:I,onCollapsedChange:A,traceHref:`/traces?traceId=${encodeURIComponent(x)}`,anchorSpanId:V?.spanId,feedbackTabBadge:G?.pagination?.total??void 0,feedbackTabSlot:({traceId:W})=>o.jsx(tY,{traceId:W}),scoresTabBadge:P?.pagination?.total??void 0,scoresTabSlot:({traceId:W,rootSpanId:Y})=>Y?o.jsx(sWt,{traceId:W,spanId:Y,isTopLevelSpan:!V?.parentSpanId,entityType:M,onScoreSelect:te=>{b?.some(J=>J.id===te)&&(T(te),N(!1))}}):null,spanFeedbackTabBadge:z?.pagination?.total??void 0,spanFeedbackTabSlot:({traceId:W,spanId:Y})=>W&&Y?o.jsx(ARe,{traceId:W,spanId:Y},`${W}:${Y}`):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(Ht,{})})}):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(yr,{iconSlot:o.jsx(L0e,{}),titleSlot:"Item not found",descriptionSlot:`No loaded result for item "${e}".`,actionSlot:o.jsx(ae,{onClick:l,children:"Close"})})})})})}const DRe=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"})}),DV="all",Ont=60,Ows=e=>e.length>Ont?`${e.slice(0,Ont)}…`:e;function Cws({value:e,onValueChange:t,className:n,variant:r,allOption:s}){const{data:a,isLoading:i,isError:l}=wY(void 0),c=(a?.experiments??[]).map(d=>({label:EWt(d),value:d.id,start:o.jsx(DRe,{className:"text-neutral3 size-4 shrink-0","data-testid":"experiments-icon"}),description:d.description?Ows(d.description):w0(d.id)??d.id})),u=s?[{label:"All experiments",value:DV},...c]:c;return o.jsx(zo,{options:u,value:e??(s?DV:""),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 _ws(){const[e,t]=Ta(),n=e.get("experiment"),r=e.get("review"),{data:s,error:a}=wY(void 0),i=s?.experiments.find(c=>c.id===n),l=c=>{t(c===DV?{}:{experiment:c},{replace:!0})};return a&&rs(a)?o.jsx(Wn,{children:o.jsx(_s,{})}):a&&is(a)?o.jsx(Wn,{children:o.jsx(ys,{resource:"experiments"})}):a?o.jsx(Wn,{children:o.jsx(Bs,{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(Cws,{allOption:!0,value:n??void 0,onValueChange:l,className:"w-80"})})})}),o.jsx(Lt.MainArea,{className:"overflow-visible",children:o.jsx(J0s,{datasetId:i?.datasetId??void 0,experimentId:n??void 0,featuredItemId:r,detailPanelVariant:"overlay"},n??DV)})]})}const Ews=20;function Tws({reviewStatus:e}){const t=Qe(),n=Fy({queryKey:["feedback","list",e],queryFn:({pageParam:r})=>t.listFeedback({filters:{reviewStatus:e},pagination:{page:r,perPage:Ews},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 jws({enabled:e}){const t=Qe();return gt({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 Nws(){const e=Qe(),t=Er();return wn({mutationFn:({feedbackId:n,reviewStatus:r})=>e.updateFeedbackReviewStatus({feedbackId:n,reviewStatus:r}),onSuccess:()=>t.invalidateQueries({queryKey:["feedback"]})})}const Cnt="minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) auto";function Iws({items:e,isLoading:t,error:n}){const r=Br(),[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}=no({count:l.length});return t?o.jsx(Lo,{columns:Cnt}):n?o.jsx(Bs,{title:"Failed to load dataset items",message:n.message}):e.length===0?o.jsx(yr,{iconSlot:o.jsx(Cs,{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(fe,{columns:Cnt,fit:"container",scrollRef:c,children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{children:"Item"}),o.jsx(fe.TopCell,{children:"Experiment"}),o.jsx(fe.TopCell,{children:"Dataset"}),o.jsx(fe.TopCell,{children:"Trace"}),o.jsx(fe.TopCell,{children:" "})]}),l.length===0?o.jsx(fe.NoMatch,{message:"No dataset items match your search"}):l.map((d,f)=>{const h=RTe(d.experimentId,d.id);return o.jsxs(fe.RowWrapper,{children:[o.jsxs(fe.RowButton,{colEnd:-2,onClick:()=>r(h),...u(f),children:[o.jsx(fe.TextCell,{font:"mono",children:d.itemId}),o.jsx(fe.TextCell,{font:"mono",children:d.experimentId}),o.jsx(fe.TextCell,{font:"mono",children:d.datasetId}),o.jsx(fe.TextCell,{font:"mono",children:d.traceId??"—"})]}),o.jsx(fe.ActionsCell,{className:"pl-2",children:d.traceId?o.jsx(ae,{as:gi,to:`/traces?traceId=${encodeURIComponent(d.traceId)}`,variant:"ghost",size:"sm",children:"Open trace"}):null})]},d.id)})]})})]})}function Aws(){return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(yr,{iconSlot:o.jsx(Cs,{}),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(ae,{as:gi,to:"/experiments",variant:"outline",children:"Go to experiments"}),o.jsx(ae,{as:gi,to:"/traces",variant:"outline",children:"Go to traces"})]})})})}function S0e(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 _nt="minmax(0, 2fr) minmax(0, 1fr) auto minmax(0, 1fr) auto auto";function Rws({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=>S0e(x).toLowerCase().includes(h)||(IV(x)??"").toLowerCase().includes(h)||(x.traceId??"").toLowerCase().includes(h)||(x.feedbackSource??"").toLowerCase().includes(h)):e,{containerRef:m,getRowProps:v}=no({count:p.length}),{inView:y,setRef:b}=i0({root:m});return g.useEffect(()=>{y&&r&&!s&&a()},[y,r,s,a]),t?o.jsx(Lo,{columns:_nt}):n?o.jsx(Bs,{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, author, trace or source"})}),o.jsx("div",{className:"min-h-0 overflow-hidden",children:o.jsxs(fe,{columns:_nt,fit:"container",scrollRef:m,children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{children:"Feedback"}),o.jsx(fe.TopCell,{children:"Author"}),o.jsx(fe.TopCell,{children:"Source"}),o.jsx(fe.TopCell,{children:"Trace"}),o.jsx(fe.TopCell,{children:"Date"}),o.jsx(fe.TopCell,{children:" "})]}),p.length===0?o.jsx(fe.NoMatch,{message:h?"No feedback matches your search":"No feedback needs review"}):p.map((x,w)=>{const k=x.feedbackId,O=IV(x);return o.jsxs(fe.RowWrapper,{children:[o.jsxs(fe.RowButton,{colEnd:-2,disabled:!x.traceId,featured:k!==void 0&&k===u,onClick:()=>c(x),...v(w),children:[o.jsx(fe.TextCell,{className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:S0e(x)})}),o.jsx(fe.Cell,{className:"flex gap-2",children:O&&o.jsxs(o.Fragment,{children:[o.jsx(Iy,{name:O,src:x.author?.avatarUrl,size:"sm"}),o.jsx("span",{className:"truncate",children:O})]})}),o.jsx(fe.Cell,{children:o.jsx(mt,{size:"sm",children:x.feedbackSource})}),o.jsx(fe.TextCell,{font:"mono",className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:x.traceId??"—"})}),o.jsx(fe.TextCell,{children:dr(x.timestamp,"MMM d, h:mm a")})]}),o.jsx(fe.ActionsCell,{className:"pl-2",children:k?o.jsx(ae,{variant:"ghost",size:"sm",onClick:()=>i(k),disabled:l===k,children:"Mark reviewed"}):null})]},k??`${String(x.timestamp)}-${x.traceId}`)}),o.jsx(fe.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:b})]})})]})}function Pws({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}=JHt({traceId:t,anchorSpanId:null,listMode:"traces"}),h=IV(e)??e.feedbackUserId;return o.jsx(bY,{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(fn,{className:"max-h-[33vh]",children:[o.jsxs(fn.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(fn.Heading,{children:"Feedback"}),o.jsx(mt,{variant:"neutral",emphasis:"muted",children:e.feedbackType}),e.feedbackSource&&o.jsx(mt,{variant:"neutral",emphasis:"muted",children:e.feedbackSource})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[h&&o.jsxs(o.Fragment,{children:[o.jsx(Iy,{name:h,src:e.author?.avatarUrl,size:"sm"}),o.jsx(me,{as:"span",variant:"ui-sm",className:"text-neutral5 truncate",children:h}),o.jsx(me,{as:"span",variant:"ui-sm",className:"text-neutral3",children:"·"})]}),o.jsx(me,{as:"span",variant:"ui-sm",className:"text-neutral3",children:dr(new Date(e.timestamp),"MMM dd, yyyy HH:mm:ss")})]})]}),o.jsx(ps,{className:"ml-auto shrink-0",children:o.jsxs(ae,{variant:"primary",size:"sm",onClick:i,disabled:l,children:[o.jsx(Ke,{children:o.jsx(Dr,{})}),"Mark as reviewed"]})})]}),o.jsx(fn.Content,{children:o.jsx(me,{as:"p",variant:"ui-md",className:"text-neutral5 whitespace-pre-wrap",children:S0e(e)})})]}),o.jsx("section",{className:"min-h-0 overflow-hidden",children:o.jsx(RRe,{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:p})=>o.jsx(tY,{traceId:p}),spanFeedbackTabSlot:({traceId:p,spanId:m})=>p&&m?o.jsx(ARe,{traceId:p,spanId:m},`${p}:${m}`):null})})]})})}const zWt=100;async function $ws(e){const t=[];let n=0,r=!0;for(;r;){const s=await e.listExperiments({page:n,perPage:zWt});t.push(...s.experiments),r=s.pagination.hasMore,n+=1}return t}async function Mws(e,t,n){const r=[];let s=0,a=!0;for(;a;){const i=await e.listDatasetExperimentResults(t,n,{page:s,perPage:zWt});r.push(...i.results),a=i.pagination.hasMore,s+=1}return r}function Dws(){const e=Qe();return gt({queryKey:["inbox-dataset-review-items"],queryFn:async()=>{const t=await $ws(e);return(await Promise.all(t.map(async r=>{const s=r.datasetId;return s?(await Mws(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 Lws({enabled:e}){const t=Qe();return gt({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 Fws(e){return e==="dataset"||e==="feedback"}function zws(){const[e,t]=Ta(),n=e.get("tab"),r=Fws(n)?n:"feedback",s=Tws({reviewStatus:"needs-review"}),a=Nws(),i=Dws(),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,O=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(Ml,{children:[o.jsx(Ml.Title,{children:"Inbox"}),o.jsx(Ml.Description,{children:"Items waiting for review"})]})}),o.jsx(Lt.MainArea,{className:"min-h-0 overflow-hidden",children:u?o.jsx(Aws,{}):o.jsxs(vc,{defaultTab:"feedback",value:r,onValueChange:_,className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[o.jsxs(gc,{variant:"pill-ghost",children:[o.jsxs(zr,{value:"feedback",className:"px-3 py-2.5",children:[o.jsx(Ke,{size:"sm",children:o.jsx(u3,{})}),o.jsx(me,{variant:"ui-sm",className:"text-inherit",children:"Feedback"}),c>0&&o.jsx(mt,{variant:"yellow",size:"sm",children:c})]}),o.jsxs(zr,{value:"dataset",className:"px-3 py-2.5",children:[o.jsx(Ke,{size:"sm",children:o.jsx(LC,{})}),o.jsx(me,{variant:"ui-sm",className:"text-inherit",children:"Dataset items"}),l.length>0&&o.jsx(mt,{variant:"yellow",size:"sm",children:l.length})]})]}),o.jsx(vs,{value:"feedback",className:"h-full min-h-0 pt-4",children:o.jsx(Rws,{items:s.items,isLoading:s.isLoading,error:s.error??void 0,hasNextPage:s.hasNextPage,isFetchingNextPage:s.isFetchingNextPage,fetchNextPage:s.fetchNextPage,onMarkReviewed:O,pendingFeedbackId:a.isPending?a.variables?.feedbackId:void 0,onSelect:v,selectedFeedbackId:d})}),o.jsx(vs,{value:"dataset",className:"h-full min-h-0 pt-4",children:o.jsx(Iws,{items:l,isLoading:i.isLoading,error:i.error??void 0})})]})})]}),k&&f&&b&&o.jsx(Pws,{feedback:b,traceId:f,initialSpanId:h,onClose:m,onPrevious:x?()=>v(x):void 0,onNext:w?()=>v(w):void 0,onMarkReviewed:()=>d&&O(d),isMarkingReviewed:a.isPending},`${d}:${f}`)]})}function Bws({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 BWt({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("ul",{className:"space-y-1",children:e.map(s=>o.jsx(Bws,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function Uws({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(BWt,{connections:a,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function qws({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(Uws,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):o.jsx(BWt,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?o.jsx("p",{className:"text-red-600",children:String(c)}):null]})}function Vws({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 Ent=e=>e.authorId?.trim()||"shared",Hws=(e,t)=>{if(!t||new Set(e.map(Ent)).size<=1)return null;const r=new Map;for(const a of e){const i=Ent(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},Wws=["*","tool-providers:*","tool-providers:admin"];function Zws(){const{data:e}=Bm();return e?.permissions?.some(t=>Wws.includes(t))??!1}function Gws(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,a]=g.useState(""),i=iA(),l=kG(e||null),c=ULt(e||null,n||null),u=BLt(),d=LLt(),f=Zws(),h=i.data?.providers??[],p=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),v=g.useMemo(()=>Hws(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(Vws,{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(qws,{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 Qws({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(Zh,{className:"h-10 w-10"}),o.jsx("h1",{className:"text-neutral6 text-xl font-semibold",children:e})]}),t,n,r]})})}function UWt({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:a}=fc(),{mutate:i,isPending:l,error:c}=GMr(),{mutate:u,isPending:d,error:f}=YMr(),{mutate:h,isPending:p}=BDt(),[m,v]=g.useState(n),[y,b]=g.useState(""),[x,w]=g.useState(""),[k,O]=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,R=A?l:d,L=A?c:f,D=()=>{t?t():e?window.location.href=e:window.location.href=AG("/")},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")},F=_.description?o.jsxs("div",{className:"border-border1 bg-surface1 flex items-start gap-2.5 rounded-md border p-3",children:[o.jsx(qd,{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(Qws,{title:A?"Sign in to Mastra Studio":"Create your account",description:F,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=>O(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(ae,{type:"submit",disabled:R,className:"w-full",size:"lg",children:R?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(ae,{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 Yws(){const[e]=Ta(),t=Br(),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(UWt,{redirectUri:n,onSuccess:i,initialMode:s,errorMessage:a})}const yh=Ra.KeyValueList;function Kws(e){return e instanceof Date?e:new Date(e)}function Xws({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=Kws(e.timestamp),p=e.traceId,m=e.spanId;return o.jsxs(Ra,{collapsed:d,children:[o.jsxs(Ra.Header,{children:[o.jsxs(Ra.Heading,{children:["Log ",o.jsx("b",{children:dr(h,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(ps,{className:"ml-auto shrink-0",children:[l&&o.jsx(ae,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(lI,{}):o.jsx(zV,{})}),o.jsxs(ps,{spacing:"close",children:[o.jsx(ae,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(J1,{})}),o.jsx(ae,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(FV,{})})]}),o.jsx(Ra.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(Ra.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(ps,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(ae,{size:"md",className:"min-w-0 flex-1 overflow-hidden",onClick:()=>n?.(p),children:[o.jsx(Bd,{}),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(ps,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(ae,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!p||!r,onClick:()=>p&&r?.(p,m),children:[o.jsx(Bd,{}),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(yh,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(yh.Key,{children:"Entity Type"}),o.jsx(yh.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(yh.Key,{children:"Entity Name"}),o.jsx(yh.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(yh.Key,{children:"Service"}),o.jsx(yh.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(yh.Key,{children:"Environment"}),o.jsx(yh.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(yh.Key,{children:"Source"}),o.jsx(yh.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(yh.Key,{children:v}),o.jsx(yh.Value,{children:String(y)})]},v))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(Ra.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function Jws({error:e,resource:t,errorTitle:n}){if(rs(e))return o.jsx(_s,{});if(is(e))return o.jsx(ys,{resource:t});if(XL(e))return o.jsx(yr,{iconSlot:o.jsx(Cs,{}),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(KL(e,"logs"))return o.jsx(yr,{iconSlot:o.jsx(Cs,{}),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(Bs,{title:n,message:r??"Unknown error"})}function e1s({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 t1s={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 n1s({level:e}){const t=t1s[e];return o.jsx(co,{children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function r1s({entityType:e,className:t}){const n=K("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case"agent":return o.jsx(uo,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return o.jsx(_u,{className:n,"aria-hidden":!0});case"tool":return o.jsx(qf,{className:n,"aria-hidden":!0});default:return null}}function s1s({entityType:e,entityName:t}){const n=e??"";return o.jsxs(co,{className:"flex min-w-0 items-center gap-2",children:[o.jsx(r1s,{entityType:n}),t?o.jsx("span",{className:"text-ui-smd min-w-0 truncate",children:t}):"-"]})}function a1s({message:e}){return o.jsx(co,{className:"text-ui-smd text-neutral4 min-w-0 truncate font-mono",children:e})}function i1s({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(co,{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(aTe,{font:"mono",children:t})}const Jl=Object.assign(GL,{Top:YL,TopCell:bS,TopCellWithTooltip:lG,TopCellSmart:Z$t,RowWrapper:lTe,RowButton:QL,RowLink:W$t,Spacer:cTe,NoMatch:oG,DateCell:q$t,TimeCell:V$t,LevelCell:n1s,EntityCell:s1s,MessageCell:a1s,DataCell:i1s,NextPageLoading:iG}),Tnt="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",o1s=36,l1s=8;function c1s({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=g.useRef(null),u=XHt({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>o1s,overscan:l1s}),{getRowProps:d}=no({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(Lo,{columns:Tnt});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(Jl,{columns:Tnt,scrollRef:c,className:"min-w-0",children:[o.jsxs(Jl.Top,{children:[o.jsx(Jl.TopCell,{children:"Date"}),o.jsx(Jl.TopCell,{children:"Time"}),o.jsx(Jl.TopCell,{children:"Level"}),o.jsx(Jl.TopCell,{children:"Entity"}),o.jsx(Jl.TopCell,{children:"Message"}),o.jsx(Jl.TopCell,{children:"Data"})]}),e.length===0?o.jsx(Jl.NoMatch,{message:"No logs match your search"}):o.jsxs(o.Fragment,{children:[o.jsx(Jl.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(Jl.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(Jl.DateCell,{timestamp:b.timestamp}),o.jsx(Jl.TimeCell,{timestamp:b.timestamp}),o.jsx(Jl.LevelCell,{level:b.level}),o.jsx(Jl.EntityCell,{entityType:b.entityType,entityName:b.entityName}),o.jsx(Jl.MessageCell,{message:b.message}),o.jsx(Jl.DataCell,{data:b.data})]},x)}),o.jsx(Jl.Spacer,{height:v})]}),o.jsx(Jl.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function u1s({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=>d1s(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(kRe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(wRe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function d1s(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 f1s={"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"},moe="MMM d, yyyy HH:mm",goe="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function h1s({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${f1s[e]}`,description:goe}:t&&n?{title:`No logs between ${dr(t,moe)} and ${dr(n,moe)}`,description:goe}:t?{title:`No logs since ${dr(t,moe)}`,description:goe}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const p1s=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=h1s({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(yr,{iconSlot:o.jsx(Cs,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(ae,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",children:["Logging Documentation ",o.jsx(Fs,{})]})})})},m1s=20,g1s=1e4;function v1s(e,t,n){if(e?.pagination?.hasMore)return n+1}function y1s(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 b1s(e){return KL(e.state.error,"logs")||XL(e.state.error)?!1:g1s}const x1s=({filters:e}={})=>{const t=Qe(),{inView:n,setRef:r}=i0(),s=Fy({queryKey:["logs",e],queryFn:({pageParam:h})=>t.listLogsVNext({pagination:{page:h,perPage:m1s},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:v1s,select:y1s,retry:!1,refetchInterval:b1s}),{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}},x8={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},qWt=[{label:"Agent",entityType:x8.AGENT},{label:"Workflow",entityType:x8.WORKFLOW},{label:"Scorer",entityType:x8.SCORER},{label:"Ingest",entityType:x8.INGEST}],w1s=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],Jx="rootEntityType",rx="datePreset",sx="dateFrom",ax="dateTo",S1s=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"},a5=Object.keys(jl),LRe=new Set(["tags"]),FRe="mastra:logs:saved-filters";function k1s(e,t=FRe){const n=T1s(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 O1s(e=FRe){try{localStorage.removeItem(e)}catch{}}function jnt(e=FRe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function C1s(e){if(e.has(rx)||e.has(sx)||e.has(ax)||e.has(Jx))return!0;for(const t of a5)if(e.has(jl[t]))return!0;return!1}function _1s({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:qWt.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:w1s.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 E1s(e){const t=[],n=new Map([[Jx,"rootEntityType"]]);for(const s of a5)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),LRe.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 T1s(e){const t=new URLSearchParams,n=e.get(Jx);n&&t.set(Jx,n);for(const r of a5){const s=jl[r];if(LRe.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 j1s(e,t){e.delete(Jx);for(const n of a5)e.delete(jl[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(Jx,n.value);continue}const r=jl[n.fieldId];if(r){if(LRe.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 N1s({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 I1s(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 A1s="Filters setting for Logs saved",R1s="Filters setting for Logs cleared up";function P1s(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=g.useState(()=>jnt(r)!==null),c=g.useCallback(()=>{k1s(e,r),l(!0);const f=s?.saved??A1s;f!==!1&&Ve.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{O1s(r),l(!1);const f=s?.cleared??R1s;f!==!1&&Ve.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(a||d.current||(d.current=!0,C1s(e)))return;const f=jnt(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 $1s(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 M1s(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,$1s(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function D1s(e,t,n,r){const s=g.useMemo(()=>M1s(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 k0e="logId",O0e="traceId",C0e="spanId",FP=1440*60*1e3,L1s={"last-24h":FP,"last-3d":3*FP,"last-7d":7*FP,"last-14d":14*FP,"last-30d":30*FP};function w8(e){e.delete(k0e),e.delete(O0e),e.delete(C0e)}function F1s(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const O=e.get(rx);return O&&S1s.has(O)?O:"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 O=L1s[s];return O?new Date(Date.now()-O):void 0},[s,a]),c=g.useMemo(()=>{if(s!=="custom"||!i)return;const O=new Date(i);return Number.isNaN(O.getTime())?void 0:O},[s,i]),u=g.useRef(s);u.current=s;const d=e.get(k0e),f=e.get(O0e),h=e.get(C0e),p=g.useMemo(()=>qWt.find(O=>O.entityType===e.get(Jx)),[e]),m=g.useMemo(()=>E1s(e),[e]),v=g.useCallback(O=>{t(_=>{const T=new URLSearchParams(_);for(const[E,N]of Object.entries(O)){const I=E==="logId"?k0e:E==="traceId"?O0e:C0e;N?T.set(I,N):T.delete(I)}return T},{replace:!0})},[t]),y=g.useCallback(O=>{t(_=>{const T=new URLSearchParams(_);return j1s(T,O),w8(T),T},{replace:!0})},[t]),b=y,x=g.useCallback((O,_)=>{if(u.current!=="custom")return;const T=_==="from"?sx:ax;t(E=>{const N=new URLSearchParams(E);return O?N.set(T,O.toISOString()):N.delete(T),w8(N),N},{replace:!0})},[t]),w=g.useCallback(O=>{u.current=O,t(_=>{const T=new URLSearchParams(_);return O==="last-24h"?(T.delete(rx),T.delete(sx),T.delete(ax)):O==="custom"?T.set(rx,"custom"):(T.set(rx,O),T.delete(sx),T.delete(ax)),w8(T),T},{replace:!0})},[t]),k=g.useCallback(()=>{t(O=>{const _=new URLSearchParams(O);_.delete(Jx);for(const T of a5)_.delete(jl[T]);return _.delete(rx),_.delete(sx),_.delete(ax),w8(_),_},{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=Ra.KeyValueList;function z1s({spanId:e,span:t,isLoading:n,onClose:r}){const s=sRe(t?.startedAt,t?.endedAt),a=_tt(t?.startedAt),i=_tt(t?.endedAt);return o.jsxs(Ra,{children:[o.jsxs(Ra.Header,{children:[o.jsxs(Ra.Heading,{children:["Span ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Ra.CloseButton,{onClick:r})]}),n?o.jsx(Ra.LoadingData,{children:"Loading span..."}):t?o.jsxs(Ra.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(Ra.CodeSection,{title:"Input",icon:o.jsx(u1,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(Ra.CodeSection,{title:"Output",icon:o.jsx(Rg,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(Ra.CodeSection,{title:"Metadata",icon:o.jsx(nc,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(Ra.CodeSection,{title:"Attributes",icon:o.jsx(nc,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(Ra.NoData,{children:"Span not found."})]})}function B1s({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:a}){const i=g.useMemo(()=>X4(t??[]),[t]),[l,c]=g.useState([]);g.useEffect(()=>{i.length>0&&c(XQ(i))},[i]);const u=d=>{s?.(a===d?void 0:d)};return o.jsxs(Ra,{children:[o.jsxs(Ra.Header,{children:[o.jsxs(Ra.Heading,{children:["Trace ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Ra.CloseButton,{onClick:r})]}),n?o.jsx(Ra.LoadingData,{children:"Loading trace..."}):i.length===0?o.jsx(Ra.NoData,{children:"No spans found for this trace."}):o.jsx(Ra.Content,{children:o.jsx(aRe,{hierarchicalSpans:i,onSpanClick:u,selectedSpanId:a??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}function U1s(){const[e,t]=Ta(),n=F1s(e,t),r=P1s(e,t),[s,a]=g.useState(),[i,l]=g.useState(!1),{data:c=[],isPending:u}=NRe(),{data:d=[],isPending:f}=ERe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:h=[],isPending:p}=TRe(),{data:m=[],isPending:v}=jRe(),y=g.useMemo(()=>_1s({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(()=>N1s({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:O,hasNextPage:_,setEndOfListElement:T}=x1s({filters:b}),{logIdMap:E,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:R}=D1s(x,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:L,isLoading:D}=J4(n.featuredTraceId??null),{data:B,isLoading:H}=JQ(n.featuredTraceId??"",n.featuredSpanId??""),q=g.useCallback(()=>n.applyFilterTokens(I1s(y,n.filterTokens)),[y,n]),F=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]),z=g.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),P=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(e4,{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(ORe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:w,onStartTextFilter:a})]})}),o.jsx(u1s,{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(Jws,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const W=!!n.selectedEntityOption||n.filterTokens.length>0;return x.length===0&&!w&&!W?o.jsxs(Lt,{width:"wide",height:"full",children:[U,o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(p1s,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Lt,{width:"wide",height:"full",children:[U,o.jsx(e1s,{logCollapsed:i,listSlot:o.jsx(c1s,{logs:x,isLoading:w,isFetchingNextPage:O,hasNextPage:_,setEndOfListElement:T,logIdMap:E,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(Xws,{log:N,onClose:F,onTraceClick:V,onSpanClick:M,onPrevious:A,onNext:R,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(B1s,{traceId:n.featuredTraceId,spans:L?.spans,isLoading:D,onClose:G,onSpanSelect:P,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(z1s,{spanId:n.featuredSpanId,span:B?.span,isLoading:H,onClose:z}):null})]})}function q1s({server:e,rowProps:t}){const{paths:n,Link:r}=un(),a=Qe().options.baseUrl,i=a?`${a}/api/mcp/${e.id}/sse`:"",{data:l}=dqt(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=Pd(e.name,50);return o.jsxs(fe.RowLink,{to:n.mcpServerLink(e.id),LinkComponent:r,...t,children:[o.jsx(fe.NameCell,{children:h}),o.jsx(fe.DescriptionCell,{children:i}),o.jsx(fe.TextCell,{className:"text-center",children:d||""}),o.jsx(fe.TextCell,{className:"text-center",children:u||""}),o.jsx(fe.TextCell,{className:"text-center",children:f||""})]})}function V1s({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}=no({count:r.length});return t?o.jsx(Lo,{columns:"auto 1fr auto auto auto"}):o.jsxs(fe,{columns:"auto 1fr auto auto auto",scrollRef:s,children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{children:"Name"}),o.jsx(fe.TopCell,{children:"URL"}),o.jsx(fe.TopCellSmart,{long:"Agents",short:o.jsx(uo,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(fe.TopCellSmart,{long:"Tools",short:o.jsx(qf,{}),tooltip:"Tools",className:"text-center"}),o.jsx(fe.TopCellSmart,{long:"Workflows",short:o.jsx(_u,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(fe.NoMatch,{message:"No MCP Servers match your search"}):null,r.map((i,l)=>o.jsx(q1s,{server:i,rowProps:a(l)},i.id))]})}const H1s=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(yr,{iconSlot:o.jsx(Cs,{}),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(ae,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(Fs,{})]})})}),W1s=()=>{const{data:e=[],isLoading:t,error:n}=qQ(),[r,s]=g.useState("");return n&&rs(n)?o.jsx(Wn,{children:o.jsx(_s,{})}):n&&is(n)?o.jsx(Wn,{children:o.jsx(ys,{resource:"MCP servers"})}):n?o.jsx(Wn,{children:o.jsx(Bs,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(Wn,{children:o.jsx(H1s,{})}):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(V1s,{mcpServers:e,isLoading:t,search:r})]})},Z1s=(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 G1s({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=un(),i=g.useMemo(()=>Z1s(e,t),[e,t]),l=g.useMemo(()=>i.filter(d=>d.id.toLowerCase().includes(r.toLowerCase())),[i,r]),{containerRef:c,getRowProps:u}=no({count:l.length});return n?o.jsx(Lo,{columns:"auto 1fr auto"}):o.jsxs(fe,{columns:"auto 1fr auto",scrollRef:c,children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{children:"Name"}),o.jsx(fe.TopCell,{children:"Description"}),o.jsx(fe.TopCellSmart,{long:"Agents",short:o.jsx(uo,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(fe.NoMatch,{message:"No Tools match your search"}):null,l.map((d,f)=>{const h=Pd(d.id,50),p=Pd(d.description??"",200),m=d.agents.length;return o.jsxs(fe.RowLink,{to:s.toolLink(d.id),LinkComponent:a,...u(f),children:[o.jsx(fe.NameCell,{children:h}),o.jsx(fe.DescriptionCell,{children:p}),o.jsx(fe.TextCell,{className:"text-center",children:m||""})]},d.id)})]})}const Q1s=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(yr,{iconSlot:o.jsx(Cs,{}),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(ae,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(Fs,{})]})})}),Y1s=()=>{const e=Qe();return wn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new WC;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}}})},K1s=({toolId:e})=>{const{canExecute:t}=Co(),n=t("tools"),{data:r={}}=Um(),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}=lMr(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=Y1s(),{requestContext:h}=bs();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?bm(Rx(c?.inputSchema)):Ss({});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(LAe,{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(me,{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(me,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function X1s({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}=sA(),{data:p={},isLoading:m,isError:v,error:y}=Um(),{navigate:b,paths:x}=un();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})),O=_=>{t?t(_):_&&_!==e&&b(x.toolLink(_))};return o.jsx(zo,{options:k,value:e,onValueChange:O,placeholder:d||m?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||d||m||f||v,variant:l,size:c})}const J1s=({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(me,{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(me,{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(mt,{icon:o.jsx(BVt,{}),size:"sm",children:"Version"}),o.jsx(mt,{size:"sm",children:t.version_detail.version})]}),o.jsx(me,{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(mt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"HTTP"}),children:"Regular HTTP Endpoint"}),o.jsx(me,{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(me,{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(mt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"SSE"}),children:"Server-Sent Events"}),o.jsx(me,{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(me,{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(mt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"CLI"}),children:"Command Line"}),o.jsx(me,{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(me,{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(eSs,{server:t})})]})},eSs=({server:e})=>{const{data:t={},isLoading:n}=dqt(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(Ke,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx($_,{})}),o.jsx(me,{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(nSs,{tool:a,serverId:e.id},s)})})]})};function tSs(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 nSs=({tool:e,serverId:t})=>{const n=g.useRef(null),{Link:r,paths:s}=un(),a=xqt[e.toolType||"tool"],i=tSs(e._meta);return o.jsxs(Gf,{onClick:()=>n.current?.click(),children:[o.jsx(zLt,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Yf,{children:[o.jsx(Qf,{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(mt,{size:"xs",children:"App"})]})}),o.jsx(cp,{children:e.description})]})]})},rSs=()=>{const{serverId:e}=fr(),{data:t=[],isLoading:n}=qQ(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(J1s,{isLoading:n,server:r})})};function sSs(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 aSs=({toolId:e,serverId:t})=>{const{canExecute:n}=Co(),r=n("tools"),s=Qe(),{data:a,isLoading:i,error:l}=DAe(t,e),{mutateAsync:c,isPending:u,data:d}=dls(t,e),f=a?sSs(a._meta):void 0,{data:h}=gt({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(me,{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(me,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let v;try{v=bm(a.inputSchema)}catch(y){console.error("Error processing input schema:",y),Ve.error("Failed to process tool input schema."),v=Ss({})}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(uqt,{html:h,toolName:a.name??a.id,onToolCall:p})}),o.jsx(LAe,{executionResult:d,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},iSs=()=>{const{serverId:e,toolId:t}=fr(),{data:n,isLoading:r}=DAe(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(aSs,{toolId:t,serverId:e})})},VWt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],nI="rootEntityType",rI={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"},SY=Object.keys(rI),zRe="mastra:metrics:saved-filters";function oSs(e){const t=fSs(e);try{localStorage.setItem(zRe,t.toString())}catch{}}function lSs(){try{localStorage.removeItem(zRe)}catch{}}function HWt(){try{const e=localStorage.getItem(zRe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function cSs(e){if(e.has(nI))return!0;for(const t of SY)if(e.has(rI[t]))return!0;return!1}function uSs({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:VWt.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 dSs(e){const t=[],n=new Map([[nI,"rootEntityType"]]);for(const s of SY)n.set(rI[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 fSs(e){const t=new URLSearchParams,n=e.getAll(nI);for(const r of n)t.append(nI,r);for(const r of SY){const s=rI[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function hSs(e,t){e.delete(nI);for(const n of SY)e.delete(rI[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?nI:rI[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 pSs="Any";function Nnt(e){const t=e.trim();return t===""||t===pSs}const mSs=new Set(VWt.map(e=>e.entityType));function Int(e){const t=e.trim();return mSs.has(t)?t:void 0}function gSs(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=>!Nnt(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?Int(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(Nnt(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=Int(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const WWt=[{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"}],vSs=new Set(WWt.map(e=>e.value));function ySs(e){return typeof e=="string"&&(vSs.has(e)||e==="custom")}const ZWt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function kY(){return g.useContext(ZWt)}function bSs(e,t){return e!=="custom"?WWt.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 xSs({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(()=>gSs(d),[d]),h=g.useMemo(()=>JSON.stringify(f),[f]),p=bSs(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(ZWt.Provider,{value:m,children:e})}const wSs=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function SSs(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 kSs(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 OSs(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=kY(),s=g.useRef(e);s.current=e;const a=g.useRef(n);return a.current=n,o.jsx(e4,{preset:SSs(e),onPresetChange:i=>{const l=kSs(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:wSs})}const _0e=1440*60*1e3,CSs={"24h":_0e,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function _Ss(e,t,n){if(e!=="custom"){const r=CSs[e]??_0e;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-_0e),end:t?.to??new Date(n)}}function Wm(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=kY(),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(()=>_Ss(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 GWt(){const e=Qe(),{filters:t,filterKey:n}=Wm();return gt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function i5({href:e,LinkComponent:t="a"}){return o.jsx(ae,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(rc,{})})}function ESs({href:e,LinkComponent:t="a"}){return o.jsx(ae,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(ren,{})})}function TSs(e){return e==="agents"||e==="workflows"||e==="tools"}function Ant(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 jSs(e){const t=e;return typeof t?.tsMs=="number"&&Number.isFinite(t.tsMs)}const NSs=[{dataKey:"p50",label:"p50",color:Qh.blue,aggregate:e=>({value:Ant(e,"p50"),suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:Qh.yellow,aggregate:e=>({value:Ant(e,"p95"),suffix:"avg ms"})}];function voe({data:e,onPointClick:t}){return e.length===0?o.jsx(Vt.NoData,{message:"No latency data yet"}):o.jsx(LD,{data:e,series:NSs,onPointClick:t?n=>jSs(n)?t(n):void 0:void 0})}function ISs({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(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(Vt.Summary,{value:y,label:"Avg p50"}),p?o.jsx(Vt.Actions,{children:p}):null]}),t?o.jsx(Vt.Loading,{}):n?o.jsx(Vt.Error,{message:"Failed to load latency data"}):o.jsx(Vt.Content,{children:m?o.jsxs(vc,{value:h,onValueChange:b=>{TSs(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(gc,{children:[o.jsx(zr,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(zr,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(zr,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(vs,{value:"agents",children:o.jsx(voe,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(vs,{value:"workflows",children:o.jsx(voe,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(vs,{value:"tools",children:o.jsx(voe,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Vt.NoData,{message:"No latency data yet"})})]})}function ASs(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 RSs(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 QWt(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=ASs(s);l&&e.set(t,l)}function Ro(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function YWt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function Rnt({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const a=new URLSearchParams;a.set(qw,"branches"),QWt(a,Vw,VT,HT,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Kx,i),r.status&&a.set(Xx,r.status),Ro(a,Tl.entityName,r.entityName??n.entityName),Ro(a,Tl.threadId,r.threadId??n.threadId),Ro(a,Tl.resourceId,r.resourceId??n.resourceId),Ro(a,Tl.entityId,n.entityId),Ro(a,Tl.runId,n.runId),Ro(a,Tl.sessionId,n.sessionId),Ro(a,Tl.requestId,n.requestId),Ro(a,Tl.userId,n.userId),Ro(a,Tl.organizationId,n.organizationId),Ro(a,Tl.experimentId,n.experimentId),Ro(a,Tl.serviceName,n.serviceName),Ro(a,Tl.environment,n.environment),YWt(a,Tl.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function PSs({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;QWt(a,rx,sx,ax,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Jx,i),Ro(a,jl.entityName,r.entityName??n.entityName),Ro(a,jl.threadId,r.threadId??n.threadId),Ro(a,jl.resourceId,r.resourceId??n.resourceId),Ro(a,jl.runId,n.runId),Ro(a,jl.sessionId,n.sessionId),Ro(a,jl.requestId,n.requestId),Ro(a,jl.userId,n.userId),Ro(a,jl.organizationId,n.organizationId),Ro(a,jl.experimentId,n.experimentId),Ro(a,jl.serviceName,n.serviceName),Ro(a,jl.environment,n.environment),YWt(a,jl.tags,n.tags),r.status==="error"&&a.append(jl.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function TA(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=kY(),a=g.useCallback((c={})=>Rnt({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=g.useCallback((c={})=>PSs({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=RSs(u,d);return Rnt({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const KWt="1h";async function yoe(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:KWt,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 $Ss(){const e=Qe(),{filters:t,filterKey:n}=Wm();return gt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([yoe(e,"mastra_agent_duration_ms",t),yoe(e,"mastra_workflow_duration_ms",t),yoe(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:KWt}}})}const Pnt={agents:Ku.AGENT,workflows:Ku.WORKFLOW_RUN,tools:Ku.TOOL};function MSs(){const{data:e,isLoading:t,isError:n}=$Ss(),{getTracesHref:r,getBucketTracesHref:s}=TA(),{Link:a}=un(),i=Br();return o.jsx(ISs,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:Pnt[l]},c.tsMs,"1h"))},actions:l=>o.jsx(i5,{href:r({rootEntityType:Pnt[l]}),LinkComponent:a})})}function DSs(e){return e==="threads"||e==="resources"}function boe(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function LSs({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(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&o.jsx(Vt.Summary,{value:h.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&o.jsx(Vt.Summary,{value:p.toLocaleString(),label:"Total threads"}),v?o.jsx(Vt.Actions,{children:v}):null]}),m.isLoading?o.jsx(Vt.Loading,{}):m.isError?o.jsx(Vt.Error,{message:"Failed to load memory data"}):o.jsx(Vt.Content,{children:o.jsxs(vc,{defaultTab:"threads",value:i,onValueChange:y=>{DSs(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(gc,{children:[o.jsx(zr,{value:"threads",children:"Threads"}),o.jsx(zr,{value:"resources",children:"Resources"})]}),o.jsx(vs,{value:"threads",children:d?o.jsxs(fe,{columns:"auto auto auto auto auto",...v0e,children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(fe.RowHeaderCell,{className:"text-ui-sm",children:boe(y.threadId)}),o.jsx(fe.NumberCell,{children:y.resourceId?boe(y.resourceId):"—"}),o.jsx(fe.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(fe.NumberCell,{children:y.tokens>0?ol(y.tokens):"—"}),o.jsx(fe.NumberCell,{children:y.cost!=null?Gh(y.cost,y.costUnit):"—"})]});return b?o.jsx(fe.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(fe.RowStatic,{children:x},y.key)})]}):o.jsx(Vt.NoData,{message:"No thread activity yet"})}),o.jsx(vs,{value:"resources",children:f?o.jsxs(fe,{columns:"auto auto auto auto",...v0e,children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(fe.RowHeaderCell,{className:"text-ui-sm",children:boe(y.resourceId)}),o.jsx(fe.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(fe.NumberCell,{children:y.tokens>0?ol(y.tokens):"—"}),o.jsx(fe.NumberCell,{children:y.cost!=null?Gh(y.cost,y.costUnit):"—"})]});return b?o.jsx(fe.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(fe.RowStatic,{children:x},y.key)})]}):o.jsx(Vt.NoData,{message:"No resource activity yet"})})]})})]})}const xoe=20;function FSs(){const e=Qe(),{filters:t,filterKey:n}=Wm();return gt({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:xoe}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:xoe}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:xoe})]),l=new Map,c=d=>_A(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 woe=20;function zSs(){const e=Qe(),{filters:t,filterKey:n}=Wm();return gt({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:woe}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:woe}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:woe})]),l=new Map,c=d=>_A(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 BSs(){const e=FSs(),t=zSs(),{getTracesHref:n}=TA(),{Link:r}=un();return o.jsx(LSs,{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 o5({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 USs(){const e=Qe(),{filters:t,filterKey:n}=Wm();return gt({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 qSs(){const e=Qe(),{filters:t,filterKey:n}=Wm();return gt({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 VSs(){const e=Qe(),{filters:t,filterKey:n}=Wm();return gt({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 HSs(){const e=Qe(),{filters:t,filterKey:n}=Wm();return gt({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 WSs(){const{data:e,isLoading:t,isError:n}=GWt();return o.jsx(o5,{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 ZSs(){const{data:e,isLoading:t,isError:n}=VSs();return o.jsx(o5,{label:"Total Model Cost",value:e?.cost!=null?Gh(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?Gh(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function GSs(){const{data:e,isLoading:t,isError:n}=HSs();return o.jsx(o5,{label:"Total Tokens",value:e?.value!=null?ol(e.value):null,prevValue:e?.previousValue!=null?ol(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function QSs(){const{data:e,isLoading:t,isError:n}=qSs();return o.jsx(o5,{label:"Total Threads",value:e?.value!=null?ol(e.value):null,prevValue:e?.previousValue!=null?ol(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function YSs(){const{data:e,isLoading:t,isError:n}=USs();return o.jsx(o5,{label:"Total Resources",value:e?.value!=null?ol(e.value):null,prevValue:e?.previousValue!=null?ol(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function KSs({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=>XSs(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(kRe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(wRe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function XSs(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 JSs({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const i=!!e&&e.length>0;return o.jsxs(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.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?Gh(l):"—":c.size===1?u=l>0?Gh(l,[...c][0]):"—":u="Mixed",o.jsx(Vt.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(Vt.Actions,{children:s}):null]}),t?o.jsx(Vt.Loading,{}):n?o.jsx(Vt.Error,{message:"Failed to load model usage data"}):o.jsx(Vt.Content,{children:i?o.jsxs(fe,{columns:"auto auto auto auto auto auto",...v0e,children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{sticky:"start",children:"Model"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(fe.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(fe.RowHeaderCell,{className:"text-ui-sm",children:l.model}),o.jsx(fe.NumberCell,{children:l.input}),o.jsx(fe.NumberCell,{children:l.output}),o.jsx(fe.NumberCell,{children:l.cacheRead}),o.jsx(fe.NumberCell,{children:l.cacheWrite}),o.jsx(fe.NumberCell,{highlight:!0,children:l.cost!=null?Gh(l.cost,l.costUnit):"—"})]});return c?o.jsx(fe.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(fe.RowStatic,{children:u},l.model)})]}):o.jsx(Vt.NoData,{message:"No model usage data yet"})})]})}function eks(){const e=Qe(),{filters:t,filterKey:n}=Wm();return gt({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=>_A(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:ol(f.input),output:ol(f.output),cacheRead:ol(f.cacheRead),cacheWrite:ol(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function tks(){const{data:e,isLoading:t,isError:n}=eks(),{getTracesHref:r}=TA(),{Link:s}=un();return o.jsx(JSs,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:Ku.AGENT}),actions:o.jsx(i5,{href:r({rootEntityType:Ku.AGENT}),LinkComponent:s})})}function nks(e){return e==="tokens"||e==="cost"}function rks({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(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&y?o.jsx(Vt.Summary,{value:Gh(v,m),label:"Total cost"}):o.jsx(Vt.Summary,{value:ol(d),label:"Total tokens"})),u&&s?o.jsx(Vt.Actions,{children:s}):null]}),t?o.jsx(Vt.Loading,{}):n?o.jsx(Vt.Error,{message:"Failed to load token usage data"}):o.jsx(Vt.Content,{children:u?o.jsxs(vc,{defaultTab:"tokens",value:i,onValueChange:b=>{nks(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(gc,{children:[o.jsx(zr,{value:"tokens",children:"Tokens"}),o.jsx(zr,{value:"cost",children:"Cost"})]}),o.jsx(vs,{value:"tokens",children:o.jsx(tI,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:Qh.blueDark},{label:"Output",color:Qh.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:ol})}),o.jsx(vs,{value:"cost",children:y?o.jsx(tI,{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:Qh.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>Gh(b,m)}):o.jsx(Vt.NoData,{message:"No cost data yet"})})]}):o.jsx(Vt.NoData,{message:"No token usage data yet"})})]})}function sks(){const e=Qe(),{filters:t,filterKey:n}=Wm();return gt({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=>_A(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 aks(){const{data:e,isLoading:t,isError:n}=sks(),{getTracesHref:r}=TA(),{Link:s}=un();return o.jsx(rks,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:Ku.AGENT,entityName:a.name}),actions:o.jsx(i5,{href:r({rootEntityType:Ku.AGENT}),LinkComponent:s})})}function E0e(e,t=ol){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const iks=[{dataKey:"input",label:"Input tokens",color:Qh.blue,aggregate:E0e("input")},{dataKey:"output",label:"Output tokens",color:Qh.yellow,aggregate:E0e("output")}];function oks(e){return e==="tokens"||e==="cost"}function lks({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,O)=>k+O.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,O)=>k+(O.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:Qh.purple,aggregate:E0e("cost",k=>Gh(k,v))}];return o.jsxs(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Token usage over time",description:x}),u&&(a==="cost"&&b?o.jsx(Vt.Summary,{value:Gh(y,v),label:"Total cost"}):o.jsx(Vt.Summary,{value:ol(d),label:"Total tokens"})),u&&s?o.jsx(Vt.Actions,{children:s}):null]}),n?o.jsx(Vt.Loading,{}):r?o.jsx(Vt.Error,{message:"Failed to load token usage timeline"}):o.jsx(Vt.Content,{children:u?o.jsxs(vc,{defaultTab:"tokens",value:a,onValueChange:k=>{oks(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(gc,{children:[o.jsx(zr,{value:"tokens",children:"Tokens"}),o.jsx(zr,{value:"cost",children:"Cost"})]}),o.jsx(vs,{value:"tokens",children:o.jsx(LD,{data:c,series:iks})}),o.jsx(vs,{value:"cost",children:b?o.jsx(LD,{data:h,series:w}):o.jsx(Vt.NoData,{message:"No cost data yet"})})]}):o.jsx(Vt.NoData,{message:"No token usage data yet"})})]})}function cks(e){return e==="24h"?"1h":"1d"}function uks(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 $nt(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 dks(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function fks(){const e=Qe(),{datePreset:t,filters:n,filterKey:r}=Wm(),s=cks(t);return gt({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 $nt(l,a.series[0],"input"),$nt(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:uks(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:dks(u)}}),interval:s}}})}function hks(){const{data:e,isLoading:t,isError:n}=fks(),{getTracesHref:r}=TA(),{Link:s}=un();return o.jsx(lks,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(i5,{href:r(),LinkComponent:s})})}function Soe({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(tI,{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:Qh.blueDark},{label:"Errors",color:Qh.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:ol})}function pks({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(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(Vt.Summary,{value:ol(f),label:"Total runs"}),u?o.jsx(Vt.Actions,{children:u}):null]}),t?o.jsx(Vt.Loading,{}):n?o.jsx(Vt.Error,{message:"Failed to load trace volume data"}):o.jsx(Vt.Content,{children:d?o.jsxs(vc,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(gc,{children:[o.jsx(zr,{value:"agents",children:"Agents"}),o.jsx(zr,{value:"workflows",children:"Workflows"}),o.jsx(zr,{value:"tools",children:"Tools"})]}),o.jsx(vs,{value:"agents",children:e.agentData.length>0?o.jsx(Soe,{data:e.agentData,rowHrefs:h("agents"),errorHrefs:p("agents"),LinkComponent:i}):o.jsx(Vt.NoData,{message:"No agent data yet"})}),o.jsx(vs,{value:"workflows",children:e.workflowData.length>0?o.jsx(Soe,{data:e.workflowData,rowHrefs:h("workflows"),errorHrefs:p("workflows"),LinkComponent:i}):o.jsx(Vt.NoData,{message:"No workflow data yet"})}),o.jsx(vs,{value:"tools",children:e.toolData.length>0?o.jsx(Soe,{data:e.toolData,rowHrefs:h("tools"),errorHrefs:p("tools"),LinkComponent:i}):o.jsx(Vt.NoData,{message:"No tool data yet"})})]}):o.jsx(Vt.NoData,{message:"No trace volume data yet"})})]})}async function koe(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=_A(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 mks(){const e=Qe(),{filters:t,filterKey:n}=Wm();return gt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([koe(e,"mastra_agent_duration_ms",t),koe(e,"mastra_workflow_duration_ms",t),koe(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const S8={agents:Ku.AGENT,workflows:Ku.WORKFLOW_RUN,tools:Ku.TOOL};function gks(){const{data:e,isLoading:t,isError:n}=mks(),{getTracesHref:r,getLogsHref:s}=TA(),{Link:a}=un();return o.jsx(pks,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:S8[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:S8[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(i5,{href:r({rootEntityType:S8[i]}),LinkComponent:a}),o.jsx(ESs,{href:s({rootEntityType:S8[i],status:"error"}),LinkComponent:a})]})})}const Ooe="period",k8="dateFrom",O8="dateTo";function vks(){const[e,t]=Ta(),n=e.get(Ooe),r=ySs(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(k8)),h=d(e.get(O8));if(!(!f&&!h))return{from:f,to:h}},[r,e.toString()]),a=g.useMemo(()=>dSs(e),[e.toString()]),i=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d==="24h"?h.delete(Ooe):h.set(Ooe,d),d!=="custom"&&(h.delete(k8),h.delete(O8)),h},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d?.from?h.set(k8,d.from.toISOString()):h.delete(k8),d?.to?h.set(O8,d.to.toISOString()):h.delete(O8),h},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return hSs(h,d),h},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,cSs(e)))return;const d=HWt();d&&t(f=>{const h=new URLSearchParams(f);for(const[p,m]of d)h.append(p,m);return h},{replace:!0})},[]),o.jsx(xSs,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(yks,{})})}function yks(){const[e]=Ta(),{error:t,isLoading:n}=GWt(),{filterTokens:r,setFilterTokens:s}=kY(),[a,i]=g.useState(),{supportsMetrics:l,isInMemory:c,isLoading:u}=tWt(),{data:d,isLoading:f}=NRe(),{data:h,isLoading:p}=ERe(),{data:m,isLoading:v}=jRe(),{data:y,isLoading:b}=TRe(),x=g.useMemo(()=>uSs({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(()=>HWt()!==null),O=g.useCallback(()=>{oSs(e),k(!0),Ve.success("Filters setting for Metrics saved")},[e]),_=g.useCallback(()=>{lSs(),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(R=>R.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&&rs(t)?o.jsx(Wn,{children:o.jsx(_s,{})}):t&&is(t)?o.jsx(Wn,{children:o.jsx(ys,{resource:"metrics"})}):t?o.jsx(Wn,{children:o.jsx(Bs,{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(OSs,{}),o.jsx(ORe,{fields:x,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(KSs,{isLoading:n,filterFields:x,filterTokens:r,onFilterTokensChange:s,onClear:E,onRemoveAll:T,onSave:O,onRemoveSaved:w?_:void 0,autoFocusFilterFieldId:a})]}),u?null:l?o.jsxs("div",{className:"grid content-start gap-8 pb-10",children:[c&&o.jsx(An,{variant:"info",title:"Metrics are not persisted",children:o.jsx(An.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(w0e,{children:[o.jsx(WSs,{}),o.jsx(ZSs,{}),o.jsx(GSs,{}),o.jsx(QSs,{}),o.jsx(YSs,{})]}),o.jsxs(w0e,{children:[o.jsx(tks,{}),o.jsx(aks,{}),o.jsx(hks,{}),o.jsx(BSs,{}),o.jsx(gks,{}),o.jsx(MSs,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(yr,{iconSlot:o.jsx(Cs,{}),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(ae,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(Fs,{})]})})})]})}const bks=50;function xks(){const{paths:e}=un(),{isCmsAvailable:t}=CS(),[n,r]=g.useState(""),[s,a]=g.useState(0),{data:i,isLoading:l,error:c,isPlaceholderData:u}=Oqt({page:s,perPage:bks}),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&&rs(c)?o.jsx(Wn,{children:o.jsx(_s,{})}):c&&is(c)?o.jsx(Wn,{children:o.jsx(ys,{resource:"prompt blocks"})}):c?o.jsx(Wn,{children:o.jsx(Bs,{title:"Failed to load prompt blocks",message:c.message})}):d.length===0&&!l&&s===0?o.jsx(Wn,{children:o.jsx(yus,{})}):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(ae,{as:gi,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(Ir,{}),"Create Prompt"]})]})}),o.jsx(vus,{promptBlocks:d,isLoading:l,search:n,currentPage:s,hasMore:f,onNextPage:h,onPrevPage:p})]})}function wks(){return o.jsx(Lt,{width:"narrow",children:o.jsx(Lt.MainArea,{children:o.jsx(rcs,{children:o.jsx(Xxe,{})})})})}const Sks=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:wXt,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:out,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Fs,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:u3,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:dut,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:lut,href:"https://mastra.ai/contact?ref=studio",external:!0}];function kks(){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:Sks.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(Fs,{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 Oks(){const{data:e={},isLoading:t,error:n}=up(),[r,s]=g.useState(""),[a,i]=g.useState("all");if(n&&rs(n))return o.jsx(Wn,{children:o.jsx(_s,{})});if(n&&is(n))return o.jsx(Wn,{children:o.jsx(ys,{resource:"scorers"})});if(n)return o.jsx(Wn,{children:o.jsx(Bs,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(Wn,{children:o.jsx(FHr,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(BHr,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(LHr,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}function Cks(){const{scorerId:e}=fr(),[t,n]=Ta(),r=t.get("scoreId")??void 0,[s,a]=g.useState(r),[i,l]=g.useState(!1),c=Br(),[u,d]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:f,error:h}=yHr(e),{data:p={},isLoading:m,error:v}=Um(),{isLoading:y,error:b}=Ky(),{data:x=[],isLoading:w,error:k,isFetchingNextPage:O,hasNextPage:_,setEndOfListElement:T}=vHr({scorerId:e,entityId:u?.value==="all"?void 0:u?.value,entityType:u?.type==="ALL"?void 0:u?.type}),E=g.useMemo(()=>f?.agentIds?.filter(P=>p[P]).map(P=>({value:P,label:p[P].name,type:"AGENT"}))||[],[f?.agentIds,p]),N=g.useMemo(()=>f?.workflowIds?.map(P=>({value:P,label:P,type:"WORKFLOW"}))||[],[f?.workflowIds]),I=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...E,...N],[E,N]),A=t.get("entity")??"all",R=I.find(P=>P.value===A);R&&R.value!==u?.value&&d(R),g.useEffect(()=>{if(h){const P=h instanceof Error?h.message:"Failed to load scorer";Ve.error(`Error loading scorer: ${P}`)}},[h]),g.useEffect(()=>{if(v){const P=v instanceof Error?v.message:"Failed to load agents";Ve.error(`Error loading agents: ${P}`)}},[v]),g.useEffect(()=>{if(b){const P=b instanceof Error?b.message:"Failed to load workflows";Ve.error(`Error loading workflows: ${P}`)}},[b]);const L=P=>{P?.value&&n(U=>{const W=new URLSearchParams(U);return W.set("entity",P.value),W})};g.useEffect(()=>{const P=t.get("scoreId")??void 0;if(P===s)return;if(!P){a(void 0);return}x.find(W=>W.id===P)&&a(P)},[t,x]);const D=g.useCallback(P=>{a(P||void 0),n(U=>{const W=new URLSearchParams(U);return P?W.set("scoreId",P):W.delete("scoreId"),W})},[n]);if(!f)return null;const B=rs(h)||rs(v)||rs(b),H=h&&is(h),q=!B&&!H&&(h||v||b),F=!w&&x.length===0,V=u?.value!=="all",M=f?.scorer?.source==="stored"?o.jsx(o0,{owner:"scorer-detail",children:o.jsxs(ae,{variant:"default",as:gi,to:`/cms/scorers/${e}/edit`,size:"sm",children:[o.jsx(Yh,{})," Edit"]})}):null,G=e?o.jsx(yY,{open:i,onOpenChange:l,initialScorerIds:[e],onSuccess:P=>{c(`/experiments/${P}`)}}):null;if(B||H||q||F&&!V){const P=(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(_s,{}):H?o.jsx(ys,{resource:"scorers"}):q?o.jsx(Bs,{title:"Failed to load scorer",message:P}):o.jsx(uHr,{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(dHr,{selectedEntity:u,entityOptions:I,onEntityChange:L,onReset:()=>{n(P=>{const U=new URLSearchParams(P);return U.set("entity","all"),U})},isLoading:w||m||y}),o.jsxs(ae,{variant:"primary",onClick:()=>l(!0),children:[o.jsx(Fc,{}),"Run Experiment"]})]})}),o.jsx(cHr,{scores:x,isLoading:w,selectedScoreId:s,isFetchingNextPage:O,hasNextPage:_,setEndOfListElement:T,onScoreClick:D,errorMsg:k?.message}),G]})}const _ks=oo("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"}}),Eks=oo("flex min-w-0 flex-col",{variants:{variant:{default:"",factory:"gap-0.5"}},defaultVariants:{variant:"default"}}),Mnt=oo("",{variants:{variant:{default:"text-sm font-medium",factory:"text-ui-md leading-ui-md text-neutral5"}},defaultVariants:{variant:"default"}}),Tks=oo("flex flex-col gap-0.5",{variants:{variant:{default:"text-sm text-neutral3",factory:"text-ui-sm text-neutral3"}},defaultVariants:{variant:"default"}});function jks({label:e,description:t,htmlFor:n,variant:r,className:s,children:a}){return o.jsxs("div",{className:K(_ks({variant:r}),s),"data-slot":"settings-row",children:[o.jsxs("div",{className:Eks({variant:r}),children:[n?o.jsx(Dt,{htmlFor:n,className:Mnt({variant:r}),children:e}):o.jsx("span",{className:Mnt({variant:r}),children:e}),t&&o.jsx("div",{className:Tks({variant:r}),children:t})]}),a]})}const XWt=[{value:"dark",label:"Dark",Icon:Sen},{value:"light",label:"Light",Icon:Ztn},{value:"system",label:"System",Icon:Cut}],Nks=e=>XWt.some(t=>t.value===e);function Iks({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 Aks=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=WH(),{theme:r,setTheme:s}=d_();return o.jsx(Lt,{width:"narrow",children:o.jsxs(Lt.MainArea,{className:"mt-6 flex flex-col gap-5",children:[o.jsx(wxe,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(jks,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(da,{value:r,onValueChange:a=>{Nks(a)&&s(a)},children:[o.jsx(ha,{id:"theme",className:"w-full sm:w-48",children:o.jsx(fa,{className:"inline-flex max-w-full min-w-0 items-center"})}),o.jsx(pa,{children:XWt.map(a=>o.jsx(xr,{value:a.value,children:o.jsx(Iks,{option:a})},a.value))})]})})}),o.jsx(wxe,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(N4t,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function Rks(){const[e]=Ta(),t=Br(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(UWt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}function Pks(e){return e.replace(/\/$/,"").split("/").pop()}function OY({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 $ks({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(uo,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(qf,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(Eut,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(pI,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx($_,{})," ",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(_G,{})," ",Pks(a.githubUrl)]})})]},a.slug)})})}function Mks({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(_C,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(Om,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(Om,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(ae,{onClick:c,children:["Reset ",o.jsx(tr,{})]})]})}function Dks(){const{data:e,isLoading:t}=zsr(),{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(ks,{children:[o.jsx(eW,{children:o.jsxs(FSe,{children:[o.jsx(Ke,{children:o.jsx(dx,{})}),"Templates"]})}),o.jsxs("div",{className:K("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(Mks,{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($ks,{templates:y,linkComponent:gi,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const Lks="1.65.0-alpha.12";function Fks({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(Pc,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx($Xt,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(OY,{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 zks({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(OY,{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(Tut,{})]}),o.jsx(Om,{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(Ht,{})," 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(j4t,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(ae,{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(Ht,{className:"h-4 w-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(Bd,{})]})})]})})}function Bks({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(dx,{}),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(_m,{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(B0e,{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(_G,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(Rje,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function Dnt(e){switch(e){case"running":return o.jsx(Ht,{size:"sm","aria-hidden":!0});case"success":return o.jsx(Dr,{"aria-hidden":!0});case"failed":return o.jsx(tr,{"aria-hidden":!0});default:return null}}function Uks(){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 qks({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(Uks,{}):Dnt(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:Dnt(e)})}function Vks({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(qks,{status:e.status,variant:r})]})}function Hks({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:K(n),children:t.map((r,s)=>o.jsx(Vks,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function Wks({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(Ht,{}):s+1})},r.id))}),o.jsxs("div",{className:K("text-center text-xs text-neutral3",Yr.colors),children:[n," of ",t," steps completed"]})]})}function Zks({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(OY,{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(Wks,{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(Pen,{}),l||"Something went wrong"]}),u&&o.jsx(Hks,{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(Ht,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function Gks({name:e,installedEntities:t}){return o.jsxs(OY,{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(Tut,{}),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(Rje,{data:t})]})}function Qks(){const{templateSlug:e}=fr(),[t,n]=Ta(),[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),[O,_]=g.useState(!1),[T,E]=g.useState([]),{data:N,isLoading:I}=Bsr({repoOrSlug:e,owner:"mastra-ai"}),R=Lks?.includes("beta")??!1?"beta":"main",{data:L,isLoading:D}=Usr({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:R}),{data:B,isLoading:H}=qsr(),{mutateAsync:q,isPending:F}=Vsr(),{mutateAsync:V}=Hsr(),{streamInstall:M,streamResult:G,isStreaming:z}=Zsr(B),{observeInstall:P,streamResult:U,isStreaming:W}=Gsr(B);g.useEffect(()=>{const ne=t.get("runId");ne&&!v&&!p&&!z&&!W&&(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:ye,errors:he}=ce.result.validationResults,xe=`Template installation completed but ${ye} validation issue${ye>1?"s":""} remain unresolved.`;m(xe),E(he||[])}else{const ye=ce?.result?.message||ce?.result?.error||"Template installation failed";m(typeof ye=="string"?ye:String(ye))}}).catch(se=>{console.error("❌ Failed to fetch run details:",se),m("Failed to retrieve installation status after reload")}))},[t,v,p,z,W,V]),g.useEffect(()=>{const ne=t.get("runId"),se=t.get("resume"),ce=t.get("provider");if(ne&&se==="true"&&ce&&!z&&!W&&!w&&!O&&B){x(ne),k(!0);try{V({runId:ne}).then(le=>{if(le.snapshot?.status==="running")return P.mutateAsync({runId:ne})}).then(()=>{n(le=>{const ye=new URLSearchParams(le);return ye.delete("resume"),ye})}).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,z,W,w,O,B,V,P,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(qf,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(ne=>ne).join(", "):"n/a",icon:o.jsx(uo,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(ne=>ne).join(", "):"n/a",icon:o.jsx(pI,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(Yv,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(hI,{})}],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"}),oe=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:R,slug:N.slug,variables:u},{runId:le}=await q({});x(le),n(ye=>{const he=new URLSearchParams(ye);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(ye=>ye!==se)),d(le=>({...le,[se]:ce}))};return o.jsx(ks,{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(Bks,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:te,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(z||W)&&o.jsx(Zks,{name:N.title,streamResult:W?U:G,runId:b,workflowInfo:B}),v&&o.jsx(Gks,{name:N.title,installedEntities:J,linkComponent:gi}),p&&o.jsx(Fks,{errorMsg:p,validationErrors:T.length>0?T:G?.validationResults?.errors||U?.validationResults?.errors}),!z&&!W&&!v&&!p&&o.jsx(zks,{providerOptions:Y,selectedProvider:r,onProviderChange:ee,variables:u,setVariables:d,errors:f,setErrors:h,handleInstallTemplate:oe,handleVariableChange:X,isLoadingEnvVars:D||H,isInstalling:F,defaultModelProvider:a,defaultModelId:l,onModelUpdate:re})]})]})})})}const Yks=()=>{const{toolId:e,agentId:t}=fr();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(xcs,{toolId:e,agentId:t})})},Kks=()=>{const{toolId:e}=fr();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(K1s,{toolId:e})})};function Xks(){const{data:e,isLoading:t,error:n}=Ky(),[r,s]=g.useState("");return n&&rs(n)?o.jsx(Wn,{children:o.jsx(_s,{})}):n&&is(n)?o.jsx(Wn,{children:o.jsx(ys,{resource:"workflows"})}):n?o.jsx(Wn,{children:o.jsx(Bs,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(Wn,{children:o.jsx(oXr,{})}):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(ae,{as:gi,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(MC,{}),"Schedules"]})]})}),o.jsx(iXr,{workflows:e||{},isLoading:t,search:r})]})}const Jks={active:"bg-accent1",paused:"bg-accent3"},eOs={active:"text-accent1",paused:"text-accent3"},JWt=({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 ${Jks[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${eOs[e]}`,children:e})]}),Rj=e=>!e||e<=0?"—":new Date(e).toLocaleString(),w2=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 eZt({status:e}){const{icon:t,color:n}=tOs(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 tOs(e){switch(e){case"success":return{icon:o.jsx(Dr,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(tr,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(Ht,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(BV,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(Cs,{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 Lnt="auto auto auto auto 1fr";function nOs(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 rOs(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 sOs=3e4,aOs=5*6e4;function iOs({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=un(),c=p=>!!(n&&p.runId&&p.outcome!=="failed"),u=e.filter(c).length,{containerRef:d,getRowProps:f}=no({count:u});let h=-1;return t?o.jsx(Lo,{columns:Lnt}):e.length===0?o.jsx(me,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(fe,{columns:Lnt,className:"min-w-0",scrollRef:d,children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{children:"Run"}),o.jsx(fe.TopCell,{children:"Status"}),o.jsx(fe.TopCell,{children:"Started"}),o.jsx(fe.TopCell,{children:"Duration"}),o.jsx(fe.TopCell,{children:" "})]}),e.map(p=>{const m=p.actualFireAt-p.scheduledFireAt,v=rOs(m),y=`Scheduled ${Rj(p.scheduledFireAt)} — published ${Rj(p.actualFireAt)} (drift ${v})`,b=p.outcome==="failed",x=b?p.error:p.run?.error,w=Math.abs(m),k=!b&&w>sOs&&w<=aOs,O=`${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(fe.Cell,{children:T}),o.jsx(fe.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(Pc,{size:14}),"publish failed"]}):p.run?o.jsx(eZt,{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(bn,{children:[o.jsx(mn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(Pc,{size:14})})}),o.jsx(gn,{children:x})]}):null]})}),o.jsx(fe.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:y,children:w2(p.actualFireAt)}),k?o.jsxs(bn,{children:[o.jsx(mn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(Pc,{size:14})})}),o.jsxs(gn,{children:["Published ",v," after the scheduled fire time"]})]}):null]})}),o.jsx(fe.Cell,{children:p.run?o.jsx("span",{children:nOs(p.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(fe.Cell,{children:" "})]});return _?o.jsx(fe.RowLink,{to:l.workflowRunLink(n,p.runId),LinkComponent:i,...f(h),children:E},O):o.jsx(fe.RowStatic,{children:E},O)}),o.jsx(fe.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const oOs=e=>{const t=Qe();return gt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},Fnt=25,lOs=e=>{const t=Qe(),{inView:n,setRef:r}=i0(),s=Fy({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:Fnt,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<Fnt))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}},cOs=e=>{const t=Qe(),n=Er();return wn({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 C8({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral4 tracking-wide uppercase",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function uOs(){const{scheduleId:e}=fr(),{paths:t}=un(),{data:n,error:r}=oOs(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=lOs(e),d=cOs(e);if(r&&rs(r))return o.jsx(Wn,{children:o.jsx(_s,{})});if(r&&is(r))return o.jsx(Wn,{children:o.jsx(ys,{resource:"schedules"})});if(r)return o.jsx(Wn,{children:o.jsx(Bs,{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(ae,{as:gi,to:t.schedulesLink(),variant:"ghost",children:[o.jsx(uc,{}),"Back to schedules"]}),f?o.jsx(ae,{as:gi,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(ae,{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(GV,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(Fc,{}),"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(C8,{label:h?"Agent":"Workflow",children:f?o.jsx(gi,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):h?o.jsx(gi,{to:t.agentLink(h),className:"text-accent1 hover:underline",children:h}):"—"}),o.jsxs(C8,{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(C8,{label:"Status",children:o.jsx(JWt,{status:n.status})}),o.jsx(C8,{label:"Next fire",children:o.jsx("span",{title:Rj(n.nextFireAt),children:w2(n.nextFireAt)})})]}),o.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[o.jsx(me,{variant:"ui-md",className:"mb-3",children:"Trigger history"}),i?o.jsx(Bs,{title:"Failed to load trigger history",message:i.message}):o.jsx(iOs,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const znt="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function dOs({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=un(),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}=no({count:a.length});return t?o.jsx(Lo,{columns:znt}):o.jsxs(fe,{columns:znt,className:"min-w-0",scrollRef:i,children:[o.jsxs(fe.Top,{children:[o.jsx(fe.TopCell,{children:"Target"}),o.jsx(fe.TopCell,{children:"Schedule ID"}),o.jsx(fe.TopCell,{children:"Cron"}),o.jsx(fe.TopCell,{children:"Status"}),o.jsx(fe.TopCell,{children:"Next fire"}),o.jsx(fe.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(fe.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(fe.NoMatch,{message:"No schedules configured"}):null,a.map((c,u)=>o.jsxs(fe.RowLink,{to:r.scheduleLink(c.id),LinkComponent:s,...l(u),children:[o.jsx(fe.NameCell,{children:c.workflowId??c.agentId}),o.jsx(fe.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(fe.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(fe.Cell,{children:o.jsx(JWt,{status:c.status})}),o.jsx(fe.Cell,{children:o.jsx("span",{className:"whitespace-nowrap",title:Rj(c.nextFireAt),children:w2(c.nextFireAt)})}),o.jsx(fe.Cell,{children:c.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(eZt,{status:c.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:Rj(c.lastFireAt),children:c.lastFireAt?w2(c.lastFireAt):""})]}):c.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:Rj(c.lastFireAt),children:w2(c.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},c.id))]})}function fOs({workflowId:e}={}){const{data:t,isLoading:n,error:r}=DSe(e?{workflowId:e}:{}),[s,a]=g.useState("");return r?o.jsx(Bs,{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(dOs,{schedules:t??[],isLoading:n,search:s})})]})}function hOs(){const[e]=Ta(),t=e.get("workflowId")??void 0,{error:n}=DSe(t?{workflowId:t}:{});return n&&rs(n)?o.jsx(Wn,{children:o.jsx(_s,{})}):n&&is(n)?o.jsx(Wn,{children:o.jsx(ys,{resource:"schedules"})}):o.jsx(Lt,{children:o.jsx("div",{className:"h-full",children:o.jsx(fOs,{workflowId:t})})})}function pOs({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=cCe({stepGraph:e}),[a,i]=g.useState(!1),[l,c,u]=oEt(r),[d]=lEt(s),{edgeTypes:f,nodeTypes:h,styledEdges:p}=G6t({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(iEt,{nodes:l,edges:p,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:h,onNodesChange:u,children:[o.jsx(hNe,{position:"bottom-left"}),o.jsx(uEt,{variant:gy.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:o.jsx(Ht,{})})})}function mOs(){const{stepDetail:e,closeStepDetail:t}=GW();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(d1,{className:"h-4 w-4",style:{color:Bu.map}}),e.type==="nested-graph"&&o.jsx(_u,{className:"h-4 w-4",style:{color:Bu.workflow}}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx(me,{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(me,{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(tr,{className:"text-neutral3 h-4 w-4"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(v2,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(lCe,{children:o.jsx(pOs,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function gOs(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function vOs(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 yOs({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(me,{as:"p",variant:"ui-md",className:"text-neutral6 flex items-center gap-2 font-semibold",children:[o.jsx(Ke,{children:o.jsx(BV,{})}),"Step suspended"]}),o.jsx(mt,{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?bm(Rx(i.resumeSchema)):yf(cr(),jf());return o.jsx(bOs,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function bOs({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(me,{as:"p",variant:"ui-md",className:"text-neutral6 truncate font-medium",children:e.stepId}),n&&o.jsx(me,{as:"p",variant:"ui-sm",className:"text-neutral3",children:n})]}),e.suspendPayload&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs(me,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(Ke,{children:o.jsx(Oen,{})}),"The step is asking"]}),o.jsxs(cc,{open:a,onOpenChange:i,children:[o.jsxs(Bl,{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(Ke,{children:o.jsx(Fr,{className:K("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(me,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:vOs(e.suspendPayload,e.stepId)})]}),o.jsx(me,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:gOs(e.suspendPayload)})]}),o.jsx(Ul,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Hr,{data:e.suspendPayload,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs(me,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(Ke,{children:o.jsx(Een,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(_U,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(Fc,{}),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 xOs(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext(Wl),{runId:a}=fr(),i=vEt(e,r??""),l=enr(),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(yOs,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const wOs=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"})]}),SOs=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"})]}),kOs=e=>e.includes("."),OOs=e=>e==="input"||e.endsWith(".input"),COs=1;function _Os(e){return`${Number((e/1e3).toPrecision(3))}s`}function EOs(e,t){const n=Object.entries(e).filter(([i])=>!OOs(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,COs);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:h,durationMs:d,isRunning:c,isNestedEntry:kOs(i)}})}const TOs=({status:e})=>o.jsxs(Ke,{children:[e==="success"&&o.jsx(wOs,{className:"text-accent1"}),e==="failed"&&o.jsx(SOs,{className:"text-accent2"}),e==="suspended"&&o.jsx(BV,{className:"text-accent3"}),e==="waiting"&&o.jsx(hpe,{className:"text-accent5"}),e==="skipped"&&o.jsx(hpe,{className:"text-icon3"}),e==="running"&&o.jsx(Ws,{className:"text-accent6 animate-spin"})]}),jOs={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function tZt(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const Bnt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},NOs=e=>{const t=e;return F6t({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},IOs=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=NOs(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(TOs,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ae,{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(Btn,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(pV,{indicators:c,className:"shrink-0"})}),o.jsx(me,{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:tZt(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 ${jOs[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ae,{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(Ftn,{})})}),o.jsx(me,{as:"span",variant:"ui-sm",className:"text-neutral3 w-20 justify-self-end text-right tabular-nums",children:_Os(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function AOs(){const{steps:e}=h4(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=sW(),[a,i]=g.useState(()=>Date.now()),[l,c]=g.useState(!1),[u,d]=g.useState(null),f=g.useRef(null);Zxt(f,{enabled:!l});const h=EOs(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(me,{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(ta,{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(IOs,{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:Bnt(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:Bnt(y.step.output)})},`timeline-item-${m.stepId}-${v}`))})]})}),o.jsx(pr,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(bEt,{data:u.data,title:`${tZt(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const ROs=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=GW();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(tFt,{workflowId:e,workflow:t,isLoading:n}),o.jsx(xOs,{}),o.jsx(AOs,{})]})}),r&&o.jsx("div",{className:"border-border1 min-h-0 w-[420px] overflow-hidden border-l",children:o.jsx(mOs,{})})]})},Unt=()=>{const{workflowId:e}=fr(),{data:t,isLoading:n,error:r}=kL(e);return r&&rs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(_s,{})}):r&&is(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ys,{resource:"workflows"})}):o.jsx(ECe,{children:o.jsx(ROs,{workflowId:e,workflow:t??void 0,isLoading:n})})};function POs(e,t){if(e==null)return{};var n,r,s=SOt(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 T0e(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 $Os(e){if(Array.isArray(e))return T0e(e)}function MOs(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function DOs(e,t){if(e){if(typeof e=="string")return T0e(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)?T0e(e,t):void 0}}function LOs(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
674
674
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function j0e(e){return $Os(e)||MOs(e)||DOs(e)||LOs()}function n3(e){"@babel/helpers - typeof";return n3=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},n3(e)}function FOs(e,t){if(n3(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(n3(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function zOs(e){var t=FOs(e,"string");return n3(t)=="symbol"?t:t+""}function nZt(e,t,n){return(t=zOs(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function qnt(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?qnt(Object(n),!0).forEach(function(r){nZt(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):qnt(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function BOs(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 Coe={};function UOs(e){if(e.length===0||e.length===1)return e;var t=e.join(".");return Coe[t]||(Coe[t]=BOs(e)),Coe[t]}function qOs(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=UOs(r);return s.reduce(function(a,i){return ZT(ZT({},a),n[i])},t)}function Vnt(e){return e.join(" ")}function VOs(e,t){var n=0;return function(r){return n+=1,r.map(function(s,a){return rZt({node:s,stylesheet:e,useInlineStyles:t,key:"code-segment-".concat(n,"-").concat(a)})})}}function rZt(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=VOs(n,a),h;if(!a)h=ZT(ZT({},l),{},{className:Vnt(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:Vnt(v)||void 0,style:qOs(l.className,Object.assign({},l.style,s),n)})}var y=f(t.children);return qe.createElement(u,cC({key:i},h),y)}}const HOs=(function(e,t){var n=e.listLanguages();return n.indexOf(t)!==-1});var WOs=["language","children","style","customStyle","codeTagProps","useInlineStyles","showLineNumbers","showInlineLineNumbers","startingLineNumber","lineNumberContainerStyle","lineNumberStyle","wrapLines","wrapLongLines","lineProps","renderer","PreTag","CodeTag","code","astGenerator"];function Hnt(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 Hw(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Hnt(Object(n),!0).forEach(function(r){nZt(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Hnt(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var ZOs=/\n/g;function GOs(e){return e.match(ZOs)}function QOs(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,`
675
675
  `))})}function YOs(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)},QOs({lines:t.replace(/\n$/,"").split(`
676
676
  `),style:i,startingLineNumber:l}))}function KOs(e){return"".concat(e.toString().length,".25em")}function sZt(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 aZt(e,t,n){var r={display:"inline-block",minWidth:KOs(n),paddingRight:"1em",textAlign:"right",userSelect:"none"},s=typeof e=="function"?e(t):e,a=Hw(Hw({},r),s);return a}function G9(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?Hw({},typeof l=="function"?l(n):l):{};if(m.className=m.className?[].concat(j0e(m.className.trim().split(/\s+/)),j0e(u)):u,n&&a){var v=aZt(r,n,s);t.unshift(sZt(n,v))}return f&d&&(m.style=Hw({display:"flex"},m.style)),{type:"element",tagName:"span",properties:m,children:t}}function iZt(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(G9({children:[s],className:j0e(new Set(t))}));else if(s.children){var a=t.concat(s.properties.className);iZt(s.children,a).forEach(function(i){return n.push(i)})}}return n}function XOs(e,t,n,r,s,a,i,l,c){var u,d=iZt(e.value),f=[],h=-1,p=0;function m(O,_){var T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return G9({children:O,lineNumber:_,lineNumberStyle:l,largestLineNumber:i,showInlineLineNumbers:s,lineProps:n,className:T,showLineNumbers:r,wrapLongLines:c,wrapLines:t})}function v(O,_){if(r&&_&&s){var T=aZt(l,_,i);O.unshift(sZt(_,T))}return O}function y(O,_){var T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return t||T.length>0?m(O,_,T):v(O,_)}for(var b=function(){var _=d[p],T=_.children[0].value,E=GOs(T);if(E){var N=T.split(`