@mastra/deployer-cloud 1.54.0 → 1.55.0-alpha.0

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-CZ7lrnPw.js","./engine-compile-BkERmzkH.js","./preload-helper-PPVm8Dsz.js","./engine-javascript-CSIo_1eZ.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./core-DBMTExoC.js","./engine-compile-BkERmzkH.js","./preload-helper-PPVm8Dsz.js","./engine-javascript-CSIo_1eZ.js"])))=>i.map(i=>d[i]);
2
2
  import{_ as mo}from"./preload-helper-PPVm8Dsz.js";function oqt(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 lT=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Fl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var hK={exports:{}},UA={};var x2e;function lqt(){if(x2e)return UA;x2e=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 UA.Fragment=t,UA.jsx=n,UA.jsxs=n,UA}var w2e;function cqt(){return w2e||(w2e=1,hK.exports=lqt()),hK.exports}var o=cqt(),mK={exports:{}},qr={},S2e;function uqt(){if(S2e)return qr;S2e=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"),p=Symbol.for("react.activity"),h=Symbol.iterator;function m(V){return V===null||typeof V!="object"?null:(V=h&&V[h]||V["@@iterator"],typeof V=="function"?V:null)}var g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y=Object.assign,b={};function x(V,$,U){this.props=V,this.context=$,this.refs=b,this.updater=U||g}x.prototype.isReactComponent={},x.prototype.setState=function(V,$){if(typeof V!="object"&&typeof V!="function"&&V!=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,V,$,"setState")},x.prototype.forceUpdate=function(V){this.updater.enqueueForceUpdate(this,V,"forceUpdate")};function S(){}S.prototype=x.prototype;function k(V,$,U){this.props=V,this.context=$,this.refs=b,this.updater=U||g}var _=k.prototype=new S;_.constructor=k,y(_,x.prototype),_.isPureReactComponent=!0;var C=Array.isArray;function E(){}var j={H:null,A:null,T:null,S:null},N=Object.prototype.hasOwnProperty;function I(V,$,U){var Z=U.ref;return{$$typeof:t,type:V,key:$,ref:Z!==void 0?Z:null,props:U}}function A(V,$){return I(V.type,$,V.props)}function R(V){return typeof V=="object"&&V!==null&&V.$$typeof===t}function L(V){var $={"=":"=0",":":"=2"};return"$"+V.replace(/[=:]/g,function(U){return $[U]})}var D=/\/+/g;function B(V,$){return typeof V=="object"&&V!==null&&V.key!=null?L(""+V.key):$.toString(36)}function H(V){switch(V.status){case"fulfilled":return V.value;case"rejected":throw V.reason;default:switch(typeof V.status=="string"?V.then(E,E):(V.status="pending",V.then(function($){V.status==="pending"&&(V.status="fulfilled",V.value=$)},function($){V.status==="pending"&&(V.status="rejected",V.reason=$)})),V.status){case"fulfilled":return V.value;case"rejected":throw V.reason}}throw V}function F(V,$,U,Z,K){var te=typeof V;(te==="undefined"||te==="boolean")&&(V=null);var ee=!1;if(V===null)ee=!0;else switch(te){case"bigint":case"string":case"number":ee=!0;break;case"object":switch(V.$$typeof){case t:case n:ee=!0;break;case f:return ee=V._init,F(ee(V._payload),$,U,Z,K)}}if(ee)return K=K(V),ee=Z===""?"."+B(V,0):Z,C(K)?(U="",ee!=null&&(U=ee.replace(D,"$&/")+"/"),F(K,$,U,"",function(de){return de})):K!=null&&(R(K)&&(K=A(K,U+(K.key==null||V&&V.key===K.key?"":(""+K.key).replace(D,"$&/")+"/")+ee)),$.push(K)),1;ee=0;var J=Z===""?".":Z+":";if(C(V))for(var ae=0;ae<V.length;ae++)Z=V[ae],te=J+B(Z,ae),ee+=F(Z,$,U,te,K);else if(ae=m(V),typeof ae=="function")for(V=ae.call(V),ae=0;!(Z=V.next()).done;)Z=Z.value,te=J+B(Z,ae++),ee+=F(Z,$,U,te,K);else if(te==="object"){if(typeof V.then=="function")return F(H(V),$,U,Z,K);throw $=String(V),Error("Objects are not valid as a React child (found: "+($==="[object Object]"?"object with keys {"+Object.keys(V).join(", ")+"}":$)+"). If you meant to render a collection of children, use an array instead.")}return ee}function z(V,$,U){if(V==null)return V;var Z=[],K=0;return F(V,Z,"","",function(te){return $.call(U,te,K++)}),Z}function q(V){if(V._status===-1){var $=V._result;$=$(),$.then(function(U){(V._status===0||V._status===-1)&&(V._status=1,V._result=U)},function(U){(V._status===0||V._status===-1)&&(V._status=2,V._result=U)}),V._status===-1&&(V._status=0,V._result=$)}if(V._status===1)return V._result.default;throw V._result}var M=typeof reportError=="function"?reportError:function(V){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var $=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof V=="object"&&V!==null&&typeof V.message=="string"?String(V.message):String(V),error:V});if(!window.dispatchEvent($))return}else if(typeof e=="object"&&typeof e.emit=="function"){e.emit("uncaughtException",V);return}console.error(V)},G={map:z,forEach:function(V,$,U){z(V,function(){$.apply(this,arguments)},U)},count:function(V){var $=0;return z(V,function(){$++}),$},toArray:function(V){return z(V,function($){return $})||[]},only:function(V){if(!R(V))throw Error("React.Children.only expected to receive a single React element child.");return V}};return qr.Activity=p,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=j,qr.__COMPILER_RUNTIME={__proto__:null,c:function(V){return j.H.useMemoCache(V)}},qr.cache=function(V){return function(){return V.apply(null,arguments)}},qr.cacheSignal=function(){return null},qr.cloneElement=function(V,$,U){if(V==null)throw Error("The argument must be a React element, but you passed "+V+".");var Z=y({},V.props),K=V.key;if($!=null)for(te in $.key!==void 0&&(K=""+$.key),$)!N.call($,te)||te==="key"||te==="__self"||te==="__source"||te==="ref"&&$.ref===void 0||(Z[te]=$[te]);var te=arguments.length-2;if(te===1)Z.children=U;else if(1<te){for(var ee=Array(te),J=0;J<te;J++)ee[J]=arguments[J+2];Z.children=ee}return I(V.type,K,Z)},qr.createContext=function(V){return V={$$typeof:l,_currentValue:V,_currentValue2:V,_threadCount:0,Provider:null,Consumer:null},V.Provider=V,V.Consumer={$$typeof:i,_context:V},V},qr.createElement=function(V,$,U){var Z,K={},te=null;if($!=null)for(Z in $.key!==void 0&&(te=""+$.key),$)N.call($,Z)&&Z!=="key"&&Z!=="__self"&&Z!=="__source"&&(K[Z]=$[Z]);var ee=arguments.length-2;if(ee===1)K.children=U;else if(1<ee){for(var J=Array(ee),ae=0;ae<ee;ae++)J[ae]=arguments[ae+2];K.children=J}if(V&&V.defaultProps)for(Z in ee=V.defaultProps,ee)K[Z]===void 0&&(K[Z]=ee[Z]);return I(V,te,K)},qr.createRef=function(){return{current:null}},qr.forwardRef=function(V){return{$$typeof:c,render:V}},qr.isValidElement=R,qr.lazy=function(V){return{$$typeof:f,_payload:{_status:-1,_result:V},_init:q}},qr.memo=function(V,$){return{$$typeof:d,type:V,compare:$===void 0?null:$}},qr.startTransition=function(V){var $=j.T,U={};j.T=U;try{var Z=V(),K=j.S;K!==null&&K(U,Z),typeof Z=="object"&&Z!==null&&typeof Z.then=="function"&&Z.then(E,M)}catch(te){M(te)}finally{$!==null&&U.types!==null&&($.types=U.types),j.T=$}},qr.unstable_useCacheRefresh=function(){return j.H.useCacheRefresh()},qr.use=function(V){return j.H.use(V)},qr.useActionState=function(V,$,U){return j.H.useActionState(V,$,U)},qr.useCallback=function(V,$){return j.H.useCallback(V,$)},qr.useContext=function(V){return j.H.useContext(V)},qr.useDebugValue=function(){},qr.useDeferredValue=function(V,$){return j.H.useDeferredValue(V,$)},qr.useEffect=function(V,$){return j.H.useEffect(V,$)},qr.useEffectEvent=function(V){return j.H.useEffectEvent(V)},qr.useId=function(){return j.H.useId()},qr.useImperativeHandle=function(V,$,U){return j.H.useImperativeHandle(V,$,U)},qr.useInsertionEffect=function(V,$){return j.H.useInsertionEffect(V,$)},qr.useLayoutEffect=function(V,$){return j.H.useLayoutEffect(V,$)},qr.useMemo=function(V,$){return j.H.useMemo(V,$)},qr.useOptimistic=function(V,$){return j.H.useOptimistic(V,$)},qr.useReducer=function(V,$,U){return j.H.useReducer(V,$,U)},qr.useRef=function(V){return j.H.useRef(V)},qr.useState=function(V){return j.H.useState(V)},qr.useSyncExternalStore=function(V,$,U){return j.H.useSyncExternalStore(V,$,U)},qr.useTransition=function(){return j.H.useTransition()},qr.version="19.2.7",qr}var k2e;function DN(){return k2e||(k2e=1,mK.exports=uqt()),mK.exports}var v=DN();const Fe=Fl(v),v_=oqt({__proto__:null,default:Fe},[v]);var gK={exports:{}},VA={},vK={exports:{}},yK={};var O2e;function dqt(){return O2e||(O2e=1,(function(e){function t(H,F){var z=H.length;H.push(F);e:for(;0<z;){var q=z-1>>>1,M=H[q];if(0<s(M,F))H[q]=F,H[z]=M,z=q;else break e}}function n(H){return H.length===0?null:H[0]}function r(H){if(H.length===0)return null;var F=H[0],z=H.pop();if(z!==F){H[0]=z;e:for(var q=0,M=H.length,G=M>>>1;q<G;){var V=2*(q+1)-1,$=H[V],U=V+1,Z=H[U];if(0>s($,z))U<M&&0>s(Z,$)?(H[q]=Z,H[U]=z,q=U):(H[q]=$,H[V]=z,q=V);else if(U<M&&0>s(Z,z))H[q]=Z,H[U]=z,q=U;else break e}}return F}function s(H,F){var z=H.sortIndex-F.sortIndex;return z!==0?z:H.id-F.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,p=3,h=!1,m=!1,g=!1,y=!1,b=typeof setTimeout=="function"?setTimeout:null,x=typeof clearTimeout=="function"?clearTimeout:null,S=typeof setImmediate<"u"?setImmediate:null;function k(H){for(var F=n(u);F!==null;){if(F.callback===null)r(u);else if(F.startTime<=H)r(u),F.sortIndex=F.expirationTime,t(c,F);else break;F=n(u)}}function _(H){if(g=!1,k(H),!m)if(n(c)!==null)m=!0,C||(C=!0,R());else{var F=n(u);F!==null&&B(_,F.startTime-H)}}var C=!1,E=-1,j=5,N=-1;function I(){return y?!0:!(e.unstable_now()-N<j)}function A(){if(y=!1,C){var H=e.unstable_now();N=H;var F=!0;try{e:{m=!1,g&&(g=!1,x(E),E=-1),h=!0;var z=p;try{t:{for(k(H),f=n(c);f!==null&&!(f.expirationTime>H&&I());){var q=f.callback;if(typeof q=="function"){f.callback=null,p=f.priorityLevel;var M=q(f.expirationTime<=H);if(H=e.unstable_now(),typeof M=="function"){f.callback=M,k(H),F=!0;break t}f===n(c)&&r(c),k(H)}else r(c);f=n(c)}if(f!==null)F=!0;else{var G=n(u);G!==null&&B(_,G.startTime-H),F=!1}}break e}finally{f=null,p=z,h=!1}F=void 0}}finally{F?R():C=!1}}}var R;if(typeof S=="function")R=function(){S(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,F){E=b(function(){H(e.unstable_now())},F)}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"):j=0<H?Math.floor(1e3/H):5},e.unstable_getCurrentPriorityLevel=function(){return p},e.unstable_next=function(H){switch(p){case 1:case 2:case 3:var F=3;break;default:F=p}var z=p;p=F;try{return H()}finally{p=z}},e.unstable_requestPaint=function(){y=!0},e.unstable_runWithPriority=function(H,F){switch(H){case 1:case 2:case 3:case 4:case 5:break;default:H=3}var z=p;p=H;try{return F()}finally{p=z}},e.unstable_scheduleCallback=function(H,F,z){var q=e.unstable_now();switch(typeof z=="object"&&z!==null?(z=z.delay,z=typeof z=="number"&&0<z?q+z:q):z=q,H){case 1:var M=-1;break;case 2:M=250;break;case 5:M=1073741823;break;case 4:M=1e4;break;default:M=5e3}return M=z+M,H={id:d++,callback:F,priorityLevel:H,startTime:z,expirationTime:M,sortIndex:-1},z>q?(H.sortIndex=z,t(u,H),n(c)===null&&H===n(u)&&(g?(x(E),E=-1):g=!0,B(_,z-q))):(H.sortIndex=M,t(c,H),m||h||(m=!0,C||(C=!0,R()))),H},e.unstable_shouldYield=I,e.unstable_wrapCallback=function(H){var F=p;return function(){var z=p;p=F;try{return H.apply(this,arguments)}finally{p=z}}}})(yK)),yK}var _2e;function fqt(){return _2e||(_2e=1,vK.exports=dqt()),vK.exports}var bK={exports:{}},vu={};var C2e;function pqt(){if(C2e)return vu;C2e=1;var e=DN();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 vu.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,vu.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)},vu.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()}},vu.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))},vu.prefetchDNS=function(c){typeof c=="string"&&r.d.D(c)},vu.preinit=function(c,u){if(typeof c=="string"&&u&&typeof u.as=="string"){var d=u.as,f=l(d,u.crossOrigin),p=typeof u.integrity=="string"?u.integrity:void 0,h=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:p,fetchPriority:h}):d==="script"&&r.d.X(c,{crossOrigin:f,integrity:p,fetchPriority:h,nonce:typeof u.nonce=="string"?u.nonce:void 0})}},vu.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)},vu.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})}},vu.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)},vu.requestFormReset=function(c){r.d.r(c)},vu.unstable_batchedUpdates=function(c,u){return c(u)},vu.useFormState=function(c,u,d){return i.H.useFormState(c,u,d)},vu.useFormStatus=function(){return i.H.useHostTransitionStatus()},vu.version="19.2.7",vu}var E2e;function Xat(){if(E2e)return bK.exports;E2e=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(),bK.exports=pqt(),bK.exports}var j2e;function hqt(){if(j2e)return VA;j2e=1;var e={env:{}};var t=fqt(),n=DN(),r=Xat();function s(w){var O="https://react.dev/errors/"+w;if(1<arguments.length){O+="?args[]="+encodeURIComponent(arguments[1]);for(var T=2;T<arguments.length;T++)O+="&args[]="+encodeURIComponent(arguments[T])}return"Minified React error #"+w+"; visit "+O+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function a(w){return!(!w||w.nodeType!==1&&w.nodeType!==9&&w.nodeType!==11)}function i(w){var O=w,T=w;if(w.alternate)for(;O.return;)O=O.return;else{w=O;do O=w,(O.flags&4098)!==0&&(T=O.return),w=O.return;while(w)}return O.tag===3?T:null}function l(w){if(w.tag===13){var O=w.memoizedState;if(O===null&&(w=w.alternate,w!==null&&(O=w.memoizedState)),O!==null)return O.dehydrated}return null}function c(w){if(w.tag===31){var O=w.memoizedState;if(O===null&&(w=w.alternate,w!==null&&(O=w.memoizedState)),O!==null)return O.dehydrated}return null}function u(w){if(i(w)!==w)throw Error(s(188))}function d(w){var O=w.alternate;if(!O){if(O=i(w),O===null)throw Error(s(188));return O!==w?null:w}for(var T=w,P=O;;){var W=T.return;if(W===null)break;var Q=W.alternate;if(Q===null){if(P=W.return,P!==null){T=P;continue}break}if(W.child===Q.child){for(Q=W.child;Q;){if(Q===T)return u(W),w;if(Q===P)return u(W),O;Q=Q.sibling}throw Error(s(188))}if(T.return!==P.return)T=W,P=Q;else{for(var ie=!1,Se=W.child;Se;){if(Se===T){ie=!0,T=W,P=Q;break}if(Se===P){ie=!0,P=W,T=Q;break}Se=Se.sibling}if(!ie){for(Se=Q.child;Se;){if(Se===T){ie=!0,T=Q,P=W;break}if(Se===P){ie=!0,P=Q,T=W;break}Se=Se.sibling}if(!ie)throw Error(s(189))}}if(T.alternate!==P)throw Error(s(190))}if(T.tag!==3)throw Error(s(188));return T.stateNode.current===T?w:O}function f(w){var O=w.tag;if(O===5||O===26||O===27||O===6)return w;for(w=w.child;w!==null;){if(O=f(w),O!==null)return O;w=w.sibling}return null}var p=Object.assign,h=Symbol.for("react.element"),m=Symbol.for("react.transitional.element"),g=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),b=Symbol.for("react.strict_mode"),x=Symbol.for("react.profiler"),S=Symbol.for("react.consumer"),k=Symbol.for("react.context"),_=Symbol.for("react.forward_ref"),C=Symbol.for("react.suspense"),E=Symbol.for("react.suspense_list"),j=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(w){return w===null||typeof w!="object"?null:(w=R&&w[R]||w["@@iterator"],typeof w=="function"?w:null)}var D=Symbol.for("react.client.reference");function B(w){if(w==null)return null;if(typeof w=="function")return w.$$typeof===D?null:w.displayName||w.name||null;if(typeof w=="string")return w;switch(w){case y:return"Fragment";case x:return"Profiler";case b:return"StrictMode";case C:return"Suspense";case E:return"SuspenseList";case I:return"Activity"}if(typeof w=="object")switch(w.$$typeof){case g:return"Portal";case k:return w.displayName||"Context";case S:return(w._context.displayName||"Context")+".Consumer";case _:var O=w.render;return w=w.displayName,w||(w=O.displayName||O.name||"",w=w!==""?"ForwardRef("+w+")":"ForwardRef"),w;case j:return O=w.displayName||null,O!==null?O:B(w.type)||"Memo";case N:O=w._payload,w=w._init;try{return B(w(O))}catch{}}return null}var H=Array.isArray,F=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,z=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,q={pending:!1,data:null,method:null,action:null},M=[],G=-1;function V(w){return{current:w}}function $(w){0>G||(w.current=M[G],M[G]=null,G--)}function U(w,O){G++,M[G]=w.current,w.current=O}var Z=V(null),K=V(null),te=V(null),ee=V(null);function J(w,O){switch(U(te,O),U(K,w),U(Z,null),O.nodeType){case 9:case 11:w=(w=O.documentElement)&&(w=w.namespaceURI)?VPe(w):0;break;default:if(w=O.tagName,O=O.namespaceURI)O=VPe(O),w=qPe(O,w);else switch(w){case"svg":w=1;break;case"math":w=2;break;default:w=0}}$(Z),U(Z,w)}function ae(){$(Z),$(K),$(te)}function de(w){w.memoizedState!==null&&U(ee,w);var O=Z.current,T=qPe(O,w.type);O!==T&&(U(K,w),U(Z,T))}function Y(w){K.current===w&&($(Z),$(K)),ee.current===w&&($(ee),LA._currentValue=q)}var ne,fe;function oe(w){if(ne===void 0)try{throw Error()}catch(T){var O=T.stack.trim().match(/\n( *(at )?)/);ne=O&&O[1]||"",fe=-1<T.stack.indexOf(`
3
3
  at`)?" (<anonymous>)":-1<T.stack.indexOf("@")?"@unknown:0:0":""}return`
4
4
  `+ne+w+fe}var le=!1;function he(w,O){if(!w||le)return"";le=!0;var T=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var P={DetermineComponentFrameRoot:function(){try{if(O){var jt=function(){throw Error()};if(Object.defineProperty(jt.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(jt,[])}catch(ft){var ot=ft}Reflect.construct(w,[],jt)}else{try{jt.call()}catch(ft){ot=ft}w.call(jt.prototype)}}else{try{throw Error()}catch(ft){ot=ft}(jt=w())&&typeof jt.catch=="function"&&jt.catch(function(){})}}catch(ft){if(ft&&ot&&typeof ft.stack=="string")return[ft.stack,ot.stack]}return[null,null]}};P.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var W=Object.getOwnPropertyDescriptor(P.DetermineComponentFrameRoot,"name");W&&W.configurable&&Object.defineProperty(P.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var Q=P.DetermineComponentFrameRoot(),ie=Q[0],Se=Q[1];if(ie&&Se){var Be=ie.split(`
@@ -334,7 +334,7 @@ attempted value: ${i}
334
334
  \${}
335
335
  }
336
336
  }`,{label:"class",detail:"definition",type:"keyword"}),Xd('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),Xd('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],Z0t=kSe.concat([Xd("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),Xd("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),Xd("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),XFe=new Kyt,G0t=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function gR(e){return(t,n)=>{let r=t.node.getChild("VariableDefinition");return r&&n(r,e),!0}}const Y9n=["FunctionDeclaration"],K9n={FunctionDeclaration:gR("function"),ClassDeclaration:gR("class"),ClassExpression:()=>!0,EnumDeclaration:gR("constant"),TypeAliasDeclaration:gR("type"),NamespaceDeclaration:gR("namespace"),VariableDefinition(e,t){e.matchContext(Y9n)||t(e,"variable")},TypeDefinition(e,t){t(e,"type")},__proto__:null};function Q0t(e,t){let n=XFe.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(La.IncludeAnonymous).iterate(i=>{if(s)s=!1;else if(i.name){let l=K9n[i.name];if(l&&l(i,a)||G0t.has(i.name))return!1}else if(i.to-i.from>8192){for(let l of Q0t(e,i.node))r.push(l);return!1}}),XFe.set(t,r),r}const dB=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,OSe=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function Y0t(e){let t=hi(e.state).resolveInner(e.pos,-1);if(OSe.indexOf(t.name)>-1)return null;let n=t.name=="VariableName"||t.to-t.from<20&&dB.test(e.state.sliceDoc(t.from,t.to));if(!n&&!e.explicit)return null;let r=[];for(let s=t;s;s=s.parent)G0t.has(s.name)&&(r=r.concat(Q0t(e.state.doc,s)));return{options:r,from:n?t.from:e.pos,validFor:dB}}function VJ(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 K0t(e){let t=r=>e.state.doc.sliceString(r.from,r.to),n=hi(e.state).resolveInner(e.pos,-1);return n.name=="PropertyName"?VJ(t,n.parent,t(n)):(n.name=="."||n.name=="?.")&&n.parent.name=="MemberExpression"?VJ(t,n.parent,""):OSe.indexOf(n.name)>-1?null:n.name=="VariableName"||n.to-n.from<20&&dB.test(t(n))?{path:[],name:t(n)}:n.name=="MemberExpression"?VJ(t,n,""):e.explicit?{path:[],name:""}:null}function X9n(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 J9n(e){let t=new Map;return n=>{let r=K0t(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=X9n(s,!r.path.length)),{from:n.pos-r.name.length,options:a,validFor:dB}}}const Qh=MO.define({name:"javascript",parser:Q9n.configure({props:[q_.add({IfStatement:Uj({except:/^\s*({|else\b)/}),TryStatement:Uj({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:Z6n,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:W6n({closing:"}"}),ArrowFunction:e=>e.baseIndent+e.unit,"TemplateString BlockComment":()=>null,"Statement Property":Uj({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}}),H_.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":rSe,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:"$"}}),X0t={test:e=>/^JSX/.test(e.name),facet:xH({commentTokens:{block:{open:"{/*",close:"*/}"}}})},_Se=Qh.configure({dialect:"ts"},"typescript"),CSe=Qh.configure({dialect:"jsx",props:[eSe.add(e=>e.isTop?[X0t]:void 0)]}),ESe=Qh.configure({dialect:"jsx ts",props:[eSe.add(e=>e.isTop?[X0t]:void 0)]},"typescript");let J0t=e=>({label:e,type:"keyword"});const ewt="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(J0t),e7n=ewt.concat(["declare","implements","private","protected","public"].map(J0t));function fB(e={}){let t=e.jsx?e.typescript?ESe:CSe:e.typescript?_Se:Qh,n=e.typescript?Z0t.concat(e7n):kSe.concat(ewt);return new LO(t,[Qh.data.of({autocomplete:AFn(OSe,Xxt(n))}),Qh.data.of({autocomplete:Y0t}),e.jsx?twt:[]])}function t7n(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 JFe(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 n7n=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),twt=Nt.inputHandler.of((e,t,n,r,s)=>{if((n7n?e.composing:e.compositionStarted)||e.state.readOnly||t!=n||r!=">"&&r!="/"||!Qh.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:i}=a,l=i.changeByRange(c=>{var u;let{head:d}=c,f=hi(i).resolveInner(d-1,-1),p;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 h=f.parent,m=h.parent;if(m&&h.from==d-2&&((p=JFe(i.doc,m.firstChild,d))||((u=m.firstChild)===null||u===void 0?void 0:u.name)=="JSXFragmentTag")){let g=`${p}>`;return{range:gt.cursor(d+g.length,-1),changes:{from:d,insert:g}}}}else if(r==">"){let h=t7n(f);if(h&&h.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(i.doc.sliceString(d,d+2))&&(p=JFe(i.doc,h,d)))return{range:c,changes:{from:d,insert:`</${p}>`}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,i.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)});function r7n(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 Qh.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(s7n(u,r.doc,c))}return s}}function eze(e,t,n,r){return n.line(e+r.line).from+t+(e==1?r.col-1:-1)}function s7n(e,t,n){let r=eze(e.line,e.column,t,n),s={from:r,to:e.endLine!=null&&e.endColumn!=1?eze(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 G6=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:twt,completionPath:K0t,esLint:r7n,javascript:fB,javascriptLanguage:Qh,jsxLanguage:CSe,localCompletionSource:Y0t,scopeCompletionSource:J9n,snippets:kSe,tsxLanguage:ESe,typescriptLanguage:_Se,typescriptSnippets:Z0t},Symbol.toStringTag,{value:"Module"})),vR=["_blank","_self","_top","_parent"],qJ=["ascii","utf-8","utf-16","latin1","latin1"],HJ=["get","post","put","delete"],WJ=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],tp=["true","false"],er={},a7n={a:{attrs:{href:null,ping:null,type:null,media:null,target:vR,hreflang:null}},abbr:er,address:er,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:er,aside:er,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:er,base:{attrs:{href:null,target:vR}},bdi:er,bdo:er,blockquote:{attrs:{cite:null}},body:er,br:er,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:WJ,formmethod:HJ,formnovalidate:["novalidate"],formtarget:vR,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:er,center:er,cite:er,code:er,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:er,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:er,div:er,dl:er,dt:er,em:er,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:er,figure:er,footer:er,form:{attrs:{action:null,name:null,"accept-charset":qJ,autocomplete:["on","off"],enctype:WJ,method:HJ,novalidate:["novalidate"],target:vR}},h1:er,h2:er,h3:er,h4:er,h5:er,h6:er,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:er,hgroup:er,hr:er,html:{attrs:{manifest:null}},i:er,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:WJ,formmethod:HJ,formnovalidate:["novalidate"],formtarget:vR,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:er,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:er,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:er,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:qJ,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:er,noscript:er,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:er,param:{attrs:{name:null,value:null}},pre:er,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:er,rt:er,ruby:er,samp:er,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:qJ}},section:er,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:er,source:{attrs:{src:null,type:null,media:null}},span:er,strong:er,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:er,summary:er,sup:er,table:er,tbody:er,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:er,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:er,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:er,time:{attrs:{datetime:null}},title:er,tr:er,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:er,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:er},nwt={accesskey:null,class:null,contenteditable:tp,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:tp,autocorrect:tp,autocapitalize:tp,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":tp,"aria-autocomplete":["inline","list","both","none"],"aria-busy":tp,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":tp,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":tp,"aria-hidden":tp,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":tp,"aria-multiselectable":tp,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":tp,"aria-relevant":null,"aria-required":tp,"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},rwt="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 rwt)nwt[e]=null;class bM{constructor(t,n){this.tags={...a7n,...t},this.globalAttrs={...nwt,...n},this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}}bM.default=new bM;function FT(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 zT(e,t=!1){for(;e;e=e.parent)if(e.name=="Element")if(t)t=!1;else return e;return null}function swt(e,t,n){let r=n.tags[FT(e,zT(t))];return r?.children||n.allTags}function jSe(e,t){let n=[];for(let r=zT(t);r&&!r.type.isTop;r=zT(r.parent)){let s=FT(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 awt=/^[:\-\.\w\u00b7-\uffff]*$/;function tze(e,t,n,r,s){let a=/\s*>/.test(e.sliceDoc(s,s+5))?"":">",i=zT(n,n.name=="StartTag"||n.name=="TagName");return{from:r,to:s,options:swt(e.doc,i,t).map(l=>({label:l,type:"type"})).concat(jSe(e.doc,n).map((l,c)=>({label:"/"+l,apply:"/"+l+a,type:"type",boost:99-c}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function nze(e,t,n,r){let s=/\s*>/.test(e.sliceDoc(r,r+5))?"":">";return{from:n,to:r,options:jSe(e.doc,t).map((a,i)=>({label:a,apply:a+s,type:"type",boost:99-i})),validFor:awt}}function i7n(e,t,n,r){let s=[],a=0;for(let i of swt(e.doc,n,t))s.push({label:"<"+i,type:"type"});for(let i of jSe(e.doc,n))s.push({label:"</"+i+">",type:"type",boost:99-a++});return{from:r,to:r,options:s,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function o7n(e,t,n,r,s){let a=zT(n),i=a?t.tags[FT(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:awt}}function l7n(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=zT(n),p=f?t.tags[FT(e.doc,f)]:null;d=p?.attrs&&p.attrs[u]}if(d){let f=e.sliceDoc(r,s).toLowerCase(),p='"',h='"';/^['"]/.test(f)?(c=f[0]=='"'?/^[^"]*$/:/^[^']*$/,p="",h=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:p+m+h,type:"constant"})}}return{from:r,to:s,options:l,validFor:c}}function iwt(e,t){let{state:n,pos:r}=t,s=hi(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)?nze(n,s,s.from,r):tze(n,e,s,s.from,r):s.name=="StartTag"||s.name=="IncompleteTag"?tze(n,e,s,r,r):s.name=="StartCloseTag"||s.name=="IncompleteCloseTag"?nze(n,s,r,r):s.name=="OpenTag"||s.name=="SelfClosingTag"||s.name=="AttributeName"?o7n(n,e,s,s.name=="AttributeName"?s.from:r,r):s.name=="Is"||s.name=="AttributeValue"||s.name=="UnquotedAttributeValue"?l7n(n,e,s,s.name=="Is"?r:s.from,r):t.explicit&&(a.name=="Element"||a.name=="Text"||a.name=="Document")?i7n(n,e,s,r):null}function c7n(e){return iwt(bM.default,e)}function u7n(e){let{extraTags:t,extraGlobalAttributes:n}=e,r=n||t?new bM(t,n):bM.default;return s=>iwt(r,s)}const d7n=Qh.parser.configure({top:"SingleExpression"}),owt=[{tag:"script",attrs:e=>e.type=="text/typescript"||e.lang=="ts",parser:_Se.parser},{tag:"script",attrs:e=>e.type=="text/babel"||e.type=="text/jsx",parser:CSe.parser},{tag:"script",attrs:e=>e.type=="text/typescript-jsx",parser:ESe.parser},{tag:"script",attrs(e){return/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(e.type)},parser:d7n},{tag:"script",attrs(e){return!e.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(e.type)},parser:Qh.parser},{tag:"style",attrs(e){return(!e.lang||e.lang=="css")&&(!e.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(e.type))},parser:uB.parser}],lwt=[{name:"style",parser:uB.parser.configure({top:"Styles"})}].concat(rwt.map(e=>({name:e,parser:Qh.parser}))),cwt=MO.define({name:"html",parser:M8n.configure({props:[q_.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}}),H_.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}}}),Hxt.add({"OpenTag CloseTag":e=>e.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:"<!--",close:"-->"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-_"}}),j8=cwt.configure({wrap:z0t(owt,lwt)});function f7n(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=z0t((e.nestedLanguages||[]).concat(owt),(e.nestedAttributes||[]).concat(lwt)));let r=n?cwt.configure({wrap:n,dialect:t}):t?j8.configure({dialect:t}):j8;return new LO(r,[j8.data.of({autocomplete:u7n(e)}),e.autoCloseTags!==!1?p7n:[],fB().support,y9n().support])}const rze=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" ")),p7n=Nt.inputHandler.of((e,t,n,r,s)=>{if(e.composing||e.state.readOnly||t!=n||r!=">"&&r!="/"||!j8.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:i}=a,l=i.changeByRange(c=>{var u,d,f;let p=i.doc.sliceString(c.from-1,c.to)==r,{head:h}=c,m=hi(i).resolveInner(h,-1),g;if(p&&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"&&(g=FT(i.doc,y.parent,h))&&!rze.has(g)){let b=h+(i.doc.sliceString(h,h+1)===">"?1:0),x=`</${g}>`;return{range:c,changes:{from:h,to:b,insert:x}}}}else if(p&&r=="/"&&m.name=="IncompleteCloseTag"){let y=m.parent;if(m.from==h-2&&((f=y.lastChild)===null||f===void 0?void 0:f.name)!="CloseTag"&&(g=FT(i.doc,y,h))&&!rze.has(g)){let b=h+(i.doc.sliceString(h,h+1)===">"?1:0),x=`${g}>`;return{range:gt.cursor(h+x.length,-1),changes:{from:h,to:b,insert:x}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,i.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),uwt=xH({commentTokens:{block:{open:"<!--",close:"-->"}}}),dwt=new Dr,fwt=Lzn.configure({props:[H_.add(e=>!e.is("Block")||e.is("Document")||Bme(e)!=null||h7n(e)?void 0:(t,n)=>({from:n.doc.lineAt(t.from).to,to:t.to})),dwt.add(Bme),q_.add({Document:()=>null}),xw.add({Document:uwt})]});function Bme(e){let t=/^(?:ATX|Setext)Heading(\d)$/.exec(e.name);return t?+t[1]:void 0}function h7n(e){return e.name=="OrderedList"||e.name=="BulletList"}function m7n(e,t){let n=e;for(;;){let r=n.nextSibling,s;if(!r||(s=Bme(r.type))!=null&&s<=t)break;n=r}return n.to}const g7n=Rxt.of((e,t,n)=>{for(let r=hi(e).resolveInner(n,-1);r&&!(r.from<t);r=r.parent){let s=r.type.prop(dwt);if(s==null)continue;let a=m7n(r,s);if(a>n)return{from:n,to:a}}return null});function TSe(e){return new _p(uwt,e,[],"markdown")}const pwt=TSe(fwt),v7n=fwt.configure([Qzn,Kzn,Yzn,Xzn,{props:[H_.add({Table:(e,t)=>({from:t.doc.lineAt(e.from).to,to:e.to})})]}]),BO=TSe(v7n);function y7n(e,t){return n=>{if(n&&e){let r=null;if(n=/\S*/.exec(n)[0],typeof e=="function"?r=e(n):r=ng.matchLanguageName(e,n,!0),r instanceof ng)return r.support?r.support.language.parser:DO.getSkippingParser(r.load());if(r)return r.parser}return t?t.parser:null}}class ZJ{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(+mwt(this.item,t)[2]+n):"";return this.spaceBefore+r+this.type+this.spaceAfter}}function hwt(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 ZJ(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 ZJ(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 ZJ(a.parent,c,c+d,i[1],u,f,a))}}return r}function mwt(e,t){return/^(\s*)(\d+)(?=[.)])/.exec(t.sliceString(e.from,e.from+10))}function GJ(e,t,n,r=0){for(let s=-1,a=e;;){if(a.name=="ListItem"){let l=mwt(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 NSe(e,t){let n=/^[ \t]*/.exec(e)[0].length;if(!n||t.facet(oI)!=" ")return e;let r=Pg(e,4,n),s="";for(let a=r;a>0;)a>=4?(s+=" ",a-=4):(s+=" ",a--);return s+e.slice(n)}const gwt=(e={})=>({state:t,dispatch:n})=>{let r=hi(t),{doc:s}=t,a=null,i=t.changeByRange(l=>{if(!l.empty||!BO.isActiveAt(t,l.from,-1)&&!BO.isActiveAt(t,l.from,1))return a={range:l};let c=l.from,u=s.lineAt(c),d=hwt(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 p=c>=f.to-f.spaceAfter.length&&!/\S/.test(u.text.slice(f.to));if(f.item&&p){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 S=d.length>1?d[d.length-2]:null,k,_="";S&&S.item?(k=u.from+S.from,_=S.marker(s,1)):k=u.from+(S?S.to:0);let C=[{from:k,to:c,insert:_}];return f.node.name=="OrderedList"&&GJ(f.item,s,C,-2),S&&S.node.name=="OrderedList"&&GJ(S.item,s,C),{range:gt.cursor(k+_.length),changes:C}}else{let S=aze(d,t,u);return{range:gt.cursor(c+S.length+1),changes:{from:u.from,insert:S+t.lineBreak}}}}if(f.node.name=="Blockquote"&&p&&u.from){let b=s.lineAt(u.from-1),x=/>\s*$/.exec(b.text);if(x&&x.index==f.from){let S=t.changes([{from:b.from+x.index,to:b.to},{from:u.from+f.from,to:u.to}]);return{range:l.map(S),changes:S}}}let h=[];f.node.name=="OrderedList"&&GJ(f.item,s,h);let m=f.item&&f.item.from<u.from,g="";if(!m||/^[\s\d.)\-+*>]*/.exec(u.text)[0].length>=f.to)for(let b=0,x=d.length-1;b<=x;b++)g+=b==x&&!m?d[b].marker(s,1):d[b].blank(b<x?Pg(u.text,4,d[b+1].from)-g.length:null);let y=c;for(;y>u.from&&/\s/.test(u.text.charAt(y-u.from-1));)y--;return g=NSe(g,t),b7n(f.node,t.doc)&&(g=aze(d,t,u)+t.lineBreak+g),h.push({from:y,to:c,insert:t.lineBreak+g}),{range:gt.cursor(y+g.length+1),changes:h}});return a?!1:(n(t.update(i,{scrollIntoView:!0,userEvent:"input"})),!0)},vwt=gwt();function sze(e){return e.name=="QuoteMark"||e.name=="ListMark"}function b7n(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 aze(e,t,n){let r="";for(let s=0,a=e.length-2;s<=a;s++)r+=e[s].blank(s<a?Pg(n.text,4,e[s+1].from)-r.length:null,s<a);return NSe(r,t)}function x7n(e,t){let n=e.resolveInner(t,-1),r=t;sze(n)&&(r=n.from,n=n.parent);for(let s;s=n.childBefore(r);)if(sze(s))r=s.from;else if(s.name=="OrderedList"||s.name=="BulletList")n=s.lastChild,r=n.to;else break;return n}const ywt=({state:e,dispatch:t})=>{let n=hi(e),r=null,s=e.changeByRange(a=>{let i=a.from,{doc:l}=e;if(a.empty&&BO.isActiveAt(e,a.from)){let c=l.lineAt(i),u=hwt(x7n(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:gt.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 p=c.from+d.from;if(d.item&&d.node.from<d.item.from&&/\S/.test(c.text.slice(d.from,d.to))){let h=d.blank(Pg(c.text,4,d.to)-Pg(c.text,4,d.from));return p==c.from&&(h=NSe(h,e)),{range:gt.cursor(p+h.length),changes:{from:p,to:c.from+d.to,insert:h}}}if(p<i)return{range:gt.cursor(p),changes:{from:p,to:i}}}}}return r={range:a}});return r?!1:(t(e.update(s,{scrollIntoView:!0,userEvent:"delete"})),!0)},bwt=[{key:"Enter",run:vwt},{key:"Backspace",run:ywt}],xwt=f7n({matchClosingTags:!1});function ISe(e={}){let{codeLanguages:t,defaultCodeLanguage:n,addKeymap:r=!0,base:{parser:s}=pwt,completeHTMLTags:a=!0,pasteURLAsLink:i=!0,htmlTagLanguage:l=xwt}=e;if(!(s instanceof OH))throw new RangeError("Base parser provided to `markdown` should be a Markdown parser");let c=e.extensions?[e.extensions]:[],u=[l.support,g7n],d;i&&u.push(wwt),n instanceof LO?(u.push(n.support),d=n.language):n&&(d=n);let f=t||d?y7n(t,d):void 0;c.push(zzn({codeParser:f,htmlParser:l.language.parser})),r&&u.push(Xp.high(iI.of(bwt)));let p=TSe(s.configure(c));return a&&u.push(p.data.of({autocomplete:w7n})),new LO(p,u)}function w7n(e){let{state:t,pos:n}=e,r=/<[:\-\.\w\u00b7-\uffff]*$/.exec(t.sliceDoc(n-25,n));if(!r)return null;let s=hi(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:S7n(),validFor:/^<[:\-\.\w\u00b7-\uffff]*$/}}let QJ=null;function S7n(){if(QJ)return QJ;let e=c7n(new oSe(cs.create({extensions:xwt}),0,!0));return QJ=e?e.options:[]}const k7n=/code|horizontalrule|html|link|comment|processing|escape|entity|image|mark|url/i,wwt=Nt.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),!BO.isActiveAt(t.state,r.from,1)))return!1;let a=hi(t.state),i=!1;return a.iterate({from:r.from,to:r.to,enter:l=>{(l.from>r.from||k7n.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)}}),O7n=Object.freeze(Object.defineProperty({__proto__:null,commonmarkLanguage:pwt,deleteMarkupBackward:ywt,insertNewlineContinueMarkup:vwt,insertNewlineContinueMarkupCommand:gwt,markdown:ISe,markdownKeymap:bwt,markdownLanguage:BO,pasteURLAsLink:wwt},Symbol.toStringTag,{value:"Module"}));function UO(){return UO=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},UO.apply(null,arguments)}var _7n=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=Nt.theme(i,{dark:t==="dark"}),d=Ug.define(a),f=[u,U1(d)];return f},C7n={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)"},E7n=[{tag:pe.comment,color:"#6272a4"},{tag:pe.string,color:"#f1fa8c"},{tag:pe.atom,color:"#bd93f9"},{tag:pe.meta,color:"#f8f8f2"},{tag:[pe.keyword,pe.operator,pe.tagName],color:"#ff79c6"},{tag:[pe.function(pe.propertyName),pe.propertyName],color:"#66d9ef"},{tag:[pe.definition(pe.variableName),pe.function(pe.variableName),pe.className,pe.attributeName],color:"#50fa7b"},{tag:pe.atom,color:"#bd93f9"}],cI=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 _7n({theme:r,settings:UO({},C7n,a),styles:[...E7n,...l]})};cI();function Swt(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 j7n=e=>{let{state:t}=e,n=t.doc.lineAt(t.selection.main.from),r=RSe(e.state,n.from);return r.line?T7n(e):r.block?I7n(e):!1};function ASe(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 T7n=ASe(P7n,0),N7n=ASe(kwt,0),I7n=ASe((e,t)=>kwt(e,t,R7n(t)),0);function RSe(e,t){let n=e.languageDataAt("commentTokens",t,1);return n.length?n[0]:{}}const yR=50;function A7n(e,{open:t,close:n},r,s){let a=e.sliceDoc(r-yR,r),i=e.sliceDoc(s,s+yR),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*yR?d=f=e.sliceDoc(r,s):(d=e.sliceDoc(r,r+yR),f=e.sliceDoc(s-yR,s));let p=/^\s*/.exec(d)[0].length,h=/\s*$/.exec(f)[0].length,m=f.length-h-n.length;return d.slice(p,p+t.length)==t&&f.slice(m,m+n.length)==n?{open:{pos:r+p+t.length,margin:/\s/.test(d.charAt(p+t.length))?1:0},close:{pos:s-h-n.length,margin:/\s/.test(f.charAt(m-1))?1:0}}:null}function R7n(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 kwt(e,t,n=t.selection.ranges){let r=n.map(a=>RSe(t,a.from).block);if(!r.every(a=>a))return null;let s=n.map((a,i)=>A7n(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 P7n(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=RSe(t,f.from).line,!u))continue e;if(f.from>s&&(a==i||i>f.from)){s=f.from;let p=/^\s*/.exec(f.text)[0].length,h=p==f.length,m=f.text.slice(p,p+u.length)==u?p:-1;p<f.text.length&&p<c&&(c=p),r.push({line:f,comment:m,token:u,indent:p,empty:h,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 Ume=Ly.define(),$7n=Ly.define(),M7n=On.define(),Owt=On.define({combine(e){return Fy(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)})}}),_wt=wl.define({create(){return qv.empty},update(e,t){let n=t.state.facet(Owt),r=t.annotation(Ume);if(r){let c=ff.fromTransaction(t,r.selection),u=r.side,d=u==0?e.undone:e.done;return c?d=pB(d,d.length,n.minDepth,c):d=jwt(d,t.startState.selection),new qv(u==0?r.rest:d,u==0?d:r.rest)}let s=t.annotation($7n);if((s=="full"||s=="before")&&(e=e.isolate()),t.annotation(Pl.addToHistory)===!1)return t.changes.empty?e:e.addMapping(t.changes.desc);let a=ff.fromTransaction(t),i=t.annotation(Pl.time),l=t.annotation(Pl.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 qv(e.done.map(ff.fromJSON),e.undone.map(ff.fromJSON))}});function D7n(e={}){return[_wt,Owt.of(e),Nt.domEventHandlers({beforeinput(t,n){let r=t.inputType=="historyUndo"?Cwt:t.inputType=="historyRedo"?Vme:null;return r?(t.preventDefault(),r(n)):!1}})]}function _H(e,t){return function({state:n,dispatch:r}){if(!t&&n.readOnly)return!1;let s=n.field(_wt,!1);if(!s)return!1;let a=s.pop(e,n,t);return a?(r(a),!0):!1}}const Cwt=_H(0,!1),Vme=_H(1,!1),L7n=_H(0,!0),F7n=_H(1,!0);class ff{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 ff(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 ff(t.changes&&Al.fromJSON(t.changes),[],t.mapped&&ny.fromJSON(t.mapped),t.startSelection&&gt.fromJSON(t.startSelection),t.selectionsAfter.map(gt.fromJSON))}static fromTransaction(t,n){let r=zh;for(let s of t.startState.facet(M7n)){let a=s(t);a.length&&(r=r.concat(a))}return!r.length&&t.changes.empty?null:new ff(t.changes.invert(t.startState.doc),r,void 0,n||t.startState.selection,zh)}static selection(t){return new ff(void 0,zh,void 0,void 0,t)}}function pB(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 z7n(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 B7n(e,t){return e.ranges.length==t.ranges.length&&e.ranges.filter((n,r)=>n.empty!=t.ranges[r].empty).length===0}function Ewt(e,t){return e.length?t.length?e.concat(t):e:t}const zh=[],U7n=200;function jwt(e,t){if(e.length){let n=e[e.length-1],r=n.selectionsAfter.slice(Math.max(0,n.selectionsAfter.length-U7n));return r.length&&r[r.length-1].eq(t)?e:(r.push(t),pB(e,e.length-1,1e9,n.setSelAfter(r)))}else return[ff.selection([t])]}function V7n(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 YJ(e,t){if(!e.length)return e;let n=e.length,r=zh;for(;n;){let s=q7n(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?[ff.selection(r)]:zh}function q7n(e,t,n){let r=Ewt(e.selectionsAfter.length?e.selectionsAfter.map(l=>l.map(t)):zh,n);if(!e.changes)return ff.selection(r);let s=e.changes.map(t),a=t.mapDesc(e.changes,!0),i=e.mapped?e.mapped.composeDesc(a):a;return new ff(s,vr.mapEffects(e.effects,t),i,e.startSelection.map(a),r)}const H7n=/^(input\.type|delete)($|\.)/;class qv{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 qv(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||H7n.test(r))&&(!l.selectionsAfter.length&&n-this.prevTime<s.newGroupDelay&&s.joinToEvent(a,z7n(l.changes,t.changes))||r=="input.type.compose")?i=pB(i,i.length-1,s.minDepth,new ff(t.changes.compose(l.changes),Ewt(vr.mapEffects(t.effects,l.changes),l.effects),l.mapped,l.startSelection,zh)):i=pB(i,i.length,s.minDepth,t),new qv(i,zh,n,r)}addSelection(t,n,r,s){let a=this.done.length?this.done[this.done.length-1].selectionsAfter:zh;return a.length>0&&n-this.prevTime<s&&r==this.prevUserEvent&&r&&/^select($|\.)/.test(r)&&B7n(a[a.length-1],t)?this:new qv(jwt(this.done,t),this.undone,n,r)}addMapping(t){return new qv(YJ(this.done,t),YJ(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:Ume.of({side:t,rest:V7n(s),selection:i}),userEvent:t==0?"select.undo":"select.redo",scrollIntoView:!0});if(a.changes){let l=s.length==1?zh:s.slice(0,s.length-1);return a.mapped&&(l=YJ(l,a.mapped)),n.update({changes:a.changes,selection:a.startSelection,effects:a.effects,annotations:Ume.of({side:t,rest:l,selection:i}),filter:!1,userEvent:t==0?"undo":"redo",scrollIntoView:!0})}else return null}}qv.empty=new qv(zh,zh);const W7n=[{key:"Mod-z",run:Cwt,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:Vme,preventDefault:!0},{linux:"Ctrl-Shift-z",run:Vme,preventDefault:!0},{key:"Mod-u",run:L7n,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:F7n,preventDefault:!0}];function uI(e,t){return gt.create(e.ranges.map(t),e.mainIndex)}function Vg(e,t){return e.update({selection:t,scrollIntoView:!0,userEvent:"select"})}function qg({state:e,dispatch:t},n){let r=uI(e.selection,n);return r.eq(e.selection,!0)?!1:(t(Vg(e,r)),!0)}function CH(e,t){return gt.cursor(t?e.to:e.from)}function Twt(e,t){return qg(e,n=>n.empty?e.moveByChar(n,t):CH(n,t))}function Ju(e){return e.textDirectionAt(e.state.selection.main.head)==Oi.LTR}const Nwt=e=>Twt(e,!Ju(e)),Iwt=e=>Twt(e,Ju(e));function Awt(e,t){return qg(e,n=>n.empty?e.moveByGroup(n,t):CH(n,t))}const Z7n=e=>Awt(e,!Ju(e)),G7n=e=>Awt(e,Ju(e));function Q7n(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 EH(e,t,n){let r=hi(e).resolveInner(t.head),s=n?Dr.closedBy:Dr.openedBy;for(let c=t.head;;){let u=n?r.childAfter(c):r.childBefore(c);if(!u)break;Q7n(e,u,s)?r=u:c=n?u.to:u.from}let a=r.type.prop(s),i,l;return a&&(i=n?Vv(e,r.from,1):Vv(e,r.to,-1))&&i.matched?l=n?i.end.to:i.end.from:l=n?r.to:r.from,gt.cursor(l,n?-1:1)}const Y7n=e=>qg(e,t=>EH(e.state,t,!Ju(e))),K7n=e=>qg(e,t=>EH(e.state,t,Ju(e)));function Rwt(e,t){return qg(e,n=>{if(!n.empty)return CH(n,t);let r=e.moveVertically(n,t);return r.head!=n.head?r:e.moveToLineBoundary(n,t)})}const Pwt=e=>Rwt(e,!1),$wt=e=>Rwt(e,!0);function Mwt(e){let t=e.scrollDOM.clientHeight<e.scrollDOM.scrollHeight-2,n=0,r=0,s;if(t){for(let a of e.state.facet(Nt.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 Dwt(e,t){let n=Mwt(e),{state:r}=e,s=uI(r.selection,i=>i.empty?e.moveVertically(i,t,n.height):CH(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=Nt.scrollIntoView(s.main.head,{y:"start",yMargin:i.top-c}))}return e.dispatch(Vg(r,s),{effects:a}),!0}const ize=e=>Dwt(e,!1),qme=e=>Dwt(e,!0);function V1(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=gt.cursor(r.from+a))}return s}const X7n=e=>qg(e,t=>V1(e,t,!0)),J7n=e=>qg(e,t=>V1(e,t,!1)),eBn=e=>qg(e,t=>V1(e,t,!Ju(e))),tBn=e=>qg(e,t=>V1(e,t,Ju(e))),nBn=e=>qg(e,t=>gt.cursor(e.lineBlockAt(t.head).from,1)),rBn=e=>qg(e,t=>gt.cursor(e.lineBlockAt(t.head).to,-1));function sBn(e,t,n){let r=!1,s=uI(e.selection,a=>{let i=Vv(e,a.head,-1)||Vv(e,a.head,1)||a.head>0&&Vv(e,a.head-1,1)||a.head<e.doc.length&&Vv(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 gt.cursor(l)});return r?(t(Vg(e,s)),!0):!1}const aBn=({state:e,dispatch:t})=>sBn(e,t);function Om(e,t,n){let r=uI(e.state.selection,s=>{s.undirectional&&s.head>=s.anchor!=t&&(s=gt.range(s.head,s.anchor));let a=n(s);return gt.range(s.anchor,a.head,a.goalColumn,a.bidiLevel||void 0,a.assoc)});return r.eq(e.state.selection)?!1:(e.dispatch(Vg(e.state,r)),!0)}function Lwt(e,t){return Om(e,t,n=>e.moveByChar(n,t))}const Fwt=e=>Lwt(e,!Ju(e)),zwt=e=>Lwt(e,Ju(e));function Bwt(e,t){return Om(e,t,n=>e.moveByGroup(n,t))}const iBn=e=>Bwt(e,!Ju(e)),oBn=e=>Bwt(e,Ju(e)),lBn=e=>{let t=!Ju(e);return Om(e,t,n=>EH(e.state,n,t))},cBn=e=>{let t=Ju(e);return Om(e,t,n=>EH(e.state,n,t))};function Uwt(e,t){return Om(e,t,n=>e.moveVertically(n,t))}const Vwt=e=>Uwt(e,!1),qwt=e=>Uwt(e,!0);function Hwt(e,t){return Om(e,t,n=>e.moveVertically(n,t,Mwt(e).height))}const oze=e=>Hwt(e,!1),lze=e=>Hwt(e,!0),uBn=e=>Om(e,!0,t=>V1(e,t,!0)),dBn=e=>Om(e,!1,t=>V1(e,t,!1)),fBn=e=>{let t=!Ju(e);return Om(e,t,n=>V1(e,n,t))},pBn=e=>{let t=Ju(e);return Om(e,t,n=>V1(e,n,t))},hBn=e=>Om(e,!1,t=>gt.cursor(e.lineBlockAt(t.head).from)),mBn=e=>Om(e,!0,t=>gt.cursor(e.lineBlockAt(t.head).to)),cze=({state:e,dispatch:t})=>(t(Vg(e,{anchor:0})),!0),uze=({state:e,dispatch:t})=>(t(Vg(e,{anchor:e.doc.length})),!0),dze=({state:e,dispatch:t})=>(t(Vg(e,{anchor:e.selection.main.anchor,head:0})),!0),fze=({state:e,dispatch:t})=>(t(Vg(e,{anchor:e.selection.main.anchor,head:e.doc.length})),!0),gBn=({state:e,dispatch:t})=>(t(e.update({selection:{anchor:0,head:e.doc.length},userEvent:"select"})),!0),vBn=({state:e,dispatch:t})=>{let n=jH(e).map(({from:r,to:s})=>gt.range(r,Math.min(s+1,e.doc.length)));return t(e.update({selection:gt.create(n),userEvent:"select"})),!0},yBn=({state:e,dispatch:t})=>{let n=uI(e.selection,r=>{let s=hi(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 gt.range(l.to,l.from)}return r});return n.eq(e.selection)?!1:(t(Vg(e,n)),!0)};function Wwt(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(Vg(n,gt.create(s,s.length-1))),!0)}const bBn=e=>Wwt(e,!1),xBn=e=>Wwt(e,!0),wBn=({state:e,dispatch:t})=>{let n=e.selection,r=null;return n.ranges.length>1?r=gt.create([n.main]):n.main.empty||(r=gt.create([gt.cursor(n.main.head)])),r?(t(Vg(e,r)),!0):!1};function P3(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=Q6(e,c,!1)):c>i&&(n="delete.forward",c=Q6(e,c,!0)),i=Math.min(i,c),l=Math.max(l,c)}else i=Q6(e,i,!1),l=Q6(e,l,!0);return i==l?{range:a}:{changes:{from:i,to:l},range:gt.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"?Nt.announce.of(r.phrase("Selection deleted")):void 0})),!0)}function Q6(e,t,n){if(e instanceof Nt)for(let r of e.state.facet(Nt.atomicRanges).map(s=>s(e)))r.between(t,t,(s,a)=>{s<t&&a>t&&(t=n?a:s)});return t}const Zwt=(e,t,n)=>P3(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=Pg(l,a.tabSize),d=u%FO(a)||FO(a);for(let f=0;f<d&&l[l.length-1-f]==" ";f++)s--;c=s}else c=kc(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=kc(i.text,c-i.from,!1,!1)+i.from);return c}),Hme=e=>Zwt(e,!1,!0),Gwt=e=>Zwt(e,!0,!1),Qwt=(e,t)=>P3(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=kc(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}),Ywt=e=>Qwt(e,!1),SBn=e=>Qwt(e,!0),kBn=e=>P3(e,t=>{let n=e.lineBlockAt(t.head).to;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),OBn=e=>P3(e,t=>{let n=e.moveToLineBoundary(t,!1).head;return t.head>n?n:Math.max(0,t.head-1)}),_Bn=e=>P3(e,t=>{let n=e.moveToLineBoundary(t,!0).head;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),CBn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(r=>({changes:{from:r.from,to:r.to,insert:wa.of(["",""])},range:gt.cursor(r.from)}));return t(e.update(n,{scrollIntoView:!0,userEvent:"input"})),!0},EBn=({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:kc(a.text,s-a.from,!1)+a.from,l=s==a.to?s+1:kc(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:gt.cursor(l)}});return n.changes.empty?!1:(t(e.update(n,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function jH(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 Kwt(e,t,n){if(e.readOnly)return!1;let r=[],s=[];for(let a of jH(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(gt.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(gt.range(c.anchor-l,c.head-l))}}return r.length?(t(e.update({changes:r,scrollIntoView:!0,selection:gt.create(s,e.selection.mainIndex),userEvent:"move.line"})),!0):!1}const jBn=({state:e,dispatch:t})=>Kwt(e,t,!1),TBn=({state:e,dispatch:t})=>Kwt(e,t,!0);function Xwt(e,t,n){if(e.readOnly)return!1;let r=[];for(let a of jH(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 NBn=({state:e,dispatch:t})=>Xwt(e,t,!1),IBn=({state:e,dispatch:t})=>Xwt(e,t,!0),ABn=e=>{if(e.state.readOnly)return!1;let{state:t}=e,n=t.changes(jH(t).map(({from:s,to:a})=>(s>0?s--:a<t.doc.length&&a++,{from:s,to:a}))),r=uI(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 RBn(e,t){if(/\(\)|\[\]|\{\}/.test(e.sliceDoc(t-1,t+1)))return{from:t,to:t};let n=hi(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(Dr.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 pze=Jwt(!1),PBn=Jwt(!0);function Jwt(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&&RBn(t,a);e&&(a=i=(i<=l.to?l:t.doc.lineAt(i)).to);let u=new wH(t,{simulateBreak:a,simulateDoubleBreak:!!c}),d=tSe(u,a);for(d==null&&(d=Pg(/^\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:wa.of(f)},range:gt.cursor(a+1+f[1].length)}});return n(t.update(r,{scrollIntoView:!0,userEvent:"input"})),!0}}function PSe(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:gt.range(a.mapPos(r.anchor,1),a.mapPos(r.head,1))}})}const $Bn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=Object.create(null),r=new wH(e,{overrideIndentation:a=>{let i=n[a];return i??-1}}),s=PSe(e,(a,i,l)=>{let c=tSe(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},e1t=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(PSe(e,(n,r)=>{r.push({from:n.from,insert:e.facet(oI)})}),{userEvent:"input.indent"})),!0),t1t=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(PSe(e,(n,r)=>{let s=/^\s*/.exec(n.text)[0];if(!s)return;let a=Pg(s,e.tabSize),i=0,l=dM(e,Math.max(0,a-FO(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),MBn=e=>(e.setTabFocusMode(),!0),DBn=[{key:"Ctrl-b",run:Nwt,shift:Fwt,preventDefault:!0},{key:"Ctrl-f",run:Iwt,shift:zwt},{key:"Ctrl-p",run:Pwt,shift:Vwt},{key:"Ctrl-n",run:$wt,shift:qwt},{key:"Ctrl-a",run:nBn,shift:hBn},{key:"Ctrl-e",run:rBn,shift:mBn},{key:"Ctrl-d",run:Gwt},{key:"Ctrl-h",run:Hme},{key:"Ctrl-k",run:kBn},{key:"Ctrl-Alt-h",run:Ywt},{key:"Ctrl-o",run:CBn},{key:"Ctrl-t",run:EBn},{key:"Ctrl-v",run:qme}],LBn=[{key:"ArrowLeft",run:Nwt,shift:Fwt,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:Z7n,shift:iBn,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:eBn,shift:fBn,preventDefault:!0},{key:"ArrowRight",run:Iwt,shift:zwt,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:G7n,shift:oBn,preventDefault:!0},{mac:"Cmd-ArrowRight",run:tBn,shift:pBn,preventDefault:!0},{key:"ArrowUp",run:Pwt,shift:Vwt,preventDefault:!0},{mac:"Cmd-ArrowUp",run:cze,shift:dze},{mac:"Ctrl-ArrowUp",run:ize,shift:oze},{key:"ArrowDown",run:$wt,shift:qwt,preventDefault:!0},{mac:"Cmd-ArrowDown",run:uze,shift:fze},{mac:"Ctrl-ArrowDown",run:qme,shift:lze},{key:"PageUp",run:ize,shift:oze},{key:"PageDown",run:qme,shift:lze},{key:"Home",run:J7n,shift:dBn,preventDefault:!0},{key:"Mod-Home",run:cze,shift:dze},{key:"End",run:X7n,shift:uBn,preventDefault:!0},{key:"Mod-End",run:uze,shift:fze},{key:"Enter",run:pze,shift:pze},{key:"Mod-a",run:gBn},{key:"Backspace",run:Hme,shift:Hme,preventDefault:!0},{key:"Delete",run:Gwt,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:Ywt,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:SBn,preventDefault:!0},{mac:"Mod-Backspace",run:OBn,preventDefault:!0},{mac:"Mod-Delete",run:_Bn,preventDefault:!0}].concat(DBn.map(e=>({mac:e.key,run:e.run,shift:e.shift}))),FBn=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:Y7n,shift:lBn},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:K7n,shift:cBn},{key:"Alt-ArrowUp",run:jBn},{key:"Shift-Alt-ArrowUp",run:NBn},{key:"Alt-ArrowDown",run:TBn},{key:"Shift-Alt-ArrowDown",run:IBn},{key:"Mod-Alt-ArrowUp",run:bBn},{key:"Mod-Alt-ArrowDown",run:xBn},{key:"Escape",run:wBn},{key:"Mod-Enter",run:PBn},{key:"Alt-l",mac:"Ctrl-l",run:vBn},{key:"Mod-i",run:yBn,preventDefault:!0},{key:"Mod-[",run:t1t},{key:"Mod-]",run:e1t},{key:"Mod-Alt-\\",run:$Bn},{key:"Shift-Mod-k",run:ABn},{key:"Shift-Mod-\\",run:aBn},{key:"Mod-/",run:j7n},{key:"Alt-A",run:N7n},{key:"Ctrl-m",mac:"Shift-Alt-m",run:MBn}].concat(LBn),zBn={key:"Tab",run:e1t,shift:t1t},hze=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class Ex{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(hze(l)):hze,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 rf(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=M1e(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=Av(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"&&(Ex.prototype[Symbol.iterator]=function(){return this});const n1t={from:-1,to:-1,match:/.*/.exec(""),precise:!0},$Se="gm"+(/x/.unicode==null?"":"u");class r1t{constructor(t,n,r,s=0,a=t.length){if(this.text=t,this.to=a,this.curLine="",this.done=!1,this.value=n1t,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new s1t(t,n,r,s,a);this.re=new RegExp(n,$Se+(r?.ignoreCase?"i":"")),this.test=r?.test,this.iter=t.iter();let i=t.lineAt(s);this.curLineStart=i.from,this.matchPos=hB(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=hB(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 KJ=new WeakMap;class qj{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let s=KJ.get(t);if(!s||s.from>=r||s.to<=n){let l=new qj(n,t.sliceString(n,r));return KJ.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)),KJ.set(t,new qj(i,a)),new qj(n,a.slice(n-i,r-i))}}class s1t{constructor(t,n,r,s,a){this.text=t,this.to=a,this.done=!1,this.value=n1t,this.matchPos=hB(t,s),this.re=new RegExp(n,$Se+(r?.ignoreCase?"i":"")),this.test=r?.test,this.flat=qj.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=hB(this.text,s+(r==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=qj.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(r1t.prototype[Symbol.iterator]=s1t.prototype[Symbol.iterator]=function(){return this});function BBn(e){try{return new RegExp(e,$Se),!0}catch{return!1}}function hB(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 UBn=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:s}=k6n(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,p=d?+d.slice(1):0,h=u?+u:l.number;if(u&&f){let y=h/100;c&&(y=y*(c=="-"?-1:1)+l.number/t.doc.lines),h=Math.round(t.doc.lines*y)}else u&&c&&(h=h*(c=="-"?-1:1)+l.number);let m=t.doc.line(Math.max(1,Math.min(t.doc.lines,h))),g=gt.cursor(m.from+Math.max(0,Math.min(p,m.length)));e.dispatch({effects:[r,Nt.scrollIntoView(g.from,{y:"center"})],selection:g})}),!0},VBn={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},qBn=On.define({combine(e){return Fy(e,VBn,{highlightWordAroundCursor:(t,n)=>t||n,minSelectionLength:Math.min,maxMatches:Math.min})}});function HBn(e){return[YBn,QBn]}const WBn=jn.mark({class:"cm-selectionMatch"}),ZBn=jn.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function mze(e,t,n,r){return(n==0||e(t.sliceDoc(n-1,n))!=wo.Word)&&(r==t.doc.length||e(t.sliceDoc(r,r+1))!=wo.Word)}function GBn(e,t,n,r){return e(t.sliceDoc(n,n+1))==wo.Word&&e(t.sliceDoc(r-1,r))==wo.Word}const QBn=Co.fromClass(class{constructor(e){this.decorations=this.getDeco(e)}update(e){(e.selectionSet||e.docChanged||e.viewportChanged)&&(this.decorations=this.getDeco(e.view))}getDeco(e){let t=e.state.facet(qBn),{state:n}=e,r=n.selection;if(r.ranges.length>1)return jn.none;let s=r.main,a,i=null;if(s.empty){if(!t.highlightWordAroundCursor)return jn.none;let c=n.wordAt(s.head);if(!c)return jn.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 jn.none;if(t.wholeWords){if(a=n.sliceDoc(s.from,s.to),i=n.charCategorizer(s.head),!(mze(i,n,s.from,s.to)&&GBn(i,n,s.from,s.to)))return jn.none}else if(a=n.sliceDoc(s.from,s.to),!a)return jn.none}let l=[];for(let c of e.visibleRanges){let u=new Ex(n.doc,a,c.from,c.to);for(;!u.next().done;){let{from:d,to:f}=u.value;if((!i||mze(i,n,d,f))&&(s.empty&&d<=s.from&&f>=s.to?l.push(ZBn.range(d,f)):(d>=s.to||f<=s.from)&&l.push(WBn.range(d,f)),l.length>t.maxMatches))return jn.none}}return jn.set(l)}},{decorations:e=>e.decorations}),YBn=Nt.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),KBn=({state:e,dispatch:t})=>{let{selection:n}=e,r=gt.create(n.ranges.map(s=>e.wordAt(s.head)||gt.cursor(s.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function XBn(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 Ex(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(i)return null;l=new Ex(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 JBn=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(a=>a.from===a.to))return KBn({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=XBn(e,r);return s?(t(e.update({selection:e.selection.addRange(gt.range(s.from,s.to),!1),effects:Nt.scrollIntoView(s.to)})),!0):!1},dI=On.define({combine(e){return Fy(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new pUn(t),scrollToMatch:t=>Nt.scrollIntoView(t)})}});class a1t{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||BBn(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"?`
337
- `: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 aUn(this):new nUn(this)}getCursor(t,n=0,r){let s=t.doc?t:cs.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?BE(this,s,n,r):zE(this,s,n,r)}}class i1t{constructor(t){this.spec=t}}function eUn(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 zE(e,t,n,r){let s;return e.wholeWord&&(s=tUn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=eUn(e.test,t,s)),new Ex(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function tUn(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(mB(s,n-a))!=wo.Word||t(gB(s,n-a))!=wo.Word)&&(t(gB(s,r-a))!=wo.Word||t(mB(s,r-a))!=wo.Word))}class nUn extends i1t{constructor(t){super(t)}nextMatch(t,n,r){let s=zE(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=zE(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=zE(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=zE(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=zE(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 rUn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function BE(e,t,n,r){let s;return e.wholeWord&&(s=sUn(t.charCategorizer(t.selection.main.head))),e.test&&(s=rUn(e.test,t,s)),new r1t(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function mB(e,t){return e.slice(kc(e,t,!1),t)}function gB(e,t){return e.slice(t,kc(e,t))}function sUn(e){return(t,n,r)=>!r[0].length||(e(mB(r.input,r.index))!=wo.Word||e(gB(r.input,r.index))!=wo.Word)&&(e(gB(r.input,r.index+r[0].length))!=wo.Word||e(mB(r.input,r.index+r[0].length))!=wo.Word)}class aUn extends i1t{nextMatch(t,n,r){let s=BE(this.spec,t,r,t.doc.length).next();return s.done&&(s=BE(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=BE(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=BE(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=BE(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 xM=vr.define(),MSe=vr.define(),Lw=wl.define({create(e){return new XJ(Wme(e).create(),null)},update(e,t){for(let n of t.effects)n.is(xM)?e=new XJ(n.value.create(),e.panel):n.is(MSe)&&(e=new XJ(e.query,n.value?DSe:null));return e},provide:e=>uM.from(e,t=>t.panel)});class XJ{constructor(t,n){this.query=t,this.panel=n}}const iUn=jn.mark({class:"cm-searchMatch"}),oUn=jn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),lUn=Co.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Lw))}update(e){let t=e.state.field(Lw);(t!=e.startState.field(Lw)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return jn.none;let{view:n}=this,r=new Rd;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(p=>p.from==u&&p.to==d);r.add(u,d,f?oUn:iUn)})}return r.finish()}},{decorations:e=>e.decorations});function $3(e){return t=>{let n=t.state.field(Lw,!1);return n&&n.query.spec.valid?e(t,n):c1t(t)}}const vB=$3((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=gt.single(r.from,r.to),a=e.state.facet(dI);return e.dispatch({selection:s,effects:[LSe(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),l1t(e),!0}),yB=$3((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let a=gt.single(s.from,s.to),i=e.state.facet(dI);return e.dispatch({selection:a,effects:[LSe(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),l1t(e),!0}),cUn=$3((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:gt.create(n.map(r=>gt.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),uUn=({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 Ex(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(i=a.length),a.push(gt.range(l.value.from,l.value.to))}return t(e.update({selection:gt.create(a,i),userEvent:"select.search.matches"})),!0},gze=$3((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(Nt.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=gt.single(i.from,i.to).map(f),d.push(LSe(e,i)),d.push(n.facet(dI).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),dUn=$3((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:Nt.announce.of(r),userEvent:"input.replace.all"}),!0});function DSe(e){return e.state.facet(dI).createPanel(e)}function Wme(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(dI);return new a1t({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 o1t(e){let t=J1e(e,DSe);return t&&t.dom.querySelector("[main-field]")}function l1t(e){let t=o1t(e);t&&t==e.root.activeElement&&t.select()}const c1t=e=>{let t=e.state.field(Lw,!1);if(t&&t.panel){let n=o1t(e);if(n&&n!=e.root.activeElement){let r=Wme(e.state,t.query.spec);r.valid&&e.dispatch({effects:xM.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[MSe.of(!0),t?xM.of(Wme(e.state,t.query.spec)):vr.appendConfig.of(mUn)]});return!0},u1t=e=>{let t=e.state.field(Lw,!1);if(!t||!t.panel)return!1;let n=J1e(e,DSe);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:MSe.of(!1)}),!0},fUn=[{key:"Mod-f",run:c1t,scope:"editor search-panel"},{key:"F3",run:vB,shift:yB,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:vB,shift:yB,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:u1t,scope:"editor search-panel"},{key:"Mod-Shift-l",run:uUn},{key:"Mod-Alt-g",run:UBn},{key:"Mod-d",run:JBn,preventDefault:!0}];class pUn{constructor(t){this.view=t;let n=this.query=t.state.field(Lw).query.spec;this.commit=this.commit.bind(this),this.searchField=ci("input",{value:n.search,placeholder:np(t,"Find"),"aria-label":np(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=ci("input",{value:n.replace,placeholder:np(t,"Replace"),"aria-label":np(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=ci("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=ci("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=ci("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return ci("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=ci("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>vB(t),[np(t,"next")]),r("prev",()=>yB(t),[np(t,"previous")]),r("select",()=>cUn(t),[np(t,"all")]),ci("label",null,[this.caseField,np(t,"match case")]),ci("label",null,[this.reField,np(t,"regexp")]),ci("label",null,[this.wordField,np(t,"by word")]),...t.state.readOnly?[]:[ci("br"),this.replaceField,r("replace",()=>gze(t),[np(t,"replace")]),r("replaceAll",()=>dUn(t),[np(t,"replace all")])],ci("button",{name:"close",onclick:()=>u1t(t),"aria-label":np(t,"close"),type:"button"},["×"])])}commit(){let t=new a1t({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:xM.of(t)}))}keydown(t){R5n(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?yB:vB)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),gze(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(xM)&&!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(dI).top}}function np(e,t){return e.state.phrase(t)}const Y6=30,K6=/[\s\.,:;?!]/;function LSe(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-Y6),i=Math.min(s,n+Y6),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<Y6;c++)if(!K6.test(l[c+1])&&K6.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-Y6;c--)if(!K6.test(l[c-1])&&K6.test(l[c])){l=l.slice(0,c);break}}return Nt.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const hUn=Nt.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"}}),mUn=[Lw,Xp.low(lUn),hUn];class vze{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class bk{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(wM).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new Rd,l=[],c=0;for(let d=0;;){let f=d==a.length?null:a[d];if(!f&&!l.length)break;let p,h;for(l.length?(p=c,h=l.reduce((g,y)=>Math.min(g,y.to),f&&f.from>p?f.from:1e8)):(p=f.from,h=f.to,l.push(f),d++);d<a.length;){let g=a[d];if(g.from==p&&(g.to>g.from||g.to==p))l.push(g),d++,h=Math.min(g.to,h);else{h=Math.min(g.from,h);break}}let m=jUn(l);if(l.some(g=>g.from==g.to||g.from==g.to-1&&r.doc.lineAt(g.from).to==g.from))i.add(p,p,jn.widget({widget:new OUn(m),diagnostics:l.slice()}));else{let g=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(p,h,jn.mark({class:"cm-lintRange cm-lintRange-"+m+g,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>h)}))}c=h;for(let g=0;g<l.length;g++)l[g].to<=c&&l.splice(g--,1)}let u=i.finish();return new bk(u,n,BT(u))}}function BT(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 vze(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new vze(r.from,a,r.diagnostic)}}),r}function gUn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(wM).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(d1t))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function vUn(e,t){return e.field(Cp,!1)?t:t.concat(vr.appendConfig.of(TUn))}const d1t=vr.define(),FSe=vr.define(),f1t=vr.define(),Cp=wl.define({create(){return new bk(jn.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=BT(n,e.selected.diagnostic,a)||BT(n,null,a)}!n.size&&s&&t.state.facet(wM).autoPanel&&(s=null),e=new bk(n,s,r)}for(let n of t.effects)if(n.is(d1t)){let r=t.state.facet(wM).autoPanel?n.value.length?SM.open:null:e.panel;e=bk.init(n.value,r,t.state)}else n.is(FSe)?e=new bk(e.diagnostics,n.value?SM.open:null,e.selected):n.is(f1t)&&(e=new bk(e.diagnostics,e.panel,n.value));return e},provide:e=>[uM.from(e,t=>t.panel),Nt.decorations.from(e,t=>t.diagnostics)]}),yUn=jn.mark({class:"cm-lintRange cm-lintRange-active"});function bUn(e,t,n){let{diagnostics:r}=e.state.field(Cp),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(wM).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:xUn(e,s)}}}:null}function xUn(e,t){return ci("ul",{class:"cm-tooltip-lint"},t.map(n=>h1t(e,n,!1)))}const wUn=e=>{let t=e.state.field(Cp,!1);(!t||!t.panel)&&e.dispatch({effects:vUn(e.state,[FSe.of(!0)])});let n=J1e(e,SM.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},yze=e=>{let t=e.state.field(Cp,!1);return!t||!t.panel?!1:(e.dispatch({effects:FSe.of(!1)}),!0)},SUn=e=>{let t=e.state.field(Cp,!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)},kUn=[{key:"Mod-Shift-m",run:wUn,preventDefault:!0},{key:"F8",run:SUn}],wM=On.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...Fy(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:bze,tooltipFilter:bze,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 bze(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function p1t(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 h1t(e,t,n){var r;let s=n?p1t(t.actions):[];return ci("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},ci("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=h=>{if(h.preventDefault(),l)return;l=!0;let m=BT(e.state.field(Cp).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),ci("u",u.slice(d,d+1)),u.slice(d+1)],p=a.markClass?" "+a.markClass:"";return ci("button",{type:"button",class:"cm-diagnosticAction"+p,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&ci("div",{class:"cm-diagnosticSource"},t.source))}class OUn extends Jp{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return ci("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class xze{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=h1t(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class SM{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)yze(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=p1t(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=BT(this.view.state.field(Cp).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=ci("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=ci("div",{class:"cm-panel-lint"},this.list,ci("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>yze(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Cp).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(Cp),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,p;for(let h=r;h<this.items.length;h++)if(this.items[h].diagnostic==d){f=h;break}f<0?(p=new xze(this.view,d),this.items.splice(r,0,p),s=!0):(p=this.items[f],f>r&&(this.items.splice(r,f-r),s=!0)),n&&p.diagnostic==n.diagnostic?p.dom.hasAttribute("aria-selected")||(p.dom.setAttribute("aria-selected","true"),a=p):p.dom.hasAttribute("aria-selected")&&p.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 xze(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(Cp),r=BT(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:f1t.of(r)})}static open(t){return new SM(t)}}function _Un(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 X6(e){return _Un(`<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 CUn=Nt.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:X6("#d11")},".cm-lintRange-warning":{backgroundImage:X6("orange")},".cm-lintRange-info":{backgroundImage:X6("#999")},".cm-lintRange-hint":{backgroundImage:X6("#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 EUn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function jUn(e){let t="hint",n=1;for(let r of e){let s=EUn(r.severity);s>n&&(n=s,t=r.severity)}return t}const TUn=[Cp,Nt.decorations.compute([Cp],e=>{let{selected:t,panel:n}=e.field(Cp);return!t||!n||t.from==t.to?jn.none:jn.set([yUn.range(t.from,t.to)])}),w6n(bUn,{hideOn:gUn}),CUn];var wze=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(yzn)),t.defaultKeymap!==!1&&(a=a.concat(FBn)),t.searchKeymap!==!1&&(a=a.concat(fUn)),t.historyKeymap!==!1&&(a=a.concat(W7n)),t.foldKeymap!==!1&&(a=a.concat(rFn)),t.completionKeymap!==!1&&(a=a.concat(l0t)),t.lintKeymap!==!1&&(a=a.concat(kUn));var i=[];return t.lineNumbers!==!1&&i.push(R6n()),t.highlightActiveLineGutter!==!1&&i.push(M6n()),t.highlightSpecialChars!==!1&&i.push(Q5n()),t.history!==!1&&i.push(D7n()),t.foldGutter!==!1&&i.push(oFn()),t.drawSelection!==!1&&i.push(F5n()),t.dropCursor!==!1&&i.push(q5n()),t.allowMultipleSelections!==!1&&i.push(cs.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(Q6n()),t.syntaxHighlighting!==!1&&i.push(U1(dFn,{fallback:!0})),t.bracketMatching!==!1&&i.push(yFn()),t.closeBrackets!==!1&&i.push(hzn()),t.autocompletion!==!1&&i.push(o0t()),t.rectangularSelection!==!1&&i.push(c6n()),s!==!1&&i.push(f6n()),t.highlightActiveLine!==!1&&i.push(t6n()),t.highlightSelectionMatches!==!1&&i.push(HBn()),t.tabSize&&typeof t.tabSize=="number"&&i.push(oI.of(" ".repeat(t.tabSize))),i.concat([iI.of(a.flat())]).filter(Boolean)};const NUn="#e5c07b",Sze="#e06c75",IUn="#56b6c2",AUn="#ffffff",T8="#abb2bf",Zme="#7d8799",RUn="#61afef",PUn="#98c379",kze="#d19a66",$Un="#c678dd",MUn="#21252b",Oze="#2c313a",_ze="#282c34",JJ="#353a42",DUn="#3E4451",Cze="#528bff",LUn=Nt.theme({"&":{color:T8,backgroundColor:_ze},".cm-content":{caretColor:Cze},".cm-cursor, .cm-dropCursor":{borderLeftColor:Cze},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:DUn},".cm-panels":{backgroundColor:MUn,color:T8},".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:_ze,color:Zme,border:"none"},".cm-activeLineGutter":{backgroundColor:Oze},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:JJ},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:JJ,borderBottomColor:JJ},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:Oze,color:T8}}},{dark:!0}),FUn=Ug.define([{tag:pe.keyword,color:$Un},{tag:[pe.name,pe.deleted,pe.character,pe.propertyName,pe.macroName],color:Sze},{tag:[pe.function(pe.variableName),pe.labelName],color:RUn},{tag:[pe.color,pe.constant(pe.name),pe.standard(pe.name)],color:kze},{tag:[pe.definition(pe.name),pe.separator],color:T8},{tag:[pe.typeName,pe.className,pe.number,pe.changed,pe.annotation,pe.modifier,pe.self,pe.namespace],color:NUn},{tag:[pe.operator,pe.operatorKeyword,pe.url,pe.escape,pe.regexp,pe.link,pe.special(pe.string)],color:IUn},{tag:[pe.meta,pe.comment],color:Zme},{tag:pe.strong,fontWeight:"bold"},{tag:pe.emphasis,fontStyle:"italic"},{tag:pe.strikethrough,textDecoration:"line-through"},{tag:pe.link,color:Zme,textDecoration:"underline"},{tag:pe.heading,fontWeight:"bold",color:Sze},{tag:[pe.atom,pe.bool,pe.special(pe.variableName)],color:kze},{tag:[pe.processingInstruction,pe.string,pe.inserted],color:PUn},{tag:pe.invalid,color:AUn}]),zUn=[LUn,U1(FUn)];var BUn=Nt.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),UUn=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,p=f===void 0?"":f,h=n.basicSetup,m=h===void 0?!0:h,g=[];switch(s&&g.unshift(iI.of([zBn])),m&&(typeof m=="boolean"?g.unshift(wze()):g.unshift(wze(m))),p&&g.unshift(a6n(p)),d){case"light":g.push(BUn);break;case"dark":g.push(zUn);break;case"none":break;default:g.push(d);break}return i===!1&&g.push(Nt.editable.of(!1)),c&&g.push(cs.readOnly.of(!0)),[...g]},VUn=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 qUn{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 Eze{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 eee=null,HUn=()=>typeof window>"u"?new Eze:(eee||(eee=new Eze),eee),WUn=Nt.theme({"& .cm-scroller":{height:"100% !important"}}),jze=null,tee=null;function ZUn(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===jze||(jze=i,tee=Nt.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a}})),tee}var Tze=Ly.define(),GUn=200,QUn=[];function YUn(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?QUn:l,u=e.autoFocus,d=e.theme,f=d===void 0?"light":d,p=e.height,h=p===void 0?null:p,m=e.minHeight,g=m===void 0?null:m,y=e.maxHeight,b=y===void 0?null:y,x=e.width,S=x===void 0?null:x,k=e.minWidth,_=k===void 0?null:k,C=e.maxWidth,E=C===void 0?null:C,j=e.placeholder,N=j===void 0?"":j,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,F=H===void 0?!0:H,z=e.root,q=e.initialState,M=v.useState(),G=M[0],V=M[1],$=v.useState(),U=$[0],Z=$[1],K=v.useState(),te=K[0],ee=K[1],J=v.useState(()=>({current:null}))[0],ae=v.useState(()=>({current:null}))[0],de=ZUn(h,g,b,S,_,E),Y=Nt.updateListener.of(oe=>{if(oe.docChanged&&typeof r=="function"&&!oe.transactions.some(be=>be.annotation(Tze))){J.current?J.current.reset():(J.current=new qUn(()=>{if(ae.current){var be=ae.current;ae.current=null,be()}J.current=null},GUn),HUn().add(J.current));var le=oe.state.doc,he=le.toString();r(he,oe)}s&&s(VUn(oe))}),ne=UUn({theme:f,editable:A,readOnly:L,placeholder:N,indentWithTab:B,basicSetup:F}),fe=[Y,...de?[de]:[],WUn,...ne];return i&&typeof i=="function"&&fe.push(Nt.updateListener.of(i)),fe=fe.concat(c),v.useLayoutEffect(()=>{if(G&&!te){var oe={doc:t,selection:n,extensions:fe},le=q?cs.fromJSON(q.json,oe,q.fields):cs.create(oe);if(ee(le),!U){var he=new Nt({state:le,parent:G,root:z});Z(he),a&&a(he,le)}}return()=>{U&&(ee(void 0),Z(void 0))}},[G,te]),v.useEffect(()=>{e.container&&V(e.container)},[e.container]),v.useEffect(()=>()=>{U&&(U.destroy(),Z(void 0)),J.current&&(J.current.cancel(),J.current=null)},[U]),v.useEffect(()=>{u&&U&&U.focus()},[u,U]),v.useEffect(()=>{U&&U.dispatch({effects:vr.reconfigure.of(fe)})},[f,c,h,g,b,S,_,E,N,A,L,B,F,r,i]),v.useEffect(()=>{if(t!==void 0){var oe=U?U.state.doc.toString():"";if(U&&t!==oe){var le=J.current&&!J.current.isDone,he=()=>{U&&t!==U.state.doc.toString()&&U.dispatch({changes:{from:0,to:U.state.doc.toString().length,insert:t||""},annotations:[Tze.of(!0)]})};le?ae.current=he:he()}}},[t,U]),{state:te,setState:ee,view:U,setView:Z,container:G,setContainer:V}}var KUn=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],Qu=v.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,p=e.autoFocus,h=e.theme,m=h===void 0?"light":h,g=e.height,y=e.minHeight,b=e.maxHeight,x=e.width,S=e.minWidth,k=e.maxWidth,_=e.basicSetup,C=e.placeholder,E=e.indentWithTab,j=e.editable,N=e.readOnly,I=e.root,A=e.initialState,R=Swt(e,KUn),L=v.useRef(null),D=YUn({root:I,value:s,autoFocus:p,theme:m,height:g,minHeight:y,maxHeight:b,width:x,minWidth:S,maxWidth:k,basicSetup:_,placeholder:C,indentWithTab:E,editable:j,readOnly:N,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),B=D.state,H=D.view,F=D.container,z=D.setContainer;v.useImperativeHandle(t,()=>({editor:L.current,state:B,view:H}),[L,F,B,H]);var q=v.useCallback(G=>{L.current=G,z(G)},[z]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var M=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",UO({ref:q,className:""+M+(n?" "+n:"")},R))});Qu.displayName="CodeMirror";const XUn={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"};let nee=null;function JUn(){return nee||(nee=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([mo(()=>import("./core-CZ7lrnPw.js"),__vite__mapDeps([0,1,2]),import.meta.url),mo(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[mo(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),mo(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[mo(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),mo(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),mo(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),mo(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),mo(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),mo(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),mo(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),mo(()=>import("./python-DhUJRlN_.js"),[],import.meta.url)],engine:t()})})()),nee}async function eVn(e,t){const n=XUn[t?.toLowerCase()];if(!n)return null;const r=await JUn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function tVn(e){return new LO(sSe.define(e))}const m1t=[ng.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return mo(()=>Promise.resolve().then(()=>G6),void 0,import.meta.url).then(e=>e.javascript())}}),ng.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return mo(()=>Promise.resolve().then(()=>NFn),void 0,import.meta.url).then(e=>e.json())}}),ng.of({name:"JSX",extensions:["jsx"],load(){return mo(()=>Promise.resolve().then(()=>G6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),ng.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return mo(()=>Promise.resolve().then(()=>O7n),void 0,import.meta.url).then(e=>e.markdown())}}),ng.of({name:"TSX",extensions:["tsx"],load(){return mo(()=>Promise.resolve().then(()=>G6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),ng.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return mo(()=>Promise.resolve().then(()=>G6),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),ng.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return mo(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>tVn(e.shell))}})];function nVn(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 rVn(e){const t=nVn(e);return o0t({override:[sVn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function sVn(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,p)=>{const g=u.state.sliceDoc(p,p+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:p,insert:g},selection:{anchor:f+g.length}})}}));return{from:a,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const aVn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,iVn=jn.mark({class:"cm-variable-highlight"}),Nze=new wxt({regexp:aVn,decoration:()=>iVn}),oVn=Co.fromClass(class{decorations;constructor(e){this.decorations=Nze.createDeco(e)}update(e){this.decorations=Nze.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),lVn=oVn;function cVn(){const e=cI({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:[pe.className,pe.propertyName],color:"var(--neutral6)"},{tag:pe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[pe.heading1,pe.heading2,pe.heading3,pe.heading4,pe.heading5,pe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:pe.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:pe.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:pe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:pe.url,color:"var(--accent3)"},{tag:pe.monospace,color:"var(--neutral6)"},{tag:pe.strikethrough,textDecoration:"line-through"},{tag:pe.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=Nt.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 uVn(){const e=Nt.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=Ug.define([{tag:[pe.comment,pe.bracket],color:"var(--neutral2)"},{tag:[pe.string,pe.meta,pe.regexp],color:"var(--accent1)"},{tag:[pe.atom,pe.bool,pe.special(pe.variableName)],color:"var(--accent6)"},{tag:[pe.keyword,pe.operator,pe.tagName],color:"var(--accent2)"},{tag:[pe.function(pe.propertyName),pe.propertyName],color:"var(--accent5)"},{tag:[pe.definition(pe.variableName),pe.function(pe.variableName),pe.className,pe.attributeName],color:"var(--accent3)"},{tag:[pe.variableName,pe.number],color:"var(--accent5)"},{tag:[pe.name,pe.quote],color:"var(--accent1)"},{tag:pe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[pe.heading1,pe.heading2,pe.heading3,pe.heading4,pe.heading5,pe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[pe.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[pe.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:pe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:pe.url,color:"var(--accent3)"},{tag:pe.monospace,color:"var(--neutral6)"},{tag:pe.strikethrough,textDecoration:"line-through"},{tag:[pe.deleted],color:"var(--accent2)"},{tag:pe.invalid,color:"var(--error)"},{tag:[pe.standard(pe.tagName)],color:"var(--accent1)"}]);return[e,U1(t)]}const Yx=()=>{const e=B_().resolvedTheme==="dark";return v.useMemo(()=>e?cVn():uVn(),[e])},dVn=co(X("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"}}),fVn=Xp.highest(Nt.editorAttributes.of({style:"outline: none"})),pVn=Xp.highest(Nt.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),hVn=[fVn,pVn],Wr=v.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:p,variant:h,...m},g)=>{const y=Yx(),b=e?JSON.stringify(e,null,2):t??"",x=v.useMemo(()=>{const S=[...hVn];return f&&S.push(Nt.lineWrapping),a==="json"?S.push(Rp):a==="markdown"&&S.push(ISe({base:BO,codeLanguages:m1t})),i&&a==="markdown"&&S.push(lVn),c&&a==="markdown"&&S.push(rVn(c)),p===!1&&S.push(cs.readOnly.of(!0)),S},[a,i,c,p,f]);return o.jsxs("div",{className:X(dVn({variant:h}),s),...m,children:[r&&o.jsx(Pa,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(Qu,{ref:g,value:b,theme:y,extensions:x,onChange:n,editable:p,"aria-label":"Code editor",placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),mVn=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},gVn=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=Yx(),{settings:r,setSettings:s}=tH(),a=r?.tracingOptions,i=v.useMemo(()=>mVn(a),[a]),[l,c]=v.useState(()=>i),u=v.useRef(!1);v.useEffect(()=>{u.current||c(i)},[i]);const d=p=>{u.current=!0,c(p)},f=()=>{if(!l){s({...r,tracingOptions:void 0}),t?.();return}try{const p=JSON.parse(l);typeof p=="object"&&p!==null&&s({...r,tracingOptions:p})}catch{return}t?.()};return o.jsxs("div",{className:"space-y-2 px-5 py-2",children:[o.jsx(ye,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),o.jsx(Qu,{value:l,onChange:d,theme:n,extensions:[Rp],className:X("overflow-y-scroll bg-surface3 rounded-lg overflow-hidden p-3",e)}),o.jsx("div",{className:"flex items-center justify-end",children:o.jsx(ce,{type:"button",onClick:f,children:"Save"})})]})},vVn=()=>{const[e,t]=v.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:o.jsx(ce,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(qe,{children:o.jsx(WV,{})})})}),o.jsx(Rn,{children:"Run Options"})]}),o.jsx(br,{open:e,onOpenChange:t,children:o.jsxs(xr,{children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Run Options"}),o.jsx(Ks,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx($r,{children:o.jsx(gVn,{onSaved:()=>t(!1)})})]})})]})};function yVn({status:e}){switch(e){case"running":return o.jsx(Xt,{});case"failed":return o.jsx(bs,{className:"text-accent2"});case"canceled":return o.jsx(Nf,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(uT,{className:"text-neutral3"});case"suspended":return o.jsx(BV,{className:"text-accent3"});case"success":return o.jsx(fa,{className:"text-accent1"});default:return o.jsx(uT,{className:"text-neutral3"})}}function g1t({status:e}){return o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:o.jsx(qe,{"aria-label":e,className:"shrink-0",children:o.jsx(yVn,{status:e})})}),o.jsx(Rn,{children:e})]})}var ree,Ize;function zSe(){if(Ize)return ree;Ize=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 p=arguments,h=this;return d.forEach(function(m){p.length>1?h.setNode(m,f):h.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 p=h=>f.removeEdge(f._edgeObjs[h]);delete this._nodes[d],this._isCompound&&(this._removeFromParentsChildList(d),delete this._parent[d],this.children(d).forEach(function(h){f.setParent(h)}),delete this._children[d]),Object.keys(this._in[d]).forEach(p),delete this._in[d],delete this._preds[d],Object.keys(this._out[d]).forEach(p),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 p=f;p!==void 0;p=this.parent(p))if(p===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 h=new Set(f);for(var p of this.successors(d))h.add(p);return Array.from(h.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 p=this;Object.entries(this._nodes).forEach(function([g,y]){d(g)&&f.setNode(g,y)}),Object.values(this._edgeObjs).forEach(function(g){f.hasNode(g.v)&&f.hasNode(g.w)&&f.setEdge(g,p.edge(g))});var h={};function m(g){var y=p.parent(g);return y===void 0||f.hasNode(y)?(h[g]=y,y):y in h?h[y]:m(y)}return this._isCompound&&f.nodes().forEach(g=>f.setParent(g,m(g))),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 p=this,h=arguments;return d.reduce(function(m,g){return h.length>1?p.setEdge(m,g,f):p.setEdge(m,g),g}),this}setEdge(){var d,f,p,h,m=!1,g=arguments[0];typeof g=="object"&&g!==null&&"v"in g?(d=g.v,f=g.w,p=g.name,arguments.length===2&&(h=arguments[1],m=!0)):(d=g,f=arguments[1],p=arguments[3],arguments.length>2&&(h=arguments[2],m=!0)),d=""+d,f=""+f,p!==void 0&&(p=""+p);var y=i(this._isDirected,d,f,p);if(Object.hasOwn(this._edgeLabels,y))return m&&(this._edgeLabels[y]=h),this;if(p!==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?h:this._defaultEdgeLabelFn(d,f,p);var b=l(this._isDirected,d,f,p);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,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return this._edgeLabels[h]}edgeAsObj(){const d=this.edge(...arguments);return typeof d!="object"?{label:d}:d}hasEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return Object.hasOwn(this._edgeLabels,h)}removeEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p),m=this._edgeObjs[h];return m&&(d=m.v,f=m.w,delete this._edgeLabels[h],delete this._edgeObjs[h],a(this._preds[f],d),a(this._sucs[d],f),delete this._in[f][h],delete this._out[d][h],this._edgeCount--),this}inEdges(d,f){var p=this._in[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.v===f):h}}outEdges(d,f){var p=this._out[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.w===f):h}}nodeEdges(d,f){var p=this.inEdges(d,f);if(p)return p.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,p){var h=""+d,m=""+f;if(!u&&h>m){var g=h;h=m,m=g}return h+n+m+n+(p===void 0?e:p)}function l(u,d,f,p){var h=""+d,m=""+f;if(!u&&h>m){var g=h;h=m,m=g}var y={v:h,w:m};return p&&(y.name=p),y}function c(u,d){return i(u,d.v,d.w,d.name)}return ree=r,ree}var see,Aze;function bVn(){return Aze||(Aze=1,see="2.2.4"),see}var aee,Rze;function xVn(){return Rze||(Rze=1,aee={Graph:zSe(),version:bVn()}),aee}var iee,Pze;function wVn(){if(Pze)return iee;Pze=1;var e=zSe();iee={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 iee}var oee,$ze;function SVn(){if($ze)return oee;$ze=1,oee=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 oee}var lee,Mze;function v1t(){if(Mze)return lee;Mze=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 lee=e,lee}var cee,Dze;function y1t(){if(Dze)return cee;Dze=1;var e=v1t();cee=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,p=function(h){var m=h.v!==d?h.v:h.w,g=c[m],y=i(h),b=f.distance+y;if(y<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+h+" Weight: "+y);b<g.distance&&(g.distance=b,g.predecessor=d,u.decrease(m,b))};for(s.nodes().forEach(function(h){var m=h===a?0:Number.POSITIVE_INFINITY;c[h]={distance:m},u.add(h,m)});u.size()>0&&(d=u.removeMin(),f=c[d],f.distance!==Number.POSITIVE_INFINITY);)l(d).forEach(p);return c}return cee}var uee,Lze;function kVn(){if(Lze)return uee;Lze=1;var e=y1t();uee=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return uee}var dee,Fze;function b1t(){if(Fze)return dee;Fze=1,dee=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 dee}var fee,zze;function OVn(){if(zze)return fee;zze=1;var e=b1t();fee=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return fee}var pee,Bze;function _Vn(){if(Bze)return pee;Bze=1,pee=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(p){var h=f[c],m=u[p],g=f[p],y=h.distance+m.distance;y<g.distance&&(g.distance=y,g.predecessor=m.predecessor)})})}),i}return pee}var hee,Uze;function x1t(){if(Uze)return hee;Uze=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 hee=e,e.CycleException=t,hee}var mee,Vze;function CVn(){if(Vze)return mee;Vze=1;var e=x1t();mee=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return mee}var gee,qze;function w1t(){if(qze)return gee;qze=1,gee=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 gee}var vee,Hze;function EVn(){if(Hze)return vee;Hze=1;var e=w1t();vee=t;function t(n,r){return e(n,r,"post")}return vee}var yee,Wze;function jVn(){if(Wze)return yee;Wze=1;var e=w1t();yee=t;function t(n,r){return e(n,r,"pre")}return yee}var bee,Zze;function TVn(){if(Zze)return bee;Zze=1;var e=zSe(),t=v1t();bee=n;function n(r,s){var a=new e,i={},l=new t,c;function u(f){var p=f.v===c?f.w:f.v,h=l.priority(p);if(h!==void 0){var m=s(f);m<h&&(i[p]=c,l.decrease(p,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 bee}var xee,Gze;function NVn(){return Gze||(Gze=1,xee={components:SVn(),dijkstra:y1t(),dijkstraAll:kVn(),findCycles:OVn(),floydWarshall:_Vn(),isAcyclic:CVn(),postorder:EVn(),preorder:jVn(),prim:TVn(),tarjan:b1t(),topsort:x1t()}),xee}var wee,Qze;function Mg(){if(Qze)return wee;Qze=1;var e=xVn();return wee={Graph:e.Graph,json:wVn(),alg:NVn(),version:e.version},wee}var See,Yze;function IVn(){if(Yze)return See;Yze=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 See=e,See}var kee,Kze;function AVn(){if(Kze)return kee;Kze=1;let e=Mg().Graph,t=IVn();kee=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(h=>u.outEdges(h.v,h.w))}function s(u,d,f){let p=[],h=d[d.length-1],m=d[0],g;for(;u.nodeCount();){for(;g=m.dequeue();)a(u,d,f,g);for(;g=h.dequeue();)a(u,d,f,g);if(u.nodeCount()){for(let y=d.length-2;y>0;--y)if(g=d[y].dequeue(),g){p=p.concat(a(u,d,f,g,!0));break}}}return p}function a(u,d,f,p,h){let m=h?[]:void 0;return u.inEdges(p.v).forEach(g=>{let y=u.edge(g),b=u.node(g.v);h&&m.push({v:g.v,w:g.w}),b.out-=y,l(d,f,b)}),u.outEdges(p.v).forEach(g=>{let y=u.edge(g),b=g.w,x=u.node(b);x.in-=y,l(d,f,x)}),u.removeNode(p.v),m}function i(u,d){let f=new e,p=0,h=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),S=b+x;f.setEdge(y.v,y.w,S),h=Math.max(h,f.node(y.v).out+=x),p=Math.max(p,f.node(y.w).in+=x)});let m=c(h+p+3).map(()=>new t),g=p+1;return f.nodes().forEach(y=>{l(m,g,f.node(y))}),{graph:f,buckets:m,zeroIdx:g}}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 kee}var Oee,Xze;function Ml(){if(Xze)return Oee;Xze=1;let e=Mg().Graph;Oee={addBorderNode:d,addDummyNode:t,applyWithChunking:h,asNonCompoundGraph:r,buildLayerMatrix:l,intersectRect:i,mapValues:C,maxRank:m,normalizeRanks:c,notime:b,partition:g,pick:_,predecessorWeights:a,range:k,removeEmptyRanks:u,simplify:n,successorWeights:s,time:y,uniqueId:S,zipObject:E};function t(j,N,I,A){for(var R=A;j.hasNode(R);)R=S(A);return I.dummy=N,j.setNode(R,I),R}function n(j){let N=new e().setGraph(j.graph());return j.nodes().forEach(I=>N.setNode(I,j.node(I))),j.edges().forEach(I=>{let A=N.edge(I.v,I.w)||{weight:0,minlen:1},R=j.edge(I);N.setEdge(I.v,I.w,{weight:A.weight+R.weight,minlen:Math.max(A.minlen,R.minlen)})}),N}function r(j){let N=new e({multigraph:j.isMultigraph()}).setGraph(j.graph());return j.nodes().forEach(I=>{j.children(I).length||N.setNode(I,j.node(I))}),j.edges().forEach(I=>{N.setEdge(I,j.edge(I))}),N}function s(j){let N=j.nodes().map(I=>{let A={};return j.outEdges(I).forEach(R=>{A[R.w]=(A[R.w]||0)+j.edge(R).weight}),A});return E(j.nodes(),N)}function a(j){let N=j.nodes().map(I=>{let A={};return j.inEdges(I).forEach(R=>{A[R.v]=(A[R.v]||0)+j.edge(R).weight}),A});return E(j.nodes(),N)}function i(j,N){let I=j.x,A=j.y,R=N.x-I,L=N.y-A,D=j.width/2,B=j.height/2;if(!R&&!L)throw new Error("Not possible to find intersection inside of the rectangle");let H,F;return Math.abs(L)*D>Math.abs(R)*B?(L<0&&(B=-B),H=B*R/L,F=B):(R<0&&(D=-D),H=D,F=D*L/R),{x:I+H,y:A+F}}function l(j){let N=k(m(j)+1).map(()=>[]);return j.nodes().forEach(I=>{let A=j.node(I),R=A.rank;R!==void 0&&(N[R][A.order]=I)}),N}function c(j){let N=j.nodes().map(A=>{let R=j.node(A).rank;return R===void 0?Number.MAX_VALUE:R}),I=h(Math.min,N);j.nodes().forEach(A=>{let R=j.node(A);Object.hasOwn(R,"rank")&&(R.rank-=I)})}function u(j){let N=j.nodes().map(D=>j.node(D).rank),I=h(Math.min,N),A=[];j.nodes().forEach(D=>{let B=j.node(D).rank-I;A[B]||(A[B]=[]),A[B].push(D)});let R=0,L=j.graph().nodeRankFactor;Array.from(A).forEach((D,B)=>{D===void 0&&B%L!==0?--R:D!==void 0&&R&&D.forEach(H=>j.node(H).rank+=R)})}function d(j,N,I,A){let R={width:0,height:0};return arguments.length>=4&&(R.rank=I,R.order=A),t(j,"border",R,N)}function f(j,N=p){const I=[];for(let A=0;A<j.length;A+=N){const R=j.slice(A,A+N);I.push(R)}return I}const p=65535;function h(j,N){if(N.length>p){const I=f(N);return j.apply(null,I.map(A=>j.apply(null,A)))}else return j.apply(null,N)}function m(j){const I=j.nodes().map(A=>{let R=j.node(A).rank;return R===void 0?Number.MIN_VALUE:R});return h(Math.max,I)}function g(j,N){let I={lhs:[],rhs:[]};return j.forEach(A=>{N(A)?I.lhs.push(A):I.rhs.push(A)}),I}function y(j,N){let I=Date.now();try{return N()}finally{console.log(j+" time: "+(Date.now()-I)+"ms")}}function b(j,N){return N()}let x=0;function S(j){var N=++x;return j+(""+N)}function k(j,N,I=1){N==null&&(N=j,j=0);let A=L=>L<N;I<0&&(A=L=>N<L);const R=[];for(let L=j;A(L);L+=I)R.push(L);return R}function _(j,N){const I={};for(const A of N)j[A]!==void 0&&(I[A]=j[A]);return I}function C(j,N){let I=N;return typeof N=="string"&&(I=A=>A[N]),Object.entries(j).reduce((A,[R,L])=>(A[R]=I(L,R),A),{})}function E(j,N){return j.reduce((I,A,R)=>(I[A]=N[R],I),{})}return Oee}var _ee,Jze;function RVn(){if(Jze)return _ee;Jze=1;let e=AVn(),t=Ml().uniqueId;_ee={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 _ee}var Cee,e8e;function PVn(){if(e8e)return Cee;e8e=1;let e=Ml();Cee={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),p=f.labelRank;if(u===l+1)return;s.removeEdge(a);let h,m,g;for(g=0,++l;l<u;++g,++l)f.points=[],m={width:0,height:0,edgeLabel:f,edgeObj:a,rank:l},h=e.addDummyNode(s,"edge",m,"_d"),l===p&&(m.width=f.width,m.height=f.height,m.dummy="edge-label",m.labelpos=f.labelpos),s.setEdge(i,h,{weight:f.weight},d),g===0&&s.graph().dummyChains.push(h),i=h;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 Cee}var Eee,t8e;function bB(){if(t8e)return Eee;t8e=1;const{applyWithChunking:e}=Ml();Eee={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 Eee}var jee,n8e;function S1t(){if(n8e)return jee;n8e=1;var e=Mg().Graph,t=bB().slack;jee=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,p=u===f?d.w:f;!i.hasNode(p)&&!t(l,d)&&(i.setNode(p,{}),i.setEdge(u,p,{}),c(p))})}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 jee}var Tee,r8e;function $Vn(){if(r8e)return Tee;r8e=1;var e=S1t(),t=bB().slack,n=bB().longestPath,r=Mg().alg.preorder,s=Mg().alg.postorder,a=Ml().simplify;Tee=i,i.initLowLimValues=d,i.initCutValues=l,i.calcCutValue=u,i.leaveEdge=p,i.enterEdge=h,i.exchangeEdges=m;function i(x){x=a(x),n(x);var S=e(x);d(S),l(S,x);for(var k,_;k=p(S);)_=h(S,x,k),m(S,x,k,_)}function l(x,S){var k=s(x,x.nodes());k=k.slice(0,k.length-1),k.forEach(_=>c(x,S,_))}function c(x,S,k){var _=x.node(k),C=_.parent;x.edge(k,C).cutvalue=u(x,S,k)}function u(x,S,k){var _=x.node(k),C=_.parent,E=!0,j=S.edge(k,C),N=0;return j||(E=!1,j=S.edge(C,k)),N=j.weight,S.nodeEdges(k).forEach(I=>{var A=I.v===k,R=A?I.w:I.v;if(R!==C){var L=A===E,D=S.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,S){arguments.length<2&&(S=x.nodes()[0]),f(x,{},1,S)}function f(x,S,k,_,C){var E=k,j=x.node(_);return S[_]=!0,x.neighbors(_).forEach(N=>{Object.hasOwn(S,N)||(k=f(x,S,k,N,_))}),j.low=E,j.lim=k++,C?j.parent=C:delete j.parent,k}function p(x){return x.edges().find(S=>x.edge(S).cutvalue<0)}function h(x,S,k){var _=k.v,C=k.w;S.hasEdge(_,C)||(_=k.w,C=k.v);var E=x.node(_),j=x.node(C),N=E,I=!1;E.lim>j.lim&&(N=j,I=!0);var A=S.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(S,L)<t(S,R)?L:R)}function m(x,S,k,_){var C=k.v,E=k.w;x.removeEdge(C,E),x.setEdge(_.v,_.w,{}),d(x),l(x,S),g(x,S)}function g(x,S){var k=x.nodes().find(C=>!S.node(C).parent),_=r(x,k);_=_.slice(1),_.forEach(C=>{var E=x.node(C).parent,j=S.edge(C,E),N=!1;j||(j=S.edge(E,C),N=!0),S.node(C).rank=S.node(E).rank+(N?j.minlen:-j.minlen)})}function y(x,S,k){return x.hasEdge(S,k)}function b(x,S,k){return k.low<=S.lim&&S.lim<=k.lim}return Tee}var Nee,s8e;function MVn(){if(s8e)return Nee;s8e=1;var e=bB(),t=e.longestPath,n=S1t(),r=$Vn();Nee=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 Nee}var Iee,a8e;function DVn(){if(a8e)return Iee;a8e=1,Iee=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,p=u[f],h=!0;for(;a!==l.w;){if(i=r.node(a),h){for(;(p=u[f])!==d&&r.node(p).maxRank<i.rank;)f++;p===d&&(h=!1)}if(!h){for(;f<u.length-1&&r.node(p=u[f+1]).minRank<=i.rank;)f++;p=u[f]}r.setParent(a,p),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,p;f=a;do f=r.parent(f),l.push(f);while(f&&(s[f].low>u||d>s[f].lim));for(p=f,f=i;(f=r.parent(f))!==p;)c.push(f);return{path:l.concat(c.reverse()),lca:p}}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 Iee}var Aee,i8e;function LVn(){if(i8e)return Aee;i8e=1;let e=Ml();Aee={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(h=>i.edge(h).minlen*=f);let p=s(i)+1;i.children().forEach(h=>n(i,l,f,p,d,c,h)),i.graph().nodeRankFactor=f}function n(i,l,c,u,d,f,p){let h=i.children(p);if(!h.length){p!==l&&i.setEdge(l,p,{weight:0,minlen:c});return}let m=e.addBorderNode(i,"_bt"),g=e.addBorderNode(i,"_bb"),y=i.node(p);i.setParent(m,p),y.borderTop=m,i.setParent(g,p),y.borderBottom=g,h.forEach(b=>{n(i,l,c,u,d,f,b);let x=i.node(b),S=x.borderTop?x.borderTop:b,k=x.borderBottom?x.borderBottom:b,_=x.borderTop?u:2*u,C=S!==k?1:d-f[p]+1;i.setEdge(m,S,{weight:_,minlen:C,nestingEdge:!0}),i.setEdge(k,g,{weight:_,minlen:C,nestingEdge:!0})}),i.parent(p)||i.setEdge(l,m,{weight:0,minlen:d+f[p]})}function r(i){var l={};function c(u,d){var f=i.children(u);f&&f.length&&f.forEach(p=>c(p,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 Aee}var Ree,o8e;function FVn(){if(o8e)return Ree;o8e=1;let e=Ml();Ree=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 Ree}var Pee,l8e;function zVn(){if(l8e)return Pee;l8e=1,Pee={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 Pee}var $ee,c8e;function BVn(){if(c8e)return $ee;c8e=1;let e=Ml();$ee=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 $ee}var Mee,u8e;function UVn(){if(u8e)return Mee;u8e=1;let e=Ml().zipObject;Mee=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((p,h)=>h)),l=s.flatMap(p=>r.outEdges(p).map(h=>({pos:i[h.w],weight:r.edge(h).weight})).sort((h,m)=>h.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(p=>{let h=p.pos+c;d[h]+=p.weight;let m=0;for(;h>0;)h%2&&(m+=d[h+1]),h=h-1>>1,d[h]+=p.weight;f+=p.weight*m}),f}return Mee}var Dee,d8e;function VVn(){if(d8e)return Dee;d8e=1,Dee=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 Dee}var Lee,f8e;function qVn(){if(f8e)return Lee;f8e=1;let e=Ml();Lee=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 Lee}var Fee,p8e;function HVn(){if(p8e)return Fee;p8e=1;let e=Ml();Fee=t;function t(s,a){let i=e.partition(s,m=>Object.hasOwn(m,"barycenter")),l=i.lhs,c=i.rhs.sort((m,g)=>g.i-m.i),u=[],d=0,f=0,p=0;l.sort(r(!!a)),p=n(u,c,p),l.forEach(m=>{p+=m.vs.length,u.push(m.vs),d+=m.barycenter*m.weight,f+=m.weight,p=n(u,c,p)});let h={vs:u.flat(!0)};return f&&(h.barycenter=d/f,h.weight=f),h}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 Fee}var zee,h8e;function WVn(){if(h8e)return zee;h8e=1;let e=VVn(),t=qVn(),n=HVn();zee=r;function r(i,l,c,u){let d=i.children(l),f=i.node(l),p=f?f.borderLeft:void 0,h=f?f.borderRight:void 0,m={};p&&(d=d.filter(x=>x!==p&&x!==h));let g=e(i,d);g.forEach(x=>{if(i.children(x.v).length){let S=r(i,x.v,c,u);m[x.v]=S,Object.hasOwn(S,"barycenter")&&a(x,S)}});let y=t(g,c);s(y,m);let b=n(y,u);if(p&&(b.vs=[p,b.vs,h].flat(!0),i.predecessors(p).length)){let x=i.node(i.predecessors(p)[0]),S=i.node(i.predecessors(h)[0]);Object.hasOwn(b,"barycenter")||(b.barycenter=0,b.weight=0),b.barycenter=(b.barycenter*b.weight+x.order+S.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 zee}var Bee,m8e;function ZVn(){if(m8e)return Bee;m8e=1;let e=Mg().Graph,t=Ml();Bee=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),p=s.parent(d);(f.rank===a||f.minRank<=a&&a<=f.maxRank)&&(u.setNode(d),u.setParent(d,p||c),s[i](d).forEach(h=>{let m=h.v===d?h.w:h.v,g=u.edge(m,d),y=g!==void 0?g.weight:0;u.setEdge(m,d,{weight:s.edge(h).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 Bee}var Uee,g8e;function GVn(){if(g8e)return Uee;g8e=1,Uee=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 Uee}var Vee,v8e;function QVn(){if(v8e)return Vee;v8e=1;let e=BVn(),t=UVn(),n=WVn(),r=ZVn(),s=GVn(),a=Mg().Graph,i=Ml();Vee=l;function l(f,p){if(p&&typeof p.customOrder=="function"){p.customOrder(f,l);return}let h=i.maxRank(f),m=c(f,i.range(1,h+1),"inEdges"),g=c(f,i.range(h-1,-1,-1),"outEdges"),y=e(f);if(d(f,y),p&&p.disableOptimalOrderHeuristic)return;let b=Number.POSITIVE_INFINITY,x;for(let S=0,k=0;k<4;++S,++k){u(S%2?m:g,S%4>=2),y=i.buildLayerMatrix(f);let _=t(f,y);_<b&&(k=0,x=Object.assign({},y),b=_)}d(f,x)}function c(f,p,h){const m=new Map,g=(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"&&g(b.rank,y),typeof b.minRank=="number"&&typeof b.maxRank=="number")for(let x=b.minRank;x<=b.maxRank;x++)x!==b.rank&&g(x,y)}return p.map(function(y){return r(f,y,h,m.get(y)||[])})}function u(f,p){let h=new a;f.forEach(function(m){let g=m.graph().root,y=n(m,g,h,p);y.vs.forEach((b,x)=>m.node(b).order=x),s(m,h,y.vs)})}function d(f,p){Object.values(p).forEach(h=>h.forEach((m,g)=>f.node(m).order=g))}return Vee}var qee,y8e;function YVn(){if(y8e)return qee;y8e=1;let e=Mg().Graph,t=Ml();qee={positionX:h,findType1Conflicts:n,findType2Conflicts:r,addConflict:a,hasConflict:i,verticalAlignment:l,horizontalCompaction:c,alignCoordinates:f,findSmallestWidthAlignment:d,balance:p};function n(y,b){let x={};function S(k,_){let C=0,E=0,j=k.length,N=_[_.length-1];return _.forEach((I,A)=>{let R=s(y,I),L=R?y.node(R).order:j;(R||I===N)&&(_.slice(E,A+1).forEach(D=>{y.predecessors(D).forEach(B=>{let H=y.node(B),F=H.order;(F<C||L<F)&&!(H.dummy&&y.node(D).dummy)&&a(x,B,D)})}),E=A+1,C=L)}),_}return b.length&&b.reduce(S),x}function r(y,b){let x={};function S(_,C,E,j,N){let I;t.range(C,E).forEach(A=>{I=_[A],y.node(I).dummy&&y.predecessors(I).forEach(R=>{let L=y.node(R);L.dummy&&(L.order<j||L.order>N)&&a(x,R,I)})})}function k(_,C){let E=-1,j,N=0;return C.forEach((I,A)=>{if(y.node(I).dummy==="border"){let R=y.predecessors(I);R.length&&(j=y.node(R[0]).order,S(C,N,A,E,j),N=A,E=j)}S(C,N,C.length,j,_.length)}),C}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 S=y[b];S||(y[b]=S={}),S[x]=!0}function i(y,b,x){if(b>x){let S=b;b=x,x=S}return!!y[b]&&Object.hasOwn(y[b],x)}function l(y,b,x,S){let k={},_={},C={};return b.forEach(E=>{E.forEach((j,N)=>{k[j]=j,_[j]=j,C[j]=N})}),b.forEach(E=>{let j=-1;E.forEach(N=>{let I=S(N);if(I.length){I=I.sort((R,L)=>C[R]-C[L]);let A=(I.length-1)/2;for(let R=Math.floor(A),L=Math.ceil(A);R<=L;++R){let D=I[R];_[N]===N&&j<C[D]&&!i(x,N,D)&&(_[D]=N,_[N]=k[N]=k[D],j=C[D])}}})}),{root:k,align:_}}function c(y,b,x,S,k){let _={},C=u(y,b,x,k),E=k?"borderLeft":"borderRight";function j(A,R){let L=C.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){_[A]=C.inEdges(A).reduce((R,L)=>Math.max(R,_[L.v]+C.edge(L)),0)}function I(A){let R=C.outEdges(A).reduce((D,B)=>Math.min(D,_[B.w]-C.edge(B)),Number.POSITIVE_INFINITY),L=y.node(A);R!==Number.POSITIVE_INFINITY&&L.borderType!==E&&(_[A]=Math.max(_[A],R))}return j(N,C.predecessors.bind(C)),j(I,C.successors.bind(C)),Object.keys(S).forEach(A=>_[A]=_[x[A]]),_}function u(y,b,x,S){let k=new e,_=y.graph(),C=m(_.nodesep,_.edgesep,S);return b.forEach(E=>{let j;E.forEach(N=>{let I=x[N];if(k.setNode(I),j){var A=x[j],R=k.edge(A,I);k.setEdge(A,I,Math.max(C(y,N,j),R||0))}j=N})}),k}function d(y,b){return Object.values(b).reduce((x,S)=>{let k=Number.NEGATIVE_INFINITY,_=Number.POSITIVE_INFINITY;Object.entries(S).forEach(([E,j])=>{let N=g(y,E)/2;k=Math.max(j+N,k),_=Math.min(j-N,_)});const C=k-_;return C<x[0]&&(x=[C,S]),x},[Number.POSITIVE_INFINITY,null])[1]}function f(y,b){let x=Object.values(b),S=t.applyWithChunking(Math.min,x),k=t.applyWithChunking(Math.max,x);["u","d"].forEach(_=>{["l","r"].forEach(C=>{let E=_+C,j=y[E];if(j===b)return;let N=Object.values(j),I=S-t.applyWithChunking(Math.min,N);C!=="l"&&(I=k-t.applyWithChunking(Math.max,N)),I&&(y[E]=t.mapValues(j,A=>A+I))})})}function p(y,b){return t.mapValues(y.ul,(x,S)=>{if(b)return y[b.toLowerCase()][S];{let k=Object.values(y).map(_=>_[S]).sort((_,C)=>_-C);return(k[1]+k[2])/2}})}function h(y){let b=t.buildLayerMatrix(y),x=Object.assign(n(y,b),r(y,b)),S={},k;["u","d"].forEach(C=>{k=C==="u"?b:Object.values(b).reverse(),["l","r"].forEach(E=>{E==="r"&&(k=k.map(A=>Object.values(A).reverse()));let j=(C==="u"?y.predecessors:y.successors).bind(y),N=l(y,k,x,j),I=c(y,k,N.root,N.align,E==="r");E==="r"&&(I=t.mapValues(I,A=>-A)),S[C+E]=I})});let _=d(y,S);return f(S,_),p(S,y.graph().align)}function m(y,b,x){return(S,k,_)=>{let C=S.node(k),E=S.node(_),j=0,N;if(j+=C.width/2,Object.hasOwn(C,"labelpos"))switch(C.labelpos.toLowerCase()){case"l":N=-C.width/2;break;case"r":N=C.width/2;break}if(N&&(j+=x?N:-N),N=0,j+=(C.dummy?b:y)/2,j+=(E.dummy?b:y)/2,j+=E.width/2,Object.hasOwn(E,"labelpos"))switch(E.labelpos.toLowerCase()){case"l":N=E.width/2;break;case"r":N=-E.width/2;break}return N&&(j+=x?N:-N),N=0,j}}function g(y,b){return y.node(b).width}return qee}var Hee,b8e;function KVn(){if(b8e)return Hee;b8e=1;let e=Ml(),t=YVn().positionX;Hee=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 p=s.node(f).height;return d>p?d:p},0);c.forEach(d=>s.node(d).y=l+u/2),l+=u+i})}return Hee}var Wee,x8e;function XVn(){if(x8e)return Wee;x8e=1;let e=RVn(),t=PVn(),n=MVn(),r=Ml().normalizeRanks,s=DVn(),a=Ml().removeEmptyRanks,i=LVn(),l=FVn(),c=zVn(),u=QVn(),d=KVn(),f=Ml(),p=Mg().Graph;Wee=h;function h($,U){let Z=U&&U.debugTiming?f.time:f.notime;Z("layout",()=>{let K=Z(" buildLayoutGraph",()=>j($));Z(" runLayout",()=>m(K,Z,U)),Z(" updateInputGraph",()=>g($,K))})}function m($,U,Z){U(" makeSpaceForEdgeLabels",()=>N($)),U(" removeSelfEdges",()=>z($)),U(" acyclic",()=>e.run($)),U(" nestingGraph.run",()=>i.run($)),U(" rank",()=>n(f.asNonCompoundGraph($))),U(" injectEdgeLabelProxies",()=>I($)),U(" removeEmptyRanks",()=>a($)),U(" nestingGraph.cleanup",()=>i.cleanup($)),U(" normalizeRanks",()=>r($)),U(" assignRankMinMax",()=>A($)),U(" removeEdgeLabelProxies",()=>R($)),U(" normalize.run",()=>t.run($)),U(" parentDummyChains",()=>s($)),U(" addBorderSegments",()=>l($)),U(" order",()=>u($,Z)),U(" insertSelfEdges",()=>q($)),U(" adjustCoordinateSystem",()=>c.adjust($)),U(" position",()=>d($)),U(" positionSelfEdges",()=>M($)),U(" removeBorderNodes",()=>F($)),U(" normalize.undo",()=>t.undo($)),U(" fixupEdgeLabelCoords",()=>B($)),U(" undoCoordinateSystem",()=>c.undo($)),U(" translateGraph",()=>L($)),U(" assignNodeIntersects",()=>D($)),U(" reversePoints",()=>H($)),U(" acyclic.undo",()=>e.undo($))}function g($,U){$.nodes().forEach(Z=>{let K=$.node(Z),te=U.node(Z);K&&(K.x=te.x,K.y=te.y,K.rank=te.rank,U.children(Z).length&&(K.width=te.width,K.height=te.height))}),$.edges().forEach(Z=>{let K=$.edge(Z),te=U.edge(Z);K.points=te.points,Object.hasOwn(te,"x")&&(K.x=te.x,K.y=te.y)}),$.graph().width=U.graph().width,$.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"],S=["width","height","rank"],k={width:0,height:0},_=["minlen","weight","width","height","labeloffset"],C={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},E=["labelpos"];function j($){let U=new p({multigraph:!0,compound:!0}),Z=V($.graph());return U.setGraph(Object.assign({},b,G(Z,y),f.pick(Z,x))),$.nodes().forEach(K=>{let te=V($.node(K));const ee=G(te,S);Object.keys(k).forEach(J=>{ee[J]===void 0&&(ee[J]=k[J])}),U.setNode(K,ee),U.setParent(K,$.parent(K))}),$.edges().forEach(K=>{let te=V($.edge(K));U.setEdge(K,Object.assign({},C,G(te,_),f.pick(te,E)))}),U}function N($){let U=$.graph();U.ranksep/=2,$.edges().forEach(Z=>{let K=$.edge(Z);K.minlen*=2,K.labelpos.toLowerCase()!=="c"&&(U.rankdir==="TB"||U.rankdir==="BT"?K.width+=K.labeloffset:K.height+=K.labeloffset)})}function I($){$.edges().forEach(U=>{let Z=$.edge(U);if(Z.width&&Z.height){let K=$.node(U.v),ee={rank:($.node(U.w).rank-K.rank)/2+K.rank,e:U};f.addDummyNode($,"edge-proxy",ee,"_ep")}})}function A($){let U=0;$.nodes().forEach(Z=>{let K=$.node(Z);K.borderTop&&(K.minRank=$.node(K.borderTop).rank,K.maxRank=$.node(K.borderBottom).rank,U=Math.max(U,K.maxRank))}),$.graph().maxRank=U}function R($){$.nodes().forEach(U=>{let Z=$.node(U);Z.dummy==="edge-proxy"&&($.edge(Z.e).labelRank=Z.rank,$.removeNode(U))})}function L($){let U=Number.POSITIVE_INFINITY,Z=0,K=Number.POSITIVE_INFINITY,te=0,ee=$.graph(),J=ee.marginx||0,ae=ee.marginy||0;function de(Y){let ne=Y.x,fe=Y.y,oe=Y.width,le=Y.height;U=Math.min(U,ne-oe/2),Z=Math.max(Z,ne+oe/2),K=Math.min(K,fe-le/2),te=Math.max(te,fe+le/2)}$.nodes().forEach(Y=>de($.node(Y))),$.edges().forEach(Y=>{let ne=$.edge(Y);Object.hasOwn(ne,"x")&&de(ne)}),U-=J,K-=ae,$.nodes().forEach(Y=>{let ne=$.node(Y);ne.x-=U,ne.y-=K}),$.edges().forEach(Y=>{let ne=$.edge(Y);ne.points.forEach(fe=>{fe.x-=U,fe.y-=K}),Object.hasOwn(ne,"x")&&(ne.x-=U),Object.hasOwn(ne,"y")&&(ne.y-=K)}),ee.width=Z-U+J,ee.height=te-K+ae}function D($){$.edges().forEach(U=>{let Z=$.edge(U),K=$.node(U.v),te=$.node(U.w),ee,J;Z.points?(ee=Z.points[0],J=Z.points[Z.points.length-1]):(Z.points=[],ee=te,J=K),Z.points.unshift(f.intersectRect(K,ee)),Z.points.push(f.intersectRect(te,J))})}function B($){$.edges().forEach(U=>{let Z=$.edge(U);if(Object.hasOwn(Z,"x"))switch((Z.labelpos==="l"||Z.labelpos==="r")&&(Z.width-=Z.labeloffset),Z.labelpos){case"l":Z.x-=Z.width/2+Z.labeloffset;break;case"r":Z.x+=Z.width/2+Z.labeloffset;break}})}function H($){$.edges().forEach(U=>{let Z=$.edge(U);Z.reversed&&Z.points.reverse()})}function F($){$.nodes().forEach(U=>{if($.children(U).length){let Z=$.node(U),K=$.node(Z.borderTop),te=$.node(Z.borderBottom),ee=$.node(Z.borderLeft[Z.borderLeft.length-1]),J=$.node(Z.borderRight[Z.borderRight.length-1]);Z.width=Math.abs(J.x-ee.x),Z.height=Math.abs(te.y-K.y),Z.x=ee.x+Z.width/2,Z.y=K.y+Z.height/2}}),$.nodes().forEach(U=>{$.node(U).dummy==="border"&&$.removeNode(U)})}function z($){$.edges().forEach(U=>{if(U.v===U.w){var Z=$.node(U.v);Z.selfEdges||(Z.selfEdges=[]),Z.selfEdges.push({e:U,label:$.edge(U)}),$.removeEdge(U)}})}function q($){var U=f.buildLayerMatrix($);U.forEach(Z=>{var K=0;Z.forEach((te,ee)=>{var J=$.node(te);J.order=ee+K,(J.selfEdges||[]).forEach(ae=>{f.addDummyNode($,"selfedge",{width:ae.label.width,height:ae.label.height,rank:J.rank,order:ee+ ++K,e:ae.e,label:ae.label},"_se")}),delete J.selfEdges})})}function M($){$.nodes().forEach(U=>{var Z=$.node(U);if(Z.dummy==="selfedge"){var K=$.node(Z.e.v),te=K.x+K.width/2,ee=K.y,J=Z.x-te,ae=K.height/2;$.setEdge(Z.e,Z.label),$.removeNode(U),Z.label.points=[{x:te+2*J/3,y:ee-ae},{x:te+5*J/6,y:ee-ae},{x:te+J,y:ee},{x:te+5*J/6,y:ee+ae},{x:te+2*J/3,y:ee+ae}],Z.label.x=Z.x,Z.label.y=Z.y}})}function G($,U){return f.mapValues(f.pick($,U),Number)}function V($){var U={};return $&&Object.entries($).forEach(([Z,K])=>{typeof Z=="string"&&(Z=Z.toLowerCase()),U[Z]=K}),U}return Wee}var Zee,w8e;function JVn(){if(w8e)return Zee;w8e=1;let e=Ml(),t=Mg().Graph;Zee={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 Zee}var Gee,S8e;function eqn(){return S8e||(S8e=1,Gee="1.1.8"),Gee}var Qee,k8e;function tqn(){return k8e||(k8e=1,Qee={graphlib:Mg(),layout:XVn(),debug:JVn(),util:{time:Ml().time,notime:Ml().notime},version:eqn()}),Qee}var nqn=tqn();const O8e=Fl(nqn);function Ul(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=Ul(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var rqn={value:()=>{}};function TH(){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 N8(n)}function N8(e){this._=e}function sqn(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}})}N8.prototype=TH.prototype={constructor:N8,on:function(e,t){var n=this._,r=sqn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=aqn(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]=_8e(n[s],e.name,t);else if(t==null)for(s in n)n[s]=_8e(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 N8(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 aqn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function _8e(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=rqn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Gme="http://www.w3.org/1999/xhtml";const C8e={svg:"http://www.w3.org/2000/svg",xhtml:Gme,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function NH(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),C8e.hasOwnProperty(t)?{space:C8e[t],local:e}:e}function iqn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Gme&&t.documentElement.namespaceURI===Gme?t.createElement(e):t.createElementNS(n,e)}}function oqn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function k1t(e){var t=NH(e);return(t.local?oqn:iqn)(t)}function lqn(){}function BSe(e){return e==null?lqn:function(){return this.querySelector(e)}}function cqn(e){typeof e!="function"&&(e=BSe(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 Hp(r,this._parents)}function uqn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function dqn(){return[]}function O1t(e){return e==null?dqn:function(){return this.querySelectorAll(e)}}function fqn(e){return function(){return uqn(e.apply(this,arguments))}}function pqn(e){typeof e=="function"?e=fqn(e):e=O1t(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 Hp(r,s)}function _1t(e){return function(){return this.matches(e)}}function C1t(e){return function(t){return t.matches(e)}}var hqn=Array.prototype.find;function mqn(e){return function(){return hqn.call(this.children,e)}}function gqn(){return this.firstElementChild}function vqn(e){return this.select(e==null?gqn:mqn(typeof e=="function"?e:C1t(e)))}var yqn=Array.prototype.filter;function bqn(){return Array.from(this.children)}function xqn(e){return function(){return yqn.call(this.children,e)}}function wqn(e){return this.selectAll(e==null?bqn:xqn(typeof e=="function"?e:C1t(e)))}function Sqn(e){typeof e!="function"&&(e=_1t(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 Hp(r,this._parents)}function E1t(e){return new Array(e.length)}function kqn(){return new Hp(this._enter||this._groups.map(E1t),this._parents)}function xB(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}xB.prototype={constructor:xB,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 Oqn(e){return function(){return e}}function _qn(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 xB(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function Cqn(e,t,n,r,s,a,i){var l,c,u=new Map,d=t.length,f=a.length,p=new Array(d),h;for(l=0;l<d;++l)(c=t[l])&&(p[l]=h=i.call(c,c.__data__,l,t)+"",u.has(h)?s[l]=c:u.set(h,c));for(l=0;l<f;++l)h=i.call(e,a[l],l,a)+"",(c=u.get(h))?(r[l]=c,c.__data__=a[l],u.delete(h)):n[l]=new xB(e,a[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(p[l])===c&&(s[l]=c)}function Eqn(e){return e.__data__}function jqn(e,t){if(!arguments.length)return Array.from(this,Eqn);var n=t?Cqn:_qn,r=this._parents,s=this._groups;typeof e!="function"&&(e=Oqn(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],p=f.length,h=Tqn(e.call(d,d&&d.__data__,u,r)),m=h.length,g=l[u]=new Array(m),y=i[u]=new Array(m),b=c[u]=new Array(p);n(d,f,g,y,b,h,t);for(var x=0,S=0,k,_;x<m;++x)if(k=g[x]){for(x>=S&&(S=x+1);!(_=y[S])&&++S<m;);k._next=_||null}}return i=new Hp(i,r),i._enter=l,i._exit=c,i}function Tqn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function Nqn(){return new Hp(this._exit||this._groups.map(E1t),this._parents)}function Iqn(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 Aqn(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,p=l[c]=new Array(f),h,m=0;m<f;++m)(h=u[m]||d[m])&&(p[m]=h);for(;c<s;++c)l[c]=n[c];return new Hp(l,this._parents)}function Rqn(){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 Pqn(e){e||(e=$qn);function t(f,p){return f&&p?e(f.__data__,p.__data__):!f-!p}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 Hp(s,this._parents).order()}function $qn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function Mqn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function Dqn(){return Array.from(this)}function Lqn(){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 Fqn(){let e=0;for(const t of this)++e;return e}function zqn(){return!this.node()}function Bqn(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 Uqn(e){return function(){this.removeAttribute(e)}}function Vqn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function qqn(e,t){return function(){this.setAttribute(e,t)}}function Hqn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function Wqn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function Zqn(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 Gqn(e,t){var n=NH(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?Vqn:Uqn:typeof t=="function"?n.local?Zqn:Wqn:n.local?Hqn:qqn)(n,t))}function j1t(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function Qqn(e){return function(){this.style.removeProperty(e)}}function Yqn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function Kqn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function Xqn(e,t,n){return arguments.length>1?this.each((t==null?Qqn:typeof t=="function"?Kqn:Yqn)(e,t,n??"")):UT(this.node(),e)}function UT(e,t){return e.style.getPropertyValue(t)||j1t(e).getComputedStyle(e,null).getPropertyValue(t)}function Jqn(e){return function(){delete this[e]}}function eHn(e,t){return function(){this[e]=t}}function tHn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function nHn(e,t){return arguments.length>1?this.each((t==null?Jqn:typeof t=="function"?tHn:eHn)(e,t)):this.node()[e]}function T1t(e){return e.trim().split(/^|\s+/)}function USe(e){return e.classList||new N1t(e)}function N1t(e){this._node=e,this._names=T1t(e.getAttribute("class")||"")}N1t.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 I1t(e,t){for(var n=USe(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function A1t(e,t){for(var n=USe(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function rHn(e){return function(){I1t(this,e)}}function sHn(e){return function(){A1t(this,e)}}function aHn(e,t){return function(){(t.apply(this,arguments)?I1t:A1t)(this,e)}}function iHn(e,t){var n=T1t(e+"");if(arguments.length<2){for(var r=USe(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?aHn:t?rHn:sHn)(n,t))}function oHn(){this.textContent=""}function lHn(e){return function(){this.textContent=e}}function cHn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function uHn(e){return arguments.length?this.each(e==null?oHn:(typeof e=="function"?cHn:lHn)(e)):this.node().textContent}function dHn(){this.innerHTML=""}function fHn(e){return function(){this.innerHTML=e}}function pHn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function hHn(e){return arguments.length?this.each(e==null?dHn:(typeof e=="function"?pHn:fHn)(e)):this.node().innerHTML}function mHn(){this.nextSibling&&this.parentNode.appendChild(this)}function gHn(){return this.each(mHn)}function vHn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function yHn(){return this.each(vHn)}function bHn(e){var t=typeof e=="function"?e:k1t(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function xHn(){return null}function wHn(e,t){var n=typeof e=="function"?e:k1t(e),r=t==null?xHn:typeof t=="function"?t:BSe(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function SHn(){var e=this.parentNode;e&&e.removeChild(this)}function kHn(){return this.each(SHn)}function OHn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function _Hn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function CHn(e){return this.select(e?_Hn:OHn)}function EHn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function jHn(e){return function(t){e.call(this,t,this.__data__)}}function THn(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 NHn(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 IHn(e,t,n){return function(){var r=this.__on,s,a=jHn(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 AHn(e,t,n){var r=THn(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?IHn:NHn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function R1t(e,t,n){var r=j1t(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 RHn(e,t){return function(){return R1t(this,e,t)}}function PHn(e,t){return function(){return R1t(this,e,t.apply(this,arguments))}}function $Hn(e,t){return this.each((typeof t=="function"?PHn:RHn)(e,t))}function*MHn(){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 P1t=[null];function Hp(e,t){this._groups=e,this._parents=t}function M3(){return new Hp([[document.documentElement]],P1t)}function DHn(){return this}Hp.prototype=M3.prototype={constructor:Hp,select:cqn,selectAll:pqn,selectChild:vqn,selectChildren:wqn,filter:Sqn,data:jqn,enter:kqn,exit:Nqn,join:Iqn,merge:Aqn,selection:DHn,order:Rqn,sort:Pqn,call:Mqn,nodes:Dqn,node:Lqn,size:Fqn,empty:zqn,each:Bqn,attr:Gqn,style:Xqn,property:nHn,classed:iHn,text:uHn,html:hHn,raise:gHn,lower:yHn,append:bHn,insert:wHn,remove:kHn,clone:CHn,datum:EHn,on:AHn,dispatch:$Hn,[Symbol.iterator]:MHn};function Sp(e){return typeof e=="string"?new Hp([[document.querySelector(e)]],[document.documentElement]):new Hp([[e]],P1t)}function LHn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function rg(e,t){if(e=LHn(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 FHn={passive:!1},kM={capture:!0,passive:!1};function Yee(e){e.stopImmediatePropagation()}function Hj(e){e.preventDefault(),e.stopImmediatePropagation()}function $1t(e){var t=e.document.documentElement,n=Sp(e).on("dragstart.drag",Hj,kM);"onselectstart"in t?n.on("selectstart.drag",Hj,kM):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function M1t(e,t){var n=e.document.documentElement,r=Sp(e).on("dragstart.drag",null);t&&(r.on("click.drag",Hj,kM),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 J6=e=>()=>e;function Qme(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}})}Qme.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function zHn(e){return!e.ctrlKey&&!e.button}function BHn(){return this.parentNode}function UHn(e,t){return t??{x:e.x,y:e.y}}function VHn(){return navigator.maxTouchPoints||"ontouchstart"in this}function D1t(){var e=zHn,t=BHn,n=UHn,r=VHn,s={},a=TH("start","drag","end"),i=0,l,c,u,d,f=0;function p(k){k.on("mousedown.drag",h).filter(r).on("touchstart.drag",y).on("touchmove.drag",b,FHn).on("touchend.drag touchcancel.drag",x).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function h(k,_){if(!(d||!e.call(this,k,_))){var C=S(this,t.call(this,k,_),k,_,"mouse");C&&(Sp(k.view).on("mousemove.drag",m,kM).on("mouseup.drag",g,kM),$1t(k.view),Yee(k),u=!1,l=k.clientX,c=k.clientY,C("start",k))}}function m(k){if(Hj(k),!u){var _=k.clientX-l,C=k.clientY-c;u=_*_+C*C>f}s.mouse("drag",k)}function g(k){Sp(k.view).on("mousemove.drag mouseup.drag",null),M1t(k.view,u),Hj(k),s.mouse("end",k)}function y(k,_){if(e.call(this,k,_)){var C=k.changedTouches,E=t.call(this,k,_),j=C.length,N,I;for(N=0;N<j;++N)(I=S(this,E,k,_,C[N].identifier,C[N]))&&(Yee(k),I("start",k,C[N]))}}function b(k){var _=k.changedTouches,C=_.length,E,j;for(E=0;E<C;++E)(j=s[_[E].identifier])&&(Hj(k),j("drag",k,_[E]))}function x(k){var _=k.changedTouches,C=_.length,E,j;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),E=0;E<C;++E)(j=s[_[E].identifier])&&(Yee(k),j("end",k,_[E]))}function S(k,_,C,E,j,N){var I=a.copy(),A=rg(N||C,_),R,L,D;if((D=n.call(k,new Qme("beforestart",{sourceEvent:C,target:p,identifier:j,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),E))!=null)return R=D.x-A[0]||0,L=D.y-A[1]||0,function B(H,F,z){var q=A,M;switch(H){case"start":s[j]=B,M=i++;break;case"end":delete s[j],--i;case"drag":A=rg(z||F,_),M=i;break}I.call(H,k,new Qme(H,{sourceEvent:F,subject:D,target:p,identifier:j,active:M,x:A[0]+R,y:A[1]+L,dx:A[0]-q[0],dy:A[1]-q[1],dispatch:I}),E)}}return p.filter=function(k){return arguments.length?(e=typeof k=="function"?k:J6(!!k),p):e},p.container=function(k){return arguments.length?(t=typeof k=="function"?k:J6(k),p):t},p.subject=function(k){return arguments.length?(n=typeof k=="function"?k:J6(k),p):n},p.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:J6(!!k),p):r},p.on=function(){var k=a.on.apply(a,arguments);return k===a?p:k},p.clickDistance=function(k){return arguments.length?(f=(k=+k)*k,p):Math.sqrt(f)},p}function VSe(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function L1t(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function D3(){}var OM=.7,wB=1/OM,Wj="\\s*([+-]?\\d+)\\s*",_M="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",ry="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",qHn=/^#([0-9a-f]{3,8})$/,HHn=new RegExp(`^rgb\\(${Wj},${Wj},${Wj}\\)$`),WHn=new RegExp(`^rgb\\(${ry},${ry},${ry}\\)$`),ZHn=new RegExp(`^rgba\\(${Wj},${Wj},${Wj},${_M}\\)$`),GHn=new RegExp(`^rgba\\(${ry},${ry},${ry},${_M}\\)$`),QHn=new RegExp(`^hsl\\(${_M},${ry},${ry}\\)$`),YHn=new RegExp(`^hsla\\(${_M},${ry},${ry},${_M}\\)$`),E8e={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};VSe(D3,VO,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:j8e,formatHex:j8e,formatHex8:KHn,formatHsl:XHn,formatRgb:T8e,toString:T8e});function j8e(){return this.rgb().formatHex()}function KHn(){return this.rgb().formatHex8()}function XHn(){return F1t(this).formatHsl()}function T8e(){return this.rgb().formatRgb()}function VO(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=qHn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?N8e(t):n===3?new pf(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?eF(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?eF(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=HHn.exec(e))?new pf(t[1],t[2],t[3],1):(t=WHn.exec(e))?new pf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=ZHn.exec(e))?eF(t[1],t[2],t[3],t[4]):(t=GHn.exec(e))?eF(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=QHn.exec(e))?R8e(t[1],t[2]/100,t[3]/100,1):(t=YHn.exec(e))?R8e(t[1],t[2]/100,t[3]/100,t[4]):E8e.hasOwnProperty(e)?N8e(E8e[e]):e==="transparent"?new pf(NaN,NaN,NaN,0):null}function N8e(e){return new pf(e>>16&255,e>>8&255,e&255,1)}function eF(e,t,n,r){return r<=0&&(e=t=n=NaN),new pf(e,t,n,r)}function JHn(e){return e instanceof D3||(e=VO(e)),e?(e=e.rgb(),new pf(e.r,e.g,e.b,e.opacity)):new pf}function Yme(e,t,n,r){return arguments.length===1?JHn(e):new pf(e,t,n,r??1)}function pf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}VSe(pf,Yme,L1t(D3,{brighter(e){return e=e==null?wB:Math.pow(wB,e),new pf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?OM:Math.pow(OM,e),new pf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new pf(Kk(this.r),Kk(this.g),Kk(this.b),SB(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:I8e,formatHex:I8e,formatHex8:eWn,formatRgb:A8e,toString:A8e}));function I8e(){return`#${Ak(this.r)}${Ak(this.g)}${Ak(this.b)}`}function eWn(){return`#${Ak(this.r)}${Ak(this.g)}${Ak(this.b)}${Ak((isNaN(this.opacity)?1:this.opacity)*255)}`}function A8e(){const e=SB(this.opacity);return`${e===1?"rgb(":"rgba("}${Kk(this.r)}, ${Kk(this.g)}, ${Kk(this.b)}${e===1?")":`, ${e})`}`}function SB(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Kk(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Ak(e){return e=Kk(e),(e<16?"0":"")+e.toString(16)}function R8e(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new ug(e,t,n,r)}function F1t(e){if(e instanceof ug)return new ug(e.h,e.s,e.l,e.opacity);if(e instanceof D3||(e=VO(e)),!e)return new ug;if(e instanceof ug)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 ug(i,l,c,e.opacity)}function tWn(e,t,n,r){return arguments.length===1?F1t(e):new ug(e,t,n,r??1)}function ug(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}VSe(ug,tWn,L1t(D3,{brighter(e){return e=e==null?wB:Math.pow(wB,e),new ug(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?OM:Math.pow(OM,e),new ug(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 pf(Kee(e>=240?e-240:e+120,s,r),Kee(e,s,r),Kee(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new ug(P8e(this.h),tF(this.s),tF(this.l),SB(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=SB(this.opacity);return`${e===1?"hsl(":"hsla("}${P8e(this.h)}, ${tF(this.s)*100}%, ${tF(this.l)*100}%${e===1?")":`, ${e})`}`}}));function P8e(e){return e=(e||0)%360,e<0?e+360:e}function tF(e){return Math.max(0,Math.min(1,e||0))}function Kee(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 qSe=e=>()=>e;function nWn(e,t){return function(n){return e+n*t}}function rWn(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 sWn(e){return(e=+e)==1?z1t:function(t,n){return n-t?rWn(t,n,e):qSe(isNaN(t)?n:t)}}function z1t(e,t){var n=t-e;return n?nWn(e,n):qSe(isNaN(e)?t:e)}const kB=(function e(t){var n=sWn(t);function r(s,a){var i=n((s=Yme(s)).r,(a=Yme(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=z1t(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 aWn(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 iWn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function oWn(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]=lx(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 lWn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function ag(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function cWn(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]=lx(e[s],t[s]):r[s]=t[s];return function(a){for(s in n)r[s]=n[s](a);return r}}var Kme=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Xee=new RegExp(Kme.source,"g");function uWn(e){return function(){return e}}function dWn(e){return function(t){return e(t)+""}}function B1t(e,t){var n=Kme.lastIndex=Xee.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Kme.exec(e))&&(s=Xee.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:ag(r,s)})),n=Xee.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?dWn(c[0].x):uWn(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 lx(e,t){var n=typeof t,r;return t==null||n==="boolean"?qSe(t):(n==="number"?ag:n==="string"?(r=VO(t))?(t=r,kB):B1t:t instanceof VO?kB:t instanceof Date?lWn:iWn(t)?aWn:Array.isArray(t)?oWn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?cWn:ag)(e,t)}function HSe(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var $8e=180/Math.PI,Xme={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function U1t(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)*$8e,skewX:Math.atan(c)*$8e,scaleX:i,scaleY:l}}var nF;function fWn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Xme:U1t(t.a,t.b,t.c,t.d,t.e,t.f)}function pWn(e){return e==null||(nF||(nF=document.createElementNS("http://www.w3.org/2000/svg","g")),nF.setAttribute("transform",e),!(e=nF.transform.baseVal.consolidate()))?Xme:(e=e.matrix,U1t(e.a,e.b,e.c,e.d,e.e,e.f))}function V1t(e,t,n,r){function s(u){return u.length?u.pop()+" ":""}function a(u,d,f,p,h,m){if(u!==f||d!==p){var g=h.push("translate(",null,t,null,n);m.push({i:g-4,x:ag(u,f)},{i:g-2,x:ag(d,p)})}else(f||p)&&h.push("translate("+f+t+p+n)}function i(u,d,f,p){u!==d?(u-d>180?d+=360:d-u>180&&(u+=360),p.push({i:f.push(s(f)+"rotate(",null,r)-2,x:ag(u,d)})):d&&f.push(s(f)+"rotate("+d+r)}function l(u,d,f,p){u!==d?p.push({i:f.push(s(f)+"skewX(",null,r)-2,x:ag(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,p,h,m){if(u!==f||d!==p){var g=h.push(s(h)+"scale(",null,",",null,")");m.push({i:g-4,x:ag(u,f)},{i:g-2,x:ag(d,p)})}else(f!==1||p!==1)&&h.push(s(h)+"scale("+f+","+p+")")}return function(u,d){var f=[],p=[];return u=e(u),d=e(d),a(u.translateX,u.translateY,d.translateX,d.translateY,f,p),i(u.rotate,d.rotate,f,p),l(u.skewX,d.skewX,f,p),c(u.scaleX,u.scaleY,d.scaleX,d.scaleY,f,p),u=d=null,function(h){for(var m=-1,g=p.length,y;++m<g;)f[(y=p[m]).i]=y.x(h);return f.join("")}}}var hWn=V1t(fWn,"px, ","px)","deg)"),mWn=V1t(pWn,", ",")",")"),gWn=1e-12;function M8e(e){return((e=Math.exp(e))+1/e)/2}function vWn(e){return((e=Math.exp(e))-1/e)/2}function yWn(e){return((e=Math.exp(2*e))-1)/(e+1)}const I8=(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],p=i[2],h=d-l,m=f-c,g=h*h+m*m,y,b;if(g<gWn)b=Math.log(p/u)/t,y=function(E){return[l+E*h,c+E*m,u*Math.exp(t*E*b)]};else{var x=Math.sqrt(g),S=(p*p-u*u+r*g)/(2*u*n*x),k=(p*p-u*u-r*g)/(2*p*n*x),_=Math.log(Math.sqrt(S*S+1)-S),C=Math.log(Math.sqrt(k*k+1)-k);b=(C-_)/t,y=function(E){var j=E*b,N=M8e(_),I=u/(n*x)*(N*yWn(t*j+_)-vWn(_));return[l+I*h,c+I*m,u*N/M8e(t*j+_)]}}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 bWn(e,t){t===void 0&&(t=e,e=lx);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 VT=0,$P=0,bR=0,q1t=1e3,OB,MP,_B=0,qO=0,IH=0,CM=typeof performance=="object"&&performance.now?performance:Date,H1t=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function WSe(){return qO||(H1t(xWn),qO=CM.now()+IH)}function xWn(){qO=0}function CB(){this._call=this._time=this._next=null}CB.prototype=W1t.prototype={constructor:CB,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?WSe():+n)+(t==null?0:+t),!this._next&&MP!==this&&(MP?MP._next=this:OB=this,MP=this),this._call=e,this._time=n,Jme()},stop:function(){this._call&&(this._call=null,this._time=1/0,Jme())}};function W1t(e,t,n){var r=new CB;return r.restart(e,t,n),r}function wWn(){WSe(),++VT;for(var e=OB,t;e;)(t=qO-e._time)>=0&&e._call.call(void 0,t),e=e._next;--VT}function D8e(){qO=(_B=CM.now())+IH,VT=$P=0;try{wWn()}finally{VT=0,kWn(),qO=0}}function SWn(){var e=CM.now(),t=e-_B;t>q1t&&(IH-=t,_B=e)}function kWn(){for(var e,t=OB,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:OB=n);MP=e,Jme(r)}function Jme(e){if(!VT){$P&&($P=clearTimeout($P));var t=e-qO;t>24?(e<1/0&&($P=setTimeout(D8e,e-CM.now()-IH)),bR&&(bR=clearInterval(bR))):(bR||(_B=CM.now(),bR=setInterval(SWn,q1t)),VT=1,H1t(D8e))}}function L8e(e,t,n){var r=new CB;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var OWn=TH("start","end","cancel","interrupt"),_Wn=[],Z1t=0,F8e=1,ege=2,A8=3,z8e=4,tge=5,R8=6;function AH(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;CWn(e,n,{name:t,index:r,group:s,on:OWn,tween:_Wn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:Z1t})}function ZSe(e,t){var n=Hg(e,t);if(n.state>Z1t)throw new Error("too late; already scheduled");return n}function zy(e,t){var n=Hg(e,t);if(n.state>A8)throw new Error("too late; already running");return n}function Hg(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function CWn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=W1t(a,0,n.time);function a(u){n.state=F8e,n.timer.restart(i,n.delay,n.time),n.delay<=u&&i(u-n.delay)}function i(u){var d,f,p,h;if(n.state!==F8e)return c();for(d in r)if(h=r[d],h.name===n.name){if(h.state===A8)return L8e(i);h.state===z8e?(h.state=R8,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete r[d]):+d<t&&(h.state=R8,h.timer.stop(),h.on.call("cancel",e,e.__data__,h.index,h.group),delete r[d])}if(L8e(function(){n.state===A8&&(n.state=z8e,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=ege,n.on.call("start",e,e.__data__,n.index,n.group),n.state===ege){for(n.state=A8,s=new Array(p=n.tween.length),d=0,f=-1;d<p;++d)(h=n.tween[d].value.call(e,e.__data__,n.index,n.group))&&(s[++f]=h);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=tge,1),f=-1,p=s.length;++f<p;)s[f].call(e,d);n.state===tge&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=R8,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function P8(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>ege&&r.state<tge,r.state=R8,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function EWn(e){return this.each(function(){P8(this,e)})}function jWn(e,t){var n,r;return function(){var s=zy(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 TWn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=zy(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 NWn(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Hg(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?jWn:TWn)(n,e,t))}function GSe(e,t,n){var r=e._id;return e.each(function(){var s=zy(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return Hg(s,r).value[t]}}function G1t(e,t){var n;return(typeof t=="number"?ag:t instanceof VO?kB:(n=VO(t))?(t=n,kB):B1t)(e,t)}function IWn(e){return function(){this.removeAttribute(e)}}function AWn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function RWn(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 PWn(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 $Wn(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 MWn(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 DWn(e,t){var n=NH(e),r=n==="transform"?mWn:G1t;return this.attrTween(e,typeof t=="function"?(n.local?MWn:$Wn)(n,r,GSe(this,"attr."+e,t)):t==null?(n.local?AWn:IWn)(n):(n.local?PWn:RWn)(n,r,t))}function LWn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function FWn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function zWn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&FWn(e,a)),n}return s._value=t,s}function BWn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&LWn(e,a)),n}return s._value=t,s}function UWn(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=NH(e);return this.tween(n,(r.local?zWn:BWn)(r,t))}function VWn(e,t){return function(){ZSe(this,e).delay=+t.apply(this,arguments)}}function qWn(e,t){return t=+t,function(){ZSe(this,e).delay=t}}function HWn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?VWn:qWn)(t,e)):Hg(this.node(),t).delay}function WWn(e,t){return function(){zy(this,e).duration=+t.apply(this,arguments)}}function ZWn(e,t){return t=+t,function(){zy(this,e).duration=t}}function GWn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?WWn:ZWn)(t,e)):Hg(this.node(),t).duration}function QWn(e,t){if(typeof t!="function")throw new Error;return function(){zy(this,e).ease=t}}function YWn(e){var t=this._id;return arguments.length?this.each(QWn(t,e)):Hg(this.node(),t).ease}function KWn(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;zy(this,e).ease=n}}function XWn(e){if(typeof e!="function")throw new Error;return this.each(KWn(this._id,e))}function JWn(e){typeof e!="function"&&(e=_1t(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 jx(r,this._parents,this._name,this._id)}function eZn(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),p,h=0;h<d;++h)(p=c[h]||u[h])&&(f[h]=p);for(;l<r;++l)i[l]=t[l];return new jx(i,this._parents,this._name,this._id)}function tZn(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 nZn(e,t,n){var r,s,a=tZn(t)?ZSe:zy;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function rZn(e,t){var n=this._id;return arguments.length<2?Hg(this.node(),n).on.on(e):this.each(nZn(n,e,t))}function sZn(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function aZn(){return this.on("end.remove",sZn(this._id))}function iZn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=BSe(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,p=0;p<c;++p)(d=l[p])&&(f=e.call(d,d.__data__,p,l))&&("__data__"in d&&(f.__data__=d.__data__),u[p]=f,AH(u[p],t,n,p,u,Hg(d,n)));return new jx(a,this._parents,t,n)}function oZn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=O1t(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 p=e.call(d,d.__data__,f,c),h,m=Hg(d,n),g=0,y=p.length;g<y;++g)(h=p[g])&&AH(h,t,n,g,p,m);a.push(p),i.push(d)}return new jx(a,i,t,n)}var lZn=M3.prototype.constructor;function cZn(){return new lZn(this._groups,this._parents)}function uZn(e,t){var n,r,s;return function(){var a=UT(this,e),i=(this.style.removeProperty(e),UT(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function Q1t(e){return function(){this.style.removeProperty(e)}}function dZn(e,t,n){var r,s=n+"",a;return function(){var i=UT(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function fZn(e,t,n){var r,s,a;return function(){var i=UT(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),UT(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function pZn(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=zy(this,e),u=c.on,d=c.value[a]==null?l||(l=Q1t(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function hZn(e,t,n){var r=(e+="")=="transform"?hWn:G1t;return t==null?this.styleTween(e,uZn(e,r)).on("end.style."+e,Q1t(e)):typeof t=="function"?this.styleTween(e,fZn(e,r,GSe(this,"style."+e,t))).each(pZn(this._id,e)):this.styleTween(e,dZn(e,r,t),n).on("end.style."+e,null)}function mZn(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function gZn(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&mZn(e,i,n)),r}return a._value=t,a}function vZn(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,gZn(e,t,n??""))}function yZn(e){return function(){this.textContent=e}}function bZn(e){return function(){var t=e(this);this.textContent=t??""}}function xZn(e){return this.tween("text",typeof e=="function"?bZn(GSe(this,"text",e)):yZn(e==null?"":e+""))}function wZn(e){return function(t){this.textContent=e.call(this,t)}}function SZn(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&wZn(s)),t}return r._value=e,r}function kZn(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,SZn(e))}function OZn(){for(var e=this._name,t=this._id,n=Y1t(),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=Hg(c,t);AH(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new jx(r,this._parents,e,n)}function _Zn(){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=zy(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 CZn=0;function jx(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function Y1t(){return++CZn}var yb=M3.prototype;jx.prototype={constructor:jx,select:iZn,selectAll:oZn,selectChild:yb.selectChild,selectChildren:yb.selectChildren,filter:JWn,merge:eZn,selection:cZn,transition:OZn,call:yb.call,nodes:yb.nodes,node:yb.node,size:yb.size,empty:yb.empty,each:yb.each,on:rZn,attr:DWn,attrTween:UWn,style:hZn,styleTween:vZn,text:xZn,textTween:kZn,remove:aZn,tween:NWn,delay:HWn,duration:GWn,ease:YWn,easeVarying:XWn,end:_Zn,[Symbol.iterator]:yb[Symbol.iterator]};function EZn(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var jZn={time:null,delay:0,duration:250,ease:EZn};function TZn(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 NZn(e){var t,n;e instanceof jx?(t=e._id,e=e._name):(t=Y1t(),(n=jZn).time=WSe(),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])&&AH(c,e,t,u,i,n||TZn(c,t));return new jx(r,this._parents,e,t)}M3.prototype.interrupt=EWn;M3.prototype.transition=NZn;const rF=e=>()=>e;function IZn(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 Kb(e,t,n){this.k=e,this.x=t,this.y=n}Kb.prototype={constructor:Kb,scale:function(e){return e===1?this:new Kb(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new Kb(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 RH=new Kb(1,0,0);K1t.prototype=Kb.prototype;function K1t(e){for(;!e.__zoom;)if(!(e=e.parentNode))return RH;return e.__zoom}function Jee(e){e.stopImmediatePropagation()}function xR(e){e.preventDefault(),e.stopImmediatePropagation()}function AZn(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function RZn(){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 B8e(){return this.__zoom||RH}function PZn(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function $Zn(){return navigator.maxTouchPoints||"ontouchstart"in this}function MZn(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 X1t(){var e=AZn,t=RZn,n=MZn,r=PZn,s=$Zn,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=I8,u=TH("start","zoom","end"),d,f,p,h=500,m=150,g=0,y=10;function b(D){D.property("__zoom",B8e).on("wheel.zoom",j,{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,F){var z=D.selection?D.selection():D;z.property("__zoom",B8e),D!==z?_(D,B,H,F):z.interrupt().each(function(){C(this,arguments).event(F).start().zoom(null,typeof B=="function"?B.apply(this,arguments):B).end()})},b.scaleBy=function(D,B,H,F){b.scaleTo(D,function(){var z=this.__zoom.k,q=typeof B=="function"?B.apply(this,arguments):B;return z*q},H,F)},b.scaleTo=function(D,B,H,F){b.transform(D,function(){var z=t.apply(this,arguments),q=this.__zoom,M=H==null?k(z):typeof H=="function"?H.apply(this,arguments):H,G=q.invert(M),V=typeof B=="function"?B.apply(this,arguments):B;return n(S(x(q,V),M,G),z,i)},H,F)},b.translateBy=function(D,B,H,F){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,F)},b.translateTo=function(D,B,H,F,z){b.transform(D,function(){var q=t.apply(this,arguments),M=this.__zoom,G=F==null?k(q):typeof F=="function"?F.apply(this,arguments):F;return n(RH.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),q,i)},F,z)};function x(D,B){return B=Math.max(a[0],Math.min(a[1],B)),B===D.k?D:new Kb(B,D.x,D.y)}function S(D,B,H){var F=B[0]-H[0]*D.k,z=B[1]-H[1]*D.k;return F===D.x&&z===D.y?D:new Kb(D.k,F,z)}function k(D){return[(+D[0][0]+ +D[1][0])/2,(+D[0][1]+ +D[1][1])/2]}function _(D,B,H,F){D.on("start.zoom",function(){C(this,arguments).event(F).start()}).on("interrupt.zoom end.zoom",function(){C(this,arguments).event(F).end()}).tween("zoom",function(){var z=this,q=arguments,M=C(z,q).event(F),G=t.apply(z,q),V=H==null?k(G):typeof H=="function"?H.apply(z,q):H,$=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),U=z.__zoom,Z=typeof B=="function"?B.apply(z,q):B,K=c(U.invert(V).concat($/U.k),Z.invert(V).concat($/Z.k));return function(te){if(te===1)te=Z;else{var ee=K(te),J=$/ee[2];te=new Kb(J,V[0]-ee[0]*J,V[1]-ee[1]*J)}M.zoom(null,te)}})}function C(D,B,H){return!H&&D.__zooming||new E(D,B)}function E(D,B){this.that=D,this.args=B,this.active=0,this.sourceEvent=null,this.extent=t.apply(D,B),this.taps=0}E.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=Sp(this.that).datum();u.call(D,this.that,new IZn(D,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),B)}};function j(D,...B){if(!e.apply(this,arguments))return;var H=C(this,B).event(D),F=this.__zoom,z=Math.max(a[0],Math.min(a[1],F.k*Math.pow(2,r.apply(this,arguments)))),q=rg(D);if(H.wheel)(H.mouse[0][0]!==q[0]||H.mouse[0][1]!==q[1])&&(H.mouse[1]=F.invert(H.mouse[0]=q)),clearTimeout(H.wheel);else{if(F.k===z)return;H.mouse=[q,F.invert(q)],P8(this),H.start()}xR(D),H.wheel=setTimeout(M,m),H.zoom("mouse",n(S(x(F,z),H.mouse[0],H.mouse[1]),H.extent,i));function M(){H.wheel=null,H.end()}}function N(D,...B){if(p||!e.apply(this,arguments))return;var H=D.currentTarget,F=C(this,B,!0).event(D),z=Sp(D.view).on("mousemove.zoom",V,!0).on("mouseup.zoom",$,!0),q=rg(D,H),M=D.clientX,G=D.clientY;$1t(D.view),Jee(D),F.mouse=[q,this.__zoom.invert(q)],P8(this),F.start();function V(U){if(xR(U),!F.moved){var Z=U.clientX-M,K=U.clientY-G;F.moved=Z*Z+K*K>g}F.event(U).zoom("mouse",n(S(F.that.__zoom,F.mouse[0]=rg(U,H),F.mouse[1]),F.extent,i))}function $(U){z.on("mousemove.zoom mouseup.zoom",null),M1t(U.view,F.moved),xR(U),F.event(U).end()}}function I(D,...B){if(e.apply(this,arguments)){var H=this.__zoom,F=rg(D.changedTouches?D.changedTouches[0]:D,this),z=H.invert(F),q=H.k*(D.shiftKey?.5:2),M=n(S(x(H,q),F,z),t.apply(this,B),i);xR(D),l>0?Sp(this).transition().duration(l).call(_,M,F,D):Sp(this).call(b.transform,M,F,D)}}function A(D,...B){if(e.apply(this,arguments)){var H=D.touches,F=H.length,z=C(this,B,D.changedTouches.length===F).event(D),q,M,G,V;for(Jee(D),M=0;M<F;++M)G=H[M],V=rg(G,this),V=[V,this.__zoom.invert(V),G.identifier],z.touch0?!z.touch1&&z.touch0[2]!==V[2]&&(z.touch1=V,z.taps=0):(z.touch0=V,q=!0,z.taps=1+!!d);d&&(d=clearTimeout(d)),q&&(z.taps<2&&(f=V[0],d=setTimeout(function(){d=null},h)),P8(this),z.start())}}function R(D,...B){if(this.__zooming){var H=C(this,B).event(D),F=D.changedTouches,z=F.length,q,M,G,V;for(xR(D),q=0;q<z;++q)M=F[q],G=rg(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 $=H.touch0[0],U=H.touch0[1],Z=H.touch1[0],K=H.touch1[1],te=(te=Z[0]-$[0])*te+(te=Z[1]-$[1])*te,ee=(ee=K[0]-U[0])*ee+(ee=K[1]-U[1])*ee;M=x(M,Math.sqrt(te/ee)),G=[($[0]+Z[0])/2,($[1]+Z[1])/2],V=[(U[0]+K[0])/2,(U[1]+K[1])/2]}else if(H.touch0)G=H.touch0[0],V=H.touch0[1];else return;H.zoom("touch",n(S(M,G,V),H.extent,i))}}function L(D,...B){if(this.__zooming){var H=C(this,B).event(D),F=D.changedTouches,z=F.length,q,M;for(Jee(D),p&&clearTimeout(p),p=setTimeout(function(){p=null},h),q=0;q<z;++q)M=F[q],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=rg(M,this),Math.hypot(f[0]-M[0],f[1]-M[1])<y)){var G=Sp(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(D){return arguments.length?(r=typeof D=="function"?D:rF(+D),b):r},b.filter=function(D){return arguments.length?(e=typeof D=="function"?D:rF(!!D),b):e},b.touchable=function(D){return arguments.length?(s=typeof D=="function"?D:rF(!!D),b):s},b.extent=function(D){return arguments.length?(t=typeof D=="function"?D:rF([[+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?(g=(D=+D)*D,b):Math.sqrt(g)},b.tapDistance=function(D){return arguments.length?(y=+D,b):y},b}const by={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."},EM=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],J1t=["Enter"," ","Escape"],eSt={"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 qT;(function(e){e.Strict="strict",e.Loose="loose"})(qT||(qT={}));var Xk;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(Xk||(Xk={}));var jM;(function(e){e.Partial="partial",e.Full="full"})(jM||(jM={}));const tSt={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var uw;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(uw||(uw={}));var TM;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(TM||(TM={}));var sr;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(sr||(sr={}));const U8e={[sr.Left]:sr.Right,[sr.Right]:sr.Left,[sr.Top]:sr.Bottom,[sr.Bottom]:sr.Top};function nSt(e){return e===null?null:e?"valid":"invalid"}const rSt=e=>"id"in e&&"source"in e&&"target"in e,DZn=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),QSe=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),L3=(e,t=[0,0])=>{const{width:n,height:r}=Kx(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},LZn=(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):QSe(s)?s:t.nodeLookup.get(s.id));const l=i?EB(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return PH(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return $H(n)},F3=(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=PH(n,EB(s)),r=!0)}),r?$H(n):{x:0,y:0,width:0,height:0}},YSe=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...B3(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:p=!1}=u;if(i&&!f||p)continue;const h=d.width??u.width??u.initialWidth??null,m=d.height??u.height??u.initialHeight??null,g=NM(l,WT(u)),y=(h??0)*(m??0),b=a&&g>0;(!u.internals.handleBounds||b||g>=y||u.dragging)&&c.push(u)}return c},FZn=(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 zZn(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 BZn({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=zZn(e,i),c=F3(l),u=KSe(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 sSt({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",by.error005());else{const h=l.measured.width,m=l.measured.height;h&&m&&(f=[[c,u],[c+h,u+m]])}else l&&ZT(i.extent)&&(f=[[i.extent[0][0]+c,i.extent[0][1]+u],[i.extent[1][0]+c,i.extent[1][1]+u]]);const p=ZT(f)?HO(t,f,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&a?.("015",by.error015()),{position:{x:p.x-c+(i.measured.width??0)*d[0],y:p.y-u+(i.measured.height??0)*d[1]},positionAbsolute:p}}async function UZn({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const a=new Set(e.map(p=>p.id)),i=[];for(const p of n){if(p.deletable===!1)continue;const h=a.has(p.id),m=!h&&p.parentId&&i.find(g=>g.id===p.parentId);(h||m)&&i.push(p)}const l=new Set(t.map(p=>p.id)),c=r.filter(p=>p.deletable!==!1),d=FZn(i,c);for(const p of c)l.has(p.id)&&!d.find(m=>m.id===p.id)&&d.push(p);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 HT=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),HO=(e={x:0,y:0},t,n)=>({x:HT(e.x,t[0][0],t[1][0]-(n?.width??0)),y:HT(e.y,t[0][1],t[1][1]-(n?.height??0))});function aSt(e,t,n){const{width:r,height:s}=Kx(n),{x:a,y:i}=n.internals.positionAbsolute;return HO(e,[[a,i],[a+r,i+s]],t)}const V8e=(e,t,n)=>e<t?HT(Math.abs(e-t),1,t)/t:e>n?-HT(Math.abs(e-n),1,t)/t:0,iSt=(e,t,n=15,r=40)=>{const s=V8e(e.x,r,t.width-r)*n,a=V8e(e.y,r,t.height-r)*n;return[s,a]},PH=(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)}),nge=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),$H=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),WT=(e,t=[0,0])=>{const{x:n,y:r}=QSe(e)?e.internals.positionAbsolute:L3(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}},EB=(e,t=[0,0])=>{const{x:n,y:r}=QSe(e)?e.internals.positionAbsolute:L3(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)}},oSt=(e,t)=>$H(PH(nge(e),nge(t))),NM=(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)},q8e=e=>gg(e.width)&&gg(e.height)&&gg(e.x)&&gg(e.y),gg=e=>!isNaN(e)&&isFinite(e),VZn=(e,t)=>{},z3=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),B3=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?z3(l,i):l},jB=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function iE(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 qZn(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=iE(e,n),s=iE(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=iE(e.top??e.y??0,n),s=iE(e.bottom??e.y??0,n),a=iE(e.left??e.x??0,t),i=iE(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 HZn(e,t,n,r,s,a){const{x:i,y:l}=jB(e,[t,n,r]),{x:c,y:u}=jB({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 KSe=(e,t,n,r,s,a)=>{const i=qZn(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=HT(u,r,s),f=e.x+e.width/2,p=e.y+e.height/2,h=t/2-f*d,m=n/2-p*d,g=HZn(e,h,m,d,t,n),y={left:Math.min(g.left-i.left,0),top:Math.min(g.top-i.top,0),right:Math.min(g.right-i.right,0),bottom:Math.min(g.bottom-i.bottom,0)};return{x:h-y.left+y.right,y:m-y.top+y.bottom,zoom:d}},IM=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function ZT(e){return e!=null&&e!=="parent"}function Kx(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function lSt(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function cSt(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 H8e(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function WZn(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function ZZn(e){return{...eSt,...e||{}}}function h2(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=vg(e),l=B3({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?z3(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const XSe=e=>({width:e.offsetWidth,height:e.offsetHeight}),uSt=e=>e?.getRootNode?.()||window?.document,GZn=["INPUT","SELECT","TEXTAREA"];function dSt(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:GZn.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const fSt=e=>"clientX"in e,vg=(e,t)=>{const n=fSt(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)}},W8e=(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,...XSe(i)}})};function pSt({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 sF(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function Z8e({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case sr.Left:return[t-sF(t-r,a),n];case sr.Right:return[t+sF(r-t,a),n];case sr.Top:return[t,n-sF(n-s,a)];case sr.Bottom:return[t,n+sF(s-n,a)]}}function JSe({sourceX:e,sourceY:t,sourcePosition:n=sr.Bottom,targetX:r,targetY:s,targetPosition:a=sr.Top,curvature:i=.25}){const[l,c]=Z8e({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=Z8e({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,p,h,m]=pSt({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,p,h,m]}function hSt({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 QZn({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 YZn({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=PH(EB(e),EB(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 NM(i,$H(a))>0}const KZn=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,XZn=(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)),JZn=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||KZn;let s;return rSt(e)?s={...e}:s={...e,id:r(e)},XZn(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function mSt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=hSt({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const G8e={[sr.Left]:{x:-1,y:0},[sr.Right]:{x:1,y:0},[sr.Top]:{x:0,y:-1},[sr.Bottom]:{x:0,y:1}},eGn=({source:e,sourcePosition:t=sr.Bottom,target:n})=>t===sr.Left||t===sr.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},Q8e=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function tGn({source:e,sourcePosition:t=sr.Bottom,target:n,targetPosition:r=sr.Top,center:s,offset:a,stepPosition:i}){const l=G8e[t],c=G8e[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=eGn({source:u,sourcePosition:t,target:d}),p=f.x!==0?"x":"y",h=f[p];let m=[],g,y;const b={x:0,y:0},x={x:0,y:0},[,,S,k]=hSt({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[p]*c[p]===-1){p==="x"?(g=s.x??u.x+(d.x-u.x)*i,y=s.y??(u.y+d.y)/2):(g=s.x??(u.x+d.x)/2,y=s.y??u.y+(d.y-u.y)*i);const j=[{x:g,y:u.y},{x:g,y:d.y}],N=[{x:u.x,y},{x:d.x,y}];l[p]===h?m=p==="x"?j:N:m=p==="x"?N:j}else{const j=[{x:u.x,y:d.y}],N=[{x:d.x,y:u.y}];if(p==="x"?m=l.x===h?N:j:m=l.y===h?j:N,t===r){const D=Math.abs(e[p]-n[p]);if(D<=a){const B=Math.min(a-1,a-D);l[p]===h?b[p]=(u[p]>e[p]?-1:1)*B:x[p]=(d[p]>n[p]?-1:1)*B}}if(t!==r){const D=p==="x"?"y":"x",B=l[p]===c[D],H=u[D]>d[D],F=u[D]<d[D];(l[p]===1&&(!B&&H||B&&F)||l[p]!==1&&(!B&&F||B&&H))&&(m=p==="x"?j: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?(g=(I.x+A.x)/2,y=m[0].y):(g=m[0].x,y=(I.y+A.y)/2)}const _={x:u.x+b.x,y:u.y+b.y},C={x:d.x+x.x,y:d.y+x.y};return[[e,..._.x!==m[0].x||_.y!==m[0].y?[_]:[],...m,...C.x!==m[m.length-1].x||C.y!==m[m.length-1].y?[C]:[],n],g,y,S,k]}function nGn(e,t,n,r){const s=Math.min(Q8e(e,t)/2,Q8e(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 rge({sourceX:e,sourceY:t,sourcePosition:n=sr.Bottom,targetX:r,targetY:s,targetPosition:a=sr.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,p,h,m,g]=tGn({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+=nGn(f[b-1],f[b],f[b+1],i);return y+=`L${f[f.length-1].x} ${f[f.length-1].y}`,[y,p,h,m,g]}function Y8e(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function rGn(e){const{sourceNode:t,targetNode:n}=e;if(!Y8e(t)||!Y8e(n))return null;const r=t.internals.handleBounds||K8e(t.handles),s=n.internals.handleBounds||K8e(n.handles),a=X8e(r?.source??[],e.sourceHandle),i=X8e(e.connectionMode===qT.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!a||!i)return e.onError?.("008",by.error008(a?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=a?.position||sr.Bottom,c=i?.position||sr.Top,u=WO(t,a,l),d=WO(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function K8e(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 WO(e,t,n=sr.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??Kx(e);if(r)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case sr.Top:return{x:s+i/2,y:a};case sr.Right:return{x:s+i,y:a+l/2};case sr.Bottom:return{x:s+i/2,y:a+l};case sr.Left:return{x:s,y:a+l/2}}}function X8e(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function sge(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function sGn(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=sge(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 gSt=1e3,aGn=10,eke={nodeOrigin:[0,0],nodeExtent:EM,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},iGn={...eke,checkEquality:!0};function tke(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function oGn(e,t,n){const r=tke(eke,n);for(const s of e.values())if(s.parentId)rke(s,e,t,r);else{const a=L3(s,r.nodeOrigin),i=ZT(s.extent)?s.extent:r.nodeExtent,l=HO(a,i,Kx(s));s.internals.positionAbsolute=l}}function lGn(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 nke(e){return e==="manual"}function age(e,t,n,r={}){const s=tke(iGn,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!nke(s.zIndexMode)?gSt: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 p=L3(d,s.nodeOrigin),h=ZT(d.extent)?d.extent:s.nodeExtent,m=HO(p,h,Kx(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:lGn(d,f),z:vSt(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&&rke(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function cGn(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 rke(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=tke(eke,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}cGn(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*aGn),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!nke(c)?gSt:0,{x:p,y:h,z:m}=uGn(e,d,i,l,f,c),{positionAbsolute:g}=e.internals,y=p!==g.x||h!==g.y;(y||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:p,y:h}:g,z:m}})}function vSt(e,t,n){const r=gg(e.zIndex)?e.zIndex:0;return nke(n)?r:r+(e.selected?t:0)}function uGn(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=Kx(e),u=L3(e,n),d=ZT(e.extent)?HO(u,e.extent,c):u;let f=HO({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=aSt(f,c,t));const p=vSt(e,s,a),h=t.internals.z??0;return{x:f.x,y:f.y,z:h>=p?h+1:p}}function ske(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??WT(l),u=oSt(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=Kx(l),f=l.origin??r,p=i.x<u.x?Math.round(Math.abs(u.x-i.x)):0,h=i.y<u.y?Math.round(Math.abs(u.y-i.y)):0,m=Math.max(d.width,Math.round(i.width)),g=Math.max(d.height,Math.round(i.height)),y=(m-d.width)*f[0],b=(g-d.height)*f[1];(p>0||h>0||y||b)&&(s.push({id:c,type:"position",position:{x:l.position.x-p+y,y:l.position.y-h+b}}),n.get(c)?.forEach(x=>{e.some(S=>S.id===x.id)||s.push({id:x.id,type:"position",position:{x:x.position.x+p,y:x.position.y+h}})})),(d.width<i.width||d.height<i.height||p||h)&&s.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:m+(p?f[0]*p-y:0),height:g+(h?f[1]*h-b:0)}})}),s}function dGn(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),p=[];for(const h of e.values()){const m=t.get(h.id);if(!m)continue;if(m.hidden){t.set(m.id,{...m,internals:{...m.internals,handleBounds:void 0}}),c=!0;continue}const g=XSe(h.nodeElement),y=m.measured.width!==g.width||m.measured.height!==g.height;if(!!(g.width&&g.height&&(y||!m.internals.handleBounds||h.force))){const x=h.nodeElement.getBoundingClientRect(),S=ZT(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=aSt(k,g,t.get(m.parentId)):S&&(k=HO(k,S,g));const _={...m,measured:g,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:W8e("source",h.nodeElement,x,f,m.id),target:W8e("target",h.nodeElement,x,f,m.id)}}};t.set(m.id,_),m.parentId&&rke(_,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,y&&(u.push({id:m.id,type:"dimensions",dimensions:g}),m.expandParent&&m.parentId&&p.push({id:m.id,parentId:m.parentId,rect:WT(_,s)}))}}if(p.length>0){const h=ske(p,t,n,s);u.push(...h)}return{changes:u,updatedInternals:c}}async function fGn({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 J8e(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 ySt(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}`;J8e("source",c,d,e,s,i),J8e("target",c,u,e,a,l),t.set(r.id,r)}}function bSt(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:bSt(n,t):!1}function e9e(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 pGn(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!bSt(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 ete({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 hGn({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=z3(a,t);return{x:i.x-a.x,y:i.y-a.y}}function mGn({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,p=null,h=!1,m=!1,g=null;function y({noDragClassName:x,handleSelector:S,domNode:k,isSelectable:_,nodeId:C,nodeClickDistance:E=0}){p=Sp(k);function j({x:R,y:L}){const{nodeLookup:D,nodeExtent:B,snapGrid:H,snapToGrid:F,nodeOrigin:z,onNodeDrag:q,onSelectionDrag:M,onError:G,updateNodePositions:V}=t();a={x:R,y:L};let $=!1;const U=l.size>1,Z=U&&B?nge(F3(l)):null,K=U&&F?hGn({dragItems:l,snapGrid:H,x:R,y:L}):null;for(const[te,ee]of l){if(!D.has(te))continue;let J={x:R-ee.distance.x,y:L-ee.distance.y};F&&(J=K?{x:Math.round(J.x+K.x),y:Math.round(J.y+K.y)}:z3(J,H));let ae=null;if(U&&B&&!ee.extent&&Z){const{positionAbsolute:ne}=ee.internals,fe=ne.x-Z.x+B[0][0],oe=ne.x+ee.measured.width-Z.x2+B[1][0],le=ne.y-Z.y+B[0][1],he=ne.y+ee.measured.height-Z.y2+B[1][1];ae=[[fe,le],[oe,he]]}const{position:de,positionAbsolute:Y}=sSt({nodeId:te,nextPosition:J,nodeLookup:D,nodeExtent:ae||B,nodeOrigin:z,onError:G});$=$||ee.position.x!==de.x||ee.position.y!==de.y,ee.position=de,ee.internals.positionAbsolute=Y}if(m=m||$,!!$&&(V(l,!0),g&&(r||q||!C&&M))){const[te,ee]=ete({nodeId:C,dragItems:l,nodeLookup:D});r?.(g,l,te,ee),q?.(g,te,ee),C||M?.(g,ee)}}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,F]=iSt(u,d,D);(H!==0||F!==0)&&(a.x=(a.x??0)-H/R[2],a.y=(a.y??0)-F/R[2],await L({x:H,y:F})&&j(a)),i=requestAnimationFrame(N)}function I(R){const{nodeLookup:L,multiSelectionActive:D,nodesDraggable:B,transform:H,snapGrid:F,snapToGrid:z,selectNodesOnDrag:q,onNodeDragStart:M,onSelectionDragStart:G,unselectNodesAndEdges:V}=t();f=!0,(!q||!_)&&!D&&C&&(L.get(C)?.selected||V()),_&&q&&C&&e?.(C);const $=h2(R.sourceEvent,{transform:H,snapGrid:F,snapToGrid:z,containerBounds:d});if(a=$,l=pGn(L,B,$,C),l.size>0&&(n||M||!C&&G)){const[U,Z]=ete({nodeId:C,dragItems:l,nodeLookup:L});n?.(R.sourceEvent,l,U,Z),M?.(R.sourceEvent,U,Z),C||G?.(R.sourceEvent,Z)}}const A=D1t().clickDistance(E).on("start",R=>{const{domNode:L,nodeDragThreshold:D,transform:B,snapGrid:H,snapToGrid:F}=t();d=L?.getBoundingClientRect()||null,h=!1,m=!1,g=R.sourceEvent,D===0&&I(R),a=h2(R.sourceEvent,{transform:B,snapGrid:H,snapToGrid:F,containerBounds:d}),u=vg(R.sourceEvent,d)}).on("drag",R=>{const{autoPanOnNodeDrag:L,transform:D,snapGrid:B,snapToGrid:H,nodeDragThreshold:F,nodeLookup:z}=t(),q=h2(R.sourceEvent,{transform:D,snapGrid:B,snapToGrid:H,containerBounds:d});if(g=R.sourceEvent,(R.sourceEvent.type==="touchmove"&&R.sourceEvent.touches.length>1||C&&!z.has(C))&&(h=!0),!h){if(!c&&L&&f&&(c=!0,N()),!f){const M=vg(R.sourceEvent,d),G=M.x-u.x,V=M.y-u.y;Math.sqrt(G*G+V*V)>F&&I(R)}(a.x!==q.xSnapped||a.y!==q.ySnapped)&&l&&f&&(u=vg(R.sourceEvent,d),j(q))}}).on("end",R=>{if(!(!f||h)&&(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||!C&&H){const[F,z]=ete({nodeId:C,dragItems:l,nodeLookup:L,dragging:!1});s?.(R.sourceEvent,l,F,z),B?.(R.sourceEvent,F,z),C||H?.(R.sourceEvent,z)}}}).filter(R=>{const L=R.target;return!R.button&&(!x||!e9e(L,`.${x}`,k))&&(!S||e9e(L,S,k))});p.call(A)}function b(){p?.on(".drag",null)}return{update:y,destroy:b}}function gGn(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())NM(s,WT(a))>0&&r.push(a);return r}const vGn=250;function yGn(e,t,n,r){let s=[],a=1/0;const i=gGn(e,n,t+vGn);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}=WO(l,u,u.position,!0),p=Math.sqrt(Math.pow(d-e.x,2)+Math.pow(f-e.y,2));p>t||(p<a?(s=[{...u,x:d,y:f}],a=p):p===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 xSt(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,...WO(i,c,c.position,!0)}:c}function wSt(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function bGn(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const SSt=()=>!0;function xGn(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:a,isTarget:i,domNode:l,nodeLookup:c,lib:u,autoPanOnConnect:d,flowId:f,panBy:p,cancelConnection:h,onConnectStart:m,onConnect:g,onConnectEnd:y,isValidConnection:b=SSt,onReconnectEnd:x,updateConnection:S,getTransform:k,getFromHandle:_,autoPanSpeed:C,dragThreshold:E=1,handleDomNode:j}){const N=uSt(e.target);let I=0,A;const{x:R,y:L}=vg(e),D=wSt(a,j),B=l?.getBoundingClientRect();let H=!1;if(!B||!D)return;const F=xSt(s,D,r,c,t);if(!F)return;let z=vg(e,B),q=!1,M=null,G=!1,V=null;function $(){if(!d||!B)return;const[de,Y]=iSt(z,B,C);p({x:de,y:Y}),I=requestAnimationFrame($)}const U={...F,nodeId:s,type:D,position:F.position},Z=c.get(s);let te={inProgress:!0,isValid:null,from:WO(Z,U,sr.Left,!0),fromHandle:U,fromPosition:U.position,fromNode:Z,to:z,toHandle:null,toPosition:U8e[U.position],toNode:null,pointer:z};function ee(){H=!0,S(te),m?.(e,{nodeId:s,handleId:r,handleType:D})}E===0&&ee();function J(de){if(!H){const{x:he,y:be}=vg(de),xe=he-R,je=be-L;if(!(xe*xe+je*je>E*E))return;ee()}if(!_()||!U){ae(de);return}const Y=k();z=vg(de,B),A=yGn(B3(z,Y,!1,[1,1]),n,c,U),q||($(),q=!0);const ne=kSt(de,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});V=ne.handleDomNode,M=ne.connection,G=bGn(!!A,ne.isValid);const fe=c.get(s),oe=fe?WO(fe,U,sr.Left,!0):te.from,le={...te,from:oe,isValid:G,to:ne.toHandle&&G?jB({x:ne.toHandle.x,y:ne.toHandle.y},Y):z,toHandle:ne.toHandle,toPosition:G&&ne.toHandle?ne.toHandle.position:U8e[U.position],toNode:ne.toHandle?c.get(ne.toHandle.nodeId):null,pointer:z};S(le),te=le}function ae(de){if(!("touches"in de&&de.touches.length>0)){if(H){(A||V)&&M&&G&&g?.(M);const{inProgress:Y,...ne}=te,fe={...ne,toPosition:te.toHandle?te.toPosition:null};y?.(de,fe),a&&x?.(de,fe)}h(),cancelAnimationFrame(I),q=!1,G=!1,M=null,V=null,N.removeEventListener("mousemove",J),N.removeEventListener("mouseup",ae),N.removeEventListener("touchmove",J),N.removeEventListener("touchend",ae)}}N.addEventListener("mousemove",J),N.addEventListener("mouseup",ae),N.addEventListener("touchmove",J),N.addEventListener("touchend",ae)}function kSt(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=SSt,nodeLookup:d}){const f=a==="target",p=t?i.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:h,y:m}=vg(e),g=i.elementFromPoint(h,m),y=g?.classList.contains(`${l}-flow__handle`)?g:p,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){const x=wSt(void 0,y),S=y.getAttribute("data-nodeid"),k=y.getAttribute("data-handleid"),_=y.classList.contains("connectable"),C=y.classList.contains("connectableend");if(!S||!x)return b;const E={source:f?S:r,sourceHandle:f?k:s,target:f?r:S,targetHandle:f?s:k};b.connection=E;const N=_&&C&&(n===qT.Strict?f&&x==="source"||!f&&x==="target":S!==r||k!==s);b.isValid=N&&u(E),b.toHandle=xSt(S,x,k,d,n,!0)}return b}const ige={onPointerDown:xGn,isValid:kSt};function wGn({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Sp(e);function a({translateExtent:l,width:c,height:u,zoomStep:d=1,pannable:f=!0,zoomable:p=!0,inversePan:h=!1}){const m=S=>{if(S.sourceEvent.type!=="wheel"||!t)return;const k=n(),_=S.sourceEvent.ctrlKey&&IM()?10:1,C=-S.sourceEvent.deltaY*(S.sourceEvent.deltaMode===1?.05:S.sourceEvent.deltaMode?1:.002)*d,E=k[2]*Math.pow(2,C*_);t.scaleTo(E)};let g=[0,0];const y=S=>{(S.sourceEvent.type==="mousedown"||S.sourceEvent.type==="touchstart")&&(g=[S.sourceEvent.clientX??S.sourceEvent.touches[0].clientX,S.sourceEvent.clientY??S.sourceEvent.touches[0].clientY])},b=S=>{const k=n();if(S.sourceEvent.type!=="mousemove"&&S.sourceEvent.type!=="touchmove"||!t)return;const _=[S.sourceEvent.clientX??S.sourceEvent.touches[0].clientX,S.sourceEvent.clientY??S.sourceEvent.touches[0].clientY],C=[_[0]-g[0],_[1]-g[1]];g=_;const E=r()*Math.max(k[2],Math.log(k[2]))*(h?-1:1),j={x:k[0]-C[0]*E,y:k[1]-C[1]*E},N=[[0,0],[c,u]];t.setViewportConstrained({x:j.x,y:j.y,zoom:k[2]},N,l)},x=X1t().on("start",y).on("zoom",f?b:null).on("zoom.wheel",p?m:null);s.call(x,{})}function i(){s.on("zoom",null)}return{update:a,destroy:i,pointer:rg}}const MH=e=>({x:e.x,y:e.y,zoom:e.k}),tte=({x:e,y:t,zoom:n})=>RH.translate(e,t).scale(n),cj=(e,t)=>e.target.closest(`.${t}`),OSt=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),SGn=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,nte=(e,t=0,n=SGn,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},_St=e=>{const t=e.ctrlKey&&IM()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function kGn({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(cj(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=rg(d),b=_St(d),x=f*Math.pow(2,b);r.scaleTo(n,x,y,d);return}const p=d.deltaMode===1?20:1;let h=s===Xk.Vertical?0:d.deltaX*p,m=s===Xk.Horizontal?0:d.deltaY*p;!IM()&&d.shiftKey&&s!==Xk.Vertical&&(h=d.deltaY*p,m=0),r.translateBy(n,-(h/f)*a,-(m/f)*a,{internal:!0});const g=MH(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(d,g),e.panScrollTimeout=setTimeout(()=>{u?.(d,g),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l?.(d,g))}}function OGn({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=cj(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function _Gn({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=MH(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 CGn({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&OSt(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,MH(a.transform))}}function EGn({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&OSt(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=MH(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function jGn({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 p=e||t,h=n&&f.ctrlKey,m=f.type==="wheel";if(f.button===1&&f.type==="mousedown"&&(cj(f,`${u}-flow__node`)||cj(f,`${u}-flow__edge`)))return!0;if(!r&&!p&&!s&&!a&&!n||i||d&&!m||cj(f,l)&&m||cj(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(!p&&!s&&!h&&m||!r&&(f.type==="mousedown"||f.type==="touchstart")||Array.isArray(r)&&!r.includes(f.button)&&f.type==="mousedown")return!1;const g=Array.isArray(r)&&r.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||m)&&g}}function TGn({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=X1t().scaleExtent([t,n]).translateExtent(r),p=Sp(e).call(f);x({x:s.x,y:s.y,zoom:HT(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const h=p.on("wheel.zoom"),m=p.on("dblclick.zoom");f.wheelDelta(_St);function g(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?lx:I8).transform(nte(p,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:F,panOnScrollSpeed:z,preventScrolling:q,zoomOnPinch:M,zoomOnScroll:G,zoomOnDoubleClick:V,zoomActivationKeyPressed:$,lib:U,onTransformChange:Z,connectionInProgress:K,paneClickDistance:te,selectionOnDrag:ee}){D&&!u.isZoomingOrPanning&&b();const J=B&&!$&&!D;f.clickDistance(ee?1/0:!gg(te)||te<0?0:te);const ae=J?kGn({zoomPanValues:u,noWheelClassName:A,d3Selection:p,d3Zoom:f,panOnScrollMode:F,panOnScrollSpeed:z,zoomOnPinch:M,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):OGn({noWheelClassName:A,preventScrolling:q,d3ZoomHandler:h});if(p.on("wheel.zoom",ae,{passive:!1}),!D){const Y=_Gn({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",Y);const ne=CGn({zoomPanValues:u,panOnDrag:H,onPaneContextMenu:!!L,onPanZoom:a,onTransformChange:Z});f.on("zoom",ne);const fe=EGn({zoomPanValues:u,panOnDrag:H,panOnScroll:B,onPaneContextMenu:L,onPanZoomEnd:l,onDraggingChange:c});f.on("end",fe)}const de=jGn({zoomActivationKeyPressed:$,panOnDrag:H,zoomOnScroll:G,panOnScroll:B,zoomOnDoubleClick:V,zoomOnPinch:M,userSelectionActive:D,noPanClassName:R,noWheelClassName:A,lib:U,connectionInProgress:K});f.filter(de),V?p.on("dblclick.zoom",m):p.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,R,L){const D=tte(A),B=f?.constrain()(D,R,L);return B&&await g(B),new Promise(H=>H(B))}async function S(A,R){const L=tte(A);return await g(L,R),new Promise(D=>D(L))}function k(A){if(p){const R=tte(A),L=p.property("__zoom");(L.k!==A.zoom||L.x!==A.x||L.y!==A.y)&&f?.transform(p,R,null,{sync:!0})}}function _(){const A=p?K1t(p.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function C(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?lx:I8).scaleTo(nte(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function E(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?lx:I8).scaleBy(nte(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function j(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const R=!gg(A)||A<0?0:A;f?.clickDistance(R)}return{update:y,destroy:b,setViewport:S,setViewportConstrained:x,getViewport:_,scaleTo:C,scaleBy:E,setScaleExtent:j,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var GT;(function(e){e.Line="line",e.Handle="handle"})(GT||(GT={}));function NGn({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 t9e(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 V0(e,t){return Math.max(0,t-e)}function q0(e,t){return Math.max(0,e-t)}function aF(e,t,n){return Math.max(0,t-e,e-n)}function n9e(e,t){return e?!t:t}function IGn(e,t,n,r,s,a,i,l){let{affectsX:c,affectsY:u}=t;const{isHorizontal:d,isVertical:f}=t,p=d&&f,{xSnapped:h,ySnapped:m}=n,{minWidth:g,maxWidth:y,minHeight:b,maxHeight:x}=r,{x:S,y:k,width:_,height:C,aspectRatio:E}=e;let j=Math.floor(d?h-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=_+(c?-j:j),A=C+(u?-N:N),R=-a[0]*_,L=-a[1]*C;let D=aF(I,g,y),B=aF(A,b,x);if(i){let z=0,q=0;c&&j<0?z=V0(S+j+R,i[0][0]):!c&&j>0&&(z=q0(S+I+R,i[1][0])),u&&N<0?q=V0(k+N+L,i[0][1]):!u&&N>0&&(q=q0(k+A+L,i[1][1])),D=Math.max(D,z),B=Math.max(B,q)}if(l){let z=0,q=0;c&&j>0?z=q0(S+j,l[0][0]):!c&&j<0&&(z=V0(S+I,l[1][0])),u&&N>0?q=q0(k+N,l[0][1]):!u&&N<0&&(q=V0(k+A,l[1][1])),D=Math.max(D,z),B=Math.max(B,q)}if(s){if(d){const z=aF(I/E,b,x)*E;if(D=Math.max(D,z),i){let q=0;!c&&!u||c&&!u&&p?q=q0(k+L+I/E,i[1][1])*E:q=V0(k+L+(c?j:-j)/E,i[0][1])*E,D=Math.max(D,q)}if(l){let q=0;!c&&!u||c&&!u&&p?q=V0(k+I/E,l[1][1])*E:q=q0(k+(c?j:-j)/E,l[0][1])*E,D=Math.max(D,q)}}if(f){const z=aF(A*E,g,y)/E;if(B=Math.max(B,z),i){let q=0;!c&&!u||u&&!c&&p?q=q0(S+A*E+R,i[1][0])/E:q=V0(S+(u?N:-N)*E+R,i[0][0])/E,B=Math.max(B,q)}if(l){let q=0;!c&&!u||u&&!c&&p?q=V0(S+A*E,l[1][0])/E:q=q0(S+(u?N:-N)*E,l[0][0])/E,B=Math.max(B,q)}}}N=N+(N<0?B:-B),j=j+(j<0?D:-D),s&&(p?I>A*E?N=(n9e(c,u)?-j:j)/E:j=(n9e(c,u)?-N:N)*E:d?(N=j/E,u=c):(j=N*E,c=u));const H=c?S+j:S,F=u?k+N:k;return{width:_+(c?-j:j),height:C+(u?-N:N),x:a[0]*j*(c?-1:1)+H,y:a[1]*N*(u?-1:1)+F}}const CSt={width:0,height:0,x:0,y:0},AGn={...CSt,pointerX:0,pointerY:0,aspectRatio:1};function RGn(e){return[[0,0],[e.measured.width,e.measured.height]]}function PGn(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 $Gn({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=Sp(e);let i={controlDirection:t9e("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:p,onResizeStart:h,onResize:m,onResizeEnd:g,shouldResize:y}){let b={...CSt},x={...AGn};i={boundaries:d,resizeDirection:p,keepAspectRatio:f,controlDirection:t9e(u)};let S,k=null,_=[],C,E,j,N=!1;const I=D1t().on("start",A=>{const{nodeLookup:R,transform:L,snapGrid:D,snapToGrid:B,nodeOrigin:H,paneDomNode:F}=n();if(S=R.get(t),!S)return;k=F?.getBoundingClientRect()??null;const{xSnapped:z,ySnapped:q}=h2(A.sourceEvent,{transform:L,snapGrid:D,snapToGrid:B,containerBounds:k});b={width:S.measured.width??0,height:S.measured.height??0,x:S.position.x??0,y:S.position.y??0},x={...b,pointerX:z,pointerY:q,aspectRatio:b.width/b.height},C=void 0,S.parentId&&(S.extent==="parent"||S.expandParent)&&(C=R.get(S.parentId),E=C&&S.extent==="parent"?RGn(C):void 0),_=[],j=void 0;for(const[M,G]of R)if(G.parentId===t&&(_.push({id:M,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const V=PGn(G,S,G.origin??H);j?j=[[Math.min(V[0][0],j[0][0]),Math.min(V[0][1],j[0][1])],[Math.max(V[1][0],j[1][0]),Math.max(V[1][1],j[1][1])]]:j=V}h?.(A,{...b})}).on("drag",A=>{const{transform:R,snapGrid:L,snapToGrid:D,nodeOrigin:B}=n(),H=h2(A.sourceEvent,{transform:R,snapGrid:L,snapToGrid:D,containerBounds:k}),F=[];if(!S)return;const{x:z,y:q,width:M,height:G}=b,V={},$=S.origin??B,{width:U,height:Z,x:K,y:te}=IGn(x,i.controlDirection,H,i.boundaries,i.keepAspectRatio,$,E,j),ee=U!==M,J=Z!==G,ae=K!==z&&ee,de=te!==q&&J;if(!ae&&!de&&!ee&&!J)return;if((ae||de||$[0]===1||$[1]===1)&&(V.x=ae?K:b.x,V.y=de?te:b.y,b.x=V.x,b.y=V.y,_.length>0)){const oe=K-z,le=te-q;for(const he of _)he.position={x:he.position.x-oe+$[0]*(U-M),y:he.position.y-le+$[1]*(Z-G)},F.push(he)}if((ee||J)&&(V.width=ee&&(!i.resizeDirection||i.resizeDirection==="horizontal")?U:b.width,V.height=J&&(!i.resizeDirection||i.resizeDirection==="vertical")?Z:b.height,b.width=V.width,b.height=V.height),C&&S.expandParent){const oe=$[0]*(V.width??0);V.x&&V.x<oe&&(b.x=oe,x.x=x.x-(V.x-oe));const le=$[1]*(V.height??0);V.y&&V.y<le&&(b.y=le,x.y=x.y-(V.y-le))}const Y=NGn({width:b.width,prevWidth:M,height:b.height,prevHeight:G,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),ne={...b,direction:Y};y?.(A,ne)!==!1&&(N=!0,m?.(A,ne),r(V,F))}).on("end",A=>{N&&(g?.(A,{...b}),s?.({...b}),N=!1)});a.call(I)}function c(){a.on(".drag",null)}return{update:l,destroy:c}}const MGn={},r9e=e=>{let t;const n=new Set,r=(d,f)=>{const p=typeof d=="function"?d(t):d;if(!Object.is(p,t)){const h=t;t=f??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(m=>m(t,h))}},s=()=>t,c={setState:r,getState:s,getInitialState:()=>u,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(MGn?"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},DGn=e=>e?r9e(e):r9e,{useDebugValue:LGn}=Fe,{useSyncExternalStoreWithSelector:FGn}=nOn,zGn=e=>e;function ESt(e,t=zGn,n){const r=FGn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return LGn(r),r}const s9e=(e,t)=>{const n=DGn(e),r=(s,a=t)=>ESt(n,s,a);return Object.assign(r,n),r},BGn=(e,t)=>e?s9e(e,t):s9e;function io(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 DH=v.createContext(null),UGn=DH.Provider,jSt=by.error001();function Bs(e,t){const n=v.useContext(DH);if(n===null)throw new Error(jSt);return ESt(n,e,t)}function jo(){const e=v.useContext(DH);if(e===null)throw new Error(jSt);return v.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const a9e={display:"none"},VGn={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},TSt="react-flow__node-desc",NSt="react-flow__edge-desc",qGn="react-flow__aria-live",HGn=e=>e.ariaLiveMessage,WGn=e=>e.ariaLabelConfig;function ZGn({rfId:e}){const t=Bs(HGn);return o.jsx("div",{id:`${qGn}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:VGn,children:t})}function GGn({rfId:e,disableKeyboardA11y:t}){const n=Bs(WGn);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${TSt}-${e}`,style:a9e,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${NSt}-${e}`,style:a9e,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(ZGn,{rfId:e})]})}const U3=v.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:Ul(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});U3.displayName="Panel";function QGn({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(U3,{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 YGn=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}},iF=e=>e.id;function KGn(e,t){return io(e.selectedNodes.map(iF),t.selectedNodes.map(iF))&&io(e.selectedEdges.map(iF),t.selectedEdges.map(iF))}function XGn({onSelectionChange:e}){const t=jo(),{selectedNodes:n,selectedEdges:r}=Bs(YGn,KGn);return v.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const JGn=e=>!!e.onSelectionChangeHandlers;function eQn({onSelectionChange:e}){const t=Bs(JGn);return e||t?o.jsx(XGn,{onSelectionChange:e}):null}const oge=typeof window<"u"?v.useLayoutEffect:v.useEffect,ISt=[0,0],tQn={x:0,y:0,zoom:1},nQn=["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"],i9e=[...nQn,"rfId"],rQn=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}),o9e={translateExtent:EM,nodeOrigin:ISt,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function sQn(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Bs(rQn,io),u=jo();oge(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=o9e,l()}),[]);const d=v.useRef(o9e);return oge(()=>{for(const f of i9e){const p=e[f],h=d.current[f];p!==h&&(typeof e[f]>"u"||(f==="nodes"?t(p):f==="edges"?n(p):f==="minZoom"?r(p):f==="maxZoom"?s(p):f==="translateExtent"?a(p):f==="nodeExtent"?i(p):f==="ariaLabelConfig"?u.setState({ariaLabelConfig:ZZn(p)}):f==="fitView"?u.setState({fitViewQueued:p}):f==="fitViewOptions"?u.setState({fitViewOptions:p}):u.setState({[f]:p})))}d.current=e},i9e.map(f=>e[f])),null}function l9e(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function aQn(e){const[t,n]=v.useState(e==="system"?null:e);return v.useEffect(()=>{if(e!=="system"){n(e);return}const r=l9e(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:l9e()?.matches?"dark":"light"}const c9e=typeof document<"u"?document:null;function AM(e=null,t={target:c9e,actInsideInputWithModifier:!0}){const[n,r]=v.useState(!1),s=v.useRef(!1),a=v.useRef(new Set([])),[i,l]=v.useMemo(()=>{if(e!==null){const u=(Array.isArray(e)?e:[e]).filter(f=>typeof f=="string").map(f=>f.replace("+",`
337
+ `: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 aUn(this):new nUn(this)}getCursor(t,n=0,r){let s=t.doc?t:cs.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?BE(this,s,n,r):zE(this,s,n,r)}}class i1t{constructor(t){this.spec=t}}function eUn(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 zE(e,t,n,r){let s;return e.wholeWord&&(s=tUn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=eUn(e.test,t,s)),new Ex(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function tUn(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(mB(s,n-a))!=wo.Word||t(gB(s,n-a))!=wo.Word)&&(t(gB(s,r-a))!=wo.Word||t(mB(s,r-a))!=wo.Word))}class nUn extends i1t{constructor(t){super(t)}nextMatch(t,n,r){let s=zE(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=zE(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=zE(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=zE(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=zE(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 rUn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function BE(e,t,n,r){let s;return e.wholeWord&&(s=sUn(t.charCategorizer(t.selection.main.head))),e.test&&(s=rUn(e.test,t,s)),new r1t(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function mB(e,t){return e.slice(kc(e,t,!1),t)}function gB(e,t){return e.slice(t,kc(e,t))}function sUn(e){return(t,n,r)=>!r[0].length||(e(mB(r.input,r.index))!=wo.Word||e(gB(r.input,r.index))!=wo.Word)&&(e(gB(r.input,r.index+r[0].length))!=wo.Word||e(mB(r.input,r.index+r[0].length))!=wo.Word)}class aUn extends i1t{nextMatch(t,n,r){let s=BE(this.spec,t,r,t.doc.length).next();return s.done&&(s=BE(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=BE(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=BE(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=BE(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 xM=vr.define(),MSe=vr.define(),Lw=wl.define({create(e){return new XJ(Wme(e).create(),null)},update(e,t){for(let n of t.effects)n.is(xM)?e=new XJ(n.value.create(),e.panel):n.is(MSe)&&(e=new XJ(e.query,n.value?DSe:null));return e},provide:e=>uM.from(e,t=>t.panel)});class XJ{constructor(t,n){this.query=t,this.panel=n}}const iUn=jn.mark({class:"cm-searchMatch"}),oUn=jn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),lUn=Co.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Lw))}update(e){let t=e.state.field(Lw);(t!=e.startState.field(Lw)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return jn.none;let{view:n}=this,r=new Rd;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(p=>p.from==u&&p.to==d);r.add(u,d,f?oUn:iUn)})}return r.finish()}},{decorations:e=>e.decorations});function $3(e){return t=>{let n=t.state.field(Lw,!1);return n&&n.query.spec.valid?e(t,n):c1t(t)}}const vB=$3((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=gt.single(r.from,r.to),a=e.state.facet(dI);return e.dispatch({selection:s,effects:[LSe(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),l1t(e),!0}),yB=$3((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let a=gt.single(s.from,s.to),i=e.state.facet(dI);return e.dispatch({selection:a,effects:[LSe(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),l1t(e),!0}),cUn=$3((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:gt.create(n.map(r=>gt.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),uUn=({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 Ex(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(i=a.length),a.push(gt.range(l.value.from,l.value.to))}return t(e.update({selection:gt.create(a,i),userEvent:"select.search.matches"})),!0},gze=$3((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(Nt.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=gt.single(i.from,i.to).map(f),d.push(LSe(e,i)),d.push(n.facet(dI).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),dUn=$3((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:Nt.announce.of(r),userEvent:"input.replace.all"}),!0});function DSe(e){return e.state.facet(dI).createPanel(e)}function Wme(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(dI);return new a1t({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 o1t(e){let t=J1e(e,DSe);return t&&t.dom.querySelector("[main-field]")}function l1t(e){let t=o1t(e);t&&t==e.root.activeElement&&t.select()}const c1t=e=>{let t=e.state.field(Lw,!1);if(t&&t.panel){let n=o1t(e);if(n&&n!=e.root.activeElement){let r=Wme(e.state,t.query.spec);r.valid&&e.dispatch({effects:xM.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[MSe.of(!0),t?xM.of(Wme(e.state,t.query.spec)):vr.appendConfig.of(mUn)]});return!0},u1t=e=>{let t=e.state.field(Lw,!1);if(!t||!t.panel)return!1;let n=J1e(e,DSe);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:MSe.of(!1)}),!0},fUn=[{key:"Mod-f",run:c1t,scope:"editor search-panel"},{key:"F3",run:vB,shift:yB,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:vB,shift:yB,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:u1t,scope:"editor search-panel"},{key:"Mod-Shift-l",run:uUn},{key:"Mod-Alt-g",run:UBn},{key:"Mod-d",run:JBn,preventDefault:!0}];class pUn{constructor(t){this.view=t;let n=this.query=t.state.field(Lw).query.spec;this.commit=this.commit.bind(this),this.searchField=ci("input",{value:n.search,placeholder:np(t,"Find"),"aria-label":np(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=ci("input",{value:n.replace,placeholder:np(t,"Replace"),"aria-label":np(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=ci("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=ci("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=ci("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return ci("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=ci("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>vB(t),[np(t,"next")]),r("prev",()=>yB(t),[np(t,"previous")]),r("select",()=>cUn(t),[np(t,"all")]),ci("label",null,[this.caseField,np(t,"match case")]),ci("label",null,[this.reField,np(t,"regexp")]),ci("label",null,[this.wordField,np(t,"by word")]),...t.state.readOnly?[]:[ci("br"),this.replaceField,r("replace",()=>gze(t),[np(t,"replace")]),r("replaceAll",()=>dUn(t),[np(t,"replace all")])],ci("button",{name:"close",onclick:()=>u1t(t),"aria-label":np(t,"close"),type:"button"},["×"])])}commit(){let t=new a1t({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:xM.of(t)}))}keydown(t){R5n(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?yB:vB)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),gze(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(xM)&&!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(dI).top}}function np(e,t){return e.state.phrase(t)}const Y6=30,K6=/[\s\.,:;?!]/;function LSe(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-Y6),i=Math.min(s,n+Y6),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<Y6;c++)if(!K6.test(l[c+1])&&K6.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-Y6;c--)if(!K6.test(l[c-1])&&K6.test(l[c])){l=l.slice(0,c);break}}return Nt.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const hUn=Nt.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"}}),mUn=[Lw,Xp.low(lUn),hUn];class vze{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class bk{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(wM).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new Rd,l=[],c=0;for(let d=0;;){let f=d==a.length?null:a[d];if(!f&&!l.length)break;let p,h;for(l.length?(p=c,h=l.reduce((g,y)=>Math.min(g,y.to),f&&f.from>p?f.from:1e8)):(p=f.from,h=f.to,l.push(f),d++);d<a.length;){let g=a[d];if(g.from==p&&(g.to>g.from||g.to==p))l.push(g),d++,h=Math.min(g.to,h);else{h=Math.min(g.from,h);break}}let m=jUn(l);if(l.some(g=>g.from==g.to||g.from==g.to-1&&r.doc.lineAt(g.from).to==g.from))i.add(p,p,jn.widget({widget:new OUn(m),diagnostics:l.slice()}));else{let g=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(p,h,jn.mark({class:"cm-lintRange cm-lintRange-"+m+g,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>h)}))}c=h;for(let g=0;g<l.length;g++)l[g].to<=c&&l.splice(g--,1)}let u=i.finish();return new bk(u,n,BT(u))}}function BT(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 vze(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new vze(r.from,a,r.diagnostic)}}),r}function gUn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(wM).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(d1t))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function vUn(e,t){return e.field(Cp,!1)?t:t.concat(vr.appendConfig.of(TUn))}const d1t=vr.define(),FSe=vr.define(),f1t=vr.define(),Cp=wl.define({create(){return new bk(jn.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=BT(n,e.selected.diagnostic,a)||BT(n,null,a)}!n.size&&s&&t.state.facet(wM).autoPanel&&(s=null),e=new bk(n,s,r)}for(let n of t.effects)if(n.is(d1t)){let r=t.state.facet(wM).autoPanel?n.value.length?SM.open:null:e.panel;e=bk.init(n.value,r,t.state)}else n.is(FSe)?e=new bk(e.diagnostics,n.value?SM.open:null,e.selected):n.is(f1t)&&(e=new bk(e.diagnostics,e.panel,n.value));return e},provide:e=>[uM.from(e,t=>t.panel),Nt.decorations.from(e,t=>t.diagnostics)]}),yUn=jn.mark({class:"cm-lintRange cm-lintRange-active"});function bUn(e,t,n){let{diagnostics:r}=e.state.field(Cp),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(wM).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:xUn(e,s)}}}:null}function xUn(e,t){return ci("ul",{class:"cm-tooltip-lint"},t.map(n=>h1t(e,n,!1)))}const wUn=e=>{let t=e.state.field(Cp,!1);(!t||!t.panel)&&e.dispatch({effects:vUn(e.state,[FSe.of(!0)])});let n=J1e(e,SM.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},yze=e=>{let t=e.state.field(Cp,!1);return!t||!t.panel?!1:(e.dispatch({effects:FSe.of(!1)}),!0)},SUn=e=>{let t=e.state.field(Cp,!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)},kUn=[{key:"Mod-Shift-m",run:wUn,preventDefault:!0},{key:"F8",run:SUn}],wM=On.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...Fy(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:bze,tooltipFilter:bze,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 bze(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function p1t(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 h1t(e,t,n){var r;let s=n?p1t(t.actions):[];return ci("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},ci("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=h=>{if(h.preventDefault(),l)return;l=!0;let m=BT(e.state.field(Cp).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),ci("u",u.slice(d,d+1)),u.slice(d+1)],p=a.markClass?" "+a.markClass:"";return ci("button",{type:"button",class:"cm-diagnosticAction"+p,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&ci("div",{class:"cm-diagnosticSource"},t.source))}class OUn extends Jp{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return ci("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class xze{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=h1t(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class SM{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)yze(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=p1t(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=BT(this.view.state.field(Cp).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=ci("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=ci("div",{class:"cm-panel-lint"},this.list,ci("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>yze(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Cp).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(Cp),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,p;for(let h=r;h<this.items.length;h++)if(this.items[h].diagnostic==d){f=h;break}f<0?(p=new xze(this.view,d),this.items.splice(r,0,p),s=!0):(p=this.items[f],f>r&&(this.items.splice(r,f-r),s=!0)),n&&p.diagnostic==n.diagnostic?p.dom.hasAttribute("aria-selected")||(p.dom.setAttribute("aria-selected","true"),a=p):p.dom.hasAttribute("aria-selected")&&p.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 xze(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(Cp),r=BT(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:f1t.of(r)})}static open(t){return new SM(t)}}function _Un(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 X6(e){return _Un(`<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 CUn=Nt.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:X6("#d11")},".cm-lintRange-warning":{backgroundImage:X6("orange")},".cm-lintRange-info":{backgroundImage:X6("#999")},".cm-lintRange-hint":{backgroundImage:X6("#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 EUn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function jUn(e){let t="hint",n=1;for(let r of e){let s=EUn(r.severity);s>n&&(n=s,t=r.severity)}return t}const TUn=[Cp,Nt.decorations.compute([Cp],e=>{let{selected:t,panel:n}=e.field(Cp);return!t||!n||t.from==t.to?jn.none:jn.set([yUn.range(t.from,t.to)])}),w6n(bUn,{hideOn:gUn}),CUn];var wze=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(yzn)),t.defaultKeymap!==!1&&(a=a.concat(FBn)),t.searchKeymap!==!1&&(a=a.concat(fUn)),t.historyKeymap!==!1&&(a=a.concat(W7n)),t.foldKeymap!==!1&&(a=a.concat(rFn)),t.completionKeymap!==!1&&(a=a.concat(l0t)),t.lintKeymap!==!1&&(a=a.concat(kUn));var i=[];return t.lineNumbers!==!1&&i.push(R6n()),t.highlightActiveLineGutter!==!1&&i.push(M6n()),t.highlightSpecialChars!==!1&&i.push(Q5n()),t.history!==!1&&i.push(D7n()),t.foldGutter!==!1&&i.push(oFn()),t.drawSelection!==!1&&i.push(F5n()),t.dropCursor!==!1&&i.push(q5n()),t.allowMultipleSelections!==!1&&i.push(cs.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(Q6n()),t.syntaxHighlighting!==!1&&i.push(U1(dFn,{fallback:!0})),t.bracketMatching!==!1&&i.push(yFn()),t.closeBrackets!==!1&&i.push(hzn()),t.autocompletion!==!1&&i.push(o0t()),t.rectangularSelection!==!1&&i.push(c6n()),s!==!1&&i.push(f6n()),t.highlightActiveLine!==!1&&i.push(t6n()),t.highlightSelectionMatches!==!1&&i.push(HBn()),t.tabSize&&typeof t.tabSize=="number"&&i.push(oI.of(" ".repeat(t.tabSize))),i.concat([iI.of(a.flat())]).filter(Boolean)};const NUn="#e5c07b",Sze="#e06c75",IUn="#56b6c2",AUn="#ffffff",T8="#abb2bf",Zme="#7d8799",RUn="#61afef",PUn="#98c379",kze="#d19a66",$Un="#c678dd",MUn="#21252b",Oze="#2c313a",_ze="#282c34",JJ="#353a42",DUn="#3E4451",Cze="#528bff",LUn=Nt.theme({"&":{color:T8,backgroundColor:_ze},".cm-content":{caretColor:Cze},".cm-cursor, .cm-dropCursor":{borderLeftColor:Cze},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:DUn},".cm-panels":{backgroundColor:MUn,color:T8},".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:_ze,color:Zme,border:"none"},".cm-activeLineGutter":{backgroundColor:Oze},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:JJ},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:JJ,borderBottomColor:JJ},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:Oze,color:T8}}},{dark:!0}),FUn=Ug.define([{tag:pe.keyword,color:$Un},{tag:[pe.name,pe.deleted,pe.character,pe.propertyName,pe.macroName],color:Sze},{tag:[pe.function(pe.variableName),pe.labelName],color:RUn},{tag:[pe.color,pe.constant(pe.name),pe.standard(pe.name)],color:kze},{tag:[pe.definition(pe.name),pe.separator],color:T8},{tag:[pe.typeName,pe.className,pe.number,pe.changed,pe.annotation,pe.modifier,pe.self,pe.namespace],color:NUn},{tag:[pe.operator,pe.operatorKeyword,pe.url,pe.escape,pe.regexp,pe.link,pe.special(pe.string)],color:IUn},{tag:[pe.meta,pe.comment],color:Zme},{tag:pe.strong,fontWeight:"bold"},{tag:pe.emphasis,fontStyle:"italic"},{tag:pe.strikethrough,textDecoration:"line-through"},{tag:pe.link,color:Zme,textDecoration:"underline"},{tag:pe.heading,fontWeight:"bold",color:Sze},{tag:[pe.atom,pe.bool,pe.special(pe.variableName)],color:kze},{tag:[pe.processingInstruction,pe.string,pe.inserted],color:PUn},{tag:pe.invalid,color:AUn}]),zUn=[LUn,U1(FUn)];var BUn=Nt.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),UUn=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,p=f===void 0?"":f,h=n.basicSetup,m=h===void 0?!0:h,g=[];switch(s&&g.unshift(iI.of([zBn])),m&&(typeof m=="boolean"?g.unshift(wze()):g.unshift(wze(m))),p&&g.unshift(a6n(p)),d){case"light":g.push(BUn);break;case"dark":g.push(zUn);break;case"none":break;default:g.push(d);break}return i===!1&&g.push(Nt.editable.of(!1)),c&&g.push(cs.readOnly.of(!0)),[...g]},VUn=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 qUn{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 Eze{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 eee=null,HUn=()=>typeof window>"u"?new Eze:(eee||(eee=new Eze),eee),WUn=Nt.theme({"& .cm-scroller":{height:"100% !important"}}),jze=null,tee=null;function ZUn(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===jze||(jze=i,tee=Nt.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a}})),tee}var Tze=Ly.define(),GUn=200,QUn=[];function YUn(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?QUn:l,u=e.autoFocus,d=e.theme,f=d===void 0?"light":d,p=e.height,h=p===void 0?null:p,m=e.minHeight,g=m===void 0?null:m,y=e.maxHeight,b=y===void 0?null:y,x=e.width,S=x===void 0?null:x,k=e.minWidth,_=k===void 0?null:k,C=e.maxWidth,E=C===void 0?null:C,j=e.placeholder,N=j===void 0?"":j,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,F=H===void 0?!0:H,z=e.root,q=e.initialState,M=v.useState(),G=M[0],V=M[1],$=v.useState(),U=$[0],Z=$[1],K=v.useState(),te=K[0],ee=K[1],J=v.useState(()=>({current:null}))[0],ae=v.useState(()=>({current:null}))[0],de=ZUn(h,g,b,S,_,E),Y=Nt.updateListener.of(oe=>{if(oe.docChanged&&typeof r=="function"&&!oe.transactions.some(be=>be.annotation(Tze))){J.current?J.current.reset():(J.current=new qUn(()=>{if(ae.current){var be=ae.current;ae.current=null,be()}J.current=null},GUn),HUn().add(J.current));var le=oe.state.doc,he=le.toString();r(he,oe)}s&&s(VUn(oe))}),ne=UUn({theme:f,editable:A,readOnly:L,placeholder:N,indentWithTab:B,basicSetup:F}),fe=[Y,...de?[de]:[],WUn,...ne];return i&&typeof i=="function"&&fe.push(Nt.updateListener.of(i)),fe=fe.concat(c),v.useLayoutEffect(()=>{if(G&&!te){var oe={doc:t,selection:n,extensions:fe},le=q?cs.fromJSON(q.json,oe,q.fields):cs.create(oe);if(ee(le),!U){var he=new Nt({state:le,parent:G,root:z});Z(he),a&&a(he,le)}}return()=>{U&&(ee(void 0),Z(void 0))}},[G,te]),v.useEffect(()=>{e.container&&V(e.container)},[e.container]),v.useEffect(()=>()=>{U&&(U.destroy(),Z(void 0)),J.current&&(J.current.cancel(),J.current=null)},[U]),v.useEffect(()=>{u&&U&&U.focus()},[u,U]),v.useEffect(()=>{U&&U.dispatch({effects:vr.reconfigure.of(fe)})},[f,c,h,g,b,S,_,E,N,A,L,B,F,r,i]),v.useEffect(()=>{if(t!==void 0){var oe=U?U.state.doc.toString():"";if(U&&t!==oe){var le=J.current&&!J.current.isDone,he=()=>{U&&t!==U.state.doc.toString()&&U.dispatch({changes:{from:0,to:U.state.doc.toString().length,insert:t||""},annotations:[Tze.of(!0)]})};le?ae.current=he:he()}}},[t,U]),{state:te,setState:ee,view:U,setView:Z,container:G,setContainer:V}}var KUn=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],Qu=v.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,p=e.autoFocus,h=e.theme,m=h===void 0?"light":h,g=e.height,y=e.minHeight,b=e.maxHeight,x=e.width,S=e.minWidth,k=e.maxWidth,_=e.basicSetup,C=e.placeholder,E=e.indentWithTab,j=e.editable,N=e.readOnly,I=e.root,A=e.initialState,R=Swt(e,KUn),L=v.useRef(null),D=YUn({root:I,value:s,autoFocus:p,theme:m,height:g,minHeight:y,maxHeight:b,width:x,minWidth:S,maxWidth:k,basicSetup:_,placeholder:C,indentWithTab:E,editable:j,readOnly:N,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),B=D.state,H=D.view,F=D.container,z=D.setContainer;v.useImperativeHandle(t,()=>({editor:L.current,state:B,view:H}),[L,F,B,H]);var q=v.useCallback(G=>{L.current=G,z(G)},[z]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var M=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",UO({ref:q,className:""+M+(n?" "+n:"")},R))});Qu.displayName="CodeMirror";const XUn={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"};let nee=null;function JUn(){return nee||(nee=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([mo(()=>import("./core-DBMTExoC.js"),__vite__mapDeps([0,1,2]),import.meta.url),mo(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[mo(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),mo(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[mo(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),mo(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),mo(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),mo(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),mo(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),mo(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),mo(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),mo(()=>import("./python-DhUJRlN_.js"),[],import.meta.url)],engine:t()})})()),nee}async function eVn(e,t){const n=XUn[t?.toLowerCase()];if(!n)return null;const r=await JUn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function tVn(e){return new LO(sSe.define(e))}const m1t=[ng.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return mo(()=>Promise.resolve().then(()=>G6),void 0,import.meta.url).then(e=>e.javascript())}}),ng.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return mo(()=>Promise.resolve().then(()=>NFn),void 0,import.meta.url).then(e=>e.json())}}),ng.of({name:"JSX",extensions:["jsx"],load(){return mo(()=>Promise.resolve().then(()=>G6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),ng.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return mo(()=>Promise.resolve().then(()=>O7n),void 0,import.meta.url).then(e=>e.markdown())}}),ng.of({name:"TSX",extensions:["tsx"],load(){return mo(()=>Promise.resolve().then(()=>G6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),ng.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return mo(()=>Promise.resolve().then(()=>G6),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),ng.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return mo(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>tVn(e.shell))}})];function nVn(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 rVn(e){const t=nVn(e);return o0t({override:[sVn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function sVn(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,p)=>{const g=u.state.sliceDoc(p,p+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:p,insert:g},selection:{anchor:f+g.length}})}}));return{from:a,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const aVn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,iVn=jn.mark({class:"cm-variable-highlight"}),Nze=new wxt({regexp:aVn,decoration:()=>iVn}),oVn=Co.fromClass(class{decorations;constructor(e){this.decorations=Nze.createDeco(e)}update(e){this.decorations=Nze.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),lVn=oVn;function cVn(){const e=cI({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:[pe.className,pe.propertyName],color:"var(--neutral6)"},{tag:pe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[pe.heading1,pe.heading2,pe.heading3,pe.heading4,pe.heading5,pe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:pe.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:pe.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:pe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:pe.url,color:"var(--accent3)"},{tag:pe.monospace,color:"var(--neutral6)"},{tag:pe.strikethrough,textDecoration:"line-through"},{tag:pe.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=Nt.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 uVn(){const e=Nt.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=Ug.define([{tag:[pe.comment,pe.bracket],color:"var(--neutral2)"},{tag:[pe.string,pe.meta,pe.regexp],color:"var(--accent1)"},{tag:[pe.atom,pe.bool,pe.special(pe.variableName)],color:"var(--accent6)"},{tag:[pe.keyword,pe.operator,pe.tagName],color:"var(--accent2)"},{tag:[pe.function(pe.propertyName),pe.propertyName],color:"var(--accent5)"},{tag:[pe.definition(pe.variableName),pe.function(pe.variableName),pe.className,pe.attributeName],color:"var(--accent3)"},{tag:[pe.variableName,pe.number],color:"var(--accent5)"},{tag:[pe.name,pe.quote],color:"var(--accent1)"},{tag:pe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[pe.heading1,pe.heading2,pe.heading3,pe.heading4,pe.heading5,pe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[pe.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[pe.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:pe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:pe.url,color:"var(--accent3)"},{tag:pe.monospace,color:"var(--neutral6)"},{tag:pe.strikethrough,textDecoration:"line-through"},{tag:[pe.deleted],color:"var(--accent2)"},{tag:pe.invalid,color:"var(--error)"},{tag:[pe.standard(pe.tagName)],color:"var(--accent1)"}]);return[e,U1(t)]}const Yx=()=>{const e=B_().resolvedTheme==="dark";return v.useMemo(()=>e?cVn():uVn(),[e])},dVn=co(X("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"}}),fVn=Xp.highest(Nt.editorAttributes.of({style:"outline: none"})),pVn=Xp.highest(Nt.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),hVn=[fVn,pVn],Wr=v.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:p,variant:h,...m},g)=>{const y=Yx(),b=e?JSON.stringify(e,null,2):t??"",x=v.useMemo(()=>{const S=[...hVn];return f&&S.push(Nt.lineWrapping),a==="json"?S.push(Rp):a==="markdown"&&S.push(ISe({base:BO,codeLanguages:m1t})),i&&a==="markdown"&&S.push(lVn),c&&a==="markdown"&&S.push(rVn(c)),p===!1&&S.push(cs.readOnly.of(!0)),S},[a,i,c,p,f]);return o.jsxs("div",{className:X(dVn({variant:h}),s),...m,children:[r&&o.jsx(Pa,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(Qu,{ref:g,value:b,theme:y,extensions:x,onChange:n,editable:p,"aria-label":"Code editor",placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),mVn=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},gVn=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=Yx(),{settings:r,setSettings:s}=tH(),a=r?.tracingOptions,i=v.useMemo(()=>mVn(a),[a]),[l,c]=v.useState(()=>i),u=v.useRef(!1);v.useEffect(()=>{u.current||c(i)},[i]);const d=p=>{u.current=!0,c(p)},f=()=>{if(!l){s({...r,tracingOptions:void 0}),t?.();return}try{const p=JSON.parse(l);typeof p=="object"&&p!==null&&s({...r,tracingOptions:p})}catch{return}t?.()};return o.jsxs("div",{className:"space-y-2 px-5 py-2",children:[o.jsx(ye,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),o.jsx(Qu,{value:l,onChange:d,theme:n,extensions:[Rp],className:X("overflow-y-scroll bg-surface3 rounded-lg overflow-hidden p-3",e)}),o.jsx("div",{className:"flex items-center justify-end",children:o.jsx(ce,{type:"button",onClick:f,children:"Save"})})]})},vVn=()=>{const[e,t]=v.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:o.jsx(ce,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(qe,{children:o.jsx(WV,{})})})}),o.jsx(Rn,{children:"Run Options"})]}),o.jsx(br,{open:e,onOpenChange:t,children:o.jsxs(xr,{children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Run Options"}),o.jsx(Ks,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx($r,{children:o.jsx(gVn,{onSaved:()=>t(!1)})})]})})]})};function yVn({status:e}){switch(e){case"running":return o.jsx(Xt,{});case"failed":return o.jsx(bs,{className:"text-accent2"});case"canceled":return o.jsx(Nf,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(uT,{className:"text-neutral3"});case"suspended":return o.jsx(BV,{className:"text-accent3"});case"success":return o.jsx(fa,{className:"text-accent1"});default:return o.jsx(uT,{className:"text-neutral3"})}}function g1t({status:e}){return o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:o.jsx(qe,{"aria-label":e,className:"shrink-0",children:o.jsx(yVn,{status:e})})}),o.jsx(Rn,{children:e})]})}var ree,Ize;function zSe(){if(Ize)return ree;Ize=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 p=arguments,h=this;return d.forEach(function(m){p.length>1?h.setNode(m,f):h.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 p=h=>f.removeEdge(f._edgeObjs[h]);delete this._nodes[d],this._isCompound&&(this._removeFromParentsChildList(d),delete this._parent[d],this.children(d).forEach(function(h){f.setParent(h)}),delete this._children[d]),Object.keys(this._in[d]).forEach(p),delete this._in[d],delete this._preds[d],Object.keys(this._out[d]).forEach(p),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 p=f;p!==void 0;p=this.parent(p))if(p===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 h=new Set(f);for(var p of this.successors(d))h.add(p);return Array.from(h.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 p=this;Object.entries(this._nodes).forEach(function([g,y]){d(g)&&f.setNode(g,y)}),Object.values(this._edgeObjs).forEach(function(g){f.hasNode(g.v)&&f.hasNode(g.w)&&f.setEdge(g,p.edge(g))});var h={};function m(g){var y=p.parent(g);return y===void 0||f.hasNode(y)?(h[g]=y,y):y in h?h[y]:m(y)}return this._isCompound&&f.nodes().forEach(g=>f.setParent(g,m(g))),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 p=this,h=arguments;return d.reduce(function(m,g){return h.length>1?p.setEdge(m,g,f):p.setEdge(m,g),g}),this}setEdge(){var d,f,p,h,m=!1,g=arguments[0];typeof g=="object"&&g!==null&&"v"in g?(d=g.v,f=g.w,p=g.name,arguments.length===2&&(h=arguments[1],m=!0)):(d=g,f=arguments[1],p=arguments[3],arguments.length>2&&(h=arguments[2],m=!0)),d=""+d,f=""+f,p!==void 0&&(p=""+p);var y=i(this._isDirected,d,f,p);if(Object.hasOwn(this._edgeLabels,y))return m&&(this._edgeLabels[y]=h),this;if(p!==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?h:this._defaultEdgeLabelFn(d,f,p);var b=l(this._isDirected,d,f,p);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,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return this._edgeLabels[h]}edgeAsObj(){const d=this.edge(...arguments);return typeof d!="object"?{label:d}:d}hasEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return Object.hasOwn(this._edgeLabels,h)}removeEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p),m=this._edgeObjs[h];return m&&(d=m.v,f=m.w,delete this._edgeLabels[h],delete this._edgeObjs[h],a(this._preds[f],d),a(this._sucs[d],f),delete this._in[f][h],delete this._out[d][h],this._edgeCount--),this}inEdges(d,f){var p=this._in[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.v===f):h}}outEdges(d,f){var p=this._out[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.w===f):h}}nodeEdges(d,f){var p=this.inEdges(d,f);if(p)return p.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,p){var h=""+d,m=""+f;if(!u&&h>m){var g=h;h=m,m=g}return h+n+m+n+(p===void 0?e:p)}function l(u,d,f,p){var h=""+d,m=""+f;if(!u&&h>m){var g=h;h=m,m=g}var y={v:h,w:m};return p&&(y.name=p),y}function c(u,d){return i(u,d.v,d.w,d.name)}return ree=r,ree}var see,Aze;function bVn(){return Aze||(Aze=1,see="2.2.4"),see}var aee,Rze;function xVn(){return Rze||(Rze=1,aee={Graph:zSe(),version:bVn()}),aee}var iee,Pze;function wVn(){if(Pze)return iee;Pze=1;var e=zSe();iee={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 iee}var oee,$ze;function SVn(){if($ze)return oee;$ze=1,oee=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 oee}var lee,Mze;function v1t(){if(Mze)return lee;Mze=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 lee=e,lee}var cee,Dze;function y1t(){if(Dze)return cee;Dze=1;var e=v1t();cee=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,p=function(h){var m=h.v!==d?h.v:h.w,g=c[m],y=i(h),b=f.distance+y;if(y<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+h+" Weight: "+y);b<g.distance&&(g.distance=b,g.predecessor=d,u.decrease(m,b))};for(s.nodes().forEach(function(h){var m=h===a?0:Number.POSITIVE_INFINITY;c[h]={distance:m},u.add(h,m)});u.size()>0&&(d=u.removeMin(),f=c[d],f.distance!==Number.POSITIVE_INFINITY);)l(d).forEach(p);return c}return cee}var uee,Lze;function kVn(){if(Lze)return uee;Lze=1;var e=y1t();uee=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return uee}var dee,Fze;function b1t(){if(Fze)return dee;Fze=1,dee=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 dee}var fee,zze;function OVn(){if(zze)return fee;zze=1;var e=b1t();fee=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return fee}var pee,Bze;function _Vn(){if(Bze)return pee;Bze=1,pee=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(p){var h=f[c],m=u[p],g=f[p],y=h.distance+m.distance;y<g.distance&&(g.distance=y,g.predecessor=m.predecessor)})})}),i}return pee}var hee,Uze;function x1t(){if(Uze)return hee;Uze=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 hee=e,e.CycleException=t,hee}var mee,Vze;function CVn(){if(Vze)return mee;Vze=1;var e=x1t();mee=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return mee}var gee,qze;function w1t(){if(qze)return gee;qze=1,gee=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 gee}var vee,Hze;function EVn(){if(Hze)return vee;Hze=1;var e=w1t();vee=t;function t(n,r){return e(n,r,"post")}return vee}var yee,Wze;function jVn(){if(Wze)return yee;Wze=1;var e=w1t();yee=t;function t(n,r){return e(n,r,"pre")}return yee}var bee,Zze;function TVn(){if(Zze)return bee;Zze=1;var e=zSe(),t=v1t();bee=n;function n(r,s){var a=new e,i={},l=new t,c;function u(f){var p=f.v===c?f.w:f.v,h=l.priority(p);if(h!==void 0){var m=s(f);m<h&&(i[p]=c,l.decrease(p,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 bee}var xee,Gze;function NVn(){return Gze||(Gze=1,xee={components:SVn(),dijkstra:y1t(),dijkstraAll:kVn(),findCycles:OVn(),floydWarshall:_Vn(),isAcyclic:CVn(),postorder:EVn(),preorder:jVn(),prim:TVn(),tarjan:b1t(),topsort:x1t()}),xee}var wee,Qze;function Mg(){if(Qze)return wee;Qze=1;var e=xVn();return wee={Graph:e.Graph,json:wVn(),alg:NVn(),version:e.version},wee}var See,Yze;function IVn(){if(Yze)return See;Yze=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 See=e,See}var kee,Kze;function AVn(){if(Kze)return kee;Kze=1;let e=Mg().Graph,t=IVn();kee=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(h=>u.outEdges(h.v,h.w))}function s(u,d,f){let p=[],h=d[d.length-1],m=d[0],g;for(;u.nodeCount();){for(;g=m.dequeue();)a(u,d,f,g);for(;g=h.dequeue();)a(u,d,f,g);if(u.nodeCount()){for(let y=d.length-2;y>0;--y)if(g=d[y].dequeue(),g){p=p.concat(a(u,d,f,g,!0));break}}}return p}function a(u,d,f,p,h){let m=h?[]:void 0;return u.inEdges(p.v).forEach(g=>{let y=u.edge(g),b=u.node(g.v);h&&m.push({v:g.v,w:g.w}),b.out-=y,l(d,f,b)}),u.outEdges(p.v).forEach(g=>{let y=u.edge(g),b=g.w,x=u.node(b);x.in-=y,l(d,f,x)}),u.removeNode(p.v),m}function i(u,d){let f=new e,p=0,h=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),S=b+x;f.setEdge(y.v,y.w,S),h=Math.max(h,f.node(y.v).out+=x),p=Math.max(p,f.node(y.w).in+=x)});let m=c(h+p+3).map(()=>new t),g=p+1;return f.nodes().forEach(y=>{l(m,g,f.node(y))}),{graph:f,buckets:m,zeroIdx:g}}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 kee}var Oee,Xze;function Ml(){if(Xze)return Oee;Xze=1;let e=Mg().Graph;Oee={addBorderNode:d,addDummyNode:t,applyWithChunking:h,asNonCompoundGraph:r,buildLayerMatrix:l,intersectRect:i,mapValues:C,maxRank:m,normalizeRanks:c,notime:b,partition:g,pick:_,predecessorWeights:a,range:k,removeEmptyRanks:u,simplify:n,successorWeights:s,time:y,uniqueId:S,zipObject:E};function t(j,N,I,A){for(var R=A;j.hasNode(R);)R=S(A);return I.dummy=N,j.setNode(R,I),R}function n(j){let N=new e().setGraph(j.graph());return j.nodes().forEach(I=>N.setNode(I,j.node(I))),j.edges().forEach(I=>{let A=N.edge(I.v,I.w)||{weight:0,minlen:1},R=j.edge(I);N.setEdge(I.v,I.w,{weight:A.weight+R.weight,minlen:Math.max(A.minlen,R.minlen)})}),N}function r(j){let N=new e({multigraph:j.isMultigraph()}).setGraph(j.graph());return j.nodes().forEach(I=>{j.children(I).length||N.setNode(I,j.node(I))}),j.edges().forEach(I=>{N.setEdge(I,j.edge(I))}),N}function s(j){let N=j.nodes().map(I=>{let A={};return j.outEdges(I).forEach(R=>{A[R.w]=(A[R.w]||0)+j.edge(R).weight}),A});return E(j.nodes(),N)}function a(j){let N=j.nodes().map(I=>{let A={};return j.inEdges(I).forEach(R=>{A[R.v]=(A[R.v]||0)+j.edge(R).weight}),A});return E(j.nodes(),N)}function i(j,N){let I=j.x,A=j.y,R=N.x-I,L=N.y-A,D=j.width/2,B=j.height/2;if(!R&&!L)throw new Error("Not possible to find intersection inside of the rectangle");let H,F;return Math.abs(L)*D>Math.abs(R)*B?(L<0&&(B=-B),H=B*R/L,F=B):(R<0&&(D=-D),H=D,F=D*L/R),{x:I+H,y:A+F}}function l(j){let N=k(m(j)+1).map(()=>[]);return j.nodes().forEach(I=>{let A=j.node(I),R=A.rank;R!==void 0&&(N[R][A.order]=I)}),N}function c(j){let N=j.nodes().map(A=>{let R=j.node(A).rank;return R===void 0?Number.MAX_VALUE:R}),I=h(Math.min,N);j.nodes().forEach(A=>{let R=j.node(A);Object.hasOwn(R,"rank")&&(R.rank-=I)})}function u(j){let N=j.nodes().map(D=>j.node(D).rank),I=h(Math.min,N),A=[];j.nodes().forEach(D=>{let B=j.node(D).rank-I;A[B]||(A[B]=[]),A[B].push(D)});let R=0,L=j.graph().nodeRankFactor;Array.from(A).forEach((D,B)=>{D===void 0&&B%L!==0?--R:D!==void 0&&R&&D.forEach(H=>j.node(H).rank+=R)})}function d(j,N,I,A){let R={width:0,height:0};return arguments.length>=4&&(R.rank=I,R.order=A),t(j,"border",R,N)}function f(j,N=p){const I=[];for(let A=0;A<j.length;A+=N){const R=j.slice(A,A+N);I.push(R)}return I}const p=65535;function h(j,N){if(N.length>p){const I=f(N);return j.apply(null,I.map(A=>j.apply(null,A)))}else return j.apply(null,N)}function m(j){const I=j.nodes().map(A=>{let R=j.node(A).rank;return R===void 0?Number.MIN_VALUE:R});return h(Math.max,I)}function g(j,N){let I={lhs:[],rhs:[]};return j.forEach(A=>{N(A)?I.lhs.push(A):I.rhs.push(A)}),I}function y(j,N){let I=Date.now();try{return N()}finally{console.log(j+" time: "+(Date.now()-I)+"ms")}}function b(j,N){return N()}let x=0;function S(j){var N=++x;return j+(""+N)}function k(j,N,I=1){N==null&&(N=j,j=0);let A=L=>L<N;I<0&&(A=L=>N<L);const R=[];for(let L=j;A(L);L+=I)R.push(L);return R}function _(j,N){const I={};for(const A of N)j[A]!==void 0&&(I[A]=j[A]);return I}function C(j,N){let I=N;return typeof N=="string"&&(I=A=>A[N]),Object.entries(j).reduce((A,[R,L])=>(A[R]=I(L,R),A),{})}function E(j,N){return j.reduce((I,A,R)=>(I[A]=N[R],I),{})}return Oee}var _ee,Jze;function RVn(){if(Jze)return _ee;Jze=1;let e=AVn(),t=Ml().uniqueId;_ee={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 _ee}var Cee,e8e;function PVn(){if(e8e)return Cee;e8e=1;let e=Ml();Cee={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),p=f.labelRank;if(u===l+1)return;s.removeEdge(a);let h,m,g;for(g=0,++l;l<u;++g,++l)f.points=[],m={width:0,height:0,edgeLabel:f,edgeObj:a,rank:l},h=e.addDummyNode(s,"edge",m,"_d"),l===p&&(m.width=f.width,m.height=f.height,m.dummy="edge-label",m.labelpos=f.labelpos),s.setEdge(i,h,{weight:f.weight},d),g===0&&s.graph().dummyChains.push(h),i=h;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 Cee}var Eee,t8e;function bB(){if(t8e)return Eee;t8e=1;const{applyWithChunking:e}=Ml();Eee={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 Eee}var jee,n8e;function S1t(){if(n8e)return jee;n8e=1;var e=Mg().Graph,t=bB().slack;jee=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,p=u===f?d.w:f;!i.hasNode(p)&&!t(l,d)&&(i.setNode(p,{}),i.setEdge(u,p,{}),c(p))})}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 jee}var Tee,r8e;function $Vn(){if(r8e)return Tee;r8e=1;var e=S1t(),t=bB().slack,n=bB().longestPath,r=Mg().alg.preorder,s=Mg().alg.postorder,a=Ml().simplify;Tee=i,i.initLowLimValues=d,i.initCutValues=l,i.calcCutValue=u,i.leaveEdge=p,i.enterEdge=h,i.exchangeEdges=m;function i(x){x=a(x),n(x);var S=e(x);d(S),l(S,x);for(var k,_;k=p(S);)_=h(S,x,k),m(S,x,k,_)}function l(x,S){var k=s(x,x.nodes());k=k.slice(0,k.length-1),k.forEach(_=>c(x,S,_))}function c(x,S,k){var _=x.node(k),C=_.parent;x.edge(k,C).cutvalue=u(x,S,k)}function u(x,S,k){var _=x.node(k),C=_.parent,E=!0,j=S.edge(k,C),N=0;return j||(E=!1,j=S.edge(C,k)),N=j.weight,S.nodeEdges(k).forEach(I=>{var A=I.v===k,R=A?I.w:I.v;if(R!==C){var L=A===E,D=S.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,S){arguments.length<2&&(S=x.nodes()[0]),f(x,{},1,S)}function f(x,S,k,_,C){var E=k,j=x.node(_);return S[_]=!0,x.neighbors(_).forEach(N=>{Object.hasOwn(S,N)||(k=f(x,S,k,N,_))}),j.low=E,j.lim=k++,C?j.parent=C:delete j.parent,k}function p(x){return x.edges().find(S=>x.edge(S).cutvalue<0)}function h(x,S,k){var _=k.v,C=k.w;S.hasEdge(_,C)||(_=k.w,C=k.v);var E=x.node(_),j=x.node(C),N=E,I=!1;E.lim>j.lim&&(N=j,I=!0);var A=S.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(S,L)<t(S,R)?L:R)}function m(x,S,k,_){var C=k.v,E=k.w;x.removeEdge(C,E),x.setEdge(_.v,_.w,{}),d(x),l(x,S),g(x,S)}function g(x,S){var k=x.nodes().find(C=>!S.node(C).parent),_=r(x,k);_=_.slice(1),_.forEach(C=>{var E=x.node(C).parent,j=S.edge(C,E),N=!1;j||(j=S.edge(E,C),N=!0),S.node(C).rank=S.node(E).rank+(N?j.minlen:-j.minlen)})}function y(x,S,k){return x.hasEdge(S,k)}function b(x,S,k){return k.low<=S.lim&&S.lim<=k.lim}return Tee}var Nee,s8e;function MVn(){if(s8e)return Nee;s8e=1;var e=bB(),t=e.longestPath,n=S1t(),r=$Vn();Nee=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 Nee}var Iee,a8e;function DVn(){if(a8e)return Iee;a8e=1,Iee=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,p=u[f],h=!0;for(;a!==l.w;){if(i=r.node(a),h){for(;(p=u[f])!==d&&r.node(p).maxRank<i.rank;)f++;p===d&&(h=!1)}if(!h){for(;f<u.length-1&&r.node(p=u[f+1]).minRank<=i.rank;)f++;p=u[f]}r.setParent(a,p),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,p;f=a;do f=r.parent(f),l.push(f);while(f&&(s[f].low>u||d>s[f].lim));for(p=f,f=i;(f=r.parent(f))!==p;)c.push(f);return{path:l.concat(c.reverse()),lca:p}}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 Iee}var Aee,i8e;function LVn(){if(i8e)return Aee;i8e=1;let e=Ml();Aee={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(h=>i.edge(h).minlen*=f);let p=s(i)+1;i.children().forEach(h=>n(i,l,f,p,d,c,h)),i.graph().nodeRankFactor=f}function n(i,l,c,u,d,f,p){let h=i.children(p);if(!h.length){p!==l&&i.setEdge(l,p,{weight:0,minlen:c});return}let m=e.addBorderNode(i,"_bt"),g=e.addBorderNode(i,"_bb"),y=i.node(p);i.setParent(m,p),y.borderTop=m,i.setParent(g,p),y.borderBottom=g,h.forEach(b=>{n(i,l,c,u,d,f,b);let x=i.node(b),S=x.borderTop?x.borderTop:b,k=x.borderBottom?x.borderBottom:b,_=x.borderTop?u:2*u,C=S!==k?1:d-f[p]+1;i.setEdge(m,S,{weight:_,minlen:C,nestingEdge:!0}),i.setEdge(k,g,{weight:_,minlen:C,nestingEdge:!0})}),i.parent(p)||i.setEdge(l,m,{weight:0,minlen:d+f[p]})}function r(i){var l={};function c(u,d){var f=i.children(u);f&&f.length&&f.forEach(p=>c(p,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 Aee}var Ree,o8e;function FVn(){if(o8e)return Ree;o8e=1;let e=Ml();Ree=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 Ree}var Pee,l8e;function zVn(){if(l8e)return Pee;l8e=1,Pee={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 Pee}var $ee,c8e;function BVn(){if(c8e)return $ee;c8e=1;let e=Ml();$ee=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 $ee}var Mee,u8e;function UVn(){if(u8e)return Mee;u8e=1;let e=Ml().zipObject;Mee=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((p,h)=>h)),l=s.flatMap(p=>r.outEdges(p).map(h=>({pos:i[h.w],weight:r.edge(h).weight})).sort((h,m)=>h.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(p=>{let h=p.pos+c;d[h]+=p.weight;let m=0;for(;h>0;)h%2&&(m+=d[h+1]),h=h-1>>1,d[h]+=p.weight;f+=p.weight*m}),f}return Mee}var Dee,d8e;function VVn(){if(d8e)return Dee;d8e=1,Dee=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 Dee}var Lee,f8e;function qVn(){if(f8e)return Lee;f8e=1;let e=Ml();Lee=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 Lee}var Fee,p8e;function HVn(){if(p8e)return Fee;p8e=1;let e=Ml();Fee=t;function t(s,a){let i=e.partition(s,m=>Object.hasOwn(m,"barycenter")),l=i.lhs,c=i.rhs.sort((m,g)=>g.i-m.i),u=[],d=0,f=0,p=0;l.sort(r(!!a)),p=n(u,c,p),l.forEach(m=>{p+=m.vs.length,u.push(m.vs),d+=m.barycenter*m.weight,f+=m.weight,p=n(u,c,p)});let h={vs:u.flat(!0)};return f&&(h.barycenter=d/f,h.weight=f),h}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 Fee}var zee,h8e;function WVn(){if(h8e)return zee;h8e=1;let e=VVn(),t=qVn(),n=HVn();zee=r;function r(i,l,c,u){let d=i.children(l),f=i.node(l),p=f?f.borderLeft:void 0,h=f?f.borderRight:void 0,m={};p&&(d=d.filter(x=>x!==p&&x!==h));let g=e(i,d);g.forEach(x=>{if(i.children(x.v).length){let S=r(i,x.v,c,u);m[x.v]=S,Object.hasOwn(S,"barycenter")&&a(x,S)}});let y=t(g,c);s(y,m);let b=n(y,u);if(p&&(b.vs=[p,b.vs,h].flat(!0),i.predecessors(p).length)){let x=i.node(i.predecessors(p)[0]),S=i.node(i.predecessors(h)[0]);Object.hasOwn(b,"barycenter")||(b.barycenter=0,b.weight=0),b.barycenter=(b.barycenter*b.weight+x.order+S.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 zee}var Bee,m8e;function ZVn(){if(m8e)return Bee;m8e=1;let e=Mg().Graph,t=Ml();Bee=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),p=s.parent(d);(f.rank===a||f.minRank<=a&&a<=f.maxRank)&&(u.setNode(d),u.setParent(d,p||c),s[i](d).forEach(h=>{let m=h.v===d?h.w:h.v,g=u.edge(m,d),y=g!==void 0?g.weight:0;u.setEdge(m,d,{weight:s.edge(h).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 Bee}var Uee,g8e;function GVn(){if(g8e)return Uee;g8e=1,Uee=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 Uee}var Vee,v8e;function QVn(){if(v8e)return Vee;v8e=1;let e=BVn(),t=UVn(),n=WVn(),r=ZVn(),s=GVn(),a=Mg().Graph,i=Ml();Vee=l;function l(f,p){if(p&&typeof p.customOrder=="function"){p.customOrder(f,l);return}let h=i.maxRank(f),m=c(f,i.range(1,h+1),"inEdges"),g=c(f,i.range(h-1,-1,-1),"outEdges"),y=e(f);if(d(f,y),p&&p.disableOptimalOrderHeuristic)return;let b=Number.POSITIVE_INFINITY,x;for(let S=0,k=0;k<4;++S,++k){u(S%2?m:g,S%4>=2),y=i.buildLayerMatrix(f);let _=t(f,y);_<b&&(k=0,x=Object.assign({},y),b=_)}d(f,x)}function c(f,p,h){const m=new Map,g=(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"&&g(b.rank,y),typeof b.minRank=="number"&&typeof b.maxRank=="number")for(let x=b.minRank;x<=b.maxRank;x++)x!==b.rank&&g(x,y)}return p.map(function(y){return r(f,y,h,m.get(y)||[])})}function u(f,p){let h=new a;f.forEach(function(m){let g=m.graph().root,y=n(m,g,h,p);y.vs.forEach((b,x)=>m.node(b).order=x),s(m,h,y.vs)})}function d(f,p){Object.values(p).forEach(h=>h.forEach((m,g)=>f.node(m).order=g))}return Vee}var qee,y8e;function YVn(){if(y8e)return qee;y8e=1;let e=Mg().Graph,t=Ml();qee={positionX:h,findType1Conflicts:n,findType2Conflicts:r,addConflict:a,hasConflict:i,verticalAlignment:l,horizontalCompaction:c,alignCoordinates:f,findSmallestWidthAlignment:d,balance:p};function n(y,b){let x={};function S(k,_){let C=0,E=0,j=k.length,N=_[_.length-1];return _.forEach((I,A)=>{let R=s(y,I),L=R?y.node(R).order:j;(R||I===N)&&(_.slice(E,A+1).forEach(D=>{y.predecessors(D).forEach(B=>{let H=y.node(B),F=H.order;(F<C||L<F)&&!(H.dummy&&y.node(D).dummy)&&a(x,B,D)})}),E=A+1,C=L)}),_}return b.length&&b.reduce(S),x}function r(y,b){let x={};function S(_,C,E,j,N){let I;t.range(C,E).forEach(A=>{I=_[A],y.node(I).dummy&&y.predecessors(I).forEach(R=>{let L=y.node(R);L.dummy&&(L.order<j||L.order>N)&&a(x,R,I)})})}function k(_,C){let E=-1,j,N=0;return C.forEach((I,A)=>{if(y.node(I).dummy==="border"){let R=y.predecessors(I);R.length&&(j=y.node(R[0]).order,S(C,N,A,E,j),N=A,E=j)}S(C,N,C.length,j,_.length)}),C}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 S=y[b];S||(y[b]=S={}),S[x]=!0}function i(y,b,x){if(b>x){let S=b;b=x,x=S}return!!y[b]&&Object.hasOwn(y[b],x)}function l(y,b,x,S){let k={},_={},C={};return b.forEach(E=>{E.forEach((j,N)=>{k[j]=j,_[j]=j,C[j]=N})}),b.forEach(E=>{let j=-1;E.forEach(N=>{let I=S(N);if(I.length){I=I.sort((R,L)=>C[R]-C[L]);let A=(I.length-1)/2;for(let R=Math.floor(A),L=Math.ceil(A);R<=L;++R){let D=I[R];_[N]===N&&j<C[D]&&!i(x,N,D)&&(_[D]=N,_[N]=k[N]=k[D],j=C[D])}}})}),{root:k,align:_}}function c(y,b,x,S,k){let _={},C=u(y,b,x,k),E=k?"borderLeft":"borderRight";function j(A,R){let L=C.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){_[A]=C.inEdges(A).reduce((R,L)=>Math.max(R,_[L.v]+C.edge(L)),0)}function I(A){let R=C.outEdges(A).reduce((D,B)=>Math.min(D,_[B.w]-C.edge(B)),Number.POSITIVE_INFINITY),L=y.node(A);R!==Number.POSITIVE_INFINITY&&L.borderType!==E&&(_[A]=Math.max(_[A],R))}return j(N,C.predecessors.bind(C)),j(I,C.successors.bind(C)),Object.keys(S).forEach(A=>_[A]=_[x[A]]),_}function u(y,b,x,S){let k=new e,_=y.graph(),C=m(_.nodesep,_.edgesep,S);return b.forEach(E=>{let j;E.forEach(N=>{let I=x[N];if(k.setNode(I),j){var A=x[j],R=k.edge(A,I);k.setEdge(A,I,Math.max(C(y,N,j),R||0))}j=N})}),k}function d(y,b){return Object.values(b).reduce((x,S)=>{let k=Number.NEGATIVE_INFINITY,_=Number.POSITIVE_INFINITY;Object.entries(S).forEach(([E,j])=>{let N=g(y,E)/2;k=Math.max(j+N,k),_=Math.min(j-N,_)});const C=k-_;return C<x[0]&&(x=[C,S]),x},[Number.POSITIVE_INFINITY,null])[1]}function f(y,b){let x=Object.values(b),S=t.applyWithChunking(Math.min,x),k=t.applyWithChunking(Math.max,x);["u","d"].forEach(_=>{["l","r"].forEach(C=>{let E=_+C,j=y[E];if(j===b)return;let N=Object.values(j),I=S-t.applyWithChunking(Math.min,N);C!=="l"&&(I=k-t.applyWithChunking(Math.max,N)),I&&(y[E]=t.mapValues(j,A=>A+I))})})}function p(y,b){return t.mapValues(y.ul,(x,S)=>{if(b)return y[b.toLowerCase()][S];{let k=Object.values(y).map(_=>_[S]).sort((_,C)=>_-C);return(k[1]+k[2])/2}})}function h(y){let b=t.buildLayerMatrix(y),x=Object.assign(n(y,b),r(y,b)),S={},k;["u","d"].forEach(C=>{k=C==="u"?b:Object.values(b).reverse(),["l","r"].forEach(E=>{E==="r"&&(k=k.map(A=>Object.values(A).reverse()));let j=(C==="u"?y.predecessors:y.successors).bind(y),N=l(y,k,x,j),I=c(y,k,N.root,N.align,E==="r");E==="r"&&(I=t.mapValues(I,A=>-A)),S[C+E]=I})});let _=d(y,S);return f(S,_),p(S,y.graph().align)}function m(y,b,x){return(S,k,_)=>{let C=S.node(k),E=S.node(_),j=0,N;if(j+=C.width/2,Object.hasOwn(C,"labelpos"))switch(C.labelpos.toLowerCase()){case"l":N=-C.width/2;break;case"r":N=C.width/2;break}if(N&&(j+=x?N:-N),N=0,j+=(C.dummy?b:y)/2,j+=(E.dummy?b:y)/2,j+=E.width/2,Object.hasOwn(E,"labelpos"))switch(E.labelpos.toLowerCase()){case"l":N=E.width/2;break;case"r":N=-E.width/2;break}return N&&(j+=x?N:-N),N=0,j}}function g(y,b){return y.node(b).width}return qee}var Hee,b8e;function KVn(){if(b8e)return Hee;b8e=1;let e=Ml(),t=YVn().positionX;Hee=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 p=s.node(f).height;return d>p?d:p},0);c.forEach(d=>s.node(d).y=l+u/2),l+=u+i})}return Hee}var Wee,x8e;function XVn(){if(x8e)return Wee;x8e=1;let e=RVn(),t=PVn(),n=MVn(),r=Ml().normalizeRanks,s=DVn(),a=Ml().removeEmptyRanks,i=LVn(),l=FVn(),c=zVn(),u=QVn(),d=KVn(),f=Ml(),p=Mg().Graph;Wee=h;function h($,U){let Z=U&&U.debugTiming?f.time:f.notime;Z("layout",()=>{let K=Z(" buildLayoutGraph",()=>j($));Z(" runLayout",()=>m(K,Z,U)),Z(" updateInputGraph",()=>g($,K))})}function m($,U,Z){U(" makeSpaceForEdgeLabels",()=>N($)),U(" removeSelfEdges",()=>z($)),U(" acyclic",()=>e.run($)),U(" nestingGraph.run",()=>i.run($)),U(" rank",()=>n(f.asNonCompoundGraph($))),U(" injectEdgeLabelProxies",()=>I($)),U(" removeEmptyRanks",()=>a($)),U(" nestingGraph.cleanup",()=>i.cleanup($)),U(" normalizeRanks",()=>r($)),U(" assignRankMinMax",()=>A($)),U(" removeEdgeLabelProxies",()=>R($)),U(" normalize.run",()=>t.run($)),U(" parentDummyChains",()=>s($)),U(" addBorderSegments",()=>l($)),U(" order",()=>u($,Z)),U(" insertSelfEdges",()=>q($)),U(" adjustCoordinateSystem",()=>c.adjust($)),U(" position",()=>d($)),U(" positionSelfEdges",()=>M($)),U(" removeBorderNodes",()=>F($)),U(" normalize.undo",()=>t.undo($)),U(" fixupEdgeLabelCoords",()=>B($)),U(" undoCoordinateSystem",()=>c.undo($)),U(" translateGraph",()=>L($)),U(" assignNodeIntersects",()=>D($)),U(" reversePoints",()=>H($)),U(" acyclic.undo",()=>e.undo($))}function g($,U){$.nodes().forEach(Z=>{let K=$.node(Z),te=U.node(Z);K&&(K.x=te.x,K.y=te.y,K.rank=te.rank,U.children(Z).length&&(K.width=te.width,K.height=te.height))}),$.edges().forEach(Z=>{let K=$.edge(Z),te=U.edge(Z);K.points=te.points,Object.hasOwn(te,"x")&&(K.x=te.x,K.y=te.y)}),$.graph().width=U.graph().width,$.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"],S=["width","height","rank"],k={width:0,height:0},_=["minlen","weight","width","height","labeloffset"],C={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},E=["labelpos"];function j($){let U=new p({multigraph:!0,compound:!0}),Z=V($.graph());return U.setGraph(Object.assign({},b,G(Z,y),f.pick(Z,x))),$.nodes().forEach(K=>{let te=V($.node(K));const ee=G(te,S);Object.keys(k).forEach(J=>{ee[J]===void 0&&(ee[J]=k[J])}),U.setNode(K,ee),U.setParent(K,$.parent(K))}),$.edges().forEach(K=>{let te=V($.edge(K));U.setEdge(K,Object.assign({},C,G(te,_),f.pick(te,E)))}),U}function N($){let U=$.graph();U.ranksep/=2,$.edges().forEach(Z=>{let K=$.edge(Z);K.minlen*=2,K.labelpos.toLowerCase()!=="c"&&(U.rankdir==="TB"||U.rankdir==="BT"?K.width+=K.labeloffset:K.height+=K.labeloffset)})}function I($){$.edges().forEach(U=>{let Z=$.edge(U);if(Z.width&&Z.height){let K=$.node(U.v),ee={rank:($.node(U.w).rank-K.rank)/2+K.rank,e:U};f.addDummyNode($,"edge-proxy",ee,"_ep")}})}function A($){let U=0;$.nodes().forEach(Z=>{let K=$.node(Z);K.borderTop&&(K.minRank=$.node(K.borderTop).rank,K.maxRank=$.node(K.borderBottom).rank,U=Math.max(U,K.maxRank))}),$.graph().maxRank=U}function R($){$.nodes().forEach(U=>{let Z=$.node(U);Z.dummy==="edge-proxy"&&($.edge(Z.e).labelRank=Z.rank,$.removeNode(U))})}function L($){let U=Number.POSITIVE_INFINITY,Z=0,K=Number.POSITIVE_INFINITY,te=0,ee=$.graph(),J=ee.marginx||0,ae=ee.marginy||0;function de(Y){let ne=Y.x,fe=Y.y,oe=Y.width,le=Y.height;U=Math.min(U,ne-oe/2),Z=Math.max(Z,ne+oe/2),K=Math.min(K,fe-le/2),te=Math.max(te,fe+le/2)}$.nodes().forEach(Y=>de($.node(Y))),$.edges().forEach(Y=>{let ne=$.edge(Y);Object.hasOwn(ne,"x")&&de(ne)}),U-=J,K-=ae,$.nodes().forEach(Y=>{let ne=$.node(Y);ne.x-=U,ne.y-=K}),$.edges().forEach(Y=>{let ne=$.edge(Y);ne.points.forEach(fe=>{fe.x-=U,fe.y-=K}),Object.hasOwn(ne,"x")&&(ne.x-=U),Object.hasOwn(ne,"y")&&(ne.y-=K)}),ee.width=Z-U+J,ee.height=te-K+ae}function D($){$.edges().forEach(U=>{let Z=$.edge(U),K=$.node(U.v),te=$.node(U.w),ee,J;Z.points?(ee=Z.points[0],J=Z.points[Z.points.length-1]):(Z.points=[],ee=te,J=K),Z.points.unshift(f.intersectRect(K,ee)),Z.points.push(f.intersectRect(te,J))})}function B($){$.edges().forEach(U=>{let Z=$.edge(U);if(Object.hasOwn(Z,"x"))switch((Z.labelpos==="l"||Z.labelpos==="r")&&(Z.width-=Z.labeloffset),Z.labelpos){case"l":Z.x-=Z.width/2+Z.labeloffset;break;case"r":Z.x+=Z.width/2+Z.labeloffset;break}})}function H($){$.edges().forEach(U=>{let Z=$.edge(U);Z.reversed&&Z.points.reverse()})}function F($){$.nodes().forEach(U=>{if($.children(U).length){let Z=$.node(U),K=$.node(Z.borderTop),te=$.node(Z.borderBottom),ee=$.node(Z.borderLeft[Z.borderLeft.length-1]),J=$.node(Z.borderRight[Z.borderRight.length-1]);Z.width=Math.abs(J.x-ee.x),Z.height=Math.abs(te.y-K.y),Z.x=ee.x+Z.width/2,Z.y=K.y+Z.height/2}}),$.nodes().forEach(U=>{$.node(U).dummy==="border"&&$.removeNode(U)})}function z($){$.edges().forEach(U=>{if(U.v===U.w){var Z=$.node(U.v);Z.selfEdges||(Z.selfEdges=[]),Z.selfEdges.push({e:U,label:$.edge(U)}),$.removeEdge(U)}})}function q($){var U=f.buildLayerMatrix($);U.forEach(Z=>{var K=0;Z.forEach((te,ee)=>{var J=$.node(te);J.order=ee+K,(J.selfEdges||[]).forEach(ae=>{f.addDummyNode($,"selfedge",{width:ae.label.width,height:ae.label.height,rank:J.rank,order:ee+ ++K,e:ae.e,label:ae.label},"_se")}),delete J.selfEdges})})}function M($){$.nodes().forEach(U=>{var Z=$.node(U);if(Z.dummy==="selfedge"){var K=$.node(Z.e.v),te=K.x+K.width/2,ee=K.y,J=Z.x-te,ae=K.height/2;$.setEdge(Z.e,Z.label),$.removeNode(U),Z.label.points=[{x:te+2*J/3,y:ee-ae},{x:te+5*J/6,y:ee-ae},{x:te+J,y:ee},{x:te+5*J/6,y:ee+ae},{x:te+2*J/3,y:ee+ae}],Z.label.x=Z.x,Z.label.y=Z.y}})}function G($,U){return f.mapValues(f.pick($,U),Number)}function V($){var U={};return $&&Object.entries($).forEach(([Z,K])=>{typeof Z=="string"&&(Z=Z.toLowerCase()),U[Z]=K}),U}return Wee}var Zee,w8e;function JVn(){if(w8e)return Zee;w8e=1;let e=Ml(),t=Mg().Graph;Zee={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 Zee}var Gee,S8e;function eqn(){return S8e||(S8e=1,Gee="1.1.8"),Gee}var Qee,k8e;function tqn(){return k8e||(k8e=1,Qee={graphlib:Mg(),layout:XVn(),debug:JVn(),util:{time:Ml().time,notime:Ml().notime},version:eqn()}),Qee}var nqn=tqn();const O8e=Fl(nqn);function Ul(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=Ul(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var rqn={value:()=>{}};function TH(){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 N8(n)}function N8(e){this._=e}function sqn(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}})}N8.prototype=TH.prototype={constructor:N8,on:function(e,t){var n=this._,r=sqn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=aqn(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]=_8e(n[s],e.name,t);else if(t==null)for(s in n)n[s]=_8e(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 N8(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 aqn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function _8e(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=rqn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Gme="http://www.w3.org/1999/xhtml";const C8e={svg:"http://www.w3.org/2000/svg",xhtml:Gme,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function NH(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),C8e.hasOwnProperty(t)?{space:C8e[t],local:e}:e}function iqn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Gme&&t.documentElement.namespaceURI===Gme?t.createElement(e):t.createElementNS(n,e)}}function oqn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function k1t(e){var t=NH(e);return(t.local?oqn:iqn)(t)}function lqn(){}function BSe(e){return e==null?lqn:function(){return this.querySelector(e)}}function cqn(e){typeof e!="function"&&(e=BSe(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 Hp(r,this._parents)}function uqn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function dqn(){return[]}function O1t(e){return e==null?dqn:function(){return this.querySelectorAll(e)}}function fqn(e){return function(){return uqn(e.apply(this,arguments))}}function pqn(e){typeof e=="function"?e=fqn(e):e=O1t(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 Hp(r,s)}function _1t(e){return function(){return this.matches(e)}}function C1t(e){return function(t){return t.matches(e)}}var hqn=Array.prototype.find;function mqn(e){return function(){return hqn.call(this.children,e)}}function gqn(){return this.firstElementChild}function vqn(e){return this.select(e==null?gqn:mqn(typeof e=="function"?e:C1t(e)))}var yqn=Array.prototype.filter;function bqn(){return Array.from(this.children)}function xqn(e){return function(){return yqn.call(this.children,e)}}function wqn(e){return this.selectAll(e==null?bqn:xqn(typeof e=="function"?e:C1t(e)))}function Sqn(e){typeof e!="function"&&(e=_1t(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 Hp(r,this._parents)}function E1t(e){return new Array(e.length)}function kqn(){return new Hp(this._enter||this._groups.map(E1t),this._parents)}function xB(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}xB.prototype={constructor:xB,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 Oqn(e){return function(){return e}}function _qn(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 xB(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function Cqn(e,t,n,r,s,a,i){var l,c,u=new Map,d=t.length,f=a.length,p=new Array(d),h;for(l=0;l<d;++l)(c=t[l])&&(p[l]=h=i.call(c,c.__data__,l,t)+"",u.has(h)?s[l]=c:u.set(h,c));for(l=0;l<f;++l)h=i.call(e,a[l],l,a)+"",(c=u.get(h))?(r[l]=c,c.__data__=a[l],u.delete(h)):n[l]=new xB(e,a[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(p[l])===c&&(s[l]=c)}function Eqn(e){return e.__data__}function jqn(e,t){if(!arguments.length)return Array.from(this,Eqn);var n=t?Cqn:_qn,r=this._parents,s=this._groups;typeof e!="function"&&(e=Oqn(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],p=f.length,h=Tqn(e.call(d,d&&d.__data__,u,r)),m=h.length,g=l[u]=new Array(m),y=i[u]=new Array(m),b=c[u]=new Array(p);n(d,f,g,y,b,h,t);for(var x=0,S=0,k,_;x<m;++x)if(k=g[x]){for(x>=S&&(S=x+1);!(_=y[S])&&++S<m;);k._next=_||null}}return i=new Hp(i,r),i._enter=l,i._exit=c,i}function Tqn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function Nqn(){return new Hp(this._exit||this._groups.map(E1t),this._parents)}function Iqn(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 Aqn(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,p=l[c]=new Array(f),h,m=0;m<f;++m)(h=u[m]||d[m])&&(p[m]=h);for(;c<s;++c)l[c]=n[c];return new Hp(l,this._parents)}function Rqn(){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 Pqn(e){e||(e=$qn);function t(f,p){return f&&p?e(f.__data__,p.__data__):!f-!p}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 Hp(s,this._parents).order()}function $qn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function Mqn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function Dqn(){return Array.from(this)}function Lqn(){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 Fqn(){let e=0;for(const t of this)++e;return e}function zqn(){return!this.node()}function Bqn(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 Uqn(e){return function(){this.removeAttribute(e)}}function Vqn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function qqn(e,t){return function(){this.setAttribute(e,t)}}function Hqn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function Wqn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function Zqn(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 Gqn(e,t){var n=NH(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?Vqn:Uqn:typeof t=="function"?n.local?Zqn:Wqn:n.local?Hqn:qqn)(n,t))}function j1t(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function Qqn(e){return function(){this.style.removeProperty(e)}}function Yqn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function Kqn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function Xqn(e,t,n){return arguments.length>1?this.each((t==null?Qqn:typeof t=="function"?Kqn:Yqn)(e,t,n??"")):UT(this.node(),e)}function UT(e,t){return e.style.getPropertyValue(t)||j1t(e).getComputedStyle(e,null).getPropertyValue(t)}function Jqn(e){return function(){delete this[e]}}function eHn(e,t){return function(){this[e]=t}}function tHn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function nHn(e,t){return arguments.length>1?this.each((t==null?Jqn:typeof t=="function"?tHn:eHn)(e,t)):this.node()[e]}function T1t(e){return e.trim().split(/^|\s+/)}function USe(e){return e.classList||new N1t(e)}function N1t(e){this._node=e,this._names=T1t(e.getAttribute("class")||"")}N1t.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 I1t(e,t){for(var n=USe(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function A1t(e,t){for(var n=USe(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function rHn(e){return function(){I1t(this,e)}}function sHn(e){return function(){A1t(this,e)}}function aHn(e,t){return function(){(t.apply(this,arguments)?I1t:A1t)(this,e)}}function iHn(e,t){var n=T1t(e+"");if(arguments.length<2){for(var r=USe(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?aHn:t?rHn:sHn)(n,t))}function oHn(){this.textContent=""}function lHn(e){return function(){this.textContent=e}}function cHn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function uHn(e){return arguments.length?this.each(e==null?oHn:(typeof e=="function"?cHn:lHn)(e)):this.node().textContent}function dHn(){this.innerHTML=""}function fHn(e){return function(){this.innerHTML=e}}function pHn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function hHn(e){return arguments.length?this.each(e==null?dHn:(typeof e=="function"?pHn:fHn)(e)):this.node().innerHTML}function mHn(){this.nextSibling&&this.parentNode.appendChild(this)}function gHn(){return this.each(mHn)}function vHn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function yHn(){return this.each(vHn)}function bHn(e){var t=typeof e=="function"?e:k1t(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function xHn(){return null}function wHn(e,t){var n=typeof e=="function"?e:k1t(e),r=t==null?xHn:typeof t=="function"?t:BSe(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function SHn(){var e=this.parentNode;e&&e.removeChild(this)}function kHn(){return this.each(SHn)}function OHn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function _Hn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function CHn(e){return this.select(e?_Hn:OHn)}function EHn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function jHn(e){return function(t){e.call(this,t,this.__data__)}}function THn(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 NHn(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 IHn(e,t,n){return function(){var r=this.__on,s,a=jHn(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 AHn(e,t,n){var r=THn(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?IHn:NHn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function R1t(e,t,n){var r=j1t(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 RHn(e,t){return function(){return R1t(this,e,t)}}function PHn(e,t){return function(){return R1t(this,e,t.apply(this,arguments))}}function $Hn(e,t){return this.each((typeof t=="function"?PHn:RHn)(e,t))}function*MHn(){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 P1t=[null];function Hp(e,t){this._groups=e,this._parents=t}function M3(){return new Hp([[document.documentElement]],P1t)}function DHn(){return this}Hp.prototype=M3.prototype={constructor:Hp,select:cqn,selectAll:pqn,selectChild:vqn,selectChildren:wqn,filter:Sqn,data:jqn,enter:kqn,exit:Nqn,join:Iqn,merge:Aqn,selection:DHn,order:Rqn,sort:Pqn,call:Mqn,nodes:Dqn,node:Lqn,size:Fqn,empty:zqn,each:Bqn,attr:Gqn,style:Xqn,property:nHn,classed:iHn,text:uHn,html:hHn,raise:gHn,lower:yHn,append:bHn,insert:wHn,remove:kHn,clone:CHn,datum:EHn,on:AHn,dispatch:$Hn,[Symbol.iterator]:MHn};function Sp(e){return typeof e=="string"?new Hp([[document.querySelector(e)]],[document.documentElement]):new Hp([[e]],P1t)}function LHn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function rg(e,t){if(e=LHn(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 FHn={passive:!1},kM={capture:!0,passive:!1};function Yee(e){e.stopImmediatePropagation()}function Hj(e){e.preventDefault(),e.stopImmediatePropagation()}function $1t(e){var t=e.document.documentElement,n=Sp(e).on("dragstart.drag",Hj,kM);"onselectstart"in t?n.on("selectstart.drag",Hj,kM):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function M1t(e,t){var n=e.document.documentElement,r=Sp(e).on("dragstart.drag",null);t&&(r.on("click.drag",Hj,kM),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 J6=e=>()=>e;function Qme(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}})}Qme.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function zHn(e){return!e.ctrlKey&&!e.button}function BHn(){return this.parentNode}function UHn(e,t){return t??{x:e.x,y:e.y}}function VHn(){return navigator.maxTouchPoints||"ontouchstart"in this}function D1t(){var e=zHn,t=BHn,n=UHn,r=VHn,s={},a=TH("start","drag","end"),i=0,l,c,u,d,f=0;function p(k){k.on("mousedown.drag",h).filter(r).on("touchstart.drag",y).on("touchmove.drag",b,FHn).on("touchend.drag touchcancel.drag",x).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function h(k,_){if(!(d||!e.call(this,k,_))){var C=S(this,t.call(this,k,_),k,_,"mouse");C&&(Sp(k.view).on("mousemove.drag",m,kM).on("mouseup.drag",g,kM),$1t(k.view),Yee(k),u=!1,l=k.clientX,c=k.clientY,C("start",k))}}function m(k){if(Hj(k),!u){var _=k.clientX-l,C=k.clientY-c;u=_*_+C*C>f}s.mouse("drag",k)}function g(k){Sp(k.view).on("mousemove.drag mouseup.drag",null),M1t(k.view,u),Hj(k),s.mouse("end",k)}function y(k,_){if(e.call(this,k,_)){var C=k.changedTouches,E=t.call(this,k,_),j=C.length,N,I;for(N=0;N<j;++N)(I=S(this,E,k,_,C[N].identifier,C[N]))&&(Yee(k),I("start",k,C[N]))}}function b(k){var _=k.changedTouches,C=_.length,E,j;for(E=0;E<C;++E)(j=s[_[E].identifier])&&(Hj(k),j("drag",k,_[E]))}function x(k){var _=k.changedTouches,C=_.length,E,j;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),E=0;E<C;++E)(j=s[_[E].identifier])&&(Yee(k),j("end",k,_[E]))}function S(k,_,C,E,j,N){var I=a.copy(),A=rg(N||C,_),R,L,D;if((D=n.call(k,new Qme("beforestart",{sourceEvent:C,target:p,identifier:j,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),E))!=null)return R=D.x-A[0]||0,L=D.y-A[1]||0,function B(H,F,z){var q=A,M;switch(H){case"start":s[j]=B,M=i++;break;case"end":delete s[j],--i;case"drag":A=rg(z||F,_),M=i;break}I.call(H,k,new Qme(H,{sourceEvent:F,subject:D,target:p,identifier:j,active:M,x:A[0]+R,y:A[1]+L,dx:A[0]-q[0],dy:A[1]-q[1],dispatch:I}),E)}}return p.filter=function(k){return arguments.length?(e=typeof k=="function"?k:J6(!!k),p):e},p.container=function(k){return arguments.length?(t=typeof k=="function"?k:J6(k),p):t},p.subject=function(k){return arguments.length?(n=typeof k=="function"?k:J6(k),p):n},p.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:J6(!!k),p):r},p.on=function(){var k=a.on.apply(a,arguments);return k===a?p:k},p.clickDistance=function(k){return arguments.length?(f=(k=+k)*k,p):Math.sqrt(f)},p}function VSe(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function L1t(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function D3(){}var OM=.7,wB=1/OM,Wj="\\s*([+-]?\\d+)\\s*",_M="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",ry="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",qHn=/^#([0-9a-f]{3,8})$/,HHn=new RegExp(`^rgb\\(${Wj},${Wj},${Wj}\\)$`),WHn=new RegExp(`^rgb\\(${ry},${ry},${ry}\\)$`),ZHn=new RegExp(`^rgba\\(${Wj},${Wj},${Wj},${_M}\\)$`),GHn=new RegExp(`^rgba\\(${ry},${ry},${ry},${_M}\\)$`),QHn=new RegExp(`^hsl\\(${_M},${ry},${ry}\\)$`),YHn=new RegExp(`^hsla\\(${_M},${ry},${ry},${_M}\\)$`),E8e={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};VSe(D3,VO,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:j8e,formatHex:j8e,formatHex8:KHn,formatHsl:XHn,formatRgb:T8e,toString:T8e});function j8e(){return this.rgb().formatHex()}function KHn(){return this.rgb().formatHex8()}function XHn(){return F1t(this).formatHsl()}function T8e(){return this.rgb().formatRgb()}function VO(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=qHn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?N8e(t):n===3?new pf(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?eF(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?eF(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=HHn.exec(e))?new pf(t[1],t[2],t[3],1):(t=WHn.exec(e))?new pf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=ZHn.exec(e))?eF(t[1],t[2],t[3],t[4]):(t=GHn.exec(e))?eF(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=QHn.exec(e))?R8e(t[1],t[2]/100,t[3]/100,1):(t=YHn.exec(e))?R8e(t[1],t[2]/100,t[3]/100,t[4]):E8e.hasOwnProperty(e)?N8e(E8e[e]):e==="transparent"?new pf(NaN,NaN,NaN,0):null}function N8e(e){return new pf(e>>16&255,e>>8&255,e&255,1)}function eF(e,t,n,r){return r<=0&&(e=t=n=NaN),new pf(e,t,n,r)}function JHn(e){return e instanceof D3||(e=VO(e)),e?(e=e.rgb(),new pf(e.r,e.g,e.b,e.opacity)):new pf}function Yme(e,t,n,r){return arguments.length===1?JHn(e):new pf(e,t,n,r??1)}function pf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}VSe(pf,Yme,L1t(D3,{brighter(e){return e=e==null?wB:Math.pow(wB,e),new pf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?OM:Math.pow(OM,e),new pf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new pf(Kk(this.r),Kk(this.g),Kk(this.b),SB(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:I8e,formatHex:I8e,formatHex8:eWn,formatRgb:A8e,toString:A8e}));function I8e(){return`#${Ak(this.r)}${Ak(this.g)}${Ak(this.b)}`}function eWn(){return`#${Ak(this.r)}${Ak(this.g)}${Ak(this.b)}${Ak((isNaN(this.opacity)?1:this.opacity)*255)}`}function A8e(){const e=SB(this.opacity);return`${e===1?"rgb(":"rgba("}${Kk(this.r)}, ${Kk(this.g)}, ${Kk(this.b)}${e===1?")":`, ${e})`}`}function SB(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Kk(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Ak(e){return e=Kk(e),(e<16?"0":"")+e.toString(16)}function R8e(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new ug(e,t,n,r)}function F1t(e){if(e instanceof ug)return new ug(e.h,e.s,e.l,e.opacity);if(e instanceof D3||(e=VO(e)),!e)return new ug;if(e instanceof ug)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 ug(i,l,c,e.opacity)}function tWn(e,t,n,r){return arguments.length===1?F1t(e):new ug(e,t,n,r??1)}function ug(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}VSe(ug,tWn,L1t(D3,{brighter(e){return e=e==null?wB:Math.pow(wB,e),new ug(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?OM:Math.pow(OM,e),new ug(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 pf(Kee(e>=240?e-240:e+120,s,r),Kee(e,s,r),Kee(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new ug(P8e(this.h),tF(this.s),tF(this.l),SB(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=SB(this.opacity);return`${e===1?"hsl(":"hsla("}${P8e(this.h)}, ${tF(this.s)*100}%, ${tF(this.l)*100}%${e===1?")":`, ${e})`}`}}));function P8e(e){return e=(e||0)%360,e<0?e+360:e}function tF(e){return Math.max(0,Math.min(1,e||0))}function Kee(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 qSe=e=>()=>e;function nWn(e,t){return function(n){return e+n*t}}function rWn(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 sWn(e){return(e=+e)==1?z1t:function(t,n){return n-t?rWn(t,n,e):qSe(isNaN(t)?n:t)}}function z1t(e,t){var n=t-e;return n?nWn(e,n):qSe(isNaN(e)?t:e)}const kB=(function e(t){var n=sWn(t);function r(s,a){var i=n((s=Yme(s)).r,(a=Yme(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=z1t(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 aWn(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 iWn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function oWn(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]=lx(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 lWn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function ag(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function cWn(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]=lx(e[s],t[s]):r[s]=t[s];return function(a){for(s in n)r[s]=n[s](a);return r}}var Kme=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Xee=new RegExp(Kme.source,"g");function uWn(e){return function(){return e}}function dWn(e){return function(t){return e(t)+""}}function B1t(e,t){var n=Kme.lastIndex=Xee.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Kme.exec(e))&&(s=Xee.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:ag(r,s)})),n=Xee.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?dWn(c[0].x):uWn(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 lx(e,t){var n=typeof t,r;return t==null||n==="boolean"?qSe(t):(n==="number"?ag:n==="string"?(r=VO(t))?(t=r,kB):B1t:t instanceof VO?kB:t instanceof Date?lWn:iWn(t)?aWn:Array.isArray(t)?oWn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?cWn:ag)(e,t)}function HSe(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var $8e=180/Math.PI,Xme={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function U1t(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)*$8e,skewX:Math.atan(c)*$8e,scaleX:i,scaleY:l}}var nF;function fWn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Xme:U1t(t.a,t.b,t.c,t.d,t.e,t.f)}function pWn(e){return e==null||(nF||(nF=document.createElementNS("http://www.w3.org/2000/svg","g")),nF.setAttribute("transform",e),!(e=nF.transform.baseVal.consolidate()))?Xme:(e=e.matrix,U1t(e.a,e.b,e.c,e.d,e.e,e.f))}function V1t(e,t,n,r){function s(u){return u.length?u.pop()+" ":""}function a(u,d,f,p,h,m){if(u!==f||d!==p){var g=h.push("translate(",null,t,null,n);m.push({i:g-4,x:ag(u,f)},{i:g-2,x:ag(d,p)})}else(f||p)&&h.push("translate("+f+t+p+n)}function i(u,d,f,p){u!==d?(u-d>180?d+=360:d-u>180&&(u+=360),p.push({i:f.push(s(f)+"rotate(",null,r)-2,x:ag(u,d)})):d&&f.push(s(f)+"rotate("+d+r)}function l(u,d,f,p){u!==d?p.push({i:f.push(s(f)+"skewX(",null,r)-2,x:ag(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,p,h,m){if(u!==f||d!==p){var g=h.push(s(h)+"scale(",null,",",null,")");m.push({i:g-4,x:ag(u,f)},{i:g-2,x:ag(d,p)})}else(f!==1||p!==1)&&h.push(s(h)+"scale("+f+","+p+")")}return function(u,d){var f=[],p=[];return u=e(u),d=e(d),a(u.translateX,u.translateY,d.translateX,d.translateY,f,p),i(u.rotate,d.rotate,f,p),l(u.skewX,d.skewX,f,p),c(u.scaleX,u.scaleY,d.scaleX,d.scaleY,f,p),u=d=null,function(h){for(var m=-1,g=p.length,y;++m<g;)f[(y=p[m]).i]=y.x(h);return f.join("")}}}var hWn=V1t(fWn,"px, ","px)","deg)"),mWn=V1t(pWn,", ",")",")"),gWn=1e-12;function M8e(e){return((e=Math.exp(e))+1/e)/2}function vWn(e){return((e=Math.exp(e))-1/e)/2}function yWn(e){return((e=Math.exp(2*e))-1)/(e+1)}const I8=(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],p=i[2],h=d-l,m=f-c,g=h*h+m*m,y,b;if(g<gWn)b=Math.log(p/u)/t,y=function(E){return[l+E*h,c+E*m,u*Math.exp(t*E*b)]};else{var x=Math.sqrt(g),S=(p*p-u*u+r*g)/(2*u*n*x),k=(p*p-u*u-r*g)/(2*p*n*x),_=Math.log(Math.sqrt(S*S+1)-S),C=Math.log(Math.sqrt(k*k+1)-k);b=(C-_)/t,y=function(E){var j=E*b,N=M8e(_),I=u/(n*x)*(N*yWn(t*j+_)-vWn(_));return[l+I*h,c+I*m,u*N/M8e(t*j+_)]}}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 bWn(e,t){t===void 0&&(t=e,e=lx);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 VT=0,$P=0,bR=0,q1t=1e3,OB,MP,_B=0,qO=0,IH=0,CM=typeof performance=="object"&&performance.now?performance:Date,H1t=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function WSe(){return qO||(H1t(xWn),qO=CM.now()+IH)}function xWn(){qO=0}function CB(){this._call=this._time=this._next=null}CB.prototype=W1t.prototype={constructor:CB,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?WSe():+n)+(t==null?0:+t),!this._next&&MP!==this&&(MP?MP._next=this:OB=this,MP=this),this._call=e,this._time=n,Jme()},stop:function(){this._call&&(this._call=null,this._time=1/0,Jme())}};function W1t(e,t,n){var r=new CB;return r.restart(e,t,n),r}function wWn(){WSe(),++VT;for(var e=OB,t;e;)(t=qO-e._time)>=0&&e._call.call(void 0,t),e=e._next;--VT}function D8e(){qO=(_B=CM.now())+IH,VT=$P=0;try{wWn()}finally{VT=0,kWn(),qO=0}}function SWn(){var e=CM.now(),t=e-_B;t>q1t&&(IH-=t,_B=e)}function kWn(){for(var e,t=OB,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:OB=n);MP=e,Jme(r)}function Jme(e){if(!VT){$P&&($P=clearTimeout($P));var t=e-qO;t>24?(e<1/0&&($P=setTimeout(D8e,e-CM.now()-IH)),bR&&(bR=clearInterval(bR))):(bR||(_B=CM.now(),bR=setInterval(SWn,q1t)),VT=1,H1t(D8e))}}function L8e(e,t,n){var r=new CB;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var OWn=TH("start","end","cancel","interrupt"),_Wn=[],Z1t=0,F8e=1,ege=2,A8=3,z8e=4,tge=5,R8=6;function AH(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;CWn(e,n,{name:t,index:r,group:s,on:OWn,tween:_Wn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:Z1t})}function ZSe(e,t){var n=Hg(e,t);if(n.state>Z1t)throw new Error("too late; already scheduled");return n}function zy(e,t){var n=Hg(e,t);if(n.state>A8)throw new Error("too late; already running");return n}function Hg(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function CWn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=W1t(a,0,n.time);function a(u){n.state=F8e,n.timer.restart(i,n.delay,n.time),n.delay<=u&&i(u-n.delay)}function i(u){var d,f,p,h;if(n.state!==F8e)return c();for(d in r)if(h=r[d],h.name===n.name){if(h.state===A8)return L8e(i);h.state===z8e?(h.state=R8,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete r[d]):+d<t&&(h.state=R8,h.timer.stop(),h.on.call("cancel",e,e.__data__,h.index,h.group),delete r[d])}if(L8e(function(){n.state===A8&&(n.state=z8e,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=ege,n.on.call("start",e,e.__data__,n.index,n.group),n.state===ege){for(n.state=A8,s=new Array(p=n.tween.length),d=0,f=-1;d<p;++d)(h=n.tween[d].value.call(e,e.__data__,n.index,n.group))&&(s[++f]=h);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=tge,1),f=-1,p=s.length;++f<p;)s[f].call(e,d);n.state===tge&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=R8,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function P8(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>ege&&r.state<tge,r.state=R8,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function EWn(e){return this.each(function(){P8(this,e)})}function jWn(e,t){var n,r;return function(){var s=zy(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 TWn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=zy(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 NWn(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Hg(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?jWn:TWn)(n,e,t))}function GSe(e,t,n){var r=e._id;return e.each(function(){var s=zy(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return Hg(s,r).value[t]}}function G1t(e,t){var n;return(typeof t=="number"?ag:t instanceof VO?kB:(n=VO(t))?(t=n,kB):B1t)(e,t)}function IWn(e){return function(){this.removeAttribute(e)}}function AWn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function RWn(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 PWn(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 $Wn(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 MWn(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 DWn(e,t){var n=NH(e),r=n==="transform"?mWn:G1t;return this.attrTween(e,typeof t=="function"?(n.local?MWn:$Wn)(n,r,GSe(this,"attr."+e,t)):t==null?(n.local?AWn:IWn)(n):(n.local?PWn:RWn)(n,r,t))}function LWn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function FWn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function zWn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&FWn(e,a)),n}return s._value=t,s}function BWn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&LWn(e,a)),n}return s._value=t,s}function UWn(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=NH(e);return this.tween(n,(r.local?zWn:BWn)(r,t))}function VWn(e,t){return function(){ZSe(this,e).delay=+t.apply(this,arguments)}}function qWn(e,t){return t=+t,function(){ZSe(this,e).delay=t}}function HWn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?VWn:qWn)(t,e)):Hg(this.node(),t).delay}function WWn(e,t){return function(){zy(this,e).duration=+t.apply(this,arguments)}}function ZWn(e,t){return t=+t,function(){zy(this,e).duration=t}}function GWn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?WWn:ZWn)(t,e)):Hg(this.node(),t).duration}function QWn(e,t){if(typeof t!="function")throw new Error;return function(){zy(this,e).ease=t}}function YWn(e){var t=this._id;return arguments.length?this.each(QWn(t,e)):Hg(this.node(),t).ease}function KWn(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;zy(this,e).ease=n}}function XWn(e){if(typeof e!="function")throw new Error;return this.each(KWn(this._id,e))}function JWn(e){typeof e!="function"&&(e=_1t(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 jx(r,this._parents,this._name,this._id)}function eZn(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),p,h=0;h<d;++h)(p=c[h]||u[h])&&(f[h]=p);for(;l<r;++l)i[l]=t[l];return new jx(i,this._parents,this._name,this._id)}function tZn(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 nZn(e,t,n){var r,s,a=tZn(t)?ZSe:zy;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function rZn(e,t){var n=this._id;return arguments.length<2?Hg(this.node(),n).on.on(e):this.each(nZn(n,e,t))}function sZn(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function aZn(){return this.on("end.remove",sZn(this._id))}function iZn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=BSe(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,p=0;p<c;++p)(d=l[p])&&(f=e.call(d,d.__data__,p,l))&&("__data__"in d&&(f.__data__=d.__data__),u[p]=f,AH(u[p],t,n,p,u,Hg(d,n)));return new jx(a,this._parents,t,n)}function oZn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=O1t(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 p=e.call(d,d.__data__,f,c),h,m=Hg(d,n),g=0,y=p.length;g<y;++g)(h=p[g])&&AH(h,t,n,g,p,m);a.push(p),i.push(d)}return new jx(a,i,t,n)}var lZn=M3.prototype.constructor;function cZn(){return new lZn(this._groups,this._parents)}function uZn(e,t){var n,r,s;return function(){var a=UT(this,e),i=(this.style.removeProperty(e),UT(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function Q1t(e){return function(){this.style.removeProperty(e)}}function dZn(e,t,n){var r,s=n+"",a;return function(){var i=UT(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function fZn(e,t,n){var r,s,a;return function(){var i=UT(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),UT(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function pZn(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=zy(this,e),u=c.on,d=c.value[a]==null?l||(l=Q1t(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function hZn(e,t,n){var r=(e+="")=="transform"?hWn:G1t;return t==null?this.styleTween(e,uZn(e,r)).on("end.style."+e,Q1t(e)):typeof t=="function"?this.styleTween(e,fZn(e,r,GSe(this,"style."+e,t))).each(pZn(this._id,e)):this.styleTween(e,dZn(e,r,t),n).on("end.style."+e,null)}function mZn(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function gZn(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&mZn(e,i,n)),r}return a._value=t,a}function vZn(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,gZn(e,t,n??""))}function yZn(e){return function(){this.textContent=e}}function bZn(e){return function(){var t=e(this);this.textContent=t??""}}function xZn(e){return this.tween("text",typeof e=="function"?bZn(GSe(this,"text",e)):yZn(e==null?"":e+""))}function wZn(e){return function(t){this.textContent=e.call(this,t)}}function SZn(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&wZn(s)),t}return r._value=e,r}function kZn(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,SZn(e))}function OZn(){for(var e=this._name,t=this._id,n=Y1t(),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=Hg(c,t);AH(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new jx(r,this._parents,e,n)}function _Zn(){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=zy(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 CZn=0;function jx(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function Y1t(){return++CZn}var yb=M3.prototype;jx.prototype={constructor:jx,select:iZn,selectAll:oZn,selectChild:yb.selectChild,selectChildren:yb.selectChildren,filter:JWn,merge:eZn,selection:cZn,transition:OZn,call:yb.call,nodes:yb.nodes,node:yb.node,size:yb.size,empty:yb.empty,each:yb.each,on:rZn,attr:DWn,attrTween:UWn,style:hZn,styleTween:vZn,text:xZn,textTween:kZn,remove:aZn,tween:NWn,delay:HWn,duration:GWn,ease:YWn,easeVarying:XWn,end:_Zn,[Symbol.iterator]:yb[Symbol.iterator]};function EZn(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var jZn={time:null,delay:0,duration:250,ease:EZn};function TZn(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 NZn(e){var t,n;e instanceof jx?(t=e._id,e=e._name):(t=Y1t(),(n=jZn).time=WSe(),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])&&AH(c,e,t,u,i,n||TZn(c,t));return new jx(r,this._parents,e,t)}M3.prototype.interrupt=EWn;M3.prototype.transition=NZn;const rF=e=>()=>e;function IZn(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 Kb(e,t,n){this.k=e,this.x=t,this.y=n}Kb.prototype={constructor:Kb,scale:function(e){return e===1?this:new Kb(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new Kb(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 RH=new Kb(1,0,0);K1t.prototype=Kb.prototype;function K1t(e){for(;!e.__zoom;)if(!(e=e.parentNode))return RH;return e.__zoom}function Jee(e){e.stopImmediatePropagation()}function xR(e){e.preventDefault(),e.stopImmediatePropagation()}function AZn(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function RZn(){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 B8e(){return this.__zoom||RH}function PZn(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function $Zn(){return navigator.maxTouchPoints||"ontouchstart"in this}function MZn(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 X1t(){var e=AZn,t=RZn,n=MZn,r=PZn,s=$Zn,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=I8,u=TH("start","zoom","end"),d,f,p,h=500,m=150,g=0,y=10;function b(D){D.property("__zoom",B8e).on("wheel.zoom",j,{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,F){var z=D.selection?D.selection():D;z.property("__zoom",B8e),D!==z?_(D,B,H,F):z.interrupt().each(function(){C(this,arguments).event(F).start().zoom(null,typeof B=="function"?B.apply(this,arguments):B).end()})},b.scaleBy=function(D,B,H,F){b.scaleTo(D,function(){var z=this.__zoom.k,q=typeof B=="function"?B.apply(this,arguments):B;return z*q},H,F)},b.scaleTo=function(D,B,H,F){b.transform(D,function(){var z=t.apply(this,arguments),q=this.__zoom,M=H==null?k(z):typeof H=="function"?H.apply(this,arguments):H,G=q.invert(M),V=typeof B=="function"?B.apply(this,arguments):B;return n(S(x(q,V),M,G),z,i)},H,F)},b.translateBy=function(D,B,H,F){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,F)},b.translateTo=function(D,B,H,F,z){b.transform(D,function(){var q=t.apply(this,arguments),M=this.__zoom,G=F==null?k(q):typeof F=="function"?F.apply(this,arguments):F;return n(RH.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),q,i)},F,z)};function x(D,B){return B=Math.max(a[0],Math.min(a[1],B)),B===D.k?D:new Kb(B,D.x,D.y)}function S(D,B,H){var F=B[0]-H[0]*D.k,z=B[1]-H[1]*D.k;return F===D.x&&z===D.y?D:new Kb(D.k,F,z)}function k(D){return[(+D[0][0]+ +D[1][0])/2,(+D[0][1]+ +D[1][1])/2]}function _(D,B,H,F){D.on("start.zoom",function(){C(this,arguments).event(F).start()}).on("interrupt.zoom end.zoom",function(){C(this,arguments).event(F).end()}).tween("zoom",function(){var z=this,q=arguments,M=C(z,q).event(F),G=t.apply(z,q),V=H==null?k(G):typeof H=="function"?H.apply(z,q):H,$=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),U=z.__zoom,Z=typeof B=="function"?B.apply(z,q):B,K=c(U.invert(V).concat($/U.k),Z.invert(V).concat($/Z.k));return function(te){if(te===1)te=Z;else{var ee=K(te),J=$/ee[2];te=new Kb(J,V[0]-ee[0]*J,V[1]-ee[1]*J)}M.zoom(null,te)}})}function C(D,B,H){return!H&&D.__zooming||new E(D,B)}function E(D,B){this.that=D,this.args=B,this.active=0,this.sourceEvent=null,this.extent=t.apply(D,B),this.taps=0}E.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=Sp(this.that).datum();u.call(D,this.that,new IZn(D,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),B)}};function j(D,...B){if(!e.apply(this,arguments))return;var H=C(this,B).event(D),F=this.__zoom,z=Math.max(a[0],Math.min(a[1],F.k*Math.pow(2,r.apply(this,arguments)))),q=rg(D);if(H.wheel)(H.mouse[0][0]!==q[0]||H.mouse[0][1]!==q[1])&&(H.mouse[1]=F.invert(H.mouse[0]=q)),clearTimeout(H.wheel);else{if(F.k===z)return;H.mouse=[q,F.invert(q)],P8(this),H.start()}xR(D),H.wheel=setTimeout(M,m),H.zoom("mouse",n(S(x(F,z),H.mouse[0],H.mouse[1]),H.extent,i));function M(){H.wheel=null,H.end()}}function N(D,...B){if(p||!e.apply(this,arguments))return;var H=D.currentTarget,F=C(this,B,!0).event(D),z=Sp(D.view).on("mousemove.zoom",V,!0).on("mouseup.zoom",$,!0),q=rg(D,H),M=D.clientX,G=D.clientY;$1t(D.view),Jee(D),F.mouse=[q,this.__zoom.invert(q)],P8(this),F.start();function V(U){if(xR(U),!F.moved){var Z=U.clientX-M,K=U.clientY-G;F.moved=Z*Z+K*K>g}F.event(U).zoom("mouse",n(S(F.that.__zoom,F.mouse[0]=rg(U,H),F.mouse[1]),F.extent,i))}function $(U){z.on("mousemove.zoom mouseup.zoom",null),M1t(U.view,F.moved),xR(U),F.event(U).end()}}function I(D,...B){if(e.apply(this,arguments)){var H=this.__zoom,F=rg(D.changedTouches?D.changedTouches[0]:D,this),z=H.invert(F),q=H.k*(D.shiftKey?.5:2),M=n(S(x(H,q),F,z),t.apply(this,B),i);xR(D),l>0?Sp(this).transition().duration(l).call(_,M,F,D):Sp(this).call(b.transform,M,F,D)}}function A(D,...B){if(e.apply(this,arguments)){var H=D.touches,F=H.length,z=C(this,B,D.changedTouches.length===F).event(D),q,M,G,V;for(Jee(D),M=0;M<F;++M)G=H[M],V=rg(G,this),V=[V,this.__zoom.invert(V),G.identifier],z.touch0?!z.touch1&&z.touch0[2]!==V[2]&&(z.touch1=V,z.taps=0):(z.touch0=V,q=!0,z.taps=1+!!d);d&&(d=clearTimeout(d)),q&&(z.taps<2&&(f=V[0],d=setTimeout(function(){d=null},h)),P8(this),z.start())}}function R(D,...B){if(this.__zooming){var H=C(this,B).event(D),F=D.changedTouches,z=F.length,q,M,G,V;for(xR(D),q=0;q<z;++q)M=F[q],G=rg(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 $=H.touch0[0],U=H.touch0[1],Z=H.touch1[0],K=H.touch1[1],te=(te=Z[0]-$[0])*te+(te=Z[1]-$[1])*te,ee=(ee=K[0]-U[0])*ee+(ee=K[1]-U[1])*ee;M=x(M,Math.sqrt(te/ee)),G=[($[0]+Z[0])/2,($[1]+Z[1])/2],V=[(U[0]+K[0])/2,(U[1]+K[1])/2]}else if(H.touch0)G=H.touch0[0],V=H.touch0[1];else return;H.zoom("touch",n(S(M,G,V),H.extent,i))}}function L(D,...B){if(this.__zooming){var H=C(this,B).event(D),F=D.changedTouches,z=F.length,q,M;for(Jee(D),p&&clearTimeout(p),p=setTimeout(function(){p=null},h),q=0;q<z;++q)M=F[q],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=rg(M,this),Math.hypot(f[0]-M[0],f[1]-M[1])<y)){var G=Sp(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(D){return arguments.length?(r=typeof D=="function"?D:rF(+D),b):r},b.filter=function(D){return arguments.length?(e=typeof D=="function"?D:rF(!!D),b):e},b.touchable=function(D){return arguments.length?(s=typeof D=="function"?D:rF(!!D),b):s},b.extent=function(D){return arguments.length?(t=typeof D=="function"?D:rF([[+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?(g=(D=+D)*D,b):Math.sqrt(g)},b.tapDistance=function(D){return arguments.length?(y=+D,b):y},b}const by={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."},EM=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],J1t=["Enter"," ","Escape"],eSt={"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 qT;(function(e){e.Strict="strict",e.Loose="loose"})(qT||(qT={}));var Xk;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(Xk||(Xk={}));var jM;(function(e){e.Partial="partial",e.Full="full"})(jM||(jM={}));const tSt={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var uw;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(uw||(uw={}));var TM;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(TM||(TM={}));var sr;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(sr||(sr={}));const U8e={[sr.Left]:sr.Right,[sr.Right]:sr.Left,[sr.Top]:sr.Bottom,[sr.Bottom]:sr.Top};function nSt(e){return e===null?null:e?"valid":"invalid"}const rSt=e=>"id"in e&&"source"in e&&"target"in e,DZn=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),QSe=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),L3=(e,t=[0,0])=>{const{width:n,height:r}=Kx(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},LZn=(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):QSe(s)?s:t.nodeLookup.get(s.id));const l=i?EB(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return PH(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return $H(n)},F3=(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=PH(n,EB(s)),r=!0)}),r?$H(n):{x:0,y:0,width:0,height:0}},YSe=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...B3(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:p=!1}=u;if(i&&!f||p)continue;const h=d.width??u.width??u.initialWidth??null,m=d.height??u.height??u.initialHeight??null,g=NM(l,WT(u)),y=(h??0)*(m??0),b=a&&g>0;(!u.internals.handleBounds||b||g>=y||u.dragging)&&c.push(u)}return c},FZn=(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 zZn(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 BZn({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=zZn(e,i),c=F3(l),u=KSe(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 sSt({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",by.error005());else{const h=l.measured.width,m=l.measured.height;h&&m&&(f=[[c,u],[c+h,u+m]])}else l&&ZT(i.extent)&&(f=[[i.extent[0][0]+c,i.extent[0][1]+u],[i.extent[1][0]+c,i.extent[1][1]+u]]);const p=ZT(f)?HO(t,f,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&a?.("015",by.error015()),{position:{x:p.x-c+(i.measured.width??0)*d[0],y:p.y-u+(i.measured.height??0)*d[1]},positionAbsolute:p}}async function UZn({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const a=new Set(e.map(p=>p.id)),i=[];for(const p of n){if(p.deletable===!1)continue;const h=a.has(p.id),m=!h&&p.parentId&&i.find(g=>g.id===p.parentId);(h||m)&&i.push(p)}const l=new Set(t.map(p=>p.id)),c=r.filter(p=>p.deletable!==!1),d=FZn(i,c);for(const p of c)l.has(p.id)&&!d.find(m=>m.id===p.id)&&d.push(p);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 HT=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),HO=(e={x:0,y:0},t,n)=>({x:HT(e.x,t[0][0],t[1][0]-(n?.width??0)),y:HT(e.y,t[0][1],t[1][1]-(n?.height??0))});function aSt(e,t,n){const{width:r,height:s}=Kx(n),{x:a,y:i}=n.internals.positionAbsolute;return HO(e,[[a,i],[a+r,i+s]],t)}const V8e=(e,t,n)=>e<t?HT(Math.abs(e-t),1,t)/t:e>n?-HT(Math.abs(e-n),1,t)/t:0,iSt=(e,t,n=15,r=40)=>{const s=V8e(e.x,r,t.width-r)*n,a=V8e(e.y,r,t.height-r)*n;return[s,a]},PH=(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)}),nge=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),$H=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),WT=(e,t=[0,0])=>{const{x:n,y:r}=QSe(e)?e.internals.positionAbsolute:L3(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}},EB=(e,t=[0,0])=>{const{x:n,y:r}=QSe(e)?e.internals.positionAbsolute:L3(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)}},oSt=(e,t)=>$H(PH(nge(e),nge(t))),NM=(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)},q8e=e=>gg(e.width)&&gg(e.height)&&gg(e.x)&&gg(e.y),gg=e=>!isNaN(e)&&isFinite(e),VZn=(e,t)=>{},z3=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),B3=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?z3(l,i):l},jB=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function iE(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 qZn(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=iE(e,n),s=iE(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=iE(e.top??e.y??0,n),s=iE(e.bottom??e.y??0,n),a=iE(e.left??e.x??0,t),i=iE(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 HZn(e,t,n,r,s,a){const{x:i,y:l}=jB(e,[t,n,r]),{x:c,y:u}=jB({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 KSe=(e,t,n,r,s,a)=>{const i=qZn(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=HT(u,r,s),f=e.x+e.width/2,p=e.y+e.height/2,h=t/2-f*d,m=n/2-p*d,g=HZn(e,h,m,d,t,n),y={left:Math.min(g.left-i.left,0),top:Math.min(g.top-i.top,0),right:Math.min(g.right-i.right,0),bottom:Math.min(g.bottom-i.bottom,0)};return{x:h-y.left+y.right,y:m-y.top+y.bottom,zoom:d}},IM=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function ZT(e){return e!=null&&e!=="parent"}function Kx(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function lSt(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function cSt(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 H8e(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function WZn(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function ZZn(e){return{...eSt,...e||{}}}function h2(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=vg(e),l=B3({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?z3(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const XSe=e=>({width:e.offsetWidth,height:e.offsetHeight}),uSt=e=>e?.getRootNode?.()||window?.document,GZn=["INPUT","SELECT","TEXTAREA"];function dSt(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:GZn.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const fSt=e=>"clientX"in e,vg=(e,t)=>{const n=fSt(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)}},W8e=(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,...XSe(i)}})};function pSt({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 sF(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function Z8e({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case sr.Left:return[t-sF(t-r,a),n];case sr.Right:return[t+sF(r-t,a),n];case sr.Top:return[t,n-sF(n-s,a)];case sr.Bottom:return[t,n+sF(s-n,a)]}}function JSe({sourceX:e,sourceY:t,sourcePosition:n=sr.Bottom,targetX:r,targetY:s,targetPosition:a=sr.Top,curvature:i=.25}){const[l,c]=Z8e({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=Z8e({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,p,h,m]=pSt({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,p,h,m]}function hSt({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 QZn({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 YZn({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=PH(EB(e),EB(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 NM(i,$H(a))>0}const KZn=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,XZn=(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)),JZn=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||KZn;let s;return rSt(e)?s={...e}:s={...e,id:r(e)},XZn(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function mSt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=hSt({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const G8e={[sr.Left]:{x:-1,y:0},[sr.Right]:{x:1,y:0},[sr.Top]:{x:0,y:-1},[sr.Bottom]:{x:0,y:1}},eGn=({source:e,sourcePosition:t=sr.Bottom,target:n})=>t===sr.Left||t===sr.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},Q8e=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function tGn({source:e,sourcePosition:t=sr.Bottom,target:n,targetPosition:r=sr.Top,center:s,offset:a,stepPosition:i}){const l=G8e[t],c=G8e[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=eGn({source:u,sourcePosition:t,target:d}),p=f.x!==0?"x":"y",h=f[p];let m=[],g,y;const b={x:0,y:0},x={x:0,y:0},[,,S,k]=hSt({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[p]*c[p]===-1){p==="x"?(g=s.x??u.x+(d.x-u.x)*i,y=s.y??(u.y+d.y)/2):(g=s.x??(u.x+d.x)/2,y=s.y??u.y+(d.y-u.y)*i);const j=[{x:g,y:u.y},{x:g,y:d.y}],N=[{x:u.x,y},{x:d.x,y}];l[p]===h?m=p==="x"?j:N:m=p==="x"?N:j}else{const j=[{x:u.x,y:d.y}],N=[{x:d.x,y:u.y}];if(p==="x"?m=l.x===h?N:j:m=l.y===h?j:N,t===r){const D=Math.abs(e[p]-n[p]);if(D<=a){const B=Math.min(a-1,a-D);l[p]===h?b[p]=(u[p]>e[p]?-1:1)*B:x[p]=(d[p]>n[p]?-1:1)*B}}if(t!==r){const D=p==="x"?"y":"x",B=l[p]===c[D],H=u[D]>d[D],F=u[D]<d[D];(l[p]===1&&(!B&&H||B&&F)||l[p]!==1&&(!B&&F||B&&H))&&(m=p==="x"?j: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?(g=(I.x+A.x)/2,y=m[0].y):(g=m[0].x,y=(I.y+A.y)/2)}const _={x:u.x+b.x,y:u.y+b.y},C={x:d.x+x.x,y:d.y+x.y};return[[e,..._.x!==m[0].x||_.y!==m[0].y?[_]:[],...m,...C.x!==m[m.length-1].x||C.y!==m[m.length-1].y?[C]:[],n],g,y,S,k]}function nGn(e,t,n,r){const s=Math.min(Q8e(e,t)/2,Q8e(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 rge({sourceX:e,sourceY:t,sourcePosition:n=sr.Bottom,targetX:r,targetY:s,targetPosition:a=sr.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,p,h,m,g]=tGn({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+=nGn(f[b-1],f[b],f[b+1],i);return y+=`L${f[f.length-1].x} ${f[f.length-1].y}`,[y,p,h,m,g]}function Y8e(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function rGn(e){const{sourceNode:t,targetNode:n}=e;if(!Y8e(t)||!Y8e(n))return null;const r=t.internals.handleBounds||K8e(t.handles),s=n.internals.handleBounds||K8e(n.handles),a=X8e(r?.source??[],e.sourceHandle),i=X8e(e.connectionMode===qT.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!a||!i)return e.onError?.("008",by.error008(a?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=a?.position||sr.Bottom,c=i?.position||sr.Top,u=WO(t,a,l),d=WO(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function K8e(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 WO(e,t,n=sr.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??Kx(e);if(r)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case sr.Top:return{x:s+i/2,y:a};case sr.Right:return{x:s+i,y:a+l/2};case sr.Bottom:return{x:s+i/2,y:a+l};case sr.Left:return{x:s,y:a+l/2}}}function X8e(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function sge(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function sGn(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=sge(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 gSt=1e3,aGn=10,eke={nodeOrigin:[0,0],nodeExtent:EM,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},iGn={...eke,checkEquality:!0};function tke(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function oGn(e,t,n){const r=tke(eke,n);for(const s of e.values())if(s.parentId)rke(s,e,t,r);else{const a=L3(s,r.nodeOrigin),i=ZT(s.extent)?s.extent:r.nodeExtent,l=HO(a,i,Kx(s));s.internals.positionAbsolute=l}}function lGn(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 nke(e){return e==="manual"}function age(e,t,n,r={}){const s=tke(iGn,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!nke(s.zIndexMode)?gSt: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 p=L3(d,s.nodeOrigin),h=ZT(d.extent)?d.extent:s.nodeExtent,m=HO(p,h,Kx(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:lGn(d,f),z:vSt(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&&rke(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function cGn(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 rke(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=tke(eke,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}cGn(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*aGn),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!nke(c)?gSt:0,{x:p,y:h,z:m}=uGn(e,d,i,l,f,c),{positionAbsolute:g}=e.internals,y=p!==g.x||h!==g.y;(y||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:p,y:h}:g,z:m}})}function vSt(e,t,n){const r=gg(e.zIndex)?e.zIndex:0;return nke(n)?r:r+(e.selected?t:0)}function uGn(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=Kx(e),u=L3(e,n),d=ZT(e.extent)?HO(u,e.extent,c):u;let f=HO({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=aSt(f,c,t));const p=vSt(e,s,a),h=t.internals.z??0;return{x:f.x,y:f.y,z:h>=p?h+1:p}}function ske(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??WT(l),u=oSt(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=Kx(l),f=l.origin??r,p=i.x<u.x?Math.round(Math.abs(u.x-i.x)):0,h=i.y<u.y?Math.round(Math.abs(u.y-i.y)):0,m=Math.max(d.width,Math.round(i.width)),g=Math.max(d.height,Math.round(i.height)),y=(m-d.width)*f[0],b=(g-d.height)*f[1];(p>0||h>0||y||b)&&(s.push({id:c,type:"position",position:{x:l.position.x-p+y,y:l.position.y-h+b}}),n.get(c)?.forEach(x=>{e.some(S=>S.id===x.id)||s.push({id:x.id,type:"position",position:{x:x.position.x+p,y:x.position.y+h}})})),(d.width<i.width||d.height<i.height||p||h)&&s.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:m+(p?f[0]*p-y:0),height:g+(h?f[1]*h-b:0)}})}),s}function dGn(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),p=[];for(const h of e.values()){const m=t.get(h.id);if(!m)continue;if(m.hidden){t.set(m.id,{...m,internals:{...m.internals,handleBounds:void 0}}),c=!0;continue}const g=XSe(h.nodeElement),y=m.measured.width!==g.width||m.measured.height!==g.height;if(!!(g.width&&g.height&&(y||!m.internals.handleBounds||h.force))){const x=h.nodeElement.getBoundingClientRect(),S=ZT(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=aSt(k,g,t.get(m.parentId)):S&&(k=HO(k,S,g));const _={...m,measured:g,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:W8e("source",h.nodeElement,x,f,m.id),target:W8e("target",h.nodeElement,x,f,m.id)}}};t.set(m.id,_),m.parentId&&rke(_,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,y&&(u.push({id:m.id,type:"dimensions",dimensions:g}),m.expandParent&&m.parentId&&p.push({id:m.id,parentId:m.parentId,rect:WT(_,s)}))}}if(p.length>0){const h=ske(p,t,n,s);u.push(...h)}return{changes:u,updatedInternals:c}}async function fGn({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 J8e(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 ySt(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}`;J8e("source",c,d,e,s,i),J8e("target",c,u,e,a,l),t.set(r.id,r)}}function bSt(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:bSt(n,t):!1}function e9e(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 pGn(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!bSt(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 ete({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 hGn({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=z3(a,t);return{x:i.x-a.x,y:i.y-a.y}}function mGn({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,p=null,h=!1,m=!1,g=null;function y({noDragClassName:x,handleSelector:S,domNode:k,isSelectable:_,nodeId:C,nodeClickDistance:E=0}){p=Sp(k);function j({x:R,y:L}){const{nodeLookup:D,nodeExtent:B,snapGrid:H,snapToGrid:F,nodeOrigin:z,onNodeDrag:q,onSelectionDrag:M,onError:G,updateNodePositions:V}=t();a={x:R,y:L};let $=!1;const U=l.size>1,Z=U&&B?nge(F3(l)):null,K=U&&F?hGn({dragItems:l,snapGrid:H,x:R,y:L}):null;for(const[te,ee]of l){if(!D.has(te))continue;let J={x:R-ee.distance.x,y:L-ee.distance.y};F&&(J=K?{x:Math.round(J.x+K.x),y:Math.round(J.y+K.y)}:z3(J,H));let ae=null;if(U&&B&&!ee.extent&&Z){const{positionAbsolute:ne}=ee.internals,fe=ne.x-Z.x+B[0][0],oe=ne.x+ee.measured.width-Z.x2+B[1][0],le=ne.y-Z.y+B[0][1],he=ne.y+ee.measured.height-Z.y2+B[1][1];ae=[[fe,le],[oe,he]]}const{position:de,positionAbsolute:Y}=sSt({nodeId:te,nextPosition:J,nodeLookup:D,nodeExtent:ae||B,nodeOrigin:z,onError:G});$=$||ee.position.x!==de.x||ee.position.y!==de.y,ee.position=de,ee.internals.positionAbsolute=Y}if(m=m||$,!!$&&(V(l,!0),g&&(r||q||!C&&M))){const[te,ee]=ete({nodeId:C,dragItems:l,nodeLookup:D});r?.(g,l,te,ee),q?.(g,te,ee),C||M?.(g,ee)}}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,F]=iSt(u,d,D);(H!==0||F!==0)&&(a.x=(a.x??0)-H/R[2],a.y=(a.y??0)-F/R[2],await L({x:H,y:F})&&j(a)),i=requestAnimationFrame(N)}function I(R){const{nodeLookup:L,multiSelectionActive:D,nodesDraggable:B,transform:H,snapGrid:F,snapToGrid:z,selectNodesOnDrag:q,onNodeDragStart:M,onSelectionDragStart:G,unselectNodesAndEdges:V}=t();f=!0,(!q||!_)&&!D&&C&&(L.get(C)?.selected||V()),_&&q&&C&&e?.(C);const $=h2(R.sourceEvent,{transform:H,snapGrid:F,snapToGrid:z,containerBounds:d});if(a=$,l=pGn(L,B,$,C),l.size>0&&(n||M||!C&&G)){const[U,Z]=ete({nodeId:C,dragItems:l,nodeLookup:L});n?.(R.sourceEvent,l,U,Z),M?.(R.sourceEvent,U,Z),C||G?.(R.sourceEvent,Z)}}const A=D1t().clickDistance(E).on("start",R=>{const{domNode:L,nodeDragThreshold:D,transform:B,snapGrid:H,snapToGrid:F}=t();d=L?.getBoundingClientRect()||null,h=!1,m=!1,g=R.sourceEvent,D===0&&I(R),a=h2(R.sourceEvent,{transform:B,snapGrid:H,snapToGrid:F,containerBounds:d}),u=vg(R.sourceEvent,d)}).on("drag",R=>{const{autoPanOnNodeDrag:L,transform:D,snapGrid:B,snapToGrid:H,nodeDragThreshold:F,nodeLookup:z}=t(),q=h2(R.sourceEvent,{transform:D,snapGrid:B,snapToGrid:H,containerBounds:d});if(g=R.sourceEvent,(R.sourceEvent.type==="touchmove"&&R.sourceEvent.touches.length>1||C&&!z.has(C))&&(h=!0),!h){if(!c&&L&&f&&(c=!0,N()),!f){const M=vg(R.sourceEvent,d),G=M.x-u.x,V=M.y-u.y;Math.sqrt(G*G+V*V)>F&&I(R)}(a.x!==q.xSnapped||a.y!==q.ySnapped)&&l&&f&&(u=vg(R.sourceEvent,d),j(q))}}).on("end",R=>{if(!(!f||h)&&(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||!C&&H){const[F,z]=ete({nodeId:C,dragItems:l,nodeLookup:L,dragging:!1});s?.(R.sourceEvent,l,F,z),B?.(R.sourceEvent,F,z),C||H?.(R.sourceEvent,z)}}}).filter(R=>{const L=R.target;return!R.button&&(!x||!e9e(L,`.${x}`,k))&&(!S||e9e(L,S,k))});p.call(A)}function b(){p?.on(".drag",null)}return{update:y,destroy:b}}function gGn(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())NM(s,WT(a))>0&&r.push(a);return r}const vGn=250;function yGn(e,t,n,r){let s=[],a=1/0;const i=gGn(e,n,t+vGn);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}=WO(l,u,u.position,!0),p=Math.sqrt(Math.pow(d-e.x,2)+Math.pow(f-e.y,2));p>t||(p<a?(s=[{...u,x:d,y:f}],a=p):p===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 xSt(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,...WO(i,c,c.position,!0)}:c}function wSt(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function bGn(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const SSt=()=>!0;function xGn(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:a,isTarget:i,domNode:l,nodeLookup:c,lib:u,autoPanOnConnect:d,flowId:f,panBy:p,cancelConnection:h,onConnectStart:m,onConnect:g,onConnectEnd:y,isValidConnection:b=SSt,onReconnectEnd:x,updateConnection:S,getTransform:k,getFromHandle:_,autoPanSpeed:C,dragThreshold:E=1,handleDomNode:j}){const N=uSt(e.target);let I=0,A;const{x:R,y:L}=vg(e),D=wSt(a,j),B=l?.getBoundingClientRect();let H=!1;if(!B||!D)return;const F=xSt(s,D,r,c,t);if(!F)return;let z=vg(e,B),q=!1,M=null,G=!1,V=null;function $(){if(!d||!B)return;const[de,Y]=iSt(z,B,C);p({x:de,y:Y}),I=requestAnimationFrame($)}const U={...F,nodeId:s,type:D,position:F.position},Z=c.get(s);let te={inProgress:!0,isValid:null,from:WO(Z,U,sr.Left,!0),fromHandle:U,fromPosition:U.position,fromNode:Z,to:z,toHandle:null,toPosition:U8e[U.position],toNode:null,pointer:z};function ee(){H=!0,S(te),m?.(e,{nodeId:s,handleId:r,handleType:D})}E===0&&ee();function J(de){if(!H){const{x:he,y:be}=vg(de),xe=he-R,je=be-L;if(!(xe*xe+je*je>E*E))return;ee()}if(!_()||!U){ae(de);return}const Y=k();z=vg(de,B),A=yGn(B3(z,Y,!1,[1,1]),n,c,U),q||($(),q=!0);const ne=kSt(de,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});V=ne.handleDomNode,M=ne.connection,G=bGn(!!A,ne.isValid);const fe=c.get(s),oe=fe?WO(fe,U,sr.Left,!0):te.from,le={...te,from:oe,isValid:G,to:ne.toHandle&&G?jB({x:ne.toHandle.x,y:ne.toHandle.y},Y):z,toHandle:ne.toHandle,toPosition:G&&ne.toHandle?ne.toHandle.position:U8e[U.position],toNode:ne.toHandle?c.get(ne.toHandle.nodeId):null,pointer:z};S(le),te=le}function ae(de){if(!("touches"in de&&de.touches.length>0)){if(H){(A||V)&&M&&G&&g?.(M);const{inProgress:Y,...ne}=te,fe={...ne,toPosition:te.toHandle?te.toPosition:null};y?.(de,fe),a&&x?.(de,fe)}h(),cancelAnimationFrame(I),q=!1,G=!1,M=null,V=null,N.removeEventListener("mousemove",J),N.removeEventListener("mouseup",ae),N.removeEventListener("touchmove",J),N.removeEventListener("touchend",ae)}}N.addEventListener("mousemove",J),N.addEventListener("mouseup",ae),N.addEventListener("touchmove",J),N.addEventListener("touchend",ae)}function kSt(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=SSt,nodeLookup:d}){const f=a==="target",p=t?i.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:h,y:m}=vg(e),g=i.elementFromPoint(h,m),y=g?.classList.contains(`${l}-flow__handle`)?g:p,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){const x=wSt(void 0,y),S=y.getAttribute("data-nodeid"),k=y.getAttribute("data-handleid"),_=y.classList.contains("connectable"),C=y.classList.contains("connectableend");if(!S||!x)return b;const E={source:f?S:r,sourceHandle:f?k:s,target:f?r:S,targetHandle:f?s:k};b.connection=E;const N=_&&C&&(n===qT.Strict?f&&x==="source"||!f&&x==="target":S!==r||k!==s);b.isValid=N&&u(E),b.toHandle=xSt(S,x,k,d,n,!0)}return b}const ige={onPointerDown:xGn,isValid:kSt};function wGn({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Sp(e);function a({translateExtent:l,width:c,height:u,zoomStep:d=1,pannable:f=!0,zoomable:p=!0,inversePan:h=!1}){const m=S=>{if(S.sourceEvent.type!=="wheel"||!t)return;const k=n(),_=S.sourceEvent.ctrlKey&&IM()?10:1,C=-S.sourceEvent.deltaY*(S.sourceEvent.deltaMode===1?.05:S.sourceEvent.deltaMode?1:.002)*d,E=k[2]*Math.pow(2,C*_);t.scaleTo(E)};let g=[0,0];const y=S=>{(S.sourceEvent.type==="mousedown"||S.sourceEvent.type==="touchstart")&&(g=[S.sourceEvent.clientX??S.sourceEvent.touches[0].clientX,S.sourceEvent.clientY??S.sourceEvent.touches[0].clientY])},b=S=>{const k=n();if(S.sourceEvent.type!=="mousemove"&&S.sourceEvent.type!=="touchmove"||!t)return;const _=[S.sourceEvent.clientX??S.sourceEvent.touches[0].clientX,S.sourceEvent.clientY??S.sourceEvent.touches[0].clientY],C=[_[0]-g[0],_[1]-g[1]];g=_;const E=r()*Math.max(k[2],Math.log(k[2]))*(h?-1:1),j={x:k[0]-C[0]*E,y:k[1]-C[1]*E},N=[[0,0],[c,u]];t.setViewportConstrained({x:j.x,y:j.y,zoom:k[2]},N,l)},x=X1t().on("start",y).on("zoom",f?b:null).on("zoom.wheel",p?m:null);s.call(x,{})}function i(){s.on("zoom",null)}return{update:a,destroy:i,pointer:rg}}const MH=e=>({x:e.x,y:e.y,zoom:e.k}),tte=({x:e,y:t,zoom:n})=>RH.translate(e,t).scale(n),cj=(e,t)=>e.target.closest(`.${t}`),OSt=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),SGn=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,nte=(e,t=0,n=SGn,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},_St=e=>{const t=e.ctrlKey&&IM()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function kGn({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(cj(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=rg(d),b=_St(d),x=f*Math.pow(2,b);r.scaleTo(n,x,y,d);return}const p=d.deltaMode===1?20:1;let h=s===Xk.Vertical?0:d.deltaX*p,m=s===Xk.Horizontal?0:d.deltaY*p;!IM()&&d.shiftKey&&s!==Xk.Vertical&&(h=d.deltaY*p,m=0),r.translateBy(n,-(h/f)*a,-(m/f)*a,{internal:!0});const g=MH(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(d,g),e.panScrollTimeout=setTimeout(()=>{u?.(d,g),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l?.(d,g))}}function OGn({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=cj(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function _Gn({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=MH(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 CGn({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&OSt(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,MH(a.transform))}}function EGn({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&OSt(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=MH(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function jGn({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 p=e||t,h=n&&f.ctrlKey,m=f.type==="wheel";if(f.button===1&&f.type==="mousedown"&&(cj(f,`${u}-flow__node`)||cj(f,`${u}-flow__edge`)))return!0;if(!r&&!p&&!s&&!a&&!n||i||d&&!m||cj(f,l)&&m||cj(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(!p&&!s&&!h&&m||!r&&(f.type==="mousedown"||f.type==="touchstart")||Array.isArray(r)&&!r.includes(f.button)&&f.type==="mousedown")return!1;const g=Array.isArray(r)&&r.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||m)&&g}}function TGn({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=X1t().scaleExtent([t,n]).translateExtent(r),p=Sp(e).call(f);x({x:s.x,y:s.y,zoom:HT(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const h=p.on("wheel.zoom"),m=p.on("dblclick.zoom");f.wheelDelta(_St);function g(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?lx:I8).transform(nte(p,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:F,panOnScrollSpeed:z,preventScrolling:q,zoomOnPinch:M,zoomOnScroll:G,zoomOnDoubleClick:V,zoomActivationKeyPressed:$,lib:U,onTransformChange:Z,connectionInProgress:K,paneClickDistance:te,selectionOnDrag:ee}){D&&!u.isZoomingOrPanning&&b();const J=B&&!$&&!D;f.clickDistance(ee?1/0:!gg(te)||te<0?0:te);const ae=J?kGn({zoomPanValues:u,noWheelClassName:A,d3Selection:p,d3Zoom:f,panOnScrollMode:F,panOnScrollSpeed:z,zoomOnPinch:M,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):OGn({noWheelClassName:A,preventScrolling:q,d3ZoomHandler:h});if(p.on("wheel.zoom",ae,{passive:!1}),!D){const Y=_Gn({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",Y);const ne=CGn({zoomPanValues:u,panOnDrag:H,onPaneContextMenu:!!L,onPanZoom:a,onTransformChange:Z});f.on("zoom",ne);const fe=EGn({zoomPanValues:u,panOnDrag:H,panOnScroll:B,onPaneContextMenu:L,onPanZoomEnd:l,onDraggingChange:c});f.on("end",fe)}const de=jGn({zoomActivationKeyPressed:$,panOnDrag:H,zoomOnScroll:G,panOnScroll:B,zoomOnDoubleClick:V,zoomOnPinch:M,userSelectionActive:D,noPanClassName:R,noWheelClassName:A,lib:U,connectionInProgress:K});f.filter(de),V?p.on("dblclick.zoom",m):p.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,R,L){const D=tte(A),B=f?.constrain()(D,R,L);return B&&await g(B),new Promise(H=>H(B))}async function S(A,R){const L=tte(A);return await g(L,R),new Promise(D=>D(L))}function k(A){if(p){const R=tte(A),L=p.property("__zoom");(L.k!==A.zoom||L.x!==A.x||L.y!==A.y)&&f?.transform(p,R,null,{sync:!0})}}function _(){const A=p?K1t(p.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function C(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?lx:I8).scaleTo(nte(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function E(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?lx:I8).scaleBy(nte(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function j(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const R=!gg(A)||A<0?0:A;f?.clickDistance(R)}return{update:y,destroy:b,setViewport:S,setViewportConstrained:x,getViewport:_,scaleTo:C,scaleBy:E,setScaleExtent:j,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var GT;(function(e){e.Line="line",e.Handle="handle"})(GT||(GT={}));function NGn({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 t9e(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 V0(e,t){return Math.max(0,t-e)}function q0(e,t){return Math.max(0,e-t)}function aF(e,t,n){return Math.max(0,t-e,e-n)}function n9e(e,t){return e?!t:t}function IGn(e,t,n,r,s,a,i,l){let{affectsX:c,affectsY:u}=t;const{isHorizontal:d,isVertical:f}=t,p=d&&f,{xSnapped:h,ySnapped:m}=n,{minWidth:g,maxWidth:y,minHeight:b,maxHeight:x}=r,{x:S,y:k,width:_,height:C,aspectRatio:E}=e;let j=Math.floor(d?h-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=_+(c?-j:j),A=C+(u?-N:N),R=-a[0]*_,L=-a[1]*C;let D=aF(I,g,y),B=aF(A,b,x);if(i){let z=0,q=0;c&&j<0?z=V0(S+j+R,i[0][0]):!c&&j>0&&(z=q0(S+I+R,i[1][0])),u&&N<0?q=V0(k+N+L,i[0][1]):!u&&N>0&&(q=q0(k+A+L,i[1][1])),D=Math.max(D,z),B=Math.max(B,q)}if(l){let z=0,q=0;c&&j>0?z=q0(S+j,l[0][0]):!c&&j<0&&(z=V0(S+I,l[1][0])),u&&N>0?q=q0(k+N,l[0][1]):!u&&N<0&&(q=V0(k+A,l[1][1])),D=Math.max(D,z),B=Math.max(B,q)}if(s){if(d){const z=aF(I/E,b,x)*E;if(D=Math.max(D,z),i){let q=0;!c&&!u||c&&!u&&p?q=q0(k+L+I/E,i[1][1])*E:q=V0(k+L+(c?j:-j)/E,i[0][1])*E,D=Math.max(D,q)}if(l){let q=0;!c&&!u||c&&!u&&p?q=V0(k+I/E,l[1][1])*E:q=q0(k+(c?j:-j)/E,l[0][1])*E,D=Math.max(D,q)}}if(f){const z=aF(A*E,g,y)/E;if(B=Math.max(B,z),i){let q=0;!c&&!u||u&&!c&&p?q=q0(S+A*E+R,i[1][0])/E:q=V0(S+(u?N:-N)*E+R,i[0][0])/E,B=Math.max(B,q)}if(l){let q=0;!c&&!u||u&&!c&&p?q=V0(S+A*E,l[1][0])/E:q=q0(S+(u?N:-N)*E,l[0][0])/E,B=Math.max(B,q)}}}N=N+(N<0?B:-B),j=j+(j<0?D:-D),s&&(p?I>A*E?N=(n9e(c,u)?-j:j)/E:j=(n9e(c,u)?-N:N)*E:d?(N=j/E,u=c):(j=N*E,c=u));const H=c?S+j:S,F=u?k+N:k;return{width:_+(c?-j:j),height:C+(u?-N:N),x:a[0]*j*(c?-1:1)+H,y:a[1]*N*(u?-1:1)+F}}const CSt={width:0,height:0,x:0,y:0},AGn={...CSt,pointerX:0,pointerY:0,aspectRatio:1};function RGn(e){return[[0,0],[e.measured.width,e.measured.height]]}function PGn(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 $Gn({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=Sp(e);let i={controlDirection:t9e("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:p,onResizeStart:h,onResize:m,onResizeEnd:g,shouldResize:y}){let b={...CSt},x={...AGn};i={boundaries:d,resizeDirection:p,keepAspectRatio:f,controlDirection:t9e(u)};let S,k=null,_=[],C,E,j,N=!1;const I=D1t().on("start",A=>{const{nodeLookup:R,transform:L,snapGrid:D,snapToGrid:B,nodeOrigin:H,paneDomNode:F}=n();if(S=R.get(t),!S)return;k=F?.getBoundingClientRect()??null;const{xSnapped:z,ySnapped:q}=h2(A.sourceEvent,{transform:L,snapGrid:D,snapToGrid:B,containerBounds:k});b={width:S.measured.width??0,height:S.measured.height??0,x:S.position.x??0,y:S.position.y??0},x={...b,pointerX:z,pointerY:q,aspectRatio:b.width/b.height},C=void 0,S.parentId&&(S.extent==="parent"||S.expandParent)&&(C=R.get(S.parentId),E=C&&S.extent==="parent"?RGn(C):void 0),_=[],j=void 0;for(const[M,G]of R)if(G.parentId===t&&(_.push({id:M,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const V=PGn(G,S,G.origin??H);j?j=[[Math.min(V[0][0],j[0][0]),Math.min(V[0][1],j[0][1])],[Math.max(V[1][0],j[1][0]),Math.max(V[1][1],j[1][1])]]:j=V}h?.(A,{...b})}).on("drag",A=>{const{transform:R,snapGrid:L,snapToGrid:D,nodeOrigin:B}=n(),H=h2(A.sourceEvent,{transform:R,snapGrid:L,snapToGrid:D,containerBounds:k}),F=[];if(!S)return;const{x:z,y:q,width:M,height:G}=b,V={},$=S.origin??B,{width:U,height:Z,x:K,y:te}=IGn(x,i.controlDirection,H,i.boundaries,i.keepAspectRatio,$,E,j),ee=U!==M,J=Z!==G,ae=K!==z&&ee,de=te!==q&&J;if(!ae&&!de&&!ee&&!J)return;if((ae||de||$[0]===1||$[1]===1)&&(V.x=ae?K:b.x,V.y=de?te:b.y,b.x=V.x,b.y=V.y,_.length>0)){const oe=K-z,le=te-q;for(const he of _)he.position={x:he.position.x-oe+$[0]*(U-M),y:he.position.y-le+$[1]*(Z-G)},F.push(he)}if((ee||J)&&(V.width=ee&&(!i.resizeDirection||i.resizeDirection==="horizontal")?U:b.width,V.height=J&&(!i.resizeDirection||i.resizeDirection==="vertical")?Z:b.height,b.width=V.width,b.height=V.height),C&&S.expandParent){const oe=$[0]*(V.width??0);V.x&&V.x<oe&&(b.x=oe,x.x=x.x-(V.x-oe));const le=$[1]*(V.height??0);V.y&&V.y<le&&(b.y=le,x.y=x.y-(V.y-le))}const Y=NGn({width:b.width,prevWidth:M,height:b.height,prevHeight:G,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),ne={...b,direction:Y};y?.(A,ne)!==!1&&(N=!0,m?.(A,ne),r(V,F))}).on("end",A=>{N&&(g?.(A,{...b}),s?.({...b}),N=!1)});a.call(I)}function c(){a.on(".drag",null)}return{update:l,destroy:c}}const MGn={},r9e=e=>{let t;const n=new Set,r=(d,f)=>{const p=typeof d=="function"?d(t):d;if(!Object.is(p,t)){const h=t;t=f??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(m=>m(t,h))}},s=()=>t,c={setState:r,getState:s,getInitialState:()=>u,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(MGn?"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},DGn=e=>e?r9e(e):r9e,{useDebugValue:LGn}=Fe,{useSyncExternalStoreWithSelector:FGn}=nOn,zGn=e=>e;function ESt(e,t=zGn,n){const r=FGn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return LGn(r),r}const s9e=(e,t)=>{const n=DGn(e),r=(s,a=t)=>ESt(n,s,a);return Object.assign(r,n),r},BGn=(e,t)=>e?s9e(e,t):s9e;function io(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 DH=v.createContext(null),UGn=DH.Provider,jSt=by.error001();function Bs(e,t){const n=v.useContext(DH);if(n===null)throw new Error(jSt);return ESt(n,e,t)}function jo(){const e=v.useContext(DH);if(e===null)throw new Error(jSt);return v.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const a9e={display:"none"},VGn={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},TSt="react-flow__node-desc",NSt="react-flow__edge-desc",qGn="react-flow__aria-live",HGn=e=>e.ariaLiveMessage,WGn=e=>e.ariaLabelConfig;function ZGn({rfId:e}){const t=Bs(HGn);return o.jsx("div",{id:`${qGn}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:VGn,children:t})}function GGn({rfId:e,disableKeyboardA11y:t}){const n=Bs(WGn);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${TSt}-${e}`,style:a9e,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${NSt}-${e}`,style:a9e,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(ZGn,{rfId:e})]})}const U3=v.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:Ul(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});U3.displayName="Panel";function QGn({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(U3,{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 YGn=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}},iF=e=>e.id;function KGn(e,t){return io(e.selectedNodes.map(iF),t.selectedNodes.map(iF))&&io(e.selectedEdges.map(iF),t.selectedEdges.map(iF))}function XGn({onSelectionChange:e}){const t=jo(),{selectedNodes:n,selectedEdges:r}=Bs(YGn,KGn);return v.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const JGn=e=>!!e.onSelectionChangeHandlers;function eQn({onSelectionChange:e}){const t=Bs(JGn);return e||t?o.jsx(XGn,{onSelectionChange:e}):null}const oge=typeof window<"u"?v.useLayoutEffect:v.useEffect,ISt=[0,0],tQn={x:0,y:0,zoom:1},nQn=["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"],i9e=[...nQn,"rfId"],rQn=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}),o9e={translateExtent:EM,nodeOrigin:ISt,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function sQn(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Bs(rQn,io),u=jo();oge(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=o9e,l()}),[]);const d=v.useRef(o9e);return oge(()=>{for(const f of i9e){const p=e[f],h=d.current[f];p!==h&&(typeof e[f]>"u"||(f==="nodes"?t(p):f==="edges"?n(p):f==="minZoom"?r(p):f==="maxZoom"?s(p):f==="translateExtent"?a(p):f==="nodeExtent"?i(p):f==="ariaLabelConfig"?u.setState({ariaLabelConfig:ZZn(p)}):f==="fitView"?u.setState({fitViewQueued:p}):f==="fitViewOptions"?u.setState({fitViewOptions:p}):u.setState({[f]:p})))}d.current=e},i9e.map(f=>e[f])),null}function l9e(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function aQn(e){const[t,n]=v.useState(e==="system"?null:e);return v.useEffect(()=>{if(e!=="system"){n(e);return}const r=l9e(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:l9e()?.matches?"dark":"light"}const c9e=typeof document<"u"?document:null;function AM(e=null,t={target:c9e,actInsideInputWithModifier:!0}){const[n,r]=v.useState(!1),s=v.useRef(!1),a=v.useRef(new Set([])),[i,l]=v.useMemo(()=>{if(e!==null){const u=(Array.isArray(e)?e:[e]).filter(f=>typeof f=="string").map(f=>f.replace("+",`
338
338
  `).replace(`
339
339
 
340
340
  `,`
@@ -699,7 +699,7 @@ window.parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/sandbox-proxy-
699
699
 
700
700
  `),a=r.filter(i=>i.type==="prompt_block"||i.type==="prompt_block_ref").map(i=>i.type==="prompt_block_ref"?Qye(i.id):SD(OKe(i.content),i.rules));return{instructionsString:s,instructionBlocks:a}}const n=U8t(e);return{instructionsString:n,instructionBlocks:[SD(n)]}},V8t=e=>{const t=e?Object.entries(e):void 0;if(t)return Object.fromEntries(t.map(([n,r])=>[n,{description:r.description,sampling:r.sampling?{type:r.sampling.type,rate:r.sampling.rate||0}:void 0,rules:r.rules}]))},tes=e=>{if(!e)return{};let t;if(Array.isArray(e)){t={};for(const r of e)Object.assign(t,r.value)}else t=e;const n={};for(const[r,s]of Object.entries(t))n[r]={description:s.description,sampling:s.sampling?.type==="ratio"?{type:"ratio",rate:s.sampling.rate}:void 0,rules:s.rules};return n},_Ke=e=>{if(!e?.enabled)return;const t=iae(e.model),n=iae(e.observation?.model),r=n||e.observation?.messageTokens||e.observation?.maxTokensPerBatch||e.observation?.bufferTokens!==void 0||e.observation?.bufferActivation!==void 0||e.observation?.blockAfter!==void 0?{model:n,messageTokens:e.observation?.messageTokens,maxTokensPerBatch:e.observation?.maxTokensPerBatch,bufferTokens:e.observation?.bufferTokens,bufferActivation:e.observation?.bufferActivation,blockAfter:e.observation?.blockAfter}:void 0,s=iae(e.reflection?.model),a=s||e.reflection?.observationTokens||e.reflection?.blockAfter!==void 0||e.reflection?.bufferActivation!==void 0?{model:s,observationTokens:e.reflection?.observationTokens,blockAfter:e.reflection?.blockAfter,bufferActivation:e.reflection?.bufferActivation}:void 0;return t||e.scope||e.shareTokenBudget||r||a?{model:t,scope:e.scope,shareTokenBudget:e.shareTokenBudget,observation:r,reflection:a}:!0},nes=e=>{if(!e)return;const t=typeof e=="object"?e:{};return{enabled:!0,model:aae(t.model),scope:t.scope,shareTokenBudget:t.shareTokenBudget,observation:t.observation?{model:aae(t.observation.model),messageTokens:t.observation.messageTokens,maxTokensPerBatch:t.observation.maxTokensPerBatch,bufferTokens:t.observation.bufferTokens,bufferActivation:t.observation.bufferActivation,blockAfter:t.observation.blockAfter}:void 0,reflection:t.reflection?{model:aae(t.reflection.model),observationTokens:t.reflection.observationTokens,blockAfter:t.reflection.blockAfter,bufferActivation:t.reflection.bufferActivation}:void 0}};async function CKe(e,t){const n=e.filter(s=>s.id).map(s=>s.id),r=await Promise.all(e.filter(s=>!s.id).map(s=>t.createStoredMCPClient({name:s.name,description:s.description,servers:s.servers}).then(a=>a.id)));return[...n,...r]}function ANe(e){let t;if(e.requestContextSchema)try{t=typeof e.requestContextSchema=="string"?wx(e.requestContextSchema):e.requestContextSchema}catch{}return{name:e.name,description:e.description,instructions:e.instructions,model:{provider:e.provider,name:e.modelId},tools:e.tools,workflows:e.workflows,agents:e.agents,skills:void 0,workspace:e.workspaceId?{workspaceId:e.workspaceId}:void 0,requestContextSchema:t}}function res(e){const t=sae(e.tools),n=e.memory,{instructionsString:r,instructionBlocks:s}=ees(e.instructions);return{name:e.name||"",description:e.description||"",instructions:r,model:{provider:e.model?.provider||"",name:e.model?.name||""},tools:t,integrationTools:KJr(e.integrationTools),workflows:sae(e.workflows),agents:sae(e.agents),scorers:tes(e.scorers),memory:n?.options?{enabled:!0,lastMessages:n.options.lastMessages,semanticRecall:n.options.semanticRecall,readOnly:n.options.readOnly,vector:n.vector,embedder:n.embedder,observationalMemory:nes(n.observationalMemory)}:void 0,instructionBlocks:s,skills:XJr(e.skills),workspace:JJr(e.workspace),variables:e.requestContextSchema}}function DG(e){const t=We(),n=Ur(),[r,s]=v.useState(!1),[a,i]=v.useState(!1),l=e.mode==="edit",c=l?e.agentId:void 0,u=l&&!!e.isCodeAgentOverride,d=l&&!!e.hasStoredOverride,f=l?e.editorConfig:void 0,p=!u||f===void 0||f!==!1&&f?.instructions===!0,h=!u||f===void 0||f!==!1&&f?.tools===!0,m=!u||f===void 0||f!==!1&&(f?.tools===!0||typeof f?.tools=="object"&&f.tools.description===!0),[g,y]=v.useState(!1),b=u&&!d&&!g,{createStoredAgent:x}=w1(),{updateStoredAgent:S}=w1(c),k=v.useMemo(()=>l?res(e.dataSource):void 0,[l,l?e.dataSource:void 0]),{form:_}=KXr({initialValues:k,isCodeAgentOverride:u}),C=v.useEffectEvent(()=>{if(!k||e.mode!=="edit")return;_.reset(k);const F=e.dataSource.mcpClients,z=Object.keys(F??{});z.length!==0&&Promise.all(z.map(q=>t.getStoredMCPClient(q).details())).then(q=>{const M=q.map($=>({id:$.id,name:$.name,description:$.description,servers:$.servers,selectedTools:F?.[$.id]?.tools??{}}));_.setValue("mcpClients",M,{shouldDirty:!1});const V={..._.getValues("tools")??{}};for(const $ of M)for(const[U,Z]of Object.entries($.selectedTools??{}))V[U]={description:Z.description};_.setValue("tools",V,{shouldDirty:!1})}).catch(()=>{})});v.useEffect(()=>{l&&C()},[l,l?e.dataSource:void 0]);const E=v.useCallback(async F=>{if(u){const V=new Set;for(const K of F.mcpClients??[])for(const te of Object.keys(K.selectedTools??{}))V.add(te);const $={};for(const[K,te]of Object.entries(F.tools??{}))V.has(K)||($[K]=te);const U=await CKe(F.mcpClients??[],t),Z=Object.fromEntries(U.map((K,te)=>{const ee=F.mcpClients?.[te]?.selectedTools??{};return[K,{tools:ee}]}));return{name:F.name,model:F.model,requestContextSchema:F.variables?Object.fromEntries(Object.entries(F.variables)):void 0,instructions:p?rbe(F.instructionBlocks):[],...h||m?{tools:Object.keys($).length>0?$:{},integrationTools:kKe(F.integrationTools),mcpClients:Z}:{}}}if(l){const V=F.mcpClientsToDelete??[];await Promise.all(V.map($=>t.getStoredMCPClient($).delete()))}const z=new Set;for(const V of F.mcpClients??[])for(const $ of Object.keys(V.selectedTools??{}))z.add($);const q={};for(const[V,$]of Object.entries(F.tools??{}))z.has(V)||(q[V]=$);const M=await CKe(F.mcpClients??[],t),G=Object.fromEntries(M.map((V,$)=>{const U=F.mcpClients?.[$]?.selectedTools??{};return[V,{tools:U}]}));return{name:F.name,description:F.description||void 0,instructions:rbe(F.instructionBlocks),model:F.model,tools:Object.keys(q).length>0?q:{},integrationTools:kKe(F.integrationTools),workflows:F.workflows&&Object.keys(F.workflows).length>0?F.workflows:void 0,agents:F.agents&&Object.keys(F.agents).length>0?F.agents:void 0,mcpClients:G,scorers:V8t(F.scorers),skills:F.skills,workspace:F.workspace,requestContextSchema:F.variables?Object.fromEntries(Object.entries(F.variables)):void 0}},[l,u,p,h,m,t]),j=v.useCallback(F=>{const z=F.memory?.enabled?{options:{lastMessages:F.memory.lastMessages,semanticRecall:F.memory.semanticRecall,readOnly:F.memory.readOnly},observationalMemory:_Ke(F.memory.observationalMemory)}:void 0;if(z)return{...z,vector:F.memory?.vector,embedder:F.memory?.embedder}},[]),N=v.useCallback(async F=>{if(!l)return;if(!await _.trigger()){Le.error("Please fill in all required fields");return}const q=_.getValues();i(!0);try{const M=await E(q),G=u?void 0:j(q);if(b){const V={id:e.agentId,...M,memory:G};await x.mutateAsync(V),y(!0)}else await S.mutateAsync({...M,memory:G,...F?{changeMessage:F}:{}});_.reset(q,{keepValues:!0}),u||(n.invalidateQueries({queryKey:["agent-versions",c]}),n.invalidateQueries({queryKey:["stored-agent",c]}),n.invalidateQueries({queryKey:["agent",c]})),Le.success(e.mode==="edit"&&e.saveSuccessMessage?e.saveSuccessMessage:"Draft saved")}catch(M){Le.error(`Failed to save draft: ${M instanceof Error?M.message:"Unknown error"}`)}finally{i(!1)}},[_,l,c,b,e,E,j,x,S,n]),I=v.useCallback(async F=>{if(!F&&!await _.trigger()){Le.error("Please fill in all required fields");return}const z=_.getValues();s(!0);try{if(l){if(F)await t.getStoredAgent(e.agentId).activateVersion(F);else if(b){const q=await E(z),M=u?void 0:j(z),G={id:e.agentId,...q,memory:M};await x.mutateAsync(G),y(!0);const $=(await t.getStoredAgent(e.agentId).listVersions({orderBy:{field:"createdAt",direction:"DESC"},perPage:1})).versions[0];$&&await t.getStoredAgent(e.agentId).activateVersion($.id)}else{const[q,M]=await Promise.all([t.getStoredAgent(e.agentId).details(),t.getStoredAgent(e.agentId).listVersions({orderBy:{field:"createdAt",direction:"DESC"},perPage:1})]),G=M.versions[0];if(!G||G.id===q.activeVersionId){Le.error("No draft changes to publish. Save a draft first.");return}await t.getStoredAgent(e.agentId).activateVersion(G.id)}await Promise.all([n.invalidateQueries({queryKey:["agent-versions",c]}),n.invalidateQueries({queryKey:["stored-agent",c]}),n.invalidateQueries({queryKey:["agent",c]}),n.invalidateQueries({queryKey:["agents"]}),n.invalidateQueries({queryKey:["stored-agents"]})]),Le.success("Agent published"),e.onSuccess(e.agentId)}else{const q=await E(z),M=z.memory?.enabled?{options:{lastMessages:z.memory.lastMessages,semanticRecall:z.memory.semanticRecall,readOnly:z.memory.readOnly},observationalMemory:_Ke(z.memory.observationalMemory)}:void 0,G={...q,memory:M},V=await x.mutateAsync(G);Le.success("Agent created successfully"),e.onSuccess(V.id)}}catch(q){const M=l?"publish":"create";Le.error(`Failed to ${M} agent: ${q instanceof Error?q.message:"Unknown error"}`)}finally{s(!1)}},[_,l,b,t,x,e,c,E,j,n]),A=v.useCallback(async()=>{if(!l)return;if(!await _.trigger()){Le.error("Please fill in all required fields");return}const z=await E(_.getValues());return t.getStoredAgent(e.agentId).export(z)},[E,t,_,l,e]),R=v.useCallback(async()=>{try{const F=await A();if(!F)return;const z=new Blob([F.content],{type:"application/json"}),q=URL.createObjectURL(z),M=document.createElement("a");M.href=q,M.download=F.fileName,M.click(),URL.revokeObjectURL(q),Le.success("Agent JSON downloaded")}catch(F){Le.error(`Failed to download JSON: ${F instanceof Error?F.message:"Unknown error"}`)}},[A]),L=v.useCallback(async({platformApiEndpoint:F,projectId:z})=>{if(l)try{const q=await A();if(!q)return;const M=F.replace(/\/$/,""),G=await fetch(`${M}/v1/server/projects/${z}/agent-overrides/pr`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:q.agentId,fileName:q.fileName,content:q.content})});if(!G.ok){const $=await G.text();throw new Error($||`Request failed with ${G.status}`)}const V=await G.json();window.open(V.url,"_blank","noopener,noreferrer"),Le.success("Pull request opened")}catch(q){Le.error(`Failed to open PR: ${q instanceof Error?q.message:"Unknown error"}`)}},[A,l]),D=Dn({control:_.control}),B=v.useMemo(()=>{if(u)return(D.instructionBlocks??[]).some(M=>M.type==="prompt_block_ref"||M.type==="prompt_block"&&typeof M.content=="string"&&M.content.trim());const F=!!D.name&&!!D.model?.provider&&!!D.model?.name,z=(D.instructionBlocks??[]).some(q=>q.type==="prompt_block_ref"||q.type==="prompt_block"&&typeof q.content=="string"&&q.content.trim());return F&&z},[u,D.name,D.model?.provider,D.model?.name,D.instructionBlocks]),H=_.formState.isDirty;return{form:_,handlePublish:I,handleSaveDraft:N,handleDownloadJson:R,handleOpenPr:L,isSubmitting:r,isSavingDraft:a,canPublish:B,isDirty:H}}function q8t({form:e,mode:t,agentId:n,isSubmitting:r,isSavingDraft:s,handlePublish:a,handleSaveDraft:i,readOnly:l,isCodeAgentOverride:c,isCodeSourceAgent:u,editorConfig:d,basePath:f,currentPath:p,banner:h,children:m,versionId:g,rightPanel:y}){return o.jsx(_Ee,{form:e,mode:t,agentId:n,isSubmitting:r,isSavingDraft:s,handlePublish:a,handleSaveDraft:i,readOnly:l,isCodeAgentOverride:c,isCodeSourceAgent:u,editorConfig:d,children:o.jsxs(oJr,{basePath:f,currentPath:p,versionId:g,rightPanel:y,children:[h,m]})})}function ses(e){return new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})}function aes({agentId:e,selectedVersionId:t,onVersionSelect:n,activeVersionId:r}){const{data:s,isLoading:a}=K1({agentId:e,params:{orderBy:{direction:"DESC"}}}),i=s?.versions??[],c=(r?i.find(u=>u.id===r):void 0)?.versionNumber;return o.jsxs("div",{className:"flex h-full flex-col",children:[o.jsx("div",{className:"border-border1 border-b px-3 py-3",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral5 font-medium",children:"Version history"})}),o.jsx(Br,{className:"min-h-0 flex-1",children:a?o.jsx("div",{className:"px-3 py-4",children:o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"Loading versions..."})}):o.jsx("ul",{className:"flex flex-col",children:i.map(u=>{const d=t===u.id||!t&&u.id===i[0]?.id,f=u.id===r,p=c!==void 0&&u.versionNumber>c;return o.jsx("li",{children:o.jsxs("button",{type:"button",onClick:()=>n(u.id),className:X("w-full text-left px-3 py-2.5 text-sm transition-colors border-l-2",d?"bg-surface2 text-neutral5 border-accent1":"border-transparent text-neutral3 hover:bg-surface3 hover:text-neutral5"),children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs(ye,{variant:"ui-sm",className:"text-inherit",children:["v",u.versionNumber]}),f&&o.jsx(un,{variant:"success",children:"Published"}),p&&o.jsx(un,{variant:"info",children:"Draft"})]}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral2 mt-0.5",children:ses(u.createdAt)})]})},u.id)})})})]})}function aT({title:e,icon:t,badge:n}){return o.jsxs(o.Fragment,{children:[o.jsx(qe,{size:"sm",className:"text-inherit",children:t}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-inherit",children:e}),n]})}function H8t({name:e,prop:t,depth:n}){const r=Array.isArray(t.type)?t.type.filter(a=>a!=="null").join(" | "):t.type,s=t.type==="object"&&t.properties&&Object.keys(t.properties).length>0;return o.jsxs("div",{style:n>0?{paddingLeft:n*12}:void 0,children:[o.jsxs("div",{className:"flex items-center gap-2 py-1",children:[o.jsx("code",{className:"text-accent1 text-xs",children:e}),o.jsx("span",{className:"text-neutral3 text-[11px]",children:r}),t.description&&o.jsxs("span",{className:"text-neutral3 truncate text-[11px] italic",children:["— ",t.description]})]}),s&&o.jsx("div",{className:"border-border1 ml-1 border-l",children:Object.entries(t.properties).map(([a,i])=>o.jsx(H8t,{name:a,prop:i,depth:n+1},a))})]})}function EKe(e,t){const n=e.split(`
701
701
  `),r=t.split(`
702
- `),s=n.length,a=r.length,i=Array.from({length:s+1},()=>new Array(a+1).fill(0));for(let d=1;d<=s;d++)for(let f=1;f<=a;f++)n[d-1]===r[f-1]?i[d][f]=i[d-1][f-1]+1:i[d][f]=Math.max(i[d-1][f],i[d][f-1]);const l=[];let c=s,u=a;for(;c>0||u>0;)c>0&&u>0&&n[c-1]===r[u-1]?(l.push({type:"equal",text:n[c-1]}),c--,u--):u>0&&(c===0||i[c][u-1]>=i[c-1][u])?(l.push({type:"added",text:r[u-1]}),u--):(l.push({type:"removed",text:n[c-1]}),c--);return l.reverse()}function sbe(e){return e.type==="prompt_block"&&typeof e.content=="string"?e.content:null}function ies({promptBlockId:e}){const{data:t}=xL(e),n=t?.content??"";return n?o.jsx(Pa,{content:n,tooltip:"Copy prompt block text",size:"sm"}):null}function tP({block:e}){const t=sbe(e);return t?o.jsx(Pa,{content:t,tooltip:"Copy prompt text",size:"sm"}):e.type==="prompt_block_ref"&&(typeof e.promptBlockId=="string"||typeof e.id=="string")?o.jsx(ies,{promptBlockId:e.promptBlockId??e.id}):null}function oes({previousBlocks:e,currentBlocks:t}){const n=Array.isArray(e)?e:[],r=Array.isArray(t)?t:[],s=r.map(l=>sbe(l)??""),a=n.map(l=>sbe(l)??"");if(n.length<=1&&r.length<=1){const l=a[0]??"",c=s[0]??"",u=n[0];if(l===c)return o.jsxs("div",{className:"border-border1 bg-surface2 relative rounded-md border p-3",children:[u&&o.jsx("div",{className:"absolute top-2 right-2",children:o.jsx(tP,{block:u})}),o.jsx(ye,{variant:"ui-sm",className:"text-neutral4 font-mono whitespace-pre-wrap",children:l||"(empty)"})]});const d=EKe(l,c);return o.jsxs("div",{className:"border-border1 relative overflow-hidden rounded-md border font-mono text-sm",children:[u&&o.jsx("div",{className:"absolute top-2 right-2 z-10",children:o.jsx(tP,{block:u})}),d.map((f,p)=>o.jsxs("div",{className:X("px-3 py-0.5 whitespace-pre-wrap wrap-break-word",f.type==="removed"&&"bg-red-950/20 text-red-300",f.type==="added"&&"bg-green-950/20 text-green-300",f.type==="equal"&&"text-neutral4"),children:[o.jsx("span",{className:"text-neutral3/50 mr-2 inline-block w-4 shrink-0 select-none",children:f.type==="removed"?"−":f.type==="added"?"+":" "}),f.text||" "]},p))]})}const i=Math.max(n.length,r.length);return o.jsx("div",{className:"flex flex-col gap-2",children:Array.from({length:i},(l,c)=>{const u=n[c],d=r[c],f=a[c]??"",p=s[c]??"";if(!u&&d)return o.jsxs("div",{className:"rounded-md border border-green-900/30 bg-green-950/10 p-3 font-mono text-sm",children:[o.jsx(ye,{variant:"ui-xs",className:"mb-1 text-green-400",children:"+ Added block"}),o.jsx(ye,{variant:"ui-sm",className:"whitespace-pre-wrap text-green-300",children:p})]},c);if(u&&!d)return o.jsxs("div",{className:"relative rounded-md border border-red-900/30 bg-red-950/10 p-3 font-mono text-sm",children:[o.jsx("div",{className:"absolute top-2 right-2",children:o.jsx(tP,{block:u})}),o.jsx(ye,{variant:"ui-xs",className:"mb-1 text-red-400",children:"− Removed in latest"}),o.jsx(ye,{variant:"ui-sm",className:"whitespace-pre-wrap text-red-300",children:f})]},c);if(f===p)return o.jsxs("div",{className:"border-border1 bg-surface2 relative rounded-md border p-3",children:[u&&o.jsx("div",{className:"absolute top-2 right-2",children:o.jsx(tP,{block:u})}),o.jsx(ye,{variant:"ui-sm",className:"text-neutral4 font-mono whitespace-pre-wrap",children:f||"(empty)"})]},c);const h=EKe(f,p);return o.jsxs("div",{className:"border-border1 relative overflow-hidden rounded-md border font-mono text-sm",children:[u&&o.jsx("div",{className:"absolute top-2 right-2 z-10",children:o.jsx(tP,{block:u})}),h.map((m,g)=>o.jsxs("div",{className:X("px-3 py-0.5 whitespace-pre-wrap wrap-break-word",m.type==="removed"&&"bg-red-950/20 text-red-300",m.type==="added"&&"bg-green-950/20 text-green-300",m.type==="equal"&&"text-neutral4"),children:[o.jsx("span",{className:"text-neutral3/50 mr-2 inline-block w-4 shrink-0 select-none",children:m.type==="removed"?"−":m.type==="added"?"+":" "}),m.text||" "]},g))]},c)})})}function les({promptBlockId:e}){const{data:t,isLoading:n}=xL(e);if(n)return o.jsx("div",{className:"flex items-center justify-center py-4",children:o.jsx(Xt,{className:"h-4 w-4"})});const r=t?.content??"";return o.jsxs("div",{className:"border-border1 bg-surface2 relative rounded-md border p-3",children:[r&&o.jsx("div",{className:"absolute top-2 right-2",children:o.jsx(Pa,{content:r,tooltip:"Copy prompt block text",size:"sm"})}),t?.name&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mb-1 font-medium",children:t.name}),o.jsx(ye,{variant:"ui-sm",className:"text-neutral4 font-mono whitespace-pre-wrap",children:r||"(empty)"})]})}function W8t({blocks:e}){const t=Array.isArray(e)?e:[];return t.length===0?o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 py-2",children:"No instruction blocks configured"}):o.jsx("div",{className:"flex flex-col gap-2",children:t.map((n,r)=>{if(n.type==="prompt_block_ref"){const a=n.promptBlockId??n.id;return o.jsx(les,{promptBlockId:a},a??r)}const s=typeof n.content=="string"?n.content:"";return o.jsxs("div",{className:"border-border1 bg-surface2 relative rounded-md border p-3",children:[s&&o.jsx("div",{className:"absolute top-2 right-2",children:o.jsx(Pa,{content:s,tooltip:"Copy prompt text",size:"sm"})}),o.jsx(ye,{variant:"ui-sm",className:"text-neutral4 font-mono whitespace-pre-wrap",children:s||"(empty)"})]},n.id??r)})})}function ces({previousTools:e,currentTools:t}){const n=new Set(e?Object.keys(e):[]),r=new Set(t?Object.keys(t):[]),s=[...new Set([...n,...r])].sort();return o.jsx("div",{className:"flex flex-col gap-1.5",children:s.map(a=>{const i=n.has(a),l=r.has(a);let c;return i&&l?c="same":i?c="removed":c="added",o.jsxs("div",{className:X("flex items-center gap-2 rounded-md border px-3 py-1.5",c==="removed"&&"border-red-900/30 bg-red-950/10",c==="added"&&"border-green-900/30 bg-green-950/10",c==="same"&&"border-border1 bg-surface2"),children:[o.jsx(ye,{variant:"ui-sm",className:X("font-mono",c==="removed"&&"text-red-300 line-through",c==="added"&&"text-green-300",c==="same"&&"text-neutral5"),children:a}),c==="removed"&&o.jsx(un,{variant:"error",className:"ml-auto",children:"removed in latest"}),c==="added"&&o.jsx(un,{variant:"success",className:"ml-auto",children:"added in latest"})]},a)})})}function ues({tools:e}){const t=e?Object.entries(e):[];return t.length===0?o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 py-2",children:"No tools configured"}):o.jsx("div",{className:"flex flex-col gap-1.5",children:t.map(([n,r])=>o.jsxs("div",{className:"border-border1 bg-surface2 rounded-md border px-3 py-1.5",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral5 font-mono",children:n}),r?.description?o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-0.5",children:String(r.description)}):null]},n))})}function des({previousVars:e,currentVars:t}){const n=e?.properties??{},r=t?.properties??{},s=new Set(Object.keys(n)),a=new Set(Object.keys(r)),i=[...new Set([...s,...a])].sort();return i.length===0?o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 py-2",children:"No variables configured"}):o.jsx("div",{className:"flex flex-col gap-1.5",children:i.map(l=>{const c=s.has(l),u=a.has(l);let d;return c&&u?d="same":c?d="removed":d="added",o.jsxs("div",{className:X("flex items-center gap-2 rounded-md border px-3 py-1.5",d==="removed"&&"border-red-900/30 bg-red-950/10",d==="added"&&"border-green-900/30 bg-green-950/10",d==="same"&&"border-border1 bg-surface2"),children:[o.jsx(ye,{variant:"ui-sm",className:X("font-mono",d==="removed"&&"text-red-300 line-through",d==="added"&&"text-green-300",d==="same"&&"text-neutral5"),children:`{{${l}}}`}),d==="removed"&&o.jsx(un,{variant:"error",className:"ml-auto",children:"removed in latest"}),d==="added"&&o.jsx(un,{variant:"success",className:"ml-auto",children:"added in latest"})]},l)})})}function fes({variables:e}){const t=e?.properties??{},n=Object.entries(t);return n.length===0?o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 py-2",children:"No variables configured"}):o.jsx("div",{className:"flex flex-col gap-1.5",children:n.map(([r,s])=>o.jsxs("div",{className:"border-border1 bg-surface2 flex items-center gap-2 rounded-md border px-3 py-1.5",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral5 font-mono",children:`{{${r}}}`}),s?.type?o.jsx(un,{variant:"default",children:String(s.type)}):null]},r))})}function pes({agentId:e,selectedVersionId:t,latestVersionId:n}){const{form:r}=Ho(),s=r.watch("tools"),a=r.watch("variables"),i=r.watch("instructionBlocks"),l=s?Object.keys(s).length:0,{data:c,isLoading:u}=g4r({agentId:e,fromVersionId:t,toVersionId:n}),d=v.useMemo(()=>{const b=new Map;if(c?.diffs)for(const x of c.diffs)b.set(x.field,{previousValue:x.previousValue,currentValue:x.currentValue});return b},[c]),f=d.get("instructions"),p=d.get("tools"),h=d.get("requestContextSchema"),m=f?o.jsx(un,{variant:"warning",size:"sm",children:"modified"}):null,g=p?o.jsx(un,{variant:"warning",size:"sm",children:"modified"}):l>0?o.jsx(un,{variant:"default",size:"sm",children:`${l}`}):null,y=h?o.jsx(un,{variant:"warning",size:"sm",children:"modified"}):null;return u?o.jsx("div",{className:"flex items-center justify-center py-8",children:o.jsx(Xt,{className:"h-5 w-5"})}):o.jsxs(Dc,{defaultTab:"variables",className:"flex min-h-full flex-col overflow-visible",children:[o.jsxs(Mc,{variant:"pill-ghost",className:"shrink-0",children:[o.jsx(Rr,{value:"variables",children:o.jsx(aT,{title:"Variables",icon:o.jsx(Ey,{}),badge:y})}),o.jsx(Rr,{value:"instructions",children:o.jsx(aT,{title:"System Prompt",icon:o.jsx(Ibe,{}),badge:m})}),o.jsx(Rr,{value:"tools",children:o.jsx(aT,{title:"Tools",icon:o.jsx(zp,{}),badge:g})})]}),o.jsx(Xr,{value:"variables",className:"px-4 py-4",children:h?o.jsx(des,{previousVars:h.previousValue,currentVars:h.currentValue}):o.jsx(fes,{variables:a})}),o.jsx(Xr,{value:"instructions",className:"px-4 py-4",children:f?o.jsx(oes,{previousBlocks:f.previousValue,currentBlocks:f.currentValue}):o.jsx(W8t,{blocks:i})}),o.jsx(Xr,{value:"tools",className:"px-4 py-4",children:p?o.jsx(ces,{previousTools:p.previousValue,currentTools:p.currentValue}):o.jsx(ues,{tools:s})})]})}function hes({agentId:e,selectedVersionId:t,latestVersionId:n}){const{form:r,readOnly:s}=Ho(),a=r.watch("tools"),i=r.watch("instructionBlocks"),l=r.watch("variables"),c=a?Object.keys(a).length:0,u=v.useMemo(()=>Object.entries(l?.properties??{}),[l]),d=s&&!!t&&!!n&&t!==n;return o.jsxs("div",{className:X("flex flex-col h-full"),children:[o.jsx("div",{className:"border-border1 border-b px-4 py-3"}),o.jsx(Br,{className:"min-h-0 flex-1",children:d?o.jsx(pes,{agentId:e,selectedVersionId:t,latestVersionId:n}):o.jsxs(Dc,{defaultTab:"variables",className:"flex min-h-full flex-col overflow-visible",children:[o.jsxs(Mc,{variant:"pill-ghost",className:"shrink-0",children:[o.jsx(Rr,{value:"variables",children:o.jsx(aT,{title:"Variables",icon:o.jsx(Ey,{})})}),o.jsx(Rr,{value:"instructions",children:o.jsx(aT,{title:"System Prompt",icon:o.jsx(Ibe,{})})}),o.jsx(Rr,{value:"tools",children:o.jsx(aT,{title:"Tools",icon:o.jsx(zp,{}),badge:c>0?o.jsx(un,{variant:"default",size:"sm",children:`${c}`}):void 0})})]}),o.jsx(Xr,{value:"variables",className:"py-0",children:o.jsxs("div",{className:"flex flex-col gap-1 px-4 py-4",children:[u.length>0?o.jsx("div",{className:"flex flex-col",children:u.map(([f,p])=>o.jsx(H8t,{name:f,prop:p,depth:0},f))}):null,o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-1",children:u.length>0?"Defined via requestContextSchema in code.":"No variables defined. Add a requestContextSchema to your agent to define variables."})]})}),o.jsxs(Xr,{value:"instructions",className:"px-4 py-0 pb-4",children:[o.jsx("div",{className:"flex flex-col gap-3 pt-4 pb-2",children:o.jsxs(ye,{variant:"ui-sm",className:"text-neutral3 font-normal",children:["Add instruction blocks to your agent. Blocks are combined in order to form the system prompt. You can"," ",o.jsxs(Pn,{children:[o.jsx(An,{className:"text-neutral3 hover:text-neutral5 inline cursor-pointer underline decoration-dotted",children:"use variables"}),o.jsx(Rn,{side:"bottom",align:"start",className:"max-w-72",children:o.jsxs("span",{children:["Use ",o.jsx("code",{className:"text-accent1 font-medium",children:"{{variableName}}"})," syntax to insert dynamic values into your instruction blocks."]})})]})," ","as part of your instruction blocks."]})}),s?o.jsx(W8t,{blocks:i}):o.jsx(y8t,{})]}),o.jsx(Xr,{value:"tools",className:"px-4 py-0 pb-4",children:o.jsx(x8t,{})})]})})]})}function oae(e){return typeof e=="object"&&e!==null}function mes(e){if(!oae(e))return{};const t={};return typeof e.maxSteps=="number"&&(t.maxSteps=e.maxSteps),oae(e.modelSettings)&&(t.modelSettings=e.modelSettings),oae(e.providerOptions)&&(t.providerOptions=e.providerOptions),t}function RNe(e){if(!e)return{modelSettings:{}};const t=mes(e.defaultOptions),{maxOutputTokens:n,...r}=t.modelSettings??{};return{modelSettings:{...r,...n!==void 0&&{maxTokens:n},...t.maxSteps!==void 0&&{maxSteps:t.maxSteps},...t.providerOptions!==void 0&&{providerOptions:t.providerOptions}}}}function ges(e){const t=e?.properties;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}function ves({labelTooltip:e,variablesSchema:t}){const{setSchemaValues:n,schemaValues:r}=Mwe(),s=JSON.stringify(r),a=v.useMemo(()=>{try{return fm(um(t))}catch(i){return console.error("Failed to parse variables schema:",i),null}},[t]);return a?o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx(Qwe,{tooltip:e,children:"Request Context"}),o.jsx(Pa,{content:s})]}),o.jsx(j3,{schema:a,onSubmit:n,submitButtonLabel:"Save",defaultValues:r})]}):o.jsx("div",{className:"p-4",children:o.jsx(ye,{variant:"ui-sm",className:"text-red-400",children:"Failed to parse request context schema"})})}function yes({mode:e,onModeChange:t}){return o.jsxs("div",{className:"border-border1 flex items-center gap-1 rounded-md border p-0.5",children:[o.jsxs("button",{type:"button","aria-pressed":e==="form",onClick:()=>t("form"),className:X("flex items-center gap-1.5 px-2 py-1 rounded text-xs transition-colors",e==="form"?"bg-surface3 text-neutral5":"text-neutral3 hover:text-neutral5"),children:[o.jsx(qe,{size:"sm",children:o.jsx(Dbe,{})}),"Form"]}),o.jsxs("button",{type:"button","aria-pressed":e==="json",onClick:()=>t("json"),className:X("flex items-center gap-1.5 px-2 py-1 rounded text-xs transition-colors",e==="json"?"bg-surface3 text-neutral5":"text-neutral3 hover:text-neutral5"),children:[o.jsx(qe,{size:"sm",children:o.jsx(FN,{})}),"JSON"]})]})}function bes({requestContextSchema:e,freeformEditorClassName:t,requestContextTooltip:n}){const s=dMt()?.form.watch("variables"),[a,i]=v.useState("form"),l=ges(s),c=!!e||l;return o.jsx("div",{className:"space-y-4",children:c?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"flex items-center justify-end",children:o.jsx(yes,{mode:a,onModeChange:i})}),a==="form"?e?o.jsx(A1e,{requestContextSchema:e,labelTooltip:n}):l?o.jsx(ves,{variablesSchema:s,labelTooltip:n}):null:o.jsx(Uye,{editorClassName:t,labelTooltip:n})]}):o.jsx(Uye,{editorClassName:t,labelTooltip:n})})}const xes=()=>{const{debugMode:e,setDebugMode:t}=v.useContext(Bl);return o.jsxs(o.Fragment,{children:[o.jsx(ye,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Debug Mode"}),o.jsx(zo,{checked:e,onCheckedChange:n=>t(n)})]})},wes=({className:e,editorClassName:t="h-[400px]",hideTitle:n=!1,showEditorHeader:r=!1}={})=>{const s=Yx(),{settings:a,setSettings:i,entityType:l}=tH(),c=d=>{if(!d)return i({...a,tracingOptions:void 0});try{const f=JSON.parse(d);typeof f=="object"&&f!==null&&i({...a,tracingOptions:f})}catch{}};let u="{}";try{u=JSON.stringify(a?.tracingOptions,null,2)}catch{}return o.jsxs("div",{className:X("px-5 py-2",!n&&"space-y-2",e),children:[!n&&o.jsx(ye,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),r&&o.jsxs("div",{className:"flex items-center justify-between pb-2",children:[o.jsx(ye,{as:"label",variant:"ui-md",className:"text-neutral3",children:"Tracing Options (JSON)"}),o.jsx(ye,{as:"span",variant:"ui-xs",className:"text-neutral3",children:"Auto-applied on valid JSON"})]}),o.jsx(Qu,{value:u,onChange:c,theme:s,extensions:[Rp],className:X(t,"overflow-y-scroll rounded-lg border border-border1 bg-surface2 overflow-hidden p-3","[&_.cm-editor]:!bg-surface2 [&_.cm-gutters]:!bg-surface2")}),l==="workflow"&&o.jsx(xes,{})]})},jKe="h-[260px] md:h-[360px]";function Z8t({requestContextSchema:e}){return o.jsx(Br,{className:"w-full",maxHeight:"min(600px, calc(100dvh - 8rem))",children:o.jsxs("div",{className:"space-y-4 p-4",children:[o.jsx(ye,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Run options"}),o.jsxs("div",{className:"grid gap-5 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]",children:[o.jsx("section",{className:"min-w-0",children:o.jsx(bes,{requestContextSchema:e,requestContextTooltip:"Request context values are passed into experiments and test chats.",freeformEditorClassName:jKe})}),o.jsx("section",{className:"min-w-0",children:o.jsx(wes,{className:"px-0 py-0",editorClassName:jKe,hideTitle:!0,showEditorHeader:!0})})]})]})})}const Ses={align:"shift"};function G8t({requestContextSchema:e}){return o.jsxs(Pf,{children:[o.jsx(Bd,{asChild:!0,children:o.jsx(ce,{variant:"default",size:"icon-md",type:"button",tooltip:"Run options","data-testid":"composer-run-options-trigger",children:o.jsx(HV,{className:"text-neutral3 hover:text-neutral6 h-5 w-5"})})}),o.jsx(Ud,{align:"start",collisionAvoidance:Ses,className:"w-[min(760px,calc(100vw-2rem))] p-0",children:o.jsx(Z8t,{requestContextSchema:e})})]})}function kes({ctx:e}){const{isDirty:t}=k1e({control:e.form.control}),n=e.handleSaveDraft,r=e.isSavingDraft??!1,s=e.isCodeSourceAgent??!1;if(!t)return null;const a=s?"Save to filesystem":"Save draft",i=s?"You have unsaved changes to the agent configuration. Save to filesystem to ensure the chat uses your latest changes.":"You have unsaved changes to the agent configuration. Save your draft to ensure the chat uses your latest changes.";return o.jsx(En,{variant:"warning",title:"Unsaved changes",className:"mx-4 mt-3 mb-0",action:n&&o.jsxs(ce,{type:"button",variant:"default",size:"sm",onClick:()=>n(),disabled:r,children:[o.jsx(jd,{className:"h-3.5 w-3.5"}),r?"Saving...":a]}),children:o.jsx(En.Message,{children:i})})}function Oes({agentId:e,agentName:t,modelVersion:n,agentVersionId:r,hasMemory:s}){const a=v.useMemo(()=>xo(),[e]),i=zl(),l=Object.keys(i).length>0,c=dMt(),{data:u}=mc(e),d=v.useMemo(()=>RNe(u),[u]);return o.jsx(wEe,{agentId:e,defaultSettings:d,children:o.jsx(fZ,{children:o.jsxs(pZ,{agentId:e,threadId:a,enabled:!!u?.browserTools?.length,children:[o.jsx(TEe,{children:o.jsx(kEe,{children:o.jsx(xFr,{enabled:!0,threadId:a,agentId:e,requestContext:l?i:void 0,children:o.jsxs("div",{className:"flex h-full flex-col",children:[c&&o.jsx(kes,{ctx:c}),o.jsx("div",{className:"min-h-0 flex-1",children:o.jsx(MNe,{agentId:e,agentName:t,modelVersion:n,agentVersionId:r,supportsMemory:u?.supportsMemory,threadId:a,memory:s,modelList:u?.modelList,isNewThread:!0,runOptionsSlot:o.jsx(G8t,{requestContextSchema:u?.requestContextSchema})},a)})]})})},a)}),o.jsx(JCe,{})]},`session-${e}-${a}`)},`browser-${e}-${a}`)})}function _es(e){return new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})}function Ces({agentId:e,activeVersionId:t,selectedVersionId:n,onVersionSelect:r,isDirty:s,isSavingDraft:a,isPublishing:i,hasDraft:l,readOnly:c,isCodeSourceAgent:u=!1,showCodeModeActions:d=!1,canOpenPr:f=!1,openPrTitle:p,onSaveDraft:h,onPublish:m,onDownloadJson:g,onOpenPr:y,isViewingPreviousVersion:b=!1}){const[x,S]=v.useState(!1),[k,_]=v.useState(""),{data:C}=K1({agentId:e,params:{orderBy:{direction:"DESC"}}}),E=v.useMemo(()=>C?.versions??[],[C?.versions]),j=E[0],I=(t?E.find(H=>H.id===t):void 0)?.versionNumber,A=v.useMemo(()=>E.map(H=>{const F=H.id===t,z=I!==void 0&&H.versionNumber>I;return{value:H.id,label:`${u?"Save":"v"}${H.versionNumber} - ${_es(H.createdAt)}`,description:H.changeMessage||void 0,end:u?o.jsx(un,{variant:F?"success":"info",children:F?"Current":"Saved"}):F?o.jsx(un,{variant:"success",children:"Published"}):z?o.jsx(un,{variant:"info",children:"Draft"}):void 0}}),[E,t,I,u]),R=n??j?.id??"",L=c||!s||a||i,D=u?"Code mode saves write override JSON to filesystem-backed editor storage. This dropdown shows saved override snapshots for this agent.":"Changes are saved as draft versions. When you're ready, publish a version to make it the active configuration used in production.",B=v.useCallback(async()=>{if(a)return;const H=k.trim();await h(H||void 0),S(!1),_("")},[k,h,a]);return{versionSelector:o.jsxs("div",{className:"border-border1 bg-surface3 flex items-center gap-2 border-b px-4 py-3",children:[E.length>0?o.jsx(ac,{options:A,value:R,onValueChange:r,placeholder:"Select version...",variant:"ghost",className:"min-w-0 flex-1"}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:u?"No filesystem saves yet":"No versions yet"}),R&&o.jsx(Pa,{content:R,tooltip:"Copy version ID",size:"sm"}),o.jsxs(Pn,{children:[o.jsx(An,{"aria-label":"Version information",className:"text-neutral3 hover:text-neutral5 shrink-0 rounded-sm transition-colors focus-visible:ring-1 focus-visible:ring-white/30 focus-visible:outline-hidden",children:o.jsx(qe,{size:"sm",children:o.jsx(Bx,{})})}),o.jsx(Rn,{side:"bottom",align:"start",className:"max-w-56",children:D})]}),o.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-2",children:[c&&o.jsx(un,{variant:"warning",children:"Read-only"}),!c&&l&&!u&&o.jsx(un,{variant:"info",children:"Unpublished"})]})]}),actionBar:o.jsxs("div",{className:"border-border1 bg-surface3 flex items-center justify-end border-t px-3 py-2",children:[d?o.jsxs(Mr,{className:"flex-wrap justify-end",children:[o.jsxs(ce,{variant:"default",size:"md",onClick:()=>{g?.()},children:[o.jsx(qe,{size:"sm",children:o.jsx(vf,{})}),"Download JSON"]}),f?o.jsxs(ce,{variant:"primary",size:"md",onClick:()=>{y?.()},title:p,children:[o.jsx(qe,{size:"sm",children:o.jsx(mit,{})}),"Open PR"]}):o.jsx(ce,{variant:"primary",size:"md",onClick:()=>{h()},disabled:L,children:a?o.jsxs(o.Fragment,{children:[o.jsx(Xt,{className:"size-3.5"}),"Saving…"]}):o.jsxs(o.Fragment,{children:[o.jsx(qe,{size:"sm",children:o.jsx(jd,{})}),"Save to filesystem"]})})]}):c&&!b?null:o.jsxs(Mr,{className:"flex-wrap justify-end",children:[o.jsxs(Mr,{spacing:"close",children:[o.jsx(ce,{variant:"default",size:"md",onClick:()=>h(),disabled:L,children:a?o.jsxs(o.Fragment,{children:[o.jsx(Xt,{className:"size-3.5"}),"Saving…"]}):o.jsxs(o.Fragment,{children:[o.jsx(qe,{size:"sm",children:o.jsx(jd,{})}),"Save New Version"]})}),o.jsxs(dt,{children:[o.jsx(dt.Trigger,{asChild:!0,children:o.jsx(ce,{variant:"default",size:"md",disabled:L,"aria-label":"More save options",children:o.jsx(Na,{className:"size-3.5"})})}),o.jsx(dt.Content,{align:"end",children:o.jsxs(dt.Item,{onSelect:()=>S(!0),children:[o.jsx(qe,{size:"sm",children:o.jsx(dT,{})}),"Save with message"]})})]})]}),o.jsx(ce,{variant:"primary",size:"md",onClick:m,disabled:b?n===t||i||a:c||!l||i||a,children:i?o.jsxs(o.Fragment,{children:[o.jsx(Xt,{className:"size-3.5"}),"Publishing…"]}):o.jsxs(o.Fragment,{children:[o.jsx(qe,{size:"sm",children:o.jsx(fa,{})}),b?"Publish This Version":"Publish"]})})]}),o.jsx(br,{open:x,onOpenChange:S,children:o.jsxs(xr,{children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Save New Version"}),o.jsx(Ks,{children:"Add a message to describe the changes in this version."})]}),o.jsx($r,{className:"py-1",children:o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"change-message",children:"Change message"}),o.jsx(Cn,{id:"change-message",placeholder:"Describe what changed...",value:k,className:"focus:ring-white/50",onChange:H=>_(H.target.value),onKeyDown:H=>{H.key==="Enter"&&B()},disabled:a,autoFocus:!0})]})}),o.jsxs(Tc,{className:"px-6",children:[o.jsx(ce,{variant:"default",size:"sm",onClick:()=>S(!1),children:"Cancel"}),o.jsxs(ce,{variant:"primary",size:"sm",onClick:B,disabled:a,children:[o.jsx(qe,{size:"sm",children:o.jsx(jd,{})}),"Save Version"]})]})]})})]})}}function Ees({agentId:e,activeVersionId:t,selectedVersionId:n,latestVersionId:r,onVersionSelect:s,isDirty:a,isSavingDraft:i,isPublishing:l,hasDraft:c,readOnly:u,isCodeSourceAgent:d,showCodeModeActions:f,canOpenPr:p,openPrTitle:h,onSaveDraft:m,onPublish:g,onDownloadJson:y,onOpenPr:b,isViewingPreviousVersion:x}){const{versionSelector:S,actionBar:k}=Ces({agentId:e,activeVersionId:t,selectedVersionId:n,onVersionSelect:s,isDirty:a,isSavingDraft:i,isPublishing:l,hasDraft:c,readOnly:u,isCodeSourceAgent:d,showCodeModeActions:f,canOpenPr:p,openPrTitle:h,onSaveDraft:m,onPublish:g,onDownloadJson:y,onOpenPr:b,isViewingPreviousVersion:x});return o.jsxs(MEe,{children:[S,o.jsx("div",{className:"px-4 pt-3",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"Edit your agent's system prompt, tools, and variables below."})}),o.jsx("div",{className:"min-h-0 flex-1",children:o.jsx(hes,{agentId:e,selectedVersionId:n,latestVersionId:r})}),k]})}function jes({agentId:e,agentName:t,modelVersion:n,agentVersionId:r,hasMemory:s,activeVersionId:a,selectedVersionId:i,latestVersionId:l,onVersionSelect:c,isDirty:u,isSavingDraft:d,isPublishing:f,hasDraft:p,readOnly:h,isCodeSourceAgent:m,showCodeModeActions:g,canOpenPr:y,openPrTitle:b,onSaveDraft:x,onPublish:S,onDownloadJson:k,onOpenPr:_,isViewingPreviousVersion:C}){return o.jsx(_Ne,{agentId:e,leftDrawerLabel:"Open configuration",leftSlot:o.jsx(Ees,{agentId:e,activeVersionId:a,selectedVersionId:i,latestVersionId:l,onVersionSelect:c,isDirty:u,isSavingDraft:d,isPublishing:f,hasDraft:p,readOnly:h,isCodeSourceAgent:m,showCodeModeActions:g,canOpenPr:y,openPrTitle:b,onSaveDraft:x,onPublish:S,onDownloadJson:k,onOpenPr:_,isViewingPreviousVersion:C}),children:o.jsx(Oes,{agentId:e,agentName:t,modelVersion:n,agentVersionId:r,hasMemory:s})})}function NN(e,t){return typeof t=="number"||/^\d+(\.\d+)*$/.test(String(t))?`${e} v${t}`:`${e} ${t}`}const kD=(e,t,n)=>{const r=We();return yt({queryKey:["dataset-experiments",e,t,n],queryFn:()=>r.listDatasetExperiments(e,t),enabled:!!e,select:s=>{if(!n)return s;const a=s.experiments.filter(i=>!(n.status&&i.status!==n.status||n.targetType&&i.targetType!==n.targetType||n.targetId&&i.targetId!==n.targetId));return{...s,experiments:a}}})},RV=(e,t)=>{const n=We();return yt({queryKey:["dataset-experiment",e,t],queryFn:()=>n.getDatasetExperiment(e,t),enabled:!!e&&!!t,gcTime:0,staleTime:0,refetchInterval:r=>{const s=r.state.data?.status;return s==="running"||s==="pending"?2e3:!1}})},TKe=100,LG=({datasetId:e,experimentId:t,experimentStatus:n})=>{const r=We(),{inView:s,setRef:a}=W_(),i=M1({queryKey:["dataset-experiment-results",e,t,n],queryFn:async({pageParam:l})=>r.listDatasetExperimentResults(e,t,{page:l,perPage:TKe}),initialPageParam:0,getNextPageParam:(l,c,u)=>{if(!l?.results?.length)return;const d=(u+1)*TKe,f=l?.pagination?.total??0;if(!(d>=f))return u+1},enabled:!!e&&!!t,refetchInterval:n==="running"||n==="pending"?2e3:!1,select:l=>l.pages.flatMap(c=>c?.results??[])});return v.useEffect(()=>{s&&i.hasNextPage&&!i.isFetchingNextPage&&i.fetchNextPage()},[s,i.hasNextPage,i.isFetchingNextPage]),{...i,setEndOfListElement:a}},Q8t=(e,t)=>{const n=We();return yt({queryKey:["dataset-experiment-scores",e,t],queryFn:async()=>{const r=[];let s=0;const a=100;for(;;){const l=await n.listScoresByRunId({runId:e,page:s,perPage:a});if(r.push(...l.scores),!l.pagination.hasMore)break;s++}const i={};for(const l of r)i[l.entityId]||(i[l.entityId]=[]),i[l.entityId].push(l);return i},enabled:!!e,refetchInterval:t==="running"||t==="pending"?2e3:!1})};function Tes(e){return new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Nes({status:e}){switch(e){case"completed":return o.jsxs(un,{variant:"success",className:"gap-1",children:[o.jsx(lO,{className:"h-3 w-3"}),"completed"]});case"failed":return o.jsxs(un,{variant:"error",className:"gap-1",children:[o.jsx(M2,{className:"h-3 w-3"}),"failed"]});case"running":return o.jsxs(un,{variant:"info",className:"gap-1",children:[o.jsx(ia,{className:"h-3 w-3 animate-spin"}),"running"]});case"pending":return o.jsxs(un,{variant:"default",className:"gap-1",children:[o.jsx(uT,{className:"h-3 w-3"}),"pending"]});default:return o.jsx(un,{variant:"default",children:e})}}function abe(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Ies(e){return Array.isArray(e)?e.flatMap(t=>{if(!t||typeof t!="object")return[];const n=t;return[{toolName:typeof n.toolName=="string"?n.toolName:"Unknown tool",args:n.args&&typeof n.args=="object"&&!Array.isArray(n.args)?n.args:{}}]}):[]}function Aes(e){const t=e&&typeof e=="object"?e:{};return{text:typeof t.text=="string"?t.text:void 0,object:t.object&&typeof t.object=="object"?t.object:void 0,toolCalls:Ies(t.toolCalls),toolResults:Array.isArray(t.toolResults)?t.toolResults:[],usage:t.usage&&typeof t.usage=="object"?t.usage:void 0,traceId:typeof t.traceId=="string"?t.traceId:void 0,error:typeof t.error=="string"?t.error:t.error?String(t.error):void 0}}function Res({traceId:e}){const t=We(),[n,r]=v.useState(!1),{data:s,isLoading:a,isError:i}=yt({queryKey:["trajectory",e],queryFn:()=>t.getTraceTrajectory(e),enabled:n});return o.jsxs(Tf,{open:n,onOpenChange:r,children:[o.jsxs($d,{className:"flex items-center gap-1.5 text-xs font-medium text-purple-400 hover:text-purple-300",children:[o.jsx(pa,{className:"h-3 w-3 shrink-0"}),"Trajectory Steps"]}),o.jsx(Md,{children:a?o.jsxs("div",{className:"mt-1 flex items-center gap-2 px-3 py-2",children:[o.jsx(Xt,{className:"h-3 w-3"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:"Loading trajectory..."})]}):i?o.jsx(ye,{variant:"ui-xs",className:"mt-1 px-3 py-2 text-red-400",children:"Failed to load trajectory steps"}):s?.steps&&s.steps.length>0?o.jsxs("div",{className:"mt-1 space-y-1",children:[s.steps.map((l,c)=>o.jsxs("div",{className:"bg-surface1 flex items-center gap-2 rounded px-3 py-1.5 text-xs",children:[o.jsx(Js,{size:"small",color:"purple",children:String(l.stepType||"step")}),o.jsx("span",{className:"text-neutral5 font-mono font-medium",children:String(l.name||`Step ${c+1}`)}),typeof l.durationMs=="number"&&o.jsxs("span",{className:"text-neutral2 ml-auto",children:[l.durationMs,"ms"]})]},c)),typeof s.totalDurationMs=="number"&&o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3 px-3 py-1",children:["Total: ",s.totalDurationMs,"ms"]})]}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral2 mt-1 px-3 py-2",children:"No trajectory steps found"})})]})}function Pes({output:e,traceId:t,onViewTrace:n}){const r=Aes(e),s=t||r.traceId;return o.jsxs("div",{className:"space-y-2",children:[r.text?o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Response"}),o.jsx("div",{className:"text-neutral5 bg-surface1 max-h-48 overflow-y-auto rounded px-3 py-2 text-sm wrap-break-word whitespace-pre-wrap",children:r.text})]}):null,r.object&&o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Structured Output"}),o.jsx("pre",{className:"text-neutral4 bg-surface1 max-h-48 overflow-x-auto overflow-y-auto rounded px-3 py-2 text-xs wrap-break-word whitespace-pre-wrap",children:JSON.stringify(r.object,null,2)})]}),r.toolCalls.length>0&&o.jsxs("div",{className:"space-y-1",children:[o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:["Tool Calls (",r.toolCalls.length,")"]}),o.jsx("div",{className:"space-y-1",children:r.toolCalls.map((a,i)=>o.jsxs(Tf,{children:[o.jsxs($d,{className:"text-neutral4 hover:text-neutral5 bg-surface1 flex w-full items-center gap-1.5 rounded px-2 py-1 text-left text-xs",children:[o.jsx(pa,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:"font-mono font-medium",children:a.toolName})]}),o.jsx(Md,{children:o.jsx("pre",{className:"text-neutral4 bg-surface2 mt-1 ml-4 max-h-32 overflow-x-auto overflow-y-auto rounded px-3 py-2 text-xs wrap-break-word whitespace-pre-wrap",children:JSON.stringify(a.args,null,2)})})]},i))})]}),r.toolResults.length>0&&o.jsxs("div",{className:"space-y-1",children:[o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:["Tool Results (",r.toolResults.length,")"]}),o.jsx("div",{className:"space-y-1",children:r.toolResults.map((a,i)=>o.jsxs(Tf,{children:[o.jsxs($d,{className:"text-neutral4 hover:text-neutral5 bg-surface1 flex w-full items-center gap-1.5 rounded px-2 py-1 text-left text-xs",children:[o.jsx(pa,{className:"h-3 w-3 shrink-0"}),o.jsxs("span",{className:"font-mono",children:["Result ",i+1]})]}),o.jsx(Md,{children:o.jsx("pre",{className:"text-neutral4 bg-surface2 mt-1 ml-4 max-h-32 overflow-x-auto overflow-y-auto rounded px-3 py-2 text-xs wrap-break-word whitespace-pre-wrap",children:JSON.stringify(a,null,2)})})]},i))})]}),r.usage&&o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Usage"}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral2 font-mono",children:[r.usage.promptTokens," prompt · ",r.usage.completionTokens," completion · ",r.usage.totalTokens," ","total"]})]}),s&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Trace"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral2 truncate font-mono",children:s}),o.jsx(Pa,{content:s,tooltip:"Copy trace ID",size:"sm"}),n&&o.jsxs("button",{type:"button",onClick:()=>n(s),className:"text-accent1 hover:text-accent2 flex cursor-pointer items-center gap-1 text-xs transition-colors",children:[o.jsx(Sa,{className:"h-3 w-3"}),"View Trace"]})]}),!r.text&&!r.object&&r.toolCalls.length===0&&o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Output"}),o.jsx("pre",{className:"text-neutral4 bg-surface1 max-h-48 overflow-x-auto overflow-y-auto rounded px-3 py-2 text-xs wrap-break-word whitespace-pre-wrap",children:abe(e)})]})]})}function $es({experiment:e,onBack:t,onSendToReview:n,onCreateScorer:r}){const[s,a]=v.useState(new Set),i=e.status,{data:l,isLoading:c,setEndOfListElement:u,isFetchingNextPage:d,hasNextPage:f}=LG({datasetId:e.datasetId,experimentId:e.id,experimentStatus:i}),{data:p}=Q8t(e.id,i),h=e.targetType==="agent"?e.targetId:void 0,{data:m}=K1({agentId:h}),g=m?.versions??[],{navigate:y}=yn(),b=_=>{a(C=>{const E=new Set(C);return E.has(_)?E.delete(_):E.add(_),E})},x=()=>{if(!l)return;const _=l.filter(C=>!!C.error).map(C=>C.id);a(new Set(_))},S=()=>a(new Set),k=l?.filter(_=>s.has(_.id))||[];return o.jsxs("div",{className:"flex h-full flex-col",children:[o.jsxs("div",{className:"border-border1 flex items-center gap-2 border-b px-4 py-3",children:[o.jsxs("button",{type:"button",onClick:t,className:"text-neutral3 hover:text-neutral5 flex cursor-pointer items-center gap-1 transition-colors",children:[o.jsx(qe,{size:"sm",children:o.jsx(Ac,{})}),o.jsx(ye,{variant:"ui-xs",children:"Back"})]}),o.jsx("div",{className:"flex-1"}),o.jsx(Nes,{status:e.status}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral2",children:[e.datasetName,e.datasetVersion!=null&&` ${NN("Dataset",e.datasetVersion)}`,e.agentVersion&&(()=>{const _=g.find(E=>E.id===e.agentVersion),C=NN("Agent",_?_.versionNumber:e.agentVersion);return o.jsxs(o.Fragment,{children:[" · ",o.jsx("button",{type:"button",className:"hover:text-neutral5 cursor-pointer underline transition-colors",onClick:()=>y(`/agents/${h}/editor?version=${encodeURIComponent(e.agentVersion)}`),children:C})]})})()," · ",e.startedAt?Tes(e.startedAt):"-"]})]}),s.size>0&&o.jsxs("div",{className:"bg-surface3 border-border1 flex items-center gap-2 border-b px-4 py-2",children:[o.jsxs(ye,{variant:"ui-xs",className:"text-neutral5 font-medium",children:[s.size," selected"]}),o.jsx("div",{className:"flex-1"}),r&&o.jsxs(ce,{variant:"outline",size:"sm",onClick:()=>{r(k.map(_=>({input:_.input,output:_.output})))},children:[o.jsx(qe,{size:"sm",children:o.jsx(Pqt,{})}),"Create Scorer"]}),n&&o.jsxs(ce,{variant:"outline",size:"sm",onClick:()=>{n(k.map(_=>{const C=p?.[_.itemId],E={};if(C)for(const j of C)typeof j.score=="number"&&(E[j.scorerId||"unknown"]=j.score);return{id:_.id,input:_.input,output:_.output,error:_.error,itemId:_.itemId,datasetId:e.datasetId,scores:E,experimentId:e.id,traceId:_.traceId??void 0}}))},children:[o.jsx(qe,{size:"sm",children:o.jsx(UV,{})}),"Send to Review"]}),o.jsx(ce,{variant:"ghost",size:"sm",onClick:S,children:"Clear"})]}),l&&l.length>0&&s.size===0&&o.jsx("div",{className:"border-border1 flex items-center gap-2 border-b px-4 py-2",children:o.jsx(ce,{variant:"ghost",size:"sm",onClick:x,children:"Select all failures"})}),o.jsx(Br,{className:"min-h-0 flex-1",children:c?o.jsx("div",{className:"flex items-center justify-center py-8",children:o.jsx(Xt,{className:"h-5 w-5"})}):!l||l.length===0?o.jsx("div",{className:"px-4 py-8 text-center",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral2",children:"No results yet"})}):o.jsxs("div",{children:[l.map(_=>{const C=!!_.error,E=p?.[_.itemId]??[],j=s.has(_.id);return o.jsxs("div",{className:X("border-b border-border1 px-4 py-3 space-y-2",j&&"bg-surface3/50"),children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(zo,{checked:j,onCheckedChange:()=>b(_.id)}),o.jsx(un,{variant:C?"error":"success",children:C?"Error":"Success"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral2 font-mono",children:_.itemId.slice(0,8)}),E.length>0&&o.jsxs("div",{className:"ml-auto flex flex-wrap items-center gap-2",children:[E.filter(N=>N.entityType!=="TRAJECTORY").map(N=>o.jsxs(un,{variant:"default",children:[N.scorerId,": ",N.score.toFixed(3)]},N.scorerId)),E.filter(N=>N.entityType==="TRAJECTORY").map(N=>o.jsxs(Js,{size:"small",color:"purple",children:[N.scorerId,": ",N.score.toFixed(3)]},N.scorerId))]})]}),E.some(N=>N.entityType==="TRAJECTORY")&&o.jsxs(Tf,{children:[o.jsxs($d,{className:"flex items-center gap-1.5 text-xs font-medium text-purple-400 hover:text-purple-300",children:[o.jsx(pa,{className:"h-3 w-3 shrink-0"}),"Trajectory Score Details"]}),o.jsx(Md,{children:o.jsx("div",{className:"mt-1 space-y-2",children:E.filter(N=>N.entityType==="TRAJECTORY").map(N=>o.jsxs("div",{className:"bg-surface1 space-y-1 rounded px-3 py-2",children:[o.jsx(ye,{variant:"ui-xs",className:"font-medium text-purple-400",children:N.scorerId}),N.reason&&o.jsx("p",{className:"text-neutral4 text-xs",children:N.reason}),N.preprocessStepResult&&o.jsx("pre",{className:"text-neutral3 max-h-48 overflow-x-auto overflow-y-auto text-xs break-words whitespace-pre-wrap",children:JSON.stringify(N.preprocessStepResult,null,2)})]},N.scorerId))})})]}),_.traceId&&E.some(N=>N.entityType==="TRAJECTORY")&&o.jsx(Res,{traceId:_.traceId}),o.jsxs(Tf,{children:[o.jsxs($d,{className:"text-neutral3 hover:text-neutral5 flex items-center gap-1.5 text-xs font-medium",children:[o.jsx(pa,{className:"h-3 w-3 shrink-0"}),"Input"]}),o.jsx(Md,{children:o.jsx("pre",{className:"text-neutral4 bg-surface1 mt-1 max-h-32 overflow-x-auto overflow-y-auto rounded px-3 py-2 text-xs wrap-break-word whitespace-pre-wrap",children:abe(_.input)})})]}),C?o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{variant:"ui-xs",className:"font-medium text-red-400",children:"Error"}),o.jsx("pre",{className:"bg-surface1 max-h-32 overflow-x-auto overflow-y-auto rounded px-3 py-2 text-xs wrap-break-word whitespace-pre-wrap text-red-300",children:abe(_.error)})]}),_.traceId&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Trace"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral2 truncate font-mono",children:_.traceId}),o.jsx(Pa,{content:_.traceId,tooltip:"Copy trace ID",size:"sm"}),o.jsxs("button",{type:"button",onClick:()=>y(`/traces/${_.traceId}`),className:"text-accent1 hover:text-accent2 flex cursor-pointer items-center gap-1 text-xs transition-colors",children:[o.jsx(Sa,{className:"h-3 w-3"}),"View Trace"]})]})]}):o.jsx(Pes,{output:_.output,traceId:_.traceId,onViewTrace:N=>y(`/traces/${N}`)})]},_.id)}),o.jsxs("div",{ref:u,className:"h-1",children:[d&&o.jsx("div",{className:"flex items-center justify-center py-4",children:o.jsx(Xt,{className:"h-4 w-4"})}),!f&&l.length>0&&o.jsx("div",{className:"py-2 text-center",children:o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"All results loaded"})})]})]})})]})}function Mes({children:e,className:t}){return o.jsx("div",{className:X("grid content-start gap-8 overflow-y-auto",t),children:e})}function Des({children:e,className:t,withLeftSeparator:n,withRightSeparator:r}){return o.jsxs("div",{className:"flex w-full overflow-y-auto",children:[n&&o.jsx(NKe,{}),o.jsx("div",{className:X("grid w-full content-start gap-8 overflow-y-auto",t),children:e}),r&&o.jsx(NKe,{})]})}function NKe(){return o.jsx("div",{className:X("mx-[1.5vw] w-[3px] shrink-0 bg-surface5")})}function Les({children:e,className:t}){return o.jsx("div",{className:X("flex w-full flex-wrap items-center justify-between gap-4 gap-x-6",t),children:e})}const Yr=Object.assign(Des,{Content:Mes,Toolbar:Les});function ly({children:e,className:t}){return o.jsx("div",{className:X("grid size-full grid-cols-1 overflow-y-auto",t),children:e})}const PNe=(e,t=[])=>{const n=We(),{data:r}=Bg(),s=r?.datasets??[];return yt({queryKey:["agent-experiments",e,t,s.map(a=>a.id)],queryFn:async()=>{if(s.length===0)return[];const a=new Set(t),i=await Promise.all(s.map(async c=>{try{return(await n.listDatasetExperiments(c.id)).experiments.filter(d=>d.targetType==="agent"&&d.targetId===e||d.targetType==="scorer"&&a.has(d.targetId)).map(d=>({...d,datasetId:c.id,datasetName:c.name}))}catch{return[]}})),l=c=>c?c instanceof Date?c.getTime():new Date(c).getTime():0;return i.flat().sort((c,u)=>l(u.startedAt)-l(c.startedAt))},enabled:!!e&&s.length>0,refetchInterval:a=>{const i=a.state.data;return i&&i.some(c=>c.status==="running"||c.status==="pending")?3e3:!1}})},PV=(e,t)=>{const n=We();return yt({queryKey:["dataset-item",e,t],queryFn:()=>n.getDatasetItem(e,t),enabled:!!e&&!!t,retry:!1})},IKe=10,j1=(e,t,n)=>{const r=We(),{inView:s,setRef:a}=W_(),i=M1({queryKey:["dataset-items",e,t,n],queryFn:async({pageParam:u})=>await r.listDatasetItems(e,{page:u,perPage:IKe,search:t||void 0,version:n||void 0}),initialPageParam:0,getNextPageParam:(u,d,f)=>{if(!u?.items?.length)return;const p=(f+1)*IKe,h=u?.pagination?.total??0;if(!(p>=h))return f+1},enabled:!!e,retry:!1}),l=i.data?.pages.flatMap(u=>u?.items??[])??[],c=i.data?.pages[0]?.pagination?.total;return v.useEffect(()=>{s&&i.hasNextPage&&!i.isFetchingNextPage&&i.fetchNextPage()},[s,i.hasNextPage,i.isFetchingNextPage]),{...i,data:l,total:c,setEndOfListElement:a}},Fes=10,$Ne=e=>{const t=We();return M1({queryKey:["dataset-versions",e],queryFn:async({pageParam:n})=>t.listDatasetVersions(e,{page:n,perPage:Fes}),initialPageParam:0,getNextPageParam:(n,r,s)=>{if(n?.pagination?.hasMore)return s+1},select:n=>n.pages.flatMap(r=>r?.versions??[]).map((r,s)=>({id:r.id,datasetId:r.datasetId,version:r.version,createdAt:r.createdAt,isCurrent:s===0})),enabled:!!e})};function zes(e){const t=new Date(e);return t.toLocaleDateString("en-US",{month:"short",day:"numeric"})+", "+t.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"})}function Bes(e,t=120){if(e==null)return"-";const n=typeof e=="string"?e:JSON.stringify(e);return!n||n.length<=t?n||"-":n.slice(0,t)+"…"}function Ues(e){const t=e,n=Array.isArray(t?.steps)?t.steps.length:0;return n>0?`${n} expected steps`:"trajectory"}const AKe=["blue","green","purple","orange","cyan","pink","red","yellow"];function Ves(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return AKe[Math.abs(t)%AKe.length]}function qes({agentId:e,datasetId:t,datasetName:n,datasetDescription:r,datasetTags:s=[],datasetTargetType:a,datasetTargetIds:i,activeScorers:l=[],datasetScorerIds:c=[],onGenerate:u,onViewExperiment:d}){const[f,p]=v.useState(!1),h=v.useRef(!1),[m,g]=v.useState(null),[y,b]=v.useState(!1),[x,S]=v.useState(!1),[k,_]=v.useState(!1),[C,E]=v.useState(!1),[j,N]=v.useState(""),[I,A]=v.useState(""),[R,L]=v.useState(""),{data:D}=ih(),{updateDataset:B}=Ni(),H=v.useMemo(()=>new Set(c??[]),[c]),F=v.useMemo(()=>D?Object.entries(D).filter(([le])=>H.has(le)):[],[D,H]),z=v.useMemo(()=>D?Object.entries(D).filter(([le])=>!H.has(le)):[],[D,H]),q=v.useCallback(async le=>{const he=[...c??[],le];try{await B.mutateAsync({datasetId:t,scorerIds:he})}catch(be){throw Le.error("Failed to attach scorer"),be}},[t,c,B]),M=v.useCallback(async le=>{const he=(c??[]).filter(be=>be!==le);try{await B.mutateAsync({datasetId:t,scorerIds:he})}catch{Le.error("Failed to detach scorer")}},[t,c,B]),{data:G=[],setEndOfListElement:V,isFetchingNextPage:$}=j1(t),{data:U,refetch:Z}=kD(t),K=U?.experiments??[],ee=$Ne(t).data??[],J=!a||a==="agent",de=K1({agentId:e,enabled:J}).data?.versions??[];v.useEffect(()=>{A("")},[t]),v.useEffect(()=>{L("")},[e]);const Y=zl(),ne=Ur(),{triggerExperiment:fe}=Ni(),oe=v.useCallback(async()=>{if(!h.current){h.current=!0,p(!0);try{const le=Object.keys(Y).length>0,he=a==="scorer"||a==="workflow"?a:"agent",be=Array.isArray(i)?i:typeof i=="string"?(()=>{try{return JSON.parse(i)}catch{return[]}})():[],xe=he!=="agent"&&be[0]?be[0]:e;await fe.mutateAsync({datasetId:t,targetType:he,targetId:xe,...l.length>0?{scorerIds:l}:{},...le?{requestContext:Y}:{},...I?{version:Number(I)}:{},...R?{agentVersion:R}:{}}),ne.invalidateQueries({queryKey:["agent-experiments",e]}),Z();const je=setInterval(()=>Z(),3e3);setTimeout(()=>clearInterval(je),3e4),Le.success("Experiment started")}catch(le){Le.error(`Failed to start experiment: ${le instanceof Error?le.message:"Unknown error"}`)}finally{h.current=!1,p(!1)}}},[t,l,e,a,i,fe,Y,ne,Z,I,R]);return o.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[o.jsxs("div",{className:"border-border1 space-y-3 border-b p-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral5 block truncate font-medium",children:n}),r&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-0.5 block truncate",children:r}),s.length>0&&o.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:s.map(le=>o.jsx(Js,{color:Ves(le),size:"small",children:le},le))})]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[o.jsxs(ce,{variant:"ghost",size:"sm",onClick:u,children:[o.jsx(qe,{size:"sm",children:o.jsx(Eg,{})}),"Generate"]}),o.jsx(ce,{variant:"primary",size:"sm",onClick:oe,disabled:G.length===0||f,children:f?o.jsxs(o.Fragment,{children:[o.jsx(Xt,{className:"h-3 w-3"})," Running..."]}):o.jsxs(o.Fragment,{children:[o.jsx(qe,{size:"sm",children:o.jsx(Of,{})})," ","Run Experiment"]})})]})]}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mb-1 block",children:"Dataset version"}),o.jsx(ac,{options:[{label:"Latest",value:""},...ee.map(le=>({label:`v${le.version}`,value:String(le.version),description:le.isCurrent?"Current":void 0}))],value:I,onValueChange:A,placeholder:"Latest",size:"sm"})]}),J&&o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mb-1 block",children:"Agent version"}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(ac,{options:[{label:"Current",value:""},...de.map(le=>({label:`v${le.versionNumber}`,value:le.id,description:le.changeMessage??void 0}))],value:R,onValueChange:L,placeholder:"Current",size:"sm"}),(R||de[0]?.id)&&o.jsx(Pa,{content:R||de[0]?.id,tooltip:"Copy version ID",size:"sm"})]})]})]})]}),o.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:o.jsxs(Br,{className:"min-h-0 flex-1",children:[o.jsxs("div",{className:"border-border1 border-b",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("button",{type:"button",onClick:()=>_(le=>!le),className:"hover:bg-surface3 flex flex-1 items-center gap-1 px-4 py-2 transition-colors",children:[o.jsx(qe,{size:"sm",className:"text-neutral3",children:k?o.jsx(pa,{}):o.jsx(Na,{})}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3 font-semibold tracking-wider uppercase",children:["Scorers (",F.length,")"]})]}),z.length>0&&o.jsx("div",{className:"pr-2",children:o.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>E(!0),children:"Attach"})})]}),!k&&(F.length===0?o.jsxs("div",{className:"px-4 py-4 text-center",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:"No scorers attached to this dataset."}),z.length>0&&o.jsx("div",{className:"mt-2",children:o.jsx(ce,{variant:"outline",size:"sm",onClick:()=>E(!0),children:"Attach a scorer"})})]}):o.jsx("div",{className:"divide-border1 divide-y",children:F.map(([le,he])=>{const be=he.scorer?.name||le;return o.jsxs("div",{className:"hover:bg-surface3 group flex items-center justify-between px-4 py-1.5 transition-colors",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral5 truncate",children:be}),o.jsx("button",{type:"button",onClick:()=>M(le),"aria-label":`Detach "${be}" from this dataset`,className:"text-neutral3 p-0.5 opacity-0 transition-opacity group-hover:opacity-100 hover:text-red-500 focus-visible:opacity-100",title:"Detach scorer",children:o.jsx(qe,{size:"sm",children:o.jsx(bs,{})})})]},le)})}))]}),o.jsxs("div",{className:"border-border1 border-b",children:[o.jsxs("button",{type:"button",onClick:()=>b(le=>!le),className:"hover:bg-surface3 flex w-full items-center gap-1 px-4 py-2 transition-colors",children:[o.jsx(qe,{size:"sm",className:"text-neutral3",children:y?o.jsx(pa,{}):o.jsx(Na,{})}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3 font-semibold tracking-wider uppercase",children:["Items (",G.length,")"]})]}),!y&&(G.length===0?o.jsx("div",{className:"px-4 py-6 text-center",children:o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:"No items yet. Use Generate to create test data."})}):o.jsxs("div",{className:"divide-border1 divide-y",children:[G.map(le=>{const he=m===le.id;return o.jsxs("div",{children:[o.jsxs("button",{type:"button",onClick:()=>g(he?null:le.id),className:"hover:bg-surface3 flex w-full items-start gap-2 px-4 py-2 text-left transition-colors",children:[o.jsx(qe,{size:"sm",className:"text-neutral3 mt-0.5 shrink-0",children:he?o.jsx(Na,{}):o.jsx(pa,{})}),o.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral5 block flex-1 truncate",children:Bes(le.input)}),le.expectedTrajectory!=null&&o.jsx(Js,{size:"small",color:"purple",children:Ues(le.expectedTrajectory)})]})]}),he&&o.jsx(Hes,{datasetId:t,item:le})]},le.id)}),o.jsx("div",{ref:V}),$&&o.jsx("div",{className:"flex items-center justify-center py-2",children:o.jsx(Xt,{className:"h-3 w-3"})})]}))]}),o.jsxs("div",{children:[o.jsxs("button",{type:"button",onClick:()=>S(le=>!le),className:"hover:bg-surface3 flex w-full items-center gap-1 px-4 py-2 transition-colors",children:[o.jsx(qe,{size:"sm",className:"text-neutral3",children:x?o.jsx(pa,{}):o.jsx(Na,{})}),o.jsx(qe,{size:"sm",className:"text-neutral3",children:o.jsx(uT,{})}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3 font-semibold tracking-wider uppercase",children:["Past Runs (",K.length,")"]})]}),!x&&(K.length===0?o.jsx("div",{className:"px-4 py-4 text-center",children:o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:"No experiment runs yet"})}):o.jsx("div",{className:"divide-border1 divide-y",children:K.map(le=>o.jsxs("button",{type:"button",onClick:()=>d(le.id),className:"hover:bg-surface3 flex w-full items-center gap-2 px-4 py-2 text-left transition-colors",children:[o.jsx(Wes,{status:le.status}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral5 block",children:le.startedAt?zes(le.startedAt):"Unknown"}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3",children:[le.succeededCount,"/",le.totalItems," passed",le.datasetVersion!=null&&` · ${NN("Dataset",le.datasetVersion)}`,le.agentVersion&&(()=>{const he=de.find(be=>be.id===le.agentVersion);return` · ${NN("Agent",he?he.versionNumber:le.agentVersion)}`})()]})]}),o.jsx(qe,{size:"sm",className:"text-neutral3",children:o.jsx(pa,{})})]},le.id))}))]})]})}),o.jsx(br,{open:C,onOpenChange:le=>{E(le),le||N("")},children:o.jsxs(xr,{className:"max-w-md",children:[o.jsx(wr,{children:o.jsx(gr,{children:"Attach Scorer to Dataset"})}),o.jsx($r,{className:"max-h-[50vh] overflow-y-auto",children:z.length===0?o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 py-4 text-center",children:"No scorers available to attach."}):o.jsxs("div",{className:"space-y-2",children:[o.jsx("input",{type:"text",placeholder:"Search scorers...",value:j,onChange:le=>N(le.target.value),className:"border-border1 bg-surface2 text-text1 placeholder:text-neutral3 focus:ring-accent1 w-full rounded border px-3 py-1.5 text-sm focus:ring-1 focus:outline-none"}),z.filter(([le,he])=>j?(he.scorer?.name||le).toLowerCase().includes(j.toLowerCase()):!0).map(([le,he])=>{const be=he.scorer?.name||le;return o.jsx("button",{type:"button",className:"hover:bg-surface4 w-full rounded px-3 py-2 text-left transition-colors",onClick:async()=>{try{await q(le),Le.success(`Attached "${be}" to this dataset`),E(!1)}catch{}},children:o.jsx(ye,{variant:"ui-sm",className:"font-medium",children:be})},le)})]})})]})})]})}function CE(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e,null,2)}function Hes({datasetId:e,item:t}){const[n,r]=v.useState(!1),[s,a]=v.useState(!1),[i,l]=v.useState(""),[c,u]=v.useState(""),[d,f]=v.useState(""),{updateItem:p,deleteItem:h}=Ni(),m=v.useCallback(()=>{l(CE(t.input)),u(CE(t.groundTruth)),f(CE(t.expectedTrajectory)),r(!0)},[t.input,t.groundTruth,t.expectedTrajectory]),g=v.useCallback(()=>{r(!1)},[]),y=v.useCallback(async()=>{try{await h.mutateAsync({datasetId:e,itemId:t.id}),Le.success("Item deleted")}catch(x){Le.error(`Failed to delete: ${x instanceof Error?x.message:"Unknown error"}`)}},[h,e,t.id]),b=v.useCallback(async()=>{let x;try{x=JSON.parse(i)}catch{x=i}let S;if(c.trim())try{S=JSON.parse(c)}catch{S=c}let k;if(d.trim())try{k=JSON.parse(d)}catch{k=d}try{await p.mutateAsync({datasetId:e,itemId:t.id,input:x,groundTruth:S,expectedTrajectory:k}),Le.success("Item updated"),r(!1)}catch(_){Le.error(`Failed to update: ${_ instanceof Error?_.message:"Unknown error"}`)}},[i,c,d,e,t.id,p]);return n?o.jsxs("div",{className:"space-y-2 px-4 pb-3 pl-10",children:[o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Input"}),o.jsx($l,{value:i,onChange:x=>l(x.target.value),className:"mt-1 font-mono text-xs",rows:4})]}),o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Ground Truth"}),o.jsx($l,{value:c,onChange:x=>u(x.target.value),className:"mt-1 font-mono text-xs",rows:3,placeholder:"Optional"})]}),o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Expected Trajectory (JSON)"}),o.jsx($l,{value:d,onChange:x=>f(x.target.value),className:"mt-1 font-mono text-xs",rows:3,placeholder:"Optional — JSON trajectory expectation"})]}),o.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[o.jsxs(ce,{variant:"primary",size:"sm",onClick:b,disabled:p.isPending,children:[p.isPending?o.jsx(Xt,{className:"h-3 w-3"}):o.jsx(qe,{size:"sm",children:o.jsx(jd,{})}),"Save"]}),o.jsxs(ce,{variant:"ghost",size:"sm",onClick:g,children:[o.jsx(qe,{size:"sm",children:o.jsx(bs,{})}),"Cancel"]})]})]}):o.jsxs("div",{className:"space-y-2 px-4 pb-3 pl-10",children:[o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Input"}),o.jsx("pre",{className:"text-neutral5 bg-surface1 mt-1 max-h-48 overflow-x-auto overflow-y-auto rounded px-2 py-1.5 text-xs wrap-break-word whitespace-pre-wrap",children:CE(t.input)})]}),t.groundTruth!==void 0&&t.groundTruth!==null&&o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Ground Truth"}),o.jsx("pre",{className:"text-neutral5 bg-surface1 mt-1 max-h-48 overflow-x-auto overflow-y-auto rounded px-2 py-1.5 text-xs wrap-break-word whitespace-pre-wrap",children:CE(t.groundTruth)})]}),t.expectedTrajectory!=null&&o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Expected Trajectory"}),o.jsx("pre",{className:"text-neutral5 bg-surface1 mt-1 max-h-48 overflow-x-auto overflow-y-auto rounded px-2 py-1.5 text-xs break-words whitespace-pre-wrap",children:CE(t.expectedTrajectory)})]}),o.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[o.jsxs(ce,{variant:"ghost",size:"sm",onClick:m,children:[o.jsx(qe,{size:"sm",children:o.jsx(rm,{})}),"Edit"]}),s?o.jsxs(o.Fragment,{children:[o.jsx(ye,{variant:"ui-xs",className:"text-negative1 font-medium",children:"Delete this item?"}),o.jsx(ce,{variant:"ghost",size:"sm",onClick:y,disabled:h.isPending,className:"text-negative1 hover:text-negative1",children:h.isPending?o.jsx(Xt,{className:"h-3 w-3"}):"Yes"}),o.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>a(!1),children:"No"})]}):o.jsxs(ce,{variant:"ghost",size:"sm",onClick:()=>a(!0),className:"text-neutral2 hover:text-negative1",children:[o.jsx(qe,{size:"sm",children:o.jsx(uu,{})}),"Delete"]}),t.source!=null&&o.jsxs(ye,{variant:"ui-xs",className:"text-neutral2",children:["Source:"," ",typeof t.source=="object"&&t.source!==null&&"type"in t.source?String(t.source.type):"manual"]})]})]})}function Wes({status:e}){const t=e==="completed"?"bg-positive1":e==="running"?"bg-warning1":e==="failed"?"bg-negative1":"bg-neutral3";return o.jsx("div",{className:X("w-2 h-2 rounded-full shrink-0",t)})}function Zes({scorerId:e,scorerData:t,isAttached:n,onToggleAttach:r,onEdit:s,linkedDatasets:a,onViewDataset:i}){if(!t)return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"Scorer not found"})});const l=t.scorer?.name||e,c=t.scorer?.description,u=t.source==="code",d=t.scorer?.config?.type==="trajectory";return o.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[o.jsxs("div",{className:"border-border1 space-y-3 border-b p-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral5 truncate font-medium",children:l}),d&&o.jsx(Js,{size:"small",color:"purple",children:"trajectory"}),u&&o.jsx("span",{title:"Defined in code — cannot be edited in the UI",children:o.jsx(un,{variant:"default",children:"Code"})})]}),c&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-1 block",children:c})]}),o.jsx("div",{className:"flex shrink-0 items-center gap-3",children:!u&&o.jsxs(ce,{variant:"ghost",size:"sm",onClick:s,children:[o.jsx(qe,{size:"sm",children:o.jsx(rm,{})}),"Edit"]})})]}),o.jsxs("div",{className:"bg-surface3 flex items-center justify-between rounded-md px-3 py-2",children:[o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral5 block",children:"Run in experiments"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-0.5 block",children:"When enabled, this scorer grades results for this agent"})]}),o.jsx(ic,{checked:n,onCheckedChange:r})]})]}),o.jsxs("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mb-2 block font-medium tracking-wider uppercase",children:"Details"}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(wz,{label:"ID",value:e}),o.jsx(wz,{label:"Type",value:d?"Trajectory":"Agent"}),o.jsx(wz,{label:"Source",value:u?"Code":"Stored"}),t.agentIds&&t.agentIds.length>0&&o.jsx(wz,{label:"Used by agents",value:t.agentNames?.join(", ")||t.agentIds.join(", ")})]})]}),a&&a.length>0&&o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mb-2 block font-medium tracking-wider uppercase",children:"Datasets"}),o.jsx("div",{className:"space-y-1",children:a.map(f=>i?o.jsx("button",{onClick:()=>i(f.id),className:"bg-surface3 hover:bg-surface4 w-full cursor-pointer rounded-md px-3 py-2 text-left transition-colors",children:o.jsx(ye,{variant:"ui-xs",className:"text-neutral5",children:f.name})},f.id):o.jsx("div",{className:"bg-surface3 rounded-md px-3 py-2",children:o.jsx(ye,{variant:"ui-xs",className:"text-neutral5",children:f.name})},f.id))})]}),u&&o.jsx("div",{className:"bg-surface3 rounded-md p-3",children:o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:"This scorer is defined in code and cannot be edited in the UI. You can toggle whether it runs in experiments for this agent."})})]})]})}function wz({label:e,value:t}){return o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 w-24 shrink-0",children:e}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral5 break-all",children:t})]})}function RKe({onBack:e,onSaved:t,initialItems:n,prefillTestItems:r,editScorerId:s,editScorerData:a}){const i=!!s,l=We(),[c,u]=v.useState(""),[d,f]=v.useState(""),[p,h]=v.useState(0),[m,g]=v.useState(1),[y,b]=v.useState(""),[x,S]=v.useState(!1),[k,_]=v.useState(()=>n?n.map(de=>({input:de.input,output:de.error||de.output,expectedDirection:de.error?"low":"high",label:de.itemId.slice(0,8)})):r?r.map((de,Y)=>({input:de.input,output:de.output,expectedDirection:de.expectedDirection==="high"?"high":"low",label:`failure-${Y+1}`})):[]),[C,E]=v.useState(!1),[j,N]=v.useState(s||null),[I,A]=v.useState(null),[R,L]=v.useState(null),[D,B]=v.useState(!1);v.useEffect(()=>{s&&(S(!0),l.getStoredScorer(s).details(void 0,{status:"draft"}).then(async de=>{u(de.name||s),f(de.instructions||""),h(de.scoreRange?.min??0),g(de.scoreRange?.max??1),de.model&&b(`${de.model.provider}/${de.model.name}`);let Y=null;try{const{datasets:ne}=await l.listDatasets({perPage:200}),fe=ne.find(oe=>oe.targetType!=="scorer"?!1:(Array.isArray(oe.targetIds)?oe.targetIds:typeof oe.targetIds=="string"?(()=>{try{return JSON.parse(oe.targetIds)}catch{return[]}})():[]).includes(s));fe&&(Y=fe.id)}catch{}if(Y){A(Y);try{const{items:ne}=await l.listDatasetItems(Y,{perPage:200}),fe=ne.map(oe=>{const le=oe.input,he=oe.groundTruth,be=oe.metadata;return{input:le?.input??"",output:le?.output??"",expectedDirection:he?.expectedDirection==="low"?"low":"high",label:be?.label||void 0}});_(fe)}catch{}}}).catch(()=>{const Y=a?.scorer?.config,ne=Y?.judge;u(Y?.name||a?.name||s),f(ne?.instructions||Y?.instructions||""),ne?.model&&b(ne.model)}).finally(()=>S(!1)))},[s]);const{provider:H,model:F}=EEe(),{createStoredScorer:z,updateStoredScorer:q}=kNe(s||j||void 0),{form:M}=Ho(),{createDataset:G,batchInsertItems:V,batchDeleteItems:$,triggerExperiment:U}=Ni(),{data:Z=[]}=LG({datasetId:I??"",experimentId:R??"",experimentStatus:D?"running":"completed"}),K=()=>{_(de=>[...de,{input:"",output:"",expectedDirection:"high"}])},te=de=>{_(Y=>Y.filter((ne,fe)=>fe!==de))},ee=(de,Y,ne)=>{_(fe=>fe.map((oe,le)=>le===de?{...oe,[Y]:ne}:oe))},J=v.useCallback(async()=>{if(!c.trim()){Le.error("Please enter a scorer name");return}if(!d.trim()){Le.error("Please enter scorer instructions");return}let de=H,Y=F;if(y){const fe=y.split("/");fe.length>=2&&(de=fe[0],Y=fe.slice(1).join("/"))}if(!de||!Y){Le.error("Please select a model");return}const ne=s||j;E(!0);try{if(ne){await q.mutateAsync({instructions:d.trim(),model:{provider:de,name:Y},scoreRange:{min:p,max:m}});let fe=I;if(!fe&&k.length>0&&(fe=(await G.mutateAsync({name:`${c.trim()} — Test Dataset`,description:`Test dataset for scorer "${c.trim()}". Items with known-good and known-bad examples to verify scoring accuracy.`,targetType:"scorer",targetIds:[ne]})).id,A(fe)),fe){try{const{items:oe}=await l.listDatasetItems(fe,{perPage:200});oe.length>0&&await $.mutateAsync({datasetId:fe,itemIds:oe.map(le=>le.id)})}catch{}k.length>0&&await V.mutateAsync({datasetId:fe,items:k.map(oe=>({input:{input:oe.input,output:oe.output},groundTruth:{expectedDirection:oe.expectedDirection},metadata:{label:oe.label},source:{type:"llm",referenceId:"scorer-editor"}}))})}t?.(ne),Le.success("Scorer updated")}else{const oe=(await z.mutateAsync({name:c.trim(),type:"llm-judge",model:{provider:de,name:Y},instructions:d.trim(),scoreRange:{min:p,max:m}}))?.id;if(oe){if(N(oe),k.length>0){const he=await G.mutateAsync({name:`${c.trim()} — Test Dataset`,description:`Test dataset for scorer "${c.trim()}". Items with known-good and known-bad examples to verify scoring accuracy.`,targetType:"scorer",targetIds:[oe]});A(he.id),await V.mutateAsync({datasetId:he.id,items:k.map(be=>({input:{input:be.input,output:be.output},groundTruth:{expectedDirection:be.expectedDirection},metadata:{label:be.label},source:{type:"llm",referenceId:"scorer-editor"}}))})}const le=M.getValues("scorers")||{};M.setValue("scorers",{...le,[oe]:{sampling:void 0}},{shouldDirty:!0}),t?.(oe)}Le.success(`Scorer saved${k.length>0?" with test dataset":""}. ${k.length>0?'Click "Run Test" to verify scoring.':""}`)}}catch(fe){Le.error(`Failed to save scorer: ${fe instanceof Error?fe.message:"Unknown error"}`)}finally{E(!1)}},[c,d,H,F,y,p,m,k,I,s,j,z,q,G,V,$,l,M,t]),ae=v.useCallback(async()=>{if(!j){Le.error("Save the scorer first before testing");return}if(!I){Le.error("No test dataset — add items and save first");return}B(!0),L(null);try{const Y=(await U.mutateAsync({datasetId:I,targetType:"scorer",targetId:j}))?.experimentId;Y&&(L(Y),Le.success("Scorer test started — results will appear below"))}catch(de){Le.error(`Failed to run test: ${de instanceof Error?de.message:"Unknown error"}`)}finally{B(!1)}},[j,I,U]);return o.jsxs("div",{className:"flex h-full flex-col",children:[o.jsxs("div",{className:"border-border1 flex items-center gap-2 border-b px-4 py-3",children:[o.jsxs(ce,{variant:"ghost",size:"sm",onClick:e,children:[o.jsx(qe,{children:o.jsx(Ac,{})}),"Back"]}),o.jsx(ye,{as:"h3",variant:"header-sm",className:"ml-2",children:i||j?"Edit Scorer":"New Scorer"}),(i||j)&&o.jsx(un,{variant:"success",className:"ml-2",children:"Saved"})]}),o.jsx(Br,{className:"flex-1",children:x?o.jsxs("div",{className:"flex items-center justify-center p-8",children:[o.jsx(Xt,{className:"mr-2"})," Loading scorer..."]}):o.jsxs("div",{className:"space-y-6 p-4",children:[o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Name"}),o.jsx(Cn,{placeholder:"e.g. Relevance Scorer",value:c,onChange:de=>u(de.target.value),disabled:i||!!j})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Model"}),o.jsx(Cn,{placeholder:"e.g. openai/gpt-4o-mini",value:y||(H&&F?`${H}/${F}`:""),onChange:de=>b(de.target.value)}),o.jsx(ye,{variant:"ui-sm",className:"text-icon3",children:"Format: provider/model (e.g. openai/gpt-4o-mini)"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Instructions"}),o.jsx($l,{placeholder:"Describe what this scorer should evaluate. Be specific about what constitutes a good vs bad response...",value:d,onChange:de=>f(de.target.value),rows:6})]}),o.jsxs("div",{className:"flex gap-4",children:[o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsx(Dt,{children:"Min Score"}),o.jsx(Cn,{type:"number",min:-1e3,max:1e3,step:"any",value:p,onChange:de=>h(Number(de.target.value))})]}),o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsx(Dt,{children:"Max Score"}),o.jsx(Cn,{type:"number",min:-1e3,max:1e3,step:"any",value:m,onChange:de=>g(Number(de.target.value))})]})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-md",className:"font-medium",children:"Test Items"}),o.jsx(ye,{variant:"ui-sm",className:"text-icon3 mt-0.5",children:"Add known-good and known-bad examples to verify your scorer"}),I&&o.jsxs(ye,{variant:"ui-xs",className:"text-icon3 mt-1",children:["Linked dataset · ",k.length," item",k.length!==1?"s":""]})]}),o.jsxs(ce,{variant:"outline",size:"sm",onClick:K,children:[o.jsx(qe,{children:o.jsx(Zr,{})}),"Add Item"]})]}),k.length===0&&o.jsx("div",{className:"border-border1 rounded-lg border border-dashed p-6 text-center",children:o.jsx(ye,{variant:"ui-sm",className:"text-icon3",children:"No test items yet. Add items with expected scoring direction to verify your scorer works correctly."})}),k.map((de,Y)=>{const ne=Z[Y],fe=ne?.output?ne.output?.score:null,oe=ne?.output?ne.output?.reason:null,le=ne?.error,he=fe!=null?de.expectedDirection==="high"?fe>=(m-p)/2+p:fe<(m-p)/2+p:null;return o.jsxs("div",{className:X("border border-border1 rounded-lg p-3 space-y-3",he===!0&&"border-success/50 bg-success/5",he===!1&&"border-error/50 bg-error/5"),children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(ye,{variant:"ui-sm",className:"font-medium",children:["Item ",Y+1]}),de.label&&o.jsx(un,{variant:"default",children:de.label}),o.jsxs("button",{className:X("px-2 py-0.5 rounded text-xs font-medium transition-colors",de.expectedDirection==="high"?"bg-success/20 text-success":"bg-error/20 text-error"),onClick:()=>ee(Y,"expectedDirection",de.expectedDirection==="high"?"low":"high"),children:["Should score ",de.expectedDirection]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[he!==null&&o.jsx(qe,{className:he?"text-success":"text-error",children:he?o.jsx(jbe,{}):o.jsx(M2,{})}),o.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>te(Y),children:o.jsx(qe,{children:o.jsx(uu,{})})})]})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-icon3 font-medium",children:"Input"}),o.jsx($l,{placeholder:"The user's question/input...",value:typeof de.input=="string"?de.input:JSON.stringify(de.input,null,2),onChange:be=>ee(Y,"input",be.target.value),rows:3,className:"text-sm"})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-icon3 font-medium",children:"Output (agent response)"}),o.jsx($l,{placeholder:"The agent's response...",value:typeof de.output=="string"?de.output:JSON.stringify(de.output,null,2),onChange:be=>ee(Y,"output",be.target.value),rows:3,className:"text-sm"})]})]}),(fe!==null||le)&&o.jsx("div",{className:"border-border1 flex items-center gap-3 border-t pt-2",children:le?o.jsxs("div",{className:"text-error flex items-center gap-1.5",children:[o.jsx(qe,{size:"sm",children:o.jsx(cT,{})}),o.jsxs(ye,{variant:"ui-xs",children:["Error: ",String(le)]})]}):o.jsxs(o.Fragment,{children:[o.jsxs(ye,{variant:"ui-sm",className:"font-mono font-medium",children:["Score: ",fe?.toFixed(3)]}),oe&&o.jsx(ye,{variant:"ui-xs",className:"text-icon3 flex-1 truncate",children:oe})]})})]},Y)})]}),Z.length>0&&o.jsxs("div",{className:"border-border1 rounded-lg border p-3",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(ye,{variant:"ui-sm",className:"font-medium",children:"Test Results:"}),(()=>{let de=0,Y=0,ne=0;return Z.forEach((fe,oe)=>{const le=k[oe];if(!le)return;if(fe.error){ne++;return}const he=fe.output?.score;if(he==null)return;const be=(m-p)/2+p;(le.expectedDirection==="high"?he>=be:he<be)?de++:Y++}),o.jsxs(o.Fragment,{children:[de>0&&o.jsxs(un,{variant:"success",children:[de," correct"]}),Y>0&&o.jsxs(un,{variant:"error",children:[Y," incorrect"]}),ne>0&&o.jsxs(un,{variant:"default",children:[ne," errors"]})]})})()]}),o.jsx(ye,{variant:"ui-xs",className:"text-icon3 mt-1",children:Z.length<k.length?"Still processing...":"All items scored. Tweak instructions and re-run to improve accuracy."})]})]})}),o.jsxs("div",{className:"border-border1 flex items-center gap-2 border-t px-4 py-3",children:[i?o.jsxs(o.Fragment,{children:[o.jsxs(ce,{variant:"default",size:"sm",onClick:J,disabled:C||!d.trim(),children:[C?o.jsx(Xt,{className:"mr-1.5"}):o.jsx(qe,{children:o.jsx(jd,{})}),"Save Changes"]}),o.jsxs(ce,{variant:"default",size:"sm",onClick:ae,disabled:D||k.length===0,children:[D?o.jsx(Xt,{className:"mr-1.5"}):o.jsx(qe,{children:o.jsx(Of,{})}),"Run Test"]})]}):j?o.jsxs(o.Fragment,{children:[o.jsxs(ce,{variant:"default",size:"sm",onClick:ae,disabled:D||k.length===0,children:[D?o.jsx(Xt,{className:"mr-1.5"}):o.jsx(qe,{children:o.jsx(Of,{})}),"Run Test"]}),o.jsxs(ce,{variant:"outline",size:"sm",onClick:J,disabled:C,children:[C?o.jsx(Xt,{className:"mr-1.5"}):null,"Update & Re-save"]})]}):o.jsxs(ce,{variant:"default",size:"sm",onClick:J,disabled:C||!c.trim()||!d.trim(),children:[C?o.jsx(Xt,{className:"mr-1.5"}):o.jsx(qe,{children:o.jsx(jd,{})}),k.length>0?"Save with Test Dataset":"Save & Attach"]}),o.jsx(ce,{variant:"ghost",size:"sm",onClick:e,className:"ml-auto",children:i||j?"Done":"Cancel"})]})]})}const Ges={anyOf:[{type:"string"},{type:"array",items:{type:"object",additionalProperties:!0}}]},PKe={type:"object",properties:{role:{type:"string",enum:["user","assistant","system","tool"]},content:Ges},required:["role","content"]},Qes={$schema:"http://json-schema.org/draft-07/schema#",description:"Agent message input (MessageListInput)",anyOf:[{type:"string",description:"Simple text message"},{type:"array",items:{type:"string"},description:"Array of text messages"},{...PKe,description:"Single message object"},{type:"array",description:"Array of message objects",items:PKe}]},Yes={$schema:"http://json-schema.org/draft-07/schema#",type:"object",description:"Agent generate() output",properties:{text:{type:"string",description:"Text response"},object:{description:"Structured output (if any)"},toolCalls:{type:"array",description:"Tool calls made by the agent",items:{type:"object",additionalProperties:!0}},toolResults:{type:"array",description:"Tool execution results",items:{type:"object",additionalProperties:!0}},sources:{type:"array",description:"Sources referenced",items:{type:"object",additionalProperties:!0}},files:{type:"array",description:"Files generated",items:{type:"object",additionalProperties:!0}},usage:{type:"object",description:"Token usage",properties:{promptTokens:{type:"number"},completionTokens:{type:"number"},totalTokens:{type:"number"}}},reasoningText:{type:"string",description:"Reasoning text (if any)"}}};function Kes(){return{inputSchema:Qes,outputSchema:Yes,isLoading:!1,error:null}}const ibe={anyOf:[{type:"string"},{type:"object",description:"Structured content (format 2 with parts)"},{type:"array",description:"Content parts array",items:{type:"object"}}]},obe={type:"object",properties:{role:{type:"string",enum:["user","assistant","system","tool"]},content:ibe},required:["role","content"]},Xes={type:"object",description:"ScorerRunInputForAgent",properties:{inputMessages:{type:"array",description:"User input messages (MastraDBMessage[])",items:obe},rememberedMessages:{type:"array",description:"Messages from memory (MastraDBMessage[])",items:obe},systemMessages:{type:"array",description:"System messages (CoreMessage[])",items:{type:"object",properties:{role:{type:"string",enum:["system"]},content:ibe},required:["role","content"]}},taggedSystemMessages:{type:"object",description:"Tagged system messages (Record<string, CoreSystemMessage[]>)",additionalProperties:{type:"array",items:{type:"object",properties:{role:{type:"string",enum:["system"]},content:ibe},required:["role","content"]}}}},required:["inputMessages","rememberedMessages","systemMessages","taggedSystemMessages"]},Jes={type:"array",description:"ScorerRunOutputForAgent (MastraDBMessage[])",items:obe},ets={$schema:"http://json-schema.org/draft-07/schema#",type:"object",description:"Scorer input for agent-type scorers (scoringInputSchema)",properties:{runId:{type:"string",description:"Run ID (optional)"},input:Xes,output:Jes,additionalContext:{type:"object",description:"Additional context (optional)",additionalProperties:!0},requestContext:{type:"object",description:"Request context (optional)",additionalProperties:!0}},required:[]},tts={$schema:"http://json-schema.org/draft-07/schema#",type:"object",description:"Scorer input for custom scorers (scoringInputSchema)",properties:{runId:{type:"string",description:"Run ID (optional)"},input:{description:"Input to the entity being scored (any)"},output:{description:"Output from the entity being scored (any)"},additionalContext:{type:"object",description:"Additional context (optional)",additionalProperties:!0},requestContext:{type:"object",description:"Request context (optional)",additionalProperties:!0}},required:[]},nts={$schema:"http://json-schema.org/draft-07/schema#",description:"Scorer ground truth (any shape)"};function rts(){return{agentInputSchema:ets,customInputSchema:tts,outputSchema:nts,isLoading:!1,error:null}}function sts(e){const t=We();return yt({queryKey:["workflow-schema",e],queryFn:async()=>{if(!e)throw new Error("No workflow selected");return t.getWorkflow(e).getSchema()},enabled:!!e,staleTime:300*1e3})}function lae({label:e,schemaType:t,value:n,onChange:r,error:s,sourceSchema:a,autoPopulate:i=!1}){const l=n!=null,[c,u]=v.useState(()=>n?JSON.stringify(n,null,2):""),[d,f]=v.useState(null),p=v.useRef(!1),h=v.useRef(!1);v.useEffect(()=>{if(h.current){h.current=!1;return}n&&(u(JSON.stringify(n,null,2)),f(null))},[n]),v.useEffect(()=>{p.current=!1},[a]);const m=y=>{y?i&&a&&!p.current?(p.current=!0,r(a)):r({type:"object",properties:{}}):r(null)},g=y=>{u(y);try{const b=JSON.parse(y);typeof b=="object"&&b!==null?(f(null),h.current=!0,r(b)):f("Schema must be a JSON object")}catch{f("Invalid JSON")}};return o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ic,{checked:l,onCheckedChange:m,id:`${t}-schema-toggle`}),o.jsx("label",{htmlFor:`${t}-schema-toggle`,className:"text-sm font-medium",children:e})]}),l&&o.jsxs("div",{className:"space-y-2",children:[o.jsx(Wr,{value:c,onChange:g,showCopyButton:!1,className:X("h-48 border rounded-md",(d||s)&&"border-destructive")}),d&&o.jsx("p",{className:"text-destructive text-xs",children:d}),s&&!d&&o.jsx("p",{className:"text-destructive text-xs",children:s})]})]})}function Y8t({inputSchema:e,outputSchema:t,requestContextSchema:n,onChange:r,disabled:s=!1,defaultOpen:a=!1}){const[i,l]=v.useState(a),[c,u]=v.useState("custom"),[d,f]=v.useState(null),[p,h]=v.useState("agent"),{data:m,isLoading:g}=Hy(),y=m?Object.entries(m):[],{data:b,isLoading:x}=sts(c==="workflow"?d:null),S=Kes(),k=rts(),C=(()=>{switch(c){case"agent":return{inputSchema:S.inputSchema,outputSchema:S.outputSchema};case"workflow":return b?{inputSchema:b.inputSchema??null,outputSchema:b.outputSchema??null}:{inputSchema:null,outputSchema:null};case"scorer":return{inputSchema:p==="agent"?k.agentInputSchema:k.customInputSchema,outputSchema:k.outputSchema};default:return{inputSchema:null,outputSchema:null}}})(),E=c!=="custom",j=v.useRef(null);v.useEffect(()=>{if(c==="custom"||!C.inputSchema&&!C.outputSchema)return;const L=c==="workflow"?`workflow:${d}`:c==="scorer"?`scorer:${p}`:c,D=j.current!==null&&j.current!==L;if(j.current=L,c==="workflow"&&!b)return;const B=e!=null,H=t!=null,F=e&&e.type==="object"&&Object.keys(e.properties||{}).length===0,z=t&&t.type==="object"&&Object.keys(t.properties||{}).length===0,q=C.inputSchema&&B&&(D||F),M=C.outputSchema&&H&&(D||z);(q||M)&&r({inputSchema:q?C.inputSchema:e??null,outputSchema:M?C.outputSchema:t??null,requestContextSchema:n??null})},[c,d,b,p]);const N=L=>{r({inputSchema:L,outputSchema:t??null,requestContextSchema:n??null})},I=L=>{r({inputSchema:e??null,outputSchema:L,requestContextSchema:n??null})},A=L=>{r({inputSchema:e??null,outputSchema:t??null,requestContextSchema:L})},R=L=>{u(L),L!=="workflow"&&f(null)};return o.jsxs(Tf,{open:i,onOpenChange:l,children:[o.jsxs($d,{className:"text-neutral4 hover:text-neutral5 flex w-full items-center gap-2 py-2 text-sm font-medium",children:[o.jsx(pa,{className:"h-4 w-4"}),"Schema Configuration (Optional)"]}),o.jsxs(Md,{className:"space-y-4 pt-4",children:[o.jsx(En,{variant:"info",title:"JSON Schema Format",children:o.jsxs(En.Message,{children:["Schemas use"," ",o.jsx("a",{href:"https://json-schema.org/",target:"_blank",rel:"noopener noreferrer",className:"hover:text-accent5Lighter underline",children:"JSON Schema"})," ","for validation and type checking."]})}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-neutral4 text-sm font-medium",children:"Import From"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(oa,{value:c,onValueChange:L=>R(L),disabled:s,children:[o.jsx(ca,{size:"sm",className:"w-40",children:o.jsx(la,{})}),o.jsxs(ua,{children:[o.jsx(Ar,{value:"custom",children:"Custom"}),o.jsx(Ar,{value:"agent",children:"Agent"}),o.jsx(Ar,{value:"workflow",children:"Workflow"}),o.jsx(Ar,{value:"scorer",children:"Scorer"})]})]}),c==="workflow"&&o.jsxs(oa,{value:d??"",onValueChange:f,disabled:s,children:[o.jsx(ca,{size:"sm",className:"w-48",children:o.jsx(la,{placeholder:"Select workflow..."})}),o.jsx(ua,{children:g?o.jsx(Ar,{value:"__loading__",disabled:!0,children:"Loading..."}):y.length===0?o.jsx(Ar,{value:"__empty__",disabled:!0,children:"No workflows"}):y.map(([L,D])=>o.jsx(Ar,{value:L,children:D.name||L},L))})]}),c==="workflow"&&d&&x&&o.jsx("span",{className:"text-neutral3 text-xs",children:"Loading schema..."}),c==="scorer"&&o.jsxs(oa,{value:p,onValueChange:L=>h(L),disabled:s,children:[o.jsx(ca,{size:"sm",className:"w-32",children:o.jsx(la,{})}),o.jsxs(ua,{children:[o.jsx(Ar,{value:"agent",children:"Agent"}),o.jsx(Ar,{value:"custom",children:"Custom"})]})]})]}),c==="scorer"&&o.jsx("p",{className:"text-neutral3 text-xs",children:p==="agent"?"For calibrating agent-type scorers":"For calibrating custom scorers (input/output as any)"})]}),o.jsx(lae,{label:"Input Schema",schemaType:"input",value:e,onChange:N,sourceSchema:E?C.inputSchema:void 0,autoPopulate:E}),o.jsx(lae,{label:"Ground Truth Schema",schemaType:"output",value:t,onChange:I,sourceSchema:E?C.outputSchema:void 0,autoPopulate:E}),o.jsx(lae,{label:"Request Context Schema",schemaType:"requestContext",value:n,onChange:A,autoPopulate:!1})]})]})}const FG=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"},{value:"processor",label:"Processor"}],ats=new Set(FG.map(e=>e.value));function $V(e){return typeof e=="string"&&ats.has(e)}function lbe({open:e,onOpenChange:t,onSuccess:n,targetType:r,targetIds:s}){const[a,i]=v.useState(""),[l,c]=v.useState(""),[u,d]=v.useState(null),[f,p]=v.useState(null),[h,m]=v.useState(null),[g,y]=v.useState(!r),[b,x]=v.useState(""),{createDataset:S}=Ni(),k=!!r,_=r??(b||void 0),C=N=>{d(N.inputSchema),p(N.outputSchema),m(N.requestContextSchema)},E=async N=>{if(N.preventDefault(),!a.trim()){Le.error("Dataset name is required");return}try{const I=await S.mutateAsync({name:a.trim(),description:l.trim()||void 0,inputSchema:u,groundTruthSchema:f,requestContextSchema:h,targetType:_,targetIds:s});Le.success("Dataset created successfully"),i(""),c(""),d(null),p(null),m(null),x(""),y(!r),t(!1),n?.(I.id)}catch(I){Le.error(`Failed to create dataset: ${I instanceof Error?I.message:"Unknown error"}`)}},j=()=>{i(""),c(""),d(null),p(null),m(null),x(""),y(!r),t(!1)};return o.jsx(br,{open:e,onOpenChange:t,children:o.jsxs(xr,{className:"max-w-2xl",children:[o.jsx(wr,{children:o.jsx(gr,{children:"Create Dataset"})}),o.jsx($r,{className:"max-h-[70vh] overflow-y-auto",children:o.jsxs("form",{onSubmit:E,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"dataset-name",children:"Name *"}),o.jsx(Cn,{id:"dataset-name",value:a,onChange:N=>i(N.target.value),placeholder:"Enter dataset name",autoFocus:!0})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"dataset-description",children:"Description"}),o.jsx(Cn,{id:"dataset-description",value:l,onChange:N=>c(N.target.value),placeholder:"Enter dataset description (optional)"})]}),!k&&o.jsx(Cc,{label:"Target type",name:"dataset-target-type",placeholder:"Select a target type (optional)",options:[...FG],value:b,onValueChange:N=>x(N),helpText:"What this dataset evaluates. Drives the Target column and the Target filter.",disabled:S.isPending}),r&&!g?o.jsx("button",{type:"button",className:"text-neutral3 hover:text-accent1 text-xs transition-colors",onClick:()=>y(!0),children:"+ Custom schema"}):o.jsx(Y8t,{inputSchema:u,outputSchema:f,requestContextSchema:h,onChange:C,disabled:S.isPending}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ce,{type:"button",onClick:j,children:"Cancel"}),o.jsx(ce,{type:"submit",variant:"primary",disabled:S.isPending||!a.trim(),children:S.isPending?"Creating...":"Create Dataset"})]})]})})]})})}const K8t=v.createContext(null);function its({children:e}){const[t,n]=v.useState({}),r=v.useRef(t);r.current=t;const s=v.useCallback(({datasetId:l,modelId:c,prompt:u,count:d,agentContext:f,generateFn:p})=>{n(h=>({...h,[l]:{datasetId:l,modelId:c,count:d,status:"generating",startedAt:Date.now()}})),p({datasetId:l,modelId:c,prompt:u,count:d,agentContext:f}).then(h=>{const m=h.items??[];n(g=>{const y=g[l];if(!y||y.status!=="generating")return g;if(m.length===0){Le.info("Generation complete — no items were produced.");const{[l]:b,...x}=g;return x}return Le.success(`Generated ${m.length} item${m.length>1?"s":""}. Click the dataset to review.`),{...g,[l]:{...y,status:"review-ready",items:m}}})}).catch(h=>{const m=h instanceof Error?h.message:"Unknown error";Le.error(`Generation failed: ${m}`),n(g=>{const y=g[l];return y?{...g,[l]:{...y,status:"error",error:m}}:g})})},[]),a=v.useCallback(l=>{n(c=>{const{[l]:u,...d}=c;return d})},[]),i=v.useCallback(l=>{const c=r.current[l];if(!c||c.status!=="review-ready"||!c.items)return null;const u=c.items;return n(d=>{const{[l]:f,...p}=d;return p}),u},[]);return o.jsx(K8t.Provider,{value:{tasks:t,startGeneration:s,dismissTask:a,consumeReviewItems:i},children:e})}function X8t(){const e=v.useContext(K8t);if(!e)throw new Error("useGenerationTasks must be used within GenerationProvider");return e}function $Ke(e){const t=[];return e?.description?t.push(`Generate diverse test inputs for an agent that ${e.description.toLowerCase()}.`):t.push("Generate diverse test inputs for this agent."),e?.instructions&&t.push(`Agent instructions: ${e.instructions}`),e?.tools?.length&&t.push(`The agent has these tools: ${e.tools.join(", ")}.`),t.push("Include edge cases, typical usage, and adversarial inputs."),t.join(" ")}function ots({datasetId:e,agentContext:t,onDismiss:n}){const{provider:r,model:s}=EEe(),[a,i]=v.useState(r),[l,c]=v.useState(s),u=a&&l?`${a}/${l}`:"",[d,f]=v.useState(()=>$Ke(t)),[p,h]=v.useState(5),m=v.useRef(null),{generateItems:g}=Ni(),{startGeneration:y}=X8t(),b=v.useCallback(()=>{if(!u){Le.error("Please select a provider and model");return}const S=d.trim()||$Ke(t);y({datasetId:e,modelId:u,prompt:S,count:p,agentContext:t,generateFn:async k=>({items:(await g.mutateAsync(k)).items??[]})}),n()},[d,p,u,e,g,t,n,y]),x=v.useCallback(S=>{S||n()},[n]);return o.jsx(br,{open:!0,onOpenChange:x,children:o.jsxs(xr,{ref:m,className:"max-w-2xl",children:[o.jsx(wr,{children:o.jsx(gr,{children:"Generate Test Data"})}),o.jsx($r,{children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(Dt,{children:"Model"}),o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("div",{className:"w-[160px]",children:o.jsx(Vy,{value:a,onValueChange:S=>{const k=fi(S);i(k),c("")},size:"sm",container:m})}),o.jsx("div",{className:"flex-1",children:o.jsx(qy,{llmId:a,value:l,onValueChange:c,size:"sm",container:m})})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Instructions (optional)"}),o.jsx($l,{value:d,onChange:S=>f(S.target.value),placeholder:"e.g., Generate diverse recipe queries covering different cuisines, dietary restrictions, and skill levels...",rows:4})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Number of items"}),o.jsx(Cn,{type:"number",min:1,max:50,value:p,onChange:S=>h(Math.max(1,Math.min(50,parseInt(S.target.value)||1)))})]}),!u&&o.jsx(ye,{variant:"ui-xs",className:"text-amber-400",children:"Select a provider and model above to generate items."})]})}),o.jsx(Tc,{className:"px-6",children:o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(ce,{onClick:()=>x(!1),children:"Cancel"}),o.jsxs(ce,{variant:"primary",onClick:b,disabled:!u,children:[o.jsx(qe,{children:o.jsx(Eg,{})}),"Generate"]})]})})]})})}function lts({datasetId:e,items:t,modelId:n,onDismiss:r,onStartOver:s}){const[a,i]=v.useState(t),[l,c]=v.useState(new Set(t.map((S,k)=>k))),[u,d]=v.useState(new Set([0])),f=a.length,{batchInsertItems:p}=Ni(),h=v.useCallback(async()=>{const S=a.filter((k,_)=>l.has(_)).map(k=>({input:k.input,groundTruth:k.groundTruth,source:{type:"llm",referenceId:n}}));if(S.length===0){Le.error("No items selected");return}try{await p.mutateAsync({datasetId:e,items:S}),Le.success(`Added ${S.length} item${S.length>1?"s":""} to dataset`),r()}catch(k){Le.error(`Failed to add items: ${k instanceof Error?k.message:"Unknown error"}`)}},[a,l,n,e,p,r]),m=v.useCallback(S=>{S||r()},[r]),g=v.useCallback(S=>{c(k=>{const _=new Set(k);return _.has(S)?_.delete(S):_.add(S),_})},[]),y=v.useCallback(S=>{d(k=>{const _=new Set(k);return _.has(S)?_.delete(S):_.add(S),_})},[]),b=v.useCallback(()=>{l.size===f?c(new Set):c(new Set(Array.from({length:f},(S,k)=>k)))},[l.size,f]),x=v.useCallback(S=>{i(k=>k.filter((_,C)=>C!==S)),c(k=>{const _=new Set;for(const C of k)C<S?_.add(C):C>S&&_.add(C-1);return _}),d(k=>{const _=new Set;for(const C of k)C<S?_.add(C):C>S&&_.add(C-1);return _})},[]);return o.jsx(br,{open:!0,onOpenChange:m,children:o.jsxs(xr,{className:"max-w-2xl",children:[o.jsx(wr,{children:o.jsx(gr,{children:"Review Generated Items"})}),o.jsx($r,{className:"flex max-h-[70vh] flex-col",children:o.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(zo,{checked:l.size===a.length,onCheckedChange:b}),o.jsxs(ye,{variant:"ui-sm",className:"text-neutral4",children:[l.size," of ",a.length," selected"]})]}),s&&o.jsx(ce,{variant:"ghost",size:"sm",onClick:s,children:"Start over"})]}),o.jsx(Br,{className:"min-h-0 flex-1",children:o.jsx("div",{className:"space-y-2",children:a.map((S,k)=>o.jsxs("div",{className:"border-border1 rounded-lg border",children:[o.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[o.jsx(zo,{checked:l.has(k),onCheckedChange:()=>g(k)}),o.jsx("button",{type:"button",className:"flex-1 text-left",onClick:()=>y(k),children:o.jsxs(ye,{variant:"ui-sm",className:"text-neutral5 truncate",children:["Item ",k+1,": ",cts(S.input)]})}),o.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>x(k),children:o.jsx(qe,{size:"sm",children:o.jsx(uu,{})})})]}),u.has(k)&&o.jsxs("div",{className:"border-border1 space-y-2 border-t px-3 py-2",children:[o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Input"}),o.jsx("pre",{className:"text-neutral5 bg-surface1 mt-1 max-h-32 overflow-x-auto overflow-y-auto rounded px-2 py-1.5 text-xs wrap-break-word whitespace-pre-wrap",children:JSON.stringify(S.input,null,2)})]}),S.groundTruth!==void 0&&o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Ground Truth"}),o.jsx("pre",{className:"text-neutral5 bg-surface1 mt-1 max-h-32 overflow-x-auto overflow-y-auto rounded px-2 py-1.5 text-xs wrap-break-word whitespace-pre-wrap",children:JSON.stringify(S.groundTruth,null,2)})]})]})]},k))})})]})}),o.jsx(Tc,{className:"px-6",children:o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(ce,{onClick:()=>m(!1),children:"Cancel"}),o.jsx(ce,{variant:"primary",onClick:h,disabled:l.size===0||p.isPending,children:p.isPending?o.jsxs(o.Fragment,{children:[o.jsx(Xt,{className:"h-4 w-4"}),"Adding..."]}):o.jsxs(o.Fragment,{children:[o.jsx(qe,{children:o.jsx(Zr,{})}),"Add ",l.size," Item",l.size!==1?"s":""]})})]})})]})})}function cts(e){if(typeof e=="string")return e.slice(0,80);if(typeof e=="object"&&e!==null){const n=Object.values(e)[0];return typeof n=="string"?n.slice(0,80):JSON.stringify(e).slice(0,80)}return String(e).slice(0,80)}function Sz(e){if(Array.isArray(e))return e;if(typeof e=="string"){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return[]}function MKe(e){return e?(typeof e=="string"?new Date(e):e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function kz(e){return e?e instanceof Date?e.getTime():new Date(e).getTime():0}const uts={completed:"success",running:"warning",failed:"error",pending:"neutral"};function dts({agentId:e,onSwitchToReview:t,pendingScorerItems:n,onPendingScorerItemsConsumed:r}){const[s,a]=v.useState("experiments"),[i,l]=v.useState(null),[c,u]=v.useState(!1),[d,f]=v.useState(!1),[p,h]=v.useState(""),[m,g]=v.useState(!1),[y,b]=v.useState(""),[x,S]=v.useState(null),[k,_]=v.useState(null),[C,E]=v.useState(""),[j,N]=v.useState(""),[I,A]=v.useState(""),{form:R,isCodeAgentOverride:L}=Ho(),{addItems:D}=pMt(),B=Dn({control:R.control,name:"scorers"})??{},H=Dn({control:R.control,name:"instructions"}),F=Dn({control:R.control,name:"description"}),z=Dn({control:R.control,name:"tools"}),{data:q,isLoading:M}=Bg(),G=q?.datasets??[],{data:V,isLoading:$}=ih(),{data:U,isLoading:Z}=PNe(e),{tasks:K}=X8t(),{updateDataset:te,updateExperimentResult:ee}=Ni(),{createStoredAgent:J,updateStoredAgent:ae}=w1(e),de=v.useMemo(()=>({description:F||"",instructions:H||"",tools:z?Object.keys(z):[]}),[F,H,z]);v.useEffect(()=>{for(const[Ce,Ee]of Object.entries(K))if(Ee.status==="review-ready"&&Ee.items?.length){_(Ce);break}},[K]),v.useEffect(()=>{n?.length&&(a("scorers"),l({type:"new-scorer",prefillTestItems:n.map(Ce=>({input:Ce.input,output:Ce.output,expectedDirection:"low"}))}),r?.())},[n,r]);const Y=G.filter(Ce=>Sz(Ce.targetIds).includes(e)),ne=G.filter(Ce=>!Sz(Ce.targetIds).includes(e)),fe=(U||[]).reduce((Ce,Ee)=>{const Oe=Ce[Ee.datasetId];return(!Oe||kz(Ee.startedAt)>kz(Oe.startedAt))&&(Ce[Ee.datasetId]=Ee),Ce},{}),oe=v.useMemo(()=>{const Ce=new Map;return Y.forEach(Ee=>Ce.set(Ee.id,Ee)),Ce},[Y]),le=Object.entries(V||{}),he=le.filter(([Ce])=>!!B[Ce]),be=le.filter(([Ce])=>!B[Ce]),xe=v.useCallback(async Ce=>{R.setValue("scorers",Ce,{shouldDirty:!1});const Ee={scorers:V8t(Ce)};try{await ae.mutateAsync(Ee)}catch(Oe){if(L)try{const Pe=R.getValues();await J.mutateAsync({id:e,name:Pe.name,instructions:rbe(Pe.instructionBlocks),model:Pe.model,...Ee})}catch(Pe){console.error("Failed to persist scorer change:",Pe),Le.error("Failed to save scorer changes")}else console.error("Failed to persist scorer change:",Oe),Le.error("Failed to save scorer changes")}},[R,e,L,J,ae]),je=v.useCallback(async(Ce,Ee)=>{const Pe={...R.getValues("scorers")||{},[Ce]:{sampling:Ee.sampling}};await xe(Pe)},[R,xe]),ke=v.useCallback(async Ce=>{const Ee=R.getValues("scorers")||{},{[Ce]:Oe,...Pe}=Ee;await xe(Pe)},[R,xe]),Ae=v.useCallback(async Ce=>{for(const Ee of Ce)if(Ee.experimentId&&Ee.datasetId)try{await ee.mutateAsync({datasetId:Ee.datasetId,experimentId:Ee.experimentId,resultId:Ee.id,status:"needs-review"})}catch{}D(Ce.map(Ee=>({id:Ee.id,itemId:Ee.itemId,input:Ee.input,output:Ee.output,error:Ee.error,scores:Ee.scores,experimentId:Ee.experimentId,datasetId:Ee.datasetId,traceId:Ee.traceId}))),t?.()},[D,t,ee]),Me=v.useCallback(Ce=>{a("scorers"),l({type:"new-scorer",prefillTestItems:Ce.map(Ee=>({input:Ee.input,output:Ee.output,expectedDirection:"low"}))})},[]),ue=v.useMemo(()=>{const Ce=[...U||[]].sort((Oe,Pe)=>{const Ue=kz(Oe.startedAt);return kz(Pe.startedAt)-Ue});if(!C)return Ce;const Ee=C.toLowerCase();return Ce.filter(Oe=>{const Pe=oe.get(Oe.datasetId)?.name??"";return Oe.id.toLowerCase().includes(Ee)||Pe.toLowerCase().includes(Ee)||(Oe.targetId??"").toLowerCase().includes(Ee)})},[U,C,oe]),re=v.useMemo(()=>{if(!j)return Y;const Ce=j.toLowerCase();return Y.filter(Ee=>Ee.name.toLowerCase().includes(Ce)||(Ee.description??"").toLowerCase().includes(Ce))},[Y,j]),se=v.useMemo(()=>{if(!I)return he;const Ce=I.toLowerCase();return he.filter(([Ee,Oe])=>(Oe.scorer?.name||Ee).toLowerCase().includes(Ce))},[he,I]),me=v.useCallback(Ce=>{a(Ce),l(null)},[]);function we(){if(!i)return null;const Ce=(Ee,Oe)=>o.jsx("div",{className:"border-border1 flex items-center gap-2 border-b px-4 py-2",children:o.jsxs(ce,{variant:"ghost",size:"sm",onClick:Oe,children:[o.jsx(lit,{className:"size-4"}),Ee]})});if(i.type==="dataset")return o.jsxs(Yr,{withLeftSeparator:!0,children:[Ce("Back to Datasets",()=>l(null)),o.jsx(Yr.Content,{children:o.jsx(qes,{agentId:e,datasetId:i.id,datasetName:oe.get(i.id)?.name??"",datasetDescription:oe.get(i.id)?.description??void 0,datasetTags:oe.get(i.id)?.tags??void 0,datasetTargetType:oe.get(i.id)?.targetType,datasetTargetIds:Sz(oe.get(i.id)?.targetIds),activeScorers:Object.keys(B),datasetScorerIds:oe.get(i.id)?.scorerIds??null,onGenerate:()=>S(i.id),onViewExperiment:Ee=>l({type:"experiment",id:Ee,datasetId:i.id})})})]});if(i.type==="scorer")return o.jsxs(Yr,{withLeftSeparator:!0,children:[Ce("Back to Scorers",()=>l(null)),o.jsx(Yr.Content,{children:o.jsx(Zes,{scorerId:i.id,scorerData:V?.[i.id],isAttached:!!B[i.id],onToggleAttach:async()=>{B[i.id]?await ke(i.id):await je(i.id,V?.[i.id]??{})},onEdit:()=>l({type:"edit-scorer",id:i.id,scorerData:V?.[i.id]??{}}),linkedDatasets:G.map(Ee=>({id:Ee.id,name:Ee.name})),onViewDataset:Ee=>{a("datasets"),l({type:"dataset",id:Ee})}})})]});if(i.type==="new-scorer")return o.jsxs(Yr,{withLeftSeparator:!0,children:[Ce("Back to Scorers",()=>l(null)),o.jsx(Yr.Content,{children:o.jsx(RKe,{onBack:()=>l(null),prefillTestItems:i.prefillTestItems,onSaved:Ee=>{je(Ee,{}),l({type:"scorer",id:Ee})}})})]});if(i.type==="edit-scorer")return o.jsxs(Yr,{withLeftSeparator:!0,children:[Ce("Back to Scorer",()=>l({type:"scorer",id:i.id})),o.jsx(Yr.Content,{children:o.jsx(RKe,{onBack:()=>l({type:"scorer",id:i.id}),editScorerId:i.id,editScorerData:i.scorerData,onSaved:()=>l({type:"scorer",id:i.id})})})]});if(i.type==="experiment"){const Ee=U?.find(Oe=>Oe.id===i.id);return Ee?o.jsxs(Yr,{withLeftSeparator:!0,children:[Ce("Back to Experiments",()=>l(null)),o.jsx(Yr.Content,{children:o.jsx($es,{experiment:Ee,onBack:()=>l(null),onSendToReview:Ae,onCreateScorer:Me})})]}):o.jsxs(Yr,{withLeftSeparator:!0,children:[Ce("Back to Experiments",()=>l(null)),o.jsx(Yr.Content,{children:o.jsx("div",{className:"text-neutral3 p-4",children:"Experiment not found"})})]})}return null}function Ne(){return Z?o.jsx(ol,{columns:"auto minmax(15rem,1fr) auto auto auto auto auto"}):U?.length?o.jsxs(ve,{columns:"auto minmax(15rem,1fr) auto auto auto auto auto",className:"min-w-0",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Experiment"}),o.jsx(ve.TopCell,{children:"Dataset"}),o.jsx(ve.TopCell,{children:"Status"}),o.jsx(ve.TopCell,{className:"text-center",children:"Items"}),o.jsx(ve.TopCell,{className:"text-center",children:"Succeeded"}),o.jsx(ve.TopCell,{className:"text-center",children:"Failed"}),o.jsx(ve.TopCell,{children:"Date"})]}),ue.map(Ce=>{const Ee=oe.get(Ce.datasetId)?.name??Ce.datasetId.slice(0,8),Oe=Ce.status??"pending",Pe=Ce.succeededCount??0,Ue=Ce.failedCount??0,Ke=Ce.totalItems??0,tt=Ke>0?Math.round(Pe/Ke*100):0,Pt=i?.type==="experiment"&&i.id===Ce.id;return o.jsxs(ve.RowButton,{featured:Pt,onClick:()=>l({type:"experiment",id:Ce.id,datasetId:Ce.datasetId}),children:[o.jsx(ve.IdCell,{id:Ce.id}),o.jsx(ve.Cell,{height:"compact",className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:Ee})}),o.jsx(ve.Cell,{height:"compact",children:o.jsx(bg,{variant:uts[Oe]??"neutral",withDot:!0,children:Oe})}),o.jsx(ve.Cell,{height:"compact",className:"text-center",children:Ke}),o.jsx(ve.Cell,{height:"compact",className:"text-center",children:o.jsxs("span",{className:Pe>0?"text-accent1":"",children:[Pe," (",tt,"%)"]})}),o.jsx(ve.Cell,{height:"compact",className:"text-center",children:o.jsx("span",{className:Ue>0?"text-accent2":"",children:Ue})}),o.jsx(ve.Cell,{height:"compact",children:MKe(Ce.startedAt)})]},Ce.id)})]}):o.jsx("div",{className:"flex h-full items-center justify-center py-20",children:o.jsx(Lr,{iconSlot:o.jsx(pit,{className:"text-neutral3 size-10"}),titleSlot:"No Experiments Yet",descriptionSlot:"Run experiments against your datasets to see results here."})})}function Re(){return M?o.jsx(ol,{columns:"minmax(10rem,1fr) auto auto auto auto"}):Y.length?o.jsxs(ve,{columns:"minmax(10rem,1fr) auto auto auto auto",className:"min-w-0",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Name"}),o.jsx(ve.TopCell,{children:"Tags"}),o.jsx(ve.TopCell,{children:"Latest Experiment"}),o.jsx(ve.TopCell,{children:"Status"}),o.jsx(ve.TopCell,{children:"Updated"})]}),re.map(Ce=>{const Ee=fe[Ce.id],Oe=K[Ce.id],Pe=Oe?.status==="generating",Ue=i?.type==="dataset"&&i.id===Ce.id;return o.jsxs(ve.RowButton,{featured:Ue,onClick:()=>l({type:"dataset",id:Ce.id}),children:[o.jsx(ve.Cell,{height:"compact",className:"text-neutral4 min-w-0",children:o.jsx("span",{className:"block truncate",children:Ce.name})}),o.jsx(ve.Cell,{height:"compact",children:Ce.tags?.length?o.jsxs("div",{className:"flex gap-1",children:[Ce.tags.slice(0,2).map(Ke=>o.jsx(un,{variant:"default",children:Ke},Ke)),Ce.tags.length>2&&o.jsxs(un,{variant:"default",children:["+",Ce.tags.length-2]})]}):o.jsx("span",{className:"text-neutral2",children:"—"})}),o.jsx(ve.Cell,{height:"compact",children:Ee?o.jsx(fts,{experiment:Ee}):o.jsx("span",{className:"text-neutral2",children:"No experiments"})}),o.jsx(ve.Cell,{height:"compact",children:Pe?o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Xt,{className:"size-3"}),o.jsx(ye,{variant:"ui-xs",className:"text-warning1",children:"Generating..."})]}):Oe?.error?o.jsx(ye,{variant:"ui-xs",className:"text-negative1",children:"Failed"}):o.jsx("span",{className:"text-neutral2",children:"—"})}),o.jsx(ve.Cell,{height:"compact",children:MKe(Ce.updatedAt)})]},Ce.id)})]}):o.jsx("div",{className:"flex h-full items-center justify-center py-20",children:o.jsx(Lr,{iconSlot:o.jsx(cy,{className:"text-neutral3 size-10"}),titleSlot:"No Datasets",descriptionSlot:"Create or attach a dataset to begin testing your agent."})})}function Qe(){return $?o.jsx(ol,{columns:"minmax(10rem,1fr) auto auto auto"}):he.length?o.jsxs(ve,{columns:"minmax(10rem,1fr) auto auto auto",className:"min-w-0",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Name"}),o.jsx(ve.TopCell,{children:"Source"}),o.jsx(ve.TopCell,{children:"Description"}),o.jsx(ve.TopCell,{children:"Datasets"})]}),se.map(([Ce,Ee])=>{const Oe=Ee.scorer?.name||Ce,Pe=Ee.scorer?.description||"",Ue=Ee.source??"stored",Ke=G.filter(Pt=>(Pt.scorerIds??[]).includes(Ce)).length,tt=i?.type==="scorer"&&i.id===Ce;return o.jsxs(ve.RowButton,{featured:tt,onClick:()=>l({type:"scorer",id:Ce}),children:[o.jsx(ve.Cell,{height:"compact",className:"text-neutral4 min-w-0",children:o.jsx("span",{className:"block truncate",children:Oe})}),o.jsx(ve.Cell,{height:"compact",children:o.jsx(un,{variant:Ue==="code"?"default":"success",children:Ue})}),o.jsx(ve.Cell,{height:"compact",className:"min-w-0",children:o.jsx("span",{className:"block max-w-[200px] truncate",children:Pe||o.jsx("span",{className:"text-neutral2",children:"—"})})}),o.jsx(ve.Cell,{height:"compact",children:Ke>0?`${Ke} dataset${Ke>1?"s":""}`:"—"})]},Ce)})]}):o.jsx("div",{className:"flex h-full items-center justify-center py-20",children:o.jsx(Lr,{iconSlot:o.jsx(nm,{className:"text-neutral3 size-10"}),titleSlot:"No Scorers Attached",descriptionSlot:"Attach or create a scorer to evaluate your agent's performance."})})}function Ze(){return o.jsxs(o.Fragment,{children:[o.jsx(lbe,{open:c,onOpenChange:u,targetType:"agent",targetIds:[e]}),x&&o.jsx(ots,{datasetId:x,agentContext:de,onDismiss:()=>S(null)}),k&&K[k]?.status==="review-ready"&&K[k]?.items&&o.jsx(lts,{datasetId:k,items:K[k].items,modelId:K[k].modelId,onDismiss:()=>_(null)}),o.jsx(br,{open:d,onOpenChange:f,children:o.jsxs(xr,{children:[o.jsx(wr,{children:o.jsx(gr,{children:"Attach Existing Dataset"})}),o.jsxs($r,{className:"max-h-[50vh] overflow-y-auto",children:[o.jsxs(Pu,{variant:"outline",children:[o.jsx(Kc,{align:"inline-start",children:o.jsx(Ya,{})}),o.jsx($u,{type:"search","aria-label":"Search datasets",placeholder:"Search datasets...",onChange:Ce=>h(Ce.target.value)})]}),ne.filter(Ce=>!p||Ce.name.toLowerCase().includes(p.toLowerCase())).map(Ce=>o.jsx("button",{type:"button",className:"hover:bg-surface3 flex w-full items-center justify-between rounded-md px-3 py-2 text-left transition-colors",onClick:async()=>{try{await te.mutateAsync({datasetId:Ce.id,targetType:Ce.targetType??"agent",targetIds:[...Sz(Ce.targetIds),e]}),Le.success(`Dataset "${Ce.name}" attached`),f(!1)}catch{Le.error("Failed to attach dataset")}},children:o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-sm",className:"font-medium",children:Ce.name}),Ce.description&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 block",children:Ce.description})]})},Ce.id)),ne.filter(Ce=>!p||Ce.name.toLowerCase().includes(p.toLowerCase())).length===0&&o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 block py-4 text-center",children:"No datasets available to attach"})]})]})}),o.jsx(br,{open:m,onOpenChange:g,children:o.jsxs(xr,{children:[o.jsx(wr,{children:o.jsx(gr,{children:"Attach Existing Scorer"})}),o.jsxs($r,{className:"max-h-[50vh] overflow-y-auto",children:[o.jsxs(Pu,{variant:"outline",children:[o.jsx(Kc,{align:"inline-start",children:o.jsx(Ya,{})}),o.jsx($u,{type:"search","aria-label":"Search scorers",placeholder:"Search scorers...",onChange:Ce=>b(Ce.target.value)})]}),be.filter(([Ce,Ee])=>y?(Ee.scorer?.name||Ce).toLowerCase().includes(y.toLowerCase()):!0).map(([Ce,Ee])=>o.jsx("button",{type:"button",className:"hover:bg-surface3 flex w-full items-center justify-between rounded-md px-3 py-2 text-left transition-colors",onClick:async()=>{try{await je(Ce,Ee),Le.success(`Scorer "${Ee.scorer?.name||Ce}" attached`),g(!1)}catch{Le.error("Failed to attach scorer")}},children:o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-sm",className:"font-medium",children:Ee.scorer?.name||Ce}),Ee.scorer?.description&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 block",children:Ee.scorer.description})]})},Ce)),be.filter(([Ce,Ee])=>y?(Ee.scorer?.name||Ce).toLowerCase().includes(y.toLowerCase()):!0).length===0&&o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 block py-4 text-center",children:"No scorers available to attach"})]})]})})]})}const Te=!!i;return o.jsxs("div",{className:"flex h-full flex-col overflow-hidden p-4",children:[o.jsxs(Dc,{defaultTab:"experiments",value:s,onValueChange:me,className:"flex h-full flex-col overflow-hidden",children:[o.jsxs("div",{className:"border-border1 flex items-center justify-between border-b",children:[o.jsxs(Mc,{className:"border-b-0",children:[o.jsx(Rr,{value:"experiments",children:"Experiments"}),o.jsx(Rr,{value:"datasets",children:"Datasets"}),o.jsx(Rr,{value:"scorers",children:"Scorers"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[s==="datasets"&&o.jsxs(o.Fragment,{children:[ne.length>0&&o.jsxs(ce,{variant:"ghost",size:"sm",onClick:()=>f(!0),children:[o.jsx(A2e,{className:"mr-1 size-3.5"}),"Attach"]}),o.jsxs(ce,{variant:"ghost",size:"sm",onClick:()=>u(!0),children:[o.jsx(Zr,{className:"mr-1 size-3.5"}),"Create"]})]}),s==="scorers"&&o.jsxs(o.Fragment,{children:[be.length>0&&o.jsxs(ce,{variant:"ghost",size:"sm",onClick:()=>g(!0),children:[o.jsx(A2e,{className:"mr-1 size-3.5"}),"Attach"]}),o.jsxs(ce,{variant:"ghost",size:"sm",onClick:()=>l({type:"new-scorer"}),children:[o.jsx(Zr,{className:"mr-1 size-3.5"}),"New"]})]})]})]}),o.jsxs("div",{className:"border-border1 border-b py-2",children:[s==="experiments"&&o.jsxs(Pu,{variant:"outline",children:[o.jsx(Kc,{align:"inline-start",children:o.jsx(Ya,{})}),o.jsx($u,{type:"search","aria-label":"Search experiments",placeholder:"Search experiments...",onChange:Ce=>E(Ce.target.value)})]}),s==="datasets"&&o.jsxs(Pu,{variant:"outline",children:[o.jsx(Kc,{align:"inline-start",children:o.jsx(Ya,{})}),o.jsx($u,{type:"search","aria-label":"Search datasets",placeholder:"Search datasets...",onChange:Ce=>N(Ce.target.value)})]}),s==="scorers"&&o.jsxs(Pu,{variant:"outline",children:[o.jsx(Kc,{align:"inline-start",children:o.jsx(Ya,{})}),o.jsx($u,{type:"search","aria-label":"Search scorers",placeholder:"Search scorers...",onChange:Ce=>A(Ce.target.value)})]})]}),o.jsxs("div",{className:"flex-1 overflow-hidden",children:[o.jsx(Xr,{value:"experiments",className:"h-full overflow-hidden",children:o.jsxs(ly,{className:Te&&i?.type==="experiment"?"grid-cols-[1fr_1fr]":"",children:[o.jsx(Yr,{children:o.jsx(Yr.Content,{children:Ne()})}),i?.type==="experiment"&&we()]})}),o.jsx(Xr,{value:"datasets",className:"h-full overflow-hidden",children:o.jsxs(ly,{className:Te&&i?.type==="dataset"?"grid-cols-[1fr_1fr]":"",children:[o.jsx(Yr,{children:o.jsx(Yr.Content,{children:Re()})}),i?.type==="dataset"&&we()]})}),o.jsx(Xr,{value:"scorers",className:"h-full overflow-hidden",children:o.jsxs(ly,{className:Te&&(i?.type==="scorer"||i?.type==="new-scorer"||i?.type==="edit-scorer")?"grid-cols-[1fr_1fr]":"",children:[o.jsx(Yr,{children:o.jsx(Yr.Content,{children:Qe()})}),(i?.type==="scorer"||i?.type==="new-scorer"||i?.type==="edit-scorer")&&we()]})})]})]}),Ze()]})}function fts({experiment:e}){const{status:t,succeededCount:n,totalItems:r}=e,s=[e.datasetVersion!=null?NN("Dataset",e.datasetVersion):null,e.agentVersion?NN("Agent",e.agentVersion):null].filter(Boolean),a=s.length>0?o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:s.join(" · ")}):null;if(t==="running"||t==="pending")return o.jsxs("div",{className:"flex flex-col",children:[o.jsx(ye,{variant:"ui-xs",className:"text-warning1",children:t==="running"?"Running...":"Pending..."}),a]});if(r===0)return o.jsxs("div",{className:"flex flex-col",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:"No results"}),a]});const i=n/r,l=i>=.8?"text-positive1":i>=.5?"text-warning1":"text-negative1";return o.jsxs("div",{className:"flex flex-col",children:[o.jsxs(ye,{variant:"ui-xs",className:l,children:[n,"/",r," passed"]}),a]})}const pts=e=>{const t=We(),{data:n}=PNe(e);return yt({queryKey:["completed-items",e,n?.map(r=>r.id)],queryFn:async()=>!n||n.length===0?[]:(await Promise.all(n.map(async s=>{try{const{results:a}=await t.listDatasetExperimentResults(s.datasetId,s.id);return a.filter(i=>i.status==="complete").map(i=>({id:i.id,input:i.input,output:i.output,error:i.error,itemId:i.itemId,experimentId:i.experimentId,datasetId:s.datasetId,traceId:i.traceId??void 0,scores:i.scores?Object.fromEntries(i.scores.map(l=>[l.scorerId,l.score??0])):{},tags:i.tags??[],comment:""}))}catch{return[]}}))).flat(),enabled:!!e&&!!n&&n.length>0,refetchOnWindowFocus:!1})},hts=e=>{const t=We(),{data:n}=PNe(e);return yt({queryKey:["review-items",e,n?.map(r=>r.id)],queryFn:async()=>!n||n.length===0?[]:(await Promise.all(n.map(async s=>{try{const{results:a}=await t.listDatasetExperimentResults(s.datasetId,s.id);return a.filter(i=>i.status==="needs-review").map(i=>({id:i.id,input:i.input,output:i.output,error:i.error,itemId:i.itemId,experimentId:i.experimentId,datasetId:s.datasetId,traceId:i.traceId??void 0,scores:i.scores?Object.fromEntries(i.scores.map(l=>[l.scorerId,l.score??0])):{},tags:i.tags??[],comment:""}))}catch{return[]}}))).flat(),enabled:!!e&&!!n&&n.length>0,refetchOnWindowFocus:!1})};function mts({tags:e,vocabulary:t,onSetTags:n}){const[r,s]=v.useState(!1),[a,i]=v.useState(""),l=v.useRef(null),c=t.filter(h=>!e.includes(h)&&h.toLowerCase().includes(a.toLowerCase())),u=a.trim()&&!t.includes(a.trim())&&!e.includes(a.trim()),d=h=>{n([...e,h]),i("")},f=h=>{n(e.filter(m=>m!==h))},p=h=>{h.key==="Enter"&&a.trim()&&(h.preventDefault(),d(a.trim()))};return o.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[e.map(h=>o.jsxs("span",{className:"bg-accent1/10 text-accent1 inline-flex items-center gap-0.5 rounded-md px-1.5 py-0.5 text-[10px] font-medium",children:[h,o.jsx("button",{type:"button",onClick:()=>f(h),className:"hover:text-accent1/70",children:o.jsx(bs,{className:"h-2.5 w-2.5"})})]},h)),o.jsxs(Pf,{open:r,onOpenChange:s,children:[o.jsx(Bd,{asChild:!0,children:o.jsxs("button",{type:"button",className:"text-neutral3 hover:text-neutral5 hover:bg-surface3 inline-flex items-center gap-0.5 rounded px-1 py-0.5 text-[10px] transition-colors",children:[o.jsx(Zr,{className:"h-3 w-3"}),"tag"]})}),o.jsxs(Ud,{className:"w-52 p-2",align:"start",children:[o.jsx(Cn,{ref:l,value:a,onChange:h=>i(h.target.value),onKeyDown:p,placeholder:"Search or create tag...",className:"mb-1 h-7 text-xs",autoFocus:!0}),o.jsxs("div",{className:"max-h-32 space-y-0.5 overflow-y-auto",children:[c.map(h=>o.jsx("button",{type:"button",onClick:()=>d(h),className:"hover:bg-surface3 text-neutral4 w-full rounded px-2 py-1 text-left text-xs",children:h},h)),u&&o.jsxs("button",{type:"button",onClick:()=>d(a.trim()),className:"hover:bg-surface3 text-accent1 w-full rounded px-2 py-1 text-left text-xs",children:['Create "',a.trim(),'"']}),c.length===0&&!u&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 block px-2 py-1",children:"No tags available"})]})]})]})]})}function cae(e){if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function J8t({item:e,isCompleted:t,tagVocabulary:n,onRate:r,onSetTags:s,onComment:a,onRemove:i,onComplete:l,onPrevious:c,onNext:u,onClose:d}){const[f,p]=v.useState(e.comment||""),[h,m]=v.useState(!1),[g,y]=v.useState(!1);v.useEffect(()=>{p(e.comment||""),m(!1),y(!1)},[e.id]);const b=v.useRef(void 0);v.useEffect(()=>()=>clearTimeout(b.current),[]);const x=()=>{f!==(e.comment||"")&&(a(f),m(!0),clearTimeout(b.current),b.current=setTimeout(()=>m(!1),1500))};return o.jsxs(o.Fragment,{children:[o.jsxs(xn,{children:[o.jsxs(xn.Header,{children:[o.jsx(xn.Heading,{children:"Review"}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[o.jsx(xn.NextPrevNav,{onPrevious:c,onNext:u,previousLabel:"Previous item",nextLabel:"Next item"}),!t&&l&&o.jsxs(ce,{size:"md",onClick:l,"aria-label":"Mark as complete",children:[o.jsx(lO,{}),"Complete"]}),o.jsx(xn.CloseButton,{onClick:d,tooltip:"Close detail panel"})]})]}),o.jsxs(xn.Content,{children:[o.jsxs("div",{className:"mb-6 grid gap-4",children:[!t&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"Rating"}),o.jsxs(Mr,{spacing:"close",children:[o.jsx(ce,{size:"md",onClick:()=>r(e.rating==="positive"?void 0:"positive"),"aria-label":"Rate positive",children:o.jsx(qe,{size:"sm",className:e.rating==="positive"?"text-positive1":"",children:o.jsx(Ube,{})})}),o.jsx(ce,{size:"md",onClick:()=>r(e.rating==="negative"?void 0:"negative"),"aria-label":"Rate negative",children:o.jsx(qe,{size:"sm",className:e.rating==="negative"?"text-negative1":"",children:o.jsx(Bbe,{})})})]}),e.rating&&o.jsx(un,{variant:e.rating==="positive"?"success":"error",children:e.rating==="positive"?"Good":"Bad"})]}),t&&e.rating&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"Rating"}),o.jsx(un,{variant:e.rating==="positive"?"success":"error",children:e.rating==="positive"?"Good":"Bad"})]}),o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 mt-0 block",children:"Tags"}),t?o.jsx("div",{className:"flex flex-wrap gap-1",children:e.tags.length>0?e.tags.map(S=>o.jsx(un,{variant:"default",children:S},S)):o.jsx(ye,{variant:"ui-sm",className:"text-neutral2",children:"No tags"})}):o.jsx(mts,{tags:e.tags,vocabulary:n,onSetTags:s})]}),e.scores&&Object.keys(e.scores).length>0&&o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mb-2 block",children:"Scores"}),o.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(e.scores).map(([S,k])=>o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(qe,{size:"sm",className:"text-neutral3",children:o.jsx(nm,{})}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral4",children:[S,":"]}),o.jsx(un,{variant:k>=.5?"success":"error",children:k.toFixed(3)})]},S))})]}),e.experimentId&&o.jsxs(Ut,{children:[o.jsx(Ut.Key,{children:"Experiment Id"}),o.jsx(Ut.ValueWithCopyBtn,{copyTooltip:"Copy Experiment Id to clipboard",copyValue:e.experimentId,children:e.experimentId})]})]}),o.jsxs("div",{className:"grid gap-3",children:[o.jsx(xn.CodeSection,{title:"Input",icon:o.jsx(cO,{}),codeStr:cae(e.input??null)}),o.jsx(xn.CodeSection,{title:"Output",icon:o.jsx(Sg,{}),codeStr:cae(e.output??null)})]}),e.error!=null&&o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mb-1 block",children:"Error"}),o.jsx("pre",{className:"text-ui-xs text-negative1 bg-surface2 max-h-48 overflow-auto rounded-md p-3 wrap-break-word whitespace-pre-wrap",children:cae(e.error)})]}),o.jsxs("div",{className:"mt-4",children:[o.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral2 tracking-widest uppercase",children:"Comment"}),h&&o.jsx(ye,{variant:"ui-xs",className:"text-positive1",children:"Saved"})]}),t?o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 block",children:e.comment||"No comment"}):o.jsx($l,{value:f,onChange:S=>p(S.target.value),onBlur:x,placeholder:"Add notes about this item...",rows:3,className:"text-xs"})]}),!t&&o.jsxs("div",{className:"border-border1 mt-4 flex items-center gap-2 border-t pt-4",children:[l&&o.jsxs(ce,{size:"md",onClick:l,children:[o.jsx(lO,{}),"Mark as complete"]}),o.jsxs(ce,{variant:"outline",size:"md",onClick:()=>y(!0),children:[o.jsx(uu,{}),"Remove"]})]})]})]}),o.jsx(At,{open:g,onOpenChange:y,children:o.jsxs(At.Content,{children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Remove from Review"}),o.jsx(At.Description,{children:"This will remove the item from the review queue. The experiment result will remain but will no longer be flagged for review."})]}),o.jsxs(At.Footer,{children:[o.jsx(At.Cancel,{children:"Cancel"}),o.jsx(At.Action,{onClick:()=>{i(),y(!1)},children:"Remove"})]})]})})]})}function e9t({selectedCount:e,vocabulary:t,onApplyTag:n,onRemoveTag:r,onNewTag:s}){const[a,i]=v.useState(!1),[l,c]=v.useState(""),u=t.filter(f=>f.toLowerCase().includes(l.toLowerCase())),d=l.trim()&&!t.includes(l.trim());return o.jsxs(Pf,{open:a,onOpenChange:i,children:[o.jsx(Bd,{asChild:!0,children:o.jsxs(ce,{variant:"outline",size:"sm",children:[o.jsx(qe,{size:"sm",children:o.jsx(BN,{})}),"Tag ",e," items"]})}),o.jsxs(Ud,{className:"w-56 p-2",align:"end",children:[o.jsx(Cn,{value:l,onChange:f=>c(f.target.value),onKeyDown:f=>{f.key==="Enter"&&l.trim()&&(f.preventDefault(),d?s(l.trim()):n(l.trim()),c(""))},placeholder:"Search or create tag...",className:"mb-1 h-7 text-xs",autoFocus:!0}),o.jsxs("div",{className:"max-h-40 space-y-0.5 overflow-y-auto",children:[u.map(f=>o.jsxs("div",{className:"hover:bg-surface3 flex items-center justify-between rounded px-2 py-1 text-xs",children:[o.jsx("button",{type:"button",onClick:()=>n(f),className:"text-neutral4 flex-1 text-left",children:f}),o.jsx("button",{type:"button",onClick:()=>r(f),className:"text-neutral2 hover:text-negative1 ml-2",children:o.jsx(bs,{className:"h-3 w-3"})})]},f)),d&&o.jsxs("button",{type:"button",onClick:()=>{s(l.trim()),c("")},className:"hover:bg-surface3 text-accent1 w-full rounded px-2 py-1 text-left text-xs",children:['Create & apply "',l.trim(),'"']})]})]})]})}function t9t({tag:e,onRename:t,onRemove:n}){const[r,s]=v.useState(!1),[a,i]=v.useState(e),l=v.useRef(null);v.useEffect(()=>{r&&(l.current?.focus(),l.current?.select())},[r]);const c=()=>{const u=a.trim();u&&u!==e&&t(u),s(!1)};return r?o.jsxs("span",{className:"bg-surface3 border-border1 inline-flex items-center gap-0.5 rounded-md border px-1",children:[o.jsx("input",{ref:l,value:a,onChange:u=>i(u.target.value),onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),c()),u.key==="Escape"&&(i(e),s(!1))},onBlur:c,className:"text-neutral4 w-20 bg-transparent py-0.5 text-xs outline-hidden"}),o.jsx("button",{type:"button",onMouseDown:u=>{u.preventDefault(),c()},className:"text-positive1 hover:text-positive2 p-0.5",children:o.jsx(fa,{className:"h-3 w-3"})})]}):o.jsxs("span",{className:"bg-surface3 border-border1 text-neutral4 group inline-flex items-center gap-0.5 rounded-md border px-1.5 py-0.5 text-xs",children:[e,o.jsx("button",{type:"button",onClick:()=>{i(e),s(!0)},className:"text-neutral2 hover:text-neutral4 p-0.5 opacity-0 transition-opacity group-hover:opacity-100",title:"Edit tag",children:o.jsx(rm,{className:"h-3 w-3"})}),o.jsx("button",{type:"button",onClick:n,className:"text-neutral2 hover:text-negative1 p-0.5 opacity-0 transition-opacity group-hover:opacity-100",title:"Remove tag",children:o.jsx(bs,{className:"h-3 w-3"})})]})}function gts(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 vts({agentId:e,onCreateScorer:t}){const{items:n,setItemTags:r,rateItem:s,commentItem:a,removeItem:i,completeItem:l,loadPersistedItems:c}=pMt(),{data:u}=hts(e),{data:d,refetch:f,isLoading:p}=pts(e),h=We(),{provider:m,model:g}=EEe(),{data:y}=Bg(),{updateDataset:b}=Ni();v.useEffect(()=>{u&&c(u)},[u,c]);const[x,S]=v.useState(null),[k,_]=v.useState(!1),[C,E]=v.useState(null),[j,N]=v.useState(new Set),[I,A]=v.useState(!1),R=v.useRef(null),[L,D]=v.useState(!1),[B,H]=v.useState("untagged"),[F,z]=v.useState(""),[q,M]=v.useState(m),[G,V]=v.useState(g),[$,U]=v.useState([]),[Z,K]=v.useState(!1),[te,ee]=v.useState(null),J=y?.datasets,ae=v.useMemo(()=>{if(!J)return[];const Oe=new Set(n.map(Ue=>Ue.datasetId).filter(Boolean)),Pe=new Set;for(const Ue of J)if(Oe.has(Ue.id)&&Array.isArray(Ue.tags))for(const Ke of Ue.tags)Pe.add(Ke);for(const Ue of n)for(const Ke of Ue.tags)Pe.add(Ke);return Array.from(Pe).sort()},[J,n]),de=v.useCallback(Oe=>{if(!J)return;const Pe=new Set(n.map(Ue=>Ue.datasetId).filter(Boolean));for(const Ue of J)if(Pe.has(Ue.id)){const Ke=Array.isArray(Ue.tags)?Ue.tags:[];Ke.includes(Oe)||b.mutate({datasetId:Ue.id,tags:[...Ke,Oe]})}},[J,n,b]),Y=v.useCallback(Oe=>{H(Oe),z(""),M(m),V(g),D(!0)},[m,g]),ne=v.useCallback(async()=>{if(!q||!G)return;const Oe=B==="untagged"?n.filter(Pe=>Pe.tags.length===0):n.filter(Pe=>j.has(Pe.id));if(Oe.length!==0){D(!1),_(!0);try{const Pe=`${q}/${G}`,Ke=((await h.clusterFailures({modelId:Pe,items:Oe.map(tt=>({id:tt.id,input:tt.input,output:tt.output,error:typeof tt.error=="string"?tt.error:tt.error?JSON.stringify(tt.error):void 0,scores:tt.scores,existingTags:tt.tags.length>0?tt.tags:void 0})),availableTags:ae.length>0?ae:void 0,prompt:F.trim()||void 0})).proposedTags??[]).filter(tt=>tt.tags.length>0).map(tt=>({itemId:tt.itemId,tags:tt.tags,reason:tt.reason||"",accepted:!0}));Ke.length>0?(ee(Pe),U(Ke),K(!0)):Le.success("Analysis complete — no new tags proposed.")}catch(Pe){console.error("Failed to analyze failures:",Pe),Le.error("Analysis failed. Please try again.")}finally{_(!1)}}},[n,q,G,h,j,ae,B,F]),fe=v.useCallback(()=>{const Oe=$.filter(tt=>tt.accepted);for(const tt of Oe){const Pt=n.find(Ot=>Ot.id===tt.itemId);if(Pt){const Ot=Array.from(new Set([...Pt.tags,...tt.tags]));r(tt.itemId,Ot)}}const Pe=new Set(Oe.flatMap(tt=>tt.tags));for(const tt of Pe)de(tt);const Ue=Pe.size,Ke=Oe.length;Le.success(`Applied ${Ue} tag${Ue!==1?"s":""} to ${Ke} item${Ke!==1?"s":""}`),K(!1),U([])},[$,n,r,de]),oe=v.useMemo(()=>C?C==="__untagged__"?n.filter(Oe=>Oe.tags.length===0):n.filter(Oe=>Oe.tags.includes(C)):n,[n,C]),le=v.useMemo(()=>{const Oe=new Map;for(const Pe of n)for(const Ue of Pe.tags)Oe.set(Ue,(Oe.get(Ue)??0)+1);return[...Oe.entries()].sort((Pe,Ue)=>Ue[1]-Pe[1])},[n]),he=v.useMemo(()=>n.filter(Oe=>Oe.tags.length===0).length,[n]),be=v.useMemo(()=>{let Oe=0;return C&&Oe++,I&&Oe++,Oe},[C,I]),xe=v.useMemo(()=>{const Oe=I?d??[]:oe;return!I||!C?Oe:C==="__untagged__"?Oe.filter(Pe=>Pe.tags.length===0):Oe.filter(Pe=>Pe.tags.includes(C))},[I,d,oe,C]),je=I?p:!1,ke=v.useMemo(()=>new Set(xe.map(Oe=>Oe.id)),[xe]),Ae=v.useMemo(()=>[...j].filter(Oe=>ke.has(Oe)).length,[j,ke]),Me=xe.length>0&&Ae===xe.length,ue=Ae>0&&!Me,re=v.useCallback(Oe=>{N(Pe=>{const Ue=new Set(Pe);return Ue.has(Oe)?Ue.delete(Oe):Ue.add(Oe),Ue})},[]),se=v.useCallback(()=>{N(Me?new Set:new Set(xe.map(Oe=>Oe.id)))},[Me,xe]),me=v.useCallback(Oe=>{for(const Pe of j){const Ue=n.find(Ke=>Ke.id===Pe);Ue&&!Ue.tags.includes(Oe)&&r(Pe,[...Ue.tags,Oe])}de(Oe)},[j,n,r,de]),we=v.useCallback(Oe=>{for(const Pe of j){const Ue=n.find(Ke=>Ke.id===Pe);Ue&&Ue.tags.includes(Oe)&&r(Pe,Ue.tags.filter(Ke=>Ke!==Oe))}},[j,n,r]),Ne=v.useCallback(async()=>{for(const Oe of j)await l(Oe);N(new Set),f()},[j,l,f]),Re=v.useCallback(()=>{for(const Oe of j)i(Oe);N(new Set)},[j,i]),Qe=v.useCallback(Oe=>{S(Pe=>Pe===Oe?null:Oe)},[]),Ze=v.useMemo(()=>x?xe.find(Oe=>Oe.id===x)??null:null,[x,xe]),Te=v.useCallback(()=>{if(!x||xe.length===0)return;const Oe=xe.findIndex(Pe=>Pe.id===x);Oe<xe.length-1&&S(xe[Oe+1].id)},[x,xe]),Ce=v.useCallback(()=>{if(!x||xe.length===0)return;const Oe=xe.findIndex(Pe=>Pe.id===x);Oe>0&&S(xe[Oe-1].id)},[x,xe]);return o.jsxs(o.Fragment,{children:[o.jsx(br,{open:L,onOpenChange:D,children:o.jsxs(xr,{ref:R,className:"max-w-lg",children:[o.jsx(wr,{children:o.jsxs(gr,{children:["Analyze ",B==="untagged"?"Untagged":"Selected"," Items"]})}),o.jsx($r,{children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(Dt,{children:"Model"}),o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("div",{className:"w-[160px]",children:o.jsx(Vy,{value:q,onValueChange:Oe=>{const Pe=fi(Oe);M(Pe),V("")},size:"sm",container:R})}),o.jsx("div",{className:"flex-1",children:o.jsx(qy,{llmId:q,value:G,onValueChange:V,size:"sm",container:R})})]})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(Dt,{children:"Items"}),o.jsx(ye,{variant:"ui-sm",className:"text-neutral4",children:B==="untagged"?`${he} untagged item${he!==1?"s":""}`:`${j.size} selected item${j.size!==1?"s":""}`})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(Dt,{children:"Instructions (optional)"}),o.jsx($l,{value:F,onChange:Oe=>z(Oe.target.value),placeholder:"e.g., Focus on tool usage failures, pay attention to whether the agent hallucinated...",rows:3,disabled:k}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"Guide the LLM on what to look for when tagging items"})]})]})}),o.jsxs(Tc,{className:"px-6",children:[o.jsx(ce,{variant:"ghost",onClick:()=>D(!1),disabled:k,children:"Cancel"}),o.jsx(ce,{variant:"default",onClick:ne,disabled:k||!q||!G,children:k?o.jsxs(o.Fragment,{children:[o.jsx(Xt,{className:"mr-2"}),"Analyzing..."]}):"Analyze"})]})]})}),o.jsx(br,{open:Z,onOpenChange:K,children:o.jsxs(xr,{className:"max-w-xl",children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Proposed Tag Assignments"}),te&&o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3 mt-1",children:["Analyzed by ",o.jsx("span",{className:"text-neutral4 font-medium",children:te})]})]}),o.jsx($r,{className:"max-h-[400px] space-y-2 overflow-y-auto",children:$.map((Oe,Pe)=>{const Ue=n.find(tt=>tt.id===Oe.itemId),Ke=typeof Ue?.input=="string"?Ue.input:Ue?.input?JSON.stringify(Ue.input):"";return o.jsxs("div",{className:X("flex items-start gap-2 p-2 rounded-md border border-border1",Oe.accepted?"bg-surface1":"bg-surface1 opacity-50"),children:[o.jsx(zo,{checked:Oe.accepted,onCheckedChange:tt=>{U(Pt=>Pt.map((Ot,St)=>St===Pe?{...Ot,accepted:!!tt}:Ot))},className:"mt-1"}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 block truncate",children:Ke||`Item ${Oe.itemId.slice(0,8)}`}),o.jsx("div",{className:"mt-1 flex flex-wrap gap-1",children:Oe.tags.map((tt,Pt)=>o.jsx(t9t,{tag:tt,onRename:Ot=>U(St=>St.map((pt,Rt)=>Rt===Pe?{...pt,tags:pt.tags.map((rn,Ge)=>Ge===Pt?Ot:rn)}:pt)),onRemove:()=>U(Ot=>Ot.map((St,pt)=>pt===Pe?{...St,tags:St.tags.filter((Rt,rn)=>rn!==Pt)}:St))},`${tt}-${Pt}`))}),Oe.reason&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-1 italic",children:Oe.reason})]})]},Oe.itemId)})}),o.jsxs(Tc,{children:[o.jsx(ce,{variant:"ghost",onClick:()=>K(!1),children:"Cancel"}),o.jsxs(ce,{variant:"default",onClick:fe,disabled:$.filter(Oe=>Oe.accepted).length===0,children:["Accept ",$.filter(Oe=>Oe.accepted).length," proposals"]})]})]})}),o.jsxs(ly,{className:X("p-4",Ze?"grid-cols-[1fr_1fr]":""),children:[o.jsxs(Yr,{children:[o.jsxs(Yr.Toolbar,{children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs(dt,{children:[o.jsx(dt.Trigger,{asChild:!0,children:o.jsxs(ce,{variant:"outline",size:"md",children:[o.jsx(hit,{}),"Filter",be>0&&o.jsx("span",{className:X("ml-0.5 inline-flex items-center justify-center rounded-full bg-accent1/50 text-neutral5 text-ui-sm w-5 h-5"),children:be})]})}),o.jsxs(dt.Content,{align:"start",className:X("min-w-48"),children:[o.jsxs(dt.Sub,{children:[o.jsxs(dt.SubTrigger,{children:["Status",I&&o.jsx("span",{className:X("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(dt.SubContent,{children:[o.jsx(dt.CheckboxItem,{checked:!I,onCheckedChange:()=>{A(!1),S(null)},onSelect:Oe=>Oe.preventDefault(),children:"Review Queue"}),o.jsx(dt.CheckboxItem,{checked:I,onCheckedChange:()=>{A(!0),S(null)},onSelect:Oe=>Oe.preventDefault(),children:"Completed"})]})]}),o.jsxs(dt.Sub,{children:[o.jsxs(dt.SubTrigger,{children:["Tags",C&&o.jsx("span",{className:X("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(dt.SubContent,{children:[o.jsx(dt.CheckboxItem,{checked:!C,onCheckedChange:()=>E(null),onSelect:Oe=>Oe.preventDefault(),children:"All tags"}),he>0&&o.jsx(dt.CheckboxItem,{checked:C==="__untagged__",onCheckedChange:()=>E(C==="__untagged__"?null:"__untagged__"),onSelect:Oe=>Oe.preventDefault(),children:"Untagged"}),le.map(([Oe])=>o.jsx(dt.CheckboxItem,{checked:C===Oe,onCheckedChange:()=>E(C===Oe?null:Oe),onSelect:Pe=>Pe.preventDefault(),children:Oe},Oe))]})]}),be>0&&o.jsxs(o.Fragment,{children:[o.jsx(dt.Separator,{}),o.jsxs(dt.Item,{onSelect:()=>{E(null),A(!1),S(null)},children:[o.jsx(bs,{}),"Clear all filters"]})]})]})]}),be>0&&o.jsxs(ce,{variant:"outline",size:"md",onClick:()=>{E(null),A(!1),S(null)},children:[o.jsx(bs,{}),"Reset"]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[!I&&j.size>0&&o.jsxs(o.Fragment,{children:[o.jsx(e9t,{selectedCount:j.size,vocabulary:ae,onApplyTag:me,onRemoveTag:we,onNewTag:Oe=>me(Oe)}),o.jsxs(dt,{children:[o.jsx(dt.Trigger,{asChild:!0,children:o.jsxs(ce,{disabled:k,children:[k?o.jsx(Xt,{className:"h-4 w-4"}):o.jsx(qe,{size:"sm",children:o.jsx(Na,{})}),"Actions"]})}),o.jsxs(dt.Content,{align:"end",children:[o.jsxs(dt.Item,{onSelect:Ne,children:[o.jsx(qe,{size:"sm",children:o.jsx(lO,{})}),"Complete"]}),o.jsxs(dt.Item,{onSelect:Re,children:[o.jsx(qe,{size:"sm",children:o.jsx(uu,{})}),"Remove"]}),o.jsx(dt.Separator,{}),o.jsxs(dt.Item,{disabled:j.size===0,onSelect:()=>Y("selected"),children:[o.jsx(qe,{size:"sm",children:o.jsx(Eg,{})}),"Analyze selected"]}),o.jsxs(dt.Item,{disabled:he===0,onSelect:()=>Y("untagged"),children:[o.jsx(qe,{size:"sm",children:o.jsx(Eg,{})}),"Analyze untagged"]})]})]})]}),t&&oe.length>0&&!I&&o.jsxs(ce,{variant:"outline",size:"md",onClick:()=>{t(oe.map(Oe=>({input:Oe.input,output:Oe.output})))},children:[o.jsx(qe,{size:"sm",children:o.jsx(nm,{})}),"Create Scorer"]})]})]}),je?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(Xt,{className:"h-4 w-4"})}):xe.length===0?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsxs("div",{className:"px-8 text-center",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 block",children:I?"No completed reviews yet":"No items to review"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-2 block",children:I?"Items marked as complete will appear here for auditing.":"When you identify failures in experiment results, send them here to annotate, cluster, and create scorers from failure patterns."})]})}):o.jsxs(ve,{columns:"auto minmax(15rem,1fr) 10rem 8rem 6rem 6rem",className:"min-w-0",children:[o.jsxs(ve.Top,{hasLeadingCell:!0,children:[I?o.jsx(ve.TopCell,{children:" "}):o.jsx(ve.TopSelectCell,{checked:Me?!0:ue?"indeterminate":!1,onToggle:()=>se(),"aria-label":"Select all"}),o.jsxs(ve.TopCells,{colStart:2,children:[o.jsx(ve.TopCell,{children:"Input"}),o.jsx(ve.TopCell,{children:"Comment"}),o.jsx(ve.TopCell,{children:"Tags"}),o.jsx(ve.TopCell,{children:"Rating"}),o.jsx(ve.TopCell,{children:"Scores"})]})]}),xe.map(Oe=>{const Pe=Oe.scores?Object.entries(Oe.scores):[],Ue=x===Oe.id,Ke=o.jsxs(o.Fragment,{children:[o.jsx(ve.Cell,{height:"compact",className:"text-neutral4 min-w-0",children:o.jsx("span",{className:"block truncate",children:gts(Oe.input,80)})}),o.jsx(ve.Cell,{height:"compact",className:"min-w-0",children:Oe.comment?o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 truncate",children:Oe.comment}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsx(ve.Cell,{height:"compact",className:"min-w-0",children:Oe.tags.length>0?o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 truncate",children:Oe.tags.join(", ")}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsxs(ve.Cell,{height:"compact",children:[Oe.rating==="positive"&&o.jsx(qe,{size:"sm",className:"text-positive1",children:o.jsx(Ube,{})}),Oe.rating==="negative"&&o.jsx(qe,{size:"sm",className:"text-negative1",children:o.jsx(Bbe,{})}),!Oe.rating&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})]}),o.jsx(ve.Cell,{height:"compact",children:Pe.length>0?o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx(qe,{size:"sm",className:"text-neutral3",children:o.jsx(nm,{})}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 font-mono",children:Pe[0][1].toFixed(2)}),Pe.length>1&&o.jsxs(un,{variant:"default",children:["+",Pe.length-1]})]}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})})]});return o.jsxs(ve.RowWrapper,{children:[I?o.jsx(ve.Cell,{height:"compact",className:"justify-items-center px-4",children:o.jsx("div",{role:"img","aria-label":Oe.error?"Error":"Success",title:Oe.error?"Error":"Success",className:X("w-2 h-2 rounded-full",Oe.error?"bg-red-700":"bg-green-600")})}):o.jsx(ve.SelectCell,{checked:j.has(Oe.id),onToggle:()=>re(Oe.id),"aria-label":`Select item ${Oe.id}`}),o.jsx(ve.RowButton,{flushLeft:!0,colStart:2,featured:Ue,onClick:()=>Qe(Oe.id),children:Ke})]},Oe.id)})]})]}),Ze&&o.jsx(J8t,{item:Ze,isCompleted:I,tagVocabulary:ae,onRate:Oe=>s(Ze.id,Oe),onSetTags:Oe=>{r(Ze.id,Oe);for(const Pe of Oe)ae.includes(Pe)||de(Pe)},onComment:Oe=>a(Ze.id,Oe),onRemove:()=>i(Ze.id),onComplete:async()=>{await l(Ze.id),f()},onPrevious:Ce,onNext:Te,onClose:()=>S(null)})]})]})}function DKe({href:e,children:t}){return o.jsxs("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-inherit underline hover:text-white",children:[t,o.jsx(Sa,{className:"size-3"})]})}function nP({value:e,icon:t,label:n,badge:r,disabled:s,disabledReason:a}){const i=o.jsxs(o.Fragment,{children:[o.jsx(qe,{size:"sm",children:t}),o.jsx(ye,{variant:"ui-sm",className:"text-inherit",children:n}),r!==void 0&&r>0&&o.jsx("span",{className:"bg-accent1 ml-1 min-w-[18px] rounded-full px-1.5 py-0 text-center text-xs leading-[18px] font-medium text-white",children:r})]});return s?o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:o.jsx("span",{tabIndex:0,className:"inline-flex",children:o.jsx(Rr,{value:e,disabled:!0,className:"px-3 py-2.5",children:i})})}),a&&o.jsx(Rn,{side:"bottom",children:a})]}):o.jsx(Rr,{value:e,className:"px-3 py-2.5",children:i})}function yts({agentId:e,activeTab:t,showPlayground:n=!1,showObservability:r=!1,reviewBadge:s,rightSlot:a}){const{navigate:i}=yn(),l=n?void 0:o.jsxs("p",{children:["Configure ",o.jsx("code",{children:"@mastra/editor"})," to use the Editor."," ",o.jsx(DKe,{href:"https://mastra.ai/docs/editor/overview",children:"Learn more"})]}),c=r?void 0:o.jsxs("p",{children:["Add ",o.jsx("code",{children:"@mastra/observability"})," to enable this tab."," ",o.jsx(DKe,{href:"https://mastra.ai/docs/observability/overview",children:"Learn more"})]}),u={chat:`/agents/${e}/chat/new`,versions:`/agents/${e}/editor`,evaluate:`/agents/${e}/evaluate`,review:`/agents/${e}/review`,traces:`/agents/${e}/traces`},d=f=>{f!=="none"&&i(u[f])};return o.jsxs("div",{className:"flex min-w-0 items-center gap-2 p-1.5 max-lg:flex-wrap",children:[o.jsx(Dc,{value:t,defaultTab:t,onValueChange:d,className:"min-w-0 flex-1 max-lg:flex-auto",children:o.jsxs(Mc,{variant:"pill-ghost",children:[o.jsx(nP,{value:"chat",icon:o.jsx(dT,{}),label:"Chat"}),o.jsx(nP,{value:"versions",icon:o.jsx(Rbe,{}),label:"Editor",disabled:!n,disabledReason:l}),o.jsx(nP,{value:"evaluate",icon:o.jsx(pit,{}),label:"Evaluate",disabled:!r,disabledReason:c}),o.jsx(nP,{value:"review",icon:o.jsx(UV,{}),label:"Review",badge:s,disabled:!r,disabledReason:c}),o.jsx(nP,{value:"traces",icon:o.jsx(Mu,{}),label:"Traces",disabled:!r,disabledReason:c})]})}),a&&o.jsx("div",{className:"ml-auto flex items-center gap-2",children:a})]})}function bts({requestContextSchema:e}){return o.jsxs(Pf,{children:[o.jsx(Bd,{asChild:!0,children:o.jsxs(ce,{variant:"ghost",size:"sm",type:"button",tooltip:"Run options","data-testid":"agent-top-bar-run-options-trigger",children:[o.jsx(HV,{}),"Run options"]})}),o.jsx(Ud,{align:"end",className:"w-[min(760px,calc(100vw-2rem))] p-0",children:o.jsx(Z8t,{requestContextSchema:e})})]})}const Oz=({label:e,children:t})=>o.jsxs("div",{className:"space-y-2",children:[o.jsx(ye,{as:"p",variant:"ui-md",className:"text-neutral3",children:e}),t]});function xts(e,t){if(!e||O$t(e).toLowerCase()!=="anthropic")return!1;if(!t)return!0;const r=t.toLowerCase();return/[^0-9]4[.-]5/.test(r)||/[^0-9][5-9][.-]\d/.test(r)}function wts({provider:e,modelId:t,settings:n,setSettings:r}){const s=xts(e,t),a=v.useEffectEvent(()=>{r({...n,modelSettings:{...n?.modelSettings,topP:void 0}})}),i=e&&t?`${e}-${t}`:void 0,l=n?.modelSettings?.topP,c=n?.modelSettings?.temperature;return v.useEffect(()=>{s&&i&&(l===void 0||c===void 0||a())},[s,i,l,c]),{hasSamplingRestriction:s}}const Sts=({canEdit:e=!0})=>{const{settings:t,setSettings:n}=SEe(),[r,s]=v.useState(""),[a,i]=v.useState(!1),[l,c]=v.useState(null),u=Yx(),{handleCopy:d}=Vp({text:r}),f=JSON.stringify(t?.modelSettings?.providerOptions??{});v.useEffect(()=>{(async()=>{if(!dD(f)){c("Invalid JSON");return}const y=await sT(f);s(y)})()},[f]);const p=async()=>{if(c(null),!dD(r)){c("Invalid JSON");return}const g=await sT(r);s(g)},h=async()=>{try{c(null);const g=JSON.parse(r);n({...t,modelSettings:{...t?.modelSettings,providerOptions:g}}),i(!0),setTimeout(()=>{i(!1)},1e3)}catch(g){console.error("error",g),c("Invalid JSON")}},m="text-neutral3 hover:text-neutral6";return o.jsx(cc,{children:o.jsxs("div",{className:"@container/advanced",children:[o.jsxs("div",{className:"grid grid-cols-1 gap-2 pb-2 @xs/advanced:grid-cols-2",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"frequency-penalty",children:"Frequency Penalty"}),o.jsx(Cn,{id:"frequency-penalty",type:"number",step:"0.1",min:"-1",max:"1",readOnly:!e,value:t?.modelSettings?.frequencyPenalty??"",onChange:g=>n({...t,modelSettings:{...t?.modelSettings,frequencyPenalty:g.target.value?Number(g.target.value):void 0}})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"presence-penalty",children:"Presence Penalty"}),o.jsx(Cn,{id:"presence-penalty",type:"number",step:"0.1",min:"-1",max:"1",readOnly:!e,value:t?.modelSettings?.presencePenalty??"",onChange:g=>n({...t,modelSettings:{...t?.modelSettings,presencePenalty:g.target.value?Number(g.target.value):void 0}})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"top-k",children:"Top K"}),o.jsx(Cn,{id:"top-k",type:"number",readOnly:!e,value:t?.modelSettings?.topK||"",onChange:g=>n({...t,modelSettings:{...t?.modelSettings,topK:g.target.value?Number(g.target.value):void 0}})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"max-tokens",children:"Max Tokens"}),o.jsx(Cn,{id:"max-tokens",type:"number",readOnly:!e,value:t?.modelSettings?.maxTokens||"",onChange:g=>n({...t,modelSettings:{...t?.modelSettings,maxTokens:g.target.value?Number(g.target.value):void 0}})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"max-steps",children:"Max Steps"}),o.jsx(Cn,{id:"max-steps",type:"number",readOnly:!e,value:t?.modelSettings?.maxSteps||"",onChange:g=>n({...t,modelSettings:{...t?.modelSettings,maxSteps:g.target.value?Number(g.target.value):void 0}})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"max-retries",children:"Max Retries"}),o.jsx(Cn,{id:"max-retries",type:"number",readOnly:!e,value:t?.modelSettings?.maxRetries||"",onChange:g=>n({...t,modelSettings:{...t?.modelSettings,maxRetries:g.target.value?Number(g.target.value):void 0}})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"seed",children:"Seed"}),o.jsx(Cn,{id:"seed",type:"number",readOnly:!e,value:t?.modelSettings?.seed||"",onChange:g=>n({...t,modelSettings:{...t?.modelSettings,seed:g.target.value?Number(g.target.value):void 0}})})]})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx(ye,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"provider-options",children:"Provider Options"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:o.jsx("button",{type:"button",onClick:p,className:m,"aria-label":"Format Provider Options",children:o.jsx(qe,{children:o.jsx(Ey,{})})})}),o.jsx(Rn,{children:"Format the Provider Options JSON"})]}),o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:o.jsx("button",{type:"button",onClick:d,className:m,"aria-label":"Copy Provider Options",children:o.jsx(qe,{children:o.jsx(tm,{})})})}),o.jsx(Rn,{children:"Copy Provider Options"})]}),e&&o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:o.jsx("button",{type:"button",onClick:h,className:m,"aria-label":"Save Provider Options",children:o.jsx(qe,{children:a?o.jsx(fa,{}):o.jsx(jd,{})})})}),o.jsx(Rn,{children:a?"Saved":"Save Provider Options"})]})]})]}),o.jsx(Qu,{value:r,onChange:s,theme:u,extensions:[Rp],readOnly:!e,className:"h-dropdown-max-height overflow-scroll rounded-lg border bg-transparent p-2 shadow-sm transition-colors"}),l&&o.jsx(ye,{variant:"ui-md",className:"text-accent2",children:l})]})]})})},kts=({hasMemory:e,hasSubAgents:t,disabled:n})=>{const r=e&&t,s=n||!r,a=o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Np,{value:"network",id:"network",className:"text-neutral6",disabled:s}),o.jsx(Dt,{className:X("text-neutral6 text-ui-md",!r&&"text-neutral3! cursor-not-allowed"),htmlFor:"network",children:"Network"})]});if(r)return a;const i=[];return e||i.push("memory enabled"),t||i.push("at least one sub-agent"),o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:a}),o.jsx(Rn,{children:o.jsxs("p",{children:["Network is not available. Please make sure you have ",i.join(" and "),"."]})})]})},Ots=({supported:e,disabled:t})=>{const n=t||!e,r=o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Np,{value:"streamSubscription",id:"streamSubscription",className:"text-neutral6",disabled:n}),o.jsx(Dt,{className:X("text-neutral6 text-ui-md",!e&&"text-neutral3! cursor-not-allowed"),htmlFor:"streamSubscription",children:"Stream subscription (default)"})]});return e?r:o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:r}),o.jsx(Rn,{children:o.jsx("p",{children:"Stream subscription is not supported for this agent."})})]})},_ts=({agentId:e})=>{const{data:t,isLoading:n}=mc(e),{data:r,isLoading:s}=oC(e),{settings:a,setSettings:i,resetAll:l}=SEe(),{canEdit:c}=ul(),[u,d]=v.useState(!1),[f,p]=v.useState(!1),h=c("agents"),{hasSamplingRestriction:m}=wts({provider:t?.provider,modelId:t?.modelId,settings:a,setSettings:i});if(!n&&!t)return null;const g=!!r?.result,y=!!(t&&Object.keys(t.agents||{}).length>0),b=t?.modelVersion,x=b==="v2"||b==="v3",S=t?.supportsMemory!==!1;let k;t&&(x?a?.modelSettings?.chatWithNetwork?k="network":a?.modelSettings?.chatWithGenerate?k="generate":a?.modelSettings?.chatWithLegacyStream||!S?k="stream":k="streamSubscription":k=a?.modelSettings?.chatWithGenerateLegacy?"generateLegacy":"streamLegacy");const _=m&&(a?.modelSettings?.temperature!==void 0||a?.modelSettings?.topP!==void 0);return o.jsxs(o.Fragment,{children:[o.jsxs(Pf,{open:f,onOpenChange:(C,E)=>{if(!C&&u){E?.cancel?.();return}p(C)},children:[o.jsx(Bd,{asChild:!0,children:o.jsx(ce,{variant:"default",size:"icon-md",type:"button",tooltip:"Model settings","data-testid":"composer-model-settings-trigger",children:o.jsx(CGt,{className:"text-neutral3 hover:text-neutral6 h-5 w-5"})})}),o.jsx(Ud,{align:"start",className:"w-80 p-4",children:n||s?o.jsx(xt,{className:"h-40 w-full","data-testid":"composer-model-settings-skeleton"}):o.jsxs("section",{className:"@container space-y-5",children:[o.jsx(Oz,{label:"Chat Method",children:o.jsxs(bL,{value:k,disabled:!h,onValueChange:C=>h&&i({...a,modelSettings:{...a?.modelSettings,chatWithGenerateLegacy:C==="generateLegacy",chatWithGenerate:C==="generate",chatWithLegacyStream:C==="stream",chatWithNetwork:C==="network"}}),className:"flex flex-col gap-3",children:[!x&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Np,{value:"generateLegacy",id:"generateLegacy",className:"text-neutral6",disabled:!h}),o.jsx(Dt,{className:"text-neutral6 text-ui-md",htmlFor:"generateLegacy",children:"Generate (Legacy)"})]}),x&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Np,{value:"generate",id:"generate",className:"text-neutral6",disabled:!h}),o.jsx(Dt,{className:"text-neutral6 text-ui-md",htmlFor:"generate",children:"Generate"})]}),!x&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Np,{value:"streamLegacy",id:"streamLegacy",className:"text-neutral6",disabled:!h}),o.jsx(Dt,{className:"text-neutral6 text-ui-md",htmlFor:"streamLegacy",children:"Stream (Legacy)"})]}),x&&o.jsx(Ots,{supported:S,disabled:!h}),x&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Np,{value:"stream",id:"stream",className:"text-neutral6",disabled:!h}),o.jsx(Dt,{className:"text-neutral6 text-ui-md",htmlFor:"stream",children:"Stream"})]}),x&&o.jsx(kts,{hasMemory:g,hasSubAgents:y,disabled:!h})]})}),o.jsx(Oz,{label:"Require Tool Approval",children:o.jsx(zo,{checked:a?.modelSettings?.requireToolApproval,disabled:!h,onCheckedChange:C=>h&&i({...a,modelSettings:{...a?.modelSettings,requireToolApproval:C}})})}),_&&o.jsxs("div",{className:"text-neutral3 bg-surface3 flex items-center gap-2 rounded px-3 py-2 text-xs","data-testid":"sampling-restriction-banner",children:[o.jsx(Bx,{className:"h-3.5 w-3.5 shrink-0"}),o.jsx("span",{children:a?.modelSettings?.temperature!==void 0?"Claude 4.5+ models only accept Temperature OR Top P. Clear Temperature to use Top P.":"Claude 4.5+ models only accept Temperature OR Top P. Setting Temperature will clear Top P."})]}),o.jsx(Oz,{label:"Temperature",children:o.jsxs("div",{className:"flex flex-row items-center justify-between gap-2",children:[o.jsx(MU,{value:[a?.modelSettings?.temperature??-.1],max:1,min:-.1,step:.1,disabled:!h,onValueChange:C=>h&&i({...a,modelSettings:{...a?.modelSettings,temperature:C[0]<0?void 0:C[0]}})}),o.jsx(ye,{as:"p",variant:"ui-sm",className:"text-neutral3",children:a?.modelSettings?.temperature??"n/a"})]})}),o.jsx(Oz,{label:"Top P",children:o.jsxs("div",{className:"flex flex-row items-center justify-between gap-2",children:[o.jsx(MU,{disabled:!h,onValueChange:C=>h&&i({...a,modelSettings:{...a?.modelSettings,topP:C[0]<0?void 0:C[0]}}),value:[a?.modelSettings?.topP??-.1],max:1,min:-.1,step:.1}),o.jsx(ye,{as:"p",variant:"ui-sm",className:"text-neutral3",children:a?.modelSettings?.topP??"n/a"})]})}),o.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[o.jsx(ce,{variant:"ghost",size:"sm",type:"button",disabled:!h,onClick:()=>h&&l(),children:"Reset"}),o.jsx(ce,{variant:"default",size:"sm",type:"button",disabled:!h,onClick:()=>d(!0),children:"Advanced Settings"})]})]})})]}),o.jsx(br,{open:u,onOpenChange:d,children:o.jsxs(xr,{className:"sm:max-w-xl",children:[o.jsx(wr,{children:o.jsx(gr,{children:"Advanced model settings"})}),o.jsx($r,{children:o.jsx(Sts,{canEdit:h})})]})})]})},LKe="lk.agent.state",Cts="lk.transcription",Ets="lk.transcription_final";function jts(e,t,n,r,s){return(e.find(l=>l.id===t)?e.map(l=>l.id===t?{...l,text:l.text+r,final:l.final||s}:l):[...e,{id:t,role:n,text:r,final:s}]).slice(-20)}const Tts=({agentId:e,threadId:t,onCallStarted:n})=>{const{baseUrl:r,headers:s}=Kq(),a=Ur(),i=v.useRef(n);v.useEffect(()=>{i.current=n},[n]);const[l,c]=v.useState("idle"),[u,d]=v.useState("initializing"),[f,p]=v.useState([]),h=v.useRef(null),m=v.useRef(null),g=v.useRef(null),y=v.useRef(0),b=v.useRef(null),x=v.useCallback(()=>{t&&a.invalidateQueries({queryKey:["memory","messages",t]}),e&&a.invalidateQueries({queryKey:["memory","threads",e,e]})},[e,a,t]),S=v.useCallback(()=>{g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{g.current=null,x()},600)},[x]),k=v.useCallback(()=>{y.current+=1,b.current?.abort(),b.current=null;const E=h.current;h.current=null,E&&E.disconnect(),g.current&&(clearTimeout(g.current),g.current=null),m.current=null,c("idle"),d("initializing")},[]);v.useEffect(()=>k,[k]);const _=v.useCallback(()=>{k(),p([]),x()},[k,x]),C=v.useCallback(async()=>{if(l!=="idle")return;const E=y.current+=1,j=new AbortController;b.current=j;const N=()=>y.current!==E;c("connecting"),p([]);try{const I=await fetch(`${r}/voice/livekit/connection-details`,{method:"POST",headers:{...s,"content-type":"application/json"},body:JSON.stringify({agentId:e,threadId:t,resourceId:e}),signal:j.signal});if(N())return;if(!I.ok){const F=await I.json().catch(()=>({}));throw new Error(F.error??"LiveKit voice is not configured for this server. Add liveKitConnectionRoute() to server.apiRoutes and run a voice worker.")}const A=await I.json();if(N())return;const{Room:R,RoomEvent:L,Track:D}=await mo(async()=>{const{Room:F,RoomEvent:z,Track:q}=await import("./livekit-client.esm-CKIgC2IJ.js");return{Room:F,RoomEvent:z,Track:q}},[],import.meta.url);if(N())return;const B=new R;h.current=B;const H=new Audio;if(H.autoplay=!0,m.current=H,B.on(L.TrackSubscribed,F=>{F.kind===D.Kind.Audio&&m.current&&F.attach(m.current)}),B.on(L.ParticipantAttributesChanged,(F,z)=>{const q=F[LKe]??z.attributes[LKe];q&&z.identity!==A.participantName&&d(q)}),B.on(L.Disconnected,()=>{h.current===B&&k()}),B.registerTextStreamHandler(Cts,async(F,z)=>{const q=z.identity===A.participantName?"user":"agent",M=F.info.attributes?.[Ets]==="true";for await(const G of F)p(V=>jts(V,F.info.id,q,G,M));q==="agent"&&S()}),await B.connect(A.serverUrl,A.participantToken),N()){B.disconnect(),h.current===B&&(h.current=null);return}if(await B.localParticipant.setMicrophoneEnabled(!0),N()){B.disconnect(),h.current===B&&(h.current=null);return}c("active"),x(),await Promise.resolve(i.current?.()).catch(()=>{})}catch(I){if(j.signal.aborted||N())return;k(),nu.error(I instanceof Error?I.message:"Failed to start the voice call.")}},[e,r,k,s,x,S,l,t]);return{status:l,agentState:u,captions:f,start:()=>{C()},stop:_}},Nts=({voiceCall:e})=>e.status==="idle"?o.jsx(ce,{variant:"default",size:"icon-md",type:"button",tooltip:"Start voice call","data-testid":"voice-call-button",onClick:()=>e.start(),children:o.jsx(QZt,{className:"text-neutral3 hover:text-neutral6 h-5 w-5"})}):e.status==="connecting"?o.jsx(ce,{variant:"default",size:"icon-md",type:"button",tooltip:"Connecting…","data-testid":"voice-call-button",children:o.jsx(ia,{className:"text-neutral3 h-5 w-5 animate-spin"})}):o.jsx(ce,{variant:"default",size:"icon-md",type:"button",tooltip:"End voice call","data-testid":"voice-call-button",onClick:()=>e.stop(),children:o.jsx(ZZt,{className:"h-5 w-5 text-red-500"})}),Its={initializing:"Connecting…",listening:"Listening…",thinking:"Thinking…",speaking:"Speaking…"},FKe=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(e[n]?.role===t)return e[n]},Ats=({voiceCall:e})=>{if(e.status==="idle")return null;const t=FKe(e.captions,"user"),n=FKe(e.captions,"agent"),r=e.status==="connecting"?"Connecting…":Its[e.agentState];return o.jsxs("div",{"data-testid":"voice-call-panel",className:"border-border2/40 bg-surface3 mx-auto mb-2 w-full max-w-3xl rounded-[16px] border px-4 py-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:X("h-2 w-2 rounded-full",e.status==="connecting"&&"bg-neutral3",e.status==="active"&&e.agentState==="speaking"&&"bg-accent1 animate-pulse",e.status==="active"&&e.agentState!=="speaking"&&"bg-green-500")}),o.jsx("span",{className:"text-ui-sm text-neutral4",children:r})]}),t&&o.jsx("p",{className:"text-ui-sm text-neutral3 mt-2 truncate","data-testid":"voice-caption-user",children:t.text}),n&&o.jsx("p",{className:"text-ui-sm text-neutral6 mt-1","data-testid":"voice-caption-agent",children:n.text})]})},Rts=300,Pts=(e,t)=>{const[n,r]=v.useState(!1);return v.useEffect(()=>{if(!e){r(!1);return}const s=setTimeout(()=>r(!0),t);return()=>clearTimeout(s)},[e,t]),n},$ts=e=>e?e.content.parts.some(n=>{if(n.type==="reasoning"||n.type==="text")return"state"in n&&n.state==="streaming";if(n.type==="tool-invocation")return"toolInvocation"in n&&n.toolInvocation.state!=="result";if(n.type==="dynamic-tool"||n.type.startsWith("tool-")){const r="state"in n?n.state:void 0;return r!=="output-available"&&r!=="output-error"}return!1}):!1,Mts=({turns:e})=>e.length===0?null:o.jsx("div",{"data-testid":"thread-rail-layer",className:"thread-rail-layer pointer-events-none absolute inset-y-0 left-4 z-20",children:o.jsx(P6r,{turns:e,className:"pointer-events-auto sticky top-1/2 -translate-y-1/2"})}),Dts=({agentName:e,agentId:t,threadId:n,hasModelList:r,hideModelSwitcher:s,runOptionsSlot:a,refreshThreadList:i})=>{const l=v.useRef(null),c=v.useRef(null);Dwe(l,{enabled:!0});const u=X5r(),{isRunning:d}=DMt(),{requestContext:f}=_s(),{isSpeaking:p,readAloud:h,stop:m}=mFr(t,f),{hasSession:g,viewMode:y}=j4(),b=g&&(y==="collapsed"||y==="expanded"),x=u.length===0,S=u[u.length-1],k=d&&(S?.role!=="assistant"||!$ts(S)),_=Pts(k,Rts),C=v.useMemo(()=>W6r(u),[u]),E=v.useMemo(()=>new Set(C.map(j=>j.messageId)),[C]);return o.jsx(rFr,{children:o.jsx(N6r,{children:o.jsxs("div",{className:"group/thread grid h-full grid-rows-[1fr_auto] overflow-y-auto","data-testid":"thread-wrapper",children:[o.jsxs(eDt,{children:[o.jsx(tDt,{ref:l,className:"h-full overflow-y-scroll",style:{overflowAnchor:"none"},children:x?o.jsx(Lts,{agentName:e}):o.jsxs("div",{"data-testid":"thread-rail-container",className:"thread-rail-container relative min-h-full",children:[o.jsx(Mts,{turns:C}),o.jsxs("div",{ref:c,"data-testid":"thread-message-column",className:"relative mx-auto w-full max-w-3xl px-4 pb-7 group-has-[[data-attachments-row]]/thread:pb-24",children:[o.jsx(gFr,{containerRef:c}),o.jsxs(nDt,{className:"flex flex-col gap-6 py-6",children:[u.map(j=>{const N=aDt(j);return o.jsx(rDt,{messageId:j.id,scrollAnchor:E.has(j.id),children:o.jsx(Nzt,{message:j,hasModelList:r,isSpeaking:p,onReadAloud:h,onStopSpeaking:m})},N)}),_&&o.jsx(kPt,{})]}),!d&&o.jsx(kFr,{})]})]})}),o.jsx(sDt,{className:"z-30"})]}),b&&t&&n&&o.jsx("div",{className:"mx-auto mb-2 w-full max-w-3xl px-4",children:o.jsx(o$t,{agentName:e})}),o.jsx(yQr,{}),o.jsx(Fts,{agentId:t,threadId:n,hasModelList:r,hideModelSwitcher:s,runOptionsSlot:a,refreshThreadList:i})]})})})},Lts=({agentName:e})=>o.jsxs("div",{className:"flex w-full grow flex-col items-center pt-[15vh]",children:[o.jsx(u_,{name:e||"Agent",size:"lg"}),o.jsx("p",{className:"mt-4 font-medium",children:"How can I help you today?"})]}),Fts=({agentId:e,threadId:t,hasModelList:n,hideModelSwitcher:r,runOptionsSlot:s,refreshThreadList:a})=>{const{threadInput:i,setThreadInput:l}=mMt(t),c=v.useRef(null),u=LMt(),{attachments:d,toCoreUserMessages:f,clear:p}=TZ(),{isRunning:h,canSendWhileStreaming:m,cancelRun:g}=DMt(),[y,b]=v.useState(0),{canExecute:x}=ul(),S=x("agents"),k=Tts({agentId:e,threadId:t,onCallStarted:a}),_=i.trim().length===0&&d.length===0,C=h&&!m,E=async()=>{if(_||C||!S)return;const j=d.length>0?await f():void 0,N=i;l(""),p(),b(I=>I+1),u({message:N,attachments:j})};return o.jsxs("div",{className:"relative",style:{viewTransitionName:"agent-chat-composer"},children:[o.jsx(Ats,{voiceCall:k}),o.jsxs(HMt,{className:"relative px-2 pb-2",onSubmit:j=>{j.preventDefault(),E()},children:[o.jsx(ZMt,{children:o.jsx(hFr,{})}),o.jsxs(WMt,{sendingPulseKey:y,children:[o.jsx(GMt,{ref:c,value:i,autoFocus:!1,placeholder:S?"Enter your message...":"You don't have permission to execute agents",onChange:j=>{l(j.target.value)},onKeyDown:j=>{if(!(j.nativeEvent.isComposing||j.keyCode===229)&&j.key==="Enter"&&!j.shiftKey){if(C)return;j.preventDefault(),j.stopPropagation(),E()}},disabled:!S}),e&&!n&&!r&&o.jsx(YKr,{}),o.jsx(QMt,{children:o.jsx(Bts,{canExecute:S,agentId:e,runOptionsSlot:s,showModelSwitcher:!!(e&&!n&&!r),isEmpty:_,isRunning:h,canSendWhileStreaming:m,onCancel:()=>{g()},onSetText:j=>{l(j)},voiceCall:k})})]})]})]})},zts=({agentId:e,onTranscript:t})=>{const{requestContext:n}=_s(),{start:r,stop:s,isListening:a,transcript:i}=Gxn({agentId:e,requestContext:n});return v.useEffect(()=>{i&&v.startTransition(()=>t(i))},[t,i]),o.jsx(ce,{variant:"default",size:"icon-md",type:"button",tooltip:a?"Stop dictation":"Start dictation",onClick:()=>a?s():r(),children:a?o.jsx(cbe,{}):o.jsx(yZt,{className:"text-neutral3 hover:text-neutral6 h-5 w-5"})})},Bts=({canExecute:e=!0,agentId:t,showModelSwitcher:n,runOptionsSlot:r,isEmpty:s,isRunning:a,canSendWhileStreaming:i,onCancel:l,onSetText:c,voiceCall:u})=>o.jsxs(o.Fragment,{children:[(n&&t||r)&&o.jsxs("div",{className:"flex max-w-full shrink-0 items-center gap-1.5",children:[n&&t&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"bg-surface3 border-border1 duration-normal focus-within:border-border2 rounded-full border transition-colors",children:o.jsx(QKr,{})}),o.jsx(_ts,{agentId:t})]}),r]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[o.jsxs(Mr,{spacing:"close",children:[e&&o.jsx(sFr,{}),e&&o.jsx(zts,{agentId:t,onTranscript:c}),e&&t&&u&&o.jsx(Nts,{voiceCall:u})]}),o.jsx(Uts,{canExecute:e,isEmpty:s,isRunning:a,canSendWhileStreaming:i,onCancel:l})]})]}),Uts=({canExecute:e=!0,isEmpty:t,isRunning:n,canSendWhileStreaming:r,onCancel:s})=>n&&!r?o.jsx(ce,{variant:"default",size:"icon-md",type:"button",tooltip:"Cancel",onClick:s,children:o.jsx(cbe,{})}):o.jsxs(o.Fragment,{children:[o.jsx(ce,{type:"submit",variant:"default",size:"icon-md",tooltip:e?"Send":"No permission to execute",className:"border-border1 bg-surface5 rounded-full border",disabled:!e||t,children:o.jsx(jD,{className:"text-neutral3 hover:text-neutral6 h-6 w-6"})}),n&&o.jsx(ce,{variant:"default",size:"icon-md",type:"button",tooltip:"Cancel",onClick:s,children:o.jsx(cbe,{})})]}),cbe=()=>o.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-neutral3 hover:text-neutral6",children:[o.jsx("circle",{cx:"12",cy:"12",r:"10"}),o.jsx("rect",{width:"6",height:"6",x:"9",y:"9",rx:"1"})]}),MNe=({agentId:e,agentName:t,threadId:n,memory:r,refreshThreadList:s,modelVersion:a,agentVersionId:i,supportsMemory:l,modelList:c,messageId:u,isNewThread:d,hideModelSwitcher:f,runOptionsSlot:p})=>{const{settings:h}=SEe(),m=zl(),{data:g,isLoading:y}=HH({agentId:e,threadId:d?void 0:n,memory:r??!1});v.useEffect(()=>{u&&g&&!y&&setTimeout(()=>{const S=document.querySelector(`[data-message-id="${u}"]`);S&&(S.scrollIntoView({behavior:"smooth",block:"center"}),S.classList.add("bg-surface4"),setTimeout(()=>{S.classList.remove("bg-surface4")},2e3))},100)},[u,g,y]);const b=v.useRef({threadId:n,messages:[]});b.current.threadId!==n&&(b.current={threadId:n,messages:[]});const x=g?.messages??b.current.messages;return o.jsx(g6r,{agentId:e,agentName:t,modelVersion:a,agentVersionId:i,supportsMemory:l,threadId:n,initialMessages:x,refreshThreadList:s,settings:h,requestContext:m,children:o.jsx(Dts,{agentName:t??"",agentId:e,threadId:n,hasModelList:!!c,hideModelSwitcher:f,refreshThreadList:s,runOptionsSlot:p})})};function Vts({agentId:e,view:t}){const n=qs(),r=qo(),{data:s}=mc(e),{canCreateAgent:a}=ARt(),{Link:i,paths:l}=yn(),c=(window.MASTRA_STUDIO_BASE_PATH??"").replace(/\/$/,""),u=`${window.location.origin}${c}/agents/${encodeURIComponent(e)}/session`,{handleCopy:d,isCopied:f}=Vp({text:u,copyMessage:"Session URL copied to clipboard!"}),p=s?.source==="stored",h=l.cmsAgentEditLink(e),m=a&&p&&!!h,g=()=>{if(t==="chat"){n(`/agents/${e}/settings`,{state:{from:`${r.pathname}${r.search}`},viewTransition:!0});return}const y=r.state?.from;n(y??`/agents/${e}/chat/new`,{viewTransition:!0})};return o.jsx(cc,{children:o.jsxs("div",{className:"flex items-center justify-between gap-2 pr-3 max-lg:py-2",style:{viewTransitionName:"agent-view-header"},children:[o.jsx("div",{className:"min-w-0 flex-1 max-lg:hidden",children:o.jsx(ZKr,{agentId:e})}),o.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-2",children:[m&&o.jsxs(ce,{variant:"outline",size:"sm",as:i,to:h,children:[o.jsx(qe,{size:"sm",children:o.jsx(rm,{})}),"Edit"]}),o.jsx(ce,{variant:"default",type:"button",onClick:d,tooltip:"Copy session URL to share with your team","data-testid":"agent-entity-header-share",children:f?o.jsx(fa,{className:"text-neutral3 h-4 w-4"}):o.jsx(yit,{className:"text-neutral3 hover:text-neutral6 h-4 w-4"})}),o.jsx(ce,{variant:"default",type:"button",onClick:g,"data-testid":"agent-view-header-toggle",children:t==="chat"?o.jsxs(o.Fragment,{children:[o.jsx(WV,{className:"text-neutral3 h-4 w-4"})," Settings"]}):o.jsxs(o.Fragment,{children:[o.jsx(bs,{className:"text-neutral3 h-4 w-4"})," Close"]})})]})]})})}function qts({agentId:e,view:t,leftSlot:n,leftDrawerLabel:r,browserOverlay:s,children:a}){return o.jsx(_Ne,{agentId:e,leftDrawerLabel:r,leftSlot:n,browserOverlay:s,children:o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[o.jsx(Vts,{agentId:e,view:t}),a]})})}function Hts({agentId:e,view:t}){return o.jsx(_Ne,{agentId:e,leftDrawerLabel:"Open threads and memory",leftSlot:o.jsx(n9t,{}),children:o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_1fr]","data-testid":"agent-route-skeleton","aria-busy":"true",children:[o.jsx(Wts,{}),o.jsx("div",{className:"min-h-0 overflow-hidden",children:t==="settings"?o.jsx(Zts,{}):o.jsx(r9t,{})})]})})}function Wts(){return o.jsxs("div",{className:"flex items-center justify-between gap-2 pr-3 max-lg:py-2",children:[o.jsx("div",{className:"min-w-0 flex-1 max-lg:hidden",children:o.jsxs("div",{className:"flex min-w-0 items-center gap-2 p-3",children:[o.jsx(xt,{className:"size-7 shrink-0 rounded-full"}),o.jsx(xt,{className:"h-4 w-36"})]})}),o.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-2",children:[o.jsx(xt,{className:"h-9 w-9 rounded-lg"}),o.jsx(xt,{className:"h-9 w-24 rounded-lg"})]})]})}function n9t(){return o.jsxs(MEe,{children:[o.jsx("div",{className:"min-h-0 flex-1 p-1","data-testid":"agent-route-sidebar-skeleton",children:o.jsxs("div",{className:"flex h-full w-full flex-col",children:[o.jsxs(rP,{children:[o.jsx(xt,{className:"h-4 w-4 shrink-0 rounded"}),o.jsx(xt,{className:"h-3 w-16"})]}),o.jsx("hr",{"aria-hidden":"true",className:"bg-border1/40 -mx-1 my-1 h-px border-0"}),o.jsxs("div",{className:"flex flex-col gap-px",children:[o.jsx(rP,{children:o.jsx(xt,{className:"h-3 w-32"})}),o.jsx(rP,{children:o.jsx(xt,{className:"h-3 w-24"})}),o.jsx(rP,{children:o.jsx(xt,{className:"h-3 w-36"})}),o.jsx(rP,{children:o.jsx(xt,{className:"h-3 w-28"})})]})]})}),o.jsxs("div",{className:"rounded-studio-panel border-border1/40 bg-surface4 m-2 border px-3 py-2.5",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[o.jsx(xt,{className:"h-4 w-4 shrink-0 rounded"}),o.jsx(xt,{className:"h-4 w-20"})]}),o.jsx(xt,{className:"h-4 w-4 shrink-0 rounded"})]}),o.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[o.jsx(xt,{className:"h-3 w-20 rounded-full"}),o.jsx(xt,{className:"h-3 w-24 rounded-full"})]})]})]})}function rP({children:e}){return o.jsx("div",{className:"flex h-9 w-full min-w-0 items-center gap-2 rounded-xl px-3",children:e})}function r9t(){return o.jsx("div",{className:"grid h-full min-h-0 w-full overflow-hidden px-4 py-6 md:px-10",children:o.jsxs("div",{className:"mx-auto grid h-full min-h-0 w-full max-w-[80ch] grid-rows-[1fr_auto]",children:[o.jsxs("div",{className:"min-h-0 space-y-4 overflow-hidden pt-6",children:[o.jsx("div",{className:"flex justify-start",children:o.jsx(xt,{className:"h-10 w-2/3 rounded-2xl"})}),o.jsx("div",{className:"flex justify-end",children:o.jsx(xt,{className:"h-12 w-3/5 rounded-2xl"})}),o.jsx("div",{className:"flex justify-start",children:o.jsxs("div",{className:"w-4/5 space-y-2",children:[o.jsx(xt,{className:"h-4 w-full rounded-full"}),o.jsx(xt,{className:"h-4 w-5/6 rounded-full"}),o.jsx(xt,{className:"h-4 w-2/3 rounded-full"})]})})]}),o.jsxs("div",{className:"border-border1 bg-surface2 rounded-3xl border px-3 py-2.5",children:[o.jsx(xt,{className:"h-5 w-1/2 rounded-full"}),o.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[o.jsx(xt,{className:"h-8 w-24 rounded-full"}),o.jsx(xt,{className:"h-8 w-8 rounded-full"})]})]})]})})}function Zts(){return o.jsxs("div",{className:"h-full w-full min-w-0","data-testid":"agent-settings-skeleton","aria-busy":"true",children:[o.jsx("div",{className:"sticky top-0 z-10 px-3 py-1.5",children:o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(xt,{className:"h-9 w-24 rounded-full"}),o.jsx(xt,{className:"h-9 w-24 rounded-full"}),o.jsx(xt,{className:"h-9 w-28 rounded-full"})]})}),o.jsxs("div",{className:"space-y-4 p-4",children:[o.jsx(xt,{className:"h-28 w-full rounded-lg"}),o.jsx(xt,{className:"h-36 w-full rounded-lg"}),o.jsx(xt,{className:"h-24 w-5/6 rounded-lg"})]})]})}const zKe="1fr auto auto",Gts=({agentId:e})=>{const{data:t,isLoading:n}=sZ(),[r,s]=v.useState("");return!n&&(!t||t.length===0)?o.jsx(lr,{children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral6",children:"No channel platforms configured."})}):o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx($f,{onSearch:s,label:"Filter channels",placeholder:"Filter by platform name"})})}),o.jsx(Qts,{platforms:t??[],isLoading:n,agentId:e,search:r})]})};function Qts({platforms:e,isLoading:t,agentId:n,search:r}){const s=v.useMemo(()=>{const a=r.toLowerCase();return e.filter(i=>i.name.toLowerCase().includes(a))},[e,r]);return t?o.jsx(ol,{columns:zKe}):o.jsxs(ve,{columns:zKe,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{className:"",children:"Platform"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Status"}),o.jsx(ve.TopCell,{className:"",children:""})]}),s.length===0&&r?o.jsx(ve.NoMatch,{message:"No channels match your search"}):null,s.map(a=>o.jsx(Yts,{platform:a,agentId:n},a.id))]})}function Yts({platform:e,agentId:t}){const{data:n,isLoading:r}=JRt(e.id,t),{connect:s,isConnecting:a}=wCe(e.id),{mutate:i,isPending:l}=ePt(e.id),c=n?.find(f=>f.status==="active"),u=()=>{s(t)},d=()=>{i(t,{onError:f=>{Le.error(f.body?.error||f.message||"Failed to disconnect channel")}})};return o.jsxs(ve.RowStatic,{children:[o.jsx(ve.Cell,{className:"text-neutral4 text-left",children:o.jsxs("span",{className:"flex min-w-0 items-center gap-3",children:[o.jsx(QCe,{platform:e.id,className:"h-5 w-5 shrink-0"}),o.jsxs("span",{className:"flex min-w-0 flex-col",children:[o.jsx("span",{className:"truncate",children:e.name}),c?o.jsx(ye,{variant:"ui-xs",className:"text-neutral5 truncate",children:c.displayName||"Workspace"}):null]})]})}),o.jsx(ve.Cell,{className:"flex justify-end",children:r?null:c?o.jsx(bg,{variant:"success",size:"sm",children:"Connected"}):e.isConfigured?null:o.jsx(bg,{variant:"warning",size:"sm",children:"Not configured"})}),o.jsx(ve.Cell,{className:"justify-end text-right",children:r?null:c?o.jsx("button",{type:"button",onClick:d,disabled:l,className:"text-neutral5 hover:text-accent2 shrink-0 text-[11px] transition-colors disabled:opacity-50",children:l?"Removing...":"Remove"}):e.isConfigured?o.jsx(ce,{size:"sm",variant:"default",onClick:u,disabled:a,children:a?"Connecting...":"Connect"}):null})]})}const BKe=e=>e===void 0?"Default":typeof e=="number"?`${e.toLocaleString()} tokens`:`${e.min.toLocaleString()}-${e.max.toLocaleString()} tokens`,Kts={success:"bg-green-500/20 text-green-400",info:"bg-blue-500/20 text-blue-400",warning:"bg-yellow-500/20 text-yellow-400"};function Xts({value:e,badge:t}){return typeof e=="boolean"?o.jsx("span",{className:X("text-xs font-medium px-2 py-0.5 rounded",e?t==="info"?"dark:bg-blue-500/20 dark:text-blue-400 bg-blue-500/10 text-blue-600":"dark:bg-green-500/20 dark:text-green-400 bg-green-500/10 text-green-600":"dark:bg-red-500/20 dark:text-red-400 bg-red-500/10 text-red-600"),children:e?"Yes":"No"}):t?o.jsx("span",{className:X("text-xs font-medium px-2 py-0.5 rounded",Kts[t]),children:e}):o.jsx("span",{className:"text-neutral3 text-xs",children:e})}const Jts=({agentId:e})=>{const{data:t,isLoading:n}=lC(e),[r,s]=v.useState(new Set(["General","Semantic Recall"])),a=t?.config,i=v.useMemo(()=>{if(!a)return[];const c=!!a,u=[{title:"General",items:[{label:"Memory Enabled",value:c,badge:c?"success":void 0},{label:"Last Messages",value:a.lastMessages||0},{label:"Auto-generate Titles",value:!!a.generateTitle,badge:a.generateTitle?"info":void 0}]}];if(a.semanticRecall){const h=!!a.semanticRecall,m=typeof a.semanticRecall=="object"?a.semanticRecall:{};u.push({title:"Semantic Recall",items:[{label:"Enabled",value:h,badge:h?"success":void 0},...h?[{label:"Scope",value:m.scope||"resource"},{label:"Top K Results",value:m.topK||4},{label:"Message Range",value:typeof m.messageRange=="object"?`${m.messageRange.before||1} before, ${m.messageRange.after||1} after`:m.messageRange!==void 0?`${m.messageRange} before, ${m.messageRange} after`:"1 before, 1 after"}]:[]]})}const d=a.observationalMemory,f=d!==null&&typeof d=="object";if(d===!0||f&&d.enabled!==!1){const h=f?d.observationModel||d.model||d.observation?.model:void 0,m=f?d.reflectionModel||d.model||d.reflection?.model:void 0;u.push({title:"Observational Memory",items:[{label:"Enabled",value:!0,badge:"success"},{label:"Scope",value:f&&d.scope||"thread"},{label:"Message Tokens",value:BKe(f?d.observation?.messageTokens:void 0)},{label:"Observation Tokens",value:BKe(f?d.reflection?.observationTokens:void 0)},...h?[{label:"Observation Model",value:String(h)}]:[],...m?[{label:"Reflection Model",value:String(m)}]:[]]})}return u},[a]),l=c=>{const u=new Set(r);u.has(c)?u.delete(c):u.add(c),s(u)};return n?o.jsx("div",{className:"p-4",children:o.jsx(xt,{className:"h-32 w-full"})}):!a||i.length===0?o.jsxs("div",{className:"p-4",children:[o.jsx("h3",{className:"text-neutral5 mb-3 text-sm font-medium",children:"Memory Configuration"}),o.jsx("p",{className:"text-neutral3 text-xs",children:"No memory configuration available"})]}):o.jsxs("div",{className:"p-4",children:[o.jsx("h3",{className:"text-neutral5 mb-3 text-sm font-medium",children:"Memory Configuration"}),o.jsx("div",{className:"space-y-2",children:i.map(c=>o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border",children:[o.jsxs("button",{type:"button",onClick:()=>l(c.title),className:"hover:bg-surface4 flex w-full items-center justify-between rounded-t-lg px-3 py-2 transition-colors",children:[o.jsx("span",{className:"text-neutral5 text-xs font-medium",children:c.title}),r.has(c.title)?o.jsx(Na,{className:"text-neutral3 h-3 w-3"}):o.jsx(pa,{className:"text-neutral3 h-3 w-3"})]}),r.has(c.title)&&o.jsx("div",{className:"space-y-1 px-3 pb-2",children:c.items.map(u=>o.jsxs("div",{className:"flex items-center justify-between py-1",children:[o.jsx("span",{className:"text-neutral3 text-xs",children:u.label}),o.jsx(Xts,{value:u.value??"",badge:u.badge})]},`${c.title}-${u.label}`))})]},c.title))})]})},ens=(e,t)=>e==="memory"?"memory":e==="channels"&&t?"channels":"overview";function tns({agentId:e}){const[t,n]=Ri(),{data:r}=sZ(),s=!!r?.length,a=ens(t.get("tab"),s),i=l=>{n(l==="overview"?{}:{tab:l},{replace:!0})};return o.jsx("div",{className:"h-full w-full min-w-0","data-testid":"agent-settings-view",style:{viewTransitionName:"agent-settings-view"},children:o.jsx(Br,{className:"h-full w-full",viewPortClassName:"h-full",mask:{top:!1},children:o.jsxs(Dc,{value:a,defaultTab:"overview",onValueChange:i,children:[o.jsx("div",{className:"sticky top-0 z-10 px-3 py-1.5",children:o.jsxs(Mc,{variant:"pill-ghost",children:[o.jsxs(Rr,{value:"overview",children:[o.jsx(qe,{size:"sm",children:o.jsx(HV,{})}),"General"]}),o.jsxs(Rr,{value:"memory",children:[o.jsx(qe,{size:"sm",children:o.jsx(Mv,{})}),"Memory"]}),s&&o.jsxs(Rr,{value:"channels",children:[o.jsx(qe,{size:"sm",children:o.jsx(kit,{})}),"Channels"]})]})}),o.jsx(Xr,{value:"overview",children:o.jsx(LKr,{agentId:e})}),o.jsx(Xr,{value:"memory",children:o.jsx(Jts,{agentId:e})}),s&&o.jsx(Xr,{value:"channels",children:o.jsx(Gts,{agentId:e})})]})})})}const nns=typeof document<"u"&&"startViewTransition"in document;function uae({view:e="chat"}){const{agentId:t,threadId:n}=Sr(),[r]=Ri(),{data:s,isLoading:a,error:i}=mc(t),{data:l}=oC(t),c=qs(),u=e==="settings",d=n==="new",f=v.useMemo(()=>xo(),[n]),p=!!l?.result,{data:h,isLoading:m,refetch:g}=Y$t({agentId:t,isMemoryEnabled:p,resourceId:t}),y=v.useMemo(()=>(h||[]).map(_=>({..._,createdAt:new Date(_.createdAt),updatedAt:new Date(_.updatedAt)})),[h]);v.useEffect(()=>{u||n||c(`/agents/${t}/chat/new`)},[u,n,t,c]);const b=r.get("messageId")??void 0,x=v.useMemo(()=>RNe(s),[s]);if(i&&ys(i))return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Hs,{})});if(i&&xs(i))return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ms,{resource:"agents"})});if(a)return o.jsx(Hts,{agentId:t,view:e});if(!s)return o.jsx("div",{className:"py-4 text-center",children:"Agent not found"});if(!u&&!n)return null;const S=d?f:n??f,k=async()=>{await g(),d&&c(`/agents/${t}/chat/${f}`)};return o.jsx(wEe,{agentId:t,defaultSettings:x,children:o.jsx(h3,{children:o.jsx(sMt,{agentId:t,threadId:S,resourceId:t,children:o.jsx(fZ,{children:o.jsx(pZ,{agentId:t,threadId:S,enabled:!!s?.browserTools?.length,children:o.jsx(TEe,{children:o.jsx(oMt,{children:o.jsx(pLr,{children:o.jsx(kEe,{children:o.jsx(qts,{agentId:t,view:e,leftDrawerLabel:"Open threads and memory",leftSlot:m?o.jsx(n9t,{}):o.jsx(K5r,{agentId:t,threadId:S,threads:y}),browserOverlay:o.jsx(JCe,{}),children:o.jsx("div",{className:nns?"min-h-0 overflow-hidden":"agent-view-enter min-h-0 overflow-hidden",children:u?o.jsx(tns,{agentId:t}):o.jsx(MNe,{agentId:t,agentName:s?.name,modelVersion:s?.modelVersion,supportsMemory:s?.supportsMemory,threadId:S,memory:p,refreshThreadList:k,modelList:s?.modelList,messageId:b,isNewThread:d,runOptionsSlot:o.jsx(G8t,{requestContextSchema:s?.requestContextSchema})},S)},e)})},`${t}-${S}`)},`memory-timeline-${t}-${S}`)})})},`session-${t}-${S}`)},`browser-${t}-${S}`)})})})}function s9t({config:e,redirectUri:t,className:n,loginUrl:r="/login"}){const{mutate:s,isPending:a}=hPt();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(ce,{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(r,window.location.origin);t&&l.searchParams.set("redirect",t),window.location.href=l.toString()};return o.jsx(ce,{onClick:i,className:n,children:"Sign in"})}function UKe({user:e,size:t="sm"}){if(!e)return null;const n=e.name||e.email||"User";return o.jsx(u_,{src:e.avatarUrl,name:n,size:t})}function rns({user:e}){const[t,n]=v.useState(!1),{mutate:r,isPending:s}=Ujr(),{data:a}=uc(),{isImpersonating:i,impersonatedRole:l,startImpersonation:c,stopImpersonation:u,isSwitching:d}=Hq();if(!e)return null;const f=()=>{r(void 0,{onSuccess:m=>{m.redirectTo?window.location.href=m.redirectTo:window.location.reload()}})},p=a&&wm(a)?a.availableRoles:void 0,h=e.name||e.email||"User";return o.jsxs(Pf,{open:t,onOpenChange:n,children:[o.jsx(Bd,{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(UKe,{user:e,size:"sm"})})}),o.jsxs(Ud,{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(UKe,{user:e,size:"md"}),o.jsxs("div",{className:"flex flex-col overflow-hidden",children:[o.jsx(ye,{variant:"ui-md",className:"truncate font-medium",children:h}),e.email&&o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 truncate",children:e.email})]})]})}),p&&p.length>0&&o.jsxs("div",{className:"border-border1 border-b p-2",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 px-2 py-1 tracking-wider uppercase",children:"Preview as role"}),p.map(m=>{const g=i&&l?.id===m.id;return o.jsxs("button",{type:"button",disabled:d,onClick:()=>{g?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 ${g?"bg-surface2":"hover:bg-surface2"} ${d?"cursor-not-allowed opacity-50":""}`,children:[d&&o.jsx(ia,{className:"h-3.5 w-3.5 animate-spin"}),o.jsx("span",{className:"flex-1 capitalize",children:m.name}),g&&o.jsx(bs,{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(ce,{as:ei,to:"/settings",variant:"ghost",className:"w-full justify-start",onClick:()=>n(!1),children:[o.jsx(p9,{className:"h-4 w-4"}),"Settings"]}),o.jsx(ce,{variant:"ghost",onClick:f,disabled:s,className:"w-full justify-start",children:s?"Signing out...":"Sign out"})]})]})]})}function OD({className:e}){const{data:t,isLoading:n,error:r}=uc();return n||r||!t?.enabled?null:wm(t)?o.jsx(rns,{user:t.user}):o.jsx(s9t,{config:t.login,redirectUri:typeof window<"u"?window.location.href:void 0,className:e})}const _z="__custom__",a9t=()=>{const e=Wyt(),{requestContext:t,setRequestContext:n}=_s(),r=v.useMemo(()=>{if(!e)return _z;const a=JSON.stringify(t??{});for(const[i,l]of Object.entries(e))if(JSON.stringify(l)===a)return i;return _z},[e,t]),s=a=>{if(a===_z){n({});return}if(!e)return;const i=e[a];i&&n(i)};return o.jsxs(Iwe,{children:[o.jsxs(jgt,{children:[o.jsx(Xh,{className:"h-5 w-8 shrink-0"}),"Mastra Studio",o.jsx(OD,{})]}),e&&Object.keys(e).length>0&&o.jsx(QTn,{children:o.jsxs(oa,{value:r,onValueChange:s,children:[o.jsx(ca,{size:"sm",className:"w-[200px]",children:o.jsx(la,{placeholder:"Select a preset..."})}),o.jsxs(ua,{children:[o.jsx(Ar,{value:_z,children:"Custom"}),Object.keys(e).map(a=>o.jsx(Ar,{value:a,children:a},a))]})]})})]})};function VKe(){const{agentId:e,threadId:t}=Sr(),[n]=Ri(),{data:r,isLoading:s}=mc(e),{data:a}=oC(e),i=qs(),l=t==="new",c=v.useMemo(()=>xo(),[t]),u=!!a?.result,{refetch:d}=Y$t({resourceId:e,agentId:e,isMemoryEnabled:u});v.useEffect(()=>{u&&(t||i(`/agents/${e}/session/new`))},[u,t,e,i]);const f=n.get("messageId")??void 0,p=v.useMemo(()=>RNe(r),[r]);if(s)return o.jsx(sns,{});if(!r)return o.jsx("div",{className:"py-4 text-center",children:"Agent not found"});const h=l?c:t??c,m=async()=>{await d(),l&&i(`/agents/${e}/session/${c}`)};return o.jsx(Pwe,{entityId:e,entityType:"agent",children:o.jsx(wEe,{agentId:e,defaultSettings:p,children:o.jsx(h3,{children:o.jsx(sMt,{agentId:e,threadId:h,resourceId:e,children:o.jsx(fZ,{children:o.jsx(pZ,{agentId:e,threadId:h,enabled:!!r?.browserTools?.length,children:o.jsx(TEe,{children:o.jsx(oMt,{children:o.jsx(kEe,{children:o.jsxs(ds,{children:[o.jsx(a9t,{}),o.jsx("div",{className:"relative grid h-full overflow-y-auto pt-6",children:o.jsx(MNe,{agentId:e,agentName:r?.name,modelVersion:r?.modelVersion,supportsMemory:r?.supportsMemory,threadId:h,memory:u,refreshThreadList:m,modelList:r?.modelList,messageId:f,isNewThread:l,hideModelSwitcher:!0},h)})]})})})})},`session-${e}-${h}`)},`browser-${e}-${h}`)})})})})}const sns=()=>o.jsxs(ds,{children:[o.jsx(a9t,{}),o.jsx("div",{className:"relative grid h-full overflow-y-auto pt-6","data-testid":"agent-session-skeleton","aria-busy":"true",children:o.jsx(r9t,{})})]}),DNe=()=>{const{data:e}=R4();return e?.editorSource==="code"?"code":"db"};function ans(){const{agentId:e}=Sr(),{navigate:t}=yn(),{data:n,isLoading:r,error:s}=mc(e),{data:a}=K1({agentId:e,params:{orderBy:{direction:"DESC"}}}),i=(a?.versions?.length??0)>0,{data:l,isLoading:c}=b4(e,{status:"draft",enabled:i}),u=DNe(),d=n?.source==="code",f=d&&u==="code",p=r||i&&c,h=v.useMemo(()=>l||(n?ANe(n):{}),[l,n]),{form:m,handlePublish:g,handleSaveDraft:y,isSubmitting:b,isSavingDraft:x}=DG({mode:"edit",agentId:e??"",dataSource:h,isCodeAgentOverride:d,hasStoredOverride:d&&!!l,editorConfig:n?.editor,onSuccess:()=>{}}),[S,k]=v.useState(()=>{const _=sessionStorage.getItem(`pending-scorer-items-${e}`);if(_){sessionStorage.removeItem(`pending-scorer-items-${e}`);try{return JSON.parse(_)}catch{return null}}return null});return s&&ys(s)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Hs,{})}):s&&xs(s)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ms,{resource:"agents"})}):p?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Xt,{className:"h-6 w-6"})}):n?o.jsx(_Ee,{form:m,mode:"edit",agentId:e,isSubmitting:b,isSavingDraft:x,handlePublish:g,handleSaveDraft:y,isCodeAgentOverride:d,isCodeSourceAgent:f,readOnly:!1,children:o.jsx(dts,{agentId:e,onSwitchToReview:()=>t(`/agents/${e}/review`),pendingScorerItems:S,onPendingScorerItemsConsumed:()=>k(null)})}):o.jsx("div",{className:"py-4 text-center",children:"Agent not found"})}const zG=()=>{const e=window.MASTRA_CLOUD_API_ENDPOINT,t=window.MASTRA_PLATFORM_PROJECT_ID,n=window.MASTRA_ORGANIZATION_ID,r=window.MASTRA_PLATFORM_OBSERVABILITY_ENDPOINT;return{isMastraPlatform:!!e,mastraPlatformEndpoint:e,mastraPlatformApiEndpoint:e,mastraPlatformProjectId:t,mastraOrganizationId:n,platformObservabilityEndpoint:r}};function ins(){const{agentId:e}=Sr(),[t,n]=v.useState(null),{data:r,isLoading:s,error:a}=mc(e),{data:i}=oC(e),l=DNe(),{isMastraPlatform:c,mastraPlatformApiEndpoint:u,mastraPlatformProjectId:d}=zG(),{data:f}=K1({agentId:e,params:{orderBy:{direction:"DESC"}}}),p=(f?.versions?.length??0)>0,{data:h,isLoading:m}=b4(e,{status:"draft",enabled:p}),g=r?.source==="code",y=g&&l==="code",b=!g||r?.editor!==!1,x=y&&b,S=x&&c&&!!u&&!!d,k=S?"Open a pull request for these JSON changes":void 0,_=s||p&&m,C=!!i?.result,{data:E}=V$t({agentId:e??"",versionId:t??""}),j=h?.activeVersionId,N=f?.versions?.[0],I=!!(N&&N.id!==j),A=!!t&&!!E,R=A&&t!==N?.id,L=v.useMemo(()=>A&&E?E:h||(r?ANe(r):{}),[A,E,h,r]),{form:D,handlePublish:B,handleSaveDraft:H,handleDownloadJson:F,handleOpenPr:z,isSubmitting:q,isSavingDraft:M,isDirty:G}=DG({mode:"edit",agentId:e??"",dataSource:L,isCodeAgentOverride:g,hasStoredOverride:g&&!!h,editorConfig:r?.editor,saveSuccessMessage:y?"Saved to filesystem":void 0,onSuccess:()=>{}}),V=v.useCallback(async()=>{R&&t?await B(t):await B()},[B,R,t]),$=v.useCallback(async()=>{!u||!d||await z({platformApiEndpoint:u,projectId:d})},[z,u,d]),U=v.useCallback(Z=>{Z===N?.id?n(null):n(Z)},[N?.id]);return a&&ys(a)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Hs,{})}):a&&xs(a)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ms,{resource:"agents"})}):_?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Xt,{className:"h-6 w-6"})}):r?o.jsx(_Ee,{form:D,mode:"edit",agentId:e,isSubmitting:q,isSavingDraft:M,handlePublish:B,handleSaveDraft:H,isCodeAgentOverride:g,isCodeSourceAgent:y,readOnly:R||!b,editorConfig:r?.editor,children:o.jsx(jes,{agentId:e,agentName:r?.name,modelVersion:r?.modelVersion,agentVersionId:R?t??void 0:void 0,hasMemory:C,activeVersionId:j,selectedVersionId:t??void 0,latestVersionId:N?.id,onVersionSelect:U,isDirty:G,isSavingDraft:M,isPublishing:q,hasDraft:I,readOnly:R||!b,isCodeSourceAgent:y,showCodeModeActions:x,canOpenPr:S,openPrTitle:k,onSaveDraft:H,onPublish:V,onDownloadJson:F,onOpenPr:$,isViewingPreviousVersion:R})}):o.jsx("div",{className:"py-4 text-center",children:"Agent not found"})}function ons(){const{agentId:e}=Sr(),{navigate:t}=yn(),{data:n,isLoading:r,error:s}=mc(e);if(s&&ys(s))return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Hs,{})});if(s&&xs(s))return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ms,{resource:"agents"})});if(r)return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Xt,{className:"h-6 w-6"})});if(!n)return o.jsx("div",{className:"py-4 text-center",children:"Agent not found"});const a=i=>{sessionStorage.setItem(`pending-scorer-items-${e}`,JSON.stringify(i)),t(`/agents/${e}/evaluate`)};return o.jsx(vts,{agentId:e,onCreateScorer:a})}let au=(function(e){return e.AGENT="agent",e.SCORER="scorer",e.RAG_INGESTION="rag_ingestion",e.TRAJECTORY="trajectory",e.INPUT_PROCESSOR="input_processor",e.INPUT_STEP_PROCESSOR="input_step_processor",e.OUTPUT_PROCESSOR="output_processor",e.OUTPUT_STEP_PROCESSOR="output_step_processor",e.WORKFLOW_STEP="workflow_step",e.TOOL="tool",e.WORKFLOW_RUN="workflow_run",e.MEMORY="memory",e})({});C_().describe("Database record creation time");const lns=C_().describe("Database record last update time");lns.nullable();const BG=_e({page:J2().int().min(0).optional().default(0).describe("Zero-indexed page number"),perPage:J2().int().min(1).max(100).optional().default(10).describe("Number of items per page")}).describe("Pagination options for list queries"),UG=_e({total:Ct().describe("Total number of items available"),page:Ct().describe("Current page"),perPage:Qn([Ct(),Vt(!1)]).describe("Number of items per page, or false if pagination is disabled"),hasMore:Ps().describe("True if more pages are available")}),nS=ge().min(1).describe("Opaque cursor value for incremental polling"),VG=Ys(["page","delta"]).describe("List mode: 'page' | 'delta', defaults to 'page' when omitted."),qG=J2().int().min(1).max(100).optional().describe("Maximum number of updates to return in one delta poll"),cns={page:0,perPage:10};function HG(e,t){if(e.mode==="delta"){e.pagination!==void 0&&t.addIssue({code:"custom",path:["pagination"],message:"pagination is not allowed in delta mode"}),e.orderBy!==void 0&&t.addIssue({code:"custom",path:["orderBy"],message:"orderBy is not allowed in delta mode"});return}e.after!==void 0&&t.addIssue({code:"custom",path:["after"],message:"after is only allowed in delta mode"}),e.limit!==void 0&&t.addIssue({code:"custom",path:["limit"],message:"limit is only allowed in delta mode"})}function WG(e,t){return{mode:e.mode==="delta"?"delta":"page",filters:e.filters,pagination:e.pagination??t.pagination??cns,orderBy:e.orderBy??t.orderBy,after:e.after,limit:e.limit??t.limit??10}}const ZG=_e({limit:Ct().describe("Maximum number of updates requested for this delta poll"),hasMore:Ps().describe("True when more matching updates remain after this response")}).describe("Incremental polling metadata"),uns=_e({start:q$e().optional().describe("Start of date range (inclusive by default)"),end:q$e().optional().describe("End of date range (inclusive by default)"),startExclusive:Ps().optional().describe("When true, excludes the start date from results (uses > instead of >=)"),endExclusive:Ps().optional().describe("When true, excludes the end date from results (uses < instead of <=)")}).describe("Date range filter for timestamps"),SL=Ys(["ASC","DESC"]).describe("Sort direction: 'ASC' | 'DESC'"),Zy=Ys(["sum","avg","min","max","count","count_distinct","last"]).describe("Aggregation function"),mC=Ys(["1m","5m","15m","1h","1d"]).describe("Time bucket interval"),LNe=Ys(["previous_period","previous_day","previous_week"]).describe("Comparison period for aggregate queries"),gC=$t(ge()).min(1).describe("Fields to group by"),FNe=$t(Ct().min(0).max(1)).min(1).describe("Percentile values (0-1)"),zNe={value:Ct().nullable().describe("Aggregated value"),previousValue:Ct().nullable().optional().describe("Value from comparison period"),changePercent:Ct().nullable().optional().describe("Percentage change from comparison period")},BNe=Us(ge(),ge().nullable()).describe("Dimension values for this group"),WI=Ct().describe("Aggregated value"),ZI=C_().describe("Bucket timestamp"),UNe=Ct().describe("Percentile value"),VNe=Ct().describe("Percentile value at this bucket"),GI=bxe(au).describe("Entity type (e.g., 'agent' | 'processor' | 'tool' | 'workflow')"),dns=ge().describe('ID of the entity (e.g., "weatherAgent", "orderWorkflow")'),i9t=ge().describe("Name of the entity"),o9t=ge().describe("Human end-user who triggered execution"),l9t=ge().describe("Multi-tenant organization/account"),c9t=ge().describe("Broader resource context (Mastra memory compatibility)"),u9t=ge().describe("Unique execution run identifier"),d9t=ge().describe("Session identifier for grouping traces"),f9t=ge().describe("Conversation thread identifier"),p9t=ge().describe("HTTP request ID for log correlation"),h9t=ge().describe('Environment (e.g., "production" | "staging" | "development")'),fns=ge().describe('Source of execution (e.g., "local" | "cloud" | "ci")'),m9t=ge().describe('Source of execution (e.g., "local" | "cloud" | "ci")'),g9t=ge().describe("Name of the service"),v9t=bxe(au).describe("Entity type of the parent entity"),pns=ge().describe("ID of the parent entity"),y9t=ge().describe("Name of the parent entity"),b9t=bxe(au).describe("Entity type of the root entity"),hns=ge().describe("ID of the root entity"),x9t=ge().describe("Name of the root entity"),w9t=ge().describe("Version ID of the entity that produced this signal (e.g., agent version, workflow version)"),S9t=ge().describe("Version ID of the parent entity that produced this signal"),k9t=ge().describe("Version ID of the root entity that produced this signal"),GG=ge().describe("Experiment or eval run identifier"),mns=Us(ge(),za()).describe('Arbitrary package/app version info (e.g., {"core": "1.0.0", "memory": "1.0.0", "gitSha": "abcd1234"})'),O9t=Us(ge(),za()).describe("User-defined metadata for custom filtering"),_9t=$t(ge()).describe("Labels for filtering"),gns={entityType:GI.nullish(),entityId:dns.nullish(),entityName:i9t.nullish(),parentEntityType:v9t.nullish(),parentEntityId:pns.nullish(),parentEntityName:y9t.nullish(),rootEntityType:b9t.nullish(),rootEntityId:hns.nullish(),rootEntityName:x9t.nullish(),userId:o9t.nullish(),organizationId:l9t.nullish(),resourceId:c9t.nullish(),runId:u9t.nullish(),sessionId:d9t.nullish(),threadId:f9t.nullish(),requestId:p9t.nullish(),environment:h9t.nullish(),serviceName:g9t.nullish(),scope:mns.nullish(),entityVersionId:w9t.nullish(),parentEntityVersionId:S9t.nullish(),rootEntityVersionId:k9t.nullish(),experimentId:GG.nullish()},QG={...gns,executionSource:m9t.nullish(),tags:_9t.nullish()};fns.nullish();const YG={timestamp:uns.optional().describe("Filter by timestamp range"),traceId:ge().optional().describe("Filter by trace ID"),spanId:ge().optional().describe("Filter by span ID"),entityType:GI.optional(),entityName:i9t.optional(),entityVersionId:w9t.optional(),parentEntityVersionId:S9t.optional(),rootEntityVersionId:k9t.optional(),userId:o9t.optional(),organizationId:l9t.optional(),experimentId:GG.optional(),serviceName:g9t.optional(),environment:h9t.optional(),parentEntityType:v9t.optional(),parentEntityName:y9t.optional(),rootEntityType:b9t.optional(),rootEntityName:x9t.optional(),resourceId:c9t.optional(),runId:u9t.optional(),sessionId:d9t.optional(),threadId:f9t.optional(),requestId:p9t.optional(),executionSource:m9t.optional(),tags:$t(ge()).optional().describe("Filter by tags (must have all specified tags)")},KG=ge().describe("Unique trace identifier"),XG=ge().describe("Unique span identifier within a trace"),MV=Ys(["debug","info","warn","error","fatal"]),C9t=ge().describe("Log message"),E9t=Us(ge(),za()).describe("Structured data attached to the log"),j9t=_e({logId:ge().nullish().describe("Unique id for this log event"),timestamp:C_().describe("When the log was created"),level:MV.describe("Log severity level"),message:C9t,data:E9t.nullish(),traceId:KG.nullish(),spanId:XG.nullish(),...QG,source:ge().nullish().describe("Execution source"),metadata:O9t.nullish()}).describe("Log record as stored in the database");_e({level:MV,message:C9t,data:E9t.optional(),tags:_9t.optional()}).describe("User-provided log input");const vns=j9t;_e({logs:$t(vns)}).describe("Arguments for batch creating logs");const yns=_e({...YG,source:ge().optional().describe("Filter by execution source"),level:Qn([MV,$t(MV)]).optional().describe("Filter by log level(s)")}).describe("Filters for querying logs"),bns=Ys(["timestamp"]).describe("Field to order by: 'timestamp'"),xns=_e({field:bns.default("timestamp").describe("Field to order by"),direction:SL.default("DESC").describe("Sort direction")}).describe("Order by configuration");_e({mode:VG.optional(),filters:yns.optional().describe("Optional filters to apply"),pagination:BG.optional(),orderBy:xns.optional(),after:nS.optional(),limit:qG}).strict().superRefine(HG).transform(e=>WG(e,{orderBy:{field:"timestamp",direction:"DESC"}})).describe("Arguments for listing logs");_e({pagination:UG.optional(),delta:ZG.optional(),deltaCursor:nS.optional(),logs:$t(j9t)}).describe("Response from listing logs");const QI=ge().describe("Identifier of the scorer (e.g., relevance, accuracy)"),T9t=ge().describe("Display name of the scorer"),N9t=ge().describe("Version of the scorer"),_y=ge().describe("How the score was produced (e.g., manual, automated, experiment)"),I9t=Ct().describe("Score value (range defined by scorer)"),A9t=ge().describe("Explanation for the score"),R9t=_e({scoreId:ge().nullish().describe("Unique id for this score event"),timestamp:C_().describe("When the score was recorded"),traceId:KG.nullish().describe("Trace that anchors the scored target when available"),spanId:XG.nullish().describe("Span ID this score applies to"),scorerId:QI,scorerName:T9t.nullish(),scorerVersion:N9t.nullish(),scoreSource:_y.nullish(),source:_y.nullish(),score:I9t,reason:A9t.nullish(),...QG,scoreTraceId:ge().nullish().describe("Trace ID of the scoring run for debugging score generation"),metadata:Us(ge(),za()).nullish().describe("User-defined metadata")}).describe("Score record as stored in the database");_e({scorerId:QI,scorerName:T9t.optional(),scorerVersion:N9t.optional(),scoreSource:_y.optional(),source:_y.optional(),score:I9t,reason:A9t.optional(),metadata:Us(ge(),za()).optional().describe("Additional scorer-specific metadata"),experimentId:GG.optional(),scoreTraceId:ge().optional().describe("Trace ID of the scoring run for debugging score generation"),targetEntityType:GI.optional().describe("Entity type the scorer evaluated when known")}).describe("User-provided score input");const qNe=R9t;_e({score:qNe}).describe("Arguments for creating a score");_e({score:qNe.omit({timestamp:!0})}).describe("Arguments for creating a score");_e({success:Ps()}).describe("Response from creating a score");_e({scores:$t(qNe)}).describe("Arguments for batch recording scores");const kL=_e({...YG,scorerId:Qn([ge(),$t(ge())]).optional().describe("Filter by scorer ID(s)"),scoreSource:_y.optional().describe("Filter by how the score was produced"),source:_y.optional().describe("Filter by how the score was produced")}).describe("Filters for querying scores"),wns=Ys(["timestamp","score"]).describe("Field to order by: 'timestamp' | 'score'"),Sns=_e({field:wns.default("timestamp").describe("Field to order by"),direction:SL.default("DESC").describe("Sort direction")}).describe("Order by configuration");_e({mode:VG.optional(),filters:kL.optional(),pagination:BG.optional(),orderBy:Sns.optional(),after:nS.optional(),limit:qG}).strict().superRefine(HG).transform(e=>WG(e,{orderBy:{field:"timestamp",direction:"DESC"}})).describe("Arguments for listing scores");_e({pagination:UG.optional(),delta:ZG.optional(),deltaCursor:nS.optional(),scores:$t(R9t)}).describe("Response from listing scores");_e({scorerId:QI,scoreSource:_y.optional(),aggregation:Zy,filters:kL.optional(),comparePeriod:LNe.optional()}).describe("Arguments for getting a score aggregate");_e(zNe);_e({scorerId:QI,scoreSource:_y.optional(),groupBy:gC,aggregation:Zy,filters:kL.optional()}).describe("Arguments for getting a score breakdown");_e({groups:$t(_e({dimensions:BNe,value:WI}))});_e({scorerId:QI,scoreSource:_y.optional(),interval:mC,aggregation:Zy,filters:kL.optional(),groupBy:gC.optional()}).describe("Arguments for getting score time series");_e({series:$t(_e({name:ge().describe("Series name (scorer ID or group key)"),points:$t(_e({timestamp:ZI,value:WI}))}))});_e({scorerId:QI,scoreSource:_y.optional(),percentiles:FNe,interval:mC,filters:kL.optional()}).describe("Arguments for getting score percentiles");_e({series:$t(_e({percentile:UNe,points:$t(_e({timestamp:ZI,value:VNe}))}))});const Cy=ge().describe("Source of feedback (e.g., 'user', 'system', 'manual')"),YI=ge().describe("Type of feedback (e.g., 'thumbs', 'rating', 'correction')"),P9t=Qn([Ct(),ge()]).describe("Feedback value (rating number or correction text)"),$9t=ge().describe("Additional comment or context"),DV=ge().describe("User who provided the feedback");function HNe(e){if(!e||typeof e!="object"||Array.isArray(e))return e;const t={...e};return typeof t.userId=="string"&&t.feedbackUserId==null&&(t.feedbackUserId=t.userId,delete t.userId),t}const JG=_e({feedbackId:ge().nullish().describe("Unique id for this feedback event"),timestamp:C_().describe("When the feedback was recorded"),traceId:KG.nullish().describe("Trace that anchors the feedback target when available"),spanId:XG.nullish().describe("Span ID this feedback applies to"),feedbackSource:Cy.nullish(),source:Cy.nullish(),feedbackType:YI,value:P9t,comment:$9t.nullish(),feedbackUserId:DV.nullish(),...QG,sourceId:ge().nullish().describe("ID of the source record this feedback is linked to (e.g. experiment result ID)"),metadata:Us(ge(),za()).nullish().describe("User-defined metadata")}),kns=_e(JG.shape).describe("Feedback record as stored in the database"),Ons=_e({feedbackSource:Cy.optional(),source:Cy.optional(),feedbackType:YI,value:P9t,comment:$9t.optional(),feedbackUserId:DV.optional(),userId:DV.optional(),metadata:Us(ge(),za()).optional().describe("Additional feedback-specific metadata"),experimentId:GG.optional(),sourceId:ge().optional().describe("ID of the source record this feedback is linked to")});_e(Ons.shape).describe("User-provided feedback input");_e({feedback:kxe(HNe,JG)}).describe("Arguments for creating feedback");_e({feedback:JG.omit({timestamp:!0})}).describe("Arguments for creating feedback");_e({success:Ps()}).describe("Response from creating feedback");_e({feedbacks:$t(kxe(HNe,JG))}).describe("Arguments for batch recording feedback");const M9t=_e({...YG,feedbackType:Qn([ge(),$t(ge())]).optional().describe("Filter by feedback type(s)"),feedbackSource:Cy.optional(),source:Cy.optional(),feedbackUserId:DV.optional()}),eQ=_e(M9t.shape).describe("Filters for querying feedback"),_ns=Ys(["timestamp"]).describe("Field to order by: 'timestamp'"),Cns=_e({field:_ns.default("timestamp").describe("Field to order by"),direction:SL.default("DESC").describe("Sort direction")}).describe("Order by configuration");_e({mode:VG.optional(),filters:kxe(HNe,M9t).optional(),pagination:BG.optional(),orderBy:Cns.optional(),after:nS.optional(),limit:qG}).strict().superRefine(HG).transform(e=>WG(e,{orderBy:{field:"timestamp",direction:"DESC"}})).describe("Arguments for listing feedback");_e({pagination:UG.optional(),delta:ZG.optional(),deltaCursor:nS.optional(),feedback:$t(kns)}).describe("Response from listing feedback");_e({feedbackType:YI,feedbackSource:Cy.optional(),aggregation:Zy,filters:eQ.optional(),comparePeriod:LNe.optional()}).describe("Arguments for getting a feedback aggregate over numeric values");_e(zNe);_e({feedbackType:YI,feedbackSource:Cy.optional(),groupBy:gC,aggregation:Zy,filters:eQ.optional()}).describe("Arguments for getting a feedback breakdown over numeric values");_e({groups:$t(_e({dimensions:BNe,value:WI}))});_e({feedbackType:YI,feedbackSource:Cy.optional(),interval:mC,aggregation:Zy,filters:eQ.optional(),groupBy:gC.optional()}).describe("Arguments for getting feedback time series over numeric values");_e({series:$t(_e({name:ge().describe("Series name (feedback type or group key)"),points:$t(_e({timestamp:ZI,value:WI}))}))});_e({feedbackType:YI,feedbackSource:Cy.optional(),percentiles:FNe,interval:mC,filters:eQ.optional()}).describe("Arguments for getting feedback percentiles over numeric values");_e({series:$t(_e({percentile:UNe,points:$t(_e({timestamp:ZI,value:VNe}))}))});Ys(["counter","gauge","histogram"]);const D9t=ge().describe("Metric name (e.g., mastra_agent_duration_ms)"),L9t=Ct().describe("Metric value"),F9t=Us(ge(),ge()).describe("Metric labels for dimensional filtering"),z9t=ge().describe("Model provider"),B9t=ge().describe("Model"),Ens=Ct().describe("Estimated cost"),U9t=ge().describe("Unit for the estimated cost (e.g., usd)"),jns=Us(ge(),za()).nullish().describe("Structured costing metadata"),V9t=_e({metricId:ge().nullish().describe("Unique id for this metric event"),timestamp:C_().describe("When the metric was recorded"),name:D9t,value:L9t,traceId:KG.nullish(),spanId:XG.nullish(),...QG,source:ge().nullish().describe("Execution source"),provider:z9t.nullish(),model:B9t.nullish(),estimatedCost:Ens.nullish(),costUnit:U9t.nullish(),costMetadata:jns.nullish(),labels:F9t.default({}),metadata:O9t.nullish()}).describe("Metric record as stored in the database");_e({name:D9t,value:L9t,labels:F9t.optional()}).describe("User-provided metric input");const Tns=V9t;_e({metrics:$t(Tns)}).describe("Arguments for batch recording metrics");_e({type:Zy,interval:mC.optional(),groupBy:gC.optional()}).describe("Metrics aggregation configuration");const OL=_e({...YG,name:$t(ge()).nonempty().optional().describe("Filter by metric name(s)"),source:ge().optional().describe("Filter by execution source"),provider:z9t.optional(),model:B9t.optional(),costUnit:U9t.optional(),labels:Us(ge(),ge()).optional().describe("Exact match on label key-value pairs")}).describe("Filters for querying metrics"),Nns=Ys(["timestamp"]).describe("Field to order by: 'timestamp'"),Ins=_e({field:Nns.default("timestamp").describe("Field to order by"),direction:SL.default("DESC").describe("Sort direction")}).describe("Order by configuration");_e({mode:VG.optional(),filters:OL.optional(),pagination:BG.optional(),orderBy:Ins.optional(),after:nS.optional(),limit:qG}).strict().superRefine(HG).transform(e=>WG(e,{orderBy:{field:"timestamp",direction:"DESC"}})).describe("Arguments for listing metrics");_e({pagination:UG.optional(),delta:ZG.optional(),deltaCursor:nS.optional(),metrics:$t(V9t)}).describe("Response from listing metrics");const Ans=["entityType","entityName","parentEntityType","parentEntityName","rootEntityType","rootEntityName","name","provider","model","environment","executionSource","serviceName","threadId","resourceId"],WNe=Ys(Ans).optional().describe("Column to apply count_distinct over (required when aggregation is 'count_distinct'). Restricted to allowlisted metric dimensions."),IN={check:e=>e.aggregation!=="count_distinct"||e.distinctColumn!==void 0,options:{message:"distinctColumn is required when aggregation is 'count_distinct'",path:["distinctColumn"]}};_e({name:$t(ge()).nonempty().describe("Metric name(s) to aggregate"),aggregation:Zy,distinctColumn:WNe,filters:OL.optional(),comparePeriod:LNe.optional()}).refine(IN.check,IN.options).describe("Arguments for getting a metric aggregate");_e({...zNe,estimatedCost:Ct().nullable().optional().describe("Aggregated estimated cost from the same filtered row set"),costUnit:ge().nullable().optional().describe("Shared cost unit for the aggregated rows, or null when mixed/unknown"),previousEstimatedCost:Ct().nullable().optional().describe("Aggregated estimated cost from the comparison period"),costChangePercent:Ct().nullable().optional().describe("Percentage change in estimated cost from comparison period")});_e({name:$t(ge()).nonempty().describe("Metric name(s) to break down"),groupBy:gC,aggregation:Zy,distinctColumn:WNe,filters:OL.optional(),limit:Ct().int().positive().max(1e3).optional().describe("Maximum number of groups to return (server-side TopK). Required for high-cardinality groupBy."),orderDirection:SL.optional().describe("Sort direction for the aggregated value (defaults to 'DESC' at the storage layer; pairs with limit for top/bottom-N).")}).refine(IN.check,IN.options).describe("Arguments for getting a metric breakdown");_e({groups:$t(_e({dimensions:BNe,value:WI,estimatedCost:Ct().nullable().optional().describe("Summed estimated cost for this group"),costUnit:ge().nullable().optional().describe("Shared cost unit for this group, or null when mixed/unknown")}))});_e({name:$t(ge()).nonempty().describe("Metric name(s)"),interval:mC,aggregation:Zy,distinctColumn:WNe,filters:OL.optional(),groupBy:gC.optional()}).refine(IN.check,IN.options).describe("Arguments for getting metric time series");_e({series:$t(_e({name:ge().describe("Series name (metric name or group key)"),costUnit:ge().nullable().optional().describe("Shared cost unit for this series, or null when mixed/unknown"),points:$t(_e({timestamp:ZI,value:WI,estimatedCost:Ct().nullable().optional().describe("Summed estimated cost in this bucket")}))}))});_e({name:ge().describe("Metric name"),percentiles:FNe,interval:mC,filters:OL.optional()}).describe("Arguments for getting metric percentiles");_e({series:$t(_e({percentile:UNe,points:$t(_e({timestamp:ZI,value:VNe}))}))});_e({prefix:ge().optional().describe("Filter metric names by prefix"),limit:J2().int().min(1).optional().describe("Maximum number of names to return")}).describe("Arguments for getting metric names");_e({names:$t(ge()).describe("Distinct metric names")});_e({metricName:ge().describe("Metric name to get label keys for")}).describe("Arguments for getting metric label keys");_e({keys:$t(ge()).describe("Distinct label keys for the metric")});_e({metricName:ge().describe("Metric name"),labelKey:ge().describe("Label key to get values for"),prefix:ge().optional().describe("Filter values by prefix"),limit:J2().int().min(1).optional().describe("Maximum number of values to return")}).describe("Arguments for getting label values");_e({values:$t(ge()).describe("Distinct label values")});_e({}).describe("Arguments for getting entity types");_e({entityTypes:$t(GI).describe("Distinct entity types")});_e({entityType:GI.optional().describe("Optional entity type filter")}).describe("Arguments for getting entity names");_e({names:$t(ge()).describe("Distinct entity names")});_e({}).describe("Arguments for getting service names");_e({serviceNames:$t(ge()).describe("Distinct service names")});_e({}).describe("Arguments for getting environments");_e({environments:$t(ge()).describe("Distinct environments")});_e({entityType:GI.optional().describe("Optional entity type filter")}).describe("Arguments for getting tags");_e({tags:$t(ge()).describe("Distinct tags")});new Set(Object.values(au));function ZNe({disabled:e,onClear:t,onRemoveAll:n,onSave:r,onRemoveSaved:s}){const a=!!(n||r||s);return!t&&!a?null:o.jsxs("div",{className:"flex items-center gap-2",children:[t&&o.jsxs(ce,{disabled:e,size:"md",onClick:t,children:[o.jsx(Wu,{}),"Clear"]}),a&&o.jsxs(dt,{children:[o.jsx(dt.Trigger,{asChild:!0,children:o.jsx(ce,{disabled:e,size:"md","aria-label":"More filter actions",children:o.jsx(dEn,{})})}),o.jsxs(dt.Content,{align:"end",children:[n&&o.jsxs(dt.Item,{onSelect:()=>n(),children:[o.jsx(Wu,{}),"Remove all filters"]}),n&&(r||s)&&o.jsx(dt.Separator,{}),r&&o.jsxs(dt.Item,{onSelect:()=>r(),children:[o.jsx(Jmt,{}),"Save filters for next time"]}),s&&o.jsxs(dt.Item,{onSelect:()=>s(),children:[o.jsx(egt,{}),"Remove saved filters"]})]})]})]})}function q9t({field:e,tokens:t,onChange:n}){const[r,s]=v.useState(""),a=v.useMemo(()=>{const u=r.trim().toLowerCase();return u?e.options.filter(d=>d.label.toLowerCase().includes(u)):e.options},[e.options,r]),i=v.useMemo(()=>t.find(u=>u.fieldId===e.id),[t,e.id]),l=typeof i?.value=="string"?i.value:e.multi?void 0:e.defaultValue,c=v.useMemo(()=>{const u=i?.value;return Array.isArray(u)?u:typeof u=="string"?[u]:[]},[i]);return o.jsxs(o.Fragment,{children:[e.searchable!==!1&&o.jsx(Cn,{size:"sm",value:r,onChange:u=>s(u.target.value),placeholder:`Search ${e.label.toLowerCase()}...`,className:"mb-2",onKeyDown:u=>{if(u.key!=="ArrowDown")return;const f=u.currentTarget.closest("[data-pick-multi-panel]")?.querySelector("[data-pick-multi-item]:not([disabled])");f&&(u.preventDefault(),u.stopPropagation(),f.focus())}}),e.isLoading?o.jsxs("div",{className:"text-ui-sm text-neutral3 flex items-center gap-2 px-2 py-1.5",children:[o.jsx(Xt,{size:"sm",className:"text-neutral3 size-3"}),"Loading options…"]}):a.length===0?o.jsx("div",{className:"text-ui-sm text-neutral3 px-2 py-1.5",children:e.emptyText??"No option found."}):e.multi?o.jsx("div",{className:"max-h-[80dvh] overflow-auto",children:a.map(u=>{const d=c.includes(u.value);return o.jsxs("label",{title:u.label,className:"text-ui-md text-neutral4 focus-within:bg-surface4 focus-within:text-neutral6 hover:bg-surface4 hover:text-neutral6 flex min-w-0 cursor-pointer items-center gap-2 rounded-md px-2 py-1.5",children:[o.jsx(zo,{"data-pick-multi-item":"",checked:d,onCheckedChange:f=>{const h=f===!0?c.includes(u.value)?c:[...c,u.value]:c.filter(m=>m!==u.value);n(e.id,h)},className:"shrink-0"}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:u.label})]},u.value)})}):o.jsxs(bL,{value:l??"",onValueChange:u=>n(e.id,u),className:"max-h-[80dvh] gap-0 overflow-auto",children:[a.map(u=>o.jsxs("label",{title:u.label,className:"text-ui-md text-neutral4 focus-within:bg-surface4 focus-within:text-neutral6 hover:bg-surface4 hover:text-neutral6 flex min-w-0 cursor-pointer items-center gap-2 rounded-md px-2 py-1.5",children:[o.jsx(Np,{"data-pick-multi-item":"",value:u.value,className:"shrink-0"}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:u.label})]},u.value)),!e.omitAnyOption&&o.jsxs("label",{title:"Any",className:"text-ui-md text-neutral4 focus-within:bg-surface4 focus-within:text-neutral6 hover:bg-surface4 hover:text-neutral6 flex min-w-0 cursor-pointer items-center gap-2 rounded-md px-2 py-1.5",children:[o.jsx(Np,{"data-pick-multi-item":"",value:"Any",className:"shrink-0"}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:"Any"})]})]})]})}function GNe(e){return Array.isArray(e)?e.length===0?"Any":e.join(", "):e}const Rns="This filter is set by the current context and cannot be removed here.";function Pns(e,t){return e.kind==="pick-multi"&&e.options?Array.isArray(t)?t.length===0?"Any":t.map(n=>e.options.find(r=>r.value===n)?.label??n).join(", "):e.options.find(n=>n.value===t)?.label??t:GNe(t)}function $ns({field:e,value:t,tooltipContent:n}){const r=Pns(e,t),s=`${e.label} filter is locked by context`;return o.jsx(cc,{delayDuration:150,children:o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:o.jsxs(Mr,{spacing:"close","data-locked-field-id":e.id,"data-property-filter-pill":"locked",tabIndex:0,"aria-label":s,children:[o.jsx(Hh,{size:"md",children:e.label}),o.jsx(Hh,{size:"md",children:"is"}),o.jsx(Hh,{size:"md",children:r}),o.jsx(Hh,{size:"md",children:o.jsx(XEn,{})})]})}),o.jsx(Rn,{children:n})]})})}function Mns({field:e,value:t,onChange:n,onRemove:r,disabled:s,autoFocus:a}){const[i,l]=v.useState(t),c=v.useRef(null);return v.useEffect(()=>{i.trim()!==t&&l(t)},[t]),v.useEffect(()=>{a&&c.current?.focus()},[a]),o.jsxs(Mr,{spacing:"close",children:[o.jsx(Hh,{size:"md",children:e.label}),o.jsx(Hh,{size:"md",children:"is"}),o.jsx(Cn,{ref:c,size:"md",disabled:s,value:i,placeholder:e.placeholder??`Enter ${e.label}`,onChange:u=>{const d=u.target.value;l(d),d.trim()!==t&&n(d)},onKeyDown:u=>{if(u.key==="Enter"){u.preventDefault();const d=i.trim();d!==t&&n(d)}else u.key==="Escape"&&(u.preventDefault(),l(t),u.target.blur())}}),o.jsx(ce,{type:"button",disabled:s,"aria-label":`Remove ${e.label} filter`,size:"md",onMouseDown:u=>u.preventDefault(),onClick:r,children:o.jsx(Wu,{})})]})}function Dns({field:e,token:t,tokens:n,onChange:r,onRemove:s,disabled:a}){const[i,l]=v.useState(!1);return o.jsxs(Mr,{spacing:"close",children:[o.jsx(Hh,{size:"md",children:e.label}),o.jsx(Hh,{size:"md",children:"is"}),o.jsxs(Pf,{open:i,onOpenChange:l,children:[o.jsx(Bd,{asChild:!0,children:o.jsx(ce,{type:"button",disabled:a,size:"md",children:GNe(t.value)})}),o.jsx(Ud,{align:"start",sideOffset:8,className:"w-64 p-2","data-pick-multi-panel":!0,children:o.jsx(q9t,{field:e,tokens:n,onChange:r})})]}),o.jsx(ce,{type:"button",disabled:a,"aria-label":`Remove ${e.label} filter`,size:"md",onClick:s,children:o.jsx(Wu,{})})]})}function QNe({fields:e,tokens:t,onTokensChange:n,disabled:r,autoFocusFieldId:s,lockedFieldIds:a,lockedTooltipContent:i=Rns}){if(t.length===0)return null;const l=new Set(a??[]),c=(d,f)=>{const p=[...t];p[d]=f,n(p)},u=d=>{n(t.filter((f,p)=>p!==d))};return o.jsx("div",{className:"flex flex-wrap items-center gap-2",children:t.map((d,f)=>{const p=e.find(h=>h.id===d.fieldId);return p?l.has(d.fieldId)?o.jsx($ns,{field:p,value:d.value,tooltipContent:i},`${d.fieldId}-${f}`):p.kind==="text"&&typeof d.value=="string"?o.jsx(Mns,{field:p,value:d.value,disabled:r,autoFocus:s===d.fieldId,onChange:h=>c(f,{fieldId:d.fieldId,value:h}),onRemove:()=>u(f)},`${d.fieldId}-${f}`):p.kind==="pick-multi"?o.jsx(Dns,{field:p,token:d,tokens:t,disabled:r,onChange:(h,m)=>{if(m===void 0){u(f);return}c(f,{fieldId:h,value:m})},onRemove:()=>u(f)},`${d.fieldId}-${f}`):o.jsxs(Mr,{spacing:"close",children:[o.jsx(Hh,{size:"md",children:p.label}),o.jsx(Hh,{size:"md",children:"is"}),o.jsx(Hh,{size:"md",children:GNe(d.value)}),o.jsx(ce,{type:"button",disabled:r,size:"md","aria-label":`Remove ${p.label} filter`,onClick:()=>u(f),children:o.jsx(Wu,{})})]},`${d.fieldId}-${f}`):null})})}function YNe({fields:e,tokens:t,onTokensChange:n,label:r="Add Filter",disabled:s,size:a,onStartTextFilter:i,hiddenFieldIds:l}){const c=v.useMemo(()=>{if(!l||l.length===0)return e;const D=new Set(l);return e.filter(B=>!D.has(B.id))},[e,l]),[u,d]=v.useState(!1),[f,p]=v.useState(),[h,m]=v.useState(""),[g,y]=v.useState([]),[b,x]=v.useState(),[S,k]=v.useState(),_=v.useRef(null),C=v.useRef(!1),E=v.useCallback(D=>{k(B=>B===D?void 0:D)},[]),j=v.useCallback(()=>k(void 0),[]);v.useEffect(()=>{u||k(void 0)},[u]);const N=v.useMemo(()=>c.find(D=>D.id===f),[c,f]),I=v.useMemo(()=>{const D=new Set;for(const B of t){const H=e.find(F=>F.id===B.fieldId);H&&H.kind!=="pick-multi"&&D.add(B.fieldId)}return D},[t,e]),A=v.useCallback(()=>{p(void 0),m(""),y([]),x(void 0)},[]);v.useEffect(()=>{u||A()},[u,A]),v.useEffect(()=>{u&&N?.kind==="text"&&_.current?.focus()},[u,N]);const R=v.useCallback((D,B)=>{const H=t.findIndex(q=>q.fieldId===D);if(B===void 0||Array.isArray(B)&&B.length===0){if(H===-1)return;n(t.filter((q,M)=>M!==H));return}if(H===-1){n([...t,{fieldId:D,value:B}]);return}const z=[...t];z[H]={fieldId:D,value:B},n(z)},[n,t]),L=v.useCallback(()=>{if(!N){x("Choose a property first.");return}if(I.has(N.id)){x(`Remove the existing ${N.label} filter before adding another.`);return}if(N.kind==="text"&&!h.trim()){x(`Enter a value for ${N.label}.`);return}if(N.kind==="multi-select"&&g.length===0){x(`Choose at least one ${N.label.toLowerCase()} value.`);return}const D=N.kind==="multi-select"?{fieldId:N.id,value:g}:{fieldId:N.id,value:h.trim()};n([...t,D]),d(!1)},[g,n,N,I,h,t]);return o.jsxs(Pf,{open:u,onOpenChange:d,children:[o.jsx(Bd,{asChild:!0,children:o.jsxs(ce,{variant:"outline",size:a,disabled:s,children:[o.jsx(qEn,{}),r]})}),o.jsx(Ud,{align:"end",className:"w-64 p-3",initialFocus:!1,finalFocus:()=>C.current?(C.current=!1,!1):!0,children:o.jsxs("div",{className:"grid gap-3",children:[N&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("button",{type:"button","aria-label":"Back to properties",className:"text-neutral3 hover:text-neutral6 transition-colors",onClick:()=>{p(void 0),m(""),y([]),x(void 0)},children:o.jsx(Zq,{className:"size-4"})}),o.jsx(EEn,{className:"text-neutral3 size-4 shrink-0"}),o.jsx("span",{className:"text-ui-sm text-neutral3",children:`${N.label} · is`})]}),!N&&o.jsx("div",{role:"menu",className:"max-h-[80dvh] overflow-auto",onKeyDown:D=>{if(D.key!=="ArrowDown"&&D.key!=="ArrowUp"&&D.key!=="Home"&&D.key!=="End")return;const B=Array.from(D.currentTarget.querySelectorAll("[data-filter-item]:not([disabled])"));if(B.length===0)return;D.preventDefault();const H=document.activeElement,F=B.findIndex(q=>q===H);let z;D.key==="Home"?z=0:D.key==="End"?z=B.length-1:D.key==="ArrowDown"?z=F<0?0:(F+1)%B.length:z=F<=0?B.length-1:F-1,B[z]?.focus()},children:c.length>0?c.map(D=>{const B=I.has(D.id);return D.kind==="pick-multi"?o.jsx(Lns,{field:D,tokens:t,onChange:R,open:S===D.id,onToggle:E,onClose:j},D.id):o.jsxs("button",{type:"button",role:"menuitem","data-filter-item":"",className:X("group flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-ui-md transition-colors","focus:bg-surface4 focus:text-neutral6 focus:outline-none",B?"cursor-not-allowed text-neutral2 opacity-70":"text-neutral4 hover:bg-surface4 hover:text-neutral6"),disabled:B,onClick:()=>{if(x(void 0),D.kind==="text"){n([...t,{fieldId:D.id,value:""}]),i?.(D.id),C.current=!0,d(!1);return}p(D.id)},children:[o.jsx("span",{className:"truncate",children:D.label}),B?o.jsx("span",{className:"text-neutral3 ml-auto",children:"In use"}):o.jsx(ywe,{className:"text-neutral3 ml-auto size-4 opacity-0 transition-opacity group-hover:opacity-100 group-focus:opacity-100"})]},D.id)}):o.jsx("div",{className:"text-ui-sm text-neutral3 px-2 py-1.5",children:"No matching property."})}),N&&N.kind==="text"&&o.jsx(Cn,{ref:_,size:"md",value:h,onChange:D=>{m(D.target.value),x(void 0)},placeholder:N.placeholder??`Enter ${N.label}`,onKeyDown:D=>{D.key==="Enter"&&(D.preventDefault(),L())}}),N&&N.kind==="multi-select"&&o.jsx(ac,{multiple:!0,options:N.options??[],value:g,onValueChange:D=>{y(D),x(void 0)},placeholder:N.placeholder??`Choose ${N.label}`,searchPlaceholder:`Search ${N.label.toLowerCase()}...`,emptyText:N.emptyText??"No option found.",size:"md"}),b&&o.jsx("div",{className:"text-ui-sm text-red-500",children:b}),N&&N.kind!=="pick-multi"&&o.jsxs("div",{className:"flex items-center justify-end gap-2",children:[o.jsx(ce,{variant:"ghost",size:"md",onClick:()=>d(!1),children:"Cancel"}),o.jsx(ce,{variant:"outline",size:"md",onClick:L,children:"Add filter"})]})]})})]})}function Lns({field:e,tokens:t,onChange:n,open:r,onToggle:s,onClose:a}){const i=v.useRef(null);return o.jsxs(Pf,{open:r,onOpenChange:l=>{l?s(e.id):a()},children:[o.jsx(Bd,{asChild:!0,children:o.jsxs("button",{type:"button",role:"menuitem","data-filter-item":"",className:X("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-ui-md text-neutral4 transition-colors hover:bg-surface4 hover:text-neutral6","focus:bg-surface4 focus:text-neutral6 focus:outline-none"),onKeyDown:l=>{l.key!=="ArrowRight"&&l.key!=="ArrowLeft"||(r||s(e.id),l.preventDefault(),requestAnimationFrame(()=>{i.current?.querySelector('input, button, [tabindex]:not([tabindex="-1"])')?.focus()}))},children:[r&&o.jsx(o1,{className:"text-neutral3 size-4 shrink-0"}),o.jsx("span",{className:"truncate",children:e.label}),!r&&o.jsx(o1,{className:"text-neutral3 ml-auto size-4 shrink-0"})]})}),o.jsx(Ud,{ref:i,side:"right",align:"start",sideOffset:8,className:"w-64 p-2",initialFocus:!1,onKeyDown:l=>{if(l.key!=="ArrowDown"&&l.key!=="ArrowUp"&&l.key!=="Home"&&l.key!=="End")return;const c=Array.from(l.currentTarget.querySelectorAll("[data-pick-multi-item]:not([disabled])"));if(c.length===0)return;l.preventDefault(),l.stopPropagation();const u=document.activeElement,d=c.findIndex(p=>p===u);let f;l.key==="Home"?f=0:l.key==="End"?f=c.length-1:l.key==="ArrowDown"?f=d<0?0:(d+1)%c.length:f=d<=0?c.length-1:d-1,c[f]?.focus()},"data-pick-multi-panel":!0,children:o.jsx(q9t,{field:e,tokens:t,onChange:n})})]})}const Fns={"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"},dae="MMM d, yyyy HH:mm",fae="Pick a wider time range — older traces may fall outside the current window.";function zns({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No traces for ${Fns[e]}`,description:fae}:t&&n?{title:`No traces between ${nr(t,dae)} and ${nr(n,dae)}`,description:fae}:t?{title:`No traces since ${nr(t,dae)}`,description:fae}:{title:"No traces yet",description:"Traces will appear here once agents, workflows, or tools are executed."}}const Bns=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=zns({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(k7,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(ce,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/tracing/overview",target:"_blank",rel:"noopener noreferrer",children:["Tracing Documentation ",o.jsx(mwe,{})]})})})};function Uns(e,t=100){if(e==null)return"";const n=Array.isArray(e)?e:e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.messages)?e.messages:null;if(n){const i=n.filter(l=>l?.role==="user").map(l=>typeof l.content=="string"?l.content:Array.isArray(l.content)?l.content.map(c=>typeof c=="string"?c:c?.type==="text"&&typeof c.text=="string"?c.text:"").filter(Boolean).join(" "):"").filter(Boolean).join(" | ");return i.length>t?i.slice(0,t)+"…":i}if(typeof e=="string")return e.length>t?e.slice(0,t)+"…":e;const r=JSON.stringify(e);return r.length>t?r.slice(0,t)+"…":r}function Vns(e){return e?.attributes?.finishReason==="length"}function qns(e){const t=e?.attributes?.usage;if(!t)return"The model stopped generating because it reached the maximum token limit. The response was truncated and may be incomplete.";const n=t.inputTokens??0,r=t.outputTokens??0,s=t.totalTokens??n+r;return n>0||r>0?`The model stopped generating because it reached the maximum token limit. The response was truncated and may be incomplete.
702
+ `),s=n.length,a=r.length,i=Array.from({length:s+1},()=>new Array(a+1).fill(0));for(let d=1;d<=s;d++)for(let f=1;f<=a;f++)n[d-1]===r[f-1]?i[d][f]=i[d-1][f-1]+1:i[d][f]=Math.max(i[d-1][f],i[d][f-1]);const l=[];let c=s,u=a;for(;c>0||u>0;)c>0&&u>0&&n[c-1]===r[u-1]?(l.push({type:"equal",text:n[c-1]}),c--,u--):u>0&&(c===0||i[c][u-1]>=i[c-1][u])?(l.push({type:"added",text:r[u-1]}),u--):(l.push({type:"removed",text:n[c-1]}),c--);return l.reverse()}function sbe(e){return e.type==="prompt_block"&&typeof e.content=="string"?e.content:null}function ies({promptBlockId:e}){const{data:t}=xL(e),n=t?.content??"";return n?o.jsx(Pa,{content:n,tooltip:"Copy prompt block text",size:"sm"}):null}function tP({block:e}){const t=sbe(e);return t?o.jsx(Pa,{content:t,tooltip:"Copy prompt text",size:"sm"}):e.type==="prompt_block_ref"&&(typeof e.promptBlockId=="string"||typeof e.id=="string")?o.jsx(ies,{promptBlockId:e.promptBlockId??e.id}):null}function oes({previousBlocks:e,currentBlocks:t}){const n=Array.isArray(e)?e:[],r=Array.isArray(t)?t:[],s=r.map(l=>sbe(l)??""),a=n.map(l=>sbe(l)??"");if(n.length<=1&&r.length<=1){const l=a[0]??"",c=s[0]??"",u=n[0];if(l===c)return o.jsxs("div",{className:"border-border1 bg-surface2 relative rounded-md border p-3",children:[u&&o.jsx("div",{className:"absolute top-2 right-2",children:o.jsx(tP,{block:u})}),o.jsx(ye,{variant:"ui-sm",className:"text-neutral4 font-mono whitespace-pre-wrap",children:l||"(empty)"})]});const d=EKe(l,c);return o.jsxs("div",{className:"border-border1 relative overflow-hidden rounded-md border font-mono text-sm",children:[u&&o.jsx("div",{className:"absolute top-2 right-2 z-10",children:o.jsx(tP,{block:u})}),d.map((f,p)=>o.jsxs("div",{className:X("px-3 py-0.5 whitespace-pre-wrap wrap-break-word",f.type==="removed"&&"bg-red-950/20 text-red-300",f.type==="added"&&"bg-green-950/20 text-green-300",f.type==="equal"&&"text-neutral4"),children:[o.jsx("span",{className:"text-neutral3/50 mr-2 inline-block w-4 shrink-0 select-none",children:f.type==="removed"?"−":f.type==="added"?"+":" "}),f.text||" "]},p))]})}const i=Math.max(n.length,r.length);return o.jsx("div",{className:"flex flex-col gap-2",children:Array.from({length:i},(l,c)=>{const u=n[c],d=r[c],f=a[c]??"",p=s[c]??"";if(!u&&d)return o.jsxs("div",{className:"rounded-md border border-green-900/30 bg-green-950/10 p-3 font-mono text-sm",children:[o.jsx(ye,{variant:"ui-xs",className:"mb-1 text-green-400",children:"+ Added block"}),o.jsx(ye,{variant:"ui-sm",className:"whitespace-pre-wrap text-green-300",children:p})]},c);if(u&&!d)return o.jsxs("div",{className:"relative rounded-md border border-red-900/30 bg-red-950/10 p-3 font-mono text-sm",children:[o.jsx("div",{className:"absolute top-2 right-2",children:o.jsx(tP,{block:u})}),o.jsx(ye,{variant:"ui-xs",className:"mb-1 text-red-400",children:"− Removed in latest"}),o.jsx(ye,{variant:"ui-sm",className:"whitespace-pre-wrap text-red-300",children:f})]},c);if(f===p)return o.jsxs("div",{className:"border-border1 bg-surface2 relative rounded-md border p-3",children:[u&&o.jsx("div",{className:"absolute top-2 right-2",children:o.jsx(tP,{block:u})}),o.jsx(ye,{variant:"ui-sm",className:"text-neutral4 font-mono whitespace-pre-wrap",children:f||"(empty)"})]},c);const h=EKe(f,p);return o.jsxs("div",{className:"border-border1 relative overflow-hidden rounded-md border font-mono text-sm",children:[u&&o.jsx("div",{className:"absolute top-2 right-2 z-10",children:o.jsx(tP,{block:u})}),h.map((m,g)=>o.jsxs("div",{className:X("px-3 py-0.5 whitespace-pre-wrap wrap-break-word",m.type==="removed"&&"bg-red-950/20 text-red-300",m.type==="added"&&"bg-green-950/20 text-green-300",m.type==="equal"&&"text-neutral4"),children:[o.jsx("span",{className:"text-neutral3/50 mr-2 inline-block w-4 shrink-0 select-none",children:m.type==="removed"?"−":m.type==="added"?"+":" "}),m.text||" "]},g))]},c)})})}function les({promptBlockId:e}){const{data:t,isLoading:n}=xL(e);if(n)return o.jsx("div",{className:"flex items-center justify-center py-4",children:o.jsx(Xt,{className:"h-4 w-4"})});const r=t?.content??"";return o.jsxs("div",{className:"border-border1 bg-surface2 relative rounded-md border p-3",children:[r&&o.jsx("div",{className:"absolute top-2 right-2",children:o.jsx(Pa,{content:r,tooltip:"Copy prompt block text",size:"sm"})}),t?.name&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mb-1 font-medium",children:t.name}),o.jsx(ye,{variant:"ui-sm",className:"text-neutral4 font-mono whitespace-pre-wrap",children:r||"(empty)"})]})}function W8t({blocks:e}){const t=Array.isArray(e)?e:[];return t.length===0?o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 py-2",children:"No instruction blocks configured"}):o.jsx("div",{className:"flex flex-col gap-2",children:t.map((n,r)=>{if(n.type==="prompt_block_ref"){const a=n.promptBlockId??n.id;return o.jsx(les,{promptBlockId:a},a??r)}const s=typeof n.content=="string"?n.content:"";return o.jsxs("div",{className:"border-border1 bg-surface2 relative rounded-md border p-3",children:[s&&o.jsx("div",{className:"absolute top-2 right-2",children:o.jsx(Pa,{content:s,tooltip:"Copy prompt text",size:"sm"})}),o.jsx(ye,{variant:"ui-sm",className:"text-neutral4 font-mono whitespace-pre-wrap",children:s||"(empty)"})]},n.id??r)})})}function ces({previousTools:e,currentTools:t}){const n=new Set(e?Object.keys(e):[]),r=new Set(t?Object.keys(t):[]),s=[...new Set([...n,...r])].sort();return o.jsx("div",{className:"flex flex-col gap-1.5",children:s.map(a=>{const i=n.has(a),l=r.has(a);let c;return i&&l?c="same":i?c="removed":c="added",o.jsxs("div",{className:X("flex items-center gap-2 rounded-md border px-3 py-1.5",c==="removed"&&"border-red-900/30 bg-red-950/10",c==="added"&&"border-green-900/30 bg-green-950/10",c==="same"&&"border-border1 bg-surface2"),children:[o.jsx(ye,{variant:"ui-sm",className:X("font-mono",c==="removed"&&"text-red-300 line-through",c==="added"&&"text-green-300",c==="same"&&"text-neutral5"),children:a}),c==="removed"&&o.jsx(un,{variant:"error",className:"ml-auto",children:"removed in latest"}),c==="added"&&o.jsx(un,{variant:"success",className:"ml-auto",children:"added in latest"})]},a)})})}function ues({tools:e}){const t=e?Object.entries(e):[];return t.length===0?o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 py-2",children:"No tools configured"}):o.jsx("div",{className:"flex flex-col gap-1.5",children:t.map(([n,r])=>o.jsxs("div",{className:"border-border1 bg-surface2 rounded-md border px-3 py-1.5",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral5 font-mono",children:n}),r?.description?o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-0.5",children:String(r.description)}):null]},n))})}function des({previousVars:e,currentVars:t}){const n=e?.properties??{},r=t?.properties??{},s=new Set(Object.keys(n)),a=new Set(Object.keys(r)),i=[...new Set([...s,...a])].sort();return i.length===0?o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 py-2",children:"No variables configured"}):o.jsx("div",{className:"flex flex-col gap-1.5",children:i.map(l=>{const c=s.has(l),u=a.has(l);let d;return c&&u?d="same":c?d="removed":d="added",o.jsxs("div",{className:X("flex items-center gap-2 rounded-md border px-3 py-1.5",d==="removed"&&"border-red-900/30 bg-red-950/10",d==="added"&&"border-green-900/30 bg-green-950/10",d==="same"&&"border-border1 bg-surface2"),children:[o.jsx(ye,{variant:"ui-sm",className:X("font-mono",d==="removed"&&"text-red-300 line-through",d==="added"&&"text-green-300",d==="same"&&"text-neutral5"),children:`{{${l}}}`}),d==="removed"&&o.jsx(un,{variant:"error",className:"ml-auto",children:"removed in latest"}),d==="added"&&o.jsx(un,{variant:"success",className:"ml-auto",children:"added in latest"})]},l)})})}function fes({variables:e}){const t=e?.properties??{},n=Object.entries(t);return n.length===0?o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 py-2",children:"No variables configured"}):o.jsx("div",{className:"flex flex-col gap-1.5",children:n.map(([r,s])=>o.jsxs("div",{className:"border-border1 bg-surface2 flex items-center gap-2 rounded-md border px-3 py-1.5",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral5 font-mono",children:`{{${r}}}`}),s?.type?o.jsx(un,{variant:"default",children:String(s.type)}):null]},r))})}function pes({agentId:e,selectedVersionId:t,latestVersionId:n}){const{form:r}=Ho(),s=r.watch("tools"),a=r.watch("variables"),i=r.watch("instructionBlocks"),l=s?Object.keys(s).length:0,{data:c,isLoading:u}=g4r({agentId:e,fromVersionId:t,toVersionId:n}),d=v.useMemo(()=>{const b=new Map;if(c?.diffs)for(const x of c.diffs)b.set(x.field,{previousValue:x.previousValue,currentValue:x.currentValue});return b},[c]),f=d.get("instructions"),p=d.get("tools"),h=d.get("requestContextSchema"),m=f?o.jsx(un,{variant:"warning",size:"sm",children:"modified"}):null,g=p?o.jsx(un,{variant:"warning",size:"sm",children:"modified"}):l>0?o.jsx(un,{variant:"default",size:"sm",children:`${l}`}):null,y=h?o.jsx(un,{variant:"warning",size:"sm",children:"modified"}):null;return u?o.jsx("div",{className:"flex items-center justify-center py-8",children:o.jsx(Xt,{className:"h-5 w-5"})}):o.jsxs(Dc,{defaultTab:"variables",className:"flex min-h-full flex-col overflow-visible",children:[o.jsxs(Mc,{variant:"pill-ghost",className:"shrink-0",children:[o.jsx(Rr,{value:"variables",children:o.jsx(aT,{title:"Variables",icon:o.jsx(Ey,{}),badge:y})}),o.jsx(Rr,{value:"instructions",children:o.jsx(aT,{title:"System Prompt",icon:o.jsx(Ibe,{}),badge:m})}),o.jsx(Rr,{value:"tools",children:o.jsx(aT,{title:"Tools",icon:o.jsx(zp,{}),badge:g})})]}),o.jsx(Xr,{value:"variables",className:"px-4 py-4",children:h?o.jsx(des,{previousVars:h.previousValue,currentVars:h.currentValue}):o.jsx(fes,{variables:a})}),o.jsx(Xr,{value:"instructions",className:"px-4 py-4",children:f?o.jsx(oes,{previousBlocks:f.previousValue,currentBlocks:f.currentValue}):o.jsx(W8t,{blocks:i})}),o.jsx(Xr,{value:"tools",className:"px-4 py-4",children:p?o.jsx(ces,{previousTools:p.previousValue,currentTools:p.currentValue}):o.jsx(ues,{tools:s})})]})}function hes({agentId:e,selectedVersionId:t,latestVersionId:n}){const{form:r,readOnly:s}=Ho(),a=r.watch("tools"),i=r.watch("instructionBlocks"),l=r.watch("variables"),c=a?Object.keys(a).length:0,u=v.useMemo(()=>Object.entries(l?.properties??{}),[l]),d=s&&!!t&&!!n&&t!==n;return o.jsxs("div",{className:X("flex flex-col h-full"),children:[o.jsx("div",{className:"border-border1 border-b px-4 py-3"}),o.jsx(Br,{className:"min-h-0 flex-1",children:d?o.jsx(pes,{agentId:e,selectedVersionId:t,latestVersionId:n}):o.jsxs(Dc,{defaultTab:"variables",className:"flex min-h-full flex-col overflow-visible",children:[o.jsxs(Mc,{variant:"pill-ghost",className:"shrink-0",children:[o.jsx(Rr,{value:"variables",children:o.jsx(aT,{title:"Variables",icon:o.jsx(Ey,{})})}),o.jsx(Rr,{value:"instructions",children:o.jsx(aT,{title:"System Prompt",icon:o.jsx(Ibe,{})})}),o.jsx(Rr,{value:"tools",children:o.jsx(aT,{title:"Tools",icon:o.jsx(zp,{}),badge:c>0?o.jsx(un,{variant:"default",size:"sm",children:`${c}`}):void 0})})]}),o.jsx(Xr,{value:"variables",className:"py-0",children:o.jsxs("div",{className:"flex flex-col gap-1 px-4 py-4",children:[u.length>0?o.jsx("div",{className:"flex flex-col",children:u.map(([f,p])=>o.jsx(H8t,{name:f,prop:p,depth:0},f))}):null,o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-1",children:u.length>0?"Defined via requestContextSchema in code.":"No variables defined. Add a requestContextSchema to your agent to define variables."})]})}),o.jsxs(Xr,{value:"instructions",className:"px-4 py-0 pb-4",children:[o.jsx("div",{className:"flex flex-col gap-3 pt-4 pb-2",children:o.jsxs(ye,{variant:"ui-sm",className:"text-neutral3 font-normal",children:["Add instruction blocks to your agent. Blocks are combined in order to form the system prompt. You can"," ",o.jsxs(Pn,{children:[o.jsx(An,{className:"text-neutral3 hover:text-neutral5 inline cursor-pointer underline decoration-dotted",children:"use variables"}),o.jsx(Rn,{side:"bottom",align:"start",className:"max-w-72",children:o.jsxs("span",{children:["Use ",o.jsx("code",{className:"text-accent1 font-medium",children:"{{variableName}}"})," syntax to insert dynamic values into your instruction blocks."]})})]})," ","as part of your instruction blocks."]})}),s?o.jsx(W8t,{blocks:i}):o.jsx(y8t,{})]}),o.jsx(Xr,{value:"tools",className:"px-4 py-0 pb-4",children:o.jsx(x8t,{})})]})})]})}function oae(e){return typeof e=="object"&&e!==null}function mes(e){if(!oae(e))return{};const t={};return typeof e.maxSteps=="number"&&(t.maxSteps=e.maxSteps),oae(e.modelSettings)&&(t.modelSettings=e.modelSettings),oae(e.providerOptions)&&(t.providerOptions=e.providerOptions),t}function RNe(e){if(!e)return{modelSettings:{}};const t=mes(e.defaultOptions),{maxOutputTokens:n,...r}=t.modelSettings??{};return{modelSettings:{...r,...n!==void 0&&{maxTokens:n},...t.maxSteps!==void 0&&{maxSteps:t.maxSteps},...t.providerOptions!==void 0&&{providerOptions:t.providerOptions}}}}function ges(e){const t=e?.properties;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}function ves({labelTooltip:e,variablesSchema:t}){const{setSchemaValues:n,schemaValues:r}=Mwe(),s=JSON.stringify(r),a=v.useMemo(()=>{try{return fm(um(t))}catch(i){return console.error("Failed to parse variables schema:",i),null}},[t]);return a?o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx(Qwe,{tooltip:e,children:"Request Context"}),o.jsx(Pa,{content:s})]}),o.jsx(j3,{schema:a,onSubmit:n,submitButtonLabel:"Save",defaultValues:r})]}):o.jsx("div",{className:"p-4",children:o.jsx(ye,{variant:"ui-sm",className:"text-red-400",children:"Failed to parse request context schema"})})}function yes({mode:e,onModeChange:t}){return o.jsxs("div",{className:"border-border1 flex items-center gap-1 rounded-md border p-0.5",children:[o.jsxs("button",{type:"button","aria-pressed":e==="form",onClick:()=>t("form"),className:X("flex items-center gap-1.5 px-2 py-1 rounded text-xs transition-colors",e==="form"?"bg-surface3 text-neutral5":"text-neutral3 hover:text-neutral5"),children:[o.jsx(qe,{size:"sm",children:o.jsx(Dbe,{})}),"Form"]}),o.jsxs("button",{type:"button","aria-pressed":e==="json",onClick:()=>t("json"),className:X("flex items-center gap-1.5 px-2 py-1 rounded text-xs transition-colors",e==="json"?"bg-surface3 text-neutral5":"text-neutral3 hover:text-neutral5"),children:[o.jsx(qe,{size:"sm",children:o.jsx(FN,{})}),"JSON"]})]})}function bes({requestContextSchema:e,freeformEditorClassName:t,requestContextTooltip:n}){const s=dMt()?.form.watch("variables"),[a,i]=v.useState("form"),l=ges(s),c=!!e||l;return o.jsx("div",{className:"space-y-4",children:c?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"flex items-center justify-end",children:o.jsx(yes,{mode:a,onModeChange:i})}),a==="form"?e?o.jsx(A1e,{requestContextSchema:e,labelTooltip:n}):l?o.jsx(ves,{variablesSchema:s,labelTooltip:n}):null:o.jsx(Uye,{editorClassName:t,labelTooltip:n})]}):o.jsx(Uye,{editorClassName:t,labelTooltip:n})})}const xes=()=>{const{debugMode:e,setDebugMode:t}=v.useContext(Bl);return o.jsxs(o.Fragment,{children:[o.jsx(ye,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Debug Mode"}),o.jsx(zo,{checked:e,onCheckedChange:n=>t(n)})]})},wes=({className:e,editorClassName:t="h-[400px]",hideTitle:n=!1,showEditorHeader:r=!1}={})=>{const s=Yx(),{settings:a,setSettings:i,entityType:l}=tH(),c=d=>{if(!d)return i({...a,tracingOptions:void 0});try{const f=JSON.parse(d);typeof f=="object"&&f!==null&&i({...a,tracingOptions:f})}catch{}};let u="{}";try{u=JSON.stringify(a?.tracingOptions,null,2)}catch{}return o.jsxs("div",{className:X("px-5 py-2",!n&&"space-y-2",e),children:[!n&&o.jsx(ye,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),r&&o.jsxs("div",{className:"flex items-center justify-between pb-2",children:[o.jsx(ye,{as:"label",variant:"ui-md",className:"text-neutral3",children:"Tracing Options (JSON)"}),o.jsx(ye,{as:"span",variant:"ui-xs",className:"text-neutral3",children:"Auto-applied on valid JSON"})]}),o.jsx(Qu,{value:u,onChange:c,theme:s,extensions:[Rp],className:X(t,"overflow-y-scroll rounded-lg border border-border1 bg-surface2 overflow-hidden p-3","[&_.cm-editor]:!bg-surface2 [&_.cm-gutters]:!bg-surface2")}),l==="workflow"&&o.jsx(xes,{})]})},jKe="h-[260px] md:h-[360px]";function Z8t({requestContextSchema:e}){return o.jsx(Br,{className:"w-full",maxHeight:"min(600px, calc(100dvh - 8rem))",children:o.jsxs("div",{className:"space-y-4 p-4",children:[o.jsx(ye,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Run options"}),o.jsxs("div",{className:"grid gap-5 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]",children:[o.jsx("section",{className:"min-w-0",children:o.jsx(bes,{requestContextSchema:e,requestContextTooltip:"Request context values are passed into experiments and test chats.",freeformEditorClassName:jKe})}),o.jsx("section",{className:"min-w-0",children:o.jsx(wes,{className:"px-0 py-0",editorClassName:jKe,hideTitle:!0,showEditorHeader:!0})})]})]})})}const Ses={align:"shift"};function G8t({requestContextSchema:e}){return o.jsxs(Pf,{children:[o.jsx(Bd,{asChild:!0,children:o.jsx(ce,{variant:"default",size:"icon-md",type:"button",tooltip:"Run options","data-testid":"composer-run-options-trigger",children:o.jsx(HV,{className:"text-neutral3 hover:text-neutral6 h-5 w-5"})})}),o.jsx(Ud,{align:"start",collisionAvoidance:Ses,className:"w-[min(760px,calc(100vw-2rem))] p-0",children:o.jsx(Z8t,{requestContextSchema:e})})]})}function kes({ctx:e}){const{isDirty:t}=k1e({control:e.form.control}),n=e.handleSaveDraft,r=e.isSavingDraft??!1,s=e.isCodeSourceAgent??!1;if(!t)return null;const a=s?"Save to filesystem":"Save draft",i=s?"You have unsaved changes to the agent configuration. Save to filesystem to ensure the chat uses your latest changes.":"You have unsaved changes to the agent configuration. Save your draft to ensure the chat uses your latest changes.";return o.jsx(En,{variant:"warning",title:"Unsaved changes",className:"mx-4 mt-3 mb-0",action:n&&o.jsxs(ce,{type:"button",variant:"default",size:"sm",onClick:()=>n(),disabled:r,children:[o.jsx(jd,{className:"h-3.5 w-3.5"}),r?"Saving...":a]}),children:o.jsx(En.Message,{children:i})})}function Oes({agentId:e,agentName:t,modelVersion:n,agentVersionId:r,hasMemory:s}){const a=v.useMemo(()=>xo(),[e]),i=zl(),l=Object.keys(i).length>0,c=dMt(),{data:u}=mc(e),d=v.useMemo(()=>RNe(u),[u]);return o.jsx(wEe,{agentId:e,defaultSettings:d,children:o.jsx(fZ,{children:o.jsxs(pZ,{agentId:e,threadId:a,enabled:!!u?.browserTools?.length,children:[o.jsx(TEe,{children:o.jsx(kEe,{children:o.jsx(xFr,{enabled:!0,threadId:a,agentId:e,requestContext:l?i:void 0,children:o.jsxs("div",{className:"flex h-full flex-col",children:[c&&o.jsx(kes,{ctx:c}),o.jsx("div",{className:"min-h-0 flex-1",children:o.jsx(MNe,{agentId:e,agentName:t,modelVersion:n,agentVersionId:r,supportsMemory:u?.supportsMemory,threadId:a,memory:s,modelList:u?.modelList,isNewThread:!0,runOptionsSlot:o.jsx(G8t,{requestContextSchema:u?.requestContextSchema})},a)})]})})},a)}),o.jsx(JCe,{})]},`session-${e}-${a}`)},`browser-${e}-${a}`)})}function _es(e){return new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})}function Ces({agentId:e,activeVersionId:t,selectedVersionId:n,onVersionSelect:r,isDirty:s,isSavingDraft:a,isPublishing:i,hasDraft:l,readOnly:c,isCodeSourceAgent:u=!1,showCodeModeActions:d=!1,canOpenPr:f=!1,openPrTitle:p,onSaveDraft:h,onPublish:m,onDownloadJson:g,onOpenPr:y,isViewingPreviousVersion:b=!1}){const[x,S]=v.useState(!1),[k,_]=v.useState(""),{data:C}=K1({agentId:e,params:{orderBy:{direction:"DESC"}}}),E=v.useMemo(()=>C?.versions??[],[C?.versions]),j=E[0],I=(t?E.find(H=>H.id===t):void 0)?.versionNumber,A=v.useMemo(()=>E.map(H=>{const F=H.id===t,z=I!==void 0&&H.versionNumber>I;return{value:H.id,label:`${u?"Save":"v"}${H.versionNumber} - ${_es(H.createdAt)}`,description:H.changeMessage||void 0,end:u?o.jsx(un,{variant:F?"success":"info",children:F?"Current":"Saved"}):F?o.jsx(un,{variant:"success",children:"Published"}):z?o.jsx(un,{variant:"info",children:"Draft"}):void 0}}),[E,t,I,u]),R=n??j?.id??"",L=c||!s||a||i,D=u?"Code mode saves write override JSON to filesystem-backed editor storage. This dropdown shows saved override snapshots for this agent.":"Changes are saved as draft versions. When you're ready, publish a version to make it the active configuration used in production.",B=v.useCallback(async()=>{if(a)return;const H=k.trim();await h(H||void 0),S(!1),_("")},[k,h,a]);return{versionSelector:o.jsxs("div",{className:"border-border1 bg-surface3 flex items-center gap-2 border-b px-4 py-3",children:[E.length>0?o.jsx(ac,{options:A,value:R,onValueChange:r,placeholder:"Select version...",variant:"ghost",className:"min-w-0 flex-1"}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:u?"No filesystem saves yet":"No versions yet"}),R&&o.jsx(Pa,{content:R,tooltip:"Copy version ID",size:"sm"}),o.jsxs(Pn,{children:[o.jsx(An,{"aria-label":"Version information",className:"text-neutral3 hover:text-neutral5 shrink-0 rounded-sm transition-colors focus-visible:ring-1 focus-visible:ring-white/30 focus-visible:outline-hidden",children:o.jsx(qe,{size:"sm",children:o.jsx(Bx,{})})}),o.jsx(Rn,{side:"bottom",align:"start",className:"max-w-56",children:D})]}),o.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-2",children:[c&&o.jsx(un,{variant:"warning",children:"Read-only"}),!c&&l&&!u&&o.jsx(un,{variant:"info",children:"Unpublished"})]})]}),actionBar:o.jsxs("div",{className:"border-border1 bg-surface3 flex items-center justify-end border-t px-3 py-2",children:[d?o.jsxs(Mr,{className:"flex-wrap justify-end",children:[o.jsxs(ce,{variant:"default",size:"md",onClick:()=>{g?.()},children:[o.jsx(qe,{size:"sm",children:o.jsx(vf,{})}),"Download JSON"]}),f?o.jsxs(ce,{variant:"primary",size:"md",onClick:()=>{y?.()},title:p,children:[o.jsx(qe,{size:"sm",children:o.jsx(mit,{})}),"Open PR"]}):o.jsx(ce,{variant:"primary",size:"md",onClick:()=>{h()},disabled:L,children:a?o.jsxs(o.Fragment,{children:[o.jsx(Xt,{className:"size-3.5"}),"Saving…"]}):o.jsxs(o.Fragment,{children:[o.jsx(qe,{size:"sm",children:o.jsx(jd,{})}),"Save to filesystem"]})})]}):c&&!b?null:o.jsxs(Mr,{className:"flex-wrap justify-end",children:[o.jsxs(Mr,{spacing:"close",children:[o.jsx(ce,{variant:"default",size:"md",onClick:()=>h(),disabled:L,children:a?o.jsxs(o.Fragment,{children:[o.jsx(Xt,{className:"size-3.5"}),"Saving…"]}):o.jsxs(o.Fragment,{children:[o.jsx(qe,{size:"sm",children:o.jsx(jd,{})}),"Save New Version"]})}),o.jsxs(dt,{children:[o.jsx(dt.Trigger,{asChild:!0,children:o.jsx(ce,{variant:"default",size:"md",disabled:L,"aria-label":"More save options",children:o.jsx(Na,{className:"size-3.5"})})}),o.jsx(dt.Content,{align:"end",children:o.jsxs(dt.Item,{onSelect:()=>S(!0),children:[o.jsx(qe,{size:"sm",children:o.jsx(dT,{})}),"Save with message"]})})]})]}),o.jsx(ce,{variant:"primary",size:"md",onClick:m,disabled:b?n===t||i||a:c||!l||i||a,children:i?o.jsxs(o.Fragment,{children:[o.jsx(Xt,{className:"size-3.5"}),"Publishing…"]}):o.jsxs(o.Fragment,{children:[o.jsx(qe,{size:"sm",children:o.jsx(fa,{})}),b?"Publish This Version":"Publish"]})})]}),o.jsx(br,{open:x,onOpenChange:S,children:o.jsxs(xr,{children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Save New Version"}),o.jsx(Ks,{children:"Add a message to describe the changes in this version."})]}),o.jsx($r,{className:"py-1",children:o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"change-message",children:"Change message"}),o.jsx(Cn,{id:"change-message",placeholder:"Describe what changed...",value:k,className:"focus:ring-white/50",onChange:H=>_(H.target.value),onKeyDown:H=>{H.key==="Enter"&&B()},disabled:a,autoFocus:!0})]})}),o.jsxs(Tc,{className:"px-6",children:[o.jsx(ce,{variant:"default",size:"sm",onClick:()=>S(!1),children:"Cancel"}),o.jsxs(ce,{variant:"primary",size:"sm",onClick:B,disabled:a,children:[o.jsx(qe,{size:"sm",children:o.jsx(jd,{})}),"Save Version"]})]})]})})]})}}function Ees({agentId:e,activeVersionId:t,selectedVersionId:n,latestVersionId:r,onVersionSelect:s,isDirty:a,isSavingDraft:i,isPublishing:l,hasDraft:c,readOnly:u,isCodeSourceAgent:d,showCodeModeActions:f,canOpenPr:p,openPrTitle:h,onSaveDraft:m,onPublish:g,onDownloadJson:y,onOpenPr:b,isViewingPreviousVersion:x}){const{versionSelector:S,actionBar:k}=Ces({agentId:e,activeVersionId:t,selectedVersionId:n,onVersionSelect:s,isDirty:a,isSavingDraft:i,isPublishing:l,hasDraft:c,readOnly:u,isCodeSourceAgent:d,showCodeModeActions:f,canOpenPr:p,openPrTitle:h,onSaveDraft:m,onPublish:g,onDownloadJson:y,onOpenPr:b,isViewingPreviousVersion:x});return o.jsxs(MEe,{children:[S,o.jsx("div",{className:"px-4 pt-3",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"Edit your agent's system prompt, tools, and variables below."})}),o.jsx("div",{className:"min-h-0 flex-1",children:o.jsx(hes,{agentId:e,selectedVersionId:n,latestVersionId:r})}),k]})}function jes({agentId:e,agentName:t,modelVersion:n,agentVersionId:r,hasMemory:s,activeVersionId:a,selectedVersionId:i,latestVersionId:l,onVersionSelect:c,isDirty:u,isSavingDraft:d,isPublishing:f,hasDraft:p,readOnly:h,isCodeSourceAgent:m,showCodeModeActions:g,canOpenPr:y,openPrTitle:b,onSaveDraft:x,onPublish:S,onDownloadJson:k,onOpenPr:_,isViewingPreviousVersion:C}){return o.jsx(_Ne,{agentId:e,leftDrawerLabel:"Open configuration",leftSlot:o.jsx(Ees,{agentId:e,activeVersionId:a,selectedVersionId:i,latestVersionId:l,onVersionSelect:c,isDirty:u,isSavingDraft:d,isPublishing:f,hasDraft:p,readOnly:h,isCodeSourceAgent:m,showCodeModeActions:g,canOpenPr:y,openPrTitle:b,onSaveDraft:x,onPublish:S,onDownloadJson:k,onOpenPr:_,isViewingPreviousVersion:C}),children:o.jsx(Oes,{agentId:e,agentName:t,modelVersion:n,agentVersionId:r,hasMemory:s})})}function NN(e,t){return typeof t=="number"||/^\d+(\.\d+)*$/.test(String(t))?`${e} v${t}`:`${e} ${t}`}const kD=(e,t,n)=>{const r=We();return yt({queryKey:["dataset-experiments",e,t,n],queryFn:()=>r.listDatasetExperiments(e,t),enabled:!!e,select:s=>{if(!n)return s;const a=s.experiments.filter(i=>!(n.status&&i.status!==n.status||n.targetType&&i.targetType!==n.targetType||n.targetId&&i.targetId!==n.targetId));return{...s,experiments:a}}})},RV=(e,t)=>{const n=We();return yt({queryKey:["dataset-experiment",e,t],queryFn:()=>n.getDatasetExperiment(e,t),enabled:!!e&&!!t,gcTime:0,staleTime:0,refetchInterval:r=>{const s=r.state.data?.status;return s==="running"||s==="pending"?2e3:!1}})},TKe=100,LG=({datasetId:e,experimentId:t,experimentStatus:n})=>{const r=We(),{inView:s,setRef:a}=W_(),i=M1({queryKey:["dataset-experiment-results",e,t,n],queryFn:async({pageParam:l})=>r.listDatasetExperimentResults(e,t,{page:l,perPage:TKe}),initialPageParam:0,getNextPageParam:(l,c,u)=>{if(!l?.results?.length)return;const d=(u+1)*TKe,f=l?.pagination?.total??0;if(!(d>=f))return u+1},enabled:!!e&&!!t,refetchInterval:n==="running"||n==="pending"?2e3:!1,select:l=>l.pages.flatMap(c=>c?.results??[])});return v.useEffect(()=>{s&&i.hasNextPage&&!i.isFetchingNextPage&&i.fetchNextPage()},[s,i.hasNextPage,i.isFetchingNextPage]),{...i,setEndOfListElement:a}},Q8t=(e,t)=>{const n=We();return yt({queryKey:["dataset-experiment-scores",e,t],queryFn:async()=>{const r=[];let s=0;const a=100;for(;;){const l=await n.listScoresByRunId({runId:e,page:s,perPage:a});if(r.push(...l.scores),!l.pagination.hasMore)break;s++}const i={};for(const l of r)i[l.entityId]||(i[l.entityId]=[]),i[l.entityId].push(l);return i},enabled:!!e,refetchInterval:t==="running"||t==="pending"?2e3:!1})};function Tes(e){return new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Nes({status:e}){switch(e){case"completed":return o.jsxs(un,{variant:"success",className:"gap-1",children:[o.jsx(lO,{className:"h-3 w-3"}),"completed"]});case"failed":return o.jsxs(un,{variant:"error",className:"gap-1",children:[o.jsx(M2,{className:"h-3 w-3"}),"failed"]});case"running":return o.jsxs(un,{variant:"info",className:"gap-1",children:[o.jsx(ia,{className:"h-3 w-3 animate-spin"}),"running"]});case"pending":return o.jsxs(un,{variant:"default",className:"gap-1",children:[o.jsx(uT,{className:"h-3 w-3"}),"pending"]});default:return o.jsx(un,{variant:"default",children:e})}}function abe(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Ies(e){return Array.isArray(e)?e.flatMap(t=>{if(!t||typeof t!="object")return[];const n=t;return[{toolName:typeof n.toolName=="string"?n.toolName:"Unknown tool",args:n.args&&typeof n.args=="object"&&!Array.isArray(n.args)?n.args:{}}]}):[]}function Aes(e){const t=e&&typeof e=="object"?e:{};return{text:typeof t.text=="string"?t.text:void 0,object:t.object&&typeof t.object=="object"?t.object:void 0,toolCalls:Ies(t.toolCalls),toolResults:Array.isArray(t.toolResults)?t.toolResults:[],usage:t.usage&&typeof t.usage=="object"?t.usage:void 0,traceId:typeof t.traceId=="string"?t.traceId:void 0,error:typeof t.error=="string"?t.error:t.error?String(t.error):void 0}}function Res({traceId:e}){const t=We(),[n,r]=v.useState(!1),{data:s,isLoading:a,isError:i}=yt({queryKey:["trajectory",e],queryFn:()=>t.getTraceTrajectory(e),enabled:n});return o.jsxs(Tf,{open:n,onOpenChange:r,children:[o.jsxs($d,{className:"flex items-center gap-1.5 text-xs font-medium text-purple-400 hover:text-purple-300",children:[o.jsx(pa,{className:"h-3 w-3 shrink-0"}),"Trajectory Steps"]}),o.jsx(Md,{children:a?o.jsxs("div",{className:"mt-1 flex items-center gap-2 px-3 py-2",children:[o.jsx(Xt,{className:"h-3 w-3"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:"Loading trajectory..."})]}):i?o.jsx(ye,{variant:"ui-xs",className:"mt-1 px-3 py-2 text-red-400",children:"Failed to load trajectory steps"}):s?.steps&&s.steps.length>0?o.jsxs("div",{className:"mt-1 space-y-1",children:[s.steps.map((l,c)=>o.jsxs("div",{className:"bg-surface1 flex items-center gap-2 rounded px-3 py-1.5 text-xs",children:[o.jsx(Js,{size:"small",color:"purple",children:String(l.stepType||"step")}),o.jsx("span",{className:"text-neutral5 font-mono font-medium",children:String(l.name||`Step ${c+1}`)}),typeof l.durationMs=="number"&&o.jsxs("span",{className:"text-neutral2 ml-auto",children:[l.durationMs,"ms"]})]},c)),typeof s.totalDurationMs=="number"&&o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3 px-3 py-1",children:["Total: ",s.totalDurationMs,"ms"]})]}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral2 mt-1 px-3 py-2",children:"No trajectory steps found"})})]})}function Pes({output:e,traceId:t,onViewTrace:n}){const r=Aes(e),s=t||r.traceId;return o.jsxs("div",{className:"space-y-2",children:[r.text?o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Response"}),o.jsx("div",{className:"text-neutral5 bg-surface1 max-h-48 overflow-y-auto rounded px-3 py-2 text-sm wrap-break-word whitespace-pre-wrap",children:r.text})]}):null,r.object&&o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Structured Output"}),o.jsx("pre",{className:"text-neutral4 bg-surface1 max-h-48 overflow-x-auto overflow-y-auto rounded px-3 py-2 text-xs wrap-break-word whitespace-pre-wrap",children:JSON.stringify(r.object,null,2)})]}),r.toolCalls.length>0&&o.jsxs("div",{className:"space-y-1",children:[o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:["Tool Calls (",r.toolCalls.length,")"]}),o.jsx("div",{className:"space-y-1",children:r.toolCalls.map((a,i)=>o.jsxs(Tf,{children:[o.jsxs($d,{className:"text-neutral4 hover:text-neutral5 bg-surface1 flex w-full items-center gap-1.5 rounded px-2 py-1 text-left text-xs",children:[o.jsx(pa,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:"font-mono font-medium",children:a.toolName})]}),o.jsx(Md,{children:o.jsx("pre",{className:"text-neutral4 bg-surface2 mt-1 ml-4 max-h-32 overflow-x-auto overflow-y-auto rounded px-3 py-2 text-xs wrap-break-word whitespace-pre-wrap",children:JSON.stringify(a.args,null,2)})})]},i))})]}),r.toolResults.length>0&&o.jsxs("div",{className:"space-y-1",children:[o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:["Tool Results (",r.toolResults.length,")"]}),o.jsx("div",{className:"space-y-1",children:r.toolResults.map((a,i)=>o.jsxs(Tf,{children:[o.jsxs($d,{className:"text-neutral4 hover:text-neutral5 bg-surface1 flex w-full items-center gap-1.5 rounded px-2 py-1 text-left text-xs",children:[o.jsx(pa,{className:"h-3 w-3 shrink-0"}),o.jsxs("span",{className:"font-mono",children:["Result ",i+1]})]}),o.jsx(Md,{children:o.jsx("pre",{className:"text-neutral4 bg-surface2 mt-1 ml-4 max-h-32 overflow-x-auto overflow-y-auto rounded px-3 py-2 text-xs wrap-break-word whitespace-pre-wrap",children:JSON.stringify(a,null,2)})})]},i))})]}),r.usage&&o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Usage"}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral2 font-mono",children:[r.usage.promptTokens," prompt · ",r.usage.completionTokens," completion · ",r.usage.totalTokens," ","total"]})]}),s&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Trace"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral2 truncate font-mono",children:s}),o.jsx(Pa,{content:s,tooltip:"Copy trace ID",size:"sm"}),n&&o.jsxs("button",{type:"button",onClick:()=>n(s),className:"text-accent1 hover:text-accent2 flex cursor-pointer items-center gap-1 text-xs transition-colors",children:[o.jsx(Sa,{className:"h-3 w-3"}),"View Trace"]})]}),!r.text&&!r.object&&r.toolCalls.length===0&&o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Output"}),o.jsx("pre",{className:"text-neutral4 bg-surface1 max-h-48 overflow-x-auto overflow-y-auto rounded px-3 py-2 text-xs wrap-break-word whitespace-pre-wrap",children:abe(e)})]})]})}function $es({experiment:e,onBack:t,onSendToReview:n,onCreateScorer:r}){const[s,a]=v.useState(new Set),i=e.status,{data:l,isLoading:c,setEndOfListElement:u,isFetchingNextPage:d,hasNextPage:f}=LG({datasetId:e.datasetId,experimentId:e.id,experimentStatus:i}),{data:p}=Q8t(e.id,i),h=e.targetType==="agent"?e.targetId:void 0,{data:m}=K1({agentId:h}),g=m?.versions??[],{navigate:y}=yn(),b=_=>{a(C=>{const E=new Set(C);return E.has(_)?E.delete(_):E.add(_),E})},x=()=>{if(!l)return;const _=l.filter(C=>!!C.error).map(C=>C.id);a(new Set(_))},S=()=>a(new Set),k=l?.filter(_=>s.has(_.id))||[];return o.jsxs("div",{className:"flex h-full flex-col",children:[o.jsxs("div",{className:"border-border1 flex items-center gap-2 border-b px-4 py-3",children:[o.jsxs("button",{type:"button",onClick:t,className:"text-neutral3 hover:text-neutral5 flex cursor-pointer items-center gap-1 transition-colors",children:[o.jsx(qe,{size:"sm",children:o.jsx(Ac,{})}),o.jsx(ye,{variant:"ui-xs",children:"Back"})]}),o.jsx("div",{className:"flex-1"}),o.jsx(Nes,{status:e.status}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral2",children:[e.datasetName,e.datasetVersion!=null&&` ${NN("Dataset",e.datasetVersion)}`,e.agentVersion&&(()=>{const _=g.find(E=>E.id===e.agentVersion),C=NN("Agent",_?_.versionNumber:e.agentVersion);return o.jsxs(o.Fragment,{children:[" · ",o.jsx("button",{type:"button",className:"hover:text-neutral5 cursor-pointer underline transition-colors",onClick:()=>y(`/agents/${h}/editor?version=${encodeURIComponent(e.agentVersion)}`),children:C})]})})()," · ",e.startedAt?Tes(e.startedAt):"-"]})]}),s.size>0&&o.jsxs("div",{className:"bg-surface3 border-border1 flex items-center gap-2 border-b px-4 py-2",children:[o.jsxs(ye,{variant:"ui-xs",className:"text-neutral5 font-medium",children:[s.size," selected"]}),o.jsx("div",{className:"flex-1"}),r&&o.jsxs(ce,{variant:"outline",size:"sm",onClick:()=>{r(k.map(_=>({input:_.input,output:_.output})))},children:[o.jsx(qe,{size:"sm",children:o.jsx(Pqt,{})}),"Create Scorer"]}),n&&o.jsxs(ce,{variant:"outline",size:"sm",onClick:()=>{n(k.map(_=>{const C=p?.[_.itemId],E={};if(C)for(const j of C)typeof j.score=="number"&&(E[j.scorerId||"unknown"]=j.score);return{id:_.id,input:_.input,output:_.output,error:_.error,itemId:_.itemId,datasetId:e.datasetId,scores:E,experimentId:e.id,traceId:_.traceId??void 0}}))},children:[o.jsx(qe,{size:"sm",children:o.jsx(UV,{})}),"Send to Review"]}),o.jsx(ce,{variant:"ghost",size:"sm",onClick:S,children:"Clear"})]}),l&&l.length>0&&s.size===0&&o.jsx("div",{className:"border-border1 flex items-center gap-2 border-b px-4 py-2",children:o.jsx(ce,{variant:"ghost",size:"sm",onClick:x,children:"Select all failures"})}),o.jsx(Br,{className:"min-h-0 flex-1",children:c?o.jsx("div",{className:"flex items-center justify-center py-8",children:o.jsx(Xt,{className:"h-5 w-5"})}):!l||l.length===0?o.jsx("div",{className:"px-4 py-8 text-center",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral2",children:"No results yet"})}):o.jsxs("div",{children:[l.map(_=>{const C=!!_.error,E=p?.[_.itemId]??[],j=s.has(_.id);return o.jsxs("div",{className:X("border-b border-border1 px-4 py-3 space-y-2",j&&"bg-surface3/50"),children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(zo,{checked:j,onCheckedChange:()=>b(_.id)}),o.jsx(un,{variant:C?"error":"success",children:C?"Error":"Success"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral2 font-mono",children:_.itemId.slice(0,8)}),E.length>0&&o.jsxs("div",{className:"ml-auto flex flex-wrap items-center gap-2",children:[E.filter(N=>N.entityType!=="TRAJECTORY").map(N=>o.jsxs(un,{variant:"default",children:[N.scorerId,": ",N.score.toFixed(3)]},N.scorerId)),E.filter(N=>N.entityType==="TRAJECTORY").map(N=>o.jsxs(Js,{size:"small",color:"purple",children:[N.scorerId,": ",N.score.toFixed(3)]},N.scorerId))]})]}),E.some(N=>N.entityType==="TRAJECTORY")&&o.jsxs(Tf,{children:[o.jsxs($d,{className:"flex items-center gap-1.5 text-xs font-medium text-purple-400 hover:text-purple-300",children:[o.jsx(pa,{className:"h-3 w-3 shrink-0"}),"Trajectory Score Details"]}),o.jsx(Md,{children:o.jsx("div",{className:"mt-1 space-y-2",children:E.filter(N=>N.entityType==="TRAJECTORY").map(N=>o.jsxs("div",{className:"bg-surface1 space-y-1 rounded px-3 py-2",children:[o.jsx(ye,{variant:"ui-xs",className:"font-medium text-purple-400",children:N.scorerId}),N.reason&&o.jsx("p",{className:"text-neutral4 text-xs",children:N.reason}),N.preprocessStepResult&&o.jsx("pre",{className:"text-neutral3 max-h-48 overflow-x-auto overflow-y-auto text-xs break-words whitespace-pre-wrap",children:JSON.stringify(N.preprocessStepResult,null,2)})]},N.scorerId))})})]}),_.traceId&&E.some(N=>N.entityType==="TRAJECTORY")&&o.jsx(Res,{traceId:_.traceId}),o.jsxs(Tf,{children:[o.jsxs($d,{className:"text-neutral3 hover:text-neutral5 flex items-center gap-1.5 text-xs font-medium",children:[o.jsx(pa,{className:"h-3 w-3 shrink-0"}),"Input"]}),o.jsx(Md,{children:o.jsx("pre",{className:"text-neutral4 bg-surface1 mt-1 max-h-32 overflow-x-auto overflow-y-auto rounded px-3 py-2 text-xs wrap-break-word whitespace-pre-wrap",children:abe(_.input)})})]}),C?o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{variant:"ui-xs",className:"font-medium text-red-400",children:"Error"}),o.jsx("pre",{className:"bg-surface1 max-h-32 overflow-x-auto overflow-y-auto rounded px-3 py-2 text-xs wrap-break-word whitespace-pre-wrap text-red-300",children:abe(_.error)})]}),_.traceId&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Trace"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral2 truncate font-mono",children:_.traceId}),o.jsx(Pa,{content:_.traceId,tooltip:"Copy trace ID",size:"sm"}),o.jsxs("button",{type:"button",onClick:()=>y(`/traces/${_.traceId}`),className:"text-accent1 hover:text-accent2 flex cursor-pointer items-center gap-1 text-xs transition-colors",children:[o.jsx(Sa,{className:"h-3 w-3"}),"View Trace"]})]})]}):o.jsx(Pes,{output:_.output,traceId:_.traceId,onViewTrace:N=>y(`/traces/${N}`)})]},_.id)}),o.jsxs("div",{ref:u,className:"h-1",children:[d&&o.jsx("div",{className:"flex items-center justify-center py-4",children:o.jsx(Xt,{className:"h-4 w-4"})}),!f&&l.length>0&&o.jsx("div",{className:"py-2 text-center",children:o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"All results loaded"})})]})]})})]})}function Mes({children:e,className:t}){return o.jsx("div",{className:X("grid content-start gap-8 overflow-y-auto",t),children:e})}function Des({children:e,className:t,withLeftSeparator:n,withRightSeparator:r}){return o.jsxs("div",{className:"flex w-full overflow-y-auto",children:[n&&o.jsx(NKe,{}),o.jsx("div",{className:X("grid w-full content-start gap-8 overflow-y-auto",t),children:e}),r&&o.jsx(NKe,{})]})}function NKe(){return o.jsx("div",{className:X("mx-[1.5vw] w-[3px] shrink-0 bg-surface5")})}function Les({children:e,className:t}){return o.jsx("div",{className:X("flex w-full flex-wrap items-center justify-between gap-4 gap-x-6",t),children:e})}const Yr=Object.assign(Des,{Content:Mes,Toolbar:Les});function ly({children:e,className:t}){return o.jsx("div",{className:X("grid size-full grid-cols-1 overflow-y-auto",t),children:e})}const PNe=(e,t=[])=>{const n=We(),{data:r}=Bg(),s=r?.datasets??[];return yt({queryKey:["agent-experiments",e,t,s.map(a=>a.id)],queryFn:async()=>{if(s.length===0)return[];const a=new Set(t),i=await Promise.all(s.map(async c=>{try{return(await n.listDatasetExperiments(c.id)).experiments.filter(d=>d.targetType==="agent"&&d.targetId===e||d.targetType==="scorer"&&a.has(d.targetId)).map(d=>({...d,datasetId:c.id,datasetName:c.name}))}catch{return[]}})),l=c=>c?c instanceof Date?c.getTime():new Date(c).getTime():0;return i.flat().sort((c,u)=>l(u.startedAt)-l(c.startedAt))},enabled:!!e&&s.length>0,refetchInterval:a=>{const i=a.state.data;return i&&i.some(c=>c.status==="running"||c.status==="pending")?3e3:!1}})},PV=(e,t)=>{const n=We();return yt({queryKey:["dataset-item",e,t],queryFn:()=>n.getDatasetItem(e,t),enabled:!!e&&!!t,retry:!1})},IKe=10,j1=(e,t,n)=>{const r=We(),{inView:s,setRef:a}=W_(),i=M1({queryKey:["dataset-items",e,t,n],queryFn:async({pageParam:u})=>await r.listDatasetItems(e,{page:u,perPage:IKe,search:t||void 0,version:n||void 0}),initialPageParam:0,getNextPageParam:(u,d,f)=>{if(!u?.items?.length)return;const p=(f+1)*IKe,h=u?.pagination?.total??0;if(!(p>=h))return f+1},enabled:!!e,retry:!1}),l=i.data?.pages.flatMap(u=>u?.items??[])??[],c=i.data?.pages[0]?.pagination?.total;return v.useEffect(()=>{s&&i.hasNextPage&&!i.isFetchingNextPage&&i.fetchNextPage()},[s,i.hasNextPage,i.isFetchingNextPage]),{...i,data:l,total:c,setEndOfListElement:a}},Fes=10,$Ne=e=>{const t=We();return M1({queryKey:["dataset-versions",e],queryFn:async({pageParam:n})=>t.listDatasetVersions(e,{page:n,perPage:Fes}),initialPageParam:0,getNextPageParam:(n,r,s)=>{if(n?.pagination?.hasMore)return s+1},select:n=>n.pages.flatMap(r=>r?.versions??[]).map((r,s)=>({id:r.id,datasetId:r.datasetId,version:r.version,createdAt:r.createdAt,isCurrent:s===0})),enabled:!!e})};function zes(e){const t=new Date(e);return t.toLocaleDateString("en-US",{month:"short",day:"numeric"})+", "+t.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"})}function Bes(e,t=120){if(e==null)return"-";const n=typeof e=="string"?e:JSON.stringify(e);return!n||n.length<=t?n||"-":n.slice(0,t)+"…"}function Ues(e){const t=e,n=Array.isArray(t?.steps)?t.steps.length:0;return n>0?`${n} expected steps`:"trajectory"}const AKe=["blue","green","purple","orange","cyan","pink","red","yellow"];function Ves(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return AKe[Math.abs(t)%AKe.length]}function qes({agentId:e,datasetId:t,datasetName:n,datasetDescription:r,datasetTags:s=[],datasetTargetType:a,datasetTargetIds:i,activeScorers:l=[],datasetScorerIds:c=[],onGenerate:u,onViewExperiment:d}){const[f,p]=v.useState(!1),h=v.useRef(!1),[m,g]=v.useState(null),[y,b]=v.useState(!1),[x,S]=v.useState(!1),[k,_]=v.useState(!1),[C,E]=v.useState(!1),[j,N]=v.useState(""),[I,A]=v.useState(""),[R,L]=v.useState(""),{data:D}=ih(),{updateDataset:B}=Ni(),H=v.useMemo(()=>new Set(c??[]),[c]),F=v.useMemo(()=>D?Object.entries(D).filter(([le])=>H.has(le)):[],[D,H]),z=v.useMemo(()=>D?Object.entries(D).filter(([le])=>!H.has(le)):[],[D,H]),q=v.useCallback(async le=>{const he=[...c??[],le];try{await B.mutateAsync({datasetId:t,scorerIds:he})}catch(be){throw Le.error("Failed to attach scorer"),be}},[t,c,B]),M=v.useCallback(async le=>{const he=(c??[]).filter(be=>be!==le);try{await B.mutateAsync({datasetId:t,scorerIds:he})}catch{Le.error("Failed to detach scorer")}},[t,c,B]),{data:G=[],setEndOfListElement:V,isFetchingNextPage:$}=j1(t),{data:U,refetch:Z}=kD(t),K=U?.experiments??[],ee=$Ne(t).data??[],J=!a||a==="agent",de=K1({agentId:e,enabled:J}).data?.versions??[];v.useEffect(()=>{A("")},[t]),v.useEffect(()=>{L("")},[e]);const Y=zl(),ne=Ur(),{triggerExperiment:fe}=Ni(),oe=v.useCallback(async()=>{if(!h.current){h.current=!0,p(!0);try{const le=Object.keys(Y).length>0,he=a==="scorer"||a==="workflow"?a:"agent",be=Array.isArray(i)?i:typeof i=="string"?(()=>{try{return JSON.parse(i)}catch{return[]}})():[],xe=he!=="agent"&&be[0]?be[0]:e;await fe.mutateAsync({datasetId:t,targetType:he,targetId:xe,...l.length>0?{scorerIds:l}:{},...le?{requestContext:Y}:{},...I?{version:Number(I)}:{},...R?{agentVersion:R}:{}}),ne.invalidateQueries({queryKey:["agent-experiments",e]}),Z();const je=setInterval(()=>Z(),3e3);setTimeout(()=>clearInterval(je),3e4),Le.success("Experiment started")}catch(le){Le.error(`Failed to start experiment: ${le instanceof Error?le.message:"Unknown error"}`)}finally{h.current=!1,p(!1)}}},[t,l,e,a,i,fe,Y,ne,Z,I,R]);return o.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[o.jsxs("div",{className:"border-border1 space-y-3 border-b p-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral5 block truncate font-medium",children:n}),r&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-0.5 block truncate",children:r}),s.length>0&&o.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:s.map(le=>o.jsx(Js,{color:Ves(le),size:"small",children:le},le))})]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[o.jsxs(ce,{variant:"ghost",size:"sm",onClick:u,children:[o.jsx(qe,{size:"sm",children:o.jsx(Eg,{})}),"Generate"]}),o.jsx(ce,{variant:"primary",size:"sm",onClick:oe,disabled:G.length===0||f,children:f?o.jsxs(o.Fragment,{children:[o.jsx(Xt,{className:"h-3 w-3"})," Running..."]}):o.jsxs(o.Fragment,{children:[o.jsx(qe,{size:"sm",children:o.jsx(Of,{})})," ","Run Experiment"]})})]})]}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mb-1 block",children:"Dataset version"}),o.jsx(ac,{options:[{label:"Latest",value:""},...ee.map(le=>({label:`v${le.version}`,value:String(le.version),description:le.isCurrent?"Current":void 0}))],value:I,onValueChange:A,placeholder:"Latest",size:"sm"})]}),J&&o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mb-1 block",children:"Agent version"}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(ac,{options:[{label:"Current",value:""},...de.map(le=>({label:`v${le.versionNumber}`,value:le.id,description:le.changeMessage??void 0}))],value:R,onValueChange:L,placeholder:"Current",size:"sm"}),(R||de[0]?.id)&&o.jsx(Pa,{content:R||de[0]?.id,tooltip:"Copy version ID",size:"sm"})]})]})]})]}),o.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:o.jsxs(Br,{className:"min-h-0 flex-1",children:[o.jsxs("div",{className:"border-border1 border-b",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("button",{type:"button",onClick:()=>_(le=>!le),className:"hover:bg-surface3 flex flex-1 items-center gap-1 px-4 py-2 transition-colors",children:[o.jsx(qe,{size:"sm",className:"text-neutral3",children:k?o.jsx(pa,{}):o.jsx(Na,{})}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3 font-semibold tracking-wider uppercase",children:["Scorers (",F.length,")"]})]}),z.length>0&&o.jsx("div",{className:"pr-2",children:o.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>E(!0),children:"Attach"})})]}),!k&&(F.length===0?o.jsxs("div",{className:"px-4 py-4 text-center",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:"No scorers attached to this dataset."}),z.length>0&&o.jsx("div",{className:"mt-2",children:o.jsx(ce,{variant:"outline",size:"sm",onClick:()=>E(!0),children:"Attach a scorer"})})]}):o.jsx("div",{className:"divide-border1 divide-y",children:F.map(([le,he])=>{const be=he.scorer?.name||le;return o.jsxs("div",{className:"hover:bg-surface3 group flex items-center justify-between px-4 py-1.5 transition-colors",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral5 truncate",children:be}),o.jsx("button",{type:"button",onClick:()=>M(le),"aria-label":`Detach "${be}" from this dataset`,className:"text-neutral3 p-0.5 opacity-0 transition-opacity group-hover:opacity-100 hover:text-red-500 focus-visible:opacity-100",title:"Detach scorer",children:o.jsx(qe,{size:"sm",children:o.jsx(bs,{})})})]},le)})}))]}),o.jsxs("div",{className:"border-border1 border-b",children:[o.jsxs("button",{type:"button",onClick:()=>b(le=>!le),className:"hover:bg-surface3 flex w-full items-center gap-1 px-4 py-2 transition-colors",children:[o.jsx(qe,{size:"sm",className:"text-neutral3",children:y?o.jsx(pa,{}):o.jsx(Na,{})}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3 font-semibold tracking-wider uppercase",children:["Items (",G.length,")"]})]}),!y&&(G.length===0?o.jsx("div",{className:"px-4 py-6 text-center",children:o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:"No items yet. Use Generate to create test data."})}):o.jsxs("div",{className:"divide-border1 divide-y",children:[G.map(le=>{const he=m===le.id;return o.jsxs("div",{children:[o.jsxs("button",{type:"button",onClick:()=>g(he?null:le.id),className:"hover:bg-surface3 flex w-full items-start gap-2 px-4 py-2 text-left transition-colors",children:[o.jsx(qe,{size:"sm",className:"text-neutral3 mt-0.5 shrink-0",children:he?o.jsx(Na,{}):o.jsx(pa,{})}),o.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral5 block flex-1 truncate",children:Bes(le.input)}),le.expectedTrajectory!=null&&o.jsx(Js,{size:"small",color:"purple",children:Ues(le.expectedTrajectory)})]})]}),he&&o.jsx(Hes,{datasetId:t,item:le})]},le.id)}),o.jsx("div",{ref:V}),$&&o.jsx("div",{className:"flex items-center justify-center py-2",children:o.jsx(Xt,{className:"h-3 w-3"})})]}))]}),o.jsxs("div",{children:[o.jsxs("button",{type:"button",onClick:()=>S(le=>!le),className:"hover:bg-surface3 flex w-full items-center gap-1 px-4 py-2 transition-colors",children:[o.jsx(qe,{size:"sm",className:"text-neutral3",children:x?o.jsx(pa,{}):o.jsx(Na,{})}),o.jsx(qe,{size:"sm",className:"text-neutral3",children:o.jsx(uT,{})}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3 font-semibold tracking-wider uppercase",children:["Past Runs (",K.length,")"]})]}),!x&&(K.length===0?o.jsx("div",{className:"px-4 py-4 text-center",children:o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:"No experiment runs yet"})}):o.jsx("div",{className:"divide-border1 divide-y",children:K.map(le=>o.jsxs("button",{type:"button",onClick:()=>d(le.id),className:"hover:bg-surface3 flex w-full items-center gap-2 px-4 py-2 text-left transition-colors",children:[o.jsx(Wes,{status:le.status}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral5 block",children:le.startedAt?zes(le.startedAt):"Unknown"}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3",children:[le.succeededCount,"/",le.totalItems," passed",le.datasetVersion!=null&&` · ${NN("Dataset",le.datasetVersion)}`,le.agentVersion&&(()=>{const he=de.find(be=>be.id===le.agentVersion);return` · ${NN("Agent",he?he.versionNumber:le.agentVersion)}`})()]})]}),o.jsx(qe,{size:"sm",className:"text-neutral3",children:o.jsx(pa,{})})]},le.id))}))]})]})}),o.jsx(br,{open:C,onOpenChange:le=>{E(le),le||N("")},children:o.jsxs(xr,{className:"max-w-md",children:[o.jsx(wr,{children:o.jsx(gr,{children:"Attach Scorer to Dataset"})}),o.jsx($r,{className:"max-h-[50vh] overflow-y-auto",children:z.length===0?o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 py-4 text-center",children:"No scorers available to attach."}):o.jsxs("div",{className:"space-y-2",children:[o.jsx("input",{type:"text",placeholder:"Search scorers...",value:j,onChange:le=>N(le.target.value),className:"border-border1 bg-surface2 text-text1 placeholder:text-neutral3 focus:ring-accent1 w-full rounded border px-3 py-1.5 text-sm focus:ring-1 focus:outline-none"}),z.filter(([le,he])=>j?(he.scorer?.name||le).toLowerCase().includes(j.toLowerCase()):!0).map(([le,he])=>{const be=he.scorer?.name||le;return o.jsx("button",{type:"button",className:"hover:bg-surface4 w-full rounded px-3 py-2 text-left transition-colors",onClick:async()=>{try{await q(le),Le.success(`Attached "${be}" to this dataset`),E(!1)}catch{}},children:o.jsx(ye,{variant:"ui-sm",className:"font-medium",children:be})},le)})]})})]})})]})}function CE(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e,null,2)}function Hes({datasetId:e,item:t}){const[n,r]=v.useState(!1),[s,a]=v.useState(!1),[i,l]=v.useState(""),[c,u]=v.useState(""),[d,f]=v.useState(""),{updateItem:p,deleteItem:h}=Ni(),m=v.useCallback(()=>{l(CE(t.input)),u(CE(t.groundTruth)),f(CE(t.expectedTrajectory)),r(!0)},[t.input,t.groundTruth,t.expectedTrajectory]),g=v.useCallback(()=>{r(!1)},[]),y=v.useCallback(async()=>{try{await h.mutateAsync({datasetId:e,itemId:t.id}),Le.success("Item deleted")}catch(x){Le.error(`Failed to delete: ${x instanceof Error?x.message:"Unknown error"}`)}},[h,e,t.id]),b=v.useCallback(async()=>{let x;try{x=JSON.parse(i)}catch{x=i}let S;if(c.trim())try{S=JSON.parse(c)}catch{S=c}let k;if(d.trim())try{k=JSON.parse(d)}catch{k=d}try{await p.mutateAsync({datasetId:e,itemId:t.id,input:x,groundTruth:S,expectedTrajectory:k}),Le.success("Item updated"),r(!1)}catch(_){Le.error(`Failed to update: ${_ instanceof Error?_.message:"Unknown error"}`)}},[i,c,d,e,t.id,p]);return n?o.jsxs("div",{className:"space-y-2 px-4 pb-3 pl-10",children:[o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Input"}),o.jsx($l,{value:i,onChange:x=>l(x.target.value),className:"mt-1 font-mono text-xs",rows:4})]}),o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Ground Truth"}),o.jsx($l,{value:c,onChange:x=>u(x.target.value),className:"mt-1 font-mono text-xs",rows:3,placeholder:"Optional"})]}),o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Expected Trajectory (JSON)"}),o.jsx($l,{value:d,onChange:x=>f(x.target.value),className:"mt-1 font-mono text-xs",rows:3,placeholder:"Optional — JSON trajectory expectation"})]}),o.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[o.jsxs(ce,{variant:"primary",size:"sm",onClick:b,disabled:p.isPending,children:[p.isPending?o.jsx(Xt,{className:"h-3 w-3"}):o.jsx(qe,{size:"sm",children:o.jsx(jd,{})}),"Save"]}),o.jsxs(ce,{variant:"ghost",size:"sm",onClick:g,children:[o.jsx(qe,{size:"sm",children:o.jsx(bs,{})}),"Cancel"]})]})]}):o.jsxs("div",{className:"space-y-2 px-4 pb-3 pl-10",children:[o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Input"}),o.jsx("pre",{className:"text-neutral5 bg-surface1 mt-1 max-h-48 overflow-x-auto overflow-y-auto rounded px-2 py-1.5 text-xs wrap-break-word whitespace-pre-wrap",children:CE(t.input)})]}),t.groundTruth!==void 0&&t.groundTruth!==null&&o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Ground Truth"}),o.jsx("pre",{className:"text-neutral5 bg-surface1 mt-1 max-h-48 overflow-x-auto overflow-y-auto rounded px-2 py-1.5 text-xs wrap-break-word whitespace-pre-wrap",children:CE(t.groundTruth)})]}),t.expectedTrajectory!=null&&o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Expected Trajectory"}),o.jsx("pre",{className:"text-neutral5 bg-surface1 mt-1 max-h-48 overflow-x-auto overflow-y-auto rounded px-2 py-1.5 text-xs break-words whitespace-pre-wrap",children:CE(t.expectedTrajectory)})]}),o.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[o.jsxs(ce,{variant:"ghost",size:"sm",onClick:m,children:[o.jsx(qe,{size:"sm",children:o.jsx(rm,{})}),"Edit"]}),s?o.jsxs(o.Fragment,{children:[o.jsx(ye,{variant:"ui-xs",className:"text-negative1 font-medium",children:"Delete this item?"}),o.jsx(ce,{variant:"ghost",size:"sm",onClick:y,disabled:h.isPending,className:"text-negative1 hover:text-negative1",children:h.isPending?o.jsx(Xt,{className:"h-3 w-3"}):"Yes"}),o.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>a(!1),children:"No"})]}):o.jsxs(ce,{variant:"ghost",size:"sm",onClick:()=>a(!0),className:"text-neutral2 hover:text-negative1",children:[o.jsx(qe,{size:"sm",children:o.jsx(uu,{})}),"Delete"]}),t.source!=null&&o.jsxs(ye,{variant:"ui-xs",className:"text-neutral2",children:["Source:"," ",typeof t.source=="object"&&t.source!==null&&"type"in t.source?String(t.source.type):"manual"]})]})]})}function Wes({status:e}){const t=e==="completed"?"bg-positive1":e==="running"?"bg-warning1":e==="failed"?"bg-negative1":"bg-neutral3";return o.jsx("div",{className:X("w-2 h-2 rounded-full shrink-0",t)})}function Zes({scorerId:e,scorerData:t,isAttached:n,onToggleAttach:r,onEdit:s,linkedDatasets:a,onViewDataset:i}){if(!t)return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"Scorer not found"})});const l=t.scorer?.name||e,c=t.scorer?.description,u=t.source==="code",d=t.scorer?.config?.type==="trajectory";return o.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[o.jsxs("div",{className:"border-border1 space-y-3 border-b p-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral5 truncate font-medium",children:l}),d&&o.jsx(Js,{size:"small",color:"purple",children:"trajectory"}),u&&o.jsx("span",{title:"Defined in code — cannot be edited in the UI",children:o.jsx(un,{variant:"default",children:"Code"})})]}),c&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-1 block",children:c})]}),o.jsx("div",{className:"flex shrink-0 items-center gap-3",children:!u&&o.jsxs(ce,{variant:"ghost",size:"sm",onClick:s,children:[o.jsx(qe,{size:"sm",children:o.jsx(rm,{})}),"Edit"]})})]}),o.jsxs("div",{className:"bg-surface3 flex items-center justify-between rounded-md px-3 py-2",children:[o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral5 block",children:"Run in experiments"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-0.5 block",children:"When enabled, this scorer grades results for this agent"})]}),o.jsx(ic,{checked:n,onCheckedChange:r})]})]}),o.jsxs("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mb-2 block font-medium tracking-wider uppercase",children:"Details"}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(wz,{label:"ID",value:e}),o.jsx(wz,{label:"Type",value:d?"Trajectory":"Agent"}),o.jsx(wz,{label:"Source",value:u?"Code":"Stored"}),t.agentIds&&t.agentIds.length>0&&o.jsx(wz,{label:"Used by agents",value:t.agentNames?.join(", ")||t.agentIds.join(", ")})]})]}),a&&a.length>0&&o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mb-2 block font-medium tracking-wider uppercase",children:"Datasets"}),o.jsx("div",{className:"space-y-1",children:a.map(f=>i?o.jsx("button",{onClick:()=>i(f.id),className:"bg-surface3 hover:bg-surface4 w-full cursor-pointer rounded-md px-3 py-2 text-left transition-colors",children:o.jsx(ye,{variant:"ui-xs",className:"text-neutral5",children:f.name})},f.id):o.jsx("div",{className:"bg-surface3 rounded-md px-3 py-2",children:o.jsx(ye,{variant:"ui-xs",className:"text-neutral5",children:f.name})},f.id))})]}),u&&o.jsx("div",{className:"bg-surface3 rounded-md p-3",children:o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:"This scorer is defined in code and cannot be edited in the UI. You can toggle whether it runs in experiments for this agent."})})]})]})}function wz({label:e,value:t}){return o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 w-24 shrink-0",children:e}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral5 break-all",children:t})]})}function RKe({onBack:e,onSaved:t,initialItems:n,prefillTestItems:r,editScorerId:s,editScorerData:a}){const i=!!s,l=We(),[c,u]=v.useState(""),[d,f]=v.useState(""),[p,h]=v.useState(0),[m,g]=v.useState(1),[y,b]=v.useState(""),[x,S]=v.useState(!1),[k,_]=v.useState(()=>n?n.map(de=>({input:de.input,output:de.error||de.output,expectedDirection:de.error?"low":"high",label:de.itemId.slice(0,8)})):r?r.map((de,Y)=>({input:de.input,output:de.output,expectedDirection:de.expectedDirection==="high"?"high":"low",label:`failure-${Y+1}`})):[]),[C,E]=v.useState(!1),[j,N]=v.useState(s||null),[I,A]=v.useState(null),[R,L]=v.useState(null),[D,B]=v.useState(!1);v.useEffect(()=>{s&&(S(!0),l.getStoredScorer(s).details(void 0,{status:"draft"}).then(async de=>{u(de.name||s),f(de.instructions||""),h(de.scoreRange?.min??0),g(de.scoreRange?.max??1),de.model&&b(`${de.model.provider}/${de.model.name}`);let Y=null;try{const{datasets:ne}=await l.listDatasets({perPage:200}),fe=ne.find(oe=>oe.targetType!=="scorer"?!1:(Array.isArray(oe.targetIds)?oe.targetIds:typeof oe.targetIds=="string"?(()=>{try{return JSON.parse(oe.targetIds)}catch{return[]}})():[]).includes(s));fe&&(Y=fe.id)}catch{}if(Y){A(Y);try{const{items:ne}=await l.listDatasetItems(Y,{perPage:200}),fe=ne.map(oe=>{const le=oe.input,he=oe.groundTruth,be=oe.metadata;return{input:le?.input??"",output:le?.output??"",expectedDirection:he?.expectedDirection==="low"?"low":"high",label:be?.label||void 0}});_(fe)}catch{}}}).catch(()=>{const Y=a?.scorer?.config,ne=Y?.judge;u(Y?.name||a?.name||s),f(ne?.instructions||Y?.instructions||""),ne?.model&&b(ne.model)}).finally(()=>S(!1)))},[s]);const{provider:H,model:F}=EEe(),{createStoredScorer:z,updateStoredScorer:q}=kNe(s||j||void 0),{form:M}=Ho(),{createDataset:G,batchInsertItems:V,batchDeleteItems:$,triggerExperiment:U}=Ni(),{data:Z=[]}=LG({datasetId:I??"",experimentId:R??"",experimentStatus:D?"running":"completed"}),K=()=>{_(de=>[...de,{input:"",output:"",expectedDirection:"high"}])},te=de=>{_(Y=>Y.filter((ne,fe)=>fe!==de))},ee=(de,Y,ne)=>{_(fe=>fe.map((oe,le)=>le===de?{...oe,[Y]:ne}:oe))},J=v.useCallback(async()=>{if(!c.trim()){Le.error("Please enter a scorer name");return}if(!d.trim()){Le.error("Please enter scorer instructions");return}let de=H,Y=F;if(y){const fe=y.split("/");fe.length>=2&&(de=fe[0],Y=fe.slice(1).join("/"))}if(!de||!Y){Le.error("Please select a model");return}const ne=s||j;E(!0);try{if(ne){await q.mutateAsync({instructions:d.trim(),model:{provider:de,name:Y},scoreRange:{min:p,max:m}});let fe=I;if(!fe&&k.length>0&&(fe=(await G.mutateAsync({name:`${c.trim()} — Test Dataset`,description:`Test dataset for scorer "${c.trim()}". Items with known-good and known-bad examples to verify scoring accuracy.`,targetType:"scorer",targetIds:[ne]})).id,A(fe)),fe){try{const{items:oe}=await l.listDatasetItems(fe,{perPage:200});oe.length>0&&await $.mutateAsync({datasetId:fe,itemIds:oe.map(le=>le.id)})}catch{}k.length>0&&await V.mutateAsync({datasetId:fe,items:k.map(oe=>({input:{input:oe.input,output:oe.output},groundTruth:{expectedDirection:oe.expectedDirection},metadata:{label:oe.label},source:{type:"llm",referenceId:"scorer-editor"}}))})}t?.(ne),Le.success("Scorer updated")}else{const oe=(await z.mutateAsync({name:c.trim(),type:"llm-judge",model:{provider:de,name:Y},instructions:d.trim(),scoreRange:{min:p,max:m}}))?.id;if(oe){if(N(oe),k.length>0){const he=await G.mutateAsync({name:`${c.trim()} — Test Dataset`,description:`Test dataset for scorer "${c.trim()}". Items with known-good and known-bad examples to verify scoring accuracy.`,targetType:"scorer",targetIds:[oe]});A(he.id),await V.mutateAsync({datasetId:he.id,items:k.map(be=>({input:{input:be.input,output:be.output},groundTruth:{expectedDirection:be.expectedDirection},metadata:{label:be.label},source:{type:"llm",referenceId:"scorer-editor"}}))})}const le=M.getValues("scorers")||{};M.setValue("scorers",{...le,[oe]:{sampling:void 0}},{shouldDirty:!0}),t?.(oe)}Le.success(`Scorer saved${k.length>0?" with test dataset":""}. ${k.length>0?'Click "Run Test" to verify scoring.':""}`)}}catch(fe){Le.error(`Failed to save scorer: ${fe instanceof Error?fe.message:"Unknown error"}`)}finally{E(!1)}},[c,d,H,F,y,p,m,k,I,s,j,z,q,G,V,$,l,M,t]),ae=v.useCallback(async()=>{if(!j){Le.error("Save the scorer first before testing");return}if(!I){Le.error("No test dataset — add items and save first");return}B(!0),L(null);try{const Y=(await U.mutateAsync({datasetId:I,targetType:"scorer",targetId:j}))?.experimentId;Y&&(L(Y),Le.success("Scorer test started — results will appear below"))}catch(de){Le.error(`Failed to run test: ${de instanceof Error?de.message:"Unknown error"}`)}finally{B(!1)}},[j,I,U]);return o.jsxs("div",{className:"flex h-full flex-col",children:[o.jsxs("div",{className:"border-border1 flex items-center gap-2 border-b px-4 py-3",children:[o.jsxs(ce,{variant:"ghost",size:"sm",onClick:e,children:[o.jsx(qe,{children:o.jsx(Ac,{})}),"Back"]}),o.jsx(ye,{as:"h3",variant:"header-sm",className:"ml-2",children:i||j?"Edit Scorer":"New Scorer"}),(i||j)&&o.jsx(un,{variant:"success",className:"ml-2",children:"Saved"})]}),o.jsx(Br,{className:"flex-1",children:x?o.jsxs("div",{className:"flex items-center justify-center p-8",children:[o.jsx(Xt,{className:"mr-2"})," Loading scorer..."]}):o.jsxs("div",{className:"space-y-6 p-4",children:[o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Name"}),o.jsx(Cn,{placeholder:"e.g. Relevance Scorer",value:c,onChange:de=>u(de.target.value),disabled:i||!!j})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Model"}),o.jsx(Cn,{placeholder:"e.g. openai/gpt-4o-mini",value:y||(H&&F?`${H}/${F}`:""),onChange:de=>b(de.target.value)}),o.jsx(ye,{variant:"ui-sm",className:"text-icon3",children:"Format: provider/model (e.g. openai/gpt-4o-mini)"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Instructions"}),o.jsx($l,{placeholder:"Describe what this scorer should evaluate. Be specific about what constitutes a good vs bad response...",value:d,onChange:de=>f(de.target.value),rows:6})]}),o.jsxs("div",{className:"flex gap-4",children:[o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsx(Dt,{children:"Min Score"}),o.jsx(Cn,{type:"number",min:-1e3,max:1e3,step:"any",value:p,onChange:de=>h(Number(de.target.value))})]}),o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsx(Dt,{children:"Max Score"}),o.jsx(Cn,{type:"number",min:-1e3,max:1e3,step:"any",value:m,onChange:de=>g(Number(de.target.value))})]})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-md",className:"font-medium",children:"Test Items"}),o.jsx(ye,{variant:"ui-sm",className:"text-icon3 mt-0.5",children:"Add known-good and known-bad examples to verify your scorer"}),I&&o.jsxs(ye,{variant:"ui-xs",className:"text-icon3 mt-1",children:["Linked dataset · ",k.length," item",k.length!==1?"s":""]})]}),o.jsxs(ce,{variant:"outline",size:"sm",onClick:K,children:[o.jsx(qe,{children:o.jsx(Zr,{})}),"Add Item"]})]}),k.length===0&&o.jsx("div",{className:"border-border1 rounded-lg border border-dashed p-6 text-center",children:o.jsx(ye,{variant:"ui-sm",className:"text-icon3",children:"No test items yet. Add items with expected scoring direction to verify your scorer works correctly."})}),k.map((de,Y)=>{const ne=Z[Y],fe=ne?.output?ne.output?.score:null,oe=ne?.output?ne.output?.reason:null,le=ne?.error,he=fe!=null?de.expectedDirection==="high"?fe>=(m-p)/2+p:fe<(m-p)/2+p:null;return o.jsxs("div",{className:X("border border-border1 rounded-lg p-3 space-y-3",he===!0&&"border-success/50 bg-success/5",he===!1&&"border-error/50 bg-error/5"),children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(ye,{variant:"ui-sm",className:"font-medium",children:["Item ",Y+1]}),de.label&&o.jsx(un,{variant:"default",children:de.label}),o.jsxs("button",{className:X("px-2 py-0.5 rounded text-xs font-medium transition-colors",de.expectedDirection==="high"?"bg-success/20 text-success":"bg-error/20 text-error"),onClick:()=>ee(Y,"expectedDirection",de.expectedDirection==="high"?"low":"high"),children:["Should score ",de.expectedDirection]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[he!==null&&o.jsx(qe,{className:he?"text-success":"text-error",children:he?o.jsx(jbe,{}):o.jsx(M2,{})}),o.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>te(Y),children:o.jsx(qe,{children:o.jsx(uu,{})})})]})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-icon3 font-medium",children:"Input"}),o.jsx($l,{placeholder:"The user's question/input...",value:typeof de.input=="string"?de.input:JSON.stringify(de.input,null,2),onChange:be=>ee(Y,"input",be.target.value),rows:3,className:"text-sm"})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-icon3 font-medium",children:"Output (agent response)"}),o.jsx($l,{placeholder:"The agent's response...",value:typeof de.output=="string"?de.output:JSON.stringify(de.output,null,2),onChange:be=>ee(Y,"output",be.target.value),rows:3,className:"text-sm"})]})]}),(fe!==null||le)&&o.jsx("div",{className:"border-border1 flex items-center gap-3 border-t pt-2",children:le?o.jsxs("div",{className:"text-error flex items-center gap-1.5",children:[o.jsx(qe,{size:"sm",children:o.jsx(cT,{})}),o.jsxs(ye,{variant:"ui-xs",children:["Error: ",String(le)]})]}):o.jsxs(o.Fragment,{children:[o.jsxs(ye,{variant:"ui-sm",className:"font-mono font-medium",children:["Score: ",fe?.toFixed(3)]}),oe&&o.jsx(ye,{variant:"ui-xs",className:"text-icon3 flex-1 truncate",children:oe})]})})]},Y)})]}),Z.length>0&&o.jsxs("div",{className:"border-border1 rounded-lg border p-3",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(ye,{variant:"ui-sm",className:"font-medium",children:"Test Results:"}),(()=>{let de=0,Y=0,ne=0;return Z.forEach((fe,oe)=>{const le=k[oe];if(!le)return;if(fe.error){ne++;return}const he=fe.output?.score;if(he==null)return;const be=(m-p)/2+p;(le.expectedDirection==="high"?he>=be:he<be)?de++:Y++}),o.jsxs(o.Fragment,{children:[de>0&&o.jsxs(un,{variant:"success",children:[de," correct"]}),Y>0&&o.jsxs(un,{variant:"error",children:[Y," incorrect"]}),ne>0&&o.jsxs(un,{variant:"default",children:[ne," errors"]})]})})()]}),o.jsx(ye,{variant:"ui-xs",className:"text-icon3 mt-1",children:Z.length<k.length?"Still processing...":"All items scored. Tweak instructions and re-run to improve accuracy."})]})]})}),o.jsxs("div",{className:"border-border1 flex items-center gap-2 border-t px-4 py-3",children:[i?o.jsxs(o.Fragment,{children:[o.jsxs(ce,{variant:"default",size:"sm",onClick:J,disabled:C||!d.trim(),children:[C?o.jsx(Xt,{className:"mr-1.5"}):o.jsx(qe,{children:o.jsx(jd,{})}),"Save Changes"]}),o.jsxs(ce,{variant:"default",size:"sm",onClick:ae,disabled:D||k.length===0,children:[D?o.jsx(Xt,{className:"mr-1.5"}):o.jsx(qe,{children:o.jsx(Of,{})}),"Run Test"]})]}):j?o.jsxs(o.Fragment,{children:[o.jsxs(ce,{variant:"default",size:"sm",onClick:ae,disabled:D||k.length===0,children:[D?o.jsx(Xt,{className:"mr-1.5"}):o.jsx(qe,{children:o.jsx(Of,{})}),"Run Test"]}),o.jsxs(ce,{variant:"outline",size:"sm",onClick:J,disabled:C,children:[C?o.jsx(Xt,{className:"mr-1.5"}):null,"Update & Re-save"]})]}):o.jsxs(ce,{variant:"default",size:"sm",onClick:J,disabled:C||!c.trim()||!d.trim(),children:[C?o.jsx(Xt,{className:"mr-1.5"}):o.jsx(qe,{children:o.jsx(jd,{})}),k.length>0?"Save with Test Dataset":"Save & Attach"]}),o.jsx(ce,{variant:"ghost",size:"sm",onClick:e,className:"ml-auto",children:i||j?"Done":"Cancel"})]})]})}const Ges={anyOf:[{type:"string"},{type:"array",items:{type:"object",additionalProperties:!0}}]},PKe={type:"object",properties:{role:{type:"string",enum:["user","assistant","system","tool"]},content:Ges},required:["role","content"]},Qes={$schema:"http://json-schema.org/draft-07/schema#",description:"Agent message input (MessageListInput)",anyOf:[{type:"string",description:"Simple text message"},{type:"array",items:{type:"string"},description:"Array of text messages"},{...PKe,description:"Single message object"},{type:"array",description:"Array of message objects",items:PKe}]},Yes={$schema:"http://json-schema.org/draft-07/schema#",type:"object",description:"Agent generate() output",properties:{text:{type:"string",description:"Text response"},object:{description:"Structured output (if any)"},toolCalls:{type:"array",description:"Tool calls made by the agent",items:{type:"object",additionalProperties:!0}},toolResults:{type:"array",description:"Tool execution results",items:{type:"object",additionalProperties:!0}},sources:{type:"array",description:"Sources referenced",items:{type:"object",additionalProperties:!0}},files:{type:"array",description:"Files generated",items:{type:"object",additionalProperties:!0}},usage:{type:"object",description:"Token usage",properties:{promptTokens:{type:"number"},completionTokens:{type:"number"},totalTokens:{type:"number"}}},reasoningText:{type:"string",description:"Reasoning text (if any)"}}};function Kes(){return{inputSchema:Qes,outputSchema:Yes,isLoading:!1,error:null}}const ibe={anyOf:[{type:"string"},{type:"object",description:"Structured content (format 2 with parts)"},{type:"array",description:"Content parts array",items:{type:"object"}}]},obe={type:"object",properties:{role:{type:"string",enum:["user","assistant","system","tool"]},content:ibe},required:["role","content"]},Xes={type:"object",description:"ScorerRunInputForAgent",properties:{inputMessages:{type:"array",description:"User input messages (MastraDBMessage[])",items:obe},rememberedMessages:{type:"array",description:"Messages from memory (MastraDBMessage[])",items:obe},systemMessages:{type:"array",description:"System messages (CoreMessage[])",items:{type:"object",properties:{role:{type:"string",enum:["system"]},content:ibe},required:["role","content"]}},taggedSystemMessages:{type:"object",description:"Tagged system messages (Record<string, CoreSystemMessage[]>)",additionalProperties:{type:"array",items:{type:"object",properties:{role:{type:"string",enum:["system"]},content:ibe},required:["role","content"]}}}},required:["inputMessages","rememberedMessages","systemMessages","taggedSystemMessages"]},Jes={type:"array",description:"ScorerRunOutputForAgent (MastraDBMessage[])",items:obe},ets={$schema:"http://json-schema.org/draft-07/schema#",type:"object",description:"Scorer input for agent-type scorers (scoringInputSchema)",properties:{runId:{type:"string",description:"Run ID (optional)"},input:Xes,output:Jes,additionalContext:{type:"object",description:"Additional context (optional)",additionalProperties:!0},requestContext:{type:"object",description:"Request context (optional)",additionalProperties:!0}},required:[]},tts={$schema:"http://json-schema.org/draft-07/schema#",type:"object",description:"Scorer input for custom scorers (scoringInputSchema)",properties:{runId:{type:"string",description:"Run ID (optional)"},input:{description:"Input to the entity being scored (any)"},output:{description:"Output from the entity being scored (any)"},additionalContext:{type:"object",description:"Additional context (optional)",additionalProperties:!0},requestContext:{type:"object",description:"Request context (optional)",additionalProperties:!0}},required:[]},nts={$schema:"http://json-schema.org/draft-07/schema#",description:"Scorer ground truth (any shape)"};function rts(){return{agentInputSchema:ets,customInputSchema:tts,outputSchema:nts,isLoading:!1,error:null}}function sts(e){const t=We();return yt({queryKey:["workflow-schema",e],queryFn:async()=>{if(!e)throw new Error("No workflow selected");return t.getWorkflow(e).getSchema()},enabled:!!e,staleTime:300*1e3})}function lae({label:e,schemaType:t,value:n,onChange:r,error:s,sourceSchema:a,autoPopulate:i=!1}){const l=n!=null,[c,u]=v.useState(()=>n?JSON.stringify(n,null,2):""),[d,f]=v.useState(null),p=v.useRef(!1),h=v.useRef(!1);v.useEffect(()=>{if(h.current){h.current=!1;return}n&&(u(JSON.stringify(n,null,2)),f(null))},[n]),v.useEffect(()=>{p.current=!1},[a]);const m=y=>{y?i&&a&&!p.current?(p.current=!0,r(a)):r({type:"object",properties:{}}):r(null)},g=y=>{u(y);try{const b=JSON.parse(y);typeof b=="object"&&b!==null?(f(null),h.current=!0,r(b)):f("Schema must be a JSON object")}catch{f("Invalid JSON")}};return o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ic,{checked:l,onCheckedChange:m,id:`${t}-schema-toggle`}),o.jsx("label",{htmlFor:`${t}-schema-toggle`,className:"text-sm font-medium",children:e})]}),l&&o.jsxs("div",{className:"space-y-2",children:[o.jsx(Wr,{value:c,onChange:g,showCopyButton:!1,className:X("h-48 border rounded-md",(d||s)&&"border-destructive")}),d&&o.jsx("p",{className:"text-destructive text-xs",children:d}),s&&!d&&o.jsx("p",{className:"text-destructive text-xs",children:s})]})]})}function Y8t({inputSchema:e,outputSchema:t,requestContextSchema:n,onChange:r,disabled:s=!1,defaultOpen:a=!1}){const[i,l]=v.useState(a),[c,u]=v.useState("custom"),[d,f]=v.useState(null),[p,h]=v.useState("agent"),{data:m,isLoading:g}=Hy(),y=m?Object.entries(m):[],{data:b,isLoading:x}=sts(c==="workflow"?d:null),S=Kes(),k=rts(),C=(()=>{switch(c){case"agent":return{inputSchema:S.inputSchema,outputSchema:S.outputSchema};case"workflow":return b?{inputSchema:b.inputSchema??null,outputSchema:b.outputSchema??null}:{inputSchema:null,outputSchema:null};case"scorer":return{inputSchema:p==="agent"?k.agentInputSchema:k.customInputSchema,outputSchema:k.outputSchema};default:return{inputSchema:null,outputSchema:null}}})(),E=c!=="custom",j=v.useRef(null);v.useEffect(()=>{if(c==="custom"||!C.inputSchema&&!C.outputSchema)return;const L=c==="workflow"?`workflow:${d}`:c==="scorer"?`scorer:${p}`:c,D=j.current!==null&&j.current!==L;if(j.current=L,c==="workflow"&&!b)return;const B=e!=null,H=t!=null,F=e&&e.type==="object"&&Object.keys(e.properties||{}).length===0,z=t&&t.type==="object"&&Object.keys(t.properties||{}).length===0,q=C.inputSchema&&B&&(D||F),M=C.outputSchema&&H&&(D||z);(q||M)&&r({inputSchema:q?C.inputSchema:e??null,outputSchema:M?C.outputSchema:t??null,requestContextSchema:n??null})},[c,d,b,p]);const N=L=>{r({inputSchema:L,outputSchema:t??null,requestContextSchema:n??null})},I=L=>{r({inputSchema:e??null,outputSchema:L,requestContextSchema:n??null})},A=L=>{r({inputSchema:e??null,outputSchema:t??null,requestContextSchema:L})},R=L=>{u(L),L!=="workflow"&&f(null)};return o.jsxs(Tf,{open:i,onOpenChange:l,children:[o.jsxs($d,{className:"text-neutral4 hover:text-neutral5 flex w-full items-center gap-2 py-2 text-sm font-medium",children:[o.jsx(pa,{className:"h-4 w-4"}),"Schema Configuration (Optional)"]}),o.jsxs(Md,{className:"space-y-4 pt-4",children:[o.jsx(En,{variant:"info",title:"JSON Schema Format",children:o.jsxs(En.Message,{children:["Schemas use"," ",o.jsx("a",{href:"https://json-schema.org/",target:"_blank",rel:"noopener noreferrer",className:"hover:text-accent5Lighter underline",children:"JSON Schema"})," ","for validation and type checking."]})}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{className:"text-neutral4 text-sm font-medium",children:"Import From"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(oa,{value:c,onValueChange:L=>R(L),disabled:s,children:[o.jsx(ca,{size:"sm",className:"w-40",children:o.jsx(la,{})}),o.jsxs(ua,{children:[o.jsx(Ar,{value:"custom",children:"Custom"}),o.jsx(Ar,{value:"agent",children:"Agent"}),o.jsx(Ar,{value:"workflow",children:"Workflow"}),o.jsx(Ar,{value:"scorer",children:"Scorer"})]})]}),c==="workflow"&&o.jsxs(oa,{value:d??"",onValueChange:f,disabled:s,children:[o.jsx(ca,{size:"sm",className:"w-48",children:o.jsx(la,{placeholder:"Select workflow..."})}),o.jsx(ua,{children:g?o.jsx(Ar,{value:"__loading__",disabled:!0,children:"Loading..."}):y.length===0?o.jsx(Ar,{value:"__empty__",disabled:!0,children:"No workflows"}):y.map(([L,D])=>o.jsx(Ar,{value:L,children:D.name||L},L))})]}),c==="workflow"&&d&&x&&o.jsx("span",{className:"text-neutral3 text-xs",children:"Loading schema..."}),c==="scorer"&&o.jsxs(oa,{value:p,onValueChange:L=>h(L),disabled:s,children:[o.jsx(ca,{size:"sm",className:"w-32",children:o.jsx(la,{})}),o.jsxs(ua,{children:[o.jsx(Ar,{value:"agent",children:"Agent"}),o.jsx(Ar,{value:"custom",children:"Custom"})]})]})]}),c==="scorer"&&o.jsx("p",{className:"text-neutral3 text-xs",children:p==="agent"?"For calibrating agent-type scorers":"For calibrating custom scorers (input/output as any)"})]}),o.jsx(lae,{label:"Input Schema",schemaType:"input",value:e,onChange:N,sourceSchema:E?C.inputSchema:void 0,autoPopulate:E}),o.jsx(lae,{label:"Ground Truth Schema",schemaType:"output",value:t,onChange:I,sourceSchema:E?C.outputSchema:void 0,autoPopulate:E}),o.jsx(lae,{label:"Request Context Schema",schemaType:"requestContext",value:n,onChange:A,autoPopulate:!1})]})]})}const FG=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"},{value:"processor",label:"Processor"}],ats=new Set(FG.map(e=>e.value));function $V(e){return typeof e=="string"&&ats.has(e)}function lbe({open:e,onOpenChange:t,onSuccess:n,targetType:r,targetIds:s}){const[a,i]=v.useState(""),[l,c]=v.useState(""),[u,d]=v.useState(null),[f,p]=v.useState(null),[h,m]=v.useState(null),[g,y]=v.useState(!r),[b,x]=v.useState(""),{createDataset:S}=Ni(),k=!!r,_=r??(b||void 0),C=N=>{d(N.inputSchema),p(N.outputSchema),m(N.requestContextSchema)},E=async N=>{if(N.preventDefault(),!a.trim()){Le.error("Dataset name is required");return}try{const I=await S.mutateAsync({name:a.trim(),description:l.trim()||void 0,inputSchema:u,groundTruthSchema:f,requestContextSchema:h,targetType:_,targetIds:s});Le.success("Dataset created successfully"),i(""),c(""),d(null),p(null),m(null),x(""),y(!r),t(!1),n?.(I.id)}catch(I){Le.error(`Failed to create dataset: ${I instanceof Error?I.message:"Unknown error"}`)}},j=()=>{i(""),c(""),d(null),p(null),m(null),x(""),y(!r),t(!1)};return o.jsx(br,{open:e,onOpenChange:t,children:o.jsxs(xr,{className:"max-w-2xl",children:[o.jsx(wr,{children:o.jsx(gr,{children:"Create Dataset"})}),o.jsx($r,{className:"max-h-[70vh] overflow-y-auto",children:o.jsxs("form",{onSubmit:E,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"dataset-name",children:"Name *"}),o.jsx(Cn,{id:"dataset-name",value:a,onChange:N=>i(N.target.value),placeholder:"Enter dataset name",autoFocus:!0})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"dataset-description",children:"Description"}),o.jsx(Cn,{id:"dataset-description",value:l,onChange:N=>c(N.target.value),placeholder:"Enter dataset description (optional)"})]}),!k&&o.jsx(Cc,{label:"Target type",name:"dataset-target-type",placeholder:"Select a target type (optional)",options:[...FG],value:b,onValueChange:N=>x(N),helpText:"What this dataset evaluates. Drives the Target column and the Target filter.",disabled:S.isPending}),r&&!g?o.jsx("button",{type:"button",className:"text-neutral3 hover:text-accent1 text-xs transition-colors",onClick:()=>y(!0),children:"+ Custom schema"}):o.jsx(Y8t,{inputSchema:u,outputSchema:f,requestContextSchema:h,onChange:C,disabled:S.isPending}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ce,{type:"button",onClick:j,children:"Cancel"}),o.jsx(ce,{type:"submit",variant:"primary",disabled:S.isPending||!a.trim(),children:S.isPending?"Creating...":"Create Dataset"})]})]})})]})})}const K8t=v.createContext(null);function its({children:e}){const[t,n]=v.useState({}),r=v.useRef(t);r.current=t;const s=v.useCallback(({datasetId:l,modelId:c,prompt:u,count:d,agentContext:f,generateFn:p})=>{n(h=>({...h,[l]:{datasetId:l,modelId:c,count:d,status:"generating",startedAt:Date.now()}})),p({datasetId:l,modelId:c,prompt:u,count:d,agentContext:f}).then(h=>{const m=h.items??[];n(g=>{const y=g[l];if(!y||y.status!=="generating")return g;if(m.length===0){Le.info("Generation complete — no items were produced.");const{[l]:b,...x}=g;return x}return Le.success(`Generated ${m.length} item${m.length>1?"s":""}. Click the dataset to review.`),{...g,[l]:{...y,status:"review-ready",items:m}}})}).catch(h=>{const m=h instanceof Error?h.message:"Unknown error";Le.error(`Generation failed: ${m}`),n(g=>{const y=g[l];return y?{...g,[l]:{...y,status:"error",error:m}}:g})})},[]),a=v.useCallback(l=>{n(c=>{const{[l]:u,...d}=c;return d})},[]),i=v.useCallback(l=>{const c=r.current[l];if(!c||c.status!=="review-ready"||!c.items)return null;const u=c.items;return n(d=>{const{[l]:f,...p}=d;return p}),u},[]);return o.jsx(K8t.Provider,{value:{tasks:t,startGeneration:s,dismissTask:a,consumeReviewItems:i},children:e})}function X8t(){const e=v.useContext(K8t);if(!e)throw new Error("useGenerationTasks must be used within GenerationProvider");return e}function $Ke(e){const t=[];return e?.description?t.push(`Generate diverse test inputs for an agent that ${e.description.toLowerCase()}.`):t.push("Generate diverse test inputs for this agent."),e?.instructions&&t.push(`Agent instructions: ${e.instructions}`),e?.tools?.length&&t.push(`The agent has these tools: ${e.tools.join(", ")}.`),t.push("Include edge cases, typical usage, and adversarial inputs."),t.join(" ")}function ots({datasetId:e,agentContext:t,onDismiss:n}){const{provider:r,model:s}=EEe(),[a,i]=v.useState(r),[l,c]=v.useState(s),u=a&&l?`${a}/${l}`:"",[d,f]=v.useState(()=>$Ke(t)),[p,h]=v.useState(5),m=v.useRef(null),{generateItems:g}=Ni(),{startGeneration:y}=X8t(),b=v.useCallback(()=>{if(!u){Le.error("Please select a provider and model");return}const S=d.trim()||$Ke(t);y({datasetId:e,modelId:u,prompt:S,count:p,agentContext:t,generateFn:async k=>({items:(await g.mutateAsync(k)).items??[]})}),n()},[d,p,u,e,g,t,n,y]),x=v.useCallback(S=>{S||n()},[n]);return o.jsx(br,{open:!0,onOpenChange:x,children:o.jsxs(xr,{ref:m,className:"max-w-2xl",children:[o.jsx(wr,{children:o.jsx(gr,{children:"Generate Test Data"})}),o.jsx($r,{children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(Dt,{children:"Model"}),o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("div",{className:"w-[160px]",children:o.jsx(Vy,{value:a,onValueChange:S=>{const k=fi(S);i(k),c("")},size:"sm",container:m})}),o.jsx("div",{className:"flex-1",children:o.jsx(qy,{llmId:a,value:l,onValueChange:c,size:"sm",container:m})})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Instructions (optional)"}),o.jsx($l,{value:d,onChange:S=>f(S.target.value),placeholder:"e.g., Generate diverse recipe queries covering different cuisines, dietary restrictions, and skill levels...",rows:4})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Number of items"}),o.jsx(Cn,{type:"number",min:1,max:50,value:p,onChange:S=>h(Math.max(1,Math.min(50,parseInt(S.target.value)||1)))})]}),!u&&o.jsx(ye,{variant:"ui-xs",className:"text-amber-400",children:"Select a provider and model above to generate items."})]})}),o.jsx(Tc,{className:"px-6",children:o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(ce,{onClick:()=>x(!1),children:"Cancel"}),o.jsxs(ce,{variant:"primary",onClick:b,disabled:!u,children:[o.jsx(qe,{children:o.jsx(Eg,{})}),"Generate"]})]})})]})})}function lts({datasetId:e,items:t,modelId:n,onDismiss:r,onStartOver:s}){const[a,i]=v.useState(t),[l,c]=v.useState(new Set(t.map((S,k)=>k))),[u,d]=v.useState(new Set([0])),f=a.length,{batchInsertItems:p}=Ni(),h=v.useCallback(async()=>{const S=a.filter((k,_)=>l.has(_)).map(k=>({input:k.input,groundTruth:k.groundTruth,source:{type:"llm",referenceId:n}}));if(S.length===0){Le.error("No items selected");return}try{await p.mutateAsync({datasetId:e,items:S}),Le.success(`Added ${S.length} item${S.length>1?"s":""} to dataset`),r()}catch(k){Le.error(`Failed to add items: ${k instanceof Error?k.message:"Unknown error"}`)}},[a,l,n,e,p,r]),m=v.useCallback(S=>{S||r()},[r]),g=v.useCallback(S=>{c(k=>{const _=new Set(k);return _.has(S)?_.delete(S):_.add(S),_})},[]),y=v.useCallback(S=>{d(k=>{const _=new Set(k);return _.has(S)?_.delete(S):_.add(S),_})},[]),b=v.useCallback(()=>{l.size===f?c(new Set):c(new Set(Array.from({length:f},(S,k)=>k)))},[l.size,f]),x=v.useCallback(S=>{i(k=>k.filter((_,C)=>C!==S)),c(k=>{const _=new Set;for(const C of k)C<S?_.add(C):C>S&&_.add(C-1);return _}),d(k=>{const _=new Set;for(const C of k)C<S?_.add(C):C>S&&_.add(C-1);return _})},[]);return o.jsx(br,{open:!0,onOpenChange:m,children:o.jsxs(xr,{className:"max-w-2xl",children:[o.jsx(wr,{children:o.jsx(gr,{children:"Review Generated Items"})}),o.jsx($r,{className:"flex max-h-[70vh] flex-col",children:o.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(zo,{checked:l.size===a.length,onCheckedChange:b}),o.jsxs(ye,{variant:"ui-sm",className:"text-neutral4",children:[l.size," of ",a.length," selected"]})]}),s&&o.jsx(ce,{variant:"ghost",size:"sm",onClick:s,children:"Start over"})]}),o.jsx(Br,{className:"min-h-0 flex-1",children:o.jsx("div",{className:"space-y-2",children:a.map((S,k)=>o.jsxs("div",{className:"border-border1 rounded-lg border",children:[o.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[o.jsx(zo,{checked:l.has(k),onCheckedChange:()=>g(k)}),o.jsx("button",{type:"button",className:"flex-1 text-left",onClick:()=>y(k),children:o.jsxs(ye,{variant:"ui-sm",className:"text-neutral5 truncate",children:["Item ",k+1,": ",cts(S.input)]})}),o.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>x(k),children:o.jsx(qe,{size:"sm",children:o.jsx(uu,{})})})]}),u.has(k)&&o.jsxs("div",{className:"border-border1 space-y-2 border-t px-3 py-2",children:[o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Input"}),o.jsx("pre",{className:"text-neutral5 bg-surface1 mt-1 max-h-32 overflow-x-auto overflow-y-auto rounded px-2 py-1.5 text-xs wrap-break-word whitespace-pre-wrap",children:JSON.stringify(S.input,null,2)})]}),S.groundTruth!==void 0&&o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Ground Truth"}),o.jsx("pre",{className:"text-neutral5 bg-surface1 mt-1 max-h-32 overflow-x-auto overflow-y-auto rounded px-2 py-1.5 text-xs wrap-break-word whitespace-pre-wrap",children:JSON.stringify(S.groundTruth,null,2)})]})]})]},k))})})]})}),o.jsx(Tc,{className:"px-6",children:o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(ce,{onClick:()=>m(!1),children:"Cancel"}),o.jsx(ce,{variant:"primary",onClick:h,disabled:l.size===0||p.isPending,children:p.isPending?o.jsxs(o.Fragment,{children:[o.jsx(Xt,{className:"h-4 w-4"}),"Adding..."]}):o.jsxs(o.Fragment,{children:[o.jsx(qe,{children:o.jsx(Zr,{})}),"Add ",l.size," Item",l.size!==1?"s":""]})})]})})]})})}function cts(e){if(typeof e=="string")return e.slice(0,80);if(typeof e=="object"&&e!==null){const n=Object.values(e)[0];return typeof n=="string"?n.slice(0,80):JSON.stringify(e).slice(0,80)}return String(e).slice(0,80)}function Sz(e){if(Array.isArray(e))return e;if(typeof e=="string"){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return[]}function MKe(e){return e?(typeof e=="string"?new Date(e):e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function kz(e){return e?e instanceof Date?e.getTime():new Date(e).getTime():0}const uts={completed:"success",running:"warning",failed:"error",pending:"neutral"};function dts({agentId:e,onSwitchToReview:t,pendingScorerItems:n,onPendingScorerItemsConsumed:r}){const[s,a]=v.useState("experiments"),[i,l]=v.useState(null),[c,u]=v.useState(!1),[d,f]=v.useState(!1),[p,h]=v.useState(""),[m,g]=v.useState(!1),[y,b]=v.useState(""),[x,S]=v.useState(null),[k,_]=v.useState(null),[C,E]=v.useState(""),[j,N]=v.useState(""),[I,A]=v.useState(""),{form:R,isCodeAgentOverride:L}=Ho(),{addItems:D}=pMt(),B=Dn({control:R.control,name:"scorers"})??{},H=Dn({control:R.control,name:"instructions"}),F=Dn({control:R.control,name:"description"}),z=Dn({control:R.control,name:"tools"}),{data:q,isLoading:M}=Bg(),G=q?.datasets??[],{data:V,isLoading:$}=ih(),{data:U,isLoading:Z}=PNe(e),{tasks:K}=X8t(),{updateDataset:te,updateExperimentResult:ee}=Ni(),{createStoredAgent:J,updateStoredAgent:ae}=w1(e),de=v.useMemo(()=>({description:F||"",instructions:H||"",tools:z?Object.keys(z):[]}),[F,H,z]);v.useEffect(()=>{for(const[Ce,Ee]of Object.entries(K))if(Ee.status==="review-ready"&&Ee.items?.length){_(Ce);break}},[K]),v.useEffect(()=>{n?.length&&(a("scorers"),l({type:"new-scorer",prefillTestItems:n.map(Ce=>({input:Ce.input,output:Ce.output,expectedDirection:"low"}))}),r?.())},[n,r]);const Y=G.filter(Ce=>Sz(Ce.targetIds).includes(e)),ne=G.filter(Ce=>!Sz(Ce.targetIds).includes(e)),fe=(U||[]).reduce((Ce,Ee)=>{const Oe=Ce[Ee.datasetId];return(!Oe||kz(Ee.startedAt)>kz(Oe.startedAt))&&(Ce[Ee.datasetId]=Ee),Ce},{}),oe=v.useMemo(()=>{const Ce=new Map;return Y.forEach(Ee=>Ce.set(Ee.id,Ee)),Ce},[Y]),le=Object.entries(V||{}),he=le.filter(([Ce])=>!!B[Ce]),be=le.filter(([Ce])=>!B[Ce]),xe=v.useCallback(async Ce=>{R.setValue("scorers",Ce,{shouldDirty:!1});const Ee={scorers:V8t(Ce)};try{await ae.mutateAsync(Ee)}catch(Oe){if(L)try{const Pe=R.getValues();await J.mutateAsync({id:e,name:Pe.name,instructions:rbe(Pe.instructionBlocks),model:Pe.model,...Ee})}catch(Pe){console.error("Failed to persist scorer change:",Pe),Le.error("Failed to save scorer changes")}else console.error("Failed to persist scorer change:",Oe),Le.error("Failed to save scorer changes")}},[R,e,L,J,ae]),je=v.useCallback(async(Ce,Ee)=>{const Pe={...R.getValues("scorers")||{},[Ce]:{sampling:Ee.sampling}};await xe(Pe)},[R,xe]),ke=v.useCallback(async Ce=>{const Ee=R.getValues("scorers")||{},{[Ce]:Oe,...Pe}=Ee;await xe(Pe)},[R,xe]),Ae=v.useCallback(async Ce=>{for(const Ee of Ce)if(Ee.experimentId&&Ee.datasetId)try{await ee.mutateAsync({datasetId:Ee.datasetId,experimentId:Ee.experimentId,resultId:Ee.id,status:"needs-review"})}catch{}D(Ce.map(Ee=>({id:Ee.id,itemId:Ee.itemId,input:Ee.input,output:Ee.output,error:Ee.error,scores:Ee.scores,experimentId:Ee.experimentId,datasetId:Ee.datasetId,traceId:Ee.traceId}))),t?.()},[D,t,ee]),Me=v.useCallback(Ce=>{a("scorers"),l({type:"new-scorer",prefillTestItems:Ce.map(Ee=>({input:Ee.input,output:Ee.output,expectedDirection:"low"}))})},[]),ue=v.useMemo(()=>{const Ce=[...U||[]].sort((Oe,Pe)=>{const Ue=kz(Oe.startedAt);return kz(Pe.startedAt)-Ue});if(!C)return Ce;const Ee=C.toLowerCase();return Ce.filter(Oe=>{const Pe=oe.get(Oe.datasetId)?.name??"";return Oe.id.toLowerCase().includes(Ee)||Pe.toLowerCase().includes(Ee)||(Oe.targetId??"").toLowerCase().includes(Ee)})},[U,C,oe]),re=v.useMemo(()=>{if(!j)return Y;const Ce=j.toLowerCase();return Y.filter(Ee=>Ee.name.toLowerCase().includes(Ce)||(Ee.description??"").toLowerCase().includes(Ce))},[Y,j]),se=v.useMemo(()=>{if(!I)return he;const Ce=I.toLowerCase();return he.filter(([Ee,Oe])=>(Oe.scorer?.name||Ee).toLowerCase().includes(Ce))},[he,I]),me=v.useCallback(Ce=>{a(Ce),l(null)},[]);function we(){if(!i)return null;const Ce=(Ee,Oe)=>o.jsx("div",{className:"border-border1 flex items-center gap-2 border-b px-4 py-2",children:o.jsxs(ce,{variant:"ghost",size:"sm",onClick:Oe,children:[o.jsx(lit,{className:"size-4"}),Ee]})});if(i.type==="dataset")return o.jsxs(Yr,{withLeftSeparator:!0,children:[Ce("Back to Datasets",()=>l(null)),o.jsx(Yr.Content,{children:o.jsx(qes,{agentId:e,datasetId:i.id,datasetName:oe.get(i.id)?.name??"",datasetDescription:oe.get(i.id)?.description??void 0,datasetTags:oe.get(i.id)?.tags??void 0,datasetTargetType:oe.get(i.id)?.targetType,datasetTargetIds:Sz(oe.get(i.id)?.targetIds),activeScorers:Object.keys(B),datasetScorerIds:oe.get(i.id)?.scorerIds??null,onGenerate:()=>S(i.id),onViewExperiment:Ee=>l({type:"experiment",id:Ee,datasetId:i.id})})})]});if(i.type==="scorer")return o.jsxs(Yr,{withLeftSeparator:!0,children:[Ce("Back to Scorers",()=>l(null)),o.jsx(Yr.Content,{children:o.jsx(Zes,{scorerId:i.id,scorerData:V?.[i.id],isAttached:!!B[i.id],onToggleAttach:async()=>{B[i.id]?await ke(i.id):await je(i.id,V?.[i.id]??{})},onEdit:()=>l({type:"edit-scorer",id:i.id,scorerData:V?.[i.id]??{}}),linkedDatasets:G.map(Ee=>({id:Ee.id,name:Ee.name})),onViewDataset:Ee=>{a("datasets"),l({type:"dataset",id:Ee})}})})]});if(i.type==="new-scorer")return o.jsxs(Yr,{withLeftSeparator:!0,children:[Ce("Back to Scorers",()=>l(null)),o.jsx(Yr.Content,{children:o.jsx(RKe,{onBack:()=>l(null),prefillTestItems:i.prefillTestItems,onSaved:Ee=>{je(Ee,{}),l({type:"scorer",id:Ee})}})})]});if(i.type==="edit-scorer")return o.jsxs(Yr,{withLeftSeparator:!0,children:[Ce("Back to Scorer",()=>l({type:"scorer",id:i.id})),o.jsx(Yr.Content,{children:o.jsx(RKe,{onBack:()=>l({type:"scorer",id:i.id}),editScorerId:i.id,editScorerData:i.scorerData,onSaved:()=>l({type:"scorer",id:i.id})})})]});if(i.type==="experiment"){const Ee=U?.find(Oe=>Oe.id===i.id);return Ee?o.jsxs(Yr,{withLeftSeparator:!0,children:[Ce("Back to Experiments",()=>l(null)),o.jsx(Yr.Content,{children:o.jsx($es,{experiment:Ee,onBack:()=>l(null),onSendToReview:Ae,onCreateScorer:Me})})]}):o.jsxs(Yr,{withLeftSeparator:!0,children:[Ce("Back to Experiments",()=>l(null)),o.jsx(Yr.Content,{children:o.jsx("div",{className:"text-neutral3 p-4",children:"Experiment not found"})})]})}return null}function Ne(){return Z?o.jsx(ol,{columns:"auto minmax(15rem,1fr) auto auto auto auto auto"}):U?.length?o.jsxs(ve,{columns:"auto minmax(15rem,1fr) auto auto auto auto auto",className:"min-w-0",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Experiment"}),o.jsx(ve.TopCell,{children:"Dataset"}),o.jsx(ve.TopCell,{children:"Status"}),o.jsx(ve.TopCell,{className:"text-center",children:"Items"}),o.jsx(ve.TopCell,{className:"text-center",children:"Succeeded"}),o.jsx(ve.TopCell,{className:"text-center",children:"Failed"}),o.jsx(ve.TopCell,{children:"Date"})]}),ue.map(Ce=>{const Ee=oe.get(Ce.datasetId)?.name??Ce.datasetId.slice(0,8),Oe=Ce.status??"pending",Pe=Ce.succeededCount??0,Ue=Ce.failedCount??0,Ke=Ce.totalItems??0,tt=Ke>0?Math.round(Pe/Ke*100):0,Pt=i?.type==="experiment"&&i.id===Ce.id;return o.jsxs(ve.RowButton,{featured:Pt,onClick:()=>l({type:"experiment",id:Ce.id,datasetId:Ce.datasetId}),children:[o.jsx(ve.IdCell,{id:Ce.id}),o.jsx(ve.Cell,{height:"compact",className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:Ee})}),o.jsx(ve.Cell,{height:"compact",children:o.jsx(bg,{variant:uts[Oe]??"neutral",withDot:!0,children:Oe})}),o.jsx(ve.Cell,{height:"compact",className:"text-center",children:Ke}),o.jsx(ve.Cell,{height:"compact",className:"text-center",children:o.jsxs("span",{className:Pe>0?"text-accent1":"",children:[Pe," (",tt,"%)"]})}),o.jsx(ve.Cell,{height:"compact",className:"text-center",children:o.jsx("span",{className:Ue>0?"text-accent2":"",children:Ue})}),o.jsx(ve.Cell,{height:"compact",children:MKe(Ce.startedAt)})]},Ce.id)})]}):o.jsx("div",{className:"flex h-full items-center justify-center py-20",children:o.jsx(Lr,{iconSlot:o.jsx(pit,{className:"text-neutral3 size-10"}),titleSlot:"No Experiments Yet",descriptionSlot:"Run experiments against your datasets to see results here."})})}function Re(){return M?o.jsx(ol,{columns:"minmax(10rem,1fr) auto auto auto auto"}):Y.length?o.jsxs(ve,{columns:"minmax(10rem,1fr) auto auto auto auto",className:"min-w-0",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Name"}),o.jsx(ve.TopCell,{children:"Tags"}),o.jsx(ve.TopCell,{children:"Latest Experiment"}),o.jsx(ve.TopCell,{children:"Status"}),o.jsx(ve.TopCell,{children:"Updated"})]}),re.map(Ce=>{const Ee=fe[Ce.id],Oe=K[Ce.id],Pe=Oe?.status==="generating",Ue=i?.type==="dataset"&&i.id===Ce.id;return o.jsxs(ve.RowButton,{featured:Ue,onClick:()=>l({type:"dataset",id:Ce.id}),children:[o.jsx(ve.Cell,{height:"compact",className:"text-neutral4 min-w-0",children:o.jsx("span",{className:"block truncate",children:Ce.name})}),o.jsx(ve.Cell,{height:"compact",children:Ce.tags?.length?o.jsxs("div",{className:"flex gap-1",children:[Ce.tags.slice(0,2).map(Ke=>o.jsx(un,{variant:"default",children:Ke},Ke)),Ce.tags.length>2&&o.jsxs(un,{variant:"default",children:["+",Ce.tags.length-2]})]}):o.jsx("span",{className:"text-neutral2",children:"—"})}),o.jsx(ve.Cell,{height:"compact",children:Ee?o.jsx(fts,{experiment:Ee}):o.jsx("span",{className:"text-neutral2",children:"No experiments"})}),o.jsx(ve.Cell,{height:"compact",children:Pe?o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Xt,{className:"size-3"}),o.jsx(ye,{variant:"ui-xs",className:"text-warning1",children:"Generating..."})]}):Oe?.error?o.jsx(ye,{variant:"ui-xs",className:"text-negative1",children:"Failed"}):o.jsx("span",{className:"text-neutral2",children:"—"})}),o.jsx(ve.Cell,{height:"compact",children:MKe(Ce.updatedAt)})]},Ce.id)})]}):o.jsx("div",{className:"flex h-full items-center justify-center py-20",children:o.jsx(Lr,{iconSlot:o.jsx(cy,{className:"text-neutral3 size-10"}),titleSlot:"No Datasets",descriptionSlot:"Create or attach a dataset to begin testing your agent."})})}function Qe(){return $?o.jsx(ol,{columns:"minmax(10rem,1fr) auto auto auto"}):he.length?o.jsxs(ve,{columns:"minmax(10rem,1fr) auto auto auto",className:"min-w-0",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Name"}),o.jsx(ve.TopCell,{children:"Source"}),o.jsx(ve.TopCell,{children:"Description"}),o.jsx(ve.TopCell,{children:"Datasets"})]}),se.map(([Ce,Ee])=>{const Oe=Ee.scorer?.name||Ce,Pe=Ee.scorer?.description||"",Ue=Ee.source??"stored",Ke=G.filter(Pt=>(Pt.scorerIds??[]).includes(Ce)).length,tt=i?.type==="scorer"&&i.id===Ce;return o.jsxs(ve.RowButton,{featured:tt,onClick:()=>l({type:"scorer",id:Ce}),children:[o.jsx(ve.Cell,{height:"compact",className:"text-neutral4 min-w-0",children:o.jsx("span",{className:"block truncate",children:Oe})}),o.jsx(ve.Cell,{height:"compact",children:o.jsx(un,{variant:Ue==="code"?"default":"success",children:Ue})}),o.jsx(ve.Cell,{height:"compact",className:"min-w-0",children:o.jsx("span",{className:"block max-w-[200px] truncate",children:Pe||o.jsx("span",{className:"text-neutral2",children:"—"})})}),o.jsx(ve.Cell,{height:"compact",children:Ke>0?`${Ke} dataset${Ke>1?"s":""}`:"—"})]},Ce)})]}):o.jsx("div",{className:"flex h-full items-center justify-center py-20",children:o.jsx(Lr,{iconSlot:o.jsx(nm,{className:"text-neutral3 size-10"}),titleSlot:"No Scorers Attached",descriptionSlot:"Attach or create a scorer to evaluate your agent's performance."})})}function Ze(){return o.jsxs(o.Fragment,{children:[o.jsx(lbe,{open:c,onOpenChange:u,targetType:"agent",targetIds:[e]}),x&&o.jsx(ots,{datasetId:x,agentContext:de,onDismiss:()=>S(null)}),k&&K[k]?.status==="review-ready"&&K[k]?.items&&o.jsx(lts,{datasetId:k,items:K[k].items,modelId:K[k].modelId,onDismiss:()=>_(null)}),o.jsx(br,{open:d,onOpenChange:f,children:o.jsxs(xr,{children:[o.jsx(wr,{children:o.jsx(gr,{children:"Attach Existing Dataset"})}),o.jsxs($r,{className:"max-h-[50vh] overflow-y-auto",children:[o.jsxs(Pu,{variant:"outline",children:[o.jsx(Kc,{align:"inline-start",children:o.jsx(Ya,{})}),o.jsx($u,{type:"search","aria-label":"Search datasets",placeholder:"Search datasets...",onChange:Ce=>h(Ce.target.value)})]}),ne.filter(Ce=>!p||Ce.name.toLowerCase().includes(p.toLowerCase())).map(Ce=>o.jsx("button",{type:"button",className:"hover:bg-surface3 flex w-full items-center justify-between rounded-md px-3 py-2 text-left transition-colors",onClick:async()=>{try{await te.mutateAsync({datasetId:Ce.id,targetType:Ce.targetType??"agent",targetIds:[...Sz(Ce.targetIds),e]}),Le.success(`Dataset "${Ce.name}" attached`),f(!1)}catch{Le.error("Failed to attach dataset")}},children:o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-sm",className:"font-medium",children:Ce.name}),Ce.description&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 block",children:Ce.description})]})},Ce.id)),ne.filter(Ce=>!p||Ce.name.toLowerCase().includes(p.toLowerCase())).length===0&&o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 block py-4 text-center",children:"No datasets available to attach"})]})]})}),o.jsx(br,{open:m,onOpenChange:g,children:o.jsxs(xr,{children:[o.jsx(wr,{children:o.jsx(gr,{children:"Attach Existing Scorer"})}),o.jsxs($r,{className:"max-h-[50vh] overflow-y-auto",children:[o.jsxs(Pu,{variant:"outline",children:[o.jsx(Kc,{align:"inline-start",children:o.jsx(Ya,{})}),o.jsx($u,{type:"search","aria-label":"Search scorers",placeholder:"Search scorers...",onChange:Ce=>b(Ce.target.value)})]}),be.filter(([Ce,Ee])=>y?(Ee.scorer?.name||Ce).toLowerCase().includes(y.toLowerCase()):!0).map(([Ce,Ee])=>o.jsx("button",{type:"button",className:"hover:bg-surface3 flex w-full items-center justify-between rounded-md px-3 py-2 text-left transition-colors",onClick:async()=>{try{await je(Ce,Ee),Le.success(`Scorer "${Ee.scorer?.name||Ce}" attached`),g(!1)}catch{Le.error("Failed to attach scorer")}},children:o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-sm",className:"font-medium",children:Ee.scorer?.name||Ce}),Ee.scorer?.description&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 block",children:Ee.scorer.description})]})},Ce)),be.filter(([Ce,Ee])=>y?(Ee.scorer?.name||Ce).toLowerCase().includes(y.toLowerCase()):!0).length===0&&o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 block py-4 text-center",children:"No scorers available to attach"})]})]})})]})}const Te=!!i;return o.jsxs("div",{className:"flex h-full flex-col overflow-hidden p-4",children:[o.jsxs(Dc,{defaultTab:"experiments",value:s,onValueChange:me,className:"flex h-full flex-col overflow-hidden",children:[o.jsxs("div",{className:"border-border1 flex items-center justify-between border-b",children:[o.jsxs(Mc,{className:"border-b-0",children:[o.jsx(Rr,{value:"experiments",children:"Experiments"}),o.jsx(Rr,{value:"datasets",children:"Datasets"}),o.jsx(Rr,{value:"scorers",children:"Scorers"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[s==="datasets"&&o.jsxs(o.Fragment,{children:[ne.length>0&&o.jsxs(ce,{variant:"ghost",size:"sm",onClick:()=>f(!0),children:[o.jsx(A2e,{className:"mr-1 size-3.5"}),"Attach"]}),o.jsxs(ce,{variant:"ghost",size:"sm",onClick:()=>u(!0),children:[o.jsx(Zr,{className:"mr-1 size-3.5"}),"Create"]})]}),s==="scorers"&&o.jsxs(o.Fragment,{children:[be.length>0&&o.jsxs(ce,{variant:"ghost",size:"sm",onClick:()=>g(!0),children:[o.jsx(A2e,{className:"mr-1 size-3.5"}),"Attach"]}),o.jsxs(ce,{variant:"ghost",size:"sm",onClick:()=>l({type:"new-scorer"}),children:[o.jsx(Zr,{className:"mr-1 size-3.5"}),"New"]})]})]})]}),o.jsxs("div",{className:"border-border1 border-b py-2",children:[s==="experiments"&&o.jsxs(Pu,{variant:"outline",children:[o.jsx(Kc,{align:"inline-start",children:o.jsx(Ya,{})}),o.jsx($u,{type:"search","aria-label":"Search experiments",placeholder:"Search experiments...",onChange:Ce=>E(Ce.target.value)})]}),s==="datasets"&&o.jsxs(Pu,{variant:"outline",children:[o.jsx(Kc,{align:"inline-start",children:o.jsx(Ya,{})}),o.jsx($u,{type:"search","aria-label":"Search datasets",placeholder:"Search datasets...",onChange:Ce=>N(Ce.target.value)})]}),s==="scorers"&&o.jsxs(Pu,{variant:"outline",children:[o.jsx(Kc,{align:"inline-start",children:o.jsx(Ya,{})}),o.jsx($u,{type:"search","aria-label":"Search scorers",placeholder:"Search scorers...",onChange:Ce=>A(Ce.target.value)})]})]}),o.jsxs("div",{className:"flex-1 overflow-hidden",children:[o.jsx(Xr,{value:"experiments",className:"h-full overflow-hidden",children:o.jsxs(ly,{className:Te&&i?.type==="experiment"?"grid-cols-[1fr_1fr]":"",children:[o.jsx(Yr,{children:o.jsx(Yr.Content,{children:Ne()})}),i?.type==="experiment"&&we()]})}),o.jsx(Xr,{value:"datasets",className:"h-full overflow-hidden",children:o.jsxs(ly,{className:Te&&i?.type==="dataset"?"grid-cols-[1fr_1fr]":"",children:[o.jsx(Yr,{children:o.jsx(Yr.Content,{children:Re()})}),i?.type==="dataset"&&we()]})}),o.jsx(Xr,{value:"scorers",className:"h-full overflow-hidden",children:o.jsxs(ly,{className:Te&&(i?.type==="scorer"||i?.type==="new-scorer"||i?.type==="edit-scorer")?"grid-cols-[1fr_1fr]":"",children:[o.jsx(Yr,{children:o.jsx(Yr.Content,{children:Qe()})}),(i?.type==="scorer"||i?.type==="new-scorer"||i?.type==="edit-scorer")&&we()]})})]})]}),Ze()]})}function fts({experiment:e}){const{status:t,succeededCount:n,totalItems:r}=e,s=[e.datasetVersion!=null?NN("Dataset",e.datasetVersion):null,e.agentVersion?NN("Agent",e.agentVersion):null].filter(Boolean),a=s.length>0?o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:s.join(" · ")}):null;if(t==="running"||t==="pending")return o.jsxs("div",{className:"flex flex-col",children:[o.jsx(ye,{variant:"ui-xs",className:"text-warning1",children:t==="running"?"Running...":"Pending..."}),a]});if(r===0)return o.jsxs("div",{className:"flex flex-col",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3",children:"No results"}),a]});const i=n/r,l=i>=.8?"text-positive1":i>=.5?"text-warning1":"text-negative1";return o.jsxs("div",{className:"flex flex-col",children:[o.jsxs(ye,{variant:"ui-xs",className:l,children:[n,"/",r," passed"]}),a]})}const pts=e=>{const t=We(),{data:n}=PNe(e);return yt({queryKey:["completed-items",e,n?.map(r=>r.id)],queryFn:async()=>!n||n.length===0?[]:(await Promise.all(n.map(async s=>{try{const{results:a}=await t.listDatasetExperimentResults(s.datasetId,s.id);return a.filter(i=>i.status==="complete").map(i=>({id:i.id,input:i.input,output:i.output,error:i.error,itemId:i.itemId,experimentId:i.experimentId,datasetId:s.datasetId,traceId:i.traceId??void 0,scores:i.scores?Object.fromEntries(i.scores.map(l=>[l.scorerId,l.score??0])):{},tags:i.tags??[],comment:""}))}catch{return[]}}))).flat(),enabled:!!e&&!!n&&n.length>0,refetchOnWindowFocus:!1})},hts=e=>{const t=We(),{data:n}=PNe(e);return yt({queryKey:["review-items",e,n?.map(r=>r.id)],queryFn:async()=>!n||n.length===0?[]:(await Promise.all(n.map(async s=>{try{const{results:a}=await t.listDatasetExperimentResults(s.datasetId,s.id);return a.filter(i=>i.status==="needs-review").map(i=>({id:i.id,input:i.input,output:i.output,error:i.error,itemId:i.itemId,experimentId:i.experimentId,datasetId:s.datasetId,traceId:i.traceId??void 0,scores:i.scores?Object.fromEntries(i.scores.map(l=>[l.scorerId,l.score??0])):{},tags:i.tags??[],comment:""}))}catch{return[]}}))).flat(),enabled:!!e&&!!n&&n.length>0,refetchOnWindowFocus:!1})};function mts({tags:e,vocabulary:t,onSetTags:n}){const[r,s]=v.useState(!1),[a,i]=v.useState(""),l=v.useRef(null),c=t.filter(h=>!e.includes(h)&&h.toLowerCase().includes(a.toLowerCase())),u=a.trim()&&!t.includes(a.trim())&&!e.includes(a.trim()),d=h=>{n([...e,h]),i("")},f=h=>{n(e.filter(m=>m!==h))},p=h=>{h.key==="Enter"&&a.trim()&&(h.preventDefault(),d(a.trim()))};return o.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[e.map(h=>o.jsxs("span",{className:"bg-accent1/10 text-accent1 inline-flex items-center gap-0.5 rounded-md px-1.5 py-0.5 text-[10px] font-medium",children:[h,o.jsx("button",{type:"button",onClick:()=>f(h),className:"hover:text-accent1/70",children:o.jsx(bs,{className:"h-2.5 w-2.5"})})]},h)),o.jsxs(Pf,{open:r,onOpenChange:s,children:[o.jsx(Bd,{asChild:!0,children:o.jsxs("button",{type:"button",className:"text-neutral3 hover:text-neutral5 hover:bg-surface3 inline-flex items-center gap-0.5 rounded px-1 py-0.5 text-[10px] transition-colors",children:[o.jsx(Zr,{className:"h-3 w-3"}),"tag"]})}),o.jsxs(Ud,{className:"w-52 p-2",align:"start",children:[o.jsx(Cn,{ref:l,value:a,onChange:h=>i(h.target.value),onKeyDown:p,placeholder:"Search or create tag...",className:"mb-1 h-7 text-xs",autoFocus:!0}),o.jsxs("div",{className:"max-h-32 space-y-0.5 overflow-y-auto",children:[c.map(h=>o.jsx("button",{type:"button",onClick:()=>d(h),className:"hover:bg-surface3 text-neutral4 w-full rounded px-2 py-1 text-left text-xs",children:h},h)),u&&o.jsxs("button",{type:"button",onClick:()=>d(a.trim()),className:"hover:bg-surface3 text-accent1 w-full rounded px-2 py-1 text-left text-xs",children:['Create "',a.trim(),'"']}),c.length===0&&!u&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 block px-2 py-1",children:"No tags available"})]})]})]})]})}function cae(e){if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function J8t({item:e,isCompleted:t,tagVocabulary:n,onRate:r,onSetTags:s,onComment:a,onRemove:i,onComplete:l,onPrevious:c,onNext:u,onClose:d}){const[f,p]=v.useState(e.comment||""),[h,m]=v.useState(!1),[g,y]=v.useState(!1);v.useEffect(()=>{p(e.comment||""),m(!1),y(!1)},[e.id]);const b=v.useRef(void 0);v.useEffect(()=>()=>clearTimeout(b.current),[]);const x=()=>{f!==(e.comment||"")&&(a(f),m(!0),clearTimeout(b.current),b.current=setTimeout(()=>m(!1),1500))};return o.jsxs(o.Fragment,{children:[o.jsxs(xn,{children:[o.jsxs(xn.Header,{children:[o.jsx(xn.Heading,{children:"Review"}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[o.jsx(xn.NextPrevNav,{onPrevious:c,onNext:u,previousLabel:"Previous item",nextLabel:"Next item"}),!t&&l&&o.jsxs(ce,{size:"md",onClick:l,"aria-label":"Mark as complete",children:[o.jsx(lO,{}),"Complete"]}),o.jsx(xn.CloseButton,{onClick:d,tooltip:"Close detail panel"})]})]}),o.jsxs(xn.Content,{children:[o.jsxs("div",{className:"mb-6 grid gap-4",children:[!t&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"Rating"}),o.jsxs(Mr,{spacing:"close",children:[o.jsx(ce,{size:"md",onClick:()=>r(e.rating==="positive"?void 0:"positive"),"aria-label":"Rate positive",children:o.jsx(qe,{size:"sm",className:e.rating==="positive"?"text-positive1":"",children:o.jsx(Ube,{})})}),o.jsx(ce,{size:"md",onClick:()=>r(e.rating==="negative"?void 0:"negative"),"aria-label":"Rate negative",children:o.jsx(qe,{size:"sm",className:e.rating==="negative"?"text-negative1":"",children:o.jsx(Bbe,{})})})]}),e.rating&&o.jsx(un,{variant:e.rating==="positive"?"success":"error",children:e.rating==="positive"?"Good":"Bad"})]}),t&&e.rating&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral3",children:"Rating"}),o.jsx(un,{variant:e.rating==="positive"?"success":"error",children:e.rating==="positive"?"Good":"Bad"})]}),o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 mt-0 block",children:"Tags"}),t?o.jsx("div",{className:"flex flex-wrap gap-1",children:e.tags.length>0?e.tags.map(S=>o.jsx(un,{variant:"default",children:S},S)):o.jsx(ye,{variant:"ui-sm",className:"text-neutral2",children:"No tags"})}):o.jsx(mts,{tags:e.tags,vocabulary:n,onSetTags:s})]}),e.scores&&Object.keys(e.scores).length>0&&o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mb-2 block",children:"Scores"}),o.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(e.scores).map(([S,k])=>o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(qe,{size:"sm",className:"text-neutral3",children:o.jsx(nm,{})}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral4",children:[S,":"]}),o.jsx(un,{variant:k>=.5?"success":"error",children:k.toFixed(3)})]},S))})]}),e.experimentId&&o.jsxs(Ut,{children:[o.jsx(Ut.Key,{children:"Experiment Id"}),o.jsx(Ut.ValueWithCopyBtn,{copyTooltip:"Copy Experiment Id to clipboard",copyValue:e.experimentId,children:e.experimentId})]})]}),o.jsxs("div",{className:"grid gap-3",children:[o.jsx(xn.CodeSection,{title:"Input",icon:o.jsx(cO,{}),codeStr:cae(e.input??null)}),o.jsx(xn.CodeSection,{title:"Output",icon:o.jsx(Sg,{}),codeStr:cae(e.output??null)})]}),e.error!=null&&o.jsxs("div",{children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mb-1 block",children:"Error"}),o.jsx("pre",{className:"text-ui-xs text-negative1 bg-surface2 max-h-48 overflow-auto rounded-md p-3 wrap-break-word whitespace-pre-wrap",children:cae(e.error)})]}),o.jsxs("div",{className:"mt-4",children:[o.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral2 tracking-widest uppercase",children:"Comment"}),h&&o.jsx(ye,{variant:"ui-xs",className:"text-positive1",children:"Saved"})]}),t?o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 block",children:e.comment||"No comment"}):o.jsx($l,{value:f,onChange:S=>p(S.target.value),onBlur:x,placeholder:"Add notes about this item...",rows:3,className:"text-xs"})]}),!t&&o.jsxs("div",{className:"border-border1 mt-4 flex items-center gap-2 border-t pt-4",children:[l&&o.jsxs(ce,{size:"md",onClick:l,children:[o.jsx(lO,{}),"Mark as complete"]}),o.jsxs(ce,{variant:"outline",size:"md",onClick:()=>y(!0),children:[o.jsx(uu,{}),"Remove"]})]})]})]}),o.jsx(At,{open:g,onOpenChange:y,children:o.jsxs(At.Content,{children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Remove from Review"}),o.jsx(At.Description,{children:"This will remove the item from the review queue. The experiment result will remain but will no longer be flagged for review."})]}),o.jsxs(At.Footer,{children:[o.jsx(At.Cancel,{children:"Cancel"}),o.jsx(At.Action,{onClick:()=>{i(),y(!1)},children:"Remove"})]})]})})]})}function e9t({selectedCount:e,vocabulary:t,onApplyTag:n,onRemoveTag:r,onNewTag:s}){const[a,i]=v.useState(!1),[l,c]=v.useState(""),u=t.filter(f=>f.toLowerCase().includes(l.toLowerCase())),d=l.trim()&&!t.includes(l.trim());return o.jsxs(Pf,{open:a,onOpenChange:i,children:[o.jsx(Bd,{asChild:!0,children:o.jsxs(ce,{variant:"outline",size:"sm",children:[o.jsx(qe,{size:"sm",children:o.jsx(BN,{})}),"Tag ",e," items"]})}),o.jsxs(Ud,{className:"w-56 p-2",align:"end",children:[o.jsx(Cn,{value:l,onChange:f=>c(f.target.value),onKeyDown:f=>{f.key==="Enter"&&l.trim()&&(f.preventDefault(),d?s(l.trim()):n(l.trim()),c(""))},placeholder:"Search or create tag...",className:"mb-1 h-7 text-xs",autoFocus:!0}),o.jsxs("div",{className:"max-h-40 space-y-0.5 overflow-y-auto",children:[u.map(f=>o.jsxs("div",{className:"hover:bg-surface3 flex items-center justify-between rounded px-2 py-1 text-xs",children:[o.jsx("button",{type:"button",onClick:()=>n(f),className:"text-neutral4 flex-1 text-left",children:f}),o.jsx("button",{type:"button",onClick:()=>r(f),className:"text-neutral2 hover:text-negative1 ml-2",children:o.jsx(bs,{className:"h-3 w-3"})})]},f)),d&&o.jsxs("button",{type:"button",onClick:()=>{s(l.trim()),c("")},className:"hover:bg-surface3 text-accent1 w-full rounded px-2 py-1 text-left text-xs",children:['Create & apply "',l.trim(),'"']})]})]})]})}function t9t({tag:e,onRename:t,onRemove:n}){const[r,s]=v.useState(!1),[a,i]=v.useState(e),l=v.useRef(null);v.useEffect(()=>{r&&(l.current?.focus(),l.current?.select())},[r]);const c=()=>{const u=a.trim();u&&u!==e&&t(u),s(!1)};return r?o.jsxs("span",{className:"bg-surface3 border-border1 inline-flex items-center gap-0.5 rounded-md border px-1",children:[o.jsx("input",{ref:l,value:a,onChange:u=>i(u.target.value),onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),c()),u.key==="Escape"&&(i(e),s(!1))},onBlur:c,className:"text-neutral4 w-20 bg-transparent py-0.5 text-xs outline-hidden"}),o.jsx("button",{type:"button",onMouseDown:u=>{u.preventDefault(),c()},className:"text-positive1 hover:text-positive2 p-0.5",children:o.jsx(fa,{className:"h-3 w-3"})})]}):o.jsxs("span",{className:"bg-surface3 border-border1 text-neutral4 group inline-flex items-center gap-0.5 rounded-md border px-1.5 py-0.5 text-xs",children:[e,o.jsx("button",{type:"button",onClick:()=>{i(e),s(!0)},className:"text-neutral2 hover:text-neutral4 p-0.5 opacity-0 transition-opacity group-hover:opacity-100",title:"Edit tag",children:o.jsx(rm,{className:"h-3 w-3"})}),o.jsx("button",{type:"button",onClick:n,className:"text-neutral2 hover:text-negative1 p-0.5 opacity-0 transition-opacity group-hover:opacity-100",title:"Remove tag",children:o.jsx(bs,{className:"h-3 w-3"})})]})}function gts(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 vts({agentId:e,onCreateScorer:t}){const{items:n,setItemTags:r,rateItem:s,commentItem:a,removeItem:i,completeItem:l,loadPersistedItems:c}=pMt(),{data:u}=hts(e),{data:d,refetch:f,isLoading:p}=pts(e),h=We(),{provider:m,model:g}=EEe(),{data:y}=Bg(),{updateDataset:b}=Ni();v.useEffect(()=>{u&&c(u)},[u,c]);const[x,S]=v.useState(null),[k,_]=v.useState(!1),[C,E]=v.useState(null),[j,N]=v.useState(new Set),[I,A]=v.useState(!1),R=v.useRef(null),[L,D]=v.useState(!1),[B,H]=v.useState("untagged"),[F,z]=v.useState(""),[q,M]=v.useState(m),[G,V]=v.useState(g),[$,U]=v.useState([]),[Z,K]=v.useState(!1),[te,ee]=v.useState(null),J=y?.datasets,ae=v.useMemo(()=>{if(!J)return[];const Oe=new Set(n.map(Ue=>Ue.datasetId).filter(Boolean)),Pe=new Set;for(const Ue of J)if(Oe.has(Ue.id)&&Array.isArray(Ue.tags))for(const Ke of Ue.tags)Pe.add(Ke);for(const Ue of n)for(const Ke of Ue.tags)Pe.add(Ke);return Array.from(Pe).sort()},[J,n]),de=v.useCallback(Oe=>{if(!J)return;const Pe=new Set(n.map(Ue=>Ue.datasetId).filter(Boolean));for(const Ue of J)if(Pe.has(Ue.id)){const Ke=Array.isArray(Ue.tags)?Ue.tags:[];Ke.includes(Oe)||b.mutate({datasetId:Ue.id,tags:[...Ke,Oe]})}},[J,n,b]),Y=v.useCallback(Oe=>{H(Oe),z(""),M(m),V(g),D(!0)},[m,g]),ne=v.useCallback(async()=>{if(!q||!G)return;const Oe=B==="untagged"?n.filter(Pe=>Pe.tags.length===0):n.filter(Pe=>j.has(Pe.id));if(Oe.length!==0){D(!1),_(!0);try{const Pe=`${q}/${G}`,Ke=((await h.clusterFailures({modelId:Pe,items:Oe.map(tt=>({id:tt.id,input:tt.input,output:tt.output,error:typeof tt.error=="string"?tt.error:tt.error?JSON.stringify(tt.error):void 0,scores:tt.scores,existingTags:tt.tags.length>0?tt.tags:void 0})),availableTags:ae.length>0?ae:void 0,prompt:F.trim()||void 0})).proposedTags??[]).filter(tt=>tt.tags.length>0).map(tt=>({itemId:tt.itemId,tags:tt.tags,reason:tt.reason||"",accepted:!0}));Ke.length>0?(ee(Pe),U(Ke),K(!0)):Le.success("Analysis complete — no new tags proposed.")}catch(Pe){console.error("Failed to analyze failures:",Pe),Le.error("Analysis failed. Please try again.")}finally{_(!1)}}},[n,q,G,h,j,ae,B,F]),fe=v.useCallback(()=>{const Oe=$.filter(tt=>tt.accepted);for(const tt of Oe){const Pt=n.find(Ot=>Ot.id===tt.itemId);if(Pt){const Ot=Array.from(new Set([...Pt.tags,...tt.tags]));r(tt.itemId,Ot)}}const Pe=new Set(Oe.flatMap(tt=>tt.tags));for(const tt of Pe)de(tt);const Ue=Pe.size,Ke=Oe.length;Le.success(`Applied ${Ue} tag${Ue!==1?"s":""} to ${Ke} item${Ke!==1?"s":""}`),K(!1),U([])},[$,n,r,de]),oe=v.useMemo(()=>C?C==="__untagged__"?n.filter(Oe=>Oe.tags.length===0):n.filter(Oe=>Oe.tags.includes(C)):n,[n,C]),le=v.useMemo(()=>{const Oe=new Map;for(const Pe of n)for(const Ue of Pe.tags)Oe.set(Ue,(Oe.get(Ue)??0)+1);return[...Oe.entries()].sort((Pe,Ue)=>Ue[1]-Pe[1])},[n]),he=v.useMemo(()=>n.filter(Oe=>Oe.tags.length===0).length,[n]),be=v.useMemo(()=>{let Oe=0;return C&&Oe++,I&&Oe++,Oe},[C,I]),xe=v.useMemo(()=>{const Oe=I?d??[]:oe;return!I||!C?Oe:C==="__untagged__"?Oe.filter(Pe=>Pe.tags.length===0):Oe.filter(Pe=>Pe.tags.includes(C))},[I,d,oe,C]),je=I?p:!1,ke=v.useMemo(()=>new Set(xe.map(Oe=>Oe.id)),[xe]),Ae=v.useMemo(()=>[...j].filter(Oe=>ke.has(Oe)).length,[j,ke]),Me=xe.length>0&&Ae===xe.length,ue=Ae>0&&!Me,re=v.useCallback(Oe=>{N(Pe=>{const Ue=new Set(Pe);return Ue.has(Oe)?Ue.delete(Oe):Ue.add(Oe),Ue})},[]),se=v.useCallback(()=>{N(Me?new Set:new Set(xe.map(Oe=>Oe.id)))},[Me,xe]),me=v.useCallback(Oe=>{for(const Pe of j){const Ue=n.find(Ke=>Ke.id===Pe);Ue&&!Ue.tags.includes(Oe)&&r(Pe,[...Ue.tags,Oe])}de(Oe)},[j,n,r,de]),we=v.useCallback(Oe=>{for(const Pe of j){const Ue=n.find(Ke=>Ke.id===Pe);Ue&&Ue.tags.includes(Oe)&&r(Pe,Ue.tags.filter(Ke=>Ke!==Oe))}},[j,n,r]),Ne=v.useCallback(async()=>{for(const Oe of j)await l(Oe);N(new Set),f()},[j,l,f]),Re=v.useCallback(()=>{for(const Oe of j)i(Oe);N(new Set)},[j,i]),Qe=v.useCallback(Oe=>{S(Pe=>Pe===Oe?null:Oe)},[]),Ze=v.useMemo(()=>x?xe.find(Oe=>Oe.id===x)??null:null,[x,xe]),Te=v.useCallback(()=>{if(!x||xe.length===0)return;const Oe=xe.findIndex(Pe=>Pe.id===x);Oe<xe.length-1&&S(xe[Oe+1].id)},[x,xe]),Ce=v.useCallback(()=>{if(!x||xe.length===0)return;const Oe=xe.findIndex(Pe=>Pe.id===x);Oe>0&&S(xe[Oe-1].id)},[x,xe]);return o.jsxs(o.Fragment,{children:[o.jsx(br,{open:L,onOpenChange:D,children:o.jsxs(xr,{ref:R,className:"max-w-lg",children:[o.jsx(wr,{children:o.jsxs(gr,{children:["Analyze ",B==="untagged"?"Untagged":"Selected"," Items"]})}),o.jsx($r,{children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(Dt,{children:"Model"}),o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("div",{className:"w-[160px]",children:o.jsx(Vy,{value:q,onValueChange:Oe=>{const Pe=fi(Oe);M(Pe),V("")},size:"sm",container:R})}),o.jsx("div",{className:"flex-1",children:o.jsx(qy,{llmId:q,value:G,onValueChange:V,size:"sm",container:R})})]})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(Dt,{children:"Items"}),o.jsx(ye,{variant:"ui-sm",className:"text-neutral4",children:B==="untagged"?`${he} untagged item${he!==1?"s":""}`:`${j.size} selected item${j.size!==1?"s":""}`})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(Dt,{children:"Instructions (optional)"}),o.jsx($l,{value:F,onChange:Oe=>z(Oe.target.value),placeholder:"e.g., Focus on tool usage failures, pay attention to whether the agent hallucinated...",rows:3,disabled:k}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"Guide the LLM on what to look for when tagging items"})]})]})}),o.jsxs(Tc,{className:"px-6",children:[o.jsx(ce,{variant:"ghost",onClick:()=>D(!1),disabled:k,children:"Cancel"}),o.jsx(ce,{variant:"default",onClick:ne,disabled:k||!q||!G,children:k?o.jsxs(o.Fragment,{children:[o.jsx(Xt,{className:"mr-2"}),"Analyzing..."]}):"Analyze"})]})]})}),o.jsx(br,{open:Z,onOpenChange:K,children:o.jsxs(xr,{className:"max-w-xl",children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Proposed Tag Assignments"}),te&&o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3 mt-1",children:["Analyzed by ",o.jsx("span",{className:"text-neutral4 font-medium",children:te})]})]}),o.jsx($r,{className:"max-h-[400px] space-y-2 overflow-y-auto",children:$.map((Oe,Pe)=>{const Ue=n.find(tt=>tt.id===Oe.itemId),Ke=typeof Ue?.input=="string"?Ue.input:Ue?.input?JSON.stringify(Ue.input):"";return o.jsxs("div",{className:X("flex items-start gap-2 p-2 rounded-md border border-border1",Oe.accepted?"bg-surface1":"bg-surface1 opacity-50"),children:[o.jsx(zo,{checked:Oe.accepted,onCheckedChange:tt=>{U(Pt=>Pt.map((Ot,St)=>St===Pe?{...Ot,accepted:!!tt}:Ot))},className:"mt-1"}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 block truncate",children:Ke||`Item ${Oe.itemId.slice(0,8)}`}),o.jsx("div",{className:"mt-1 flex flex-wrap gap-1",children:Oe.tags.map((tt,Pt)=>o.jsx(t9t,{tag:tt,onRename:Ot=>U(St=>St.map((pt,Rt)=>Rt===Pe?{...pt,tags:pt.tags.map((rn,Ge)=>Ge===Pt?Ot:rn)}:pt)),onRemove:()=>U(Ot=>Ot.map((St,pt)=>pt===Pe?{...St,tags:St.tags.filter((Rt,rn)=>rn!==Pt)}:St))},`${tt}-${Pt}`))}),Oe.reason&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-1 italic",children:Oe.reason})]})]},Oe.itemId)})}),o.jsxs(Tc,{children:[o.jsx(ce,{variant:"ghost",onClick:()=>K(!1),children:"Cancel"}),o.jsxs(ce,{variant:"default",onClick:fe,disabled:$.filter(Oe=>Oe.accepted).length===0,children:["Accept ",$.filter(Oe=>Oe.accepted).length," proposals"]})]})]})}),o.jsxs(ly,{className:X("p-4",Ze?"grid-cols-[1fr_1fr]":""),children:[o.jsxs(Yr,{children:[o.jsxs(Yr.Toolbar,{children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs(dt,{children:[o.jsx(dt.Trigger,{asChild:!0,children:o.jsxs(ce,{variant:"outline",size:"md",children:[o.jsx(hit,{}),"Filter",be>0&&o.jsx("span",{className:X("ml-0.5 inline-flex items-center justify-center rounded-full bg-accent1/50 text-neutral5 text-ui-sm w-5 h-5"),children:be})]})}),o.jsxs(dt.Content,{align:"start",className:X("min-w-48"),children:[o.jsxs(dt.Sub,{children:[o.jsxs(dt.SubTrigger,{children:["Status",I&&o.jsx("span",{className:X("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(dt.SubContent,{children:[o.jsx(dt.CheckboxItem,{checked:!I,onCheckedChange:()=>{A(!1),S(null)},onSelect:Oe=>Oe.preventDefault(),children:"Review Queue"}),o.jsx(dt.CheckboxItem,{checked:I,onCheckedChange:()=>{A(!0),S(null)},onSelect:Oe=>Oe.preventDefault(),children:"Completed"})]})]}),o.jsxs(dt.Sub,{children:[o.jsxs(dt.SubTrigger,{children:["Tags",C&&o.jsx("span",{className:X("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(dt.SubContent,{children:[o.jsx(dt.CheckboxItem,{checked:!C,onCheckedChange:()=>E(null),onSelect:Oe=>Oe.preventDefault(),children:"All tags"}),he>0&&o.jsx(dt.CheckboxItem,{checked:C==="__untagged__",onCheckedChange:()=>E(C==="__untagged__"?null:"__untagged__"),onSelect:Oe=>Oe.preventDefault(),children:"Untagged"}),le.map(([Oe])=>o.jsx(dt.CheckboxItem,{checked:C===Oe,onCheckedChange:()=>E(C===Oe?null:Oe),onSelect:Pe=>Pe.preventDefault(),children:Oe},Oe))]})]}),be>0&&o.jsxs(o.Fragment,{children:[o.jsx(dt.Separator,{}),o.jsxs(dt.Item,{onSelect:()=>{E(null),A(!1),S(null)},children:[o.jsx(bs,{}),"Clear all filters"]})]})]})]}),be>0&&o.jsxs(ce,{variant:"outline",size:"md",onClick:()=>{E(null),A(!1),S(null)},children:[o.jsx(bs,{}),"Reset"]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[!I&&j.size>0&&o.jsxs(o.Fragment,{children:[o.jsx(e9t,{selectedCount:j.size,vocabulary:ae,onApplyTag:me,onRemoveTag:we,onNewTag:Oe=>me(Oe)}),o.jsxs(dt,{children:[o.jsx(dt.Trigger,{asChild:!0,children:o.jsxs(ce,{disabled:k,children:[k?o.jsx(Xt,{className:"h-4 w-4"}):o.jsx(qe,{size:"sm",children:o.jsx(Na,{})}),"Actions"]})}),o.jsxs(dt.Content,{align:"end",children:[o.jsxs(dt.Item,{onSelect:Ne,children:[o.jsx(qe,{size:"sm",children:o.jsx(lO,{})}),"Complete"]}),o.jsxs(dt.Item,{onSelect:Re,children:[o.jsx(qe,{size:"sm",children:o.jsx(uu,{})}),"Remove"]}),o.jsx(dt.Separator,{}),o.jsxs(dt.Item,{disabled:j.size===0,onSelect:()=>Y("selected"),children:[o.jsx(qe,{size:"sm",children:o.jsx(Eg,{})}),"Analyze selected"]}),o.jsxs(dt.Item,{disabled:he===0,onSelect:()=>Y("untagged"),children:[o.jsx(qe,{size:"sm",children:o.jsx(Eg,{})}),"Analyze untagged"]})]})]})]}),t&&oe.length>0&&!I&&o.jsxs(ce,{variant:"outline",size:"md",onClick:()=>{t(oe.map(Oe=>({input:Oe.input,output:Oe.output})))},children:[o.jsx(qe,{size:"sm",children:o.jsx(nm,{})}),"Create Scorer"]})]})]}),je?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(Xt,{className:"h-4 w-4"})}):xe.length===0?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsxs("div",{className:"px-8 text-center",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 block",children:I?"No completed reviews yet":"No items to review"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-2 block",children:I?"Items marked as complete will appear here for auditing.":"When you identify failures in experiment results, send them here to annotate, cluster, and create scorers from failure patterns."})]})}):o.jsxs(ve,{columns:"auto minmax(15rem,1fr) 10rem 8rem 6rem 6rem",className:"min-w-0",children:[o.jsxs(ve.Top,{hasLeadingCell:!0,children:[I?o.jsx(ve.TopCell,{children:" "}):o.jsx(ve.TopSelectCell,{checked:Me?!0:ue?"indeterminate":!1,onToggle:()=>se(),"aria-label":"Select all"}),o.jsxs(ve.TopCells,{colStart:2,children:[o.jsx(ve.TopCell,{children:"Input"}),o.jsx(ve.TopCell,{children:"Comment"}),o.jsx(ve.TopCell,{children:"Tags"}),o.jsx(ve.TopCell,{children:"Rating"}),o.jsx(ve.TopCell,{children:"Scores"})]})]}),xe.map(Oe=>{const Pe=Oe.scores?Object.entries(Oe.scores):[],Ue=x===Oe.id,Ke=o.jsxs(o.Fragment,{children:[o.jsx(ve.Cell,{height:"compact",className:"text-neutral4 min-w-0",children:o.jsx("span",{className:"block truncate",children:gts(Oe.input,80)})}),o.jsx(ve.Cell,{height:"compact",className:"min-w-0",children:Oe.comment?o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 truncate",children:Oe.comment}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsx(ve.Cell,{height:"compact",className:"min-w-0",children:Oe.tags.length>0?o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 truncate",children:Oe.tags.join(", ")}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsxs(ve.Cell,{height:"compact",children:[Oe.rating==="positive"&&o.jsx(qe,{size:"sm",className:"text-positive1",children:o.jsx(Ube,{})}),Oe.rating==="negative"&&o.jsx(qe,{size:"sm",className:"text-negative1",children:o.jsx(Bbe,{})}),!Oe.rating&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})]}),o.jsx(ve.Cell,{height:"compact",children:Pe.length>0?o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx(qe,{size:"sm",className:"text-neutral3",children:o.jsx(nm,{})}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 font-mono",children:Pe[0][1].toFixed(2)}),Pe.length>1&&o.jsxs(un,{variant:"default",children:["+",Pe.length-1]})]}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})})]});return o.jsxs(ve.RowWrapper,{children:[I?o.jsx(ve.Cell,{height:"compact",className:"justify-items-center px-4",children:o.jsx("div",{role:"img","aria-label":Oe.error?"Error":"Success",title:Oe.error?"Error":"Success",className:X("w-2 h-2 rounded-full",Oe.error?"bg-red-700":"bg-green-600")})}):o.jsx(ve.SelectCell,{checked:j.has(Oe.id),onToggle:()=>re(Oe.id),"aria-label":`Select item ${Oe.id}`}),o.jsx(ve.RowButton,{flushLeft:!0,colStart:2,featured:Ue,onClick:()=>Qe(Oe.id),children:Ke})]},Oe.id)})]})]}),Ze&&o.jsx(J8t,{item:Ze,isCompleted:I,tagVocabulary:ae,onRate:Oe=>s(Ze.id,Oe),onSetTags:Oe=>{r(Ze.id,Oe);for(const Pe of Oe)ae.includes(Pe)||de(Pe)},onComment:Oe=>a(Ze.id,Oe),onRemove:()=>i(Ze.id),onComplete:async()=>{await l(Ze.id),f()},onPrevious:Ce,onNext:Te,onClose:()=>S(null)})]})]})}function DKe({href:e,children:t}){return o.jsxs("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-inherit underline hover:text-white",children:[t,o.jsx(Sa,{className:"size-3"})]})}function nP({value:e,icon:t,label:n,badge:r,disabled:s,disabledReason:a}){const i=o.jsxs(o.Fragment,{children:[o.jsx(qe,{size:"sm",children:t}),o.jsx(ye,{variant:"ui-sm",className:"text-inherit",children:n}),r!==void 0&&r>0&&o.jsx("span",{className:"bg-accent1 ml-1 min-w-[18px] rounded-full px-1.5 py-0 text-center text-xs leading-[18px] font-medium text-white",children:r})]});return s?o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:o.jsx("span",{tabIndex:0,className:"inline-flex",children:o.jsx(Rr,{value:e,disabled:!0,className:"px-3 py-2.5",children:i})})}),a&&o.jsx(Rn,{side:"bottom",children:a})]}):o.jsx(Rr,{value:e,className:"px-3 py-2.5",children:i})}function yts({agentId:e,activeTab:t,showPlayground:n=!1,showObservability:r=!1,reviewBadge:s,rightSlot:a}){const{navigate:i}=yn(),l=n?void 0:o.jsxs("p",{children:["Configure ",o.jsx("code",{children:"@mastra/editor"})," to use the Editor."," ",o.jsx(DKe,{href:"https://mastra.ai/docs/editor/overview",children:"Learn more"})]}),c=r?void 0:o.jsxs("p",{children:["Add ",o.jsx("code",{children:"@mastra/observability"})," to enable this tab."," ",o.jsx(DKe,{href:"https://mastra.ai/docs/observability/overview",children:"Learn more"})]}),u={chat:`/agents/${e}/chat/new`,versions:`/agents/${e}/editor`,evaluate:`/agents/${e}/evaluate`,review:`/agents/${e}/review`,traces:`/agents/${e}/traces`},d=f=>{f!=="none"&&i(u[f])};return o.jsxs("div",{className:"flex min-w-0 items-center gap-2 p-1.5 max-lg:flex-wrap",children:[o.jsx(Dc,{value:t,defaultTab:t,onValueChange:d,className:"min-w-0 flex-1 max-lg:flex-auto",children:o.jsxs(Mc,{variant:"pill-ghost",children:[o.jsx(nP,{value:"chat",icon:o.jsx(dT,{}),label:"Chat"}),o.jsx(nP,{value:"versions",icon:o.jsx(Rbe,{}),label:"Editor",disabled:!n,disabledReason:l}),o.jsx(nP,{value:"evaluate",icon:o.jsx(pit,{}),label:"Evaluate",disabled:!r,disabledReason:c}),o.jsx(nP,{value:"review",icon:o.jsx(UV,{}),label:"Review",badge:s,disabled:!r,disabledReason:c}),o.jsx(nP,{value:"traces",icon:o.jsx(Mu,{}),label:"Traces",disabled:!r,disabledReason:c})]})}),a&&o.jsx("div",{className:"ml-auto flex items-center gap-2",children:a})]})}function bts({requestContextSchema:e}){return o.jsxs(Pf,{children:[o.jsx(Bd,{asChild:!0,children:o.jsxs(ce,{variant:"ghost",size:"sm",type:"button",tooltip:"Run options","data-testid":"agent-top-bar-run-options-trigger",children:[o.jsx(HV,{}),"Run options"]})}),o.jsx(Ud,{align:"end",className:"w-[min(760px,calc(100vw-2rem))] p-0",children:o.jsx(Z8t,{requestContextSchema:e})})]})}const Oz=({label:e,children:t})=>o.jsxs("div",{className:"space-y-2",children:[o.jsx(ye,{as:"p",variant:"ui-md",className:"text-neutral3",children:e}),t]});function xts(e,t){if(!e||O$t(e).toLowerCase()!=="anthropic")return!1;if(!t)return!0;const r=t.toLowerCase();return/[^0-9]4[.-]5/.test(r)||/[^0-9][5-9][.-]\d/.test(r)}function wts({provider:e,modelId:t,settings:n,setSettings:r}){const s=xts(e,t),a=v.useEffectEvent(()=>{r({...n,modelSettings:{...n?.modelSettings,topP:void 0}})}),i=e&&t?`${e}-${t}`:void 0,l=n?.modelSettings?.topP,c=n?.modelSettings?.temperature;return v.useEffect(()=>{s&&i&&(l===void 0||c===void 0||a())},[s,i,l,c]),{hasSamplingRestriction:s}}const Sts=({canEdit:e=!0})=>{const{settings:t,setSettings:n}=SEe(),[r,s]=v.useState(""),[a,i]=v.useState(!1),[l,c]=v.useState(null),u=Yx(),{handleCopy:d}=Vp({text:r}),f=JSON.stringify(t?.modelSettings?.providerOptions??{});v.useEffect(()=>{(async()=>{if(!dD(f)){c("Invalid JSON");return}const y=await sT(f);s(y)})()},[f]);const p=async()=>{if(c(null),!dD(r)){c("Invalid JSON");return}const g=await sT(r);s(g)},h=async()=>{try{c(null);const g=JSON.parse(r);n({...t,modelSettings:{...t?.modelSettings,providerOptions:g}}),i(!0),setTimeout(()=>{i(!1)},1e3)}catch(g){console.error("error",g),c("Invalid JSON")}},m="text-neutral3 hover:text-neutral6";return o.jsx(cc,{children:o.jsxs("div",{className:"@container/advanced",children:[o.jsxs("div",{className:"grid grid-cols-1 gap-2 pb-2 @xs/advanced:grid-cols-2",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"frequency-penalty",children:"Frequency Penalty"}),o.jsx(Cn,{id:"frequency-penalty",type:"number",step:"0.1",min:"-1",max:"1",readOnly:!e,value:t?.modelSettings?.frequencyPenalty??"",onChange:g=>n({...t,modelSettings:{...t?.modelSettings,frequencyPenalty:g.target.value?Number(g.target.value):void 0}})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"presence-penalty",children:"Presence Penalty"}),o.jsx(Cn,{id:"presence-penalty",type:"number",step:"0.1",min:"-1",max:"1",readOnly:!e,value:t?.modelSettings?.presencePenalty??"",onChange:g=>n({...t,modelSettings:{...t?.modelSettings,presencePenalty:g.target.value?Number(g.target.value):void 0}})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"top-k",children:"Top K"}),o.jsx(Cn,{id:"top-k",type:"number",readOnly:!e,value:t?.modelSettings?.topK||"",onChange:g=>n({...t,modelSettings:{...t?.modelSettings,topK:g.target.value?Number(g.target.value):void 0}})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"max-tokens",children:"Max Tokens"}),o.jsx(Cn,{id:"max-tokens",type:"number",readOnly:!e,value:t?.modelSettings?.maxTokens||"",onChange:g=>n({...t,modelSettings:{...t?.modelSettings,maxTokens:g.target.value?Number(g.target.value):void 0}})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"max-steps",children:"Max Steps"}),o.jsx(Cn,{id:"max-steps",type:"number",readOnly:!e,value:t?.modelSettings?.maxSteps||"",onChange:g=>n({...t,modelSettings:{...t?.modelSettings,maxSteps:g.target.value?Number(g.target.value):void 0}})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"max-retries",children:"Max Retries"}),o.jsx(Cn,{id:"max-retries",type:"number",readOnly:!e,value:t?.modelSettings?.maxRetries||"",onChange:g=>n({...t,modelSettings:{...t?.modelSettings,maxRetries:g.target.value?Number(g.target.value):void 0}})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(ye,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"seed",children:"Seed"}),o.jsx(Cn,{id:"seed",type:"number",readOnly:!e,value:t?.modelSettings?.seed||"",onChange:g=>n({...t,modelSettings:{...t?.modelSettings,seed:g.target.value?Number(g.target.value):void 0}})})]})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx(ye,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"provider-options",children:"Provider Options"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:o.jsx("button",{type:"button",onClick:p,className:m,"aria-label":"Format Provider Options",children:o.jsx(qe,{children:o.jsx(Ey,{})})})}),o.jsx(Rn,{children:"Format the Provider Options JSON"})]}),o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:o.jsx("button",{type:"button",onClick:d,className:m,"aria-label":"Copy Provider Options",children:o.jsx(qe,{children:o.jsx(tm,{})})})}),o.jsx(Rn,{children:"Copy Provider Options"})]}),e&&o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:o.jsx("button",{type:"button",onClick:h,className:m,"aria-label":"Save Provider Options",children:o.jsx(qe,{children:a?o.jsx(fa,{}):o.jsx(jd,{})})})}),o.jsx(Rn,{children:a?"Saved":"Save Provider Options"})]})]})]}),o.jsx(Qu,{value:r,onChange:s,theme:u,extensions:[Rp],readOnly:!e,className:"h-dropdown-max-height overflow-scroll rounded-lg border bg-transparent p-2 shadow-sm transition-colors"}),l&&o.jsx(ye,{variant:"ui-md",className:"text-accent2",children:l})]})]})})},kts=({hasMemory:e,hasSubAgents:t,disabled:n})=>{const r=e&&t,s=n||!r,a=o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Np,{value:"network",id:"network",className:"text-neutral6",disabled:s}),o.jsx(Dt,{className:X("text-neutral6 text-ui-md",!r&&"text-neutral3! cursor-not-allowed"),htmlFor:"network",children:"Network"})]});if(r)return a;const i=[];return e||i.push("memory enabled"),t||i.push("at least one sub-agent"),o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:a}),o.jsx(Rn,{children:o.jsxs("p",{children:["Network is not available. Please make sure you have ",i.join(" and "),"."]})})]})},Ots=({supported:e,disabled:t})=>{const n=t||!e,r=o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Np,{value:"streamSubscription",id:"streamSubscription",className:"text-neutral6",disabled:n}),o.jsx(Dt,{className:X("text-neutral6 text-ui-md",!e&&"text-neutral3! cursor-not-allowed"),htmlFor:"streamSubscription",children:"Stream subscription (default)"})]});return e?r:o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:r}),o.jsx(Rn,{children:o.jsx("p",{children:"Stream subscription is not supported for this agent."})})]})},_ts=({agentId:e})=>{const{data:t,isLoading:n}=mc(e),{data:r,isLoading:s}=oC(e),{settings:a,setSettings:i,resetAll:l}=SEe(),{canEdit:c}=ul(),[u,d]=v.useState(!1),[f,p]=v.useState(!1),h=c("agents"),{hasSamplingRestriction:m}=wts({provider:t?.provider,modelId:t?.modelId,settings:a,setSettings:i});if(!n&&!t)return null;const g=!!r?.result,y=!!(t&&Object.keys(t.agents||{}).length>0),b=t?.modelVersion,x=b==="v2"||b==="v3",S=t?.supportsMemory!==!1;let k;t&&(x?a?.modelSettings?.chatWithNetwork?k="network":a?.modelSettings?.chatWithGenerate?k="generate":a?.modelSettings?.chatWithLegacyStream||!S?k="stream":k="streamSubscription":k=a?.modelSettings?.chatWithGenerateLegacy?"generateLegacy":"streamLegacy");const _=m&&(a?.modelSettings?.temperature!==void 0||a?.modelSettings?.topP!==void 0);return o.jsxs(o.Fragment,{children:[o.jsxs(Pf,{open:f,onOpenChange:(C,E)=>{if(!C&&u){E?.cancel?.();return}p(C)},children:[o.jsx(Bd,{asChild:!0,children:o.jsx(ce,{variant:"default",size:"icon-md",type:"button",tooltip:"Model settings","data-testid":"composer-model-settings-trigger",children:o.jsx(CGt,{className:"text-neutral3 hover:text-neutral6 h-5 w-5"})})}),o.jsx(Ud,{align:"start",className:"w-80 p-4",children:n||s?o.jsx(xt,{className:"h-40 w-full","data-testid":"composer-model-settings-skeleton"}):o.jsxs("section",{className:"@container space-y-5",children:[o.jsx(Oz,{label:"Chat Method",children:o.jsxs(bL,{value:k,disabled:!h,onValueChange:C=>h&&i({...a,modelSettings:{...a?.modelSettings,chatWithGenerateLegacy:C==="generateLegacy",chatWithGenerate:C==="generate",chatWithLegacyStream:C==="stream",chatWithNetwork:C==="network"}}),className:"flex flex-col gap-3",children:[!x&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Np,{value:"generateLegacy",id:"generateLegacy",className:"text-neutral6",disabled:!h}),o.jsx(Dt,{className:"text-neutral6 text-ui-md",htmlFor:"generateLegacy",children:"Generate (Legacy)"})]}),x&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Np,{value:"generate",id:"generate",className:"text-neutral6",disabled:!h}),o.jsx(Dt,{className:"text-neutral6 text-ui-md",htmlFor:"generate",children:"Generate"})]}),!x&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Np,{value:"streamLegacy",id:"streamLegacy",className:"text-neutral6",disabled:!h}),o.jsx(Dt,{className:"text-neutral6 text-ui-md",htmlFor:"streamLegacy",children:"Stream (Legacy)"})]}),x&&o.jsx(Ots,{supported:S,disabled:!h}),x&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Np,{value:"stream",id:"stream",className:"text-neutral6",disabled:!h}),o.jsx(Dt,{className:"text-neutral6 text-ui-md",htmlFor:"stream",children:"Stream"})]}),x&&o.jsx(kts,{hasMemory:g,hasSubAgents:y,disabled:!h})]})}),o.jsx(Oz,{label:"Require Tool Approval",children:o.jsx(zo,{checked:a?.modelSettings?.requireToolApproval,disabled:!h,onCheckedChange:C=>h&&i({...a,modelSettings:{...a?.modelSettings,requireToolApproval:C}})})}),_&&o.jsxs("div",{className:"text-neutral3 bg-surface3 flex items-center gap-2 rounded px-3 py-2 text-xs","data-testid":"sampling-restriction-banner",children:[o.jsx(Bx,{className:"h-3.5 w-3.5 shrink-0"}),o.jsx("span",{children:a?.modelSettings?.temperature!==void 0?"Claude 4.5+ models only accept Temperature OR Top P. Clear Temperature to use Top P.":"Claude 4.5+ models only accept Temperature OR Top P. Setting Temperature will clear Top P."})]}),o.jsx(Oz,{label:"Temperature",children:o.jsxs("div",{className:"flex flex-row items-center justify-between gap-2",children:[o.jsx(MU,{value:[a?.modelSettings?.temperature??-.1],max:1,min:-.1,step:.1,disabled:!h,onValueChange:C=>h&&i({...a,modelSettings:{...a?.modelSettings,temperature:C[0]<0?void 0:C[0]}})}),o.jsx(ye,{as:"p",variant:"ui-sm",className:"text-neutral3",children:a?.modelSettings?.temperature??"n/a"})]})}),o.jsx(Oz,{label:"Top P",children:o.jsxs("div",{className:"flex flex-row items-center justify-between gap-2",children:[o.jsx(MU,{disabled:!h,onValueChange:C=>h&&i({...a,modelSettings:{...a?.modelSettings,topP:C[0]<0?void 0:C[0]}}),value:[a?.modelSettings?.topP??-.1],max:1,min:-.1,step:.1}),o.jsx(ye,{as:"p",variant:"ui-sm",className:"text-neutral3",children:a?.modelSettings?.topP??"n/a"})]})}),o.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[o.jsx(ce,{variant:"ghost",size:"sm",type:"button",disabled:!h,onClick:()=>h&&l(),children:"Reset"}),o.jsx(ce,{variant:"default",size:"sm",type:"button",disabled:!h,onClick:()=>d(!0),children:"Advanced Settings"})]})]})})]}),o.jsx(br,{open:u,onOpenChange:d,children:o.jsxs(xr,{className:"sm:max-w-xl",children:[o.jsx(wr,{children:o.jsx(gr,{children:"Advanced model settings"})}),o.jsx($r,{children:o.jsx(Sts,{canEdit:h})})]})})]})},LKe="lk.agent.state",Cts="lk.transcription",Ets="lk.transcription_final";function jts(e,t,n,r,s){return(e.find(l=>l.id===t)?e.map(l=>l.id===t?{...l,text:l.text+r,final:l.final||s}:l):[...e,{id:t,role:n,text:r,final:s}]).slice(-20)}const Tts=({agentId:e,threadId:t,onCallStarted:n})=>{const{baseUrl:r,headers:s}=Kq(),a=Ur(),i=v.useRef(n);v.useEffect(()=>{i.current=n},[n]);const[l,c]=v.useState("idle"),[u,d]=v.useState("initializing"),[f,p]=v.useState([]),h=v.useRef(null),m=v.useRef(null),g=v.useRef(null),y=v.useRef(0),b=v.useRef(null),x=v.useCallback(()=>{t&&a.invalidateQueries({queryKey:["memory","messages",t]}),e&&a.invalidateQueries({queryKey:["memory","threads",e,e]})},[e,a,t]),S=v.useCallback(()=>{g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{g.current=null,x()},600)},[x]),k=v.useCallback(()=>{y.current+=1,b.current?.abort(),b.current=null;const E=h.current;h.current=null,E&&E.disconnect(),g.current&&(clearTimeout(g.current),g.current=null),m.current=null,c("idle"),d("initializing")},[]);v.useEffect(()=>k,[k]);const _=v.useCallback(()=>{k(),p([]),x()},[k,x]),C=v.useCallback(async()=>{if(l!=="idle")return;const E=y.current+=1,j=new AbortController;b.current=j;const N=()=>y.current!==E;c("connecting"),p([]);try{const I=await fetch(`${r}/voice/livekit/connection-details`,{method:"POST",headers:{...s,"content-type":"application/json"},body:JSON.stringify({agentId:e,threadId:t,resourceId:e}),signal:j.signal});if(N())return;if(!I.ok){const F=await I.json().catch(()=>({}));throw new Error(F.error??"LiveKit voice is not configured for this server. Add liveKitConnectionRoute() to server.apiRoutes and run a voice worker.")}const A=await I.json();if(N())return;const{Room:R,RoomEvent:L,Track:D}=await mo(async()=>{const{Room:F,RoomEvent:z,Track:q}=await import("./livekit-client.esm-CKIgC2IJ.js");return{Room:F,RoomEvent:z,Track:q}},[],import.meta.url);if(N())return;const B=new R;h.current=B;const H=new Audio;if(H.autoplay=!0,m.current=H,B.on(L.TrackSubscribed,F=>{F.kind===D.Kind.Audio&&m.current&&F.attach(m.current)}),B.on(L.ParticipantAttributesChanged,(F,z)=>{const q=F[LKe]??z.attributes[LKe];q&&z.identity!==A.participantName&&d(q)}),B.on(L.Disconnected,()=>{h.current===B&&k()}),B.registerTextStreamHandler(Cts,async(F,z)=>{const q=z.identity===A.participantName?"user":"agent",M=F.info.attributes?.[Ets]==="true";for await(const G of F)p(V=>jts(V,F.info.id,q,G,M));q==="agent"&&S()}),await B.connect(A.serverUrl,A.participantToken),N()){B.disconnect(),h.current===B&&(h.current=null);return}if(await B.localParticipant.setMicrophoneEnabled(!0),N()){B.disconnect(),h.current===B&&(h.current=null);return}c("active"),x(),await Promise.resolve(i.current?.()).catch(()=>{})}catch(I){if(j.signal.aborted||N())return;k(),nu.error(I instanceof Error?I.message:"Failed to start the voice call.")}},[e,r,k,s,x,S,l,t]);return{status:l,agentState:u,captions:f,start:()=>{C()},stop:_}},Nts=({voiceCall:e})=>e.status==="idle"?o.jsx(ce,{variant:"default",size:"icon-md",type:"button",tooltip:"Start voice call","data-testid":"voice-call-button",onClick:()=>e.start(),children:o.jsx(QZt,{className:"text-neutral3 hover:text-neutral6 h-5 w-5"})}):e.status==="connecting"?o.jsx(ce,{variant:"default",size:"icon-md",type:"button",tooltip:"Connecting…","data-testid":"voice-call-button",children:o.jsx(ia,{className:"text-neutral3 h-5 w-5 animate-spin"})}):o.jsx(ce,{variant:"default",size:"icon-md",type:"button",tooltip:"End voice call","data-testid":"voice-call-button",onClick:()=>e.stop(),children:o.jsx(ZZt,{className:"h-5 w-5 text-red-500"})}),Its={initializing:"Connecting…",listening:"Listening…",thinking:"Thinking…",speaking:"Speaking…"},FKe=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(e[n]?.role===t)return e[n]},Ats=({voiceCall:e})=>{if(e.status==="idle")return null;const t=FKe(e.captions,"user"),n=FKe(e.captions,"agent"),r=e.status==="connecting"?"Connecting…":Its[e.agentState];return o.jsxs("div",{"data-testid":"voice-call-panel",className:"border-border2/40 bg-surface3 mx-auto mb-2 w-full max-w-3xl rounded-[16px] border px-4 py-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:X("h-2 w-2 rounded-full",e.status==="connecting"&&"bg-neutral3",e.status==="active"&&e.agentState==="speaking"&&"bg-accent1 animate-pulse",e.status==="active"&&e.agentState!=="speaking"&&"bg-green-500")}),o.jsx("span",{className:"text-ui-sm text-neutral4",children:r})]}),t&&o.jsx("p",{className:"text-ui-sm text-neutral3 mt-2 truncate","data-testid":"voice-caption-user",children:t.text}),n&&o.jsx("p",{className:"text-ui-sm text-neutral6 mt-1","data-testid":"voice-caption-agent",children:n.text})]})},Rts=300,Pts=(e,t)=>{const[n,r]=v.useState(!1);return v.useEffect(()=>{if(!e){r(!1);return}const s=setTimeout(()=>r(!0),t);return()=>clearTimeout(s)},[e,t]),n},$ts=e=>e?e.content.parts.some(n=>{if(n.type==="reasoning"||n.type==="text")return"state"in n&&n.state==="streaming";if(n.type==="tool-invocation")return"toolInvocation"in n&&n.toolInvocation.state!=="result";if(n.type==="dynamic-tool"||n.type.startsWith("tool-")){const r="state"in n?n.state:void 0;return r!=="output-available"&&r!=="output-error"}return!1}):!1,Mts=({turns:e})=>e.length===0?null:o.jsx("div",{"data-testid":"thread-rail-layer",className:"thread-rail-layer pointer-events-none absolute inset-y-0 left-4 z-20",children:o.jsx(P6r,{turns:e,className:"pointer-events-auto sticky top-1/2 -translate-y-1/2"})}),Dts=({agentName:e,agentId:t,threadId:n,hasModelList:r,hideModelSwitcher:s,runOptionsSlot:a,refreshThreadList:i})=>{const l=v.useRef(null),c=v.useRef(null);Dwe(l,{enabled:!0});const u=X5r(),{isRunning:d}=DMt(),{requestContext:f}=_s(),{isSpeaking:p,readAloud:h,stop:m}=mFr(t,f),{hasSession:g,viewMode:y}=j4(),b=g&&(y==="collapsed"||y==="expanded"),x=u.length===0,S=u[u.length-1],k=d&&(S?.role!=="assistant"||!$ts(S)),_=Pts(k,Rts),C=v.useMemo(()=>W6r(u),[u]),E=v.useMemo(()=>new Set(C.map(j=>j.messageId)),[C]);return o.jsx(rFr,{children:o.jsx(N6r,{children:o.jsxs("div",{className:"group/thread grid h-full grid-rows-[1fr_auto] overflow-y-auto","data-testid":"thread-wrapper",children:[o.jsxs(eDt,{children:[o.jsx(tDt,{ref:l,className:"h-full overflow-y-scroll",style:{overflowAnchor:"none"},children:x?o.jsx(Lts,{agentName:e}):o.jsxs("div",{"data-testid":"thread-rail-container",className:"thread-rail-container relative min-h-full",children:[o.jsx(Mts,{turns:C}),o.jsxs("div",{ref:c,"data-testid":"thread-message-column",className:"relative mx-auto w-full max-w-3xl px-4 pb-7 group-has-[[data-attachments-row]]/thread:pb-24",children:[o.jsx(gFr,{containerRef:c}),o.jsxs(nDt,{className:"flex flex-col gap-6 py-6",children:[u.map(j=>{const N=aDt(j);return o.jsx(rDt,{messageId:j.id,scrollAnchor:E.has(j.id),children:o.jsx(Nzt,{message:j,hasModelList:r,isSpeaking:p,onReadAloud:h,onStopSpeaking:m})},N)}),_&&o.jsx(kPt,{})]}),!d&&o.jsx(kFr,{})]})]})}),o.jsx("div",{className:"pointer-events-none absolute inset-x-0 bottom-4 z-30 mx-auto flex w-full max-w-3xl px-4",children:o.jsx(sDt,{className:"pointer-events-auto static ms-auto translate-x-0 rtl:translate-x-0"})})]}),b&&t&&n&&o.jsx("div",{className:"mx-auto mb-2 w-full max-w-3xl px-4",children:o.jsx(o$t,{agentName:e})}),o.jsx(yQr,{}),o.jsx(Fts,{agentId:t,threadId:n,hasModelList:r,hideModelSwitcher:s,runOptionsSlot:a,refreshThreadList:i})]})})})},Lts=({agentName:e})=>o.jsxs("div",{className:"flex w-full grow flex-col items-center pt-[15vh]",children:[o.jsx(u_,{name:e||"Agent",size:"lg"}),o.jsx("p",{className:"mt-4 font-medium",children:"How can I help you today?"})]}),Fts=({agentId:e,threadId:t,hasModelList:n,hideModelSwitcher:r,runOptionsSlot:s,refreshThreadList:a})=>{const{threadInput:i,setThreadInput:l}=mMt(t),c=v.useRef(null),u=LMt(),{attachments:d,toCoreUserMessages:f,clear:p}=TZ(),{isRunning:h,canSendWhileStreaming:m,cancelRun:g}=DMt(),[y,b]=v.useState(0),{canExecute:x}=ul(),S=x("agents"),k=Tts({agentId:e,threadId:t,onCallStarted:a}),_=i.trim().length===0&&d.length===0,C=h&&!m,E=async()=>{if(_||C||!S)return;const j=d.length>0?await f():void 0,N=i;l(""),p(),b(I=>I+1),u({message:N,attachments:j})};return o.jsxs("div",{className:"relative",style:{viewTransitionName:"agent-chat-composer"},children:[o.jsx(Ats,{voiceCall:k}),o.jsxs(HMt,{className:"relative px-2 pb-2",onSubmit:j=>{j.preventDefault(),E()},children:[o.jsx(ZMt,{children:o.jsx(hFr,{})}),o.jsxs(WMt,{sendingPulseKey:y,children:[o.jsx(GMt,{ref:c,value:i,autoFocus:!1,placeholder:S?"Enter your message...":"You don't have permission to execute agents",onChange:j=>{l(j.target.value)},onKeyDown:j=>{if(!(j.nativeEvent.isComposing||j.keyCode===229)&&j.key==="Enter"&&!j.shiftKey){if(C)return;j.preventDefault(),j.stopPropagation(),E()}},disabled:!S}),e&&!n&&!r&&o.jsx(YKr,{}),o.jsx(QMt,{children:o.jsx(Bts,{canExecute:S,agentId:e,runOptionsSlot:s,showModelSwitcher:!!(e&&!n&&!r),isEmpty:_,isRunning:h,canSendWhileStreaming:m,onCancel:()=>{g()},onSetText:j=>{l(j)},voiceCall:k})})]})]})]})},zts=({agentId:e,onTranscript:t})=>{const{requestContext:n}=_s(),{start:r,stop:s,isListening:a,transcript:i}=Gxn({agentId:e,requestContext:n});return v.useEffect(()=>{i&&v.startTransition(()=>t(i))},[t,i]),o.jsx(ce,{variant:"default",size:"icon-md",type:"button",tooltip:a?"Stop dictation":"Start dictation",onClick:()=>a?s():r(),children:a?o.jsx(cbe,{}):o.jsx(yZt,{className:"text-neutral3 hover:text-neutral6 h-5 w-5"})})},Bts=({canExecute:e=!0,agentId:t,showModelSwitcher:n,runOptionsSlot:r,isEmpty:s,isRunning:a,canSendWhileStreaming:i,onCancel:l,onSetText:c,voiceCall:u})=>o.jsxs(o.Fragment,{children:[(n&&t||r)&&o.jsxs("div",{className:"flex max-w-full shrink-0 items-center gap-1.5",children:[n&&t&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"bg-surface3 border-border1 duration-normal focus-within:border-border2 rounded-full border transition-colors",children:o.jsx(QKr,{})}),o.jsx(_ts,{agentId:t})]}),r]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[o.jsxs(Mr,{spacing:"close",children:[e&&o.jsx(sFr,{}),e&&o.jsx(zts,{agentId:t,onTranscript:c}),e&&t&&u&&o.jsx(Nts,{voiceCall:u})]}),o.jsx(Uts,{canExecute:e,isEmpty:s,isRunning:a,canSendWhileStreaming:i,onCancel:l})]})]}),Uts=({canExecute:e=!0,isEmpty:t,isRunning:n,canSendWhileStreaming:r,onCancel:s})=>n&&!r?o.jsx(ce,{variant:"default",size:"icon-md",type:"button",tooltip:"Cancel",onClick:s,children:o.jsx(cbe,{})}):o.jsxs(o.Fragment,{children:[o.jsx(ce,{type:"submit",variant:"default",size:"icon-md",tooltip:e?"Send":"No permission to execute",className:"border-border1 bg-surface5 rounded-full border",disabled:!e||t,children:o.jsx(jD,{className:"text-neutral3 hover:text-neutral6 h-6 w-6"})}),n&&o.jsx(ce,{variant:"default",size:"icon-md",type:"button",tooltip:"Cancel",onClick:s,children:o.jsx(cbe,{})})]}),cbe=()=>o.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-neutral3 hover:text-neutral6",children:[o.jsx("circle",{cx:"12",cy:"12",r:"10"}),o.jsx("rect",{width:"6",height:"6",x:"9",y:"9",rx:"1"})]}),MNe=({agentId:e,agentName:t,threadId:n,memory:r,refreshThreadList:s,modelVersion:a,agentVersionId:i,supportsMemory:l,modelList:c,messageId:u,isNewThread:d,hideModelSwitcher:f,runOptionsSlot:p})=>{const{settings:h}=SEe(),m=zl(),{data:g,isLoading:y}=HH({agentId:e,threadId:d?void 0:n,memory:r??!1});v.useEffect(()=>{u&&g&&!y&&setTimeout(()=>{const S=document.querySelector(`[data-message-id="${u}"]`);S&&(S.scrollIntoView({behavior:"smooth",block:"center"}),S.classList.add("bg-surface4"),setTimeout(()=>{S.classList.remove("bg-surface4")},2e3))},100)},[u,g,y]);const b=v.useRef({threadId:n,messages:[]});b.current.threadId!==n&&(b.current={threadId:n,messages:[]});const x=g?.messages??b.current.messages;return o.jsx(g6r,{agentId:e,agentName:t,modelVersion:a,agentVersionId:i,supportsMemory:l,threadId:n,initialMessages:x,refreshThreadList:s,settings:h,requestContext:m,children:o.jsx(Dts,{agentName:t??"",agentId:e,threadId:n,hasModelList:!!c,hideModelSwitcher:f,refreshThreadList:s,runOptionsSlot:p})})};function Vts({agentId:e,view:t}){const n=qs(),r=qo(),{data:s}=mc(e),{canCreateAgent:a}=ARt(),{Link:i,paths:l}=yn(),c=(window.MASTRA_STUDIO_BASE_PATH??"").replace(/\/$/,""),u=`${window.location.origin}${c}/agents/${encodeURIComponent(e)}/session`,{handleCopy:d,isCopied:f}=Vp({text:u,copyMessage:"Session URL copied to clipboard!"}),p=s?.source==="stored",h=l.cmsAgentEditLink(e),m=a&&p&&!!h,g=()=>{if(t==="chat"){n(`/agents/${e}/settings`,{state:{from:`${r.pathname}${r.search}`},viewTransition:!0});return}const y=r.state?.from;n(y??`/agents/${e}/chat/new`,{viewTransition:!0})};return o.jsx(cc,{children:o.jsxs("div",{className:"flex items-center justify-between gap-2 pr-3 max-lg:py-2",style:{viewTransitionName:"agent-view-header"},children:[o.jsx("div",{className:"min-w-0 flex-1 max-lg:hidden",children:o.jsx(ZKr,{agentId:e})}),o.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-2",children:[m&&o.jsxs(ce,{variant:"outline",size:"sm",as:i,to:h,children:[o.jsx(qe,{size:"sm",children:o.jsx(rm,{})}),"Edit"]}),o.jsx(ce,{variant:"default",type:"button",onClick:d,tooltip:"Copy session URL to share with your team","data-testid":"agent-entity-header-share",children:f?o.jsx(fa,{className:"text-neutral3 h-4 w-4"}):o.jsx(yit,{className:"text-neutral3 hover:text-neutral6 h-4 w-4"})}),o.jsx(ce,{variant:"default",type:"button",onClick:g,"data-testid":"agent-view-header-toggle",children:t==="chat"?o.jsxs(o.Fragment,{children:[o.jsx(WV,{className:"text-neutral3 h-4 w-4"})," Settings"]}):o.jsxs(o.Fragment,{children:[o.jsx(bs,{className:"text-neutral3 h-4 w-4"})," Close"]})})]})]})})}function qts({agentId:e,view:t,leftSlot:n,leftDrawerLabel:r,browserOverlay:s,children:a}){return o.jsx(_Ne,{agentId:e,leftDrawerLabel:r,leftSlot:n,browserOverlay:s,children:o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[o.jsx(Vts,{agentId:e,view:t}),a]})})}function Hts({agentId:e,view:t}){return o.jsx(_Ne,{agentId:e,leftDrawerLabel:"Open threads and memory",leftSlot:o.jsx(n9t,{}),children:o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_1fr]","data-testid":"agent-route-skeleton","aria-busy":"true",children:[o.jsx(Wts,{}),o.jsx("div",{className:"min-h-0 overflow-hidden",children:t==="settings"?o.jsx(Zts,{}):o.jsx(r9t,{})})]})})}function Wts(){return o.jsxs("div",{className:"flex items-center justify-between gap-2 pr-3 max-lg:py-2",children:[o.jsx("div",{className:"min-w-0 flex-1 max-lg:hidden",children:o.jsxs("div",{className:"flex min-w-0 items-center gap-2 p-3",children:[o.jsx(xt,{className:"size-7 shrink-0 rounded-full"}),o.jsx(xt,{className:"h-4 w-36"})]})}),o.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-2",children:[o.jsx(xt,{className:"h-9 w-9 rounded-lg"}),o.jsx(xt,{className:"h-9 w-24 rounded-lg"})]})]})}function n9t(){return o.jsxs(MEe,{children:[o.jsx("div",{className:"min-h-0 flex-1 p-1","data-testid":"agent-route-sidebar-skeleton",children:o.jsxs("div",{className:"flex h-full w-full flex-col",children:[o.jsxs(rP,{children:[o.jsx(xt,{className:"h-4 w-4 shrink-0 rounded"}),o.jsx(xt,{className:"h-3 w-16"})]}),o.jsx("hr",{"aria-hidden":"true",className:"bg-border1/40 -mx-1 my-1 h-px border-0"}),o.jsxs("div",{className:"flex flex-col gap-px",children:[o.jsx(rP,{children:o.jsx(xt,{className:"h-3 w-32"})}),o.jsx(rP,{children:o.jsx(xt,{className:"h-3 w-24"})}),o.jsx(rP,{children:o.jsx(xt,{className:"h-3 w-36"})}),o.jsx(rP,{children:o.jsx(xt,{className:"h-3 w-28"})})]})]})}),o.jsxs("div",{className:"rounded-studio-panel border-border1/40 bg-surface4 m-2 border px-3 py-2.5",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[o.jsx(xt,{className:"h-4 w-4 shrink-0 rounded"}),o.jsx(xt,{className:"h-4 w-20"})]}),o.jsx(xt,{className:"h-4 w-4 shrink-0 rounded"})]}),o.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[o.jsx(xt,{className:"h-3 w-20 rounded-full"}),o.jsx(xt,{className:"h-3 w-24 rounded-full"})]})]})]})}function rP({children:e}){return o.jsx("div",{className:"flex h-9 w-full min-w-0 items-center gap-2 rounded-xl px-3",children:e})}function r9t(){return o.jsx("div",{className:"grid h-full min-h-0 w-full overflow-hidden px-4 py-6 md:px-10",children:o.jsxs("div",{className:"mx-auto grid h-full min-h-0 w-full max-w-[80ch] grid-rows-[1fr_auto]",children:[o.jsxs("div",{className:"min-h-0 space-y-4 overflow-hidden pt-6",children:[o.jsx("div",{className:"flex justify-start",children:o.jsx(xt,{className:"h-10 w-2/3 rounded-2xl"})}),o.jsx("div",{className:"flex justify-end",children:o.jsx(xt,{className:"h-12 w-3/5 rounded-2xl"})}),o.jsx("div",{className:"flex justify-start",children:o.jsxs("div",{className:"w-4/5 space-y-2",children:[o.jsx(xt,{className:"h-4 w-full rounded-full"}),o.jsx(xt,{className:"h-4 w-5/6 rounded-full"}),o.jsx(xt,{className:"h-4 w-2/3 rounded-full"})]})})]}),o.jsxs("div",{className:"border-border1 bg-surface2 rounded-3xl border px-3 py-2.5",children:[o.jsx(xt,{className:"h-5 w-1/2 rounded-full"}),o.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[o.jsx(xt,{className:"h-8 w-24 rounded-full"}),o.jsx(xt,{className:"h-8 w-8 rounded-full"})]})]})]})})}function Zts(){return o.jsxs("div",{className:"h-full w-full min-w-0","data-testid":"agent-settings-skeleton","aria-busy":"true",children:[o.jsx("div",{className:"sticky top-0 z-10 px-3 py-1.5",children:o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(xt,{className:"h-9 w-24 rounded-full"}),o.jsx(xt,{className:"h-9 w-24 rounded-full"}),o.jsx(xt,{className:"h-9 w-28 rounded-full"})]})}),o.jsxs("div",{className:"space-y-4 p-4",children:[o.jsx(xt,{className:"h-28 w-full rounded-lg"}),o.jsx(xt,{className:"h-36 w-full rounded-lg"}),o.jsx(xt,{className:"h-24 w-5/6 rounded-lg"})]})]})}const zKe="1fr auto auto",Gts=({agentId:e})=>{const{data:t,isLoading:n}=sZ(),[r,s]=v.useState("");return!n&&(!t||t.length===0)?o.jsx(lr,{children:o.jsx(ye,{variant:"ui-sm",className:"text-neutral6",children:"No channel platforms configured."})}):o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx($f,{onSearch:s,label:"Filter channels",placeholder:"Filter by platform name"})})}),o.jsx(Qts,{platforms:t??[],isLoading:n,agentId:e,search:r})]})};function Qts({platforms:e,isLoading:t,agentId:n,search:r}){const s=v.useMemo(()=>{const a=r.toLowerCase();return e.filter(i=>i.name.toLowerCase().includes(a))},[e,r]);return t?o.jsx(ol,{columns:zKe}):o.jsxs(ve,{columns:zKe,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{className:"",children:"Platform"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Status"}),o.jsx(ve.TopCell,{className:"",children:""})]}),s.length===0&&r?o.jsx(ve.NoMatch,{message:"No channels match your search"}):null,s.map(a=>o.jsx(Yts,{platform:a,agentId:n},a.id))]})}function Yts({platform:e,agentId:t}){const{data:n,isLoading:r}=JRt(e.id,t),{connect:s,isConnecting:a}=wCe(e.id),{mutate:i,isPending:l}=ePt(e.id),c=n?.find(f=>f.status==="active"),u=()=>{s(t)},d=()=>{i(t,{onError:f=>{Le.error(f.body?.error||f.message||"Failed to disconnect channel")}})};return o.jsxs(ve.RowStatic,{children:[o.jsx(ve.Cell,{className:"text-neutral4 text-left",children:o.jsxs("span",{className:"flex min-w-0 items-center gap-3",children:[o.jsx(QCe,{platform:e.id,className:"h-5 w-5 shrink-0"}),o.jsxs("span",{className:"flex min-w-0 flex-col",children:[o.jsx("span",{className:"truncate",children:e.name}),c?o.jsx(ye,{variant:"ui-xs",className:"text-neutral5 truncate",children:c.displayName||"Workspace"}):null]})]})}),o.jsx(ve.Cell,{className:"flex justify-end",children:r?null:c?o.jsx(bg,{variant:"success",size:"sm",children:"Connected"}):e.isConfigured?null:o.jsx(bg,{variant:"warning",size:"sm",children:"Not configured"})}),o.jsx(ve.Cell,{className:"justify-end text-right",children:r?null:c?o.jsx("button",{type:"button",onClick:d,disabled:l,className:"text-neutral5 hover:text-accent2 shrink-0 text-[11px] transition-colors disabled:opacity-50",children:l?"Removing...":"Remove"}):e.isConfigured?o.jsx(ce,{size:"sm",variant:"default",onClick:u,disabled:a,children:a?"Connecting...":"Connect"}):null})]})}const BKe=e=>e===void 0?"Default":typeof e=="number"?`${e.toLocaleString()} tokens`:`${e.min.toLocaleString()}-${e.max.toLocaleString()} tokens`,Kts={success:"bg-green-500/20 text-green-400",info:"bg-blue-500/20 text-blue-400",warning:"bg-yellow-500/20 text-yellow-400"};function Xts({value:e,badge:t}){return typeof e=="boolean"?o.jsx("span",{className:X("text-xs font-medium px-2 py-0.5 rounded",e?t==="info"?"dark:bg-blue-500/20 dark:text-blue-400 bg-blue-500/10 text-blue-600":"dark:bg-green-500/20 dark:text-green-400 bg-green-500/10 text-green-600":"dark:bg-red-500/20 dark:text-red-400 bg-red-500/10 text-red-600"),children:e?"Yes":"No"}):t?o.jsx("span",{className:X("text-xs font-medium px-2 py-0.5 rounded",Kts[t]),children:e}):o.jsx("span",{className:"text-neutral3 text-xs",children:e})}const Jts=({agentId:e})=>{const{data:t,isLoading:n}=lC(e),[r,s]=v.useState(new Set(["General","Semantic Recall"])),a=t?.config,i=v.useMemo(()=>{if(!a)return[];const c=!!a,u=[{title:"General",items:[{label:"Memory Enabled",value:c,badge:c?"success":void 0},{label:"Last Messages",value:a.lastMessages||0},{label:"Auto-generate Titles",value:!!a.generateTitle,badge:a.generateTitle?"info":void 0}]}];if(a.semanticRecall){const h=!!a.semanticRecall,m=typeof a.semanticRecall=="object"?a.semanticRecall:{};u.push({title:"Semantic Recall",items:[{label:"Enabled",value:h,badge:h?"success":void 0},...h?[{label:"Scope",value:m.scope||"resource"},{label:"Top K Results",value:m.topK||4},{label:"Message Range",value:typeof m.messageRange=="object"?`${m.messageRange.before||1} before, ${m.messageRange.after||1} after`:m.messageRange!==void 0?`${m.messageRange} before, ${m.messageRange} after`:"1 before, 1 after"}]:[]]})}const d=a.observationalMemory,f=d!==null&&typeof d=="object";if(d===!0||f&&d.enabled!==!1){const h=f?d.observationModel||d.model||d.observation?.model:void 0,m=f?d.reflectionModel||d.model||d.reflection?.model:void 0;u.push({title:"Observational Memory",items:[{label:"Enabled",value:!0,badge:"success"},{label:"Scope",value:f&&d.scope||"thread"},{label:"Message Tokens",value:BKe(f?d.observation?.messageTokens:void 0)},{label:"Observation Tokens",value:BKe(f?d.reflection?.observationTokens:void 0)},...h?[{label:"Observation Model",value:String(h)}]:[],...m?[{label:"Reflection Model",value:String(m)}]:[]]})}return u},[a]),l=c=>{const u=new Set(r);u.has(c)?u.delete(c):u.add(c),s(u)};return n?o.jsx("div",{className:"p-4",children:o.jsx(xt,{className:"h-32 w-full"})}):!a||i.length===0?o.jsxs("div",{className:"p-4",children:[o.jsx("h3",{className:"text-neutral5 mb-3 text-sm font-medium",children:"Memory Configuration"}),o.jsx("p",{className:"text-neutral3 text-xs",children:"No memory configuration available"})]}):o.jsxs("div",{className:"p-4",children:[o.jsx("h3",{className:"text-neutral5 mb-3 text-sm font-medium",children:"Memory Configuration"}),o.jsx("div",{className:"space-y-2",children:i.map(c=>o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border",children:[o.jsxs("button",{type:"button",onClick:()=>l(c.title),className:"hover:bg-surface4 flex w-full items-center justify-between rounded-t-lg px-3 py-2 transition-colors",children:[o.jsx("span",{className:"text-neutral5 text-xs font-medium",children:c.title}),r.has(c.title)?o.jsx(Na,{className:"text-neutral3 h-3 w-3"}):o.jsx(pa,{className:"text-neutral3 h-3 w-3"})]}),r.has(c.title)&&o.jsx("div",{className:"space-y-1 px-3 pb-2",children:c.items.map(u=>o.jsxs("div",{className:"flex items-center justify-between py-1",children:[o.jsx("span",{className:"text-neutral3 text-xs",children:u.label}),o.jsx(Xts,{value:u.value??"",badge:u.badge})]},`${c.title}-${u.label}`))})]},c.title))})]})},ens=(e,t)=>e==="memory"?"memory":e==="channels"&&t?"channels":"overview";function tns({agentId:e}){const[t,n]=Ri(),{data:r}=sZ(),s=!!r?.length,a=ens(t.get("tab"),s),i=l=>{n(l==="overview"?{}:{tab:l},{replace:!0})};return o.jsx("div",{className:"h-full w-full min-w-0","data-testid":"agent-settings-view",style:{viewTransitionName:"agent-settings-view"},children:o.jsx(Br,{className:"h-full w-full",viewPortClassName:"h-full",mask:{top:!1},children:o.jsxs(Dc,{value:a,defaultTab:"overview",onValueChange:i,children:[o.jsx("div",{className:"sticky top-0 z-10 px-3 py-1.5",children:o.jsxs(Mc,{variant:"pill-ghost",children:[o.jsxs(Rr,{value:"overview",children:[o.jsx(qe,{size:"sm",children:o.jsx(HV,{})}),"General"]}),o.jsxs(Rr,{value:"memory",children:[o.jsx(qe,{size:"sm",children:o.jsx(Mv,{})}),"Memory"]}),s&&o.jsxs(Rr,{value:"channels",children:[o.jsx(qe,{size:"sm",children:o.jsx(kit,{})}),"Channels"]})]})}),o.jsx(Xr,{value:"overview",children:o.jsx(LKr,{agentId:e})}),o.jsx(Xr,{value:"memory",children:o.jsx(Jts,{agentId:e})}),s&&o.jsx(Xr,{value:"channels",children:o.jsx(Gts,{agentId:e})})]})})})}const nns=typeof document<"u"&&"startViewTransition"in document;function uae({view:e="chat"}){const{agentId:t,threadId:n}=Sr(),[r]=Ri(),{data:s,isLoading:a,error:i}=mc(t),{data:l}=oC(t),c=qs(),u=e==="settings",d=n==="new",f=v.useMemo(()=>xo(),[n]),p=!!l?.result,{data:h,isLoading:m,refetch:g}=Y$t({agentId:t,isMemoryEnabled:p,resourceId:t}),y=v.useMemo(()=>(h||[]).map(_=>({..._,createdAt:new Date(_.createdAt),updatedAt:new Date(_.updatedAt)})),[h]);v.useEffect(()=>{u||n||c(`/agents/${t}/chat/new`)},[u,n,t,c]);const b=r.get("messageId")??void 0,x=v.useMemo(()=>RNe(s),[s]);if(i&&ys(i))return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Hs,{})});if(i&&xs(i))return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ms,{resource:"agents"})});if(a)return o.jsx(Hts,{agentId:t,view:e});if(!s)return o.jsx("div",{className:"py-4 text-center",children:"Agent not found"});if(!u&&!n)return null;const S=d?f:n??f,k=async()=>{await g(),d&&c(`/agents/${t}/chat/${f}`)};return o.jsx(wEe,{agentId:t,defaultSettings:x,children:o.jsx(h3,{children:o.jsx(sMt,{agentId:t,threadId:S,resourceId:t,children:o.jsx(fZ,{children:o.jsx(pZ,{agentId:t,threadId:S,enabled:!!s?.browserTools?.length,children:o.jsx(TEe,{children:o.jsx(oMt,{children:o.jsx(pLr,{children:o.jsx(kEe,{children:o.jsx(qts,{agentId:t,view:e,leftDrawerLabel:"Open threads and memory",leftSlot:m?o.jsx(n9t,{}):o.jsx(K5r,{agentId:t,threadId:S,threads:y}),browserOverlay:o.jsx(JCe,{}),children:o.jsx("div",{className:nns?"min-h-0 overflow-hidden":"agent-view-enter min-h-0 overflow-hidden",children:u?o.jsx(tns,{agentId:t}):o.jsx(MNe,{agentId:t,agentName:s?.name,modelVersion:s?.modelVersion,supportsMemory:s?.supportsMemory,threadId:S,memory:p,refreshThreadList:k,modelList:s?.modelList,messageId:b,isNewThread:d,runOptionsSlot:o.jsx(G8t,{requestContextSchema:s?.requestContextSchema})},S)},e)})},`${t}-${S}`)},`memory-timeline-${t}-${S}`)})})},`session-${t}-${S}`)},`browser-${t}-${S}`)})})})}function s9t({config:e,redirectUri:t,className:n,loginUrl:r="/login"}){const{mutate:s,isPending:a}=hPt();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(ce,{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(r,window.location.origin);t&&l.searchParams.set("redirect",t),window.location.href=l.toString()};return o.jsx(ce,{onClick:i,className:n,children:"Sign in"})}function UKe({user:e,size:t="sm"}){if(!e)return null;const n=e.name||e.email||"User";return o.jsx(u_,{src:e.avatarUrl,name:n,size:t})}function rns({user:e}){const[t,n]=v.useState(!1),{mutate:r,isPending:s}=Ujr(),{data:a}=uc(),{isImpersonating:i,impersonatedRole:l,startImpersonation:c,stopImpersonation:u,isSwitching:d}=Hq();if(!e)return null;const f=()=>{r(void 0,{onSuccess:m=>{m.redirectTo?window.location.href=m.redirectTo:window.location.reload()}})},p=a&&wm(a)?a.availableRoles:void 0,h=e.name||e.email||"User";return o.jsxs(Pf,{open:t,onOpenChange:n,children:[o.jsx(Bd,{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(UKe,{user:e,size:"sm"})})}),o.jsxs(Ud,{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(UKe,{user:e,size:"md"}),o.jsxs("div",{className:"flex flex-col overflow-hidden",children:[o.jsx(ye,{variant:"ui-md",className:"truncate font-medium",children:h}),e.email&&o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 truncate",children:e.email})]})]})}),p&&p.length>0&&o.jsxs("div",{className:"border-border1 border-b p-2",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 px-2 py-1 tracking-wider uppercase",children:"Preview as role"}),p.map(m=>{const g=i&&l?.id===m.id;return o.jsxs("button",{type:"button",disabled:d,onClick:()=>{g?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 ${g?"bg-surface2":"hover:bg-surface2"} ${d?"cursor-not-allowed opacity-50":""}`,children:[d&&o.jsx(ia,{className:"h-3.5 w-3.5 animate-spin"}),o.jsx("span",{className:"flex-1 capitalize",children:m.name}),g&&o.jsx(bs,{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(ce,{as:ei,to:"/settings",variant:"ghost",className:"w-full justify-start",onClick:()=>n(!1),children:[o.jsx(p9,{className:"h-4 w-4"}),"Settings"]}),o.jsx(ce,{variant:"ghost",onClick:f,disabled:s,className:"w-full justify-start",children:s?"Signing out...":"Sign out"})]})]})]})}function OD({className:e}){const{data:t,isLoading:n,error:r}=uc();return n||r||!t?.enabled?null:wm(t)?o.jsx(rns,{user:t.user}):o.jsx(s9t,{config:t.login,redirectUri:typeof window<"u"?window.location.href:void 0,className:e})}const _z="__custom__",a9t=()=>{const e=Wyt(),{requestContext:t,setRequestContext:n}=_s(),r=v.useMemo(()=>{if(!e)return _z;const a=JSON.stringify(t??{});for(const[i,l]of Object.entries(e))if(JSON.stringify(l)===a)return i;return _z},[e,t]),s=a=>{if(a===_z){n({});return}if(!e)return;const i=e[a];i&&n(i)};return o.jsxs(Iwe,{children:[o.jsxs(jgt,{children:[o.jsx(Xh,{className:"h-5 w-8 shrink-0"}),"Mastra Studio",o.jsx(OD,{})]}),e&&Object.keys(e).length>0&&o.jsx(QTn,{children:o.jsxs(oa,{value:r,onValueChange:s,children:[o.jsx(ca,{size:"sm",className:"w-[200px]",children:o.jsx(la,{placeholder:"Select a preset..."})}),o.jsxs(ua,{children:[o.jsx(Ar,{value:_z,children:"Custom"}),Object.keys(e).map(a=>o.jsx(Ar,{value:a,children:a},a))]})]})})]})};function VKe(){const{agentId:e,threadId:t}=Sr(),[n]=Ri(),{data:r,isLoading:s}=mc(e),{data:a}=oC(e),i=qs(),l=t==="new",c=v.useMemo(()=>xo(),[t]),u=!!a?.result,{refetch:d}=Y$t({resourceId:e,agentId:e,isMemoryEnabled:u});v.useEffect(()=>{u&&(t||i(`/agents/${e}/session/new`))},[u,t,e,i]);const f=n.get("messageId")??void 0,p=v.useMemo(()=>RNe(r),[r]);if(s)return o.jsx(sns,{});if(!r)return o.jsx("div",{className:"py-4 text-center",children:"Agent not found"});const h=l?c:t??c,m=async()=>{await d(),l&&i(`/agents/${e}/session/${c}`)};return o.jsx(Pwe,{entityId:e,entityType:"agent",children:o.jsx(wEe,{agentId:e,defaultSettings:p,children:o.jsx(h3,{children:o.jsx(sMt,{agentId:e,threadId:h,resourceId:e,children:o.jsx(fZ,{children:o.jsx(pZ,{agentId:e,threadId:h,enabled:!!r?.browserTools?.length,children:o.jsx(TEe,{children:o.jsx(oMt,{children:o.jsx(kEe,{children:o.jsxs(ds,{children:[o.jsx(a9t,{}),o.jsx("div",{className:"relative grid h-full overflow-y-auto pt-6",children:o.jsx(MNe,{agentId:e,agentName:r?.name,modelVersion:r?.modelVersion,supportsMemory:r?.supportsMemory,threadId:h,memory:u,refreshThreadList:m,modelList:r?.modelList,messageId:f,isNewThread:l,hideModelSwitcher:!0},h)})]})})})})},`session-${e}-${h}`)},`browser-${e}-${h}`)})})})})}const sns=()=>o.jsxs(ds,{children:[o.jsx(a9t,{}),o.jsx("div",{className:"relative grid h-full overflow-y-auto pt-6","data-testid":"agent-session-skeleton","aria-busy":"true",children:o.jsx(r9t,{})})]}),DNe=()=>{const{data:e}=R4();return e?.editorSource==="code"?"code":"db"};function ans(){const{agentId:e}=Sr(),{navigate:t}=yn(),{data:n,isLoading:r,error:s}=mc(e),{data:a}=K1({agentId:e,params:{orderBy:{direction:"DESC"}}}),i=(a?.versions?.length??0)>0,{data:l,isLoading:c}=b4(e,{status:"draft",enabled:i}),u=DNe(),d=n?.source==="code",f=d&&u==="code",p=r||i&&c,h=v.useMemo(()=>l||(n?ANe(n):{}),[l,n]),{form:m,handlePublish:g,handleSaveDraft:y,isSubmitting:b,isSavingDraft:x}=DG({mode:"edit",agentId:e??"",dataSource:h,isCodeAgentOverride:d,hasStoredOverride:d&&!!l,editorConfig:n?.editor,onSuccess:()=>{}}),[S,k]=v.useState(()=>{const _=sessionStorage.getItem(`pending-scorer-items-${e}`);if(_){sessionStorage.removeItem(`pending-scorer-items-${e}`);try{return JSON.parse(_)}catch{return null}}return null});return s&&ys(s)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Hs,{})}):s&&xs(s)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ms,{resource:"agents"})}):p?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Xt,{className:"h-6 w-6"})}):n?o.jsx(_Ee,{form:m,mode:"edit",agentId:e,isSubmitting:b,isSavingDraft:x,handlePublish:g,handleSaveDraft:y,isCodeAgentOverride:d,isCodeSourceAgent:f,readOnly:!1,children:o.jsx(dts,{agentId:e,onSwitchToReview:()=>t(`/agents/${e}/review`),pendingScorerItems:S,onPendingScorerItemsConsumed:()=>k(null)})}):o.jsx("div",{className:"py-4 text-center",children:"Agent not found"})}const zG=()=>{const e=window.MASTRA_CLOUD_API_ENDPOINT,t=window.MASTRA_PLATFORM_PROJECT_ID,n=window.MASTRA_ORGANIZATION_ID,r=window.MASTRA_PLATFORM_OBSERVABILITY_ENDPOINT;return{isMastraPlatform:!!e,mastraPlatformEndpoint:e,mastraPlatformApiEndpoint:e,mastraPlatformProjectId:t,mastraOrganizationId:n,platformObservabilityEndpoint:r}};function ins(){const{agentId:e}=Sr(),[t,n]=v.useState(null),{data:r,isLoading:s,error:a}=mc(e),{data:i}=oC(e),l=DNe(),{isMastraPlatform:c,mastraPlatformApiEndpoint:u,mastraPlatformProjectId:d}=zG(),{data:f}=K1({agentId:e,params:{orderBy:{direction:"DESC"}}}),p=(f?.versions?.length??0)>0,{data:h,isLoading:m}=b4(e,{status:"draft",enabled:p}),g=r?.source==="code",y=g&&l==="code",b=!g||r?.editor!==!1,x=y&&b,S=x&&c&&!!u&&!!d,k=S?"Open a pull request for these JSON changes":void 0,_=s||p&&m,C=!!i?.result,{data:E}=V$t({agentId:e??"",versionId:t??""}),j=h?.activeVersionId,N=f?.versions?.[0],I=!!(N&&N.id!==j),A=!!t&&!!E,R=A&&t!==N?.id,L=v.useMemo(()=>A&&E?E:h||(r?ANe(r):{}),[A,E,h,r]),{form:D,handlePublish:B,handleSaveDraft:H,handleDownloadJson:F,handleOpenPr:z,isSubmitting:q,isSavingDraft:M,isDirty:G}=DG({mode:"edit",agentId:e??"",dataSource:L,isCodeAgentOverride:g,hasStoredOverride:g&&!!h,editorConfig:r?.editor,saveSuccessMessage:y?"Saved to filesystem":void 0,onSuccess:()=>{}}),V=v.useCallback(async()=>{R&&t?await B(t):await B()},[B,R,t]),$=v.useCallback(async()=>{!u||!d||await z({platformApiEndpoint:u,projectId:d})},[z,u,d]),U=v.useCallback(Z=>{Z===N?.id?n(null):n(Z)},[N?.id]);return a&&ys(a)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Hs,{})}):a&&xs(a)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ms,{resource:"agents"})}):_?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Xt,{className:"h-6 w-6"})}):r?o.jsx(_Ee,{form:D,mode:"edit",agentId:e,isSubmitting:q,isSavingDraft:M,handlePublish:B,handleSaveDraft:H,isCodeAgentOverride:g,isCodeSourceAgent:y,readOnly:R||!b,editorConfig:r?.editor,children:o.jsx(jes,{agentId:e,agentName:r?.name,modelVersion:r?.modelVersion,agentVersionId:R?t??void 0:void 0,hasMemory:C,activeVersionId:j,selectedVersionId:t??void 0,latestVersionId:N?.id,onVersionSelect:U,isDirty:G,isSavingDraft:M,isPublishing:q,hasDraft:I,readOnly:R||!b,isCodeSourceAgent:y,showCodeModeActions:x,canOpenPr:S,openPrTitle:k,onSaveDraft:H,onPublish:V,onDownloadJson:F,onOpenPr:$,isViewingPreviousVersion:R})}):o.jsx("div",{className:"py-4 text-center",children:"Agent not found"})}function ons(){const{agentId:e}=Sr(),{navigate:t}=yn(),{data:n,isLoading:r,error:s}=mc(e);if(s&&ys(s))return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Hs,{})});if(s&&xs(s))return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ms,{resource:"agents"})});if(r)return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Xt,{className:"h-6 w-6"})});if(!n)return o.jsx("div",{className:"py-4 text-center",children:"Agent not found"});const a=i=>{sessionStorage.setItem(`pending-scorer-items-${e}`,JSON.stringify(i)),t(`/agents/${e}/evaluate`)};return o.jsx(vts,{agentId:e,onCreateScorer:a})}let au=(function(e){return e.AGENT="agent",e.SCORER="scorer",e.RAG_INGESTION="rag_ingestion",e.TRAJECTORY="trajectory",e.INPUT_PROCESSOR="input_processor",e.INPUT_STEP_PROCESSOR="input_step_processor",e.OUTPUT_PROCESSOR="output_processor",e.OUTPUT_STEP_PROCESSOR="output_step_processor",e.WORKFLOW_STEP="workflow_step",e.TOOL="tool",e.WORKFLOW_RUN="workflow_run",e.MEMORY="memory",e})({});C_().describe("Database record creation time");const lns=C_().describe("Database record last update time");lns.nullable();const BG=_e({page:J2().int().min(0).optional().default(0).describe("Zero-indexed page number"),perPage:J2().int().min(1).max(100).optional().default(10).describe("Number of items per page")}).describe("Pagination options for list queries"),UG=_e({total:Ct().describe("Total number of items available"),page:Ct().describe("Current page"),perPage:Qn([Ct(),Vt(!1)]).describe("Number of items per page, or false if pagination is disabled"),hasMore:Ps().describe("True if more pages are available")}),nS=ge().min(1).describe("Opaque cursor value for incremental polling"),VG=Ys(["page","delta"]).describe("List mode: 'page' | 'delta', defaults to 'page' when omitted."),qG=J2().int().min(1).max(100).optional().describe("Maximum number of updates to return in one delta poll"),cns={page:0,perPage:10};function HG(e,t){if(e.mode==="delta"){e.pagination!==void 0&&t.addIssue({code:"custom",path:["pagination"],message:"pagination is not allowed in delta mode"}),e.orderBy!==void 0&&t.addIssue({code:"custom",path:["orderBy"],message:"orderBy is not allowed in delta mode"});return}e.after!==void 0&&t.addIssue({code:"custom",path:["after"],message:"after is only allowed in delta mode"}),e.limit!==void 0&&t.addIssue({code:"custom",path:["limit"],message:"limit is only allowed in delta mode"})}function WG(e,t){return{mode:e.mode==="delta"?"delta":"page",filters:e.filters,pagination:e.pagination??t.pagination??cns,orderBy:e.orderBy??t.orderBy,after:e.after,limit:e.limit??t.limit??10}}const ZG=_e({limit:Ct().describe("Maximum number of updates requested for this delta poll"),hasMore:Ps().describe("True when more matching updates remain after this response")}).describe("Incremental polling metadata"),uns=_e({start:q$e().optional().describe("Start of date range (inclusive by default)"),end:q$e().optional().describe("End of date range (inclusive by default)"),startExclusive:Ps().optional().describe("When true, excludes the start date from results (uses > instead of >=)"),endExclusive:Ps().optional().describe("When true, excludes the end date from results (uses < instead of <=)")}).describe("Date range filter for timestamps"),SL=Ys(["ASC","DESC"]).describe("Sort direction: 'ASC' | 'DESC'"),Zy=Ys(["sum","avg","min","max","count","count_distinct","last"]).describe("Aggregation function"),mC=Ys(["1m","5m","15m","1h","1d"]).describe("Time bucket interval"),LNe=Ys(["previous_period","previous_day","previous_week"]).describe("Comparison period for aggregate queries"),gC=$t(ge()).min(1).describe("Fields to group by"),FNe=$t(Ct().min(0).max(1)).min(1).describe("Percentile values (0-1)"),zNe={value:Ct().nullable().describe("Aggregated value"),previousValue:Ct().nullable().optional().describe("Value from comparison period"),changePercent:Ct().nullable().optional().describe("Percentage change from comparison period")},BNe=Us(ge(),ge().nullable()).describe("Dimension values for this group"),WI=Ct().describe("Aggregated value"),ZI=C_().describe("Bucket timestamp"),UNe=Ct().describe("Percentile value"),VNe=Ct().describe("Percentile value at this bucket"),GI=bxe(au).describe("Entity type (e.g., 'agent' | 'processor' | 'tool' | 'workflow')"),dns=ge().describe('ID of the entity (e.g., "weatherAgent", "orderWorkflow")'),i9t=ge().describe("Name of the entity"),o9t=ge().describe("Human end-user who triggered execution"),l9t=ge().describe("Multi-tenant organization/account"),c9t=ge().describe("Broader resource context (Mastra memory compatibility)"),u9t=ge().describe("Unique execution run identifier"),d9t=ge().describe("Session identifier for grouping traces"),f9t=ge().describe("Conversation thread identifier"),p9t=ge().describe("HTTP request ID for log correlation"),h9t=ge().describe('Environment (e.g., "production" | "staging" | "development")'),fns=ge().describe('Source of execution (e.g., "local" | "cloud" | "ci")'),m9t=ge().describe('Source of execution (e.g., "local" | "cloud" | "ci")'),g9t=ge().describe("Name of the service"),v9t=bxe(au).describe("Entity type of the parent entity"),pns=ge().describe("ID of the parent entity"),y9t=ge().describe("Name of the parent entity"),b9t=bxe(au).describe("Entity type of the root entity"),hns=ge().describe("ID of the root entity"),x9t=ge().describe("Name of the root entity"),w9t=ge().describe("Version ID of the entity that produced this signal (e.g., agent version, workflow version)"),S9t=ge().describe("Version ID of the parent entity that produced this signal"),k9t=ge().describe("Version ID of the root entity that produced this signal"),GG=ge().describe("Experiment or eval run identifier"),mns=Us(ge(),za()).describe('Arbitrary package/app version info (e.g., {"core": "1.0.0", "memory": "1.0.0", "gitSha": "abcd1234"})'),O9t=Us(ge(),za()).describe("User-defined metadata for custom filtering"),_9t=$t(ge()).describe("Labels for filtering"),gns={entityType:GI.nullish(),entityId:dns.nullish(),entityName:i9t.nullish(),parentEntityType:v9t.nullish(),parentEntityId:pns.nullish(),parentEntityName:y9t.nullish(),rootEntityType:b9t.nullish(),rootEntityId:hns.nullish(),rootEntityName:x9t.nullish(),userId:o9t.nullish(),organizationId:l9t.nullish(),resourceId:c9t.nullish(),runId:u9t.nullish(),sessionId:d9t.nullish(),threadId:f9t.nullish(),requestId:p9t.nullish(),environment:h9t.nullish(),serviceName:g9t.nullish(),scope:mns.nullish(),entityVersionId:w9t.nullish(),parentEntityVersionId:S9t.nullish(),rootEntityVersionId:k9t.nullish(),experimentId:GG.nullish()},QG={...gns,executionSource:m9t.nullish(),tags:_9t.nullish()};fns.nullish();const YG={timestamp:uns.optional().describe("Filter by timestamp range"),traceId:ge().optional().describe("Filter by trace ID"),spanId:ge().optional().describe("Filter by span ID"),entityType:GI.optional(),entityName:i9t.optional(),entityVersionId:w9t.optional(),parentEntityVersionId:S9t.optional(),rootEntityVersionId:k9t.optional(),userId:o9t.optional(),organizationId:l9t.optional(),experimentId:GG.optional(),serviceName:g9t.optional(),environment:h9t.optional(),parentEntityType:v9t.optional(),parentEntityName:y9t.optional(),rootEntityType:b9t.optional(),rootEntityName:x9t.optional(),resourceId:c9t.optional(),runId:u9t.optional(),sessionId:d9t.optional(),threadId:f9t.optional(),requestId:p9t.optional(),executionSource:m9t.optional(),tags:$t(ge()).optional().describe("Filter by tags (must have all specified tags)")},KG=ge().describe("Unique trace identifier"),XG=ge().describe("Unique span identifier within a trace"),MV=Ys(["debug","info","warn","error","fatal"]),C9t=ge().describe("Log message"),E9t=Us(ge(),za()).describe("Structured data attached to the log"),j9t=_e({logId:ge().nullish().describe("Unique id for this log event"),timestamp:C_().describe("When the log was created"),level:MV.describe("Log severity level"),message:C9t,data:E9t.nullish(),traceId:KG.nullish(),spanId:XG.nullish(),...QG,source:ge().nullish().describe("Execution source"),metadata:O9t.nullish()}).describe("Log record as stored in the database");_e({level:MV,message:C9t,data:E9t.optional(),tags:_9t.optional()}).describe("User-provided log input");const vns=j9t;_e({logs:$t(vns)}).describe("Arguments for batch creating logs");const yns=_e({...YG,source:ge().optional().describe("Filter by execution source"),level:Qn([MV,$t(MV)]).optional().describe("Filter by log level(s)")}).describe("Filters for querying logs"),bns=Ys(["timestamp"]).describe("Field to order by: 'timestamp'"),xns=_e({field:bns.default("timestamp").describe("Field to order by"),direction:SL.default("DESC").describe("Sort direction")}).describe("Order by configuration");_e({mode:VG.optional(),filters:yns.optional().describe("Optional filters to apply"),pagination:BG.optional(),orderBy:xns.optional(),after:nS.optional(),limit:qG}).strict().superRefine(HG).transform(e=>WG(e,{orderBy:{field:"timestamp",direction:"DESC"}})).describe("Arguments for listing logs");_e({pagination:UG.optional(),delta:ZG.optional(),deltaCursor:nS.optional(),logs:$t(j9t)}).describe("Response from listing logs");const QI=ge().describe("Identifier of the scorer (e.g., relevance, accuracy)"),T9t=ge().describe("Display name of the scorer"),N9t=ge().describe("Version of the scorer"),_y=ge().describe("How the score was produced (e.g., manual, automated, experiment)"),I9t=Ct().describe("Score value (range defined by scorer)"),A9t=ge().describe("Explanation for the score"),R9t=_e({scoreId:ge().nullish().describe("Unique id for this score event"),timestamp:C_().describe("When the score was recorded"),traceId:KG.nullish().describe("Trace that anchors the scored target when available"),spanId:XG.nullish().describe("Span ID this score applies to"),scorerId:QI,scorerName:T9t.nullish(),scorerVersion:N9t.nullish(),scoreSource:_y.nullish(),source:_y.nullish(),score:I9t,reason:A9t.nullish(),...QG,scoreTraceId:ge().nullish().describe("Trace ID of the scoring run for debugging score generation"),metadata:Us(ge(),za()).nullish().describe("User-defined metadata")}).describe("Score record as stored in the database");_e({scorerId:QI,scorerName:T9t.optional(),scorerVersion:N9t.optional(),scoreSource:_y.optional(),source:_y.optional(),score:I9t,reason:A9t.optional(),metadata:Us(ge(),za()).optional().describe("Additional scorer-specific metadata"),experimentId:GG.optional(),scoreTraceId:ge().optional().describe("Trace ID of the scoring run for debugging score generation"),targetEntityType:GI.optional().describe("Entity type the scorer evaluated when known")}).describe("User-provided score input");const qNe=R9t;_e({score:qNe}).describe("Arguments for creating a score");_e({score:qNe.omit({timestamp:!0})}).describe("Arguments for creating a score");_e({success:Ps()}).describe("Response from creating a score");_e({scores:$t(qNe)}).describe("Arguments for batch recording scores");const kL=_e({...YG,scorerId:Qn([ge(),$t(ge())]).optional().describe("Filter by scorer ID(s)"),scoreSource:_y.optional().describe("Filter by how the score was produced"),source:_y.optional().describe("Filter by how the score was produced")}).describe("Filters for querying scores"),wns=Ys(["timestamp","score"]).describe("Field to order by: 'timestamp' | 'score'"),Sns=_e({field:wns.default("timestamp").describe("Field to order by"),direction:SL.default("DESC").describe("Sort direction")}).describe("Order by configuration");_e({mode:VG.optional(),filters:kL.optional(),pagination:BG.optional(),orderBy:Sns.optional(),after:nS.optional(),limit:qG}).strict().superRefine(HG).transform(e=>WG(e,{orderBy:{field:"timestamp",direction:"DESC"}})).describe("Arguments for listing scores");_e({pagination:UG.optional(),delta:ZG.optional(),deltaCursor:nS.optional(),scores:$t(R9t)}).describe("Response from listing scores");_e({scorerId:QI,scoreSource:_y.optional(),aggregation:Zy,filters:kL.optional(),comparePeriod:LNe.optional()}).describe("Arguments for getting a score aggregate");_e(zNe);_e({scorerId:QI,scoreSource:_y.optional(),groupBy:gC,aggregation:Zy,filters:kL.optional()}).describe("Arguments for getting a score breakdown");_e({groups:$t(_e({dimensions:BNe,value:WI}))});_e({scorerId:QI,scoreSource:_y.optional(),interval:mC,aggregation:Zy,filters:kL.optional(),groupBy:gC.optional()}).describe("Arguments for getting score time series");_e({series:$t(_e({name:ge().describe("Series name (scorer ID or group key)"),points:$t(_e({timestamp:ZI,value:WI}))}))});_e({scorerId:QI,scoreSource:_y.optional(),percentiles:FNe,interval:mC,filters:kL.optional()}).describe("Arguments for getting score percentiles");_e({series:$t(_e({percentile:UNe,points:$t(_e({timestamp:ZI,value:VNe}))}))});const Cy=ge().describe("Source of feedback (e.g., 'user', 'system', 'manual')"),YI=ge().describe("Type of feedback (e.g., 'thumbs', 'rating', 'correction')"),P9t=Qn([Ct(),ge()]).describe("Feedback value (rating number or correction text)"),$9t=ge().describe("Additional comment or context"),DV=ge().describe("User who provided the feedback");function HNe(e){if(!e||typeof e!="object"||Array.isArray(e))return e;const t={...e};return typeof t.userId=="string"&&t.feedbackUserId==null&&(t.feedbackUserId=t.userId,delete t.userId),t}const JG=_e({feedbackId:ge().nullish().describe("Unique id for this feedback event"),timestamp:C_().describe("When the feedback was recorded"),traceId:KG.nullish().describe("Trace that anchors the feedback target when available"),spanId:XG.nullish().describe("Span ID this feedback applies to"),feedbackSource:Cy.nullish(),source:Cy.nullish(),feedbackType:YI,value:P9t,comment:$9t.nullish(),feedbackUserId:DV.nullish(),...QG,sourceId:ge().nullish().describe("ID of the source record this feedback is linked to (e.g. experiment result ID)"),metadata:Us(ge(),za()).nullish().describe("User-defined metadata")}),kns=_e(JG.shape).describe("Feedback record as stored in the database"),Ons=_e({feedbackSource:Cy.optional(),source:Cy.optional(),feedbackType:YI,value:P9t,comment:$9t.optional(),feedbackUserId:DV.optional(),userId:DV.optional(),metadata:Us(ge(),za()).optional().describe("Additional feedback-specific metadata"),experimentId:GG.optional(),sourceId:ge().optional().describe("ID of the source record this feedback is linked to")});_e(Ons.shape).describe("User-provided feedback input");_e({feedback:kxe(HNe,JG)}).describe("Arguments for creating feedback");_e({feedback:JG.omit({timestamp:!0})}).describe("Arguments for creating feedback");_e({success:Ps()}).describe("Response from creating feedback");_e({feedbacks:$t(kxe(HNe,JG))}).describe("Arguments for batch recording feedback");const M9t=_e({...YG,feedbackType:Qn([ge(),$t(ge())]).optional().describe("Filter by feedback type(s)"),feedbackSource:Cy.optional(),source:Cy.optional(),feedbackUserId:DV.optional()}),eQ=_e(M9t.shape).describe("Filters for querying feedback"),_ns=Ys(["timestamp"]).describe("Field to order by: 'timestamp'"),Cns=_e({field:_ns.default("timestamp").describe("Field to order by"),direction:SL.default("DESC").describe("Sort direction")}).describe("Order by configuration");_e({mode:VG.optional(),filters:kxe(HNe,M9t).optional(),pagination:BG.optional(),orderBy:Cns.optional(),after:nS.optional(),limit:qG}).strict().superRefine(HG).transform(e=>WG(e,{orderBy:{field:"timestamp",direction:"DESC"}})).describe("Arguments for listing feedback");_e({pagination:UG.optional(),delta:ZG.optional(),deltaCursor:nS.optional(),feedback:$t(kns)}).describe("Response from listing feedback");_e({feedbackType:YI,feedbackSource:Cy.optional(),aggregation:Zy,filters:eQ.optional(),comparePeriod:LNe.optional()}).describe("Arguments for getting a feedback aggregate over numeric values");_e(zNe);_e({feedbackType:YI,feedbackSource:Cy.optional(),groupBy:gC,aggregation:Zy,filters:eQ.optional()}).describe("Arguments for getting a feedback breakdown over numeric values");_e({groups:$t(_e({dimensions:BNe,value:WI}))});_e({feedbackType:YI,feedbackSource:Cy.optional(),interval:mC,aggregation:Zy,filters:eQ.optional(),groupBy:gC.optional()}).describe("Arguments for getting feedback time series over numeric values");_e({series:$t(_e({name:ge().describe("Series name (feedback type or group key)"),points:$t(_e({timestamp:ZI,value:WI}))}))});_e({feedbackType:YI,feedbackSource:Cy.optional(),percentiles:FNe,interval:mC,filters:eQ.optional()}).describe("Arguments for getting feedback percentiles over numeric values");_e({series:$t(_e({percentile:UNe,points:$t(_e({timestamp:ZI,value:VNe}))}))});Ys(["counter","gauge","histogram"]);const D9t=ge().describe("Metric name (e.g., mastra_agent_duration_ms)"),L9t=Ct().describe("Metric value"),F9t=Us(ge(),ge()).describe("Metric labels for dimensional filtering"),z9t=ge().describe("Model provider"),B9t=ge().describe("Model"),Ens=Ct().describe("Estimated cost"),U9t=ge().describe("Unit for the estimated cost (e.g., usd)"),jns=Us(ge(),za()).nullish().describe("Structured costing metadata"),V9t=_e({metricId:ge().nullish().describe("Unique id for this metric event"),timestamp:C_().describe("When the metric was recorded"),name:D9t,value:L9t,traceId:KG.nullish(),spanId:XG.nullish(),...QG,source:ge().nullish().describe("Execution source"),provider:z9t.nullish(),model:B9t.nullish(),estimatedCost:Ens.nullish(),costUnit:U9t.nullish(),costMetadata:jns.nullish(),labels:F9t.default({}),metadata:O9t.nullish()}).describe("Metric record as stored in the database");_e({name:D9t,value:L9t,labels:F9t.optional()}).describe("User-provided metric input");const Tns=V9t;_e({metrics:$t(Tns)}).describe("Arguments for batch recording metrics");_e({type:Zy,interval:mC.optional(),groupBy:gC.optional()}).describe("Metrics aggregation configuration");const OL=_e({...YG,name:$t(ge()).nonempty().optional().describe("Filter by metric name(s)"),source:ge().optional().describe("Filter by execution source"),provider:z9t.optional(),model:B9t.optional(),costUnit:U9t.optional(),labels:Us(ge(),ge()).optional().describe("Exact match on label key-value pairs")}).describe("Filters for querying metrics"),Nns=Ys(["timestamp"]).describe("Field to order by: 'timestamp'"),Ins=_e({field:Nns.default("timestamp").describe("Field to order by"),direction:SL.default("DESC").describe("Sort direction")}).describe("Order by configuration");_e({mode:VG.optional(),filters:OL.optional(),pagination:BG.optional(),orderBy:Ins.optional(),after:nS.optional(),limit:qG}).strict().superRefine(HG).transform(e=>WG(e,{orderBy:{field:"timestamp",direction:"DESC"}})).describe("Arguments for listing metrics");_e({pagination:UG.optional(),delta:ZG.optional(),deltaCursor:nS.optional(),metrics:$t(V9t)}).describe("Response from listing metrics");const Ans=["entityType","entityName","parentEntityType","parentEntityName","rootEntityType","rootEntityName","name","provider","model","environment","executionSource","serviceName","threadId","resourceId"],WNe=Ys(Ans).optional().describe("Column to apply count_distinct over (required when aggregation is 'count_distinct'). Restricted to allowlisted metric dimensions."),IN={check:e=>e.aggregation!=="count_distinct"||e.distinctColumn!==void 0,options:{message:"distinctColumn is required when aggregation is 'count_distinct'",path:["distinctColumn"]}};_e({name:$t(ge()).nonempty().describe("Metric name(s) to aggregate"),aggregation:Zy,distinctColumn:WNe,filters:OL.optional(),comparePeriod:LNe.optional()}).refine(IN.check,IN.options).describe("Arguments for getting a metric aggregate");_e({...zNe,estimatedCost:Ct().nullable().optional().describe("Aggregated estimated cost from the same filtered row set"),costUnit:ge().nullable().optional().describe("Shared cost unit for the aggregated rows, or null when mixed/unknown"),previousEstimatedCost:Ct().nullable().optional().describe("Aggregated estimated cost from the comparison period"),costChangePercent:Ct().nullable().optional().describe("Percentage change in estimated cost from comparison period")});_e({name:$t(ge()).nonempty().describe("Metric name(s) to break down"),groupBy:gC,aggregation:Zy,distinctColumn:WNe,filters:OL.optional(),limit:Ct().int().positive().max(1e3).optional().describe("Maximum number of groups to return (server-side TopK). Required for high-cardinality groupBy."),orderDirection:SL.optional().describe("Sort direction for the aggregated value (defaults to 'DESC' at the storage layer; pairs with limit for top/bottom-N).")}).refine(IN.check,IN.options).describe("Arguments for getting a metric breakdown");_e({groups:$t(_e({dimensions:BNe,value:WI,estimatedCost:Ct().nullable().optional().describe("Summed estimated cost for this group"),costUnit:ge().nullable().optional().describe("Shared cost unit for this group, or null when mixed/unknown")}))});_e({name:$t(ge()).nonempty().describe("Metric name(s)"),interval:mC,aggregation:Zy,distinctColumn:WNe,filters:OL.optional(),groupBy:gC.optional()}).refine(IN.check,IN.options).describe("Arguments for getting metric time series");_e({series:$t(_e({name:ge().describe("Series name (metric name or group key)"),costUnit:ge().nullable().optional().describe("Shared cost unit for this series, or null when mixed/unknown"),points:$t(_e({timestamp:ZI,value:WI,estimatedCost:Ct().nullable().optional().describe("Summed estimated cost in this bucket")}))}))});_e({name:ge().describe("Metric name"),percentiles:FNe,interval:mC,filters:OL.optional()}).describe("Arguments for getting metric percentiles");_e({series:$t(_e({percentile:UNe,points:$t(_e({timestamp:ZI,value:VNe}))}))});_e({prefix:ge().optional().describe("Filter metric names by prefix"),limit:J2().int().min(1).optional().describe("Maximum number of names to return")}).describe("Arguments for getting metric names");_e({names:$t(ge()).describe("Distinct metric names")});_e({metricName:ge().describe("Metric name to get label keys for")}).describe("Arguments for getting metric label keys");_e({keys:$t(ge()).describe("Distinct label keys for the metric")});_e({metricName:ge().describe("Metric name"),labelKey:ge().describe("Label key to get values for"),prefix:ge().optional().describe("Filter values by prefix"),limit:J2().int().min(1).optional().describe("Maximum number of values to return")}).describe("Arguments for getting label values");_e({values:$t(ge()).describe("Distinct label values")});_e({}).describe("Arguments for getting entity types");_e({entityTypes:$t(GI).describe("Distinct entity types")});_e({entityType:GI.optional().describe("Optional entity type filter")}).describe("Arguments for getting entity names");_e({names:$t(ge()).describe("Distinct entity names")});_e({}).describe("Arguments for getting service names");_e({serviceNames:$t(ge()).describe("Distinct service names")});_e({}).describe("Arguments for getting environments");_e({environments:$t(ge()).describe("Distinct environments")});_e({entityType:GI.optional().describe("Optional entity type filter")}).describe("Arguments for getting tags");_e({tags:$t(ge()).describe("Distinct tags")});new Set(Object.values(au));function ZNe({disabled:e,onClear:t,onRemoveAll:n,onSave:r,onRemoveSaved:s}){const a=!!(n||r||s);return!t&&!a?null:o.jsxs("div",{className:"flex items-center gap-2",children:[t&&o.jsxs(ce,{disabled:e,size:"md",onClick:t,children:[o.jsx(Wu,{}),"Clear"]}),a&&o.jsxs(dt,{children:[o.jsx(dt.Trigger,{asChild:!0,children:o.jsx(ce,{disabled:e,size:"md","aria-label":"More filter actions",children:o.jsx(dEn,{})})}),o.jsxs(dt.Content,{align:"end",children:[n&&o.jsxs(dt.Item,{onSelect:()=>n(),children:[o.jsx(Wu,{}),"Remove all filters"]}),n&&(r||s)&&o.jsx(dt.Separator,{}),r&&o.jsxs(dt.Item,{onSelect:()=>r(),children:[o.jsx(Jmt,{}),"Save filters for next time"]}),s&&o.jsxs(dt.Item,{onSelect:()=>s(),children:[o.jsx(egt,{}),"Remove saved filters"]})]})]})]})}function q9t({field:e,tokens:t,onChange:n}){const[r,s]=v.useState(""),a=v.useMemo(()=>{const u=r.trim().toLowerCase();return u?e.options.filter(d=>d.label.toLowerCase().includes(u)):e.options},[e.options,r]),i=v.useMemo(()=>t.find(u=>u.fieldId===e.id),[t,e.id]),l=typeof i?.value=="string"?i.value:e.multi?void 0:e.defaultValue,c=v.useMemo(()=>{const u=i?.value;return Array.isArray(u)?u:typeof u=="string"?[u]:[]},[i]);return o.jsxs(o.Fragment,{children:[e.searchable!==!1&&o.jsx(Cn,{size:"sm",value:r,onChange:u=>s(u.target.value),placeholder:`Search ${e.label.toLowerCase()}...`,className:"mb-2",onKeyDown:u=>{if(u.key!=="ArrowDown")return;const f=u.currentTarget.closest("[data-pick-multi-panel]")?.querySelector("[data-pick-multi-item]:not([disabled])");f&&(u.preventDefault(),u.stopPropagation(),f.focus())}}),e.isLoading?o.jsxs("div",{className:"text-ui-sm text-neutral3 flex items-center gap-2 px-2 py-1.5",children:[o.jsx(Xt,{size:"sm",className:"text-neutral3 size-3"}),"Loading options…"]}):a.length===0?o.jsx("div",{className:"text-ui-sm text-neutral3 px-2 py-1.5",children:e.emptyText??"No option found."}):e.multi?o.jsx("div",{className:"max-h-[80dvh] overflow-auto",children:a.map(u=>{const d=c.includes(u.value);return o.jsxs("label",{title:u.label,className:"text-ui-md text-neutral4 focus-within:bg-surface4 focus-within:text-neutral6 hover:bg-surface4 hover:text-neutral6 flex min-w-0 cursor-pointer items-center gap-2 rounded-md px-2 py-1.5",children:[o.jsx(zo,{"data-pick-multi-item":"",checked:d,onCheckedChange:f=>{const h=f===!0?c.includes(u.value)?c:[...c,u.value]:c.filter(m=>m!==u.value);n(e.id,h)},className:"shrink-0"}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:u.label})]},u.value)})}):o.jsxs(bL,{value:l??"",onValueChange:u=>n(e.id,u),className:"max-h-[80dvh] gap-0 overflow-auto",children:[a.map(u=>o.jsxs("label",{title:u.label,className:"text-ui-md text-neutral4 focus-within:bg-surface4 focus-within:text-neutral6 hover:bg-surface4 hover:text-neutral6 flex min-w-0 cursor-pointer items-center gap-2 rounded-md px-2 py-1.5",children:[o.jsx(Np,{"data-pick-multi-item":"",value:u.value,className:"shrink-0"}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:u.label})]},u.value)),!e.omitAnyOption&&o.jsxs("label",{title:"Any",className:"text-ui-md text-neutral4 focus-within:bg-surface4 focus-within:text-neutral6 hover:bg-surface4 hover:text-neutral6 flex min-w-0 cursor-pointer items-center gap-2 rounded-md px-2 py-1.5",children:[o.jsx(Np,{"data-pick-multi-item":"",value:"Any",className:"shrink-0"}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:"Any"})]})]})]})}function GNe(e){return Array.isArray(e)?e.length===0?"Any":e.join(", "):e}const Rns="This filter is set by the current context and cannot be removed here.";function Pns(e,t){return e.kind==="pick-multi"&&e.options?Array.isArray(t)?t.length===0?"Any":t.map(n=>e.options.find(r=>r.value===n)?.label??n).join(", "):e.options.find(n=>n.value===t)?.label??t:GNe(t)}function $ns({field:e,value:t,tooltipContent:n}){const r=Pns(e,t),s=`${e.label} filter is locked by context`;return o.jsx(cc,{delayDuration:150,children:o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:o.jsxs(Mr,{spacing:"close","data-locked-field-id":e.id,"data-property-filter-pill":"locked",tabIndex:0,"aria-label":s,children:[o.jsx(Hh,{size:"md",children:e.label}),o.jsx(Hh,{size:"md",children:"is"}),o.jsx(Hh,{size:"md",children:r}),o.jsx(Hh,{size:"md",children:o.jsx(XEn,{})})]})}),o.jsx(Rn,{children:n})]})})}function Mns({field:e,value:t,onChange:n,onRemove:r,disabled:s,autoFocus:a}){const[i,l]=v.useState(t),c=v.useRef(null);return v.useEffect(()=>{i.trim()!==t&&l(t)},[t]),v.useEffect(()=>{a&&c.current?.focus()},[a]),o.jsxs(Mr,{spacing:"close",children:[o.jsx(Hh,{size:"md",children:e.label}),o.jsx(Hh,{size:"md",children:"is"}),o.jsx(Cn,{ref:c,size:"md",disabled:s,value:i,placeholder:e.placeholder??`Enter ${e.label}`,onChange:u=>{const d=u.target.value;l(d),d.trim()!==t&&n(d)},onKeyDown:u=>{if(u.key==="Enter"){u.preventDefault();const d=i.trim();d!==t&&n(d)}else u.key==="Escape"&&(u.preventDefault(),l(t),u.target.blur())}}),o.jsx(ce,{type:"button",disabled:s,"aria-label":`Remove ${e.label} filter`,size:"md",onMouseDown:u=>u.preventDefault(),onClick:r,children:o.jsx(Wu,{})})]})}function Dns({field:e,token:t,tokens:n,onChange:r,onRemove:s,disabled:a}){const[i,l]=v.useState(!1);return o.jsxs(Mr,{spacing:"close",children:[o.jsx(Hh,{size:"md",children:e.label}),o.jsx(Hh,{size:"md",children:"is"}),o.jsxs(Pf,{open:i,onOpenChange:l,children:[o.jsx(Bd,{asChild:!0,children:o.jsx(ce,{type:"button",disabled:a,size:"md",children:GNe(t.value)})}),o.jsx(Ud,{align:"start",sideOffset:8,className:"w-64 p-2","data-pick-multi-panel":!0,children:o.jsx(q9t,{field:e,tokens:n,onChange:r})})]}),o.jsx(ce,{type:"button",disabled:a,"aria-label":`Remove ${e.label} filter`,size:"md",onClick:s,children:o.jsx(Wu,{})})]})}function QNe({fields:e,tokens:t,onTokensChange:n,disabled:r,autoFocusFieldId:s,lockedFieldIds:a,lockedTooltipContent:i=Rns}){if(t.length===0)return null;const l=new Set(a??[]),c=(d,f)=>{const p=[...t];p[d]=f,n(p)},u=d=>{n(t.filter((f,p)=>p!==d))};return o.jsx("div",{className:"flex flex-wrap items-center gap-2",children:t.map((d,f)=>{const p=e.find(h=>h.id===d.fieldId);return p?l.has(d.fieldId)?o.jsx($ns,{field:p,value:d.value,tooltipContent:i},`${d.fieldId}-${f}`):p.kind==="text"&&typeof d.value=="string"?o.jsx(Mns,{field:p,value:d.value,disabled:r,autoFocus:s===d.fieldId,onChange:h=>c(f,{fieldId:d.fieldId,value:h}),onRemove:()=>u(f)},`${d.fieldId}-${f}`):p.kind==="pick-multi"?o.jsx(Dns,{field:p,token:d,tokens:t,disabled:r,onChange:(h,m)=>{if(m===void 0){u(f);return}c(f,{fieldId:h,value:m})},onRemove:()=>u(f)},`${d.fieldId}-${f}`):o.jsxs(Mr,{spacing:"close",children:[o.jsx(Hh,{size:"md",children:p.label}),o.jsx(Hh,{size:"md",children:"is"}),o.jsx(Hh,{size:"md",children:GNe(d.value)}),o.jsx(ce,{type:"button",disabled:r,size:"md","aria-label":`Remove ${p.label} filter`,onClick:()=>u(f),children:o.jsx(Wu,{})})]},`${d.fieldId}-${f}`):null})})}function YNe({fields:e,tokens:t,onTokensChange:n,label:r="Add Filter",disabled:s,size:a,onStartTextFilter:i,hiddenFieldIds:l}){const c=v.useMemo(()=>{if(!l||l.length===0)return e;const D=new Set(l);return e.filter(B=>!D.has(B.id))},[e,l]),[u,d]=v.useState(!1),[f,p]=v.useState(),[h,m]=v.useState(""),[g,y]=v.useState([]),[b,x]=v.useState(),[S,k]=v.useState(),_=v.useRef(null),C=v.useRef(!1),E=v.useCallback(D=>{k(B=>B===D?void 0:D)},[]),j=v.useCallback(()=>k(void 0),[]);v.useEffect(()=>{u||k(void 0)},[u]);const N=v.useMemo(()=>c.find(D=>D.id===f),[c,f]),I=v.useMemo(()=>{const D=new Set;for(const B of t){const H=e.find(F=>F.id===B.fieldId);H&&H.kind!=="pick-multi"&&D.add(B.fieldId)}return D},[t,e]),A=v.useCallback(()=>{p(void 0),m(""),y([]),x(void 0)},[]);v.useEffect(()=>{u||A()},[u,A]),v.useEffect(()=>{u&&N?.kind==="text"&&_.current?.focus()},[u,N]);const R=v.useCallback((D,B)=>{const H=t.findIndex(q=>q.fieldId===D);if(B===void 0||Array.isArray(B)&&B.length===0){if(H===-1)return;n(t.filter((q,M)=>M!==H));return}if(H===-1){n([...t,{fieldId:D,value:B}]);return}const z=[...t];z[H]={fieldId:D,value:B},n(z)},[n,t]),L=v.useCallback(()=>{if(!N){x("Choose a property first.");return}if(I.has(N.id)){x(`Remove the existing ${N.label} filter before adding another.`);return}if(N.kind==="text"&&!h.trim()){x(`Enter a value for ${N.label}.`);return}if(N.kind==="multi-select"&&g.length===0){x(`Choose at least one ${N.label.toLowerCase()} value.`);return}const D=N.kind==="multi-select"?{fieldId:N.id,value:g}:{fieldId:N.id,value:h.trim()};n([...t,D]),d(!1)},[g,n,N,I,h,t]);return o.jsxs(Pf,{open:u,onOpenChange:d,children:[o.jsx(Bd,{asChild:!0,children:o.jsxs(ce,{variant:"outline",size:a,disabled:s,children:[o.jsx(qEn,{}),r]})}),o.jsx(Ud,{align:"end",className:"w-64 p-3",initialFocus:!1,finalFocus:()=>C.current?(C.current=!1,!1):!0,children:o.jsxs("div",{className:"grid gap-3",children:[N&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("button",{type:"button","aria-label":"Back to properties",className:"text-neutral3 hover:text-neutral6 transition-colors",onClick:()=>{p(void 0),m(""),y([]),x(void 0)},children:o.jsx(Zq,{className:"size-4"})}),o.jsx(EEn,{className:"text-neutral3 size-4 shrink-0"}),o.jsx("span",{className:"text-ui-sm text-neutral3",children:`${N.label} · is`})]}),!N&&o.jsx("div",{role:"menu",className:"max-h-[80dvh] overflow-auto",onKeyDown:D=>{if(D.key!=="ArrowDown"&&D.key!=="ArrowUp"&&D.key!=="Home"&&D.key!=="End")return;const B=Array.from(D.currentTarget.querySelectorAll("[data-filter-item]:not([disabled])"));if(B.length===0)return;D.preventDefault();const H=document.activeElement,F=B.findIndex(q=>q===H);let z;D.key==="Home"?z=0:D.key==="End"?z=B.length-1:D.key==="ArrowDown"?z=F<0?0:(F+1)%B.length:z=F<=0?B.length-1:F-1,B[z]?.focus()},children:c.length>0?c.map(D=>{const B=I.has(D.id);return D.kind==="pick-multi"?o.jsx(Lns,{field:D,tokens:t,onChange:R,open:S===D.id,onToggle:E,onClose:j},D.id):o.jsxs("button",{type:"button",role:"menuitem","data-filter-item":"",className:X("group flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-ui-md transition-colors","focus:bg-surface4 focus:text-neutral6 focus:outline-none",B?"cursor-not-allowed text-neutral2 opacity-70":"text-neutral4 hover:bg-surface4 hover:text-neutral6"),disabled:B,onClick:()=>{if(x(void 0),D.kind==="text"){n([...t,{fieldId:D.id,value:""}]),i?.(D.id),C.current=!0,d(!1);return}p(D.id)},children:[o.jsx("span",{className:"truncate",children:D.label}),B?o.jsx("span",{className:"text-neutral3 ml-auto",children:"In use"}):o.jsx(ywe,{className:"text-neutral3 ml-auto size-4 opacity-0 transition-opacity group-hover:opacity-100 group-focus:opacity-100"})]},D.id)}):o.jsx("div",{className:"text-ui-sm text-neutral3 px-2 py-1.5",children:"No matching property."})}),N&&N.kind==="text"&&o.jsx(Cn,{ref:_,size:"md",value:h,onChange:D=>{m(D.target.value),x(void 0)},placeholder:N.placeholder??`Enter ${N.label}`,onKeyDown:D=>{D.key==="Enter"&&(D.preventDefault(),L())}}),N&&N.kind==="multi-select"&&o.jsx(ac,{multiple:!0,options:N.options??[],value:g,onValueChange:D=>{y(D),x(void 0)},placeholder:N.placeholder??`Choose ${N.label}`,searchPlaceholder:`Search ${N.label.toLowerCase()}...`,emptyText:N.emptyText??"No option found.",size:"md"}),b&&o.jsx("div",{className:"text-ui-sm text-red-500",children:b}),N&&N.kind!=="pick-multi"&&o.jsxs("div",{className:"flex items-center justify-end gap-2",children:[o.jsx(ce,{variant:"ghost",size:"md",onClick:()=>d(!1),children:"Cancel"}),o.jsx(ce,{variant:"outline",size:"md",onClick:L,children:"Add filter"})]})]})})]})}function Lns({field:e,tokens:t,onChange:n,open:r,onToggle:s,onClose:a}){const i=v.useRef(null);return o.jsxs(Pf,{open:r,onOpenChange:l=>{l?s(e.id):a()},children:[o.jsx(Bd,{asChild:!0,children:o.jsxs("button",{type:"button",role:"menuitem","data-filter-item":"",className:X("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-ui-md text-neutral4 transition-colors hover:bg-surface4 hover:text-neutral6","focus:bg-surface4 focus:text-neutral6 focus:outline-none"),onKeyDown:l=>{l.key!=="ArrowRight"&&l.key!=="ArrowLeft"||(r||s(e.id),l.preventDefault(),requestAnimationFrame(()=>{i.current?.querySelector('input, button, [tabindex]:not([tabindex="-1"])')?.focus()}))},children:[r&&o.jsx(o1,{className:"text-neutral3 size-4 shrink-0"}),o.jsx("span",{className:"truncate",children:e.label}),!r&&o.jsx(o1,{className:"text-neutral3 ml-auto size-4 shrink-0"})]})}),o.jsx(Ud,{ref:i,side:"right",align:"start",sideOffset:8,className:"w-64 p-2",initialFocus:!1,onKeyDown:l=>{if(l.key!=="ArrowDown"&&l.key!=="ArrowUp"&&l.key!=="Home"&&l.key!=="End")return;const c=Array.from(l.currentTarget.querySelectorAll("[data-pick-multi-item]:not([disabled])"));if(c.length===0)return;l.preventDefault(),l.stopPropagation();const u=document.activeElement,d=c.findIndex(p=>p===u);let f;l.key==="Home"?f=0:l.key==="End"?f=c.length-1:l.key==="ArrowDown"?f=d<0?0:(d+1)%c.length:f=d<=0?c.length-1:d-1,c[f]?.focus()},"data-pick-multi-panel":!0,children:o.jsx(q9t,{field:e,tokens:t,onChange:n})})]})}const Fns={"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"},dae="MMM d, yyyy HH:mm",fae="Pick a wider time range — older traces may fall outside the current window.";function zns({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No traces for ${Fns[e]}`,description:fae}:t&&n?{title:`No traces between ${nr(t,dae)} and ${nr(n,dae)}`,description:fae}:t?{title:`No traces since ${nr(t,dae)}`,description:fae}:{title:"No traces yet",description:"Traces will appear here once agents, workflows, or tools are executed."}}const Bns=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=zns({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(k7,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(ce,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/tracing/overview",target:"_blank",rel:"noopener noreferrer",children:["Tracing Documentation ",o.jsx(mwe,{})]})})})};function Uns(e,t=100){if(e==null)return"";const n=Array.isArray(e)?e:e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.messages)?e.messages:null;if(n){const i=n.filter(l=>l?.role==="user").map(l=>typeof l.content=="string"?l.content:Array.isArray(l.content)?l.content.map(c=>typeof c=="string"?c:c?.type==="text"&&typeof c.text=="string"?c.text:"").filter(Boolean).join(" "):"").filter(Boolean).join(" | ");return i.length>t?i.slice(0,t)+"…":i}if(typeof e=="string")return e.length>t?e.slice(0,t)+"…":e;const r=JSON.stringify(e);return r.length>t?r.slice(0,t)+"…":r}function Vns(e){return e?.attributes?.finishReason==="length"}function qns(e){const t=e?.attributes?.usage;if(!t)return"The model stopped generating because it reached the maximum token limit. The response was truncated and may be incomplete.";const n=t.inputTokens??0,r=t.outputTokens??0,s=t.totalTokens??n+r;return n>0||r>0?`The model stopped generating because it reached the maximum token limit. The response was truncated and may be incomplete.
703
703
 
704
704
  Token usage: ${n} input + ${r} output = ${s} total`:`The model stopped generating because it reached the maximum token limit (${s} tokens). The response was truncated and may be incomplete.`}function qKe(e){return!!e&&Object.values(e).some(t=>typeof t=="number")}function Hns(e){if(!e)return null;const t=typeof e.inputTokens=="number",n=typeof e.outputTokens=="number";if(!t&&!n)return null;const r=e.inputTokens??0,s=e.outputTokens??0,a=r+s,i=a>0;return{inputValue:r,outputValue:s,total:a,showSplit:i,inputPct:i?r/a*100:0,outputPct:i?s/a*100:0,inputDetails:t&&qKe(e.inputDetails)?e.inputDetails:void 0,outputDetails:n&&qKe(e.outputDetails)?e.outputDetails:void 0}}const Wns={text:"Text",cacheRead:"Cache read",cacheWrite:"Cache write",audio:"Audio",image:"Image",reasoning:"Reasoning"},HKe="oklch(0.78 0.16 320)",WKe="oklch(0.55 0.18 320)";function Zns({usage:e,className:t}){const n=Hns(e);if(!n)return null;const{inputValue:r,outputValue:s,total:a,showSplit:i,inputPct:l,outputPct:c,inputDetails:u,outputDetails:d}=n;return o.jsxs("div",{className:X("mt-2 mb-8 grid grid-cols-1 border-b border-border1 pb-3 4xl:grid-cols-2 4xl:gap-12",t),children:[i&&o.jsxs("div",{className:"mb-2",children:[o.jsxs("div",{className:"text-neutral2 flex items-baseline gap-3",children:[o.jsx("span",{className:"text-ui-md",children:"Tokens Used"}),o.jsx("span",{className:"text-ui-md text-neutral4 font-semibold",children:a.toLocaleString()}),o.jsxs("span",{className:"text-ui-sm ml-auto",children:[Math.round(l),"% Input vs ",Math.round(c),"% Output"]})]}),o.jsx("div",{className:"bg-surface4 mt-2 rounded-md p-1.5",children:o.jsxs("div",{className:"relative h-1.5 w-full overflow-hidden rounded-sm",children:[o.jsx("div",{className:"absolute top-0 left-0 h-1.5",style:{width:`${l}%`,backgroundColor:HKe}}),o.jsx("div",{className:"absolute top-0 h-1.5",style:{left:`${l}%`,width:`${c}%`,backgroundColor:WKe}})]})})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[o.jsx(ZKe,{label:"Input",color:HKe,value:r,details:u}),o.jsx(ZKe,{label:"Output",color:WKe,value:s,details:d})]})]})}function ZKe({label:e,color:t,value:n,details:r}){return o.jsxs("div",{children:[o.jsxs("div",{className:"text-neutral2 mb-2 flex items-baseline gap-3",children:[o.jsx("span",{className:"text-ui-md",children:e}),typeof n=="number"&&o.jsxs("span",{className:"flex items-baseline gap-1.5",children:[o.jsx("span",{className:"text-ui-md text-neutral4 font-semibold",children:n.toLocaleString()}),o.jsx("span",{className:"size-2 self-center rounded-full",style:{backgroundColor:t}})]})]}),r&&o.jsx(Gns,{details:r})]})}function Gns({details:e}){return o.jsx(Ut,{density:"dense",children:Object.entries(e).map(([t,n])=>typeof n!="number"?null:o.jsxs(v.Fragment,{children:[o.jsx(Ut.Key,{children:Wns[t]||t}),o.jsx(Ut.Value,{className:"text-right",children:n.toLocaleString()})]},t))})}function Cz(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:["› Span ",o.jsxs("b",{className:"text-neutral3",children:["#",n.spanId]})]}),o.jsxs("span",{children:["› Trace ",o.jsxs("b",{className:"text-neutral3",children:["#",n.traceId]})]})]})}function KNe({traceId:e,spanId:t,span:n,isLoading:r,onClose:s,onPrevious:a,onNext:i,activeTab:l,onTabChange:c,scoringTabSlot:u,scoringTabBadge:d,feedbackTabSlot:f,feedbackTabBadge:p,isAnchor:h}){return o.jsxs(xn,{children:[o.jsxs(xn.Header,{children:[o.jsxs(xn.Heading,{children:["Span ",o.jsxs("b",{children:["# ",t]})]}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[o.jsx(xn.NextPrevNav,{onPrevious:a,onNext:i,previousLabel:"Previous span",nextLabel:"Next span"}),o.jsx(xn.CloseButton,{onClick:s})]})]}),r?o.jsx(xn.LoadingData,{children:"Loading span details..."}):n?o.jsx(Qns,{span:n,traceId:e,spanId:t,activeTab:l,onTabChange:c,scoringTabSlot:u,scoringTabBadge:d,feedbackTabSlot:f,feedbackTabBadge:p,isAnchor:h}):o.jsx(xn.NoData,{children:"Span not found."})]})}function Qns({span:e,traceId:t,spanId:n,activeTab:r,onTabChange:s,scoringTabSlot:a,scoringTabBadge:i,feedbackTabSlot:l,feedbackTabBadge:c,isAnchor:u}){const d=e.startedAt&&e.endedAt?new Date(e.endedAt).getTime()-new Date(e.startedAt).getTime():null,f=e.attributes?.usage,p=o.jsxs(o.Fragment,{children:[Vns(e)&&o.jsx("div",{className:"mb-3",children:o.jsx(En,{variant:"warning",title:"Token Limit Exceeded",children:o.jsx(En.Message,{children:qns(e)})})}),f&&o.jsx(Zns,{usage:f,className:"mb-3"}),o.jsxs(Ut,{children:[(u??e.parentSpanId==null)&&o.jsxs(o.Fragment,{children:[e.traceId&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Trace Id"}),o.jsx(Ut.ValueWithCopyBtn,{copyTooltip:"Copy Trace Id to clipboard",copyValue:e.traceId,children:e.traceId})]}),e.tags&&e.tags.length>0&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Tags"}),o.jsx(Ut.Value,{children:e.tags.join(", ")})]}),e.runId&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Run Id"}),o.jsx(Ut.ValueWithCopyBtn,{copyTooltip:"Copy Run Id to clipboard",copyValue:e.runId,children:e.runId})]}),e.threadId&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Thread Id"}),o.jsx(Ut.ValueWithCopyBtn,{copyTooltip:"Copy Thread Id to clipboard",copyValue:e.threadId,children:e.threadId})]}),e.sessionId&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Session Id"}),o.jsx(Ut.ValueWithCopyBtn,{copyTooltip:"Copy Session Id to clipboard",copyValue:e.sessionId,children:e.sessionId})]}),e.requestId&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Request Id"}),o.jsx(Ut.ValueWithCopyBtn,{copyTooltip:"Copy Request Id to clipboard",copyValue:e.requestId,children:e.requestId})]}),e.resourceId&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Resource Id"}),o.jsx(Ut.ValueWithCopyBtn,{copyTooltip:"Copy Resource Id to clipboard",copyValue:e.resourceId,children:e.resourceId})]}),e.userId&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"User Id"}),o.jsx(Ut.ValueWithCopyBtn,{copyTooltip:"Copy User Id to clipboard",copyValue:e.userId,children:e.userId})]}),e.organizationId&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Organization Id"}),o.jsx(Ut.ValueWithCopyBtn,{copyTooltip:"Copy Organization Id to clipboard",copyValue:e.organizationId,children:e.organizationId})]}),e.experimentId&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Experiment Id"}),o.jsx(Ut.ValueWithCopyBtn,{copyTooltip:"Copy Experiment Id to clipboard",copyValue:e.experimentId,children:e.experimentId})]})]}),e.name&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Name"}),o.jsx(Ut.Value,{children:e.name})]}),e.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Type"}),o.jsx(Ut.Value,{children:e.spanType})]}),e.startedAt&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Started"}),o.jsx(Ut.Value,{children:nr(new Date(e.startedAt),"MMM dd, HH:mm:ss.SSS")})]}),e.endedAt&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Ended"}),o.jsx(Ut.Value,{children:nr(new Date(e.endedAt),"MMM dd, HH:mm:ss.SSS")})]}),d!=null&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Duration"}),o.jsx(Ut.Value,{children:d<1e3?`${d}ms`:`${(d/1e3).toFixed(2)}s`})]})]}),o.jsxs("div",{className:"mt-3 grid gap-3",children:[o.jsx(xn.CodeSection,{title:"Input",dialogTitle:Cz("Input",o.jsx(che,{}),{spanId:n,traceId:t}),icon:o.jsx(che,{}),codeStr:JSON.stringify(e.input??null,null,2)}),o.jsx(xn.CodeSection,{title:"Output",dialogTitle:Cz("Output",o.jsx(uhe,{}),{spanId:n,traceId:t}),icon:o.jsx(uhe,{}),codeStr:JSON.stringify(e.output??null,null,2)}),o.jsx(xn.CodeSection,{title:"Metadata",dialogTitle:Cz("Metadata",o.jsx(vw,{}),{spanId:n,traceId:t}),icon:o.jsx(vw,{}),codeStr:JSON.stringify(e.metadata??null,null,2)}),o.jsx(xn.CodeSection,{title:"Attributes",dialogTitle:Cz("Attributes",o.jsx(vw,{}),{spanId:n,traceId:t}),icon:o.jsx(vw,{}),codeStr:JSON.stringify(e.attributes??null,null,2)})]})]});return!a&&!l?o.jsx(xn.Content,{children:p}):o.jsx(xn.Content,{children:o.jsxs(Dc,{defaultTab:"details",value:r,onValueChange:s,children:[o.jsxs(Mc,{children:[o.jsx(Rr,{value:"details",children:"Details"}),a&&o.jsxs(Rr,{value:"scoring",children:["Scoring ",i!=null&&o.jsxs(o.Fragment,{children:["(",i,")"]})]}),l&&o.jsxs(Rr,{value:"feedback",children:["Feedback ",c!=null&&o.jsxs(o.Fragment,{children:["(",c,")"]})]})]}),o.jsx(Xr,{value:"details",children:p}),a&&o.jsx(Xr,{value:"scoring",children:a({span:e,traceId:t,spanId:n})}),l&&o.jsx(Xr,{value:"feedback",children:l({span:e,traceId:t,spanId:n})})]})})}function LV(e){if(!e.spans||e.spans.length===0)return[];const t=[];return e.spans.forEach(n=>{t.push(n.id),t.push(...LV(n))}),t}function XNe(e){const t=[];for(const n of e)t.push(n.id),t.push(...LV(n));return t}function Yns(){const e=We(),[t,n]=v.useState(!1);return{download:s=>{if(t)return;n(!0);const a=e.getTrace(s).then(i=>Z6r(`trace-${s}.json`,i)).finally(()=>n(!1));Le.promise({myPromise:a,loadingMessage:"Preparing trace download…",successMessage:"Trace downloaded",errorMessage:"Failed to download trace"})},isPending:t}}const JNe=(e,t)=>{if(!e||e.length===0)return[];const n=e.reduce((u,d)=>{const f=d?.endedAt?new Date(d.endedAt):void 0;return f&&(!u||f>u)?f:u},null),r=new Map,s=[];e.forEach(u=>{const d=new Date(u.startedAt),f=u.endedAt?new Date(u.endedAt):void 0,p={id:u.spanId,name:u.name,type:u.spanType,latency:f?f.getTime()-d.getTime():0,startTime:d.toISOString(),endTime:f?f.toISOString():void 0,spans:[],parentSpanId:u.parentSpanId};r.set(u.spanId,p)});const a=u=>t?u.spanId===t:u?.parentSpanId==null;e.forEach(u=>{const d=r.get(u.spanId);if(d)if(a(u)){if(n&&d.endTime&&n>new Date(d.endTime)){d.endTime=n.toISOString();const f=new Date(n).getTime(),p=new Date(d.startTime).getTime();d.latency=f-p}s.push(d)}else{const f=u.parentSpanId?r.get(u.parentSpanId):void 0;f?(f.spans??=[],f.spans.push(d)):s.push(d)}});const i=u=>u.sort((d,f)=>new Date(d.startTime).getTime()-new Date(f.startTime).getTime()),l=i(s),c=u=>{u.forEach(d=>{d.spans&&d.spans.length>0&&(d.spans=i(d.spans),c(d.spans))})};return c(l),l};function Kns(e){return e.error!=null?"error":e.endedAt==null?"running":"success"}function H9t({rootSpan:e,numOfCol:t=2,className:n}){const r=e.startedAt?new Date(e.startedAt):null,s=e.endedAt?new Date(e.endedAt):null,a=Kns(e),i=a==="error"?"ERROR":a==="running"?"RUNNING":"SUCCESS";return o.jsxs(Ut,{numOfCol:t,className:n,children:[e.entityId&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Entity Id"}),o.jsx(Ut.Value,{children:e.entityName||e.entityId})]}),e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Entity Type"}),o.jsx(Ut.Value,{children:e.entityType})]}),o.jsx(Ut.Key,{children:"Status"}),o.jsx(Ut.Value,{children:i}),r&&s&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Duration"}),o.jsx(Ut.Value,{children:`${(s.getTime()-r.getTime()).toLocaleString()}ms`})]}),r&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Started at"}),o.jsx(Ut.Value,{children:nr(r,"MMM dd, h:mm:ss.SSS aaa")})]}),s&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Ended at"}),o.jsx(Ut.Value,{children:nr(s,"MMM dd, h:mm:ss.SSS aaa")})]})]})}const W9t=e=>o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:o.jsx("path",{d:"M1.5 8.5V8C1.5 7.60218 1.65804 7.22064 1.93934 6.93934C2.22064 6.65804 2.60218 6.5 3 6.5H13C13.3978 6.5 13.7794 6.65804 14.0607 6.93934C14.342 7.22064 14.5 7.60218 14.5 8V8.5M8.70667 4.20667L7.29333 2.79333C7.20048 2.70037 7.09022 2.62661 6.96886 2.57628C6.84749 2.52595 6.71739 2.50003 6.586 2.5H3C2.60218 2.5 2.22064 2.65804 1.93934 2.93934C1.65804 3.22064 1.5 3.60218 1.5 4V12C1.5 12.3978 1.65804 12.7794 1.93934 13.0607C2.22064 13.342 2.60218 13.5 3 13.5H13C13.3978 13.5 13.7794 13.342 14.0607 13.0607C14.342 12.7794 14.5 12.3978 14.5 12V6C14.5 5.60218 14.342 5.22064 14.0607 4.93934C13.7794 4.65804 13.3978 4.5 13 4.5H9.414C9.14887 4.49977 8.89402 4.39426 8.70667 4.20667Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})}),GKe=["agent","workflow","model","mcp","tool","provider","memory","workspace","scorer","other"],Xns={agent:{icon:o.jsx(Uo,{}),color:"oklch(0.75 0.15 250)",label:"Agent",typePrefix:"agent"},workflow:{icon:o.jsx(Xu,{}),color:"oklch(0.75 0.15 200)",label:"Workflow",typePrefix:"workflow"},model:{icon:o.jsx(Hmt,{}),color:"oklch(0.75 0.15 320)",label:"Model",typePrefix:"model"},mcp:{icon:o.jsx(hC,{}),color:"oklch(0.75 0.15 160)",label:"MCP",typePrefix:"mcp"},tool:{icon:o.jsx(Ld,{}),color:"oklch(0.75 0.15 100)",label:"Tool",typePrefix:"tool"},provider:{icon:o.jsx(Ld,{}),color:"oklch(0.75 0.15 60)",label:"Provider Tool",typePrefix:"provider"},memory:{icon:o.jsx(A4,{}),color:"oklch(0.75 0.12 50)",label:"Memory",typePrefix:"memory"},workspace:{icon:o.jsx(W9t,{}),color:"oklch(0.75 0.15 40)",label:"Workspace",typePrefix:"workspace"},scorer:{icon:o.jsx(REn,{}),color:"oklch(0.75 0.15 280)",label:"Scorer",typePrefix:"scorer"}},Jns={color:"oklch(0.65 0 0)",label:"Other",typePrefix:"other"};function Z9t(e){const t=e?.toLowerCase().split("_")[0]??"";return Xns[t]??Jns}function ers({isSelected:e,isFaded:t,isExpanded:n,isRootSpan:r,toggleChildren:s,expandAllDescendants:a,collapseAllDescendants:i,collapseAll:l,totalDescendants:c=0,allDescendantsExpanded:u,numOfChildren:d=0,toggleSiblings:f,siblingsAllExpanded:p,siblingsWithChildrenCount:h=0}){const m=n?`Collapse children (${d})`:`Expand children (${d})`,g=!r&&!!d&&d>0,y=!r&&g&&c>d,b=!r&&h>=2,x=!!r&&!!d&&d>0,S=!!n&&!!u;return o.jsx("div",{className:X("flex h-full items-center justify-end px-1.5",{"opacity-30 [&:hover]:opacity-60":t,"bg-surface4":e}),children:o.jsxs("div",{className:"grid grid-cols-[1.625rem_1.625rem_1.625rem] gap-1",children:[o.jsx("div",{children:g&&o.jsx(Ez,{onClick:()=>s?.(),tooltip:m,children:n?o.jsx($Cn,{}):o.jsx(fwe,{})})}),o.jsx("div",{children:y&&o.jsx(Ez,{onClick:()=>u?i?.():a?.(),tooltip:u?`Collapse all descendants (${c})`:`Expand all descendants (${c})`,children:u?o.jsx(qCn,{}):o.jsx(LCn,{})})}),o.jsxs("div",{children:[b&&o.jsx(Ez,{onClick:()=>f?.(),tooltip:p?"Collapse at this level":"Expand at this level",children:p?o.jsx(TEn,{}):o.jsx(Ijn,{})}),x&&o.jsx(Ez,{onClick:()=>S?l?.():a?.(),tooltip:S?"Collapse all":"Expand all",children:S?o.jsx(hwe,{}):o.jsx(Qq,{})})]})]})})}function Ez({onClick:e,children:t,className:n,tooltip:r}){return o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:o.jsx("button",{onClick:e,className:X("h-full shrink-0 cursor-pointer",n),"aria-label":r,children:o.jsx("div",{className:X("flex items-center gap-[0.1rem] rounded-md p-1 transition-all","hover:bg-surface5","[&:hover>svg]:opacity-100 [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:opacity-50 [&>svg]:transition-all"),children:t})})}),r&&o.jsx(Rn,{children:r})]})}function trs({isLastChild:e}){return o.jsx("div",{className:X("relative h-[1.8rem] w-2 shrink-0 opacity-100",'after:absolute after:inset-y-0 after:-left-px after:w-0 after:border-l-[1px] after:border-dashed after:border-neutral3 after:content-[""] ','before:absolute before:top-[50%] before:left-0 before:h-0 before:w-full before:border-b-[1px] before:border-dashed before:border-neutral3 before:content-[""]',{"after:bottom-[50%]":e})})}function nrs({span:e,spanUI:t,isFaded:n,depth:r=0,onSpanClick:s,selectedSpanId:a,isLastChild:i,hasChildren:l,isRootSpan:c,isExpanded:u}){return o.jsxs("div",{"data-span-id":e.id,"aria-label":`View details for span ${e.name}`,className:X("flex min-h-8 items-center rounded-md rounded-l-lg opacity-80",{"opacity-30 [&:hover]:opacity-60":n,"bg-surface4":a===e.id}),style:{paddingLeft:`${r*1}rem`},children:[!c&&o.jsx(trs,{isLastChild:i}),o.jsxs("button",{onClick:()=>s?.(e.id),className:X("flex size-full min-w-0 items-center gap-1.5 rounded-md px-2 py-1 text-left text-ui-smd text-neutral6 transition-colors","[&>svg]:ml-auto [&>svg]:size-[1em] [&>svg]:shrink-0 [&>svg]:opacity-0 [&>svg]:transition-all","hover:bg-surface4 [&:hover>svg]:opacity-60","focus:outline-none focus-visible:ring-1 focus-visible:ring-accent1 focus-visible:ring-inset"),children:[t?.color&&o.jsx("span",{"aria-hidden":!0,title:t.label,className:"inline-block size-2 shrink-0 rounded-full",style:{backgroundColor:t.color}}),o.jsx("span",{className:"min-w-0 truncate",children:e.name})]})]})}function rrs({span:e,selectedSpanId:t,isFaded:n,overallLatency:r,overallStartTime:s,color:a,chartWidth:i="default"}){const l=r?Math.ceil(e.latency/r*100):0,c=s?new Date(s):null,u=e.startTime?new Date(e.startTime):null,d=u&&c?u.getTime()-c.getTime():0,f=r&&Math.floor(d/r*100);return o.jsxs(LI,{children:[o.jsxs(rC,{className:X("grid h-8 cursor-help grid-cols-[1fr_auto] items-center gap-2 rounded-r-md p-1 pr-2",i==="wide"?"min-w-72":"min-w-32","[&:hover>div]:bg-surface5",{"opacity-30 [&:hover]:opacity-60":n,"bg-surface4":t===e.id}),children:[o.jsx("div",{className:X("w-full rounded-md bg-surface4 p-1.5 transition-colors duration-1000"),children:o.jsx("div",{className:"relative h-1.5 w-full overflow-hidden rounded-sm",children:o.jsx("div",{className:X("absolute top-0 h-1.5 rounded-sm bg-neutral1"),style:{width:l?`${l}%`:"2px",left:`${f||0}%`,backgroundColor:a}})})}),o.jsxs("div",{className:X("flex justify-end text-ui-xs text-neutral3"),children:[(e.latency/1e3).toFixed(3)," s"]})]}),o.jsxs(sC,{className:"bg-surface4 pr-6",children:[o.jsx("div",{className:X("mt-1 mb-2 flex items-center gap-2 text-ui-sm"),children:"Span Timing"}),o.jsxs(Ut,{children:[o.jsx(Ut.Key,{children:"Latency"}),o.jsxs(Ut.Value,{children:[e.latency," ms"]}),o.jsx(Ut.Key,{children:"Started at"}),o.jsx(Ut.Value,{children:e.startTime?nr(new Date(e.startTime),"hh:mm:ss:SSS a"):"-"}),o.jsx(Ut.Key,{children:"Ended at"}),o.jsx(Ut.Value,{children:e.endTime?nr(new Date(e.endTime),"hh:mm:ss:SSS a"):"-"}),o.jsx(Ut.Key,{children:"Start Shift"}),o.jsxs(Ut.Value,{children:[d,"ms"]})]})]})]})}function G9t({span:e,siblings:t,depth:n=0,onSpanClick:r,selectedSpanId:s,isLastChild:a,overallLatency:i,overallStartTime:l,fadedTypes:c,searchPhrase:u,featuredSpanIds:d,expandedSpanIds:f,setExpandedSpanIds:p,chartWidth:h}){const m=e.spans&&e.spans.length>0,g=e.spans?e.spans.length:0,y=LV(e),b=y.length,x=n===0,S=Z9t(e?.type),k=f?f.includes(e.id):!1,_=d&&d.length>0?!d.includes(e.id):!1,E=(c&&c.length>0?c.includes(S?.typePrefix||""):!1)||_;v.useEffect(()=>{if(!d||y.length===0||k)return;y.some(z=>d.includes(z))&&p&&p(z=>!z||z.includes(e.id)?z??[e.id]:[...z,e.id])},[d,y]);const j=()=>{p&&p(F=>F&&(k?F.filter(z=>z!==e.id):[...F,e.id]))},N=()=>{p&&p(F=>F&&Array.from(new Set([...F,e.id,...y])))},I=()=>{p&&p(F=>{if(!F)return F;const z=new Set(y);return F.filter(q=>!z.has(q))})},A=()=>{p&&p(F=>{if(!F)return F;const z=new Set([e.id,...y]);return F.filter(q=>!z.has(q))})},R=y.every(F=>f?.includes(F)),L=(t??[]).filter(F=>F.spans&&F.spans.length>0),D=L.length,B=D>0&&L.every(F=>f?.includes(F.id)),H=()=>{!p||D===0||p(F=>{if(!F)return F;if(B){const z=new Set;return L.forEach(q=>{z.add(q.id),LV(q).forEach(M=>z.add(M))}),F.filter(q=>!z.has(q))}return Array.from(new Set([...F,...L.map(z=>z.id)]))})};return o.jsxs(o.Fragment,{children:[o.jsx(nrs,{span:e,spanUI:S,isFaded:E,depth:n,onSpanClick:r,selectedSpanId:s,isLastChild:a,hasChildren:m,isRootSpan:x,isExpanded:k}),o.jsx(ers,{isSelected:s===e.id,isFaded:E,isExpanded:k,isRootSpan:x,toggleChildren:j,expandAllDescendants:N,collapseAllDescendants:I,collapseAll:A,totalDescendants:b,allDescendantsExpanded:R,numOfChildren:g,toggleSiblings:H,siblingsAllExpanded:B,siblingsWithChildrenCount:D}),o.jsx(rrs,{span:e,selectedSpanId:s,isFaded:E,overallLatency:i,overallStartTime:l,color:S?.color,chartWidth:h}),m&&k&&e.spans?.map((F,z,q)=>{const M=z===q.length-1;return o.jsx(G9t,{span:F,siblings:q,depth:n+1,onSpanClick:r,selectedSpanId:s,isLastChild:M,overallLatency:i,overallStartTime:l,fadedTypes:c,searchPhrase:u,expandedSpanIds:f,setExpandedSpanIds:p,featuredSpanIds:d,chartWidth:h},F.id)})]})}function Q9t({hierarchicalSpans:e=[],onSpanClick:t,selectedSpanId:n,isLoading:r,fadedTypes:s,expandedSpanIds:a,setExpandedSpanIds:i,featuredSpanIds:l,chartWidth:c="default"}){const u=e?.[0]?.latency||0,d=e?.[0]?.startTime||"",f=v.useMemo(()=>{const p=y=>{const b=new Set;for(const x of y){const S=x.type?.toLowerCase().split("_")[0];if(S&&b.add(S),x.spans)for(const k of p(x.spans))b.add(k)}return b},h=p(e),m=[...h].some(y=>!GKe.includes(y)),g=GKe.filter(y=>y!=="other"&&h.has(y));return m&&g.push("other"),g},[e]);return o.jsx(o.Fragment,{children:r?o.jsxs("div",{className:X("flex items-center justify-center gap-3 rounded-md bg-surface3/50 p-3 text-ui-sm text-neutral3","[&_svg]:size-[1.25em] [&_svg]:opacity-50"),children:[o.jsx(Xt,{})," Loading Trace Timeline ..."]}):o.jsxs(o.Fragment,{children:[f.length>0&&o.jsx("div",{className:"flex flex-wrap justify-end gap-3 px-2 py-1.5",children:f.map(p=>{const h=Z9t(p);return o.jsxs("div",{className:"text-ui-sm text-neutral3 flex items-center gap-1",children:[o.jsx("span",{className:"inline-block size-1.5 shrink-0 rounded-full",style:{backgroundColor:h?.color}}),h?.label||p]},p)})}),o.jsx("div",{className:"grid grid-cols-[minmax(0,1fr)_auto_auto] content-start items-start gap-y-px overflow-hidden py-1",children:e?.map(p=>o.jsx(G9t,{span:p,siblings:e,onSpanClick:t,selectedSpanId:n,overallLatency:u,overallStartTime:d,fadedTypes:s,featuredSpanIds:l,expandedSpanIds:a,setExpandedSpanIds:i,chartWidth:c},p.id))})]})})}function eIe({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,onEvaluateTrace:a,onSaveAsDatasetItem:i,onAddTraceMocksToItem:l,initialSpanId:c,onPrevious:u,onNext:d,collapsed:f,onCollapsedChange:p,placement:h,timelineChartWidth:m="default",LinkComponent:g,traceHref:y,anchorSpanId:b,showUnavailableFeaturesMsg:x=!0}){const S=h==="trace-page",[k,_]=v.useState(!1),C=f??k,E=p??_,{download:j,isPending:N}=Yns(),I=v.useRef(null),[A,R]=v.useState(c??void 0);v.useEffect(()=>{if(!c){R(void 0),s?.(void 0);return}if(!t)return;t.find(G=>G.spanId===c)?(R(c),s?.(c)):(R(void 0),s?.(void 0))},[c,t]),v.useEffect(()=>{if(!A||!I.current)return;I.current.querySelector(`[data-span-id="${A}"]`)?.scrollIntoView({block:"nearest"})},[A]);const L=v.useMemo(()=>JNe(t??[],b),[t,b]),[D,B]=v.useState([]);v.useEffect(()=>{L.length>0&&B(XNe(L))},[L]);const H=v.useMemo(()=>b?t?.find(M=>M.spanId===b):t?.find(M=>M.parentSpanId==null),[t,b]),F=M=>{const G=A===M?void 0:M;R(G),s?.(G)},z=!S&&g&&y,q=o.jsx(ce,{size:"md",tooltip:"Download trace JSON","aria-label":"Download trace JSON",disabled:N,onClick:()=>j(e),children:N?o.jsx(Xmt,{className:"animate-spin"}):o.jsx(cEn,{})});return o.jsxs(xn,{collapsed:C,children:[o.jsx(xn.Header,{children:S?o.jsxs(o.Fragment,{children:[o.jsx(xn.Heading,{children:"Trace Timeline"}),o.jsx(Mr,{className:"ml-auto shrink-0",children:q})]}):o.jsxs(o.Fragment,{children:[o.jsxs(xn.Heading,{children:["Trace ",o.jsxs("b",{children:["# ",ky(e,12)]})]}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[p&&o.jsx(ce,{size:"md",tooltip:C?"Expand panel":"Collapse panel",onClick:()=>E(!C),children:C?o.jsx(Qq,{}):o.jsx(hwe,{})}),(u||d)&&o.jsx(xn.NextPrevNav,{onPrevious:u,onNext:d,previousLabel:"Previous trace",nextLabel:"Next trace"}),z&&o.jsx(ce,{as:g,href:y,size:"md",tooltip:"Open trace page","aria-label":"Open trace page",children:o.jsx(Kmt,{})}),q,o.jsx(xn.CloseButton,{onClick:r})]})]})}),!C&&(n?o.jsx(xn.LoadingData,{children:"Loading trace..."}):L.length===0?o.jsx(xn.NoData,{children:"No spans found for this trace."}):o.jsxs(xn.Content,{ref:I,children:[!S&&H&&o.jsx(H9t,{rootSpan:H,className:"mb-6"}),!S&&(a||i||l)&&o.jsxs("div",{className:"mb-6 flex flex-wrap items-center justify-between gap-4",children:[a&&o.jsxs(ce,{size:"sm",onClick:a,children:[o.jsx(qe,{children:o.jsx(GCn,{})}),"Evaluate Trace"]}),i&&o.jsxs(ce,{size:"sm",onClick:()=>i({traceId:e,rootSpanId:H?.spanId}),children:[o.jsx(qe,{children:o.jsx(Jmt,{})}),"Save as Dataset Item"]}),l&&o.jsxs(ce,{size:"sm",onClick:()=>l({traceId:e}),children:[o.jsx(qe,{children:o.jsx($jn,{})}),"Add tool mocks to item"]})]}),!S&&!a&&!i&&!l&&x&&o.jsx(En,{variant:"info",className:"mb-6",children:o.jsx(En.Message,{children:"Evaluating traces and saving them as dataset items is available in Mastra Studio (local or deployed)."})}),o.jsx(Q9t,{hierarchicalSpans:L,onSpanClick:F,selectedSpanId:A,expandedSpanIds:D,setExpandedSpanIds:B,chartWidth:m})]}))]})}function Y9t({error:e,resource:t,errorTitle:n}){if(ys(e))return o.jsx(Hs,{});if(xs(e))return o.jsx(Ms,{resource:t});const r=e instanceof Error?lEr(e):void 0;return o.jsx(qi,{title:n,message:r?.error??"Unknown error"})}function srs({listSlot:e,tracePanelSlot:t,spanPanelSlot:n,scorePanelSlot:r,traceCollapsed:s}){const a=!!t;return o.jsxs("div",{className:X("grid max-h-full min-h-0 items-start gap-4 ",a?"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[e,a&&o.jsxs("div",{className:X("grid max-h-full gap-4 overflow-auto",r?s?"grid-rows-[auto_3fr_3fr]":"grid-rows-[2fr_3fr_3fr]":n?s?"grid-rows-[auto_3fr]":"grid-rows-[2fr_3fr]":s?"grid-rows-[auto]":"grid-rows-[1fr]"),children:[t,n,r]})]})}function ars(e,t,n){const r=new Array(e);return new Proxy(r,{get(s,a,i){if(typeof a=="string"){const l=a.charCodeAt(0);if(l>=48&&l<=57){const c=+a;if(Number.isInteger(c)&&c>=0&&c<e){let u=s[c];if(!u){const d=t[c*2];u=s[c]={index:c,key:n(c),start:d,size:t[c*2+1],end:d+t[c*2+1],lane:0}}return u}}if(a==="length")return e}return Reflect.get(s,a,i)}})}function EE(e,t,n){let r=n.initialDeps??[],s,a=!0;function i(){const l=e();return(l.length!==r.length||l.some((u,d)=>r[d]!==u))&&(r=l,s=t(...l),n?.onChange&&!(a&&n.skipInitialOnChange)&&n.onChange(s),a=!1),s}return i.updateDeps=l=>{r=l},i}function QKe(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const irs=(e,t)=>Math.abs(e-t)<1.01,ors=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}};let sP;const pae=()=>{if(sP!==void 0)return sP;if(typeof navigator>"u")return sP=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return sP=!0;const e=navigator.maxTouchPoints;return sP=navigator.platform==="MacIntel"&&e!==void 0&&e>0},YKe=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},lrs=e=>e,crs=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,s=new Array(r);for(let a=0;a<r;a++)s[a]=t+a;return s},urs=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const s=i=>{const{width:l,height:c}=i;t({width:Math.round(l),height:Math.round(c)})};if(s(YKe(n)),!r.ResizeObserver)return()=>{};const a=new r.ResizeObserver(i=>{const l=()=>{const c=i[0];if(c?.borderBoxSize){const u=c.borderBoxSize[0];if(u){s({width:u.inlineSize,height:u.blockSize});return}}s(YKe(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return a.observe(n,{box:"border-box"}),()=>{a.unobserve(n)}},FV={passive:!0},drs=typeof window>"u"?!0:"onscrollend"in window,frs=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const s=e.targetWindow;if(!s)return;const a=e.options.useScrollendEvent&&drs;let i=0;const l=a?null:ors(s,()=>t(i,!1),e.options.isScrollingResetDelay),c=f=>()=>{i=n(r),l?.(),t(i,f)},u=c(!0),d=c(!1);return r.addEventListener("scroll",u,FV),a&&r.addEventListener("scrollend",d,FV),()=>{r.removeEventListener("scroll",u),a&&r.removeEventListener("scrollend",d)}},prs=(e,t)=>frs(e,t,n=>{const{horizontal:r,isRtl:s}=e.options;return r?n.scrollLeft*(s&&-1||1):n.scrollTop}),hrs=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),s=n.options.getItemKey(r);return n.itemSizeCache.get(s)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),s=n.options.getItemKey(r),a=n.itemSizeCache.get(s);if(a!==void 0)return a}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},mrs=(e,{adjustments:t=0,behavior:n},r)=>{var s,a;(a=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||a.call(s,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},grs=mrs;class vrs{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,s;return((s=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:s.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(s=>{s.forEach(a=>{const i=()=>{const l=a.target,c=this.indexFromElement(l);if(!l.isConnected){this.observer.unobserve(l);for(const[u,d]of this.elementsCache)if(d===l){this.elementsCache.delete(u);break}return}this.shouldMeasureDuringScroll(c)&&this.resizeItem(c,this.options.measureElement(l,a,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var s;(s=r())==null||s.disconnect(),n=null},observe:s=>{var a;return(a=r())==null?void 0:a.observe(s,{box:"border-box"})},unobserve:s=>{var a;return(a=r())==null?void 0:a.unobserve(s)}}})(),this.range=null,this.setOptions=n=>{var r,s;const a={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:lrs,rangeExtractor:crs,onChange:()=>{},measureElement:hrs,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const p in n){const h=n[p];h!==void 0&&(a[p]=h)}const i=this.options;let l=null,c=null,u=!1;if(i!==void 0&&i.enabled&&a.enabled&&a.anchorTo==="end"&&this.scrollElement!==null){const p=i.count,h=a.count,m=this.getMeasurements(),g=p>0?((r=m[0])==null?void 0:r.key)??i.getItemKey(0):null,y=p>0?((s=m[p-1])==null?void 0:s.key)??i.getItemKey(p-1):null;if(h!==p||p>0&&h>0&&(a.getItemKey(0)!==g||a.getItemKey(h-1)!==y)){u=!0;const S=p>0?this.getVirtualItemForOffset(this.getScrollOffset())??m[0]:null;S&&(l=[S.key,this.getScrollOffset()-S.start]);const k=a.followOnAppend===!0?"auto":a.followOnAppend||null;k&&h>p&&this.isAtEnd(i.scrollEndThreshold)&&(p===0||a.getItemKey(h-1)!==y)&&(c=k)}}this.options=a,u&&(this.pendingMin=0,this.itemSizeCacheVersion++);let d=!1,f=0;if(l&&this.scrollOffset!==null){const[p,h]=l,m=this.getMeasurements(),{count:g,getItemKey:y}=this.options;let b=0;for(;b<g&&y(b)!==p;)b++;if(b<g){const x=m[b];if(x){const S=x.start+h;S!==this.scrollOffset&&(f=S-this.scrollOffset,this.scrollOffset=S,d=!0)}}}(d||c)&&(this.pendingScrollAnchor=[d?l[0]:null,d?l[1]:0,c,f])},this.notify=n=>{var r,s;(s=(r=this.options).onChange)==null||s.call(r,this,n)},this.maybeNotify=EE(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(a=>{this.observer.observe(a)}),this.unsubs.push(this.options.observeElementRect(this,a=>{this.scrollRect=a,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(a,i)=>{if(i&&this._intendedScrollOffset===null&&a===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(a-this._intendedScrollOffset)<1.5&&(a=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const l=this.getScrollOffset();this.scrollDirection=i?l===a?this.scrollDirection:l<a?"forward":"backward":null,this.scrollOffset=a,this.isScrolling=i,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const a=this.scrollElement,i=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},l=()=>{this._iosTouching=!1,!(!pae()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};a.addEventListener("touchstart",i,FV),a.addEventListener("touchend",l,FV),this.unsubs.push(()=>{a.removeEventListener("touchstart",i),a.removeEventListener("touchend",l),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const s=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,s&&this.scrollElement&&this.options.enabled){const[a,i,l,c]=s;a!==null&&!l&&(pae()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?c!==0&&(this._iosDeferredAdjustment+=c):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),l&&this.scrollToEnd({behavior:l})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const s=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=s,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(n,r)=>{const s=new Map,a=new Map;for(let i=r-1;i>=0;i--){const l=n[i];if(s.has(l.lane))continue;const c=a.get(l.lane);if(c==null||l.end>c.end?a.set(l.lane,l):l.end<c.end&&s.set(l.lane,!0),s.size===this.options.lanes)break}return a.size===this.options.lanes?Array.from(a.values()).sort((i,l)=>i.end===l.end?i.index-l.index:i.end-l.end)[0]:void 0},this.getMeasurementOptions=EE(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(n,r,s,a,i,l,c)=>(this.prevLanes!==void 0&&this.prevLanes!==l&&(this.lanesChangedFlag=!0),this.prevLanes=l,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:s,getItemKey:a,enabled:i,lanes:l,laneAssignmentMode:c}),{key:!1}),this.getMeasurements=EE(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:s,getItemKey:a,enabled:i,lanes:l,laneAssignmentMode:c},u)=>{const d=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const m of this.laneAssignments.keys())m>=n&&this.laneAssignments.delete(m);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(m=>{this.itemSizeCache.set(m.key,m.size)}));const f=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),l===1){const m=this.options.gap,g=n*2;let y=this._flatMeasurements;if(!y||y.length<g){const S=new Float64Array(g);y&&f>0&&S.set(y.subarray(0,f*2)),y=S,this._flatMeasurements=y}let b;if(f===0)b=r+s;else{const S=f-1;b=y[S*2]+y[S*2+1]+m}for(let S=f;S<n;S++){const k=a(S),_=d.get(k),C=typeof _=="number"?_:this.options.estimateSize(S);y[S*2]=b,y[S*2+1]=C,b+=C+m}const x=ars(n,y,a);return this.measurementsCache=x,x}const p=this.measurementsCache.slice(0,f),h=new Array(l).fill(void 0);for(let m=0;m<f;m++){const g=p[m];g&&(h[g.lane]=m)}for(let m=f;m<n;m++){const g=a(m),y=this.laneAssignments.get(m);let b,x;const S=c==="estimate"||d.has(g);if(y!==void 0&&this.options.lanes>1){b=y;const E=h[b],j=E!==void 0?p[E]:void 0;x=j?j.end+this.options.gap:r+s}else{const E=this.options.lanes===1?p[m-1]:this.getFurthestMeasurement(p,m);x=E?E.end+this.options.gap:r+s,b=E?E.lane:m%this.options.lanes,this.options.lanes>1&&S&&this.laneAssignments.set(m,b)}const k=d.get(g),_=typeof k=="number"?k:this.options.estimateSize(m),C=x+_;p[m]={index:m,start:x,size:_,end:C,key:g,lane:b},h[b]=m}return this.measurementsCache=p,p},{key:!1,debug:()=>this.options.debug}),this.calculateRange=EE(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,a)=>n.length===0||r===0?(this.range=null,null):(this.range=brs(n,r,s,a,a===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=EE(()=>{let n=null,r=null;const s=this.calculateRange();return s&&(n=s.startIndex,r=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,s,a,i)=>a===null||i===null?[]:n({startIndex:a,endIndex:i,overscan:r,count:s}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,s=n.getAttribute(r);return s?parseInt(s,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const s=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(s!==void 0&&this.range){const a=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,s-a),l=Math.min(this.options.count-1,s+a);return n>=i&&n<=l}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((i,l)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(l))});return}const r=this.indexFromElement(n),s=this.options.getItemKey(r),a=this.elementsCache.get(s);a!==n&&(a&&this.observer.unobserve(a),this.observer.observe(n),this.elementsCache.set(s,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var s,a;if(n<0||n>=this.options.count)return;let i,l,c;const u=this._flatMeasurements;if(this.options.lanes===1&&u!==null)c=this.options.getItemKey(n),l=u[n*2],i=u[n*2+1];else{const p=this.measurementsCache[n];if(!p)return;c=p.key,l=p.start,i=p.size}const d=this.itemSizeCache.get(c)??i,f=r-d;if(f!==0){const p=this.options.anchorTo==="end"&&((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,h=p?this.getTotalSize():0,m=((a=this.scrollState)==null?void 0:a.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:c,start:l,size:i,end:l+i,lane:0},f,this):l<this.getScrollOffset()+this.scrollAdjustments&&(!this.itemSizeCache.has(c)||this.scrollDirection!=="backward"));(this.pendingMin===null||n<this.pendingMin)&&(this.pendingMin=n),this.itemSizeCache.set(c,r),this.itemSizeCacheVersion++,p?this.applyScrollAdjustment(this.getTotalSize()-h):m&&this.applyScrollAdjustment(f),this.notify(!1)}},this.getVirtualItems=EE(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let a=0,i=n.length;a<i;a++){const l=n[a],c=r[l];s.push(c)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const s=this._flatMeasurements,a=this.options.lanes===1&&s!=null,i=K9t(0,r.length-1,a?l=>s[l*2]:l=>QKe(r[l]).start,n);return QKe(r[i])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,s=0)=>{if(!this.scrollElement)return 0;const a=this.getSize(),i=this.getScrollOffset();r==="auto"&&(r=n>=i+a?"end":"start"),r==="center"?n+=(s-a)/2:r==="end"&&(n-=a);const l=this.getMaxScrollOffset();return Math.max(Math.min(l,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const s=this.getSize(),a=this.getScrollOffset(),i=this.measurementsCache[n];if(!i)return;if(r==="auto")if(i.end>=a+s-this.options.scrollPaddingEnd)r="end";else if(i.start<=a+this.options.scrollPaddingStart)r="start";else return[a,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const l=r==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,r,i.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:s="auto"}={})=>{const a=this.getOffsetForAlignment(n,r),i=this.now();this.scrollState={index:null,align:r,behavior:s,startedAt:i,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:s="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const a=this.getOffsetForIndex(n,r);if(!a)return;const[i,l]=a,c=this.now();this.scrollState={index:n,align:l,behavior:s,startedAt:c,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const s=this.getScrollOffset()+n,a=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:a,lastTargetOffset:s,stableFrames:0},this._scrollToOffset(s,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let s;if(r.length===0)s=this.options.paddingStart;else if(this.options.lanes===1){const a=r.length-1,i=this._flatMeasurements;i!=null?s=i[a*2]+i[a*2+1]:s=((n=r[a])==null?void 0:n.end)??0}else{const a=Array(this.options.lanes).fill(null);let i=r.length-1;for(;i>=0&&a.some(l=>l===null);){const l=r[i];a[l.lane]===null&&(a[l.lane]=l.end),i--}s=Math.max(...a.filter(l=>l!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const s of r)s&&this.itemSizeCache.has(s.key)&&n.push({index:s.index,key:s.key,start:s.start,size:s.size,end:s.end,lane:s.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:s})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:s,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(pae()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,s=r?r[0]:this.scrollState.lastTargetOffset,a=1,i=s!==this.scrollState.lastTargetOffset;if(!i&&irs(s,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=a){this.getScrollOffset()!==s&&this._scrollToOffset(s,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,i){const l=this.getSize()||600,c=Math.abs(s-this.getScrollOffset()),u=this.scrollState.behavior==="smooth"&&c>l;this.scrollState.lastTargetOffset=s,u||(this.scrollState.behavior="auto"),this._scrollToOffset(s,{adjustments:void 0,behavior:u?"smooth":"auto"})}this.scheduleScrollReconcile()}}const K9t=(e,t,n,r)=>{for(;e<=t;){const s=(e+t)/2|0,a=n(s);if(a<r)e=s+1;else if(a>r)t=s-1;else return s}return e>0?e-1:0};function yrs(e,t,n){let r=0;for(;r<=t;){const s=(r+t)/2|0,a=e[s*2];if(a<n)r=s+1;else if(a>n)t=s-1;else return s}return r>0?r-1:0}function brs(e,t,n,r,s){const a=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:a};if(r===1&&s!==null){const u=yrs(s,a,n);let d=u;const f=n+t;for(;d<a&&s[d*2]+s[d*2+1]<f;)d++;return{startIndex:u,endIndex:d}}let l=K9t(0,a,u=>e[u].start,n),c=l;if(r===1)for(;c<a&&e[c].end<n+t;)c++;else if(r>1){const u=Array(r).fill(0);for(;c<a&&u.some(f=>f<n+t);){const f=e[c];u[f.lane]=f.end,c++}const d=Array(r).fill(n+t);for(;l>=0&&d.some(f=>f>=n);){const f=e[l];d[f.lane]=f.start,l--}l=Math.max(0,l-l%r),c=Math.min(a,c+(r-1-c%r))}return{startIndex:l,endIndex:c}}const hae=typeof document<"u"?v.useLayoutEffect:v.useEffect;function xrs({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const s=v.useReducer(u=>u+1,0)[1],a=v.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});a.current.enabled=t,a.current.mode=n;const i=u=>{const d=a.current;if(!d.enabled||!d.container)return;const f=u.getTotalSize();if(f!==d.lastSize){d.lastSize=f;const b=u.options.horizontal?"width":"height";d.container.style[b]=`${f}px`}const p=!!u.options.horizontal,h=d.mode==="transform",m=p?"left":"top",g=u.options.scrollMargin,y=u.getVirtualItems();for(const b of y){const x=b.start-g,S=u.elementsCache.get(b.key);S&&d.lastPositions.get(S)!==x&&(d.lastPositions.set(S,x),h?S.style.transform=p?`translate3d(${x}px, 0, 0)`:`translate3d(0, ${x}px, 0)`:S.style[m]=`${x}px`)}},l={...r,onChange:(u,d)=>{var f;const p=a.current;let h=!0;if(p.enabled){i(u);const m=u.range,g=p.prevRange;h=!g||g.isScrolling!==u.isScrolling||g.startIndex!==m?.startIndex||g.endIndex!==m?.endIndex,h&&(p.prevRange=m?{startIndex:m.startIndex,endIndex:m.endIndex,isScrolling:u.isScrolling}:null)}h&&(e&&d?Ti.flushSync(s):s()),(f=r.onChange)==null||f.call(r,u,d)}},[c]=v.useState(()=>{const u=new vrs(l);return Object.assign(u,{containerRef:d=>{const f=a.current;if(f.container=d,f.lastSize=null,d&&f.enabled){const p=u.getTotalSize();f.lastSize=p;const h=u.options.horizontal?"width":"height";d.style[h]=`${p}px`}}})});return c.setOptions(l),hae(()=>c._didMount(),[]),hae(()=>c._willUpdate()),hae(()=>{i(c)}),c}function X9t(e){return xrs({observeElementRect:urs,observeElementOffset:prs,scrollToFn:grs,...e})}const KKe="6rem 9rem 14rem minmax(8rem,1fr) 14rem 6rem",wrs=36,Srs=8;function krs({traces:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,filtersApplied:a,featuredTraceId:i,featuredSpanId:l,isBranchesMode:c,recentlyAddedKeys:u,onTraceClick:d}){const f=v.useRef(null),p=X9t({count:e.length,getScrollElement:()=>f.current,estimateSize:()=>wrs,overscan:Srs}),h=v.useRef(t);if(v.useEffect(()=>{h.current&&!t&&f.current?.dispatchEvent(new Event("scroll")),h.current=t},[t]),t)return o.jsx(ol,{columns:KKe});const m=p.getVirtualItems(),g=p.getTotalSize(),y=m[0]?.start??0,b=m.length>0?Math.max(0,g-(m[m.length-1]?.end??0)):0;return o.jsxs(Zl,{columns:KKe,variant:"striped",scrollRef:f,className:"min-w-0",children:[o.jsxs(Zl.Top,{children:[o.jsx(Zl.TopCell,{children:"Date"}),o.jsx(Zl.TopCell,{children:"Time"}),o.jsx(Zl.TopCell,{children:"Name"}),o.jsx(Zl.TopCell,{children:"Input"}),o.jsx(Zl.TopCell,{children:"Entity"}),o.jsx(Zl.TopCell,{children:"Status"})]}),e.length===0?o.jsx(Zl.NoMatch,{message:a?"No traces found for applied filters":"No traces found yet"}):o.jsxs(o.Fragment,{children:[o.jsx(Zl.Spacer,{height:y}),m.map(x=>{const S=e[x.index];if(!S)return null;const k=S.traceId===i&&(l==null||S.spanId===l),_=`${S.traceId}:${S.spanId??""}`,C=u?.has(_)??!1,E=S.startedAt??S.createdAt,j=S.entityName||S.entityId||S.attributes?.agentId||S.attributes?.workflowId;return o.jsxs(Zl.RowButton,{ref:p.measureElement,"data-index":x.index,onClick:()=>d(S),featured:k,className:X(C&&"animate-row-highlight"),children:[o.jsx(Zl.DateCell,{timestamp:E}),o.jsx(Zl.TimeCell,{timestamp:E}),o.jsx(Zl.NameCell,{name:S.name,parentSpanId:S.parentSpanId,showLevelTooltip:c}),o.jsx(Zl.InputCell,{input:Uns(S.input)}),o.jsx(Zl.EntityCell,{entityType:S.entityType,entityName:j}),o.jsx(Zl.StatusCell,{status:S.attributes?.status})]},_)}),o.jsx(Zl.Spacer,{height:b}),o.jsx(Zl.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})]})}function Ors({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c,lockedFieldIds:u,lockedTooltipContent:d}){const f=i.length>0,p=new Set(u??[]),h=i.filter(y=>!p.has(y.fieldId)),m=h.some(y=>_rs(y,a)),g=h.length>0;return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] items-start gap-3 "),children:[o.jsx(QNe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c,lockedFieldIds:u,lockedTooltipContent:d}),f&&g&&o.jsx(ZNe,{disabled:s,onClear:m?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function _rs(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 jz={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},tIe=[{label:"Agent",entityType:jz.AGENT},{label:"Workflow",entityType:jz.WORKFLOW},{label:"Scorer",entityType:jz.SCORER},{label:"Ingest",entityType:jz.INGEST}],Crs=[{label:"Running",value:"running"},{label:"Success",value:"success"},{label:"Error",value:"error"}],Dx="rootEntityType",Lx="status",kw="listMode",a9="anchorSpanId",Ers=new Set(["traces","branches"]),Ow="datePreset",_w="dateFrom",Cw="dateTo",jrs=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),Tl={tags:"filterTags",entityId:"filterEntityId",entityName:"filterEntityName",traceId:"filterTraceId",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId"},_L=Object.keys(Tl),Trs=new Set(["running","success","error"]),nIe="mastra:traces:saved-filters";function Nrs(e,t=nIe){const n=$rs(e),r=e.get(Ow);r&&n.set(Ow,r);const s=e.get(_w);s&&n.set(_w,s);const a=e.get(Cw);a&&n.set(Cw,a);try{localStorage.setItem(t,n.toString())}catch{}}function Irs(e=nIe){try{localStorage.removeItem(e)}catch{}}function XKe(e=nIe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function Ars(e){if(e.has(Ow)||e.has(_w)||e.has(Cw)||e.has(Dx)||e.has(Lx)||e.has(kw))return!0;for(const t of _L)if(e.has(Tl[t]))return!0;return!1}function Rrs({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:tIe.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:"status",label:"Status",kind:"pick-multi",searchable:!1,options:Crs.map(u=>({label:u.label,value:u.value})),placeholder:"Choose status",emptyText:"No statuses."},{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:"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 Prs(e){const t=[],n=new Map([[Dx,"rootEntityType"],[Lx,"status"]]);for(const s of _L)n.set(Tl[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}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function $rs(e){const t=new URLSearchParams,n=e.get(Dx);n&&t.set(Dx,n);const r=e.get(Lx);r&&t.set(Lx,r);const s=e.get(kw);s&&t.set(kw,s);for(const a of _L){const i=Tl[a];if(a==="tags"){for(const c of e.getAll(i))t.append(i,c);continue}const l=e.get(i);l&&t.set(i,l)}return t}function Mrs(e,t){e.delete(Dx),e.delete(Lx);for(const n of _L)e.delete(Tl[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(Dx,n.value);continue}if(n.fieldId==="status"&&typeof n.value=="string"){e.set(Lx,n.value);continue}const r=Tl[n.fieldId];if(r){if(n.fieldId==="tags"&&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 Drs({rootEntityType:e,status:t,dateFrom:n,dateTo:r,tokens:s}){const a={};e&&(a.entityType=e),t&&(a.status=t),n&&(a.startedAt={start:n}),r&&(a.endedAt={end:r});for(const i of s){if(i.fieldId==="tags"){Array.isArray(i.value)&&i.value.length>0?a.tags=i.value:typeof i.value=="string"&&i.value.trim()&&(a.tags=[i.value.trim()]);continue}if(typeof i.value=="string"&&i.value.trim()&&i.value!=="Any")switch(i.fieldId){case"entityId":a.entityId=i.value;break;case"entityName":a.entityName=i.value;break;case"traceId":a.traceId=i.value;break;case"runId":a.runId=i.value;break;case"threadId":a.threadId=i.value;break;case"sessionId":a.sessionId=i.value;break;case"requestId":a.requestId=i.value;break;case"resourceId":a.resourceId=i.value;break;case"userId":a.userId=i.value;break;case"organizationId":a.organizationId=i.value;break;case"serviceName":a.serviceName=i.value;break;case"environment":a.environment=i.value;break;case"experimentId":a.experimentId=i.value;break}}return a}function Lrs(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.omitAnyOption?n:r.multi?{fieldId:n.fieldId,value:[]}:{fieldId:n.fieldId,value:"Any"}:n:n})}const rIe=({entityType:e,rootOnly:t=!1}={})=>{const n=We();return yt({queryKey:e?["observability-entity-names","by-type",e]:["observability-entity-names","all",t?"root-only":"all-types"],queryFn:async()=>{try{if(e)return await n.getEntityNames({entityType:e});if(!t)return await n.getEntityNames();const s=await Promise.all(tIe.map(a=>n.getEntityNames({entityType:a.entityType})));return{names:Array.from(new Set(s.flatMap(a=>a?.names??[]))).sort()}}catch{return{names:[]}}},select:s=>s?.names??[],retry:!1})},sIe=()=>{const e=We();return yt({queryKey:["observability-environments"],queryFn:async()=>{try{return await e.getEnvironments()}catch{return{environments:[]}}},select:t=>t?.environments??[],retry:!1})},aIe=()=>{const e=We();return yt({queryKey:["observability-service-names"],queryFn:async()=>{try{return await e.getServiceNames()}catch{return{serviceNames:[]}}},select:t=>t?.serviceNames??[],retry:!1})},Frs=1e3*60*60*24*30;function CL(e,t){const n=We();return yt({queryKey:["span-detail",e,t],queryFn:async()=>{if(!e||!t)throw new Error("Trace ID and Span ID are required");return n.getSpan(e,t)},enabled:!!e&&!!t,staleTime:r=>r.state.data?.span?.endedAt?Frs:0})}const iIe=()=>{const e=We();return yt({queryKey:["observability-tags"],queryFn:async()=>{try{return await e.getTags()}catch{return{tags:[]}}},select:t=>t?.tags??[],retry:!1})},zrs="Trace filter settings saved.",Brs="Trace filter settings cleared.";function Urs(e,t,n){const{storageKey:r,messages:s,skipHydration:a}=n??{},[i,l]=v.useState(()=>XKe(r)!==null),c=v.useCallback(()=>{Nrs(e,r),l(!0);const f=s?.saved??zrs;f!==!1&&Le.success(f)},[e,r,s?.saved]),u=v.useCallback(()=>{Irs(r),l(!1);const f=s?.cleared??Brs;f!==!1&&Le.success(f)},[r,s?.cleared]),d=v.useRef(!1);return v.useEffect(()=>{if(a||d.current||(d.current=!0,Ars(e)))return;const f=XKe(r);f&&t(p=>{const h=new URLSearchParams(p);for(const[m,g]of f)h.append(m,g);return h},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function Vrs(e,t,n,r){const s=v.useMemo(()=>t?e.findIndex(u=>u.traceId===t&&(n==null||u.spanId===n)):-1,[e,t,n]),a=n!=null,i=u=>r(u.traceId,a?u.spanId??void 0:void 0),l=s>0?()=>{const u=e[s-1];u&&i(u)}:void 0,c=s>=0&&s<e.length-1?()=>{const u=e[s+1];u&&i(u)}:void 0;return{featuredTraceIdx:s,handlePreviousTrace:l,handleNextTrace:c}}const qrs=1e3*60*60*24*30;function Hrs({traceId:e,spanId:t,depth:n}){const r=We();return yt({queryKey:["branch",e,t,n],queryFn:async()=>{if(!e||!t)throw new Error("traceId and spanId are required");return r.getBranch({traceId:e,spanId:t,depth:n})},enabled:!!e&&!!t,staleTime:s=>s.state.data?.spans.every(l=>!!l.endedAt)?qrs:0})}const Wrs=1e3*60*60*24*30;function oIe(e){const t=We();return yt({queryKey:["trace-light-spans",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return await t.getTraceLight(e)},enabled:!!e,staleTime:n=>n.state.data?.spans.every(a=>!!a.endedAt)?Wrs:0})}function Zrs({traceId:e,anchorSpanId:t,listMode:n,depth:r}){const s=n==="branches",a=oIe(s?null:e),i=Hrs({traceId:s?e:null,spanId:s?t:null,depth:r});return s?{spans:i.data?.spans,anchorSpanId:t??void 0,isLoading:i.isLoading,isError:i.isError,error:i.error}:{spans:a.data?.spans,anchorSpanId:void 0,isLoading:a.isLoading,isError:a.isError,error:a.error}}function lIe(e,t,n){const r=v.useMemo(()=>XNe(JNe(e??[])),[e]),s=t?r.indexOf(t):-1,a=s>0?()=>{const l=r[s-1];l!==void 0&&n(l)}:void 0,i=s>=0&&s<r.length-1?()=>{const l=r[s+1];l!==void 0&&n(l)}:void 0;return{handlePreviousSpan:a,handleNextSpan:i,timelineSpanIds:r}}const i9="traceId",Ab="spanId",Sv="tab",kv="scoreId",aP=1440*60*1e3,Grs={"last-24h":aP,"last-3d":3*aP,"last-7d":7*aP,"last-14d":14*aP,"last-30d":30*aP};function iP(e){e.delete(i9),e.delete(Ab),e.delete(a9),e.delete(Sv),e.delete(kv)}function Qrs(e,t,n){const{onRemoveAll:r}={},s=v.useMemo(()=>{const F=e.get(Ow);return F&&jrs.has(F)?F:"last-24h"},[e]),a=e.get(_w),i=e.get(Cw),l=v.useMemo(()=>{if(s==="custom"){if(!a)return;const z=new Date(a);return Number.isNaN(z.getTime())?void 0:z}if(s==="all")return;const F=Grs[s];return F?new Date(Date.now()-F):void 0},[s,a]),c=v.useMemo(()=>{if(s!=="custom"||!i)return;const F=new Date(i);return Number.isNaN(F.getTime())?void 0:F},[s,i]),u=v.useRef(s);u.current=s;const d=e.get(i9)||void 0,f=e.get(Ab)||void 0,p=e.get(a9)||void 0,h=e.get(Sv),m=h==="scoring"?"scoring":h==="feedback"?"feedback":h==="details"?"details":void 0,g=e.get(kv)||void 0,y=v.useMemo(()=>{const F=e.get(kw);return F&&Ers.has(F)?F:"traces"},[e]),b=v.useMemo(()=>tIe.find(F=>F.entityType===e.get(Dx)),[e]),x=v.useMemo(()=>{const F=e.get(Lx);return F&&Trs.has(F)?F:void 0},[e]),S=v.useMemo(()=>Prs(e),[e]),k=v.useCallback((F,z,q)=>{t(M=>{const G=new URLSearchParams(M);return F?G.set(i9,F):G.delete(i9),z?G.set(Ab,z):G.delete(Ab),q?G.set(a9,q):G.delete(a9),G.delete(Sv),G.delete(kv),G},{replace:!0})},[t]),_=v.useCallback(()=>k(""),[k]),C=v.useCallback(F=>{const z=e.get(Ab)||null;F!==z&&t(q=>{const M=new URLSearchParams(q);return F?M.set(Ab,F):M.delete(Ab),M.delete(Sv),M.delete(kv),M},{replace:!0})},[e,t]),E=v.useCallback(()=>C(null),[C]),j=v.useCallback(F=>{const z=e.get(Sv)||null;F!==z&&t(q=>{const M=new URLSearchParams(q);return F&&F!=="details"?M.set(Sv,F):M.delete(Sv),M.delete(kv),M},{replace:!0})},[e,t]),N=v.useCallback((F,z)=>{const q=z&&z!=="details"?z:null;F===(e.get(Ab)||null)&&q===(e.get(Sv)||null)&&!e.get(kv)||t(G=>{const V=new URLSearchParams(G);return V.set(Ab,F),q?V.set(Sv,q):V.delete(Sv),V.delete(kv),V},{replace:!0})},[e,t]),I=v.useCallback(F=>{const z=e.get(kv)||null;F!==z&&t(q=>{const M=new URLSearchParams(q);return F?M.set(kv,F):M.delete(kv),M},{replace:!0})},[e,t]),A=v.useCallback(F=>{t(z=>{const q=new URLSearchParams(z);return Mrs(q,F),iP(q),q},{replace:!0})},[t]),R=A,L=v.useCallback((F,z)=>{if(u.current!=="custom")return;const q=z==="from"?_w:Cw;t(M=>{const G=new URLSearchParams(M);return F?G.set(q,F.toISOString()):G.delete(q),iP(G),G},{replace:!0})},[t]),D=v.useCallback(F=>{u.current=F,t(z=>{const q=new URLSearchParams(z);return F==="last-24h"?(q.delete(Ow),q.delete(_w),q.delete(Cw)):F==="custom"?q.set(Ow,"custom"):(q.set(Ow,F),q.delete(_w),q.delete(Cw)),iP(q),q},{replace:!0})},[t]),B=v.useCallback(F=>{t(z=>{const q=new URLSearchParams(z);return F==="traces"?q.delete(kw):q.set(kw,F),iP(q),q},{replace:!0})},[t]),H=v.useCallback(()=>{t(F=>{const z=new URLSearchParams(F);z.delete(kw),z.delete(Dx),z.delete(Lx);for(const q of _L)z.delete(Tl[q]);return iP(z),z},{replace:!0}),r?.()},[t,r]);return{searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,traceIdParam:d,spanIdParam:f,anchorSpanIdParam:p,spanTabParam:m,scoreIdParam:g,listMode:y,selectedEntityOption:b,selectedStatus:x,filterTokens:S,handleTraceClick:k,handleTraceClose:_,handleSpanChange:C,handleSpanClose:E,handleSpanTabChange:j,handleSpanChangeWithTab:N,handleScoreChange:I,handleListModeChange:B,handleFilterTokensChange:R,handleDateChange:L,handleDatePresetChange:D,handleRemoveAll:H,applyFilterTokens:A}}const mae=new WeakMap,G0={deltaPollIntervalMs:5e3,deltaChaseIntervalMs:100,deltaLimit:100,pageModeRefetchIntervalMs:1e4,page0StatusRefreshIntervalMs:6e4,idleGuardThresholdMs:15*6e4,minRefetchSpinMs:400,deltaHighlightMs:1e3};function Yrs(e,t,n){return e===0?!1:t-e>n}function Krs(e){return e?.status===501}const gae=async e=>{const{client:t,filters:n,listMode:r="traces"}=e,s=e.mode==="delta"?{mode:"delta",after:e.after,limit:e.limit,filters:n}:{pagination:{page:e.page,perPage:e.perPage},filters:n};return r==="branches"?t.listBranches(s):t.listTraces(s)},JKe=25;function Xrs(e,t,n){if(e?.pagination?.hasMore)return n+1}function Jrs(e){return"branches"in e?e.branches??[]:e.spans??[]}function ess(e){const t=new Set;return{spans:e.pages.flatMap(r=>Jrs(r)).filter(r=>{const s=`${r.traceId}:${r.spanId}`;return t.has(s)?!1:(t.add(s),!0)}),deltaCursor:e.pages[0]?.deltaCursor}}function tss(e,t,n){if(!e||e.pages.length===0)return e;const[r,...s]=e.pages;if(!r)return e;const a=n==="branches"&&"branches"in t?t.branches??[]:"spans"in t?t.spans??[]:[];if(a.length===0)return e;const i=new Map;for(const c of a)i.set(`${c.traceId}:${c.spanId}`,c);let l;if(n==="branches"&&"branches"in r){const c=(r.branches??[]).map(u=>i.get(`${u.traceId}:${u.spanId}`)??u);l={...r,branches:c}}else if("spans"in r){const c=(r.spans??[]).map(u=>i.get(`${u.traceId}:${u.spanId}`)??u);l={...r,spans:c}}else return e;return{...e,pages:[l,...s]}}function eXe(e){return[...e].sort((t,n)=>{const r=t.startedAt?new Date(t.startedAt).getTime():0;return(n.startedAt?new Date(n.startedAt).getTime():0)-r})}function nss(e,t,n){if(!e||e.pages.length===0)return e;const[r,...s]=e.pages;if(!r)return e;const a=t.deltaCursor??r.deltaCursor;let i;if(n==="branches"&&"branches"in r){const l=t.branches??[];i={...r,branches:eXe([...l,...r.branches??[]]),deltaCursor:a}}else if("spans"in r){const l=t.spans??[];i={...r,spans:eXe([...l,...r.spans??[]]),deltaCursor:a}}else return e;return{...e,pages:[i,...s]}}const rss=({filters:e,listMode:t="traces",polling:n={}})=>{const{deltaPollIntervalMs:r=G0.deltaPollIntervalMs,deltaChaseIntervalMs:s=G0.deltaChaseIntervalMs,deltaLimit:a=G0.deltaLimit,pageModeRefetchIntervalMs:i=G0.pageModeRefetchIntervalMs,page0StatusRefreshIntervalMs:l=G0.page0StatusRefreshIntervalMs,idleGuardThresholdMs:c=G0.idleGuardThresholdMs,minRefetchSpinMs:u=G0.minRefetchSpinMs,deltaHighlightMs:d=G0.deltaHighlightMs}=n,f=We(),p=Ur(),{inView:h,setRef:m}=W_(),[g,y]=v.useState(()=>mae.get(f)??"unknown"),b=g==="unsupported",[x,S]=v.useState(!0),[k,_]=v.useState(()=>new Set);v.useEffect(()=>{_(new Set)},[t,e]);const C=["traces",t,e],E=M1({queryKey:C,queryFn:({pageParam:V})=>gae({client:f,page:V,perPage:JKe,filters:e,listMode:t}),initialPageParam:0,getNextPageParam:Xrs,select:ess,retry:!1,refetchInterval:V=>xs(V.state.error)||!x?!1:b?i:!1}),j=E.data?.deltaCursor;v.useEffect(()=>{E.isSuccess&&j===void 0&&g==="unknown"&&(mae.set(f,"unsupported"),y("unsupported"))},[E.isSuccess,j,g,f]);const N=yt({queryKey:["traces-delta",t,e],queryFn:()=>{const V=p.getQueryData(C)?.pages[0]?.deltaCursor;return V?gae({client:f,mode:"delta",after:V,limit:a,filters:e,listMode:t}):null},enabled:!!j&&!b&&x,retry:!1,refetchInterval:V=>V.state.error?!1:V.state.data?.delta?.hasMore?s:r});v.useEffect(()=>{const V=N.data;if(!V)return;p.setQueryData(C,Z=>nss(Z,V,t));const $=t==="branches"&&"branches"in V?V.branches??[]:"spans"in V?V.spans??[]:[];if($.length===0)return;const U=$.map(Z=>`${Z.traceId}:${Z.spanId??""}`);_(Z=>{const K=new Set(Z);for(const te of U)K.add(te);return K}),setTimeout(()=>{_(Z=>{const K=new Set(Z);for(const te of U)K.delete(te);return K})},d)},[N.data,p,t,e,d]),v.useEffect(()=>{Krs(N.error)&&(mae.set(f,"unsupported"),y("unsupported"))},[N.error,f]);const I=yt({queryKey:["traces-status-refresh",t,e],queryFn:()=>gae({client:f,page:0,perPage:JKe,filters:e,listMode:t}),enabled:!!j&&!b&&x,refetchInterval:l,refetchOnMount:!1,retry:!1});v.useEffect(()=>{const V=I.data;V&&p.setQueryData(C,$=>tss($,V,t))},[I.data,p,t,e]);const A=v.useRef(0);v.useEffect(()=>{const V=Math.max(E.dataUpdatedAt,N.dataUpdatedAt,I.dataUpdatedAt);V>A.current&&(A.current=V)},[E.dataUpdatedAt,N.dataUpdatedAt,I.dataUpdatedAt]);const R=v.useRef(x);v.useEffect(()=>{R.current=x},[x]),v.useEffect(()=>{const V=()=>{document.visibilityState==="visible"&&R.current&&Yrs(A.current,Date.now(),c)&&p.resetQueries({queryKey:["traces",t,e]})};return document.addEventListener("visibilitychange",V),()=>document.removeEventListener("visibilitychange",V)},[p,t,e,c]);const{hasNextPage:L,isFetchingNextPage:D,fetchNextPage:B}=E;v.useEffect(()=>{h&&L&&!D&&B()},[h,L,D,B]);const H=E.isFetching||I.isFetching||N.isFetching,F=Math.max(E.dataUpdatedAt,E.errorUpdatedAt,N.dataUpdatedAt,N.errorUpdatedAt,I.dataUpdatedAt,I.errorUpdatedAt),[z,q]=v.useState(!1),M=v.useRef(F);return v.useEffect(()=>{if(F>M.current){M.current=F,q(!0);const V=setTimeout(()=>q(!1),u);return()=>clearTimeout(V)}},[F,u]),{...E,setEndOfListElement:m,isRefetching:H||z,autoRefetch:x,setAutoRefetch:S,recentlyAddedKeys:k}};function sss(e){return e.startsWith("agent-")}function ass(e){return e.match(/^(?:mcp_)?tool:\s*'(.*?)'/)?.[1]??e}function J9t(e){return e7t(e,[])}function e7t(e,t){if(!e)return t;for(const n of e){const r=n.stepType==="tool_call"||n.stepType==="mcp_tool_call";if(r&&n.name){const s=ass(n.name),a="toolArgs"in n?n.toolArgs:void 0,i="toolResult"in n?n.toolResult:void 0;t.push({toolName:s,args:a??{},output:i,...sss(s)?{matchArgs:"ignore"}:{}})}!r&&n.children?.length&&e7t(n.children,t)}return t}function iss(e){const t=(()=>{try{const r=JSON.stringify(e.input);return r?r.length>40?`${r.slice(0,40)}…`:r:""}catch{return""}})(),n=Y1(e.id)??e.id;return t?`${n} — ${t}`:n}function oss({traceId:e,isOpen:t,onClose:n,level:r=2}){const s=We(),{data:a,isLoading:i}=yt({queryKey:["trace-trajectory",e],queryFn:()=>s.getTraceTrajectory(e),enabled:t&&!!e}),l=a?.steps?J9t(a.steps):[],c=l.length>0?oO(l,2):"";return o.jsxs(As,{dialogTitle:"Add Tool Mocks to Item",dialogDescription:"Append trace-derived tool mocks to an existing dataset item",isOpen:t,onClose:n,level:r,children:[o.jsxs(As.Top,{children:[o.jsxs(ko,{children:[o.jsx(Mu,{})," ",Y1(e)]}),"›",o.jsxs(ko,{children:[o.jsx(zp,{})," Add Tool Mocks to Item"]})]}),o.jsxs(As.Content,{children:[o.jsx(As.Header,{children:o.jsxs(As.Heading,{children:[o.jsx(zp,{})," Add Tool Mocks to Item"]})}),i?o.jsx("div",{className:"text-neutral4 px-2 py-4 text-sm",children:"Loading tool calls from trace..."}):o.jsx(lss,{initialMocksJson:c,onClose:n},e??"no-trace")]})]})}function lss({initialMocksJson:e,onClose:t}){const[n,r]=v.useState(""),[s,a]=v.useState(""),[i,l]=v.useState(e),{data:c,isLoading:u}=Bg(),d=c?.datasets??[],{data:f=[],isLoading:p}=j1(n),{data:h,isFetching:m}=PV(n,s),{updateItem:g}=Ni(),y=(()=>{if(!i.trim())return!1;try{const S=JSON.parse(i);return Array.isArray(S)&&S.length>0}catch{return!1}})(),b=S=>{r(S),a("")},x=async S=>{if(S.preventDefault(),!n||!s){Le.error("Please select a dataset and an item");return}let k;try{const E=i.trim()?JSON.parse(i):[];if(!Array.isArray(E)){Le.error("Tool Mocks must be a JSON array");return}k=E}catch{Le.error("Tool Mocks must be valid JSON");return}if(k.length===0){Le.error("There are no tool mocks to add");return}if(!h||h.id!==s){Le.error("Item is still loading, please try again");return}const C=[...h.toolMocks??[],...k];try{await g.mutateAsync({datasetId:n,itemId:s,toolMocks:C}),Le.success(`Added ${k.length} tool mock(s) to the item`),t()}catch(E){Le.error(`Failed to add tool mocks: ${E instanceof Error?E.message:"Unknown error"}`)}};return o.jsxs("form",{onSubmit:x,className:"grid gap-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"target-dataset",children:"Dataset *"}),o.jsxs(oa,{value:n,onValueChange:b,disabled:u,children:[o.jsx(ca,{id:"target-dataset",children:o.jsx(la,{placeholder:u?"Loading datasets...":"Select a dataset"})}),o.jsx(ua,{children:d.length===0?o.jsx("div",{className:"text-neutral4 px-2 py-4 text-center text-sm",children:"No datasets available"}):d.map(S=>o.jsx(Ar,{value:S.id,children:S.name},S.id))})]})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"target-item",children:"Item *"}),o.jsxs(oa,{value:s,onValueChange:a,disabled:!n||p,children:[o.jsx(ca,{id:"target-item",children:o.jsx(la,{placeholder:n?p?"Loading items...":"Select an item":"Select a dataset first"})}),o.jsx(ua,{children:f.length===0?o.jsx("div",{className:"text-neutral4 px-2 py-4 text-center text-sm",children:"No items available"}):f.map(S=>o.jsx(Ar,{value:S.id,children:iss(S)},S.id))})]})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"derived-mocks",children:"Tool Mocks (JSON)"}),o.jsx(Wr,{value:i,onChange:l,showCopyButton:!1,className:"min-h-[160px]"}),o.jsx("p",{className:"text-neutral4 text-xs",children:"Seeded from the trace's tool calls. Edit or remove entries before appending."})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ce,{type:"button",variant:"outline",onClick:t,children:"Cancel"}),o.jsx(ce,{type:"submit",variant:"default",disabled:g.isPending||m||!y||!n||!s||h?.id!==s,children:g.isPending?"Adding...":"Append Tool Mocks"})]})]})}function css(e){if(e?.input==null)return"{}";const t=e.input,r=e.spanType==="agent_run"&&t&&typeof t=="object"&&!Array.isArray(t)&&"messages"in t?t.messages??e.input:e.input;return oO(r,2)}function t7t({traceDetails:e,rootSpanId:t,traceId:n,isOpen:r,onClose:s,level:a=2}){const i=We(),{data:l}=CL(!e&&r?n:null,!e&&r?t:null),c=e??l?.span,{data:u,isLoading:d}=yt({queryKey:["trace-trajectory",n],queryFn:()=>i.getTraceTrajectory(n),enabled:r&&!!n}),f=u?.steps&&u.steps.length>0?oO({steps:u.steps.map(m=>{const{name:g,stepType:y,children:b,...x}=m,S={name:g,stepType:y};for(const[k,_]of Object.entries(x))_!=null&&k!=="durationMs"&&k!=="metadata"&&(S[k]=_);return S}),ordering:"relaxed"},2):void 0,p=u?.steps?J9t(u.steps):[],h=p.length>0?oO(p,2):void 0;return o.jsx(Pzt,{initialInput:css(c),initialGroundTruth:c?.output!=null?oO(c.output,2):"",initialTrajectory:f,trajectoryLoading:d,initialToolMocks:h,breadcrumb:o.jsxs(ko,{children:[o.jsx(Mu,{})," ",Y1(n)]}),isOpen:r,onClose:s,level:a,source:n?{type:"trace",referenceId:n}:void 0})}function uss(e){return e.feedbackType==="thumbs"?e.value===1?"👍 Positive (1)":e.value===0||e.value===-1?"👎 Negative":String(e.value):e.feedbackType==="rating"?String(e.value):e.feedbackType==="comment"?String(e.value??e.comment??"-"):String(e.value??"-")}function dss({feedback:e,isOpen:t,onClose:n,onNext:r,onPrevious:s}){const a=e?.metadata&&Object.keys(e.metadata).length>0?JSON.stringify(e.metadata,null,2):void 0;return o.jsxs(As,{dialogTitle:"Feedback Detail",dialogDescription:"View feedback details",isOpen:t,onClose:n,level:3,children:[o.jsxs(As.Top,{children:[o.jsxs(ko,{children:[o.jsx(dT,{})," Feedback"]}),"|",o.jsx(As.Nav,{onNext:r,onPrevious:s})]}),o.jsxs(As.Content,{children:[o.jsxs(As.Header,{children:[o.jsxs(As.Heading,{children:[o.jsx(dT,{})," Feedback"]}),e?.traceId&&o.jsxs(ko,{children:[o.jsx(kfe,{})," ",e.traceId]})]}),o.jsxs(wNe,{children:[o.jsx(xNe,{data:[{label:"Created at",value:e?.timestamp?nr(new Date(e.timestamp),"MMM d, h:mm:ss aaa"):"n/a",key:"timestamp"},{label:"Type",value:e?.feedbackType??"n/a",key:"type"},{label:"Value",value:e?uss(e):"n/a",key:"value"},...e?.comment?[{label:"Comment",value:e.comment,key:"comment"}]:[],{label:"Source",value:e?.feedbackSource??e?.source??"n/a",key:"source"},...e?.feedbackUserId?[{label:"User",value:e.feedbackUserId,key:"userId"}]:[],...e?.traceId?[{label:"Trace ID",value:e.traceId,key:"traceId"}]:[],...e?.spanId?[{label:"Span ID",value:e.spanId,key:"spanId"}]:[]]}),a&&o.jsx(As.CodeSection,{title:"Metadata",icon:o.jsx(kfe,{}),codeStr:a,simplified:!0})]})]})]})}const n7t=[{label:"Source",size:"1fr"},{label:"Date",size:"0.8fr"},{label:"Time",size:"0.8fr"},{label:"Value",size:"0.6fr"},{label:"Comment",size:"2fr"}],tXe=n7t.map(e=>e.size).join(" ");function fss(e){return e.feedbackType==="thumbs"?e.value===1?"👍":e.value===0||e.value===-1?"👎":String(e.value):typeof e.value=="number"?String(e.value):"—"}function pss(e){const t=e.comment||(typeof e.value=="string"?e.value:"");return t?t.length>60?t.slice(0,60)+"…":t:"—"}function r7t({feedbackData:e,isLoadingFeedbackData:t,onPageChange:n}){const[r,s]=v.useState(!1),[a,i]=v.useState();if(t)return o.jsx(ol,{columns:tXe});const l=e?.feedback??[],c=e?.pagination?.page??0,u=h=>{i(l[h]),s(!0)},d=a?l.indexOf(a):-1,f=d>=0&&d<l.length-1?()=>i(l[d+1]):void 0,p=d>0?()=>i(l[d-1]):void 0;return o.jsxs(o.Fragment,{children:[o.jsxs(ve,{columns:tXe,children:[o.jsx(ve.Top,{children:n7t.map(h=>o.jsx(ve.TopCell,{children:h.label},h.label))}),l.length===0?o.jsx(ve.NoMatch,{message:"No feedback found"}):l.map((h,m)=>{const g=new Date(h.timestamp),y=h.feedbackUserId||h.feedbackSource||"unknown";return o.jsxs(ve.RowButton,{onClick:()=>u(m),children:[o.jsx(ve.Cell,{height:"compact",children:y}),o.jsx(ve.DateCell,{timestamp:g}),o.jsx(ve.Cell,{height:"compact",children:nr(g,"h:mm:ss aaa")}),o.jsx(ve.Cell,{height:"compact",children:fss(h)}),o.jsx(ve.Cell,{height:"compact",children:pss(h)})]},`${h.traceId}-${m}`)}),o.jsx(ve.Pagination,{currentPage:c,hasMore:e?.pagination?.hasMore,onNextPage:()=>n?.(c+1),onPrevPage:()=>{c>0&&n?.(c-1)}})]}),o.jsx(dss,{feedback:a,isOpen:r,onClose:()=>s(!1),onNext:f,onPrevious:p})]})}const nXe="auto auto auto auto 1fr";function s7t({scoresData:e,isLoadingScoresData:t,onPageChange:n,onScoreSelect:r}){return t?o.jsx(ol,{columns:nXe}):o.jsxs("div",{className:"grid gap-2",children:[o.jsxs(ve,{columns:nXe,className:"min-w-0",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"ID"}),o.jsx(ve.TopCell,{children:"Date"}),o.jsx(ve.TopCell,{children:"Time"}),o.jsx(ve.TopCell,{children:"Score"}),o.jsx(ve.TopCell,{children:"Scorer"})]}),e?.scores&&e.scores.length>0?e.scores.map(s=>{const a=new Date(s.createdAt),i=rI(a);return o.jsxs(ve.RowButton,{onClick:()=>r?.(s),children:[o.jsx(ve.Cell,{height:"compact",className:"text-neutral3 text-ui-smd font-mono",children:Y1(s?.id)||"n/a"}),o.jsx(ve.Cell,{height:"compact",className:"text-neutral2 text-ui-smd",children:i?"Today":nr(a,"MMM dd")}),o.jsx(ve.Cell,{height:"compact",className:"text-neutral3 text-ui-smd font-mono",children:nr(a,"h:mm:ss aaa")}),o.jsx(ve.Cell,{height:"compact",className:"text-ui-smd",children:String(s?.score??"")}),o.jsx(ve.Cell,{height:"compact",className:"text-ui-smd",children:String(s?.scorer?.name||s?.scorer?.id||"")})]},s.id)}):o.jsx(ve.NoMatch,{message:"No scores found"})]}),o.jsx(ve.Pagination,{currentPage:e?.pagination?.page||0,hasMore:e?.pagination?.hasMore,onNextPage:()=>n?.((e?.pagination?.page||0)+1),onPrevPage:()=>n?.((e?.pagination?.page||0)-1)})]})}const hss=()=>{const e=We();return Mn({mutationFn:async({scorerName:t,traceId:n,spanId:r})=>await e.score({scorerName:t,targets:[{traceId:n,spanId:r}]})})};function a7t({traceId:e,spanId:t,entityType:n,isTopLevelSpan:r,scorers:s,isLoadingScorers:a}){const[i,l]=v.useState(null),{mutate:c,isPending:u}=hss();let d=Object.entries(s||{}).map(([m,g])=>({id:m,name:g.scorer.config.name,description:g.scorer.config.description,isRegistered:g.isRegistered,type:g.scorer.config.type})).filter(m=>m.isRegistered);(n!=="Agent"||!r)&&(d=d.filter(m=>m.type!=="agent"));const f=u||a,p=()=>{i&&e&&c({scorerName:i,traceId:e,spanId:t},{onSuccess:()=>Le.info("Scorer triggered",{description:"Results will appear once scoring completes."})})},h=d.find(m=>m.id===i)?.description||"";return s===void 0&&!a?o.jsx(En,{variant:"destructive",children:"Failed to load scorers."}):!a&&d.length===0?o.jsx(En,{variant:"info",children:"No eligible scorers have been defined to run."}):o.jsxs("div",{className:"grid grid-cols-[3fr_1fr] items-start gap-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Cc,{name:"select-scorer",label:"Select scorer",labelIsHidden:!0,placeholder:"Select a scorer...",options:d.map(m=>({label:m.name||m.id,value:m.id||m.name||""})),onValueChange:l,value:i||"",className:"min-w-80",disabled:f}),h&&o.jsxs(ko,{className:"text-neutral3 text-ui-sm",children:[o.jsx(Bx,{})," ",h]})]}),o.jsx(ce,{disabled:!i||f,onClick:p,children:u?"Starting...":"Start Scoring"})]})}const mss=3e3;function gss(e){return x4(e.state.error,"feedback")||w4(e.state.error)?!1:mss}const i7t=({traceId:e="",page:t})=>{const n=We(),r=t??0;return yt({queryKey:["trace-feedback",e,r],queryFn:()=>n.listFeedback({filters:{traceId:e},pagination:{page:r,perPage:10}}),enabled:!!e,refetchInterval:gss,gcTime:0,staleTime:0})};function o7t({scopedEntityId:e,scopedEntityType:t}={}){const n=!!e,[r,s]=Ri(),a=Qrs(r,s);v.useEffect(()=>{if(!e)return;const Oe=r.get("rootEntityType"),Pe=r.get("filterEntityId");!(t&&Oe!==t)&&!(Pe!==e)||s(tt=>{const Pt=new URLSearchParams(tt);return t&&Pt.set("rootEntityType",t),Pt.set("filterEntityId",e),Pt},{replace:!0})},[e,t,r,s]);const i=v.useMemo(()=>n?["rootEntityType","entityId"]:[],[n]),l=v.useMemo(()=>n?["rootEntityType","entityId","entityName"]:[],[n]),c=n?"This filter is scoped to the current agent. Open the global Traces view to change it.":void 0,[u,d]=v.useState(),[f,p]=v.useState(0),[h,m]=v.useState(!1),[g,y]=v.useState(!1),[b,x]=v.useState(!1),[S,k]=v.useState(null),[_,C]=v.useState(null);v.useEffect(()=>p(0),[a.traceIdParam,a.spanIdParam]);const{data:E,isLoading:j}=ih(),{data:N,isLoading:I}=Yzt({traceId:a.traceIdParam,spanId:a.spanIdParam,page:f}),[A,R]=v.useState(0);v.useEffect(()=>R(0),[a.traceIdParam,a.spanIdParam]);const{data:L,isLoading:D}=i7t({traceId:a.traceIdParam,page:A}),{spans:B,anchorSpanId:H,isLoading:F}=Zrs({traceId:a.traceIdParam??null,anchorSpanId:a.listMode==="branches"?a.anchorSpanIdParam??null:null,listMode:a.listMode}),{data:z,isLoading:q}=CL(a.traceIdParam??"",a.spanIdParam??""),M=a.scoreIdParam?N?.scores?.find(Oe=>Oe.id===a.scoreIdParam):void 0,{data:G=[],isPending:V}=iIe(),{data:$=[],isPending:U}=rIe({entityType:a.selectedEntityOption?.entityType,rootOnly:!0}),{data:Z=[],isPending:K}=sIe(),{data:te=[],isPending:ee}=aIe(),J=v.useMemo(()=>Rrs({availableTags:G,availableRootEntityNames:$,availableServiceNames:te,availableEnvironments:Z,loading:{tags:V,entityNames:U,serviceNames:ee,environments:K}}),[G,$,te,Z,V,U,ee,K]),ae=v.useMemo(()=>Drs({rootEntityType:a.selectedEntityOption?.entityType,status:a.selectedStatus,dateFrom:a.selectedDateFrom,dateTo:a.selectedDateTo,tokens:a.filterTokens}),[a.filterTokens,a.selectedDateFrom,a.selectedDateTo,a.selectedEntityOption,a.selectedStatus]),{data:de,isLoading:Y,isFetchingNextPage:ne,hasNextPage:fe,setEndOfListElement:oe,error:le,isRefetching:he,autoRefetch:be,setAutoRefetch:xe,recentlyAddedKeys:je}=rss({filters:ae,listMode:a.listMode}),ke=v.useMemo(()=>de?.spans??[],[de?.spans]);v.useEffect(()=>{!le||g||rZe(le)&&(y(!0),a.listMode==="branches"&&a.handleListModeChange("traces"))},[le,g,a]);const{handlePreviousSpan:Ae,handleNextSpan:Me}=lIe(B,a.spanIdParam??null,Oe=>a.handleSpanChange(Oe)),ue=Urs(r,s,{storageKey:n?`mastra:traces:saved-filters:${t}:${e}`:void 0}),re=v.useCallback(()=>a.applyFilterTokens(Lrs(J,a.filterTokens)),[J,a]),se=v.useCallback((Oe,Pe)=>{a.listMode==="branches"?a.handleTraceClick(Oe,Pe,Pe):a.handleTraceClick(Oe)},[a]),{handlePreviousTrace:me,handleNextTrace:we}=Vrs(ke,a.traceIdParam,a.listMode==="branches"?a.anchorSpanIdParam:null,se),Ne=v.useCallback(()=>{const Oe=H?B?.find(Pe=>Pe.spanId===H):B?.find(Pe=>Pe.parentSpanId==null);Oe&&a.handleSpanChangeWithTab(Oe.spanId,"scoring")},[B,H,a]),Re=v.useMemo(()=>(H?B?.find(Pe=>Pe.spanId===H):B?.find(Pe=>Pe.parentSpanId==null))?.entityType==="agent",[B,H]),Qe=!!a.selectedEntityOption||!!a.selectedStatus||a.filterTokens.length>0||a.datePreset!=="last-24h"||!!a.selectedDateTo,Ze=o.jsxs(o.Fragment,{children:[o.jsx(G3,{preset:a.datePreset,onPresetChange:a.handleDatePresetChange,dateFrom:a.selectedDateFrom,dateTo:a.selectedDateTo,onDateChange:a.handleDateChange,disabled:Y,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),o.jsx(YNe,{fields:J,tokens:a.filterTokens,onTokensChange:a.handleFilterTokensChange,disabled:Y,onStartTextFilter:d,hiddenFieldIds:l}),o.jsxs("div",{className:"h-form-default ml-auto flex items-center gap-2",children:[!g&&o.jsxs(o.Fragment,{children:[o.jsx(ic,{id:"show-subtraces",checked:a.listMode==="branches",onCheckedChange:Oe=>a.handleListModeChange(Oe?"branches":"traces"),disabled:Y}),o.jsx(Dt,{htmlFor:"show-subtraces",children:"Show subtraces"})]}),o.jsx(ce,{variant:"ghost",size:"md",onClick:()=>xe(!be),"aria-label":"Toggle auto-refetch","aria-pressed":be,tooltip:be?"Auto-refetch ON":"Auto-refetch OFF",children:be?o.jsx(Ww,{className:`h-4 w-4 ${he?"animate-spin":""}`}):o.jsx(yHt,{className:"h-4 w-4"})})]})]}),Te=g&&!b?o.jsx(En,{variant:"info",action:o.jsx(En.Button,{variant:"ghost",onClick:()=>x(!0),children:"Dismiss"}),className:"mb-4",children:o.jsx(En.Message,{children:"Selected list mode isn't supported by this storage provider — switched to default."})}):null,Ce=o.jsxs(Ft.TopArea,{children:[o.jsx(Ft.Row,{children:o.jsx(Ft.Column,{className:"flex w-full flex-wrap items-start justify-start gap-2",children:Ze})}),o.jsx(Ors,{isLoading:Y,filterFields:J,filterTokens:a.filterTokens,onFilterTokensChange:a.handleFilterTokensChange,onClear:re,onRemoveAll:a.handleRemoveAll,onSave:ue.handleSave,onRemoveSaved:ue.hasSavedFilters?ue.handleRemoveSaved:void 0,autoFocusFilterFieldId:u,lockedFieldIds:i,lockedTooltipContent:c}),Te]});if(le&&!rZe(le))return o.jsxs(Ft,{width:"wide",height:"full",children:[Ce,o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsx(Y9t,{error:le,resource:"traces",errorTitle:"Failed to load traces"})})]});const Ee=!!a.selectedEntityOption||!!a.selectedStatus||a.filterTokens.length>0;return ke.length===0&&!Y&&!Ee?o.jsxs(Ft,{width:"wide",height:"full",children:[Ce,o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsx(Bns,{datePreset:a.datePreset,dateFrom:a.selectedDateFrom,dateTo:a.selectedDateTo})})]}):o.jsxs(Ft,{width:"wide",height:"full",children:[Ce,o.jsx(srs,{traceCollapsed:h,listSlot:o.jsx(krs,{traces:ke,isLoading:Y,isFetchingNextPage:ne,hasNextPage:fe,setEndOfListElement:oe,filtersApplied:Qe,featuredTraceId:a.traceIdParam,featuredSpanId:a.listMode==="branches"?a.anchorSpanIdParam:null,isBranchesMode:a.listMode==="branches",recentlyAddedKeys:je,onTraceClick:Oe=>{const Pe=a.listMode==="branches";if(Pe?a.traceIdParam===Oe.traceId&&a.anchorSpanIdParam===Oe.spanId:a.traceIdParam===Oe.traceId){a.handleTraceClick("");return}const Ke=Pe?Oe.spanId??void 0:void 0;a.handleTraceClick(Oe.traceId,Ke,Ke)}},a.listMode),tracePanelSlot:a.traceIdParam&&(a.listMode!=="branches"||a.anchorSpanIdParam)?o.jsx(eIe,{traceId:a.traceIdParam,spans:B,anchorSpanId:H,isLoading:F,onClose:a.handleTraceClose,onSpanSelect:Oe=>a.handleSpanChange(Oe??null),onEvaluateTrace:Ne,onSaveAsDatasetItem:Oe=>k(Oe),onAddTraceMocksToItem:Re?Oe=>C(Oe):void 0,initialSpanId:a.spanIdParam,onPrevious:me,onNext:we,collapsed:h,onCollapsedChange:m,placement:"traces-list",LinkComponent:i1,traceHref:`/traces/${a.traceIdParam}`}):null,spanPanelSlot:a.traceIdParam&&a.spanIdParam?o.jsx(KNe,{traceId:a.traceIdParam,spanId:a.spanIdParam,span:z?.span,isAnchor:H?a.spanIdParam===H:void 0,isLoading:q,onClose:a.handleSpanClose,onPrevious:Ae,onNext:Me,activeTab:a.spanTabParam??"details",onTabChange:Oe=>a.handleSpanTabChange(Oe),feedbackTabBadge:L?.pagination?.total??void 0,feedbackTabSlot:()=>o.jsx(r7t,{feedbackData:L,onPageChange:R,isLoadingFeedbackData:D}),scoringTabBadge:N?.pagination?.total??void 0,scoringTabSlot:({span:Oe,traceId:Pe,spanId:Ue})=>o.jsxs("div",{className:"grid gap-6",children:[o.jsx(a7t,{traceId:Pe,isTopLevelSpan:!Oe.parentSpanId,spanId:Ue,entityType:Oe.attributes?.agentId||Oe.entityType==="agent"?"Agent":Oe.attributes?.workflowId||Oe.entityType==="workflow_run"?"Workflow":void 0,scorers:E,isLoadingScorers:j}),o.jsx(s7t,{scoresData:N,onPageChange:p,isLoadingScoresData:I,onScoreSelect:Ke=>a.handleScoreChange(Ke.id)})]})}):null,scorePanelSlot:M?o.jsx(bNe,{score:M,onClose:()=>a.handleScoreChange(null)}):null}),o.jsx(t7t,{rootSpanId:S?.rootSpanId,traceId:S?.traceId,isOpen:!!S,onClose:()=>k(null)}),o.jsx(oss,{traceId:_?.traceId,isOpen:!!_,onClose:()=>C(null)})]})}function vss(){const{agentId:e}=Sr();return e?o.jsx(o7t,{scopedEntityId:e,scopedEntityType:au.AGENT}):null}function yss(){return o.jsx(SJr,{})}function bss(){const{navigate:e,paths:t}=yn(),n=qo(),{form:r,handlePublish:s,isSubmitting:a,canPublish:i}=DG({mode:"create",onSuccess:l=>e(t.agentLink(l))});return o.jsxs(ds,{children:[o.jsx($y,{owner:"cms-agent-create",children:o.jsx(ce,{variant:"primary",onClick:()=>{s()},disabled:a||!i,children:a?o.jsxs(o.Fragment,{children:[o.jsx(Xt,{className:"h-4 w-4"}),"Creating..."]}):o.jsxs(o.Fragment,{children:[o.jsx(qe,{children:o.jsx(fa,{})}),"Create agent"]})})}),o.jsx(q8t,{form:r,mode:"create",isSubmitting:a,handlePublish:s,basePath:"/cms/agents/create",currentPath:n.pathname,children:o.jsx(yx,{})})]})}function rXe({agentId:e,selectedVersionId:t,versionData:n,readOnly:r=!1,form:s,handlePublish:a,handleSaveDraft:i,isSubmitting:l,isSavingDraft:c,onVersionSelect:u,activeVersionId:d,latestVersionId:f,hideVersionPanel:p=!1,isCodeAgentOverride:h=!1,isCodeSourceAgent:m=!1,editorConfig:g}){const[,y]=Ri(),{pathname:b}=qo(),k=!!t&&!!n&&t!==f?o.jsxs(En,{variant:"info",title:"This is a previous version",className:"mb-4",children:[o.jsx(En.Message,{children:"You are seeing a specific version of the agent."}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ce,{type:"button",variant:"default",size:"sm",onClick:()=>y({}),children:"View latest version"}),o.jsx(ce,{type:"button",variant:"default",size:"sm",onClick:()=>{a(t??void 0)},disabled:t===d,children:"Publish This Version"})]})]}):void 0,_=p?void 0:o.jsx(aes,{agentId:e,selectedVersionId:t??void 0,onVersionSelect:u,activeVersionId:d}),C=h&&g===!1;return o.jsx(q8t,{form:s,mode:"edit",agentId:e,isSubmitting:l,isSavingDraft:c,handlePublish:a,handleSaveDraft:i,readOnly:r,isCodeAgentOverride:h,isCodeSourceAgent:m,editorConfig:g,basePath:`/cms/agents/${e}/edit`,currentPath:b,banner:k,versionId:t??void 0,rightPanel:_,children:C?o.jsx("div",{className:"p-6",children:o.jsx(En,{variant:"info",title:"Editing disabled",children:o.jsx(En.Message,{children:"This code-defined agent has disabled Studio editing with `editor: false`."})})}):o.jsx(yx,{})})}function xss(){const{agentId:e}=Sr(),{navigate:t,paths:n}=yn(),r=qs(),{hash:s,pathname:a,search:i}=qo(),[l,c]=Ri(),u=l.get("versionId"),{isMastraPlatform:d,mastraPlatformApiEndpoint:f,mastraPlatformProjectId:p}=zG(),{data:h,isLoading:m}=mc(e),{data:g}=K1({agentId:e,params:{orderBy:{direction:"DESC"}}}),y=(g?.versions?.length??0)>0,{data:b,isLoading:x}=b4(e,{status:"draft",enabled:y}),S=h?.source==="code",k=v.useMemo(()=>S?TNe(h?.editor):[],[h?.editor,S]),_=b??null,C=m||y&&x,E=`/cms/agents/${e}/edit`,j=a===E||a===`${E}/`;v.useEffect(()=>{if(!S||k.length===0)return;const ne=k.some(fe=>a===`${E}${fe.pathSuffix}`);(j||!ne)&&r(`${E}${k[0].pathSuffix}${i}${s}`,{replace:!0})},[k,S,j,a,r,E,i,s]);const{data:N}=V$t({agentId:e??"",versionId:u??""}),I=_?.activeVersionId,A=g?.versions?.[0],R=!!(A&&A.id!==I),L=!!u&&!!N,D=L&&u!==A?.id,B=v.useMemo(()=>L&&N?N:_||(h?ANe(h):{}),[L,N,_,h]),{form:H,handlePublish:F,handleSaveDraft:z,handleDownloadJson:q,handleOpenPr:M,isSubmitting:G,isSavingDraft:V,isDirty:$}=DG({mode:"edit",agentId:e??"",dataSource:B,isCodeAgentOverride:S,hasStoredOverride:S&&!!b,editorConfig:h?.editor,onSuccess:ne=>t(n.agentLink(ne))}),U=v.useCallback(async()=>{D&&u?await F(u):await F()},[F,D,u]),Z=v.useCallback(ne=>{c(ne?{versionId:ne}:{})},[c]),K=!C&&!_&&!h,te=!C&&!!e&&(!!_||!!h),ee=!S||h?.editor!==!1,J=DNe(),ae=S&&J==="code",de=ee&&d&&!!f&&!!p,Y=de?"Open a pull request with this agent override JSON":"Open PR is available on Mastra-hosted projects with GitHub App support";return o.jsxs(ds,{children:[te&&o.jsx($y,{owner:"cms-agent-edit",children:o.jsxs("div",{className:"flex items-center gap-2",children:[R&&o.jsx(un,{variant:"info",children:"Unpublished changes"}),ae?ee?o.jsxs(o.Fragment,{children:[o.jsxs(ce,{onClick:()=>{q()},disabled:V||G,children:[o.jsx(vf,{}),"Download JSON"]}),o.jsxs(ce,{variant:"primary",disabled:!de||V||G,title:Y,onClick:()=>{!f||!p||M({platformApiEndpoint:f,projectId:p})},children:[o.jsx(mit,{}),"Open PR"]})]}):null:ee?o.jsxs(o.Fragment,{children:[o.jsx(ce,{onClick:()=>{z()},disabled:!$||V||G,children:V?o.jsxs(o.Fragment,{children:[o.jsx(Xt,{className:"h-4 w-4"}),"Saving..."]}):o.jsxs(o.Fragment,{children:[o.jsx(jd,{}),"Save"]})}),o.jsx(ce,{variant:"primary",onClick:()=>{U()},disabled:D?u===I||G||V:!R||G||V,children:G?o.jsxs(o.Fragment,{children:[o.jsx(Xt,{className:"h-4 w-4"}),"Publishing..."]}):o.jsxs(o.Fragment,{children:[o.jsx(fa,{}),D?"Publish This Version":"Publish"]})})]}):null]})}),K?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"text-neutral3 flex h-full items-center justify-center",children:"Agent not found"}),o.jsx("div",{className:"hidden",children:o.jsx(rXe,{agentId:e??"",selectedVersionId:u,versionData:N,readOnly:!0,form:H,handlePublish:F,handleSaveDraft:z,isSubmitting:G,isSavingDraft:V,onVersionSelect:Z,activeVersionId:I,latestVersionId:A?.id,editorConfig:void 0})})]}):o.jsx(rXe,{agentId:e??"",selectedVersionId:u,versionData:N,readOnly:!ee,form:H,handlePublish:F,handleSaveDraft:z,isSubmitting:G,isSavingDraft:V,onVersionSelect:Z,activeVersionId:I,latestVersionId:A?.id,hideVersionPanel:S&&!b,isCodeAgentOverride:S,isCodeSourceAgent:ae,editorConfig:h?.editor})]})}function wss(){return o.jsx(lJr,{})}function Sss(){return o.jsx(y8t,{})}function kss(){return o.jsx(CJr,{})}function Oss(){return o.jsx(kJr,{})}function _ss(){return o.jsx(YJr,{})}function Css(){return o.jsx(x8t,{})}function Ess(){return o.jsx(PJr,{})}function jss(){return o.jsx(_Jr,{})}function Tss(){const{navigate:e,paths:t}=yn();return o.jsx(ds,{className:"grid-rows-[1fr]",children:o.jsx(DXr,{onSuccess:n=>e(t.cmsPromptBlockEditLink(n.id))})})}function sXe(e){return{name:e.name,description:e.description||void 0,content:e.content,rules:e.rules||void 0,requestContextSchema:e.variables||void 0}}function Nss({block:e,blockId:t,selectedVersionId:n,hasDraft:r,latestVersionId:s,activeVersionId:a,onClearVersion:i}){const l=We(),c=Ur(),{navigate:u,paths:d}=yn(),{updateStoredPromptBlock:f}=AG(t),[p,h]=v.useState(!1),[m,g]=v.useState(!1),{data:y}=LXr({blockId:t,versionId:n??""}),b=!!n&&!!y,x=b&&n!==s,S=b?y:e,k=v.useMemo(()=>({name:S.name||"",description:S.description||"",content:S.content||"",rules:S.rules,variables:S.requestContextSchema}),[S]),{form:_}=h8t({initialValues:k}),[C,E]=v.useState(0);v.useEffect(()=>{k&&(_.reset(k),E(A=>A+1))},[k,_]);const j=v.useCallback(async()=>{if(!await _.trigger()){Le.error("Please fill in all required fields");return}g(!0);try{const R=sXe(_.getValues());await f.mutateAsync(R),_.reset(_.getValues()),Le.success("Draft saved")}catch(R){Le.error(`Failed to save draft: ${R instanceof Error?R.message:"Unknown error"}`)}finally{g(!1)}},[_,f]),N=v.useCallback(async()=>{if(!await _.trigger()){Le.error("Please fill in all required fields");return}h(!0);try{const R=sXe(_.getValues());await f.mutateAsync(R);const D=(await l.getStoredPromptBlock(t).listVersions({orderBy:{direction:"DESC"},perPage:1})).versions[0];if(!D)throw new Error("No version found to publish");await l.getStoredPromptBlock(t).activateVersion(D.id),c.invalidateQueries({queryKey:["stored-prompt-blocks"]}),c.invalidateQueries({queryKey:["stored-prompt-block"]}),c.invalidateQueries({queryKey:["prompt-block-versions",t]}),Le.success("Prompt block published"),u(d.promptBlocksLink())}catch(R){Le.error(`Failed to publish: ${R instanceof Error?R.message:"Unknown error"}`)}finally{h(!1)}},[_,f,l,t,u,d,c]),I=v.useCallback(async()=>{if(x&&n){h(!0);try{await l.getStoredPromptBlock(t).activateVersion(n),c.invalidateQueries({queryKey:["stored-prompt-blocks"]}),c.invalidateQueries({queryKey:["stored-prompt-block"]}),c.invalidateQueries({queryKey:["prompt-block-versions",t]}),Le.success("Version published"),u(d.promptBlocksLink())}catch(A){Le.error(`Failed to publish version: ${A instanceof Error?A.message:"Unknown error"}`)}finally{h(!1)}}else await N()},[N,x,n,l,t,c,u,d]);return o.jsxs(E1,{leftSlot:o.jsx(p8t,{form:_,onPublish:N,onSaveDraft:j,isSubmitting:p,isSavingDraft:m,isDirty:_.formState.isDirty,hasDraft:r,formResetKey:C,mode:"edit",blockId:t}),children:[x&&o.jsxs(En,{variant:"info",title:"This is a previous version",className:"m-4 mb-0",children:[o.jsx(En.Message,{children:"You are seeing a specific version of the prompt block."}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(ce,{type:"button",variant:"default",size:"sm",onClick:i,children:"View latest version"}),o.jsx(ce,{type:"button",variant:"default",size:"sm",onClick:I,disabled:n===a||p,children:p?"Publishing...":"Publish This Version"})]})]}),o.jsx("form",{className:"h-full",children:o.jsx(n8t,{form:_,formResetKey:C})})]})}function Iss(){const{promptBlockId:e}=Sr(),[t,n]=Ri(),r=t.get("versionId"),{data:s,isLoading:a}=xL(e,{status:"draft"}),{data:i}=m8t({blockId:e??"",params:{orderBy:{direction:"DESC"}}}),l=s?.activeVersionId,c=i?.versions?.[0],u=!!(c&&(!l||c.id!==l)),d=v.useCallback(p=>{n(p?{versionId:p}:{})},[n]),f=v.useCallback(()=>{n({})},[n]);return a?o.jsx(ds,{className:"grid-rows-[1fr]",children:o.jsx(E1,{leftSlot:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Xt,{className:"size-8"})}),children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Xt,{className:"size-8"})})})}):!s||!e?o.jsx(ds,{className:"grid-rows-[1fr]",children:o.jsx(E1,{leftSlot:o.jsx("div",{className:"text-neutral3 flex h-full items-center justify-center",children:"Prompt block not found"}),children:o.jsx("div",{className:"text-neutral3 flex h-full items-center justify-center",children:"Prompt block not found"})})}):o.jsxs(ds,{className:"grid-rows-[1fr]",children:[o.jsx($y,{owner:"cms-prompt-block-edit",children:o.jsxs("div",{className:"flex items-center gap-2",children:[u&&o.jsx(un,{variant:"info",children:"Unpublished changes"}),o.jsx(zXr,{blockId:e,value:r??"",onValueChange:d,variant:"ghost",activeVersionId:l})]})}),o.jsx(Nss,{block:s,blockId:e,selectedVersionId:r,hasDraft:u,latestVersionId:c?.id,activeVersionId:l,onClearVersion:f})]})}function Ass(){const{navigate:e,paths:t}=yn();return o.jsx(ds,{className:"grid-rows-[1fr]",children:o.jsx(NKr,{onSuccess:n=>e(t.scorerLink(n.id))})})}function aXe(e){return{name:e.name,description:e.description||void 0,type:e.type,model:e.model,instructions:e.instructions||void 0,scoreRange:e.scoreRange,defaultSampling:e.defaultSampling?.type==="ratio"&&typeof e.defaultSampling.rate=="number"?e.defaultSampling:{type:"none"}}}function Rss({scorer:e,scorerId:t,selectedVersionId:n,latestVersionId:r,activeVersionId:s,onClearVersion:a}){const i=We(),l=Ur(),{navigate:c,paths:u}=yn(),{updateStoredScorer:d}=kNe(t),[f,p]=v.useState(!1),[h,m]=v.useState(!1),g=v.useRef(null),{data:y}=RKr({scorerId:t,versionId:n??""}),b=!!n&&!!y,x=b&&n!==r,S=b?y:e,k=v.useMemo(()=>({name:S.name||"",description:S.description||"",type:"llm-judge",model:{provider:S.model?.provider||"",name:S.model?.name||""},instructions:S.instructions||"",scoreRange:{min:S.scoreRange?.min??0,max:S.scoreRange?.max??1},defaultSampling:S.defaultSampling}),[S]),{form:_}=Gzt({initialValues:k});v.useEffect(()=>{k&&_.reset(k)},[k,_]);const C=v.useCallback(async()=>{if(!await _.trigger()){Le.error("Please fill in all required fields");return}m(!0);try{const I=aXe(_.getValues());await d.mutateAsync(I),Le.success("Draft saved")}catch(I){Le.error(`Failed to save draft: ${I instanceof Error?I.message:"Unknown error"}`)}finally{m(!1)}},[_,d]),E=v.useCallback(async()=>{if(!await _.trigger()){Le.error("Please fill in all required fields");return}p(!0);try{const I=aXe(_.getValues());await d.mutateAsync(I);const R=(await i.getStoredScorer(t).listVersions({orderBy:{direction:"DESC"},perPage:1})).versions[0];R&&await i.getStoredScorer(t).activateVersion(R.id),l.invalidateQueries({queryKey:["scorers"]}),l.invalidateQueries({queryKey:["stored-scorers"]}),Le.success("Scorer published"),c(u.scorerLink(t))}catch(I){Le.error(`Failed to publish scorer: ${I instanceof Error?I.message:"Unknown error"}`)}finally{p(!1)}},[_,d,i,t,c,u,l]),j=v.useCallback(async()=>{if(x&&n){p(!0);try{await i.getStoredScorer(t).activateVersion(n),l.invalidateQueries({queryKey:["scorers"]}),l.invalidateQueries({queryKey:["stored-scorers"]}),l.invalidateQueries({queryKey:["scorer-versions",t]}),Le.success("Version published"),c(u.scorerLink(t))}catch(N){Le.error(`Failed to publish version: ${N instanceof Error?N.message:"Unknown error"}`)}finally{p(!1)}}else await E()},[E,x,n,i,t,l,c,u]);return o.jsxs(E1,{leftSlot:o.jsx(Wzt,{form:_,onPublish:E,onSaveDraft:C,isSubmitting:f,isSavingDraft:h,formRef:g,mode:"edit"}),children:[x&&o.jsxs(En,{variant:"info",title:"This is a previous version",className:"m-4 mb-0",children:[o.jsx(En.Message,{children:"You are seeing a specific version of the scorer."}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(ce,{type:"button",variant:"default",size:"sm",onClick:a,children:"View latest version"}),o.jsx(ce,{type:"button",variant:"default",size:"sm",onClick:j,disabled:n===s||f,children:f?"Publishing...":"Publish This Version"})]})]}),o.jsx("form",{ref:g,className:"h-full",children:o.jsx(Zzt,{form:_})})]})}function Pss(){const{scorerId:e}=Sr(),[t,n]=Ri(),r=t.get("versionId"),{data:s,isLoading:a}=Qzt(e,{status:"draft"}),{data:i}=Kzt({scorerId:e??"",params:{orderBy:{direction:"DESC"}}}),l=s?.activeVersionId,c=i?.versions?.[0],u=!!(c&&l&&c.id!==l),d=v.useCallback(p=>{n(p?{versionId:p}:{})},[n]),f=v.useCallback(()=>{n({})},[n]);return a?o.jsx(ds,{className:"grid-rows-[1fr]",children:o.jsx(E1,{leftSlot:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Xt,{className:"size-8"})}),children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Xt,{className:"size-8"})})})}):!s||!e?o.jsx(ds,{className:"grid-rows-[1fr]",children:o.jsx(E1,{leftSlot:o.jsx("div",{className:"text-neutral3 flex h-full items-center justify-center",children:"Scorer not found"}),children:o.jsx("div",{className:"text-neutral3 flex h-full items-center justify-center",children:"Scorer not found"})})}):o.jsxs(ds,{className:"grid-rows-[1fr]",children:[o.jsx($y,{owner:"cms-scorer-edit",children:o.jsxs("div",{className:"flex items-center gap-2",children:[u&&o.jsx(un,{variant:"info",children:"Unpublished changes"}),o.jsx(MKr,{scorerId:e,value:r??"",onValueChange:d,variant:"ghost",activeVersionId:l})]})}),o.jsx(Rss,{scorer:s,scorerId:e,selectedVersionId:r,latestVersionId:c?.id,activeVersionId:l,onClearVersion:f})]})}const cIe=(e,t)=>{const n=We();return yt({queryKey:["dataset-item-versions",e,t],queryFn:async()=>((await n.getItemHistory(e,t))?.history??[]).map((s,a)=>({id:s.id,datasetId:s.datasetId,datasetVersion:s.datasetVersion,input:s.input,groundTruth:s.groundTruth,expectedTrajectory:s.expectedTrajectory,toolMocks:s.toolMocks,metadata:s.metadata,validTo:s.validTo,isDeleted:s.isDeleted,createdAt:s.createdAt,updatedAt:s.updatedAt,isLatest:a===0})),enabled:!!e&&!!t})},ube=(e,t,n,r)=>{const s=We();return yt({queryKey:["dataset-item-version",e,t,n],queryFn:async()=>{const a=await s.getDatasetItemVersion(e,t,n);return{id:a.id,datasetId:a.datasetId,datasetVersion:a.datasetVersion,input:a.input,groundTruth:a.groundTruth,expectedTrajectory:a.expectedTrajectory,toolMocks:a.toolMocks,metadata:a.metadata,validTo:a.validTo??null,isDeleted:a.isDeleted??!1,createdAt:a.createdAt,updatedAt:a.updatedAt,isLatest:r!=null?n===r:!1}},enabled:!!e&&!!t&&n>0})},tQ=e=>{const t=We();return yt({queryKey:["experiments",e],queryFn:()=>t.listExperiments(e)})},$ss=(e,t,n,r)=>{const s=We();return yt({queryKey:["compare-experiments",e,t,n,r],queryFn:()=>s.compareExperiments({datasetId:e,experimentIdA:t,experimentIdB:n,...r}),enabled:!!e&&!!t&&!!n})};var o9={exports:{}};var Mss=o9.exports,iXe;function Dss(){return iXe||(iXe=1,(function(e,t){((n,r)=>{e.exports=r()})(Mss,function n(){var r=typeof self<"u"?self:typeof window<"u"?window:r!==void 0?r:{},s,a=!r.document&&!!r.postMessage,i=r.IS_PAPA_WORKER||!1,l={},c=0,u={};function d(N){return N.charCodeAt(0)===65279?N.slice(1):N}function f(N){this._handle=null,this._finished=!1,this._completed=!1,this._halted=!1,this._input=null,this._baseIndex=0,this._partialLine="",this._rowCount=0,this._start=0,this._nextChunk=null,this.isFirstChunk=!0,this._completeResults={data:[],errors:[],meta:{}},(function(I){var A=C(I);A.chunkSize=parseInt(A.chunkSize),I.step||I.chunk||(A.chunkSize=null),this._handle=new y(A),(this._handle.streamer=this)._config=A}).call(this,N),this.parseChunk=function(I,A){var R=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&0<R){let D=this._config.newline;D||(L=this._config.quoteChar||'"',D=this._handle.guessLineEndings(I,L)),I=[...I.split(D).slice(R)].join(D)}this.isFirstChunk&&j(this._config.beforeFirstChunk)&&(L=this._config.beforeFirstChunk(I))!==void 0&&(I=L),this.isFirstChunk=!1,this._halted=!1;var R=this._partialLine+I,L=(this._partialLine="",this._handle.parse(R,this._baseIndex,!this._finished));if(!this._handle.paused()&&!this._handle.aborted()){if(I=L.meta.cursor,R=(this._finished||(this._partialLine=R.substring(I-this._baseIndex),this._baseIndex=I),L&&L.data&&(this._rowCount+=L.data.length),this._finished||this._config.preview&&this._rowCount>=this._config.preview),i)r.postMessage({results:L,workerId:u.WORKER_ID,finished:R});else if(j(this._config.chunk)&&!A){if(this._config.chunk(L,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);this._completeResults=L=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(L.data),this._completeResults.errors=this._completeResults.errors.concat(L.errors),this._completeResults.meta=L.meta),this._completed||!R||!j(this._config.complete)||L&&L.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),R||L&&L.meta.paused||this._nextChunk(),L}this._halted=!0},this._sendError=function(I){j(this._config.error)?this._config.error(I):i&&this._config.error&&r.postMessage({workerId:u.WORKER_ID,error:I,finished:!1})}}function p(N){var I;(N=N||{}).chunkSize||(N.chunkSize=u.RemoteChunkSize),f.call(this,N),this._nextChunk=a?function(){this._readChunk(),this._chunkLoaded()}:function(){this._readChunk()},this.stream=function(A){this._input=A,this._nextChunk()},this._readChunk=function(){if(this._finished)this._chunkLoaded();else{if(I=new XMLHttpRequest,this._config.withCredentials&&(I.withCredentials=this._config.withCredentials),a||(I.onload=E(this._chunkLoaded,this),I.onerror=E(this._chunkError,this)),I.open(this._config.downloadRequestBody?"POST":"GET",this._input,!a),this._config.downloadRequestHeaders){var A,R=this._config.downloadRequestHeaders;for(A in R)I.setRequestHeader(A,R[A])}var L;this._config.chunkSize&&(L=this._start+this._config.chunkSize-1,I.setRequestHeader("Range","bytes="+this._start+"-"+L));try{I.send(this._config.downloadRequestBody)}catch(D){this._chunkError(D.message)}a&&I.status===0&&this._chunkError()}},this._chunkLoaded=function(){I.readyState===4&&(I.status<200||400<=I.status?this._chunkError():(this._start+=this._config.chunkSize||I.responseText.length,this._finished=!this._config.chunkSize||this._start>=(A=>(A=A.getResponseHeader("Content-Range"))!==null?parseInt(A.substring(A.lastIndexOf("/")+1)):-1)(I),this.parseChunk(I.responseText)))},this._chunkError=function(A){A=I.statusText||A,this._sendError(new Error(A))}}function h(N){(N=N||{}).chunkSize||(N.chunkSize=u.LocalChunkSize),f.call(this,N);var I,A,R=typeof FileReader<"u";this.stream=function(L){this._input=L,A=L.slice||L.webkitSlice||L.mozSlice,R?((I=new FileReader).onload=E(this._chunkLoaded,this),I.onerror=E(this._chunkError,this)):I=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){this._finished||this._config.preview&&!(this._rowCount<this._config.preview)||this._readChunk()},this._readChunk=function(){var L=this._input,D=(this._config.chunkSize&&(D=Math.min(this._start+this._config.chunkSize,this._input.size),L=A.call(L,this._start,D)),I.readAsText(L,this._config.encoding));R||this._chunkLoaded({target:{result:D}})},this._chunkLoaded=function(L){this._start+=this._config.chunkSize,this._finished=!this._config.chunkSize||this._start>=this._input.size,this.parseChunk(L.target.result)},this._chunkError=function(){this._sendError(I.error)}}function m(N){var I;f.call(this,N=N||{}),this.stream=function(A){return I=A,this._nextChunk()},this._nextChunk=function(){var A,R;if(!this._finished)return A=this._config.chunkSize,I=A?(R=I.substring(0,A),I.substring(A)):(R=I,""),this._finished=!I,this.parseChunk(R)}}function g(N){f.call(this,N=N||{});var I=[],A=!0,R=!1;this.pause=function(){f.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){f.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function(L){this._input=L,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){R&&I.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),I.length?this.parseChunk(I.shift()):A=!0},this._streamData=E(function(L){try{I.push(typeof L=="string"?L:L.toString(this._config.encoding)),A&&(A=!1,this._checkIsFinished(),this.parseChunk(I.shift()))}catch(D){this._streamError(D)}},this),this._streamError=E(function(L){this._streamCleanUp(),this._sendError(L)},this),this._streamEnd=E(function(){this._streamCleanUp(),R=!0,this._streamData("")},this),this._streamCleanUp=E(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}function y(N){var I,A,R,L,D=Math.pow(2,53),B=-D,H=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,F=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,z=this,q=0,M=0,G=!1,V=!1,$=[],U={data:[],errors:[],meta:{}};function Z(J){return N.skipEmptyLines==="greedy"?J.join("").trim()==="":J.length===1&&J[0].length===0}function K(){if(U&&R&&(ee("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+u.DefaultDelimiter+"'"),R=!1),N.skipEmptyLines&&(U.data=U.data.filter(function(Y){return!Z(Y)})),te()){let Y=function(ne,fe){ne=d(ne),j(N.transformHeader)&&(ne=N.transformHeader(ne,fe)),$.push(ne)};if(U)if(Array.isArray(U.data[0])){for(var J=0;te()&&J<U.data.length;J++)U.data[J].forEach(Y);U.data.splice(0,1)}else U.data.forEach(Y)}function ae(Y,ne){for(var fe=N.header?{}:[],oe=0;oe<Y.length;oe++){var le=oe,he=Y[oe],he=((be,xe)=>(je=>(N.dynamicTypingFunction&&N.dynamicTyping[je]===void 0&&(N.dynamicTyping[je]=N.dynamicTypingFunction(je)),(N.dynamicTyping[je]||N.dynamicTyping)===!0))(be)?xe==="true"||xe==="TRUE"||xe!=="false"&&xe!=="FALSE"&&((je=>{if(H.test(je)&&(je=parseFloat(je),B<je&&je<D))return 1})(xe)?parseFloat(xe):F.test(xe)?new Date(xe):xe===""?null:xe):xe)(le=N.header?oe>=$.length?"__parsed_extra":$[oe]:le,he=N.transform?N.transform(he,le):he);le==="__parsed_extra"?(fe[le]=fe[le]||[],fe[le].push(he)):fe[le]=he}return N.header&&(oe>$.length?ee("FieldMismatch","TooManyFields","Too many fields: expected "+$.length+" fields but parsed "+oe,M+ne):oe<$.length&&ee("FieldMismatch","TooFewFields","Too few fields: expected "+$.length+" fields but parsed "+oe,M+ne)),fe}var de;U&&(N.header||N.dynamicTyping||N.transform)&&(de=1,!U.data.length||Array.isArray(U.data[0])?(U.data=U.data.map(ae),de=U.data.length):U.data=ae(U.data,0),N.header&&U.meta&&(U.meta.fields=$),M+=de)}function te(){return N.header&&$.length===0}function ee(J,ae,de,Y){J={type:J,code:ae,message:de},Y!==void 0&&(J.row=Y),U.errors.push(J)}j(N.step)&&(L=N.step,N.step=function(J){U=J,te()?K():(K(),U.data.length!==0&&(q+=J.data.length,N.preview&&q>N.preview?A.abort():(U.data=U.data[0],L(U,z))))}),this.parse=function(J,ae,de){var Y=N.quoteChar||'"',Y=(N.newline||(N.newline=this.guessLineEndings(J,Y)),R=!1,N.delimiter?j(N.delimiter)&&(N.delimiter=N.delimiter(J),U.meta.delimiter=N.delimiter):((Y=((ne,fe,oe,le,he)=>{var be,xe,je,ke;he=he||[","," ","|",";",u.RECORD_SEP,u.UNIT_SEP];for(var Ae=0;Ae<he.length;Ae++){for(var Me,ue=he[Ae],re=0,se=0,me=0,we=(je=void 0,new x({comments:le,delimiter:ue,newline:fe,preview:10}).parse(ne)),Ne=0;Ne<we.data.length;Ne++)oe&&Z(we.data[Ne])?me++:(Me=we.data[Ne].length,se+=Me,je===void 0?je=Me:0<Me&&(re+=Math.abs(Me-je),je=Me));0<we.data.length&&(se/=we.data.length-me),(xe===void 0||re<=xe)&&(ke===void 0||ke<se)&&1.99<se&&(xe=re,be=ue,ke=se)}return{successful:!!(N.delimiter=be),bestDelimiter:be}})(J,N.newline,N.skipEmptyLines,N.comments,N.delimitersToGuess)).successful?N.delimiter=Y.bestDelimiter:(R=!0,N.delimiter=u.DefaultDelimiter),U.meta.delimiter=N.delimiter),C(N));return N.preview&&N.header&&Y.preview++,I=J,A=new x(Y),U=A.parse(I,ae,de),K(),G?{meta:{paused:!0}}:U||{meta:{paused:!1}}},this.paused=function(){return G},this.pause=function(){G=!0,A.abort(),I=j(N.chunk)?"":I.substring(A.getCharIndex())},this.resume=function(){z.streamer._halted?(G=!1,z.streamer.parseChunk(I,!0)):setTimeout(z.resume,3)},this.aborted=function(){return V},this.abort=function(){V=!0,A.abort(),U.meta.aborted=!0,j(N.complete)&&N.complete(U),I=""},this.guessLineEndings=function(ne,Y){ne=ne.substring(0,1048576);var Y=new RegExp(b(Y)+"([^]*?)"+b(Y),"gm"),de=(ne=ne.replace(Y,"")).split("\r"),Y=ne.split(`
705
705
  `),ne=1<Y.length&&Y[0].length<de[0].length;if(de.length===1||ne)return`
@@ -718,7 +718,7 @@ Token usage: ${n} input + ${r} output = ${s} total`:`The model stopped generatin
718
718
  }
719
719
  ]`})]})]})}function yis({errors:e,maxErrors:t=5}){if(e.length===0)return null;const n=e.slice(0,t),r=e.length-t;return o.jsxs("div",{className:"bg-accent2/10 border-accent2/30 rounded-md border p-3",children:[o.jsxs("div",{className:"text-accent2 mb-2 flex items-center gap-2",children:[o.jsx(qe,{children:o.jsx(yf,{className:"h-4 w-4"})}),o.jsxs("span",{className:"text-sm font-medium",children:[e.length," validation error",e.length!==1?"s":""]})]}),o.jsx("ul",{className:"text-accent2/80 space-y-1 text-sm",children:n.map((s,a)=>o.jsxs("li",{className:"flex gap-2",children:[o.jsx("span",{className:"shrink-0",children:"•"}),o.jsx("span",{children:s.message})]},a))}),r>0&&o.jsxs("div",{className:"text-accent2/60 mt-2 text-xs",children:["+",r," more error",r!==1?"s":""]})]})}function bis({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=v.useState("upload"),[i,l]=v.useState(null),[c,u]=v.useState({current:0,total:0}),[d,f]=v.useState(null),[p,h]=v.useState(!1),{parseFile:m,isParsing:g,error:y}=Hss(),{batchInsertItems:b}=Ni(),x=v.useCallback(async I=>{try{const A=await m(I);l(A),a("preview")}catch{}},[m]),S=v.useCallback(async()=>{if(!i||i.items.length===0)return;a("importing"),h(!0);const{items:I}=i;u({current:0,total:I.length});try{await b.mutateAsync({datasetId:e,items:I.map(A=>({input:A.input,groundTruth:A.groundTruth,metadata:A.metadata}))}),f({success:I.length,errors:0})}catch{f({success:0,errors:I.length})}u({current:I.length,total:I.length}),h(!1),a("complete")},[i,b,e]),k=v.useCallback(()=>{n(!1),r?.(),d&&d.success>0&&Le.success(`Imported ${d.success} item${d.success!==1?"s":""}`),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150)},[n,r,d]),_=v.useCallback(()=>{p||(n(!1),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150))},[p,n]),C=i&&i.items.length>0&&i.errors.length===0,E=()=>{switch(s){case"upload":return o.jsx(vis,{onFileSelect:x,isParsing:g,error:y?.message});case"preview":return i?o.jsx("div",{className:"flex flex-col gap-4",children:i.errors.length>0?o.jsxs(o.Fragment,{children:[o.jsx(yis,{errors:i.errors}),o.jsx("div",{className:"text-neutral4 text-sm",children:"Please fix the errors in your JSON file and try again."})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"text-neutral4 text-sm",children:["Found ",i.items.length," valid item",i.items.length!==1?"s":""," to import."]}),o.jsx(gis,{items:i.items,maxRows:5})]})}):null;case"importing":return o.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[o.jsx(Xt,{}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-neutral1 text-lg font-medium",children:"Importing items..."}),o.jsxs("div",{className:"text-neutral4 mt-1 text-sm",children:[c.current," of ",c.total]})]})]});case"complete":return o.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[o.jsx("div",{className:"text-4xl",children:d&&d.errors===0?"✓":"⚠"}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-neutral1 text-lg font-medium",children:"Import Complete"}),o.jsxs("div",{className:"text-neutral4 mt-1 text-sm",children:[d?.success??0," item",d?.success!==1?"s":""," imported",d&&d.errors>0&&o.jsxs("span",{className:"text-accent2",children:[" ","(",d.errors," error",d.errors!==1?"s":"",")"]})]})]})]})}},j=()=>{switch(s){case"upload":return o.jsx(ce,{onClick:_,children:"Cancel"});case"preview":return o.jsxs(o.Fragment,{children:[o.jsx(ce,{onClick:()=>a("upload"),children:"Back"}),o.jsxs(ce,{variant:"primary",onClick:S,disabled:!C,children:["Import ",i?.items.length??0," Item",i?.items.length!==1?"s":""]})]});case"importing":return null;case"complete":return o.jsx(ce,{variant:"primary",onClick:k,children:"Done"})}},N={upload:"Import JSON",preview:"Preview Data",importing:"Importing",complete:"Import Complete"};return o.jsx(br,{open:t,onOpenChange:_,children:o.jsxs(xr,{className:"max-h-[90vh] max-w-2xl",children:[o.jsxs(wr,{children:[o.jsx(gr,{children:N[s]}),o.jsx(Ks,{children:"Import dataset items from a JSON file."})]}),o.jsx($r,{className:"max-h-[50vh] min-h-[200px] overflow-y-auto",children:E()}),o.jsx(Tc,{className:"flex justify-end gap-2 px-6 pt-4",children:j()})]})})}const fIe=e=>{const t=We(),{data:n}=kD(e),r=n?.experiments;return yt({queryKey:["dataset-review-items",e,r?.map(s=>s.id)],queryFn:async()=>!r||r.length===0?[]:(await Promise.all(r.map(async a=>{if(!a.datasetId)return[];try{const{results:i}=await t.listDatasetExperimentResults(a.datasetId,a.id);return i.filter(l=>l.status==="needs-review").map(l=>({id:l.id,input:l.input,output:l.output,error:l.error,itemId:l.itemId,experimentId:l.experimentId,datasetId:a.datasetId??void 0,traceId:l.traceId??void 0,scores:l.scores?Object.fromEntries(l.scores.map(c=>[c.scorerId,c.score??0])):{},tags:l.tags??[],comment:""}))}catch{return[]}}))).flat(),enabled:!!e&&!!r&&r.length>0,refetchOnWindowFocus:!1})},xis=e=>{const t=We(),{data:n}=kD(e),r=n?.experiments;return yt({queryKey:["dataset-completed-items",e,r?.map(s=>s.id)],queryFn:async()=>!r||r.length===0?[]:(await Promise.all(r.map(async a=>{if(!a.datasetId)return[];try{const{results:i}=await t.listDatasetExperimentResults(a.datasetId,a.id);return i.filter(l=>l.status==="complete").map(l=>({id:l.id,input:l.input,output:l.output,error:l.error,itemId:l.itemId,experimentId:l.experimentId,datasetId:a.datasetId??void 0,traceId:l.traceId??void 0,scores:l.scores?Object.fromEntries(l.scores.map(c=>[c.scorerId,c.score??0])):{},tags:l.tags??[],comment:""}))}catch{return[]}}))).flat(),enabled:!!e&&!!r&&r.length>0,refetchOnWindowFocus:!1})};function wis(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 p7t({datasetId:e,experimentId:t,featuredItemId:n}){const r=We(),{data:s}=Gx(e),{data:a,isLoading:i}=fIe(e),{data:l,isLoading:c}=xis(e),u=v.useMemo(()=>t?(a??[]).filter(Te=>Te.experimentId===t):a,[a,t]),d=v.useMemo(()=>t?(l??[]).filter(Te=>Te.experimentId===t):l,[l,t]),{updateExperimentResult:f}=Ni(),[p,h]=v.useState(n??null);v.useEffect(()=>{n!==void 0&&h(n)},[n]);const[m,g]=v.useState(null),[y,b]=v.useState(new Set),[x,S]=v.useState(!1),[k,_]=v.useState(!1),[C,E]=v.useState(!1),[j,N]=v.useState(""),[I,A]=v.useState(""),[R,L]=v.useState(""),[D,B]=v.useState([]),[H,F]=v.useState(!1),[z,q]=v.useState(null),M=v.useMemo(()=>z??u??[],[z,u]);v.useEffect(()=>{q(null)},[e,t]),v.useEffect(()=>{u&&z===null&&q(u)},[u,z]);const G=v.useMemo(()=>{const Te=new Set;if(s?.tags)for(const Ce of s.tags)Te.add(Ce);for(const Ce of M)for(const Ee of Ce.tags)Te.add(Ee);return[...Te].sort()},[s,M]),V=v.useCallback(Te=>{!s||!e||(s.tags??[]).includes(Te)},[s,e]),$=v.useMemo(()=>m?m==="__untagged__"?M.filter(Te=>Te.tags.length===0):M.filter(Te=>Te.tags.includes(m)):M,[M,m]),U=v.useMemo(()=>{const Te=new Map;for(const Ce of M)for(const Ee of Ce.tags)Te.set(Ee,(Te.get(Ee)??0)+1);return[...Te.entries()].sort((Ce,Ee)=>Ee[1]-Ce[1])},[M]),Z=v.useMemo(()=>M.filter(Te=>Te.tags.length===0).length,[M]),K=v.useMemo(()=>{let Te=0;return m&&Te++,x&&Te++,Te},[m,x]),te=v.useCallback((Te,Ce)=>{q(Oe=>(Oe??[]).map(Pe=>Pe.id===Te?{...Pe,tags:Ce}:Pe));const Ee=M.find(Oe=>Oe.id===Te);Ee?.experimentId&&Ee?.datasetId&&f.mutate({datasetId:Ee.datasetId,experimentId:Ee.experimentId,resultId:Ee.id,tags:Ce})},[M,f]),ee=v.useCallback((Te,Ce)=>{const Ee=M.find(Oe=>Oe.id===Te);Ee?.traceId&&Ce!==void 0&&r.createFeedback({feedback:{traceId:Ee.traceId,source:"studio",feedbackSource:"studio",feedbackType:"rating",value:Ce==="positive"?1:-1,experimentId:Ee.experimentId??void 0,sourceId:Ee.id}}).catch(()=>{}),q(Oe=>(Oe??[]).map(Pe=>Pe.id===Te?{...Pe,rating:Ce}:Pe))},[M,r]),J=v.useCallback((Te,Ce)=>{const Ee=M.find(Oe=>Oe.id===Te);Ee?.traceId&&r.createFeedback({feedback:{traceId:Ee.traceId,source:"studio",feedbackSource:"studio",feedbackType:"comment",value:Ce,comment:Ce,experimentId:Ee.experimentId??void 0,sourceId:Ee.id}}).catch(()=>{}),q(Oe=>(Oe??[]).map(Pe=>Pe.id===Te?{...Pe,comment:Ce}:Pe))},[M,r]),ae=v.useCallback(Te=>{const Ce=M.find(Ee=>Ee.id===Te);q(Ee=>(Ee??[]).filter(Oe=>Oe.id!==Te)),b(Ee=>{const Oe=new Set(Ee);return Oe.delete(Te),Oe}),p===Te&&h(null),Ce?.experimentId&&Ce?.datasetId&&f.mutate({datasetId:Ce.datasetId,experimentId:Ce.experimentId,resultId:Ce.id,status:null})},[M,f,p]),de=v.useCallback(Te=>{const Ce=M.find(Ee=>Ee.id===Te);q(Ee=>(Ee??[]).filter(Oe=>Oe.id!==Te)),b(Ee=>{const Oe=new Set(Ee);return Oe.delete(Te),Oe}),p===Te&&h(null),Ce?.experimentId&&Ce?.datasetId&&f.mutate({datasetId:Ce.datasetId,experimentId:Ce.experimentId,resultId:Ce.id,status:"complete"})},[M,f,p]),Y=v.useMemo(()=>{const Te=x?d??[]:$;return!x||!m?Te:m==="__untagged__"?Te.filter(Ce=>Ce.tags.length===0):Te.filter(Ce=>Ce.tags.includes(m))},[x,d,$,m]),ne=x?c:!1,fe=v.useMemo(()=>new Set(Y.map(Te=>Te.id)),[Y]),oe=v.useMemo(()=>[...y].filter(Te=>fe.has(Te)).length,[y,fe]),le=Y.length>0&&oe===Y.length,he=oe>0&&!le,be=v.useCallback(Te=>{b(Ce=>{const Ee=new Set(Ce);return Ee.has(Te)?Ee.delete(Te):Ee.add(Te),Ee})},[]),xe=v.useCallback(()=>{b(le?new Set:new Set(Y.map(Te=>Te.id)))},[le,Y]),je=v.useCallback(Te=>{for(const Ce of y){const Ee=M.find(Oe=>Oe.id===Ce);Ee&&!Ee.tags.includes(Te)&&te(Ce,[...Ee.tags,Te])}},[M,y,te]),ke=v.useCallback(Te=>{for(const Ce of y){const Ee=M.find(Oe=>Oe.id===Ce);Ee&&Ee.tags.includes(Te)&&te(Ce,Ee.tags.filter(Oe=>Oe!==Te))}},[M,y,te]),Ae=v.useCallback(()=>{for(const Te of y)de(Te);b(new Set)},[y,de]),Me=v.useCallback(()=>{for(const Te of y)ae(Te);b(new Set)},[y,ae]),ue=v.useCallback(()=>{N(""),E(!0)},[]),re=v.useCallback(async()=>{if(!(!I||!R)){_(!0),E(!1);try{const Te=M.filter(Ee=>y.has(Ee.id));if(Te.length===0){_(!1);return}const Ce=await r.clusterFailures({modelId:`${I}/${R}`,items:Te.map(Ee=>({id:Ee.id,input:Ee.input,output:Ee.output??void 0,error:typeof Ee.error=="string"?Ee.error:Ee.error?String(Ee.error):void 0,scores:Ee.scores,existingTags:Ee.tags.length>0?Ee.tags:void 0})),availableTags:G.length>0?G:void 0,prompt:j||void 0});Ce.proposedTags&&Ce.proposedTags.length>0&&(B(Ce.proposedTags.map(Ee=>({...Ee,accepted:!0}))),F(!0))}catch(Te){console.error("Analysis failed:",Te)}finally{_(!1)}}},[I,R,M,y,r,G,j]),se=v.useCallback(()=>{for(const Te of D){if(!Te.accepted)continue;const Ce=M.find(Ee=>Ee.id===Te.itemId);if(Ce){const Ee=[...new Set([...Ce.tags,...Te.tags])];te(Ce.id,Ee)}}F(!1)},[D,M,te]),me=v.useCallback(Te=>{h(Ce=>Ce===Te?null:Te)},[]),we=v.useMemo(()=>p?Y.find(Te=>Te.id===p)??null:null,[p,Y]),Ne=p?Y.findIndex(Te=>Te.id===p):-1,Re=Ne>0?()=>h(Y[Ne-1].id):void 0,Qe=Ne>=0&&Ne<Y.length-1?()=>h(Y[Ne+1].id):void 0,Ze="auto minmax(15rem,1fr) 10rem 8rem 6rem 6rem";return i?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(Xt,{className:"h-6 w-6"})}):o.jsxs("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:[o.jsx(br,{open:C,onOpenChange:E,children:o.jsxs(xr,{children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Analyze Items"}),o.jsx(Ks,{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(Vy,{value:I,onValueChange:A})]}),o.jsxs("div",{children:[o.jsx(Dt,{className:"mb-1 block text-xs",children:"Model"}),o.jsx(qy,{llmId:I,value:R,onValueChange:L})]})]}),o.jsxs(ye,{variant:"ui-xs",className:"text-neutral3",children:[y.size," item",y.size!==1?"s":""," will be analyzed"]}),o.jsxs("div",{children:[o.jsx(Dt,{className:"text-xs",children:"Instructions (optional)"}),o.jsx($l,{value:j,onChange:Te=>N(Te.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3,className:"mt-1 text-xs"})]})]}),o.jsxs(Tc,{children:[o.jsx(ce,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),o.jsxs(ce,{onClick:re,disabled:!I||!R||k,children:[k?o.jsx(Xt,{className:"mr-1 h-4 w-4"}):null,"Analyze"]})]})]})}),o.jsx(br,{open:H,onOpenChange:F,children:o.jsxs(xr,{className:"max-h-[80vh] max-w-2xl overflow-y-auto",children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Review Proposed Tags"}),o.jsxs(Ks,{children:[D.filter(Te=>Te.accepted).length," of ",D.length," proposals selected"]})]}),o.jsx("div",{className:"space-y-3 py-2",children:D.map((Te,Ce)=>{const Ee=M.find(Oe=>Oe.id===Te.itemId);return o.jsx("div",{className:X("p-3 border rounded-lg",!Te.accepted&&"opacity-50"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(zo,{checked:Te.accepted,onCheckedChange:Oe=>B(Pe=>Pe.map((Ue,Ke)=>Ke===Ce?{...Ue,accepted:!!Oe}:Ue))}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 block truncate",children:Ee?typeof Ee.input=="string"?Ee.input.slice(0,100):JSON.stringify(Ee.input).slice(0,100):Te.itemId}),o.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:Te.tags.map((Oe,Pe)=>o.jsx(t9t,{tag:Oe,onRename:Ue=>B(Ke=>Ke.map((tt,Pt)=>Pt===Ce?{...tt,tags:tt.tags.map((Ot,St)=>St===Pe?Ue:Ot)}:tt)),onRemove:()=>B(Ue=>Ue.map((Ke,tt)=>tt===Ce?{...Ke,tags:Ke.tags.filter((Pt,Ot)=>Ot!==Pe)}:Ke))},`${Oe}-${Pe}`))}),Te.reason&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-1 block italic",children:Te.reason})]})]})},Te.itemId)})}),o.jsxs(Tc,{children:[o.jsx(ce,{variant:"outline",onClick:()=>F(!1),children:"Cancel"}),o.jsxs(ce,{onClick:se,disabled:D.filter(Te=>Te.accepted).length===0,children:["Accept ",D.filter(Te=>Te.accepted).length," proposals"]})]})]})}),o.jsxs("div",{className:X("grid w-full h-full grid-cols-1 gap-4 overflow-y-auto",we&&"grid-cols-[1fr_1fr]"),children:[o.jsxs("div",{className:"grid w-full content-start gap-8 overflow-y-auto",children:[o.jsxs("div",{className:"flex w-full flex-wrap items-center justify-between gap-4 gap-x-6",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs(dt,{children:[o.jsx(dt.Trigger,{asChild:!0,children:o.jsxs(ce,{variant:"outline",size:"md",children:[o.jsx(hit,{}),"Filter",K>0&&o.jsx("span",{className:X("ml-0.5 inline-flex items-center justify-center rounded-full bg-accent1/50 text-neutral5 text-ui-sm w-5 h-5"),children:K})]})}),o.jsxs(dt.Content,{align:"start",className:X("min-w-48"),children:[o.jsxs(dt.Sub,{children:[o.jsxs(dt.SubTrigger,{children:["Status",x&&o.jsx("span",{className:X("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(dt.SubContent,{children:[o.jsx(dt.CheckboxItem,{checked:!x,onCheckedChange:()=>{S(!1),h(null)},onSelect:Te=>Te.preventDefault(),children:"Review Queue"}),o.jsx(dt.CheckboxItem,{checked:x,onCheckedChange:()=>{S(!0),h(null)},onSelect:Te=>Te.preventDefault(),children:"Completed"})]})]}),o.jsxs(dt.Sub,{children:[o.jsxs(dt.SubTrigger,{children:["Tags",m&&o.jsx("span",{className:X("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(dt.SubContent,{children:[o.jsx(dt.CheckboxItem,{checked:!m,onCheckedChange:()=>g(null),onSelect:Te=>Te.preventDefault(),children:"All"}),Z>0&&o.jsx(dt.CheckboxItem,{checked:m==="__untagged__",onCheckedChange:()=>g(m==="__untagged__"?null:"__untagged__"),onSelect:Te=>Te.preventDefault(),children:"Untagged"}),U.length>0&&o.jsx(dt.Separator,{}),U.map(([Te])=>o.jsx(dt.CheckboxItem,{checked:m===Te,onCheckedChange:()=>g(m===Te?null:Te),onSelect:Ce=>Ce.preventDefault(),children:Te},Te))]})]}),K>0&&o.jsxs(o.Fragment,{children:[o.jsx(dt.Separator,{}),o.jsxs(dt.Item,{onSelect:()=>{g(null),S(!1),h(null)},children:[o.jsx(bs,{}),"Clear all filters"]})]})]})]}),K>0&&o.jsxs(ce,{variant:"outline",size:"md",onClick:()=>{g(null),S(!1),h(null)},children:[o.jsx(bs,{}),"Reset"]})]}),!x&&y.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(e9t,{selectedCount:y.size,vocabulary:G,onApplyTag:je,onRemoveTag:ke,onNewTag:Te=>je(Te)}),o.jsxs(dt,{children:[o.jsx(dt.Trigger,{asChild:!0,children:o.jsxs(ce,{disabled:k,children:[k?o.jsx(Xt,{className:"h-4 w-4"}):o.jsx(qe,{size:"sm",children:o.jsx(Na,{})}),"Actions"]})}),o.jsxs(dt.Content,{align:"end",children:[o.jsxs(dt.Item,{onSelect:Ae,children:[o.jsx(qe,{size:"sm",children:o.jsx(lO,{})}),"Complete"]}),o.jsxs(dt.Item,{onSelect:Me,children:[o.jsx(qe,{size:"sm",children:o.jsx(uu,{})}),"Remove"]}),o.jsx(dt.Separator,{}),o.jsxs(dt.Item,{onSelect:ue,children:[o.jsx(qe,{size:"sm",children:o.jsx(Eg,{})}),"Analyze"]})]})]})]})]}),ne?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(Xt,{className:"h-6 w-6"})}):Y.length===0?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsxs("div",{className:"px-8 text-center",children:[o.jsx(ye,{variant:"ui-sm",className:"text-neutral3 block",children:x?"No completed reviews yet":"No items to review"}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 mt-2 block",children:x?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here."})]})}):o.jsxs(ve,{columns:Ze,className:"min-w-0",children:[o.jsxs(ve.Top,{hasLeadingCell:!0,children:[x?o.jsx(ve.TopCell,{children:" "}):o.jsx(ve.TopSelectCell,{checked:le?!0:he?"indeterminate":!1,onToggle:()=>xe(),"aria-label":"Select all"}),o.jsxs(ve.TopCells,{colStart:2,children:[o.jsx(ve.TopCell,{children:"Input"}),o.jsx(ve.TopCell,{children:"Comment"}),o.jsx(ve.TopCell,{children:"Tags"}),o.jsx(ve.TopCell,{children:"Rating"}),o.jsx(ve.TopCell,{children:"Scores"})]})]}),Y.map(Te=>{const Ce=Te.scores?Object.entries(Te.scores):[],Ee=p===Te.id,Oe=o.jsxs(o.Fragment,{children:[o.jsx(ve.Cell,{height:"compact",className:"text-neutral4 min-w-0",children:o.jsx("span",{className:"block truncate",children:wis(Te.input,200)})}),o.jsx(ve.Cell,{height:"compact",className:"min-w-0",children:Te.comment?o.jsx(ye,{variant:"ui-xs",className:"text-neutral3 truncate",children:Te.comment}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsx(ve.Cell,{height:"compact",className:"min-w-0",children:Te.tags.length>0?o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 truncate",children:Te.tags.join(", ")}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsxs(ve.Cell,{height:"compact",children:[Te.rating==="positive"&&o.jsx(qe,{size:"sm",className:"text-positive1",children:o.jsx(Ube,{})}),Te.rating==="negative"&&o.jsx(qe,{size:"sm",className:"text-negative1",children:o.jsx(Bbe,{})}),!Te.rating&&o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})]}),o.jsx(ve.Cell,{height:"compact",children:Ce.length>0?o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(qe,{size:"sm",className:"text-neutral3",children:o.jsx(nm,{})}),o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 font-mono",children:Ce[0][1].toFixed(2)}),Ce.length>1&&o.jsxs(un,{variant:"default",children:["+",Ce.length-1]})]}):o.jsx(ye,{variant:"ui-xs",className:"text-neutral2",children:"—"})})]});return o.jsxs(ve.RowWrapper,{children:[x?o.jsx(ve.Cell,{height:"compact",className:"justify-items-center px-4",children:o.jsx("div",{role:"img","aria-label":Te.error?"Error":"Success",title:Te.error?"Error":"Success",className:X("w-2 h-2 rounded-full",Te.error?"bg-red-700":"bg-green-600")})}):o.jsx(ve.SelectCell,{checked:y.has(Te.id),onToggle:()=>be(Te.id),"aria-label":`Select item ${Te.id}`}),o.jsx(ve.RowButton,{flushLeft:!0,colStart:2,featured:Ee,onClick:()=>me(Te.id),children:Oe})]},Te.id)})]})]}),we&&o.jsx(J8t,{item:we,isCompleted:x,tagVocabulary:G,onRate:Te=>ee(we.id,Te),onSetTags:Te=>{te(we.id,Te);for(const Ce of Te)G.includes(Ce)||V(Ce)},onComment:Te=>J(we.id,Te),onRemove:()=>ae(we.id),onComplete:x?void 0:()=>de(we.id),onPrevious:Re,onNext:Qe,onClose:()=>h(null)})]})]})}function Sis({datasetId:e,onAddItemClick:t,onNavigateToDataset:n}){const{navigate:r}=yn(),[s,a]=Ri(),{tab:i,activeVersion:l,handleTabChange:c}=uIe(s,a),[u,d]=v.useState(!1),[f,p]=v.useState(!1),[h,m]=v.useState(!1),[g,y]=v.useState([]),[b,x]=v.useState(!1),[S,k]=v.useState([]),[_,C]=v.useState(!1),[E,j]=v.useState([]),[N,I]=v.useState(0),[A,R]=v.useState(null),[L,D]=v.useState(""),[B]=c1e(L,300),{data:H}=Gx(e),{data:F=[],total:z,isLoading:q,setEndOfListElement:M,isFetchingNextPage:G,hasNextPage:V}=j1(e,B||void 0,l),{total:$}=j1(e,void 0,l),[U,Z]=v.useState({}),{data:K,isLoading:te}=kD(e,void 0,U),{data:ee}=kD(e),{deleteItems:J}=Ni(),ae=K?.experiments??[],de=ee?.experiments??[],Y=kas({hasSearchQuery:!!B,filteredItemsLength:F.length,unfilteredItemsTotal:$,itemsTotal:z}),{data:ne}=fIe(e),fe=ne?.length??0,oe=se=>{R(se)},le=()=>{R(null)},he=se=>{y(se),m(!0)},be=se=>{k(se),x(!0)},xe=se=>{x(se),se||(k([]),I(me=>me+1))},je=se=>{r(`/datasets/${e}/items?items=${se.join(",")}`)},ke=se=>{r(`/datasets/${e}/versions?ids=${se.join(",")}`)},Ae=se=>{j(se),C(!0)},Me=async()=>{await J.mutateAsync({datasetId:e,itemIds:E}),Le.success(`Deleted ${E.length} items`),C(!1),j([]),I(se=>se+1)},ue=se=>{m(!1),y([]),I(me=>me+1),n?.(se)},re=se=>{m(se),se||(y([]),I(me=>me+1))};return o.jsxs(o.Fragment,{children:[o.jsxs(Dc,{defaultTab:"items",value:i,onValueChange:c,className:"grid h-full grid-rows-[auto_1fr]",children:[o.jsxs(Mc,{children:[o.jsxs(Rr,{value:"items",children:["Items ",o.jsx(Js,{color:"gray",children:Y})]}),o.jsxs(Rr,{value:"experiments",children:["Experiments",o.jsx(Js,{color:"gray",children:ae.length})]}),o.jsxs(Rr,{value:"review",children:["Review",fe>0&&o.jsx(Js,{color:"orange",children:fe})]})]}),o.jsx(Xr,{value:"items",className:"mt-5 grid overflow-auto pb-0",children:o.jsx(mis,{datasetId:e,items:F,isLoading:q,featuredItemId:A,onItemSelect:oe,onItemClose:le,onAddClick:t??(()=>{}),onImportClick:()=>d(!0),onImportJsonClick:()=>p(!0),onBulkDeleteClick:Ae,onCreateDatasetClick:he,onAddToDatasetClick:be,onCompareItemsClick:je,datasetName:H?.name,clearSelectionTrigger:N,setEndOfListElement:M,isFetchingNextPage:G,hasNextPage:V,searchQuery:L,activeSearchQuery:B,onSearchChange:D,currentDatasetVersion:H?.version,onCompareVersionsClick:ke})}),o.jsx(Xr,{value:"experiments",className:"mt-5 grid overflow-auto pb-0",children:o.jsx(zas,{experiments:ae,allExperiments:de,isLoading:te,datasetId:e,filters:U,onFiltersChange:Z})}),o.jsx(Xr,{value:"review",className:"mt-2 overflow-auto pb-0",children:o.jsx(p7t,{datasetId:e})})]}),o.jsx(Aas,{datasetId:e,open:u,onOpenChange:d}),o.jsx(bis,{datasetId:e,open:f,onOpenChange:p}),o.jsx(las,{open:h,onOpenChange:re,items:g,onSuccess:ue}),o.jsx(cas,{open:b,onOpenChange:xe,items:S,currentDatasetId:e}),o.jsx(At,{open:_,onOpenChange:C,children:o.jsxs(At.Content,{children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Delete Items"}),o.jsxs(At.Description,{children:["Are you sure you want to delete ",E.length," item",E.length!==1?"s":"","? This action cannot be undone."]})]}),o.jsxs(At.Footer,{children:[o.jsx(At.Cancel,{children:"Cancel"}),o.jsx(At.Action,{onClick:Me,children:J.isPending?"Deleting...":"Delete"})]})]})})]})}function kis(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 wae({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 Ois({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=v.useState("{}"),[i,l]=v.useState(""),[c,u]=v.useState(""),[d,f]=v.useState(""),[p,h]=v.useState(""),[m,g]=v.useState(null),{addItem:y}=Ni(),b=async C=>{C.preventDefault();let E;try{E=JSON.parse(s)}catch{Le.error("Input must be valid JSON");return}let j;if(i.trim())try{j=JSON.parse(i)}catch{Le.error("Ground Truth must be valid JSON");return}let N;if(c.trim())try{N=JSON.parse(c)}catch{Le.error("Expected Trajectory must be valid JSON");return}let I;if(d.trim())try{const R=JSON.parse(d);if(!Array.isArray(R)){Le.error("Tool Mocks must be a JSON array");return}I=R}catch{Le.error("Tool Mocks must be valid JSON");return}let A;if(p.trim())try{A=JSON.parse(p)}catch{Le.error("Request Context must be valid JSON");return}try{await y.mutateAsync({datasetId:e,input:E,groundTruth:j,expectedTrajectory:N,toolMocks:I,requestContext:A}),Le.success("Item added successfully"),g(null),a("{}"),l(""),u(""),f(""),h(""),n(!1),r?.()}catch(R){const L=kis(R);L?g(L):Le.error(`Failed to add item: ${R instanceof Error?R.message:"Unknown error"}`)}},x=C=>{a(C),m?.field==="input"&&g(null)},S=C=>{l(C),m?.field==="groundTruth"&&g(null)},k=C=>{f(C),m?.field==="toolMocks"&&g(null)},_=()=>{a("{}"),l(""),u(""),f(""),h(""),g(null),n(!1)};return o.jsx(br,{open:t,onOpenChange:n,children:o.jsxs(xr,{className:"max-w-lg",children:[o.jsx(wr,{children:o.jsx(gr,{children:"Add Item"})}),o.jsx($r,{children:o.jsxs("form",{onSubmit:b,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Wr,{value:s,onChange:x,showCopyButton:!1,className:"min-h-[120px]"}),m?.field==="input"&&o.jsx(wae,{field:"input",errors:m.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),o.jsx(Wr,{value:i,onChange:S,showCopyButton:!1,className:"min-h-[80px]"}),m?.field==="groundTruth"&&o.jsx(wae,{field:"groundTruth",errors:m.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),o.jsx(Wr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"item-tool-mocks",children:"Tool Mocks (JSON array, optional)"}),o.jsx(Wr,{value:d,onChange:k,showCopyButton:!1,className:"min-h-[80px]"}),m?.field==="toolMocks"&&o.jsx(wae,{field:"toolMocks",errors:m.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"item-request-context",children:"Request Context (JSON, optional)"}),o.jsx(Wr,{value:p,onChange:h,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ce,{type:"button",onClick:_,children:"Cancel"}),o.jsx(ce,{type:"submit",variant:"primary",disabled:y.isPending,children:y.isPending?"Adding...":"Add Item"})]})]})})]})})}function _is({item:e}){return o.jsx(ma,{withMargins:!1,children:o.jsxs(ma.Column,{children:[o.jsxs(ma.Title,{size:"smaller",children:[o.jsx(LN,{}),o.jsx("span",{className:"truncate",children:e.id}),o.jsx(Pa,{content:e.id,tooltip:`Copy item ID: ${e.id}`})]}),o.jsxs(ma.Description,{children:[o.jsxs(ko,{children:[o.jsx(iit,{})," Created ",nr(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")]}),e.datasetVersion!=null&&o.jsxs(ko,{children:[o.jsx(b_,{})," Version v",e.datasetVersion]})]})]})})}function pIe({item:e}){const t=e?.input?JSON.stringify(e.input,null,2):"null",n=e?.groundTruth?JSON.stringify(e.groundTruth,null,2):"null",r=e?.metadata?JSON.stringify(e.metadata,null,2):"null",s=e?.expectedTrajectory?JSON.stringify(e.expectedTrajectory,null,2):null;return o.jsxs(wNe,{children:[o.jsx(As.CodeSection,{title:"Input",icon:o.jsx(cO,{}),codeStr:t}),o.jsx(As.CodeSection,{title:"Ground Truth",icon:o.jsx(Sg,{}),codeStr:n}),s&&o.jsx(As.CodeSection,{title:"Expected Trajectory",icon:o.jsx(Lbe,{}),codeStr:s}),o.jsx(As.CodeSection,{title:"Metadata",icon:o.jsx(BN,{}),codeStr:r})]})}function Cis({selectedScorers:e,setSelectedScorers:t,disabled:n=!1,container:r}){const{data:s,isLoading:a}=ih(),i=v.useMemo(()=>s?Object.entries(s).map(([l,c])=>({value:l,label:c.scorer?.config?.name||l,description:c.scorer?.config?.description||""})):[],[s]);return o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{children:"Scorers (Optional)"}),o.jsx(ac,{multiple:!0,options:i,value:e,onValueChange:t,placeholder:"Select scorers...",searchPlaceholder:"Search scorers...",emptyText:"No scorers available",disabled:n||a,container:r})]})}const Eis=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function jis({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:a,isLoading:i}=Em(),{data:l,isLoading:c}=Hy(),{data:u,isLoading:d}=ih(),f=e==="agent"?Object.entries(a??{}).map(([g,y])=>({value:g,label:y.name??g})):e==="workflow"?Object.entries(l??{}).map(([g,y])=>({value:g,label:y.name??g})):e==="scorer"?Object.entries(u??{}).map(([g,y])=>({value:g,label:y.scorer?.config?.name??g})):[],p=e==="agent"&&i||e==="workflow"&&c||e==="scorer"&&d,h=g=>{t(g),r("")},m=e==="agent"?"Agent":e==="workflow"?"Workflow":"Scorer";return o.jsxs("div",{className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{children:"Target Type"}),o.jsx(ac,{options:Eis,value:e,onValueChange:h,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(ac,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:p,container:s})]})]})}function Tis({requestContextSchema:e,onChange:t}){const n=v.useMemo(()=>{try{return fm(um(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(j3,{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 Nis({datasetId:e,version:t,requestContextSchema:n,open:r,onOpenChange:s,onSuccess:a}){const i=v.useRef(null),[l,c]=v.useState(""),[u,d]=v.useState(""),[f,p]=v.useState([]),[h,m]=v.useState({}),[g,y]=v.useState(""),{triggerExperiment:b}=Ni(),x=!!(n&&Object.keys(n).length>0),S=l&&u,k=b.isPending,_=()=>{c(""),d(""),p([]),m({}),y("")},C=()=>{if(x){const N=Object.entries(h).filter(([,I])=>I!==void 0&&I!=="");return N.length>0?Object.fromEntries(N):void 0}if(g.trim()){let N;try{N=JSON.parse(g)}catch{throw new Error("Request Context must be valid JSON")}if(!N||typeof N!="object"||Array.isArray(N))throw new Error("Request Context must be a JSON object");return N}},E=async()=>{if(!S)return;let N;try{N=C()}catch(I){const A=I instanceof Error?I.message:"Request Context must be valid JSON";nu.error(A);return}try{const I=await b.mutateAsync({datasetId:e,targetType:l,targetId:u,scorerIds:f.length>0?f:void 0,version:t,requestContext:N});nu.success("Experiment triggered successfully"),s(!1),a?.(I.experimentId),_()}catch(I){const A=I instanceof Error?I.message:"Failed to trigger experiment";nu.error(A)}},j=()=>{k||(s(!1),_())};return o.jsx(br,{open:r,onOpenChange:j,children:o.jsxs(xr,{ref:i,children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Run Experiment"}),o.jsx(Ks,{children:t?`Execute items from ${nr(new Date(t),"MMM d, yyyy")} version against a target.`:"Execute all items in this dataset against a target."})]}),o.jsxs($r,{className:"grid gap-6",children:[o.jsx(jis,{targetType:l,setTargetType:c,targetId:u,setTargetId:d,container:i}),l&&l!=="scorer"&&o.jsx(Cis,{selectedScorers:f,setSelectedScorers:p,disabled:k,container:i}),x?o.jsx(Tis,{requestContextSchema:n,onChange:m}):o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Request Context (JSON, optional)"}),o.jsx(Wr,{value:g,onChange:y,showCopyButton:!1,className:"min-h-[80px]"})]})]}),o.jsxs(Tc,{className:"px-6 pt-4",children:[o.jsx(ce,{onClick:j,disabled:k,children:"Cancel"}),o.jsx(ce,{variant:"primary",onClick:E,disabled:!S||k,children:k?o.jsxs(o.Fragment,{children:[o.jsx(Xt,{className:"h-4 w-4"}),"Running..."]}):"Run"})]})]})})}const Iis=e=>{const t=We();return yt({queryKey:["experiment-trace-light",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return t.getTraceLight(e)},enabled:!!e})},hIe=e=>o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 9.45892 8.88606",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{d:"M8.53702 7.36403C8.98547 7.36403 9.34918 7.70502 9.34918 8.12535C9.34906 8.54559 8.9854 8.88606 8.53702 8.88606H5.6839C5.23552 8.88606 4.87186 8.54559 4.87174 8.12535C4.87174 7.70502 5.23545 7.36403 5.6839 7.36403H8.53702Z",fill:"currentColor"}),o.jsx("path",{d:"M8.53702 3.67209C8.98547 3.67209 9.34918 4.01309 9.34918 4.43342C9.34911 4.8537 8.98543 5.19413 8.53702 5.19413H5.6839C5.23549 5.19413 4.87181 4.8537 4.87174 4.43342C4.87174 4.01309 5.23545 3.67209 5.6839 3.67209H8.53702Z",fill:"currentColor"}),o.jsx("path",{d:"M8.67155 0C9.10635 2.06584e-05 9.45892 0.341006 9.45892 0.761326C9.45878 1.18153 9.10627 1.52201 8.67155 1.52203H2.88163C2.4469 1.52203 2.0944 1.18154 2.09427 0.761326C2.09427 0.340993 2.44681 3.80132e-08 2.88163 0H8.67155Z",fill:"currentColor"}),o.jsx("path",{d:"M0.757606 0.760086V4.01122H3.50594V4.76883H0.759466L0.762566 5.4291C0.76837 6.70703 1.8058 7.73972 3.08374 7.73973H3.67953V8.49796H3.08374C1.38863 8.49795 0.0120204 7.1273 0.00433981 5.4322L0 4.39188V0.760086H0.757606Z",fill:"currentColor"})]});function Sae(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function Ais({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(xn.SectionHeading,{icon:o.jsx(zp,{}),className:"mb-2",children:"Tool Mocks"}),s&&o.jsx(En,{variant:"destructive",title:"Mock mismatch",children:o.jsxs(En.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: ",Sae(s.args)]}),n.length>0&&o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Unconsumed mocks: ",n.map(i=>Sae(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:Sae(i.args)})]}),o.jsx("span",{className:`shrink-0 rounded px-2 py-0.5 text-xs ${Ris(i.outcome)}`,children:i.outcome})]},`${i.outcome}-${i.toolName}-${l}`))})]})}function Ris(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 Pis({result:e,scores:t,onPrevious:n,onNext:r,onClose:s,onShowTrace:a,onOpenInReview:i,onScoreClick:l,featuredScoreId:c,onFlagForReview:u,collapsed:d,onCollapsedChange:f}){const[p,h]=v.useState(!1),m=d??p,g=f??h,y=!!e?.error,b=Iz(e?.input),x=Iz(e?.output),S=Iz(e?.groundTruth),k=u&&e.status!=="needs-review"&&e.status!=="complete",_=Array.isArray(e.tags)?e.tags:[];return o.jsxs(xn,{collapsed:m,children:[o.jsxs(xn.Header,{children:[o.jsxs(xn.Heading,{children:["Result ",o.jsxs("b",{children:["# ",e.id.length>12?`${e.id.slice(0,12)}…`:e.id]})]}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[f&&o.jsx(ce,{size:"md",tooltip:m?"Expand panel":"Collapse panel",onClick:()=>g(!m),children:m?o.jsx(uit,{}):o.jsx(cit,{})}),o.jsx(xn.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Previous result",nextLabel:"Next result"}),o.jsxs(ce,{size:"md",onClick:a,disabled:!e.traceId,children:[o.jsx(hIe,{}),"Trace"]}),o.jsx(xn.CloseButton,{onClick:s,tooltip:"Close result panel"})]})]}),!m&&o.jsxs(xn.Content,{children:[o.jsxs("div",{className:"mb-6 grid gap-4",children:[o.jsxs(Ut,{children:[o.jsx(Ut.Key,{children:"Item Id"}),o.jsx(Ut.ValueWithCopyBtn,{copyTooltip:"Copy Item Id to clipboard",copyValue:e.itemId,children:e.itemId}),o.jsx(Ut.Key,{children:"Created"}),o.jsx(Ut.Value,{children:nr(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")})]}),y&&o.jsx(En,{variant:"destructive",title:"Error",children:o.jsx(En.Message,{children:Iz(e?.error&&typeof e.error=="object"?e.error.message:e?.error)})}),t&&t.length>0&&o.jsxs(ve,{columns:"1fr 1fr",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Scorer"}),o.jsx(ve.TopCell,{children:"Score"})]}),t.map(C=>o.jsxs(ve.RowButton,{featured:c===C.id,onClick:()=>l?.(C.id),children:[o.jsx(ve.Cell,{height:"compact",children:C.scorerId}),o.jsx(ve.MonoCell,{children:C.score.toFixed(3)})]},C.id))]}),e.toolMockReport&&o.jsx(Ais,{report:e.toolMockReport}),(e.status||_.length>0||k)&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(xn.SectionHeading,{icon:o.jsx(BN,{}),className:"mb-2",children:"Review"}),(e.status||_.length>0)&&o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.status&&o.jsx("span",{className:`rounded-full px-2 py-0.5 text-xs font-medium ${e.status==="needs-review"?"bg-orange-500/10 text-orange-400":e.status==="complete"?"bg-accent1/10 text-accent1":"bg-neutral3/10 text-neutral4"}`,children:e.status}),_.map(C=>o.jsx("span",{className:"bg-surface4 text-neutral4 rounded px-2 py-0.5 text-xs",children:C},C))]}),k&&o.jsx("div",{children:o.jsxs(ce,{size:"sm",onClick:()=>u(e.id),children:[o.jsx(UV,{}),"Flag for Review"]})}),e.status==="needs-review"&&i&&o.jsx("div",{children:o.jsxs(ce,{size:"sm",onClick:i,children:[o.jsx(Sa,{}),"Review"]})})]})]}),o.jsxs("div",{className:"grid gap-3",children:[o.jsx(xn.CodeSection,{title:"Input",icon:o.jsx(LN,{}),codeStr:b}),o.jsx(xn.CodeSection,{title:"Output",icon:o.jsx(Sg,{}),codeStr:x}),o.jsx(xn.CodeSection,{title:"Ground Truth",icon:o.jsx(zbe,{}),codeStr:S})]})]})]})}function Iz(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function $is({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 p=!!(d&&f),h=[p?"auto":"",...s.map(g=>g.size)].filter(Boolean).join(" "),m=s.some(g=>g.name==="input");return t?o.jsx(ol,{columns:h}):o.jsxs(ve,{columns:h,className:"min-w-0",children:[o.jsxs(ve.Top,{hasLeadingCell:p,children:[p&&o.jsx(ve.TopCell,{children:" "}),p?o.jsx(ve.TopCells,{colStart:2,children:s.map(g=>o.jsx(ve.TopCell,{children:g.label},g.name))}):s.map(g=>o.jsx(ve.TopCell,{children:g.label},g.name))]}),e.length===0?o.jsx(ve.NoMatch,{message:"No results yet"}):o.jsxs(o.Fragment,{children:[e.map(g=>{const y=!!g.error,b=g.id===n,x=o.jsxs(o.Fragment,{children:[o.jsx(ve.IdCell,{id:g.itemId}),o.jsx(ve.Cell,{height:"compact",children:o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:o.jsx("div",{className:"relative flex h-full w-10 items-center justify-center bg-transparent",children:o.jsx("div",{role:"img","aria-label":y?"Error":"Success",className:X("w-2 h-2 rounded-full",y?"bg-red-700":"bg-green-600")})})}),o.jsx(Rn,{children:y?"Error":"Success"})]})}),m&&o.jsx(ve.MonoCell,{children:Dis(Mis(g.input),200)}),i?.map(S=>{const _=a?.[g.itemId]?.find(C=>C.scorerId===S);return o.jsx(ve.Cell,{height:"compact",className:"text-neutral3 text-ui-smd font-mono",children:_!=null?_.score.toFixed(3):"-"},S)})]});return p?o.jsxs(ve.RowWrapper,{children:[o.jsx(ve.SelectCell,{checked:d.has(g.id),onToggle:()=>f(g.id),"aria-label":`Select result ${g.itemId}`}),o.jsx(ve.RowButton,{flushLeft:!0,colStart:2,featured:b,onClick:()=>r(g.id),children:x})]},g.id):o.jsx(ve.RowButton,{featured:b,onClick:()=>r(g.id),children:x},g.id)}),o.jsx(ve.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function Mis(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Dis(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}function Lis(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function Fis({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s,collapsed:a,onCollapsedChange:i}){const[l,c]=v.useState(!1),u=a??l,d=i??c,f=Lis(e),p=f?"N/A — code-based scorer":"N/A — step not configured";return o.jsxs(xn,{collapsed:u,children:[o.jsxs(xn.Header,{children:[o.jsxs(xn.Heading,{children:["Score ",o.jsx("b",{children:e.scorerId})]}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[i&&o.jsx(ce,{size:"md",tooltip:u?"Expand panel":"Collapse panel",onClick:()=>d(!u),children:u?o.jsx(uit,{}):o.jsx(cit,{})}),(n||t)&&o.jsx(xn.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:"Previous score",nextLabel:"Next score"}),s&&o.jsxs(ce,{size:"md",onClick:s,disabled:!e.traceId,children:[o.jsx(hIe,{}),"Trace"]}),o.jsx(xn.CloseButton,{onClick:r,tooltip:"Close score panel"})]})]}),!u&&o.jsx(xn.Content,{children:o.jsxs("div",{className:"grid gap-3",children:[o.jsx(xn.CodeSection,{title:`Score: ${e.score}`,icon:o.jsx(nm,{}),codeStr:e.reason||p,simplified:!0}),!f&&o.jsxs(o.Fragment,{children:[o.jsx(xn.CodeSection,{title:"Preprocess Prompt",icon:o.jsx(_h,{}),codeStr:e.preprocessPrompt||p,simplified:!0}),o.jsx(xn.CodeSection,{title:"Analyze Prompt",icon:o.jsx(_h,{}),codeStr:e.analyzePrompt||p,simplified:!0}),o.jsx(xn.CodeSection,{title:"Generate Score Prompt",icon:o.jsx(_h,{}),codeStr:e.generateScorePrompt||p,simplified:!0}),o.jsx(xn.CodeSection,{title:"Generate Reason Prompt",icon:o.jsx(_h,{}),codeStr:e.generateReasonPrompt||p,simplified:!0})]})]})})]})}const hXe=[{name:"scorer",label:"Scorer",size:"1fr"},{name:"avg",label:"Avg Score",size:"1fr"},{name:"count",label:"Items Scored",size:"1fr"}];function zis({scoresByItemId:e,experimentStatus:t}){const n=v.useMemo(()=>{if(!e)return[];const r={};for(const s of Object.values(e))for(const a of s)r[a.scorerId]||(r[a.scorerId]={sum:0,count:0}),r[a.scorerId].sum+=a.score,r[a.scorerId].count++;return Object.entries(r).map(([s,{sum:a,count:i}])=>({scorerId:s,avg:a/i,count:i})).sort((s,a)=>s.scorerId.localeCompare(a.scorerId))},[e]);if(n.length===0){const r=t==="running"||t==="pending",s=e!==void 0;let a,i;return r?(a="Experiment in progress",i="Summary metrics will appear here once the experiment completes."):s?(a="No scorers configured",i="Add scorers when triggering an experiment to evaluate results and see summary metrics here."):(a="Loading scores",i="Fetching scorer results…"),o.jsx("div",{className:"flex h-full items-center justify-center py-12",children:o.jsx(Lr,{iconSlot:o.jsx(nm,{className:"text-neutral3 h-8 w-8"}),titleSlot:a,descriptionSlot:i})})}return o.jsxs(vn,{children:[o.jsxs(vn.Header,{columns:hXe,children:[o.jsx(vn.HeaderCol,{children:"Scorer"}),o.jsx(vn.HeaderCol,{children:"Avg Score"}),o.jsx(vn.HeaderCol,{children:"Items Scored"})]}),o.jsx(vn.Scroller,{children:o.jsx(vn.Items,{children:n.map(({scorerId:r,avg:s,count:a})=>o.jsxs(vn.Row,{columns:hXe,children:[o.jsx(vn.TextCell,{children:r}),o.jsx(vn.TextCell,{className:"font-mono",children:s.toFixed(3)}),o.jsx(vn.TextCell,{className:"font-mono",children:a})]},r))})})]})}function h7t({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoading:s,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l}){const[c,u]=v.useState(null),[d,f]=v.useState(null),[p,h]=v.useState(void 0),[m,g]=v.useState(null),[y,b]=v.useState(new Set),[x,S]=v.useState(!1),[k,_]=v.useState(!1),[C,E]=v.useState(!1),[j,N]=v.useState(!1),{updateExperimentResult:I}=Ni(),A=v.useCallback(re=>{b(se=>{const me=new Set(se);return me.has(re)?me.delete(re):me.add(re),me})},[]),R=v.useCallback(()=>b(new Set),[]),L=v.useCallback(()=>{const re=r.filter(se=>!!se.error).map(se=>se.id);b(new Set(re))},[r]),D=v.useCallback(async re=>{if(x||re.length===0)return;S(!0);let se=0;const me=new Set;try{for(const we of re)try{await I.mutateAsync({datasetId:t,experimentId:e,resultId:we,status:"needs-review"}),se++,me.add(we)}catch{}}finally{S(!1)}me.size>0&&b(we=>{const Ne=new Set(we);for(const Re of me)Ne.delete(Re);return Ne}),se>0&&Le(`${se} result${se>1?"s":""} flagged for review`)},[t,e,x,I]),B=r.find(re=>re.id===c)??null,[H,F]=v.useState("summary"),[z,q]=v.useState(null),M=re=>{F(re),re!=="reviews"&&q(null)},{data:G}=fIe(t),V=(G??[]).filter(re=>re.experimentId===e).length,{data:$}=Q8t(e,n),U=v.useMemo(()=>{if(!$)return[];const re=new Set;for(const se of Object.values($))for(const me of se)re.add(me.scorerId);return[...re].sort()},[$]),Z=re=>{u(re),f(null),h(void 0),g(null)},K=re=>{Z(re===c?null:re)},te=()=>{Z(null)},ee=()=>{if(!B)return;const re=r.findIndex(se=>se.id===B.id);if(re>=0&&re<r.length-1)return()=>Z(r[re+1].id)},J=()=>{if(!B)return;const re=r.findIndex(se=>se.id===B.id);if(re>0)return()=>Z(r[re-1].id)},ae=B?$?.[B.itemId]:void 0,de=ae?.find(re=>re.id===m)??null,Y=re=>{g(re===m?null:re),f(null),h(void 0)},ne=()=>{if(!m||!ae)return;const re=ae.findIndex(se=>se.id===m);if(re>=0&&re<ae.length-1)return()=>g(ae[re+1].id)},fe=()=>{if(!m||!ae)return;const re=ae.findIndex(se=>se.id===m);if(re>0)return()=>g(ae[re-1].id)},{data:oe,isLoading:le}=Iis(d),he=oe?.spans,{data:be,isLoading:xe}=CL(d,p),je=be?.span,{handlePreviousSpan:ke,handleNextSpan:Ae}=lIe(he,p??null,h),Me=(()=>{const re=[],se=!!de,me=!!d;return re.push(k?"auto":se||me?"2fr":"1fr"),se&&re.push(j?"auto":"3fr"),me&&re.push(C?"auto":"3fr"),me&&p&&re.push("3fr"),re.join(" ")})(),ue=v.useMemo(()=>[{name:"itemId",label:"Item ID",size:"7rem"},{name:"status",label:"Status",size:"5rem"},{name:"input",label:"Input",size:"minmax(15rem,1fr)"},...U.map(re=>({name:re,label:re,size:"12rem"}))],[U]);return o.jsxs(Dc,{defaultTab:"summary",value:H,onValueChange:M,className:"grid h-full grid-rows-[auto_1fr] overflow-hidden",children:[o.jsxs(Mc,{children:[o.jsx(Rr,{value:"summary",children:"Summary"}),o.jsx(Rr,{value:"results",children:"Results"}),o.jsxs(Rr,{value:"reviews",children:["Reviews",V>0&&o.jsx(Js,{color:"orange",children:V})]})]}),o.jsx(Xr,{value:"summary",className:"mt-5 overflow-y-auto",children:o.jsx(zis,{scoresByItemId:$,experimentStatus:n})}),o.jsx(Xr,{value:"reviews",className:"mt-2 overflow-auto pb-0",children:o.jsx(p7t,{datasetId:t,experimentId:e,featuredItemId:z})}),o.jsxs(Xr,{value:"results",className:"mt-2 grid grid-rows-[auto_1fr] overflow-hidden",children:[o.jsxs("div",{className:"mb-4",children:[y.size>0&&o.jsxs("div",{className:"bg-surface3 flex items-center gap-2 px-4 py-2",children:[o.jsxs(ye,{variant:"ui-xs",className:"text-neutral5 font-medium",children:[y.size," selected"]}),o.jsx("div",{className:"flex-1"}),o.jsxs(ce,{variant:"outline",size:"sm",disabled:x,onClick:()=>D([...y]),children:[o.jsx(qe,{size:"sm",children:o.jsx(UV,{})}),"Flag for Review"]}),o.jsx(ce,{variant:"ghost",size:"sm",onClick:R,children:"Clear"})]}),r.length>0&&y.size===0&&!s&&o.jsx("div",{className:"flex items-center gap-2 px-4 py-2",children:o.jsx(ce,{variant:"ghost",size:"sm",onClick:L,children:"Select loaded failures"})})]}),o.jsxs("div",{className:X("grid w-full h-full grid-cols-1 gap-4 overflow-y-auto",B&&"grid-cols-[1fr_1fr]"),children:[o.jsx("div",{className:"flex w-full overflow-y-auto",children:o.jsx("div",{className:"grid w-full content-start gap-8 overflow-y-auto",children:o.jsx($is,{results:r,isLoading:s,featuredResultId:c,onResultClick:K,columns:ue,scoresByItemId:$,scorerIds:U,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l,selectedIds:y,onToggleSelect:A})})}),B&&o.jsxs("div",{className:"grid max-h-full min-h-0 content-start gap-4 overflow-auto",style:{gridTemplateRows:Me},children:[o.jsx(Pis,{result:B,scores:ae,onPrevious:J(),onNext:ee(),onClose:te,onScoreClick:Y,featuredScoreId:m,onShowTrace:()=>{B.traceId&&(f(B.traceId),h(void 0),g(null),_(!0),E(!1))},onOpenInReview:()=>{q(B.id),F("reviews")},onFlagForReview:re=>D([re]),collapsed:k,onCollapsedChange:_}),de&&o.jsx(Fis,{score:de,onNext:ne(),onPrevious:fe(),onClose:()=>g(null),onShowTrace:()=>{de.traceId&&(f(de.traceId),h(void 0),_(!0),N(!0),E(!1))},collapsed:j,onCollapsedChange:N}),d&&o.jsxs(o.Fragment,{children:[o.jsx(eIe,{traceId:d,spans:he,isLoading:le,onClose:()=>{f(null),h(void 0),_(!1),N(!1)},onSpanSelect:h,initialSpanId:p??null,placement:"traces-list",showUnavailableFeaturesMsg:!1,collapsed:C,onCollapsedChange:E,LinkComponent:i1,traceHref:`/traces/${d}`}),p&&o.jsx(KNe,{traceId:d,spanId:p,span:je,isLoading:xe,onPrevious:ke,onNext:Ae,onClose:()=>h(void 0)})]})]})]})]})]})}const Bis={pending:o.jsx(uT,{}),running:o.jsx(_fe,{}),completed:o.jsx(fa,{}),failed:o.jsx(bs,{})};function Uis({experiment:e,className:t}){const n=e.status,r=e.totalItems-e.succeededCount-e.failedCount;return o.jsxs("div",{className:X("grid justify-items-end gap-3",t),children:[o.jsxs("div",{className:"text-ui-lg text-neutral4 bg-surface5 flex items-center gap-2 rounded-lg p-1 px-3 capitalize",children:[o.jsx("span",{className:X("w-5 h-5 flex items-center justify-center rounded-full text-black","[&>svg]:w-4 [&>svg]:h-4",{"bg-green-700":n==="completed","bg-red-700":n==="failed","bg-cyan-600":n==="running","bg-yellow-600":n==="pending"}),children:Bis[n]}),e.status]}),o.jsxs("div",{className:X("flex items-center gap-3 text-neutral3 text-ui-md ","[&>span]:flex [&>span]:gap-1 [&>span]:items-center ","[&_b]:text-neutral4 [&_b]:font-semibold"),children:[o.jsxs("span",{children:["Total: ",o.jsx("b",{children:e.totalItems})]}),o.jsxs("span",{children:["Succeeded: ",o.jsx("b",{children:e.succeededCount})]}),o.jsxs("span",{children:["Failed: ",o.jsx("b",{children:e.failedCount})]}),(n==="pending"||n==="running")&&o.jsxs("span",{children:["Pending: ",o.jsx("b",{children:r})]})]})]})}function Vis({onPrevious:e,onNext:t,previousAriaLabel:n="Previous",nextAriaLabel:r="Next"}){return o.jsxs(Mr,{spacing:"close",children:[o.jsxs(ce,{onClick:e,disabled:!e,"aria-label":n,children:[o.jsx(Gq,{})," Prev"]}),o.jsxs(ce,{onClick:t,disabled:!t,"aria-label":r,children:["Next",o.jsx(u3,{})]})]})}function mIe({delta:e}){const t=e>0?o.jsx(Js,{size:"small",color:"green",intensity:"muted",children:o.jsx(jD,{})}):e<0?o.jsx(Js,{size:"small",color:"red",intensity:"muted",children:o.jsx(Cqt,{})}):null;return o.jsxs("span",{className:X("font-mono text-sm text-neutral4 min-w-20"),children:[o.jsx("span",{className:"inline-block w-3",children:e>0?"+ ":e<0?"- ":""}),Math.abs(e).toFixed(2)," ",t]})}function Az(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function qis({item:e,baselineId:t,contenderId:n,baselineVersion:r,contenderVersion:s,onPrevious:a,onNext:i,onClose:l}){const c=e.results[t],u=e.results[n],d=!!(c&&u),f=new Set;if(c)for(const h of Object.keys(c.scores))f.add(h);if(u)for(const h of Object.keys(u.scores))f.add(h);const p=[...f].sort();return o.jsxs(Yr,{withLeftSeparator:!0,children:[o.jsxs(Yr.Toolbar,{children:[o.jsx(Vis,{onPrevious:a,onNext:i,previousAriaLabel:"Previous comparison item",nextAriaLabel:"Next comparison item"}),o.jsx(Mr,{children:o.jsx(ce,{onClick:l,"aria-label":"Close comparison detail panel",children:o.jsx(bs,{})})})]}),o.jsxs(Yr.Content,{className:"pb-6",children:[o.jsx(ma,{withMargins:!1,children:o.jsx(ma.Column,{children:o.jsxs(ma.Title,{size:"smaller",children:[o.jsx(LN,{})," ",e.itemId]})})}),d?o.jsx(o.Fragment,{children:o.jsxs(wNe,{children:[p.length>0&&o.jsxs("div",{className:"grid gap-3",children:[o.jsx("h4",{className:"text-neutral5 text-sm font-medium",children:"Scores"}),o.jsx("div",{className:"grid gap-2",children:p.map(h=>{const m=c?.scores[h]??null,g=u?.scores[h]??null,y=m!=null&&g!=null?g-m:null;return o.jsxs("div",{className:"bg-surface2 flex items-center justify-between gap-4 rounded-lg px-3 py-2",children:[o.jsx("span",{className:"text-neutral5 text-sm font-medium",children:h}),o.jsxs("div",{className:"flex items-center gap-4",children:[o.jsxs("span",{className:"text-neutral3 text-sm",children:[m!=null?m.toFixed(3):"-"," →"," ",g!=null?g.toFixed(3):"-"]}),y!=null&&o.jsx(mIe,{delta:y})]})]},h)})})]}),o.jsx(As.CodeSection,{title:o.jsxs(o.Fragment,{children:[o.jsx(Js,{color:"purple",children:"Baseline "})," Experiment Output"]}),icon:o.jsx(Sg,{}),codeStr:Az(c?.output)}),o.jsx(As.CodeSection,{title:o.jsxs(o.Fragment,{children:[o.jsx(Js,{color:"cyan",children:"Contender "})," Experiment Output"]}),icon:o.jsx(Sg,{}),codeStr:Az(u?.output)}),o.jsx(As.CodeSection,{title:"Item Input",icon:o.jsx(cO,{}),codeStr:Az(e.input)}),o.jsx(As.CodeSection,{title:"Item Ground Truth",icon:o.jsx(zbe,{}),codeStr:Az(e.groundTruth)})]})}):o.jsx(En,{variant:"warning",title:"Comparison not available",children:o.jsx(En.Message,{children:(()=>{const h=c?"Contender":"Baseline",m=c?s:r;return o.jsxs(o.Fragment,{children:["The ",h," experiment was run against dataset",m!=null?` v. ${m}`:"",", which does not contain this item."]})})()})})]})]})}function His({items:e,baselineId:t,contenderId:n,scorerIds:r,featuredItemId:s,columns:a,onItemClick:i}){return o.jsx(Yr,{children:o.jsxs(vn,{children:[o.jsxs(vn.Header,{columns:a,children:[o.jsx(vn.HeaderCol,{children:"Item ID"}),!s&&r.map(l=>o.jsx(vn.HeaderCol,{className:"flex justify-center",children:l},l))]}),o.jsx(vn.Scroller,{children:o.jsx(vn.Items,{children:e.map(l=>{const c=l.results[t],u=l.results[n],d=!!(c&&u);return o.jsx(vn.Row,{children:o.jsxs(vn.RowButton,{item:{id:l.itemId},columns:a,isFeatured:s===l.itemId,onClick:i,children:[o.jsx(vn.IdCell,{id:l.itemId,className:d?"":"text-neutral1"}),!s&&o.jsx(o.Fragment,{children:r.map(f=>{const p=c?.scores[f]??null,h=u?.scores[f]??null,m=p!=null&&h!=null?h-p:null;return o.jsx(vn.Cell,{className:"flex items-center justify-center gap-5 font-mono",children:m!=null?o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"text-neutral2 flex min-w-24 items-center",children:[p?.toFixed(2)," → ",h?.toFixed(2)]}),o.jsx(mIe,{delta:m})]}):o.jsx("span",{className:"text-neutral1",children:"-"})},f)})})]})},l.itemId)})})})]})})}const Wis={baseline:{label:"Baseline",color:"purple",customStyle:"items-end justify-items-end [&>div]:justify-end border-r-0 rounded-r-none"},contender:{label:"Contender",color:"cyan",customStyle:"items-start justify-items-start [&>div]:justify-start border-l-0 rounded-l-none"}};function mXe({datasetId:e,experiment:t,type:n}){const{Link:r}=yn(),{label:s,color:a,customStyle:i}=Wis[n];if(!t)return null;const l=t.createdAt?new Date(t.createdAt):null,c=Y1(t.id)??t.id,u=t.name||c,d=o.jsx(ce,{as:r,href:`/datasets/${e}/experiments/${t.id}`,children:o.jsx("span",{className:"min-w-0 truncate",children:u})});return o.jsxs("div",{className:`border-border1 grid gap-3 rounded-lg border-2 p-5 ${i}`,children:[o.jsxs("div",{className:"flex w-full items-center gap-3 overflow-clip",children:[n==="contender"&&o.jsxs(Js,{size:"small",color:a,children:[s,o.jsx(ym,{})]}),t.description?o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:d}),o.jsx(Rn,{children:t.description})]}):d,n==="baseline"&&o.jsxs(Js,{size:"small",color:a,children:[o.jsx(Ac,{})," ",s]})]}),o.jsxs("div",{className:"text-ui-sm text-neutral3 flex flex-wrap gap-x-4 gap-y-1",children:[t.name&&o.jsxs(ko,{children:[o.jsx(kfe,{})," ",c]}),o.jsxs(ko,{children:[o.jsx(zbe,{})," ",t.targetType," / ",t.targetId]}),o.jsxs(ko,{children:[o.jsx(qV,{})," v",t.datasetVersion??"—"]}),l&&o.jsxs(ko,{children:[o.jsx(oit,{})," ",nr(l,"MMM d, yyyy HH:mm")]})]})]})}function Zis({datasetId:e,experimentIdA:t,experimentIdB:n,onSwap:r}){const[s,a]=v.useState(null),{data:i,isLoading:l,error:c}=$ss(e,t,n),{data:u}=RV(e,t),{data:d}=RV(e,n),f=u&&d&&u.datasetVersion!==d.datasetVersion,p=v.useMemo(()=>{if(!i)return[];const E=new Set;for(const j of i.items)for(const N of Object.values(j.results))if(N)for(const I of Object.keys(N.scores))E.add(I);return[...E].sort()},[i]),h=v.useMemo(()=>{if(!i||p.length===0)return[];const E=i.baselineId,j=t===E?n:t;return p.map(N=>{let I=0,A=0,R=0,L=0;for(const F of i.items){const z=F.results[E]?.scores[N],q=F.results[j]?.scores[N];z!=null&&(I+=z,R++),q!=null&&(A+=q,L++)}const D=R>0?I/R:null,B=L>0?A/L:null,H=D!=null&&B!=null?B-D:null;return{scorerId:N,avgA:D,avgB:B,delta:H}})},[i,p,t,n]),m=[{name:"scorer",label:"Scorer",size:"1fr"},{name:"baselineAvg",label:"Baseline Avg",size:"1fr"},{name:"comparisonAvg",label:"Comparison Avg",size:"1fr"},{name:"delta",label:"Delta",size:"1fr"}],g=v.useMemo(()=>[{name:"itemId",label:"Item ID",size:"8rem"},...s?[]:p.map(E=>({name:E,label:E,size:"1fr"}))],[p,s]),y=i?.items.find(E=>E.itemId===s)??null,b=E=>{a(E===s?null:E)},x=()=>{a(null)},S=()=>{if(!i||!s)return;const E=i.items.findIndex(j=>j.itemId===s);if(E>=0&&E<i.items.length-1)return()=>a(i.items[E+1].itemId)},k=()=>{if(!i||!s)return;const E=i.items.findIndex(j=>j.itemId===s);if(E>0)return()=>a(i.items[E-1].itemId)};if(l)return o.jsx("div",{className:"flex h-64 items-center justify-center",children:o.jsx(Xt,{})});if(c)return o.jsx(En,{variant:"warning",title:"Error loading comparison",children:o.jsx(En.Message,{children:c instanceof Error?c.message:"Unknown error"})});if(!i||i.items.length===0)return o.jsx("div",{className:"text-neutral4 py-8 text-center text-sm",children:"No comparison data"});const _=i.baselineId,C=t===_?n:t;return o.jsxs("div",{className:"grid gap-10",children:[u&&d&&o.jsxs("div",{className:X("relative grid xl:grid-cols-[1fr_auto_1fr] gap-4 xl:gap-0"),children:[o.jsx(mXe,{datasetId:e,experiment:u,type:"baseline"}),o.jsx("div",{className:"before:bg-border1 relative flex items-center justify-center px-[2vw] before:absolute before:inset-y-0 before:left-1/2 before:w-[2px] before:-translate-x-1/2",children:o.jsx("div",{className:"bg-surface2 relative z-1 rounded-lg p-2",children:o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:o.jsx(ce,{onClick:r,children:"VS"})}),o.jsx(Rn,{children:"Switch the order"})]})})}),o.jsx(mXe,{datasetId:e,experiment:d,type:"contender"})]}),f&&o.jsx(En,{variant:"warning",title:"Version mismatch",children:o.jsxs(En.Message,{children:["These experiments used different dataset versions (v",u.datasetVersion," vs v",d.datasetVersion,"). Results may not be directly comparable."]})}),h.length>0&&o.jsxs(vn,{children:[o.jsxs(vn.Header,{columns:m,children:[o.jsx(vn.HeaderCol,{children:"Scorer"}),o.jsx(vn.HeaderCol,{className:"flex justify-center",children:o.jsxs(hKe,{children:[o.jsx(Js,{color:"purple",size:"small",intensity:"muted",children:"Baseline"}),o.jsx(Js,{color:"purple",size:"small",children:"Avg"})]})}),o.jsx(vn.HeaderCol,{className:"flex justify-center",children:o.jsxs(hKe,{children:[o.jsx(Js,{color:"cyan",size:"small",intensity:"muted",children:"Contender"}),o.jsx(Js,{color:"cyan",size:"small",children:"Avg"})]})}),o.jsx(vn.HeaderCol,{className:"flex justify-center",children:"Delta"})]}),o.jsx(vn.Scroller,{children:o.jsx(vn.Items,{children:h.map(({scorerId:E,avgA:j,avgB:N,delta:I})=>o.jsxs(vn.Row,{columns:m,children:[o.jsx(vn.TextCell,{children:E}),o.jsx(vn.TextCell,{className:"text-center font-mono",children:j!=null?j.toFixed(3):"-"}),o.jsx(vn.TextCell,{className:"text-center font-mono",children:N!=null?N.toFixed(3):"-"}),o.jsx(vn.TextCell,{className:"flex justify-center",children:I!=null?o.jsx(mIe,{delta:I}):"-"})]},E))})})]}),o.jsxs(ly,{className:X({"grid-cols-[1fr_2fr]":!!y}),children:[o.jsx(His,{items:i.items,baselineId:_,contenderId:C,scorerIds:p,featuredItemId:s,columns:g,onItemClick:b}),!!y&&o.jsx(qis,{item:y,baselineId:_,contenderId:C,baselineVersion:u?.datasetVersion,contenderVersion:d?.datasetVersion,onPrevious:k(),onNext:S(),onClose:x})]})]})}function Gis({datasetId:e,itemId:t,onVersionSelect:n,onCompareVersionsClick:r,activeVersion:s}){const{data:a,isLoading:i}=cIe(e,t),[l,c]=v.useState(!1),[u,d]=v.useState(new Set),f=b=>{n?.(b)},p=b=>s==null?b.isLatest:b.datasetVersion===s,h=b=>{d(x=>{const S=new Set(x);if(S.has(b))S.delete(b);else if(S.size>=2){const[k]=Array.from(S);return new Set([k,b])}else S.add(b);return S})},m=()=>{c(!1),d(new Set)},g=()=>{c(!0)},y=()=>{u.size===2&&r?.([...u])};return o.jsxs(Yr,{className:"min-w-56",children:[l?o.jsx(Yr.Toolbar,{className:"grid w-full justify-stretch gap-3",children:o.jsxs(Mr,{children:[o.jsx(ce,{onClick:m,children:"Cancel"}),o.jsx(ce,{variant:"primary",disabled:u.size!==2,onClick:y,tooltip:u.size!==2?"Check 2 versions to compare":void 0,className:"grow",children:"Compare"})]})}):o.jsx(o.Fragment,{children:(a||[]).length>1&&o.jsx(Yr.Toolbar,{children:o.jsxs(ce,{onClick:g,className:"w-full",children:[o.jsx(Hw,{})," Compare Ver."]})})}),i?o.jsx(Qis,{}):o.jsxs(vn,{children:[o.jsx(vn.Header,{children:o.jsx(vn.HeaderCol,{children:"Item Version History"})}),o.jsx(vn.Scroller,{children:o.jsx(vn.Items,{children:a?.map(b=>{const x=String(b.datasetVersion),S=typeof b.updatedAt=="string"?new Date(b.updatedAt):b.updatedAt;return o.jsxs(vn.Row,{isSelected:l&&u.has(x),children:[l&&o.jsx(vn.LabelCell,{children:o.jsx(zo,{checked:u.has(x),disabled:b.isDeleted,onCheckedChange:()=>{},onClick:k=>{k.stopPropagation(),b.isDeleted||h(x)},"aria-label":`Select version ${b.datasetVersion}`})}),o.jsx(vn.RowButton,{item:b,columns:[{name:"version",label:"Item Version History",size:"1fr"}],isFeatured:p(b),onClick:()=>f(b),className:"py-2",children:o.jsx(vn.VersionCell,{version:b.datasetVersion,date:S,isLatest:b.isLatest,isDeleted:b.isDeleted})})]},String(b.datasetVersion))})})})]})]})}function Qis(){return o.jsxs(vn,{children:[o.jsx(vn.Header,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(vn.HeaderCol,{children:"Item Version History"})}),o.jsx(vn.Items,{children:Array.from({length:3}).map((e,t)=>o.jsx(vn.Row,{children:o.jsx(vn.RowButton,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(vn.TextCell,{isLoading:!0,children:"Loading..."})})},t))})]})}function Yis(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${nr(n,"MMM dd 'at' H:mm:ss a")}`}return`v${e}`}function Kis({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=$Ne(e),a=(s??[]).map(i=>({value:String(i.version),label:`${Yis(i.version,i.createdAt)}${i.isCurrent?" (current)":""}`}));return o.jsxs(Yr.Toolbar,{className:"grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4",children:[o.jsx("div",{}),o.jsx(Cc,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:a,value:t??"",onValueChange:i=>r?.(i,n??"")}),o.jsx(Cc,{label:"Version B",labelIsHidden:!0,name:"version-b",options:a,value:n??"",onValueChange:i=>r?.(t??"",i)}),o.jsx("div",{})]})}const Xis=[{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"}],Jis={added:{color:"blue",borderColor:"border-blue-900",icon:o.jsx(Zr,{}),tooltip:"Added in this version"},changed:{color:"orange",borderColor:"border-yellow-900",icon:o.jsx(Sit,{}),tooltip:"Changed in this version"},same:{color:"green",borderColor:"border-green-900",icon:o.jsx(QHt,{}),tooltip:"Same in both versions"}};function kae({red:e=!1,tooltip:t}){return o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:o.jsx(Mqt,{className:X("text-neutral3/40 w-5 h-5 ",{"text-red-900":e})})}),t&&o.jsx(Rn,{children:t})]})}function JS({variant:e,version:t}){if(!e)return o.jsxs("span",{className:"text-ui-md text-neutral4",children:["v. ",t]});const{color:n,icon:r,tooltip:s}=Jis[e];return o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children: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(Js,{color:n,size:"small",children:r})]})}),o.jsx(Rn,{children:s})]})}function eos(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function tos({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:a}){const{Link:i}=yn(),l=t>n;return o.jsx(vn,{children:o.jsx(vn.Scroller,{children:o.jsx(vn.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=a.get(c),f=eos(u,d);return o.jsxs(vn.Row,{columns:Xis,children:[o.jsx(vn.IdCell,{id:c,isShortened:!1}),f!=="same"?o.jsxs(o.Fragment,{children:[u?.datasetVersion?o.jsx(vn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",children:!d&&l?o.jsx(JS,{variant:"added",version:u.datasetVersion}):f==="changed"&&l?o.jsx(JS,{variant:"changed",version:u.datasetVersion}):o.jsx(JS,{version:u.datasetVersion})}):o.jsx(vn.Cell,{className:"flex items-center justify-center",children:o.jsx(kae,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?o.jsx(vn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",children:!u&&!l?o.jsx(JS,{variant:"added",version:d.datasetVersion}):f==="changed"&&!l?o.jsx(JS,{variant:"changed",version:d.datasetVersion}):o.jsx(JS,{version:d.datasetVersion})}):o.jsx(vn.Cell,{className:"flex items-center justify-center",children:o.jsx(kae,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):o.jsx(vn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",children:o.jsx(JS,{variant:"same",version:d?.datasetVersion})}),f==="changed"?o.jsx(vn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}/versions?ids=${u?.datasetVersion},${d?.datasetVersion}`,children:"Compare"}):o.jsx(vn.Cell,{children:o.jsx(kae,{tooltip:o.jsxs(o.Fragment,{children:["Comparing is available",o.jsx("br",{})," only for changed items"]})})})]},c)})})})})}const gXe={needsReview:"#facc15",complete:"#22c55e"},nos=[{label:"Needs Review",color:gXe.needsReview},{label:"Reviewed",color:gXe.complete}];function ros({reviewSummary:e,experiments:t,datasets:n,isLoading:r,isError:s}){const{data:a,maxVal:i,totalInPipeline:l}=v.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,p=0;const h=[];for(const m of e.counts){const g=m.needsReview+m.complete;if(g===0)continue;p+=g,g>f&&(f=g);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);h.push({name:x,values:[m.needsReview,m.complete]})}return{data:h,maxVal:f,totalInPipeline:p}},[e,t,n]),c=a.length>0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Review Pipeline",description:"Items in review across experiments."}),c&&o.jsx(Ht.Summary,{value:String(l),label:"Items in pipeline"})]}),r?o.jsx(Ht.Loading,{}):s?o.jsx(Ht.Error,{message:"Failed to load review data"}):o.jsx(Ht.Content,{children:c?o.jsx(AN,{data:a,segments:nos,maxVal:i,fmt:u=>String(u)}):o.jsx(Ht.NoData,{message:"No items have been sent to review yet"})})]})}function gIe(){const e=We();return yt({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function m7t(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 sos(e,t){const n=new Map,r=m7t(e);if(!r.size||!t)return n;for(const s of t){const a=r.get(s.id);if(!a||!s.datasetId||a.needsReview+a.complete===0)continue;const l=n.get(s.datasetId)??{needsReview:0,complete:0};l.needsReview+=a.needsReview,l.complete+=a.complete,n.set(s.datasetId,l)}return n}function aos(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}}const ios=10;function oos(){const[e,t]=v.useState(!1),[n,r]=v.useState(""),[s,a]=v.useState("all"),[i,l]=v.useState("all"),[c,u]=v.useState("all"),[d,f]=v.useState(0),{data:p,isLoading:h,error:m}=Bg({page:d,perPage:ios}),{data:g,isLoading:y,error:b}=tQ(),{data:x}=gIe(),S=v.useMemo(()=>p?.datasets??[],[p?.datasets]),k=p?.pagination?.hasMore??!1,_=v.useMemo(()=>g?.experiments??[],[g?.experiments]),C=v.useMemo(()=>Jss(S),[S]),E=v.useMemo(()=>sos(x,_),[x,_]),j=h||y,N=m||b,I=()=>t(!0),A=v.useCallback(()=>f(q=>q+1),[]),R=v.useCallback(()=>f(q=>Math.max(0,q-1)),[]),L=v.useCallback(q=>{r(q),f(0)},[]),D=v.useCallback(q=>{a(q),f(0)},[]),B=v.useCallback(q=>{l(q),f(0)},[]),H=v.useCallback(q=>{u(q),f(0)},[]);if(N&&ys(N))return o.jsx(lr,{children:o.jsx(Hs,{})});if(N&&xs(N))return o.jsx(lr,{children:o.jsx(Ms,{resource:"datasets"})});if(N)return o.jsx(lr,{children:o.jsx(qi,{title:"Failed to load datasets",message:N.message})});if(S.length===0&&!j&&d===0)return o.jsxs(o.Fragment,{children:[o.jsx(lr,{children:o.jsx(sas,{onCreateClick:I})}),o.jsx(lbe,{open:e,onOpenChange:t})]});const F=s!=="all"||i!=="all"||c!=="all"||n!=="",z=()=>{r(""),a("all"),l("all"),u("all"),f(0)};return o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsx(oas,{search:n,onSearchChange:L,targetFilter:s,onTargetFilterChange:D,experimentFilter:i,onExperimentFilterChange:B,tagFilter:c,onTagFilterChange:H,tagOptions:C,onReset:z,hasActiveFilters:F,onCreateClick:I})}),o.jsx(ras,{datasets:S,experiments:_,reviewByDataset:E,isLoading:j,search:n,targetFilter:s,experimentFilter:i,tagFilter:c,currentPage:d,hasMore:k,onNextPage:A,onPrevPage:R}),o.jsx(lbe,{open:e,onOpenChange:t})]})}function Rz({children:e}){return o.jsxs(Ft,{height:"full",children:[o.jsx("div",{}),o.jsx(Ft.MainArea,{isCentered:!0,children:e})]})}function los(){const{datasetId:e}=Sr(),t=qs(),[n,r]=Ri(),{activeVersion:s}=uIe(n,r),[a,i]=v.useState(!1),[l,c]=v.useState(!1),[u,d]=v.useState(!1),[f,p]=v.useState(!1),[h,m]=v.useState(!1),{data:g,error:y,isLoading:b}=Gx(e),{data:x=[],isLoading:S}=j1(e,void 0,s),k=!S&&x.length===0;if(b)return null;if(y&&ys(y))return o.jsx(Rz,{children:o.jsx(Hs,{})});if(y&&xs(y))return o.jsx(Rz,{children:o.jsx(Ms,{resource:"datasets"})});if(y&&gCe(y)||!b&&!y&&!g)return o.jsx(Rz,{children:o.jsx(Lr,{iconSlot:o.jsx(cy,{}),titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:o.jsxs(ce,{as:ei,to:"/datasets",children:[o.jsx(Ac,{}),"Back to Datasets"]})})});if(y)return o.jsx(Rz,{children:o.jsx(qi,{title:"Failed to load dataset",message:y instanceof Error?y.message:"An unexpected error occurred. Please try again."})});const _=E=>{t(`/datasets/${e}/experiments/${E}`)},C=()=>{t("/datasets")};return o.jsxs(o.Fragment,{children:[o.jsxs(Ft,{height:"full",children:[o.jsx(Ft.TopArea,{children:o.jsxs(Ft.Row,{children:[o.jsxs(Ft.Column,{children:[g?.description&&o.jsx("p",{className:"text-ui-smd text-neutral3 mb-1",children:g.description}),o.jsxs(Ut,{numOfCol:2,children:[o.jsx(Ut.Key,{children:"Created at"}),o.jsx(Ut.Value,{children:g?.createdAt?nr(new Date(g.createdAt),"MMM d, yyyy"):""}),o.jsx(Ut.Key,{children:"Latest version"}),o.jsxs(Ut.Value,{children:["v",g?.version??""]})]})]}),o.jsx(Ft.Column,{children:o.jsxs(Mr,{children:[k?o.jsxs(Pn,{children:[o.jsx(An,{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(ce,{variant:"primary",children:[o.jsx(Of,{}),s!=null?`Run on v${s}`:"Run Experiment"]})})})}),o.jsx(Rn,{children:"Add items to the dataset before running an experiment"})]}):o.jsxs(ce,{variant:"primary",onClick:()=>i(!0),children:[o.jsx(Of,{}),s!=null?`Run on v${s}`:"Run Experiment"]}),o.jsxs(dt,{children:[o.jsx(dt.Trigger,{asChild:!0,children:o.jsx(ce,{size:"lg","aria-label":"Dataset actions menu",children:o.jsx(ND,{})})}),o.jsxs(dt.Content,{align:"end",className:"w-48",children:[o.jsxs(dt.Item,{onSelect:()=>d(!0),children:[o.jsx(rm,{})," Edit Dataset"]}),o.jsxs(dt.Item,{onSelect:()=>m(!0),children:[o.jsx(tm,{})," Duplicate Dataset"]}),o.jsxs(dt.Item,{onSelect:()=>p(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(uu,{})," Delete Dataset"]})]})]})]})})]})}),o.jsx(Ft.MainArea,{children:o.jsx(Sis,{datasetId:e,onAddItemClick:()=>c(!0)})})]}),o.jsx(Nis,{datasetId:e,version:s??void 0,requestContextSchema:g?.requestContextSchema,open:a,onOpenChange:i,onSuccess:_}),o.jsx(Ois,{datasetId:e,open:l,onOpenChange:c}),g&&o.jsx(pas,{open:u,onOpenChange:d,dataset:{id:g.id,name:g.name,description:g?.description||"",targetType:g.targetType,inputSchema:g.inputSchema,groundTruthSchema:g.groundTruthSchema,requestContextSchema:g.requestContextSchema}}),g&&o.jsx(uas,{open:h,onOpenChange:m,sourceDatasetId:g.id,sourceDatasetName:g.name,sourceDatasetDescription:g.description,sourceDatasetTargetType:g.targetType}),g&&o.jsx(mas,{open:f,onOpenChange:p,datasetId:g.id,datasetName:g.name,onSuccess:C})]})}function g7t({experiment:e}){const{Link:t,paths:n}=yn(),{data:r}=Em(),{data:s}=Hy(),{data:a}=ih(),i=()=>{switch(e.targetType){case"agent":return n.agentLink(e.targetId);case"workflow":return n.workflowLink(e.targetId);case"scorer":return n.scorerLink(e.targetId);default:return"#"}},l=()=>{const u=e.targetId;if(!u)return u;switch(e.targetType){case"agent":return r?.[u]?.name??u;case"workflow":return s?.[u]?.name??u;case"scorer":return a?.[u]?.scorer?.config?.name??u;default:return u}},c=e.agentVersion&&e.targetType==="agent"&&e.targetId?`${n.agentLink(e.targetId)}/editor?version=${encodeURIComponent(e.agentVersion)}`:null;return o.jsx(Ft.TopArea,{children:o.jsxs(Ft.Row,{children:[o.jsx(Ft.Column,{children:o.jsxs(Ut,{numOfCol:2,children:[e.name&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Name"}),o.jsx(Ut.Value,{children:e.name})]}),e.description&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Description"}),o.jsx(Ut.Value,{children:e.description})]}),o.jsx(Ut.Key,{children:"Created at"}),o.jsx(Ut.Value,{children:nr(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")}),e.completedAt&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Completed at"}),o.jsx(Ut.Value,{children:nr(new Date(e.completedAt),"MMM d, yyyy 'at' h:mm a")})]}),o.jsx(Ut.Key,{children:"Target"}),o.jsx(Ut.ValueLink,{href:i(),as:t,children:l()}),e.agentVersion&&o.jsxs(o.Fragment,{children:[o.jsx(Ut.Key,{children:"Version"}),c?o.jsx(Ut.ValueLink,{href:c,as:t,children:e.agentVersion}):o.jsx(Ut.Value,{children:e.agentVersion})]})]})}),o.jsx(Ft.Column,{children:o.jsx(Uis,{experiment:e})})]})})}function Pz({children:e}){return o.jsxs(Ft,{height:"full",children:[o.jsx("div",{}),o.jsx(Ft.MainArea,{isCentered:!0,children:e})]})}function cos(){const{datasetId:e,experimentId:t}=Sr(),{data:n,isLoading:r,error:s}=RV(e,t),{data:a,isLoading:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u}=LG({datasetId:e,experimentId:t,experimentStatus:n?.status});return!e||!t||r?null:s&&ys(s)?o.jsx(Pz,{children:o.jsx(Hs,{})}):s&&xs(s)?o.jsx(Pz,{children:o.jsx(Ms,{resource:"datasets"})}):s&&gCe(s)||!r&&!s&&!n?o.jsx(Pz,{children:o.jsx(Lr,{iconSlot:o.jsx(Tbe,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${t}".`,actionSlot:o.jsxs(ce,{as:ei,to:`/datasets/${e}?tab=experiments`,children:[o.jsx(Ac,{}),"Back to Dataset"]})})}):s?o.jsx(Pz,{children:o.jsx(qi,{title:"Failed to load experiment",message:s instanceof Error?s.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Ft,{height:"full",children:[o.jsx(g7t,{experiment:n}),o.jsx(Ft.MainArea,{children:o.jsx(h7t,{experimentId:t,datasetId:e,experimentStatus:n.status,results:a??[],isLoading:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u})})]})}function uos(){const{datasetId:e}=Sr(),[t,n]=Ri(),{error:r}=Gx(e??""),s=t.get("baseline")??"",a=t.get("contender")??"";return r&&ys(r)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Hs,{})})}):r&&xs(r)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ms,{resource:"datasets"})})}):!e||!s||!a?o.jsx(ds,{children:o.jsx(Oy,{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: /datasets/","{datasetId}","/experiments?baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})}):o.jsx(ds,{children:o.jsx(Oy,{children:o.jsxs("div",{className:"mx-auto grid w-full max-w-[100rem] content-start px-12",children:[o.jsxs(ma,{children:[o.jsxs(ma.Column,{children:[o.jsxs(ma.Title,{children:[o.jsx(Hw,{})," Dataset Experiments Comparison"]}),o.jsxs(ma.Description,{children:["Comparing"," ",o.jsx(ei,{to:`/datasets/${e}/experiments/${s}`,children:s.slice(0,8)})," vs"," ",o.jsx(ei,{to:`/datasets/${e}/experiments/${a}`,children:a.slice(0,8)})]})]}),o.jsx(ma.Column,{children:o.jsxs(ce,{as:ei,to:`/datasets/${e}`,children:[o.jsx(Ac,{}),"Back to Dataset"]})})]}),o.jsx(Zis,{datasetId:e,experimentIdA:s,experimentIdB:a,onSwap:()=>{n({baseline:a,contender:s})}})]})})})}function dos(){const{datasetId:e,itemId:t}=Sr(),{Link:n}=yn(),r=qs(),{data:s,isLoading:a,error:i}=cIe(e??"",t??""),{updateItem:l,deleteItem:c}=Ni(),{data:u}=Gx(e??""),d=s?.[0]??null,f=d?.isDeleted??!1,[p,h]=v.useState(null),m=v.useMemo(()=>!d||f?{input:"",groundTruth:"",metadata:"",trajectory:"",toolMocks:"",requestContext:""}:{input:JSON.stringify(d.input,null,2),groundTruth:d.groundTruth?JSON.stringify(d.groundTruth,null,2):"",metadata:d.metadata?JSON.stringify(d.metadata,null,2):"",trajectory:d.expectedTrajectory!=null?JSON.stringify(d.expectedTrajectory,null,2):"",toolMocks:d.toolMocks?.length?JSON.stringify(d.toolMocks,null,2):"",requestContext:d.requestContext?JSON.stringify(d.requestContext,null,2):""},[d,f]),g=d?.datasetVersion??0,[y,b]=v.useState(!1),[x,S]=v.useState(m.input),[k,_]=v.useState(m.groundTruth),[C,E]=v.useState(m.metadata),[j,N]=v.useState(m.trajectory),[I,A]=v.useState(m.toolMocks),[R,L]=v.useState(m.requestContext),[D,B]=v.useState(g);g!==D&&(B(g),S(m.input),_(m.groundTruth),E(m.metadata),N(m.trajectory),A(m.toolMocks),L(m.requestContext));const[H,F]=v.useState(!1),z=ee=>{h(f?ee:ee.isLatest?null:ee)},q=()=>{h(null)},M=!f&&p!=null,G=()=>{M||b(!0)},V=()=>{M||F(!0)},$=async()=>{if(!e||!t)return;let ee;try{ee=JSON.parse(x)}catch{Le.error("Input must be valid JSON");return}let J;if(k.trim())try{J=JSON.parse(k)}catch{Le.error("Ground Truth must be valid JSON");return}let ae;if(C.trim())try{ae=JSON.parse(C)}catch{Le.error("Metadata must be valid JSON");return}let de;const Y=j!==m.trajectory;if(Y&&j.trim())try{de=JSON.parse(j)}catch{Le.error("Expected Trajectory must be valid JSON");return}let ne;const fe=I!==m.toolMocks;if(fe&&I.trim())try{const he=JSON.parse(I);if(!Array.isArray(he)){Le.error("Tool Mocks must be a JSON array");return}ne=he}catch{Le.error("Tool Mocks must be valid JSON");return}let oe;const le=R!==m.requestContext;if(le&&R.trim())try{oe=JSON.parse(R)}catch{Le.error("Request Context must be valid JSON");return}try{await l.mutateAsync({datasetId:e,itemId:t,input:ee,groundTruth:J,metadata:ae,...Y?{expectedTrajectory:de??null}:{},...fe?{toolMocks:ne??[]}:{},...le?{requestContext:oe}:{}}),Le.success("Item updated successfully"),b(!1)}catch(he){Le.error(`Failed to update item: ${he instanceof Error?he.message:"Unknown error"}`)}},U=()=>{d&&(S(JSON.stringify(d.input,null,2)),_(d.groundTruth?JSON.stringify(d.groundTruth,null,2):""),E(d.metadata?JSON.stringify(d.metadata,null,2):""),N(d.expectedTrajectory!=null?JSON.stringify(d.expectedTrajectory,null,2):""),A(d.toolMocks?.length?JSON.stringify(d.toolMocks,null,2):""),L(d.requestContext?JSON.stringify(d.requestContext,null,2):"")),b(!1)},Z=async()=>{if(!(!e||!t))try{await c.mutateAsync({datasetId:e,itemId:t}),Le.success("Item deleted successfully"),F(!1),r(`/datasets/${e}`)}catch(ee){Le.error(`Failed to delete item: ${ee instanceof Error?ee.message:"Unknown error"}`)}},K=p??d,te=K?{id:t??"",datasetId:e??"",datasetVersion:K.datasetVersion,input:K.input,groundTruth:K.groundTruth,expectedTrajectory:K.expectedTrajectory,metadata:K.metadata,createdAt:K.createdAt,updatedAt:K.updatedAt}:null;return i&&ys(i)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Hs,{})})}):i&&xs(i)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ms,{resource:"datasets"})})}):a?null:!e||!t||!s||s.length===0?o.jsx(ds,{children:o.jsx(Oy,{children:o.jsx("div",{className:"text-neutral3 p-4",children:"Item not found"})})}):o.jsxs(o.Fragment,{children:[o.jsx(ds,{children:o.jsx("div",{className:"h-full overflow-hidden px-6 pb-4",children:o.jsxs("div",{className:"mx-auto grid h-full max-w-[60rem] grid-rows-[auto_1fr] gap-6",children:[o.jsxs(ma,{children:[o.jsxs(ma.Column,{children:[o.jsxs(ma.Title,{children:[o.jsx(LN,{}),t," ",o.jsx(Pa,{content:t})]}),o.jsx(ma.Description,{children:o.jsxs(ko,{children:["Item of ",o.jsx(cy,{})," ",u?.name]})}),o.jsxs(ma.Description,{children:[o.jsxs(ko,{children:[o.jsx(iit,{})," Created at"," ",d?.createdAt?nr(new Date(d.createdAt),"MMM d, yyyy"):""]}),o.jsxs(ko,{children:[o.jsx(b_,{})," Latest version v",d?.datasetVersion??""]})]})]}),o.jsx(ma.Column,{children:!y&&!f&&o.jsxs(Mr,{children:[o.jsxs(ce,{onClick:G,disabled:M,title:M?"Return to latest version to edit":void 0,children:[o.jsx(Sit,{})," Edit"]}),o.jsxs(ce,{onClick:V,disabled:M,title:M?"Return to latest version to delete":void 0,children:[o.jsx(uu,{})," Delete"]})]})})]}),o.jsxs(ly,{className:y?"grid-cols-1":"grid-cols-[1fr_auto]",children:[o.jsxs(Yr,{withRightSeparator:!y,children:[f&&d&&o.jsx(En,{variant:"destructive",title:"Item deleted",children:o.jsxs(En.Message,{children:["This item was deleted at version v",d.datasetVersion]})}),!f&&M&&p&&o.jsx(En,{variant:"warning",title:"Previous version",action:o.jsxs(En.Button,{onClick:q,children:[o.jsx(tit,{})," Return to the latest version"]}),children:o.jsxs(En.Message,{children:["Viewing version v",p.datasetVersion]})}),y?o.jsx(d7t,{inputValue:x,setInputValue:S,groundTruthValue:k,setGroundTruthValue:_,metadataValue:C,setMetadataValue:E,trajectoryValue:j,setTrajectoryValue:N,toolMocksValue:I,setToolMocksValue:A,requestContextValue:R,setRequestContextValue:L,validationErrors:null,onSave:$,onCancel:U,isSaving:l.isPending}):te?o.jsx(pIe,{item:te,Link:n}):o.jsx("div",{className:"text-neutral4 text-sm",children:"Item data not available"})]}),!y&&o.jsx(Yr,{children:o.jsx(Gis,{datasetId:e,itemId:t,onClose:()=>{},onVersionSelect:z,onCompareVersionsClick:ee=>{r(`/datasets/${e}/items/${t}/versions?ids=${ee.join(",")}`)},activeVersion:p?.datasetVersion??null})})]})]})})}),o.jsx(At,{open:H,onOpenChange:F,children:o.jsxs(At.Content,{children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Delete Item"}),o.jsx(At.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),o.jsxs(At.Footer,{children:[o.jsx(At.Cancel,{children:"Cancel"}),o.jsx(At.Action,{onClick:Z,children:c.isPending?"Deleting...":"Delete"})]})]})})]})}function vXe(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,metadata:e.metadata??null},null,2)}function fos(){const{datasetId:e}=Sr(),[t,n]=Ri(),r=t.get("items")?.split(",").filter(Boolean)??[],{data:s,error:a}=Gx(e??""),{Link:i}=yn(),[l,c]=v.useState(!1),{data:u}=PV(e??"",r[0]??""),{data:d}=PV(e??"",r[1]??"");return a&&ys(a)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Hs,{})})}):a&&xs(a)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ms,{resource:"datasets"})})}):!e||r.length<2?o.jsx(ds,{children:o.jsx(Oy,{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(ds,{children:[o.jsx($y,{owner:"dataset-items-compare",children:o.jsxs(ce,{as:ei,to:`/datasets/${e}`,variant:"outline",children:[o.jsx(Ac,{}),"Back to Dataset"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:X("grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",{"grid-rows-[auto_auto_1fr]":l}),children:[o.jsxs(ma,{children:[o.jsxs(ma.Column,{children:[o.jsxs(ma.Title,{children:[o.jsx(Hw,{}),"Compare Dataset Items"]}),o.jsx(ma.Description,{children:o.jsxs(ko,{children:["Comparing ",r.length," items of"," ",o.jsx(ei,{to:`/datasets/${e}`,className:"text-info1 hover:underline",children:s?.name||e?.slice(0,8)})]})})]}),o.jsx(ma.Column,{children:o.jsx(Mr,{children:o.jsx(ce,{variant:"primary",onClick:()=>c(f=>!f),children:l?o.jsxs(o.Fragment,{children:[o.jsx(Nbe,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(BHt,{})," Diff View"]})})})})]}),o.jsx(ly,{className:"grid-cols-[1fr_3vw_1fr]",children:r.map((f,p)=>o.jsxs(v.Fragment,{children:[o.jsx(pos,{datasetId:e,itemId:f,Link:i,idx:p,itemIds:r,showContent:!l,onItemChange:h=>{const m=[...r];m[p]=h,n({items:m.join(",")})}}),p==0&&o.jsx("div",{className:X("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},f))}),l&&u&&d&&o.jsx($Ee,{codeA:vXe(u),codeB:vXe(d)})]})})]})}function pos({datasetId:e,itemId:t,Link:n,idx:r,itemIds:s,onItemChange:a,showContent:i=!0}){const{data:l,isLoading:c}=PV(e,t),{data:u}=j1(e),d=new Set(s.filter((p,h)=>h!==r)),f=(u??[]).map(p=>({value:p.id,label:p.id,disabled:d.has(p.id)}));return o.jsxs(Yr,{children:[o.jsxs(Yr.Toolbar,{className:"flex gap-4",children:[o.jsxs(oa,{name:`compare-item-${r}`,value:t,onValueChange:a,children:[o.jsx(ca,{"aria-label":"Item",children:o.jsx(la,{placeholder:"Select item"})}),o.jsx(ua,{children:f.map(p=>o.jsx(Ar,{value:p.value,disabled:p.disabled,children:p.label},p.value))})]}),o.jsxs(ce,{as:n,to:`/datasets/${e}/items/${t}`,children:[o.jsx(b_,{}),"Versions"]})]}),i&&o.jsx(Yr.Content,{children:c?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):l?o.jsxs(o.Fragment,{children:[o.jsx(_is,{item:l}),o.jsx(pIe,{item:l,Link:n})]}):o.jsxs("div",{className:"text-neutral4 text-sm",children:["Item ",t.slice(0,8)," not found"]})})]})}function yXe(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,metadata:e.metadata??null},null,2)}function hos(){const{datasetId:e,itemId:t}=Sr(),[n,r]=Ri(),[s,a]=v.useState(!1),i=n.get("ids")?.split(",").map(Number).filter(h=>!isNaN(h)&&h>0)??[],{data:l,error:c}=Gx(e??""),{Link:u}=yn(),{data:d}=cIe(e??"",t??""),{data:f}=ube(e??"",t??"",i[0]??0,l?.version),{data:p}=ube(e??"",t??"",i[1]??0,l?.version);return c&&ys(c)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Hs,{})})}):c&&xs(c)?o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ms,{resource:"datasets"})})}):!e||!t||i.length<2?o.jsx(ds,{children:o.jsx(Oy,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Select at least two versions to compare."})})})}):o.jsxs(ds,{children:[o.jsx($y,{owner:"dataset-item-versions-compare",children:o.jsxs(ce,{as:ei,to:`/datasets/${e}/items/${t}`,variant:"outline",children:[o.jsx(Ac,{}),"Back to Item"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:X("grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",{"grid-rows-[auto_auto_1fr]":s}),children:[o.jsxs(ma,{children:[o.jsxs(ma.Column,{children:[o.jsxs(ma.Title,{children:[o.jsx(Hw,{}),"Compare Dataset Item Versions"]}),o.jsx(ma.Description,{children:o.jsxs(ko,{children:["Comparing ",i.length," versions of"," ",o.jsx(ei,{to:`/datasets/${e}/items/${t}`,className:"text-info1 hover:underline",children:t})]})})]}),o.jsx(ma.Column,{children:o.jsx(Mr,{children:o.jsx(ce,{variant:"primary",onClick:()=>a(h=>!h),children:s?o.jsxs(o.Fragment,{children:[o.jsx(Nbe,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(CWt,{})," Diff View"]})})})})]}),o.jsx(ly,{className:"grid-cols-[1fr_3vw_1fr]",children:i.map((h,m)=>o.jsxs(v.Fragment,{children:[o.jsx(mos,{datasetId:e,itemId:t,datasetVersion:h,latestVersion:l?.version,allVersions:d??[],versionNumbers:i,Link:u,idx:m,showContent:!s,onVersionChange:g=>{const y=[...i];y[m]=g,r({ids:y.join(",")})}}),m===0&&o.jsx("div",{className:X("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},h))}),s&&f&&p&&o.jsx($Ee,{codeA:yXe(f),codeB:yXe(p)})]})})]})}function mos({datasetId:e,itemId:t,datasetVersion:n,latestVersion:r,allVersions:s,versionNumbers:a,Link:i,idx:l,showContent:c=!0,onVersionChange:u}){const{data:d,isLoading:f}=ube(e,t,n,r),p=new Set(a.filter((g,y)=>y!==l)),h=s.map(g=>{const y=typeof g.updatedAt=="string"?new Date(g.updatedAt):g.updatedAt;return{value:String(g.datasetVersion),label:o.jsxs(o.Fragment,{children:[o.jsxs("b",{children:["v. ",g.datasetVersion]})," - ",nr(y,"MMM d, yyyy h:mm a"),g.isLatest?o.jsx(Js,{color:"blue",size:"small",children:"Latest"}):null]}),disabled:p.has(g.datasetVersion)}}),m=d?{id:d.id,datasetId:e,datasetVersion:d.datasetVersion,input:d.input,groundTruth:d.groundTruth,metadata:d.metadata,createdAt:d.createdAt,updatedAt:d.updatedAt}:null;return o.jsxs(Yr,{children:[o.jsxs(Yr.Toolbar,{className:"grid grid-cols-[auto_1fr] gap-4",children:[o.jsx(b_,{className:"h-6 w-6 opacity-50"}),o.jsxs(oa,{name:`compare-version-${l}`,value:String(n),onValueChange:g=>u(Number(g)),children:[o.jsx(ca,{"aria-label":"Version",className:"w-full",children:o.jsx(la,{placeholder:"Select version"})}),o.jsx(ua,{children:h.map(g=>o.jsx(Ar,{value:g.value,disabled:g.disabled,children:g.label},g.value))})]})]}),c&&o.jsx(Yr.Content,{children:f?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):!d||!m?o.jsxs("div",{className:"text-neutral4 text-sm",children:["Version ",n," not found"]}):o.jsx(pIe,{item:m,Link:i})})]})}function gos(){const{datasetId:e}=Sr(),[t]=Ri(),n=t.get("ids")?.split(",").map(Number).filter(g=>!isNaN(g)&&g>0)??[],r=qs(),{data:s,error:a}=Gx(e??""),i=j1(e??"",void 0,n[0]??null),l=j1(e??"",void 0,n[1]??null),c=v.useMemo(()=>i.data??[],[i.data]),u=v.useMemo(()=>l.data??[],[l.data]),d=v.useMemo(()=>{const g=new Map;for(const y of[...c,...u])g.has(y.id)||g.set(y.id,{id:y.id,createdAt:new Date(y.createdAt)});return[...g.values()].sort((y,b)=>b.createdAt.getTime()-y.createdAt.getTime())},[c,u]),f=v.useMemo(()=>new Map(c.map(g=>[g.id,g])),[c]),p=v.useMemo(()=>new Map(u.map(g=>[g.id,g])),[u]);if(a&&ys(a))return o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Hs,{})})});if(a&&xs(a))return o.jsx(ds,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ms,{resource:"datasets"})})});if(!e||n.length<2)return o.jsx(ds,{children:o.jsx(Oy,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Select at least two versions to compare."})})})});const h=(g,y,b)=>{r(`/datasets/${e}/items/${g}/versions?ids=${y?.datasetVersion??""},${b?.datasetVersion??""}`)},m=(g,y)=>{r(`/datasets/${e}/versions?ids=${g},${y}`,{replace:!0})};return o.jsx(ds,{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(ma,{children:[o.jsxs(ma.Column,{children:[o.jsxs(ma.Title,{children:[o.jsx(gGt,{})," Compare Dataset Versions"]}),o.jsx(ma.Description,{children:o.jsxs(ko,{children:[o.jsx(b_,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),o.jsx(ma.Column,{children:o.jsxs(ce,{as:ei,to:`/datasets/${e}`,children:[o.jsx(Ac,{}),"Back to Dataset"]})})]}),o.jsx(ly,{children:o.jsxs(Yr,{children:[o.jsx(Kis,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:m}),o.jsx(tos,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:p,onItemClick:h})]})})]})})})}function fbe({children:e,className:t}){return o.jsx("div",{className:X("flex flex-wrap gap-8",t),children:e})}function vos(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 yos({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,p=t?.length,h=n?.length,m=r!=null&&s!=null&&s!==0?{changePct:Math.round((r-s)/s*100*10)/10,prevValue:String(s)}:null,g=vos(n);return o.jsxs(o.Fragment,{children:[o.jsxs(es,{children:[o.jsx(es.Label,{children:"Total Scorers"}),i?o.jsx(es.Loading,{}):f!=null?o.jsxs(o.Fragment,{children:[o.jsx(es.Value,{children:String(f)}),o.jsx(es.NoChange,{message:"Static count"})]}):o.jsx(es.NoData,{})]}),o.jsxs(es,{children:[o.jsx(es.Label,{children:"Total Datasets"}),l?o.jsx(es.Loading,{}):p!=null?o.jsxs(o.Fragment,{children:[o.jsx(es.Value,{children:String(p)}),o.jsx(es.NoChange,{message:"Static count"})]}):o.jsx(es.NoData,{})]}),o.jsxs(es,{children:[o.jsx(es.Label,{children:"Avg Score"}),u?o.jsx(es.Loading,{}):r!=null?o.jsxs(o.Fragment,{children:[o.jsx(es.Value,{children:String(r)}),m?o.jsx(es.Change,{changePct:m.changePct,prevValue:m.prevValue}):o.jsx(es.NoChange,{})]}):o.jsx(es.NoData,{})]}),o.jsxs(es,{children:[o.jsx(es.Label,{children:"Total Experiments"}),c?o.jsx(es.Loading,{}):h!=null?o.jsxs(o.Fragment,{children:[o.jsx(es.Value,{children:String(h)}),g?o.jsx(es.Change,{changePct:g.changePct,prevValue:g.prevValue}):o.jsx(es.NoChange,{})]}):o.jsx(es.NoData,{})]}),o.jsxs(es,{children:[o.jsx(es.Label,{children:"Needs Review"}),d?o.jsx(es.Loading,{}):a!=null?o.jsxs(o.Fragment,{children:[o.jsx(es.Value,{children:String(a)}),a>0?o.jsx(es.NoChange,{message:"items pending review"}):o.jsx(es.NoChange,{message:"All caught up"})]}):o.jsx(es.NoData,{})]})]})}const bXe="minmax(9rem,1fr) 1fr auto auto auto auto auto auto auto";function bos(e){return e?(typeof e=="string"?new Date(e):e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}const xos={completed:"success",running:"warning",failed:"error",pending:"neutral"};function wos({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:a="all",datasetFilter:i="all"}){const{paths:l,Link:c}=yn(),u=v.useMemo(()=>{const p=new Map;return t?.forEach(h=>p.set(h.id,h.name)),p},[t]),d=v.useMemo(()=>[...e].sort((p,h)=>{const m=p.createdAt?new Date(p.createdAt).getTime():0;return(h.createdAt?new Date(h.createdAt).getTime():0)-m}),[e]),f=v.useMemo(()=>{const p=s.toLowerCase();return d.filter(h=>{const m=h.datasetId?u.get(h.datasetId)??"":"",g=!p||h.id.toLowerCase().includes(p)||(h.name??"").toLowerCase().includes(p)||m.toLowerCase().includes(p)||(h.targetId??"").toLowerCase().includes(p),y=a==="all"||h.status===a,b=i==="all"||h.datasetId===i;return g&&y&&b})},[d,s,u,a,i]);return r?o.jsx(ol,{columns:bXe}):o.jsxs(ve,{columns:bXe,variant:"striped",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Experiment"}),o.jsx(ve.TopCell,{children:"Dataset"}),o.jsx(ve.TopCell,{children:"Target"}),o.jsx(ve.TopCell,{children:"Status"}),o.jsx(ve.TopCell,{className:"text-center",children:"Items"}),o.jsx(ve.TopCell,{className:"text-center",children:"Succeeded"}),o.jsx(ve.TopCell,{className:"text-center",children:"Failed"}),o.jsx(ve.TopCell,{className:"text-center",children:"Review"}),o.jsx(ve.TopCell,{children:"Date"})]}),f.map(p=>{const h=p.datasetId?u.get(p.datasetId)??Y1(p.datasetId)??p.datasetId:"—",m=p.status??"pending",g=p.succeededCount??0,y=p.failedCount??0,b=p.totalItems??0,x=b>0?Math.round(g/b*100):0;return o.jsxs(ve.RowLink,{to:l.experimentLink(p.id),LinkComponent:c,children:[o.jsx(ve.Cell,{children:o.jsx(u7t,{experiment:p})}),o.jsx(ve.TextCell,{children:h}),o.jsx(ve.Cell,{children:o.jsxs("span",{className:"truncate",children:[p.targetType," ",p.targetId]})}),o.jsx(ve.Cell,{children:o.jsx(bg,{variant:xos[m]??"neutral",withDot:!0,children:m})}),o.jsx(ve.TextCell,{className:"text-center",children:b}),o.jsx(ve.TextCell,{className:"text-center",children:o.jsxs("span",{className:g>0?"text-accent1":"",children:[g," (",x,"%)"]})}),o.jsx(ve.TextCell,{className:"text-center",children:o.jsx("span",{className:y>0?"text-accent2":"",children:y})}),o.jsx(ve.Cell,{className:"text-center",children:(()=>{const S=n?.get(p.id);if(!S)return o.jsx("span",{className:"text-neutral2",children:"—"});const k=S.needsReview+S.complete;return k===0?o.jsx("span",{className:"text-neutral2",children:"—"}):S.needsReview>0?o.jsxs(Js,{size:"small",color:"yellow",children:[S.needsReview," pending"]}):o.jsxs(Js,{size:"small",color:"green",children:[S.complete,"/",k," reviewed"]})})()}),o.jsx(ve.TextCell,{children:bos(p.createdAt)})]},p.id)})]})}const Sos=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function kos(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const $z={completed:"#22c55e",running:"#facc15",pending:"#fb923c",failed:"#f87171"},Oos=[{label:"Completed",color:$z.completed},{label:"Running",color:$z.running},{label:"Pending",color:$z.pending},{label:"Failed",color:$z.failed}];function _os({experiments:e,datasets:t,isLoading:n,isError:r}){const{data:s,maxVal:a}=v.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 p=f.datasetId??"unknown";c.has(p)||c.set(p,{completed:0,running:0,pending:0,failed:0});const h=c.get(p),m=f.status;m in h&&h[m]++}let u=0;return{data:Array.from(c.entries()).map(([f,p])=>{const h=p.completed+p.running+p.pending+p.failed;return h>u&&(u=h),{name:l.get(f)??f.slice(0,12),values:[p.completed,p.running,p.pending,p.failed]}}),maxVal:u}},[e,t]),i=s.length>0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Experiments by Dataset",description:"Experiment status breakdown per dataset."}),i&&o.jsx(Ht.Summary,{value:String(e?.length??0),label:"Total experiments"})]}),n?o.jsx(Ht.Loading,{}):r?o.jsx(Ht.Error,{message:"Failed to load experiments data"}):o.jsx(Ht.Content,{children:i?o.jsx(AN,{data:s,segments:Oos,maxVal:a,fmt:l=>String(l)}):o.jsx(Ht.NoData,{message:"No experiments have been run yet"})})]})}const Cos=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(Nf,{}),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.jsx("div",{className:"flex flex-col items-center gap-2",children:o.jsxs(ce,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/evals/datasets/running-experiments",target:"_blank",rel:"noopener noreferrer",children:["Experiments Documentation ",o.jsx(Sa,{})]})})})});function Eos({search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:i,onReset:l,hasActiveFilters:c}){return o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx($f,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t}),o.jsxs(Mr,{children:[o.jsx(Cc,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...Sos],value:n,onValueChange:r,className:"whitespace-nowrap"}),o.jsx(Cc,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:i,value:s,onValueChange:a,className:"whitespace-nowrap"}),l&&c&&o.jsxs(ce,{onClick:l,size:"sm",variant:"default",children:[o.jsx(bs,{className:"size-3"})," Reset"]})]})]})}function jos(){const[e,t]=v.useState("all"),[n,r]=v.useState({}),{data:s,isLoading:a,error:i}=ih(),{data:l,isLoading:c,error:u}=Bg(),{data:d,isLoading:f,error:p}=tQ(),{data:h,isLoading:m,isError:g,error:y}=PKr(n),{data:b,isLoading:x,isError:S,error:k}=gIe(),_=l?.datasets,C=d?.experiments,E=v.useMemo(()=>aos(b),[b]),j=i||u||p||y||k;return j&&ys(j)?o.jsx(lr,{children:o.jsx(Hs,{})}):j&&xs(j)?o.jsx(lr,{children:o.jsx(Ms,{resource:"evaluation"})}):j?o.jsx(lr,{children:o.jsx(qi,{title:"Failed to load evaluation data",message:j.message})}):o.jsxs(Ft,{width:"wide",height:"full",children:[o.jsx(Ft.TopArea,{children:o.jsx(Ft.Row,{children:o.jsx(Ft.Column,{children:o.jsx(G3,{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(fbe,{children:o.jsx(yos,{scorers:s,datasets:_,experiments:C,avgScore:h?.avgScore??null,prevAvgScore:h?.prevAvgScore??null,totalNeedsReview:E.needsReview,isLoadingScorers:a,isLoadingDatasets:c,isLoadingExperiments:f,isLoadingScores:m,isLoadingReview:x})}),o.jsx(qYr,{summaryData:h?.summaryData??[],overTimeData:h?.overTimeData??[],scorerNames:h?.scorerNames??[],avgScore:h?.avgScore??null,isLoading:m,isError:g}),o.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:[o.jsx(ias,{experiments:C,isLoading:f,isError:!!p}),o.jsx(_os,{experiments:C,datasets:_,isLoading:f,isError:!!p})]}),o.jsx(ros,{reviewSummary:b,experiments:C,datasets:_,isLoading:x,isError:!!S})]})]})}function Tos(){const[e,t]=v.useState(""),[n,r]=v.useState("all"),[s,a]=v.useState("all"),{data:i,isLoading:l,error:c}=Bg(),{data:u,isLoading:d,error:f}=tQ(),{data:p}=gIe(),h=v.useMemo(()=>i?.datasets??[],[i?.datasets]),m=v.useMemo(()=>u?.experiments??[],[u?.experiments]),g=v.useMemo(()=>kos(h),[h]),y=v.useMemo(()=>m7t(p),[p]),b=l||d,x=f||c;if(x&&ys(x))return o.jsx(lr,{children:o.jsx(Hs,{})});if(f&&xs(f))return o.jsx(lr,{children:o.jsx(Ms,{resource:"experiments"})});if(c&&xs(c))return o.jsx(lr,{children:o.jsx(Ms,{resource:"datasets"})});if(x)return o.jsx(lr,{children:o.jsx(qi,{title:"Failed to load experiments",message:x.message})});if(m.length===0&&!b)return o.jsx(lr,{children:o.jsx(Cos,{})});const S=n!=="all"||s!=="all"||e!=="",k=()=>{t(""),r("all"),a("all")};return o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsx(Eos,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:g,onReset:k,hasActiveFilters:S})}),o.jsx(wos,{experiments:m,datasets:h,reviewByExperiment:y,isLoading:b,search:e,statusFilter:n,datasetFilter:s})]})}function Mz({children:e}){return o.jsxs(Ft,{height:"full",children:[o.jsx("div",{}),o.jsx(Ft.MainArea,{isCentered:!0,children:e})]})}function Nos(){const{experimentId:e}=Sr(),{data:t,isLoading:n}=tQ(),s=t?.experiments?.find(h=>h.id===e)?.datasetId??"",{data:a,isLoading:i,error:l}=RV(s,e??""),{data:c,isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p}=LG({datasetId:s,experimentId:e??"",experimentStatus:a?.status});return!e||n||i?null:l&&ys(l)?o.jsx(Mz,{children:o.jsx(Hs,{})}):l&&xs(l)?o.jsx(Mz,{children:o.jsx(Ms,{resource:"datasets"})}):l&&gCe(l)||!n&&!s||!i&&!l&&!a?o.jsx(Mz,{children:o.jsx(Lr,{iconSlot:o.jsx(Tbe,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:o.jsxs(ce,{as:ei,to:"/experiments",children:[o.jsx(Ac,{}),"Back to Experiments"]})})}):l?o.jsx(Mz,{children:o.jsx(qi,{title:"Failed to load experiment",message:l instanceof Error?l.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Ft,{height:"full",children:[o.jsx(g7t,{experiment:a}),o.jsx(Ft.MainArea,{children:o.jsx(h7t,{experimentId:e,datasetId:s,experimentStatus:a.status,results:c??[],isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p})})]})}function Ios({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 v7t({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("ul",{className:"space-y-1",children:e.map(s=>o.jsx(Ios,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function Aos({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(v7t,{connections:a,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function Ros({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(Aos,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):o.jsx(v7t,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?o.jsx("p",{className:"text-red-600",children:String(c)}):null]})}function Pos({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:p,onToolkitChange:h,onLabelChange:m,onConnect:g}){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=>p(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=>h(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:g,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 xXe=e=>e.authorId?.trim()||"shared",$os=(e,t)=>{if(!t||new Set(e.map(xXe)).size<=1)return null;const r=new Map;for(const a of e){const i=xXe(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},Mos=["*","tool-providers:*","tool-providers:admin"];function Dos(){const{data:e}=Cm();return e?.permissions?.some(t=>Mos.includes(t))??!1}function Los(){const[e,t]=v.useState(""),[n,r]=v.useState(""),[s,a]=v.useState(""),i=$I(),l=dZ(e||null),c=Q2t(e||null,n||null),u=G2t(),d=H2t(),f=Dos(),p=i.data?.providers??[],h=l.data?.data??[],m=v.useMemo(()=>c.data?.items??[],[c.data?.items]),g=v.useMemo(()=>$os(m,f),[m,f]),y=S=>{t(S),r("")},b=()=>{!e||!n||u.mutate({providerId:e,toolkit:n,label:s.trim()||null},{onSuccess:()=>{a(""),c.refetch()}})},x=S=>{d.mutate({providerId:e,connectionId:S})};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(Pos,{providers:p,toolkits:h,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(Ros,{providerId:e,toolkit:n,connections:m,groupedByAuthor:g,isAdmin:f,isLoading:c.isLoading,error:c.error,disconnectPending:d.isPending,disconnectError:d.error,onDisconnect:x})]})}function Fos({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(Xh,{className:"h-10 w-10"}),o.jsx("h1",{className:"text-neutral6 text-xl font-semibold",children:e})]}),t,n,r]})})}function y7t({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:a}=uc(),{mutate:i,isPending:l,error:c}=qjr(),{mutate:u,isPending:d,error:f}=Wjr(),{mutate:p,isPending:h}=hPt(),[m,g]=v.useState(n),[y,b]=v.useState(""),[x,S]=v.useState(""),[k,_]=v.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:C}=s,E=C.type==="sso"||C.type==="both",j=C.type==="credentials"||C.type==="both",N=C.sso,I=C.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="/"},B=M=>{M.preventDefault(),A?i({email:x,password:k},{onSuccess:D}):u({email:x,password:k,name:y||void 0},{onSuccess:D})},H=()=>{p({redirectUri:e},{onSuccess:M=>{window.location.href=M.url}})},F=()=>{g(A?"signup":"signin")},z=C.description?o.jsxs("div",{className:"border-border1 bg-surface1 flex items-start gap-2.5 rounded-md border p-3",children:[o.jsx(kf,{className:"text-neutral4 mt-0.5 h-4 w-4 shrink-0"}),o.jsx("p",{className:"text-neutral3 text-sm",children:C.description})]}):null,q=r?o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:r}):null;return o.jsxs(Fos,{title:A?"Sign in to Mastra Studio":"Create your account",description:z,errorBanner:q,children:[j&&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(Cn,{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(Cn,{id:"email",type:"email",value:x,onChange:M=>S(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(Cn,{id:"password",type:"password",value:k,onChange:M=>_(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(ce,{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:F,className:"text-neutral6 hover:underline",children:A?"Sign up":"Sign in"})]})]}),E&&j&&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"})})]}),E&&N&&o.jsxs(ce,{onClick:H,disabled:h,className:"w-full",size:"lg",variant:"outline",children:[N.icon&&o.jsx("span",{className:"mr-2",children:N.icon}),h?"Redirecting...":N.text||"Sign in"]})]})}function zos(){const[e]=Ri(),t=qs(),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(y7t,{redirectUri:n,onSuccess:i,initialMode:s,errorMessage:a})}function Bos({collapsed:e,children:t}){return o.jsx("section",{className:X("flex flex-col overflow-hidden rounded-xl border border-border1 bg-surface2",e?"h-auto":"h-full"),children:t})}function Uos({onClick:e,tooltip:t="Close panel",className:n}){return o.jsx(ce,{size:"md",onClick:e,"aria-label":"Close Panel",tooltip:t,className:n,children:o.jsx(Wu,{})})}function Vos(){return cI({settings:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"#939393",background:"transparent"},styles:[{tag:[pe.className,pe.propertyName]}]})}function qos(){const e=Nt.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"0.75rem"},"&.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=Ug.define([{tag:[pe.comment,pe.bracket],color:"var(--neutral2)"},{tag:[pe.string,pe.meta,pe.regexp],color:"var(--accent1)"},{tag:[pe.atom,pe.bool,pe.special(pe.variableName)],color:"var(--accent6)"},{tag:[pe.keyword,pe.operator,pe.tagName],color:"var(--accent2)"},{tag:[pe.function(pe.propertyName),pe.propertyName],color:"var(--accent5)"},{tag:[pe.definition(pe.variableName),pe.function(pe.variableName),pe.className,pe.attributeName],color:"var(--accent3)"},{tag:[pe.variableName,pe.number],color:"var(--accent5)"},{tag:[pe.name,pe.quote],color:"var(--accent1)"}]);return[e,U1(t)]}const Hos=()=>{const e=B_().resolvedTheme==="dark";return v.useMemo(()=>e?Vos():qos(),[e])};function Wos({codeStr:e="",title:t,icon:n,simplified:r=!1,className:s}){const a=Hos(),[i,l]=v.useState(!1),c=v.useMemo(()=>{try{const f=JSON.parse(e);return pbe(f||"")}catch{return!1}},[e]),u=i?e?.replace(/\\n/g,`
720
720
  `):e,d=r||i;return!e||e==="null"?null:o.jsxs("div",{className:X("flex flex-col gap-2",s),children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:X("flex items-center gap-1.5 text-ui-xs tracking-widest text-neutral2 uppercase","[&>svg]:size-3.5"),children:[n,t]}),o.jsxs(Mr,{children:[o.jsx(Pa,{content:e||"No content",size:"sm"}),c&&o.jsx(ce,{size:"sm","aria-label":i?"Show escaped newlines":"Show multiline text",onClick:()=>l(f=>!f),children:i?o.jsx(j$,{}):o.jsx(w7,{})})]})]}),o.jsx("div",{className:"border-border1 bg-surface3 text-ui-sm text-neutral4 max-h-[30vh] overflow-hidden overflow-y-auto rounded-lg border p-3 break-all dark:border-white/10 dark:bg-black/20",children:d?o.jsx("div",{className:"text-neutral4 font-mono break-all",children:o.jsx("pre",{className:"text-wrap",children:u})}):o.jsx(Qu,{extensions:[DT(),Nt.lineWrapping],theme:a,value:e,editable:!1})})]})}function pbe(e){if(typeof e=="string"){const t=e.indexOf(`
721
- `);return t!==-1&&t!==e.length-1}else{if(Array.isArray(e))return e.some(t=>pbe(t));if(e&&typeof e=="object")return Object.values(e).some(t=>pbe(t))}return!1}function Zos({children:e}){return o.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e})}function Gos({className:e,children:t}){return o.jsx("div",{className:X("mx-4 flex items-center justify-between gap-2 border-b border-border1 py-3",e),children:t})}function Qos({className:e,children:t}){return o.jsx("h3",{className:X("flex gap-2 text-ui-md text-neutral3 [&>b]:font-normal [&>b]:text-neutral2",e),children:t})}function Yos({className:e,children:t}){return o.jsx("dl",{className:X("grid grid-cols-[auto_1fr] gap-x-4 gap-y-1.5",e),children:t})}function Kos({className:e,children:t}){return o.jsx("dt",{className:X("shrink-0 py-0.5 text-ui-smd text-neutral2",e),children:t})}function Xos({className:e,children:t}){return o.jsx("dd",{className:X("min-w-0 truncate py-0.5 text-ui-smd text-neutral3",e),children:t})}function Jos({className:e,children:t}){return o.jsx("dt",{className:X("col-span-2 py-3 text-ui-sm tracking-widest text-neutral2 uppercase",e),children:t})}const els=Object.assign(Yos,{Key:Kos,Value:Xos,Header:Jos});function tls({children:e}){return o.jsxs("div",{className:"text-ui-sm text-neutral3 flex items-center justify-center gap-2 px-4 py-6",children:[o.jsx(Xt,{size:"sm",variant:"pulse",className:"text-neutral3"})," ",e??"Loading..."]})}function nls({children:e}){return o.jsx("p",{className:"text-ui-sm text-neutral2 px-4 py-6",children:e??"No data found."})}const zi=Object.assign(Bos,{Header:Gos,Heading:Qos,CloseButton:Uos,LoadingData:tls,NoData:nls,Content:Zos,KeyValueList:els,CodeSection:Wos}),ap=zi.KeyValueList;function rls(e){return e instanceof Date?e:new Date(e)}function sls({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:a,collapsed:i,onCollapsedChange:l}){const[c,u]=v.useState(!1),d=i??c,f=l??u,p=rls(e.timestamp),h=e.traceId,m=e.spanId;return o.jsxs(zi,{collapsed:d,children:[o.jsxs(zi.Header,{children:[o.jsxs(zi.Heading,{children:["Log ",o.jsx("b",{children:nr(p,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[l&&o.jsx(ce,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(Qq,{}):o.jsx(hwe,{})}),o.jsxs(Mr,{spacing:"close",children:[o.jsx(ce,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(Gq,{})}),o.jsx(ce,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(u3,{})})]}),o.jsx(zi.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(zi.Content,{children:[o.jsx("p",{className:"text-ui-md text-neutral4 font-mono wrap-break-word whitespace-pre-wrap",children:e.message}),(h||m)&&o.jsxs("div",{className:X("my-8 grid gap-2","[&>button]:justify-between [&>button]:overflow-hidden"),children:[h&&o.jsxs(Mr,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(ce,{size:"md",className:"min-w-0 flex-1 overflow-hidden",onClick:()=>n?.(h),children:[o.jsx(S7,{}),o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",h]})]}),o.jsx(Pa,{content:h,size:"md",tooltip:"Copy Trace ID to clipboard"})]}),m&&o.jsxs(Mr,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(ce,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!h||!r,onClick:()=>h&&r?.(h,m),children:[o.jsx(S7,{}),o.jsx("span",{children:"Span"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",m]})]}),o.jsx(Pa,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(ap,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(ap.Key,{children:"Entity Type"}),o.jsx(ap.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(ap.Key,{children:"Entity Name"}),o.jsx(ap.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(ap.Key,{children:"Service"}),o.jsx(ap.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(ap.Key,{children:"Environment"}),o.jsx(ap.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(ap.Key,{children:"Source"}),o.jsx(ap.Value,{children:e.source})]}),e.metadata&&Object.keys(e.metadata).length>0&&o.jsx(o.Fragment,{children:Object.entries(e.metadata).map(([g,y])=>o.jsxs(v.Fragment,{children:[o.jsx(ap.Key,{children:g}),o.jsx(ap.Value,{children:String(y)})]},g))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(zi.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function als({error:e,resource:t,errorTitle:n}){if(ys(e))return o.jsx(Hs,{});if(xs(e))return o.jsx(Ms,{resource:t});if(w4(e))return o.jsx(Lr,{iconSlot:o.jsx(k7,{}),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(x4(e,"logs"))return o.jsx(Lr,{iconSlot:o.jsx(k7,{}),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(qi,{title:n,message:r??"Unknown error"})}function ils({listSlot:e,logPanelSlot:t,tracePanelSlot:n,spanPanelSlot:r,logCollapsed:s}){const a=!!t;return o.jsxs("div",{className:X("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:X("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 ols={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 lls({level:e}){const t=ols[e];return o.jsx(To,{height:"compact",children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function cls({entityType:e,className:t}){const n=X("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(Xu,{className:n,"aria-hidden":!0});case"tool":return o.jsx(Ld,{className:n,"aria-hidden":!0});default:return null}}function uls({entityType:e,entityName:t}){const n=e??"";return o.jsxs(To,{height:"compact",className:"flex min-w-0 items-center gap-2",children:[o.jsx(cls,{entityType:n}),t?o.jsx("span",{className:"text-ui-smd min-w-0 truncate",children:t}):"-"]})}function dls({message:e}){return o.jsx(To,{height:"compact",className:"text-ui-smd text-neutral4 min-w-0 truncate font-mono",children:e})}function fls({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(To,{height:"compact",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(oEe,{children:t})}const Gl=Object.assign(N4,{Top:yZ,TopCell:aC,TopCellWithTooltip:bZ,TopCellSmart:$$t,RowWrapper:fEe,RowButton:I4,RowLink:M$t,Spacer:dEe,NoMatch:vZ,DateCell:lEe,TimeCell:cEe,LevelCell:lls,EntityCell:uls,MessageCell:dls,DataCell:fls,NextPageLoading:gZ}),wXe="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",pls=36,hls=8;function mls({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=v.useRef(null),u=X9t({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>pls,overscan:hls}),d=v.useRef(t);if(v.useEffect(()=>{d.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),d.current=t},[t]),t)return o.jsx(ol,{columns:wXe});const f=u.getVirtualItems(),p=u.getTotalSize(),h=f[0]?.start??0,m=f.length>0?Math.max(0,p-(f[f.length-1]?.end??0)):0;return o.jsxs(Gl,{columns:wXe,variant:"striped",scrollRef:c,className:"min-w-0",children:[o.jsxs(Gl.Top,{children:[o.jsx(Gl.TopCell,{children:"Date"}),o.jsx(Gl.TopCell,{children:"Time"}),o.jsx(Gl.TopCell,{children:"Level"}),o.jsx(Gl.TopCell,{children:"Entity"}),o.jsx(Gl.TopCell,{children:"Message"}),o.jsx(Gl.TopCell,{children:"Data"})]}),e.length===0?o.jsx(Gl.NoMatch,{message:"No logs match your search"}):o.jsxs(o.Fragment,{children:[o.jsx(Gl.Spacer,{height:h}),f.map(g=>{const y=e[g.index];if(!y)return null;const b=a.get(y);if(!b)return null;const x=b===i;return o.jsxs(Gl.RowButton,{ref:u.measureElement,"data-index":g.index,onClick:()=>l(y),featured:x,variant:y.level==="error"||y.level==="fatal"?"error":"default",children:[o.jsx(Gl.DateCell,{timestamp:y.timestamp}),o.jsx(Gl.TimeCell,{timestamp:y.timestamp}),o.jsx(Gl.LevelCell,{level:y.level}),o.jsx(Gl.EntityCell,{entityType:y.entityType,entityName:y.entityName}),o.jsx(Gl.MessageCell,{message:y.message}),o.jsx(Gl.DataCell,{data:y.data})]},b)}),o.jsx(Gl.Spacer,{height:m})]}),o.jsx(Gl.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function gls({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=>vls(f,a));return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(QNe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(ZNe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function vls(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 yls={"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"},Oae="MMM d, yyyy HH:mm",_ae="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function bls({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${yls[e]}`,description:_ae}:t&&n?{title:`No logs between ${nr(t,Oae)} and ${nr(n,Oae)}`,description:_ae}:t?{title:`No logs since ${nr(t,Oae)}`,description:_ae}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const xls=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=bls({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(k7,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(ce,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",children:["Logging Documentation ",o.jsx(mwe,{})]})})})},wls=20,Sls=1e4;function kls(e,t,n){if(e?.pagination?.hasMore)return n+1}function Ols(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 _ls(e){return x4(e.state.error,"logs")||w4(e.state.error)?!1:Sls}const Cls=({filters:e}={})=>{const t=We(),{inView:n,setRef:r}=W_(),s=M1({queryKey:["logs",e],queryFn:({pageParam:p})=>t.listLogsVNext({pagination:{page:p,perPage:wls},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:kls,select:Ols,retry:!1,refetchInterval:_ls}),{hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,data:c,isLoading:u,isError:d,error:f}=s;return v.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}},Dz={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},b7t=[{label:"Agent",entityType:Dz.AGENT},{label:"Workflow",entityType:Dz.WORKFLOW},{label:"Scorer",entityType:Dz.SCORER},{label:"Ingest",entityType:Dz.INGEST}],Els=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],Fx="rootEntityType",Gb="datePreset",Qb="dateFrom",Yb="dateTo",jls=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),Nl={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"},EL=Object.keys(Nl),vIe=new Set(["tags"]),yIe="mastra:logs:saved-filters";function Tls(e,t=yIe){const n=Pls(e),r=e.get(Gb);r&&n.set(Gb,r);const s=e.get(Qb);s&&n.set(Qb,s);const a=e.get(Yb);a&&n.set(Yb,a);try{localStorage.setItem(t,n.toString())}catch{}}function Nls(e=yIe){try{localStorage.removeItem(e)}catch{}}function SXe(e=yIe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function Ils(e){if(e.has(Gb)||e.has(Qb)||e.has(Yb)||e.has(Fx))return!0;for(const t of EL)if(e.has(Nl[t]))return!0;return!1}function Als({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:b7t.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:Els.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 Rls(e){const t=[],n=new Map([[Fx,"rootEntityType"]]);for(const s of EL)n.set(Nl[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),vIe.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 Pls(e){const t=new URLSearchParams,n=e.get(Fx);n&&t.set(Fx,n);for(const r of EL){const s=Nl[r];if(vIe.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 $ls(e,t){e.delete(Fx);for(const n of EL)e.delete(Nl[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(Fx,n.value);continue}const r=Nl[n.fieldId];if(r){if(vIe.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 Mls({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 Dls(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 Lls="Filters setting for Logs saved",Fls="Filters setting for Logs cleared up";function zls(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=v.useState(()=>SXe(r)!==null),c=v.useCallback(()=>{Tls(e,r),l(!0);const f=s?.saved??Lls;f!==!1&&Le.success(f)},[e,r,s?.saved]),u=v.useCallback(()=>{Nls(r),l(!1);const f=s?.cleared??Fls;f!==!1&&Le.success(f)},[r,s?.cleared]),d=v.useRef(!1);return v.useEffect(()=>{if(a||d.current||(d.current=!0,Ils(e)))return;const f=SXe(r);f&&t(p=>{const h=new URLSearchParams(p);for(const[m,g]of f)h.append(m,g);return h},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function Bls(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 Uls(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,Bls(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function Vls(e,t,n,r){const s=v.useMemo(()=>Uls(e),[e]),a=v.useMemo(()=>{const h=new Map;for(const[m,g]of e.entries()){const y=s.get(g);y&&h.set(y,{log:g,idx:m})}return h},[e,s]),l=(t?a.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=v.useCallback(h=>s.get(h),[s]),d=v.useCallback(h=>{const m=s.get(h);if(m){if(t===m){n({logId:null});return}n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}},[s,t,r,n]),f=l>0?()=>{const h=e[l-1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0,p=l>=0&&l<e.length-1?()=>{const h=e[l+1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0;return{logIdMap:s,getLogId:u,featuredLog:c,handleLogClick:d,handlePreviousLog:f,handleNextLog:p}}const hbe="logId",mbe="traceId",gbe="spanId",oP=1440*60*1e3,qls={"last-24h":oP,"last-3d":3*oP,"last-7d":7*oP,"last-14d":14*oP,"last-30d":30*oP};function Lz(e){e.delete(hbe),e.delete(mbe),e.delete(gbe)}function Hls(e,t,n){const{onRemoveAll:r}={},s=v.useMemo(()=>{const _=e.get(Gb);return _&&jls.has(_)?_:"last-24h"},[e]),a=e.get(Qb),i=e.get(Yb),l=v.useMemo(()=>{if(s==="custom"){if(!a)return;const C=new Date(a);return Number.isNaN(C.getTime())?void 0:C}if(s==="all")return;const _=qls[s];return _?new Date(Date.now()-_):void 0},[s,a]),c=v.useMemo(()=>{if(s!=="custom"||!i)return;const _=new Date(i);return Number.isNaN(_.getTime())?void 0:_},[s,i]),u=v.useRef(s);u.current=s;const d=e.get(hbe),f=e.get(mbe),p=e.get(gbe),h=v.useMemo(()=>b7t.find(_=>_.entityType===e.get(Fx)),[e]),m=v.useMemo(()=>Rls(e),[e]),g=v.useCallback(_=>{t(C=>{const E=new URLSearchParams(C);for(const[j,N]of Object.entries(_)){const I=j==="logId"?hbe:j==="traceId"?mbe:gbe;N?E.set(I,N):E.delete(I)}return E},{replace:!0})},[t]),y=v.useCallback(_=>{t(C=>{const E=new URLSearchParams(C);return $ls(E,_),Lz(E),E},{replace:!0})},[t]),b=y,x=v.useCallback((_,C)=>{if(u.current!=="custom")return;const E=C==="from"?Qb:Yb;t(j=>{const N=new URLSearchParams(j);return _?N.set(E,_.toISOString()):N.delete(E),Lz(N),N},{replace:!0})},[t]),S=v.useCallback(_=>{u.current=_,t(C=>{const E=new URLSearchParams(C);return _==="last-24h"?(E.delete(Gb),E.delete(Qb),E.delete(Yb)):_==="custom"?E.set(Gb,"custom"):(E.set(Gb,_),E.delete(Qb),E.delete(Yb)),Lz(E),E},{replace:!0})},[t]),k=v.useCallback(()=>{t(_=>{const C=new URLSearchParams(_);C.delete(Fx);for(const E of EL)C.delete(Nl[E]);return C.delete(Gb),C.delete(Qb),C.delete(Yb),Lz(C),C},{replace:!0}),r?.()},[t,r]);return v.useMemo(()=>({searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,featuredLogId:d,featuredTraceId:f,featuredSpanId:p,selectedEntityOption:h,filterTokens:m,handleFeaturedChange:g,handleFilterTokensChange:b,handleDateChange:x,handleDatePresetChange:S,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,p,h,m,g,b,x,S,k,y])}const kb=zi.KeyValueList;function Wls({spanId:e,span:t,isLoading:n,onClose:r}){const s=t?.startedAt&&t?.endedAt?new Date(t.endedAt).getTime()-new Date(t.startedAt).getTime():null;return o.jsxs(zi,{children:[o.jsxs(zi.Header,{children:[o.jsxs(zi.Heading,{children:["Span ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(zi.CloseButton,{onClick:r})]}),n?o.jsx(zi.LoadingData,{children:"Loading span..."}):t?o.jsxs(zi.Content,{children:[o.jsxs(kb,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(kb.Key,{children:"Type"}),o.jsx(kb.Value,{children:t.spanType})]}),t.startedAt&&o.jsxs(o.Fragment,{children:[o.jsx(kb.Key,{children:"Started"}),o.jsx(kb.Value,{children:nr(new Date(t.startedAt),"MMM dd, HH:mm:ss.SSS")})]}),t.endedAt&&o.jsxs(o.Fragment,{children:[o.jsx(kb.Key,{children:"Ended"}),o.jsx(kb.Value,{children:nr(new Date(t.endedAt),"MMM dd, HH:mm:ss.SSS")})]}),s!=null&&o.jsxs(o.Fragment,{children:[o.jsx(kb.Key,{children:"Duration"}),o.jsx(kb.Value,{children:s<1e3?`${s}ms`:`${(s/1e3).toFixed(2)}s`})]})]}),o.jsx("br",{}),o.jsx(zi.CodeSection,{title:"Input",icon:o.jsx(che,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(zi.CodeSection,{title:"Output",icon:o.jsx(uhe,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(zi.CodeSection,{title:"Metadata",icon:o.jsx(vw,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(zi.CodeSection,{title:"Attributes",icon:o.jsx(vw,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(zi.NoData,{children:"Span not found."})]})}function Zls({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:a}){const i=v.useMemo(()=>JNe(t??[]),[t]),[l,c]=v.useState([]);v.useEffect(()=>{i.length>0&&c(XNe(i))},[i]);const u=d=>{s?.(a===d?void 0:d)};return o.jsxs(zi,{children:[o.jsxs(zi.Header,{children:[o.jsxs(zi.Heading,{children:["Trace ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(zi.CloseButton,{onClick:r})]}),n?o.jsx(zi.LoadingData,{children:"Loading trace..."}):i.length===0?o.jsx(zi.NoData,{children:"No spans found for this trace."}):o.jsx(zi.Content,{children:o.jsx(Q9t,{hierarchicalSpans:i,onSpanClick:u,selectedSpanId:a??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}function Gls(){const[e,t]=Ri(),n=Hls(e,t),r=zls(e,t),[s,a]=v.useState(),[i,l]=v.useState(!1),{data:c=[],isPending:u}=iIe(),{data:d=[],isPending:f}=rIe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:p=[],isPending:h}=sIe(),{data:m=[],isPending:g}=aIe(),y=v.useMemo(()=>Als({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:p,loading:{tags:u,entityNames:f,serviceNames:g,environments:h}}),[c,d,m,p,u,f,g,h]),b=v.useMemo(()=>Mls({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:x=[],isLoading:S,error:k,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:E}=Cls({filters:b}),{logIdMap:j,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:R}=Vls(x,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:L,isLoading:D}=oIe(n.featuredTraceId??null),{data:B,isLoading:H}=CL(n.featuredTraceId??"",n.featuredSpanId??""),F=v.useCallback(()=>n.applyFilterTokens(Dls(y,n.filterTokens)),[y,n]),z=v.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),q=v.useCallback(K=>n.handleFeaturedChange({traceId:K,spanId:null}),[n]),M=v.useCallback((K,te)=>n.handleFeaturedChange({traceId:K,spanId:te}),[n]),G=v.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),V=v.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),$=v.useCallback(K=>n.handleFeaturedChange({spanId:K??null}),[n]),U=o.jsxs(Ft.TopArea,{children:[o.jsx(Ft.Row,{children:o.jsxs(Ft.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(G3,{preset:n.datePreset,onPresetChange:n.handleDatePresetChange,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,onDateChange:n.handleDateChange,disabled:S,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),o.jsx(YNe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:S,onStartTextFilter:a})]})}),o.jsx(gls,{isLoading:S,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:F,onRemoveAll:n.handleRemoveAll,onSave:r.handleSave,onRemoveSaved:r.hasSavedFilters?r.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(k)return o.jsxs(Ft,{width:"wide",height:"full",children:[U,o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsx(als,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const Z=!!n.selectedEntityOption||n.filterTokens.length>0;return x.length===0&&!S&&!Z?o.jsxs(Ft,{width:"wide",height:"full",children:[U,o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsx(xls,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Ft,{width:"wide",height:"full",children:[U,o.jsx(ils,{logCollapsed:i,listSlot:o.jsx(mls,{logs:x,isLoading:S,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:E,logIdMap:j,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(sls,{log:N,onClose:z,onTraceClick:q,onSpanClick:M,onPrevious:A,onNext:R,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(Zls,{traceId:n.featuredTraceId,spans:L?.spans,isLoading:D,onClose:G,onSpanSelect:$,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(Wls,{spanId:n.featuredSpanId,span:B?.span,isLoading:H,onClose:V}):null})]})}function Qls({server:e}){const{paths:t,Link:n}=yn(),s=We().options.baseUrl,a=s?`${s}/api/mcp/${e.id}/sse`:"",{data:i}=Ezt(e),l=Object.values(i||{}),c=l.length,u=l.filter(p=>p.toolType==="agent").length,d=l.filter(p=>p.toolType==="workflow").length,f=ky(e.name,50);return o.jsxs(ve.RowLink,{to:t.mcpServerLink(e.id),LinkComponent:n,children:[o.jsx(ve.NameCell,{children:f}),o.jsx(ve.DescriptionCell,{children:a}),o.jsx(ve.TextCell,{className:"text-center",children:u||""}),o.jsx(ve.TextCell,{className:"text-center",children:c||""}),o.jsx(ve.TextCell,{className:"text-center",children:d||""})]})}function Yls({mcpServers:e,isLoading:t,search:n=""}){const r=v.useMemo(()=>{const s=n.toLowerCase();return e.filter(a=>a.name?.toLowerCase().includes(s)||a.id?.toLowerCase().includes(s))},[e,n]);return t?o.jsx(ol,{columns:"auto 1fr auto auto auto"}):o.jsxs(ve,{columns:"auto 1fr auto auto auto",variant:"striped",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Name"}),o.jsx(ve.TopCell,{children:"URL"}),o.jsx(ve.TopCellSmart,{long:"Agents",short:o.jsx(Uo,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(ve.TopCellSmart,{long:"Tools",short:o.jsx(Ld,{}),tooltip:"Tools",className:"text-center"}),o.jsx(ve.TopCellSmart,{long:"Workflows",short:o.jsx(Xu,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(ve.NoMatch,{message:"No MCP Servers match your search"}):null,r.map(s=>o.jsx(Qls,{server:s},s.id))]})}const Kls=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(Nf,{}),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(ce,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(Sa,{})]})})}),Xls=()=>{const{data:e=[],isLoading:t,error:n}=IG(),[r,s]=v.useState("");return n&&ys(n)?o.jsx(lr,{children:o.jsx(Hs,{})}):n&&xs(n)?o.jsx(lr,{children:o.jsx(Ms,{resource:"MCP servers"})}):n?o.jsx(lr,{children:o.jsx(qi,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(lr,{children:o.jsx(Kls,{})}):o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx($f,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(Yls,{mcpServers:e,isLoading:t,search:r})]})},Jls=(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 ecs({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=yn(),i=v.useMemo(()=>Jls(e,t),[e,t]),l=v.useMemo(()=>i.filter(c=>c.id.toLowerCase().includes(r.toLowerCase())),[i,r]);return n?o.jsx(ol,{columns:"auto 1fr auto"}):o.jsxs(ve,{columns:"auto 1fr auto",variant:"striped",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Name"}),o.jsx(ve.TopCell,{children:"Description"}),o.jsx(ve.TopCellSmart,{long:"Agents",short:o.jsx(Uo,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(ve.NoMatch,{message:"No Tools match your search"}):null,l.map(c=>{const u=ky(c.id,50),d=ky(c.description??"",200),f=c.agents.length;return o.jsxs(ve.RowLink,{to:s.toolLink(c.id),LinkComponent:a,children:[o.jsx(ve.NameCell,{children:u}),o.jsx(ve.DescriptionCell,{children:d}),o.jsx(ve.TextCell,{className:"text-center",children:f||""})]},c.id)})]})}const tcs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(Nf,{}),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(ce,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(Sa,{})]})})}),ncs=()=>{const e=We();return Mn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new E_;Object.entries(r??{}).forEach(([a,i])=>{s.set(a,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(a){throw Le.error("Error executing dev tool"),console.error("Error executing dev tool:",a),a}}})},rcs=({toolId:e})=>{const{canExecute:t}=ul(),n=t("tools"),{data:r={}}=Em(),s=v.useMemo(()=>{for(const g of Object.values(r))if(g.tools){const y=Object.values(g.tools).find(b=>b.id===e);if(y)return y}return null},[r,e]),{data:a,isLoading:i,error:l}=VEr(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=ncs(),{requestContext:p}=_s();v.useEffect(()=>{if(l){const g=l instanceof Error?l.message:"Failed to load tool";Le.error(`Error loading tool: ${g}`)}},[l]);const h=async(g,y)=>{if(!c)return;const b={...p??{},...y??{}};return u({toolId:c.id,input:g,requestContext:b})},m=c?.inputSchema?fm(um(wx(c?.inputSchema))):ks({});return i?o.jsxs("div",{className:"p-6",children:[o.jsx(xt,{className:"mb-4 h-8 w-48"}),o.jsx(xt,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(ONe,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:h,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{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(ye,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function scs({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}){const{data:c={},isLoading:u,isError:d,error:f}=RI(),{data:p={},isLoading:h,isError:m,error:g}=Em(),{navigate:y,paths:b}=yn();v.useEffect(()=>{if(d){const _=f instanceof Error?f.message:"Failed to load tools";Le.error(`Error loading tools: ${_}`)}},[d,f]),v.useEffect(()=>{if(m){const _=g instanceof Error?g.message:"Failed to load agents";Le.error(`Error loading agents: ${_}`)}},[m,g]);const x=new Map;Object.values(p).forEach(_=>{_.tools&&Object.values(_.tools).forEach(C=>{x.has(C.id)||x.set(C.id,C)})}),Object.values(c).forEach(_=>{x.has(_.id)||x.set(_.id,_)});const S=Array.from(x.values()).map(_=>({label:_.id,value:_.id})),k=_=>{t?t(_):_&&_!==e&&y(b.toolLink(_))};return o.jsx(ac,{options:S,value:e,onValueChange:k,placeholder:u||h?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||u||h||d||m,variant:l})}const acs=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=v.useState({sseUrl:"",httpStreamUrl:""});if(v.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(Oy,{children:o.jsx(ye,{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(Oy,{isDivided:!0,children:[o.jsxs("div",{className:"mx-auto w-full max-w-2xl px-8 py-12",children:[o.jsx(ye,{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(un,{icon:o.jsx(W9t,{className:"text-neutral6"}),className:"text-neutral4! rounded-r-sm",children:"Version"}),o.jsx(un,{className:"text-neutral4! rounded-l-sm",children:t.version_detail.version})]}),o.jsx(ye,{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(un,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"HTTP"}),children:"Regular HTTP Endpoint"}),o.jsx(ye,{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(ye,{className:"bg-surface4 rounded-lg px-2 py-1",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx(Pa,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(un,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"SSE"}),children:"Server-Sent Events"}),o.jsx(ye,{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(ye,{className:"bg-surface4 rounded-lg px-2 py-1",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx(Pa,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(un,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"CLI"}),children:"Command Line"}),o.jsx(ye,{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(ye,{className:"bg-surface4 rounded-lg px-2 py-1",children:a}),o.jsx("div",{className:"pt-1",children:o.jsx(Pa,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"border-border1 h-full overflow-y-scroll border-l",children:o.jsx(ics,{server:t})})]})},ics=({server:e})=>{const{data:t={},isLoading:n}=Ezt(e);if(n)return null;const r=Object.keys(t);return o.jsxs("div",{className:"overflow-y-scroll p-5",children:[o.jsxs("div",{className:"text-neutral6 flex items-center gap-2",children:[o.jsx(qe,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(hC,{})}),o.jsx(ye,{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(lcs,{tool:a,serverId:e.id},s)})})]})};function ocs(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 lcs=({tool:e,serverId:t})=>{const n=v.useRef(null),{Link:r,paths:s}=yn(),a=Jzt[e.toolType||"tool"],i=ocs(e._meta);return o.jsxs(Df,{onClick:()=>n.current?.click(),children:[o.jsx(Z2t,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Ff,{children:[o.jsx(Lf,{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(un,{className:"py-0 text-[10px]",children:"App"})]})}),o.jsx(th,{children:e.description})]})]})},ccs=()=>{const{serverId:e}=Sr(),{data:t=[],isLoading:n}=IG(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(acs,{isLoading:n,server:r})})};function ucs(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 dcs=({toolId:e,serverId:t})=>{const{canExecute:n}=ul(),r=n("tools"),s=We(),{data:a,isLoading:i,error:l}=vNe(t,e),{mutateAsync:c,isPending:u,data:d}=MGr(t,e),f=a?ucs(a._meta):void 0,{data:p}=yt({queryKey:["mcp-app-resource",t,f],queryFn:async()=>f?(await s.readMcpServerResource(t,f)).contents[0]?.text??null:null,enabled:!!f}),h=v.useCallback(async(y,b)=>await c(b),[c]);v.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";Le.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(xt,{className:"mb-4 h-8 w-48"}),o.jsx(xt,{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(ye,{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(ye,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let g;try{g=fm(um(a.inputSchema))}catch(y){console.error("Error processing input schema:",y),Le.error("Failed to process tool input schema."),g=ks({})}return o.jsxs("div",{className:"flex flex-col gap-4",children:[p&&o.jsx("div",{className:"border-border1 border-b p-4",children:o.jsx(Czt,{html:p,toolName:a.name??a.id,onToolCall:h})}),o.jsx(ONe,{executionResult:d,isExecutingTool:u,zodInputSchema:g,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},fcs=()=>{const{serverId:e,toolId:t}=Sr(),{data:n,isLoading:r}=vNe(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(dcs,{toolId:t,serverId:e})})},x7t=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],RN="rootEntityType",PN={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"},nQ=Object.keys(PN),bIe="mastra:metrics:saved-filters";function pcs(e){const t=ycs(e);try{localStorage.setItem(bIe,t.toString())}catch{}}function hcs(){try{localStorage.removeItem(bIe)}catch{}}function w7t(){try{const e=localStorage.getItem(bIe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function mcs(e){if(e.has(RN))return!0;for(const t of nQ)if(e.has(PN[t]))return!0;return!1}function gcs({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:x7t.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 vcs(e){const t=[],n=new Map([[RN,"rootEntityType"]]);for(const s of nQ)n.set(PN[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 ycs(e){const t=new URLSearchParams,n=e.getAll(RN);for(const r of n)t.append(RN,r);for(const r of nQ){const s=PN[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function bcs(e,t){e.delete(RN);for(const n of nQ)e.delete(PN[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?RN:PN[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 xcs="Any";function kXe(e){const t=e.trim();return t===""||t===xcs}const wcs=new Set(x7t.map(e=>e.entityType));function OXe(e){const t=e.trim();return wcs.has(t)?t:void 0}function Scs(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=>!kXe(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?OXe(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(kXe(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=OXe(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const S7t=[{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"}],kcs=new Set(S7t.map(e=>e.value));function Ocs(e){return typeof e=="string"&&(kcs.has(e)||e==="custom")}const k7t=v.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function rQ(){return v.useContext(k7t)}function _cs(e,t){return e!=="custom"?S7t.find(n=>n.value===e)?.label??e:t?.from?t.to?`${nr(t.from,"MMM d, yyyy")} – ${nr(t.to,"MMM d, yyyy")}`:nr(t.from,"MMM d, yyyy"):"Custom range"}function Ccs({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:a,onCustomRangeChange:i,tracesBasePath:l,logsBasePath:c}){const u=v.useMemo(()=>JSON.stringify(n),[n]),d=v.useMemo(()=>n,[u]),f=v.useMemo(()=>Scs(d),[d]),p=v.useMemo(()=>JSON.stringify(f),[f]),h=_cs(t,a),m=v.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:a,setCustomRange:i??(()=>{}),dateRangeLabel:h,filterTokens:d,setFilterTokens:s,dimensionalFilter:f,dimensionalFilterKey:p,tracesBasePath:l,logsBasePath:c}),[t,r,a,i,h,d,s,f,p,l,c]);return o.jsx(k7t.Provider,{value:m,children:e})}const Ecs=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function jcs(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 Tcs(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 Ncs(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=rQ(),s=v.useRef(e);s.current=e;const a=v.useRef(n);return a.current=n,o.jsx(G3,{preset:jcs(e),onPresetChange:i=>{const l=Tcs(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:Ecs})}const vbe=1440*60*1e3,Ics={"24h":vbe,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function Acs(e,t,n){if(e!=="custom"){const r=Ics[e]??vbe;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-vbe),end:t?.to??new Date(n)}}function Im(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=rQ(),s=v.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=v.useMemo(()=>Acs(e,t,i),[e,t,i]),c=v.useMemo(()=>({timestamp:l,...n}),[l,r]),u=v.useMemo(()=>`${a}|${r}`,[a,r]);return{datePreset:e,customRange:t,timestamp:l,filters:c,dimensionalFilter:n,filterKey:u}}function O7t(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}const Rcs=new Set(["ObservabilityStorageClickhouseVNext","ObservabilityStorageDuckDB","ObservabilityInMemory","ObservabilitySpanner","ObservabilityStoragePostgresVNext"]),Pcs=()=>{const{data:e,isLoading:t}=R4(),n=e?.observabilityStorageType;return{supportsMetrics:e?.observabilityStorageCapabilities?.metrics??(n?Rcs.has(n):!1),isInMemory:n==="ObservabilityInMemory",isLoading:t}};function jL({href:e,LinkComponent:t="a"}){return o.jsx(ce,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(xEn,{})})}function $cs({href:e,LinkComponent:t="a"}){return o.jsx(ce,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(njn,{})})}const Mcs=[{dataKey:"p50",label:"p50",color:Fp.blue,aggregate:e=>({value:e.length>0?`${Math.round(e.reduce((t,n)=>t+n.p50,0)/e.length)}`:"0",suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:Fp.yellow,aggregate:e=>({value:e.length>0?`${Math.round(e.reduce((t,n)=>t+n.p95,0)/e.length)}`:"0",suffix:"avg ms"})}];function Dcs(e){return e==="agents"||e==="workflows"||e==="tools"}function Cae({data:e,onPointClick:t}){return e.length===0?o.jsx(Ht.NoData,{message:"No latency data yet"}):o.jsx(IV,{data:e,series:Mcs,onPointClick:t?n=>{const r=n;typeof r?.tsMs=="number"&&Number.isFinite(r.tsMs)&&t(r)}:void 0})}function Lcs({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]=v.useState("agents"),p=c[d]?d:u,h=typeof s=="function"?s(p):s,m=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),g=e?Object.values(e).filter(Array.isArray).flat().map(b=>b.p50).filter(b=>typeof b=="number"):[],y=g.length>0?`${Math.round(g.reduce((b,x)=>b+x,0)/g.length)}ms`:"—";return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(Ht.Summary,{value:y,label:"Avg p50"}),h?o.jsx(Ht.Actions,{children:h}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load latency data"}):o.jsx(Ht.Content,{children:m?o.jsxs(Dc,{value:p,onValueChange:b=>{Dcs(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(Mc,{children:[o.jsx(Rr,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(Rr,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(Rr,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(Xr,{value:"agents",children:o.jsx(Cae,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(Xr,{value:"workflows",children:o.jsx(Cae,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(Xr,{value:"tools",children:o.jsx(Cae,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Ht.NoData,{message:"No latency data yet"})})]})}function Fcs(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 zcs(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 _7t(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=Fcs(s);l&&e.set(t,l)}function Po(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function C7t(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function _Xe({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/observability"}){const a=new URLSearchParams;a.set(kw,"branches"),_7t(a,Ow,_w,Cw,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Dx,i),r.status&&a.set(Lx,r.status),Po(a,Tl.entityName,r.entityName??n.entityName),Po(a,Tl.threadId,r.threadId??n.threadId),Po(a,Tl.resourceId,r.resourceId??n.resourceId),Po(a,Tl.entityId,n.entityId),Po(a,Tl.runId,n.runId),Po(a,Tl.sessionId,n.sessionId),Po(a,Tl.requestId,n.requestId),Po(a,Tl.userId,n.userId),Po(a,Tl.organizationId,n.organizationId),Po(a,Tl.experimentId,n.experimentId),Po(a,Tl.serviceName,n.serviceName),Po(a,Tl.environment,n.environment),C7t(a,Tl.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function Bcs({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;_7t(a,Gb,Qb,Yb,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Fx,i),Po(a,Nl.entityName,r.entityName??n.entityName),Po(a,Nl.threadId,r.threadId??n.threadId),Po(a,Nl.resourceId,r.resourceId??n.resourceId),Po(a,Nl.runId,n.runId),Po(a,Nl.sessionId,n.sessionId),Po(a,Nl.requestId,n.requestId),Po(a,Nl.userId,n.userId),Po(a,Nl.organizationId,n.organizationId),Po(a,Nl.experimentId,n.experimentId),Po(a,Nl.serviceName,n.serviceName),Po(a,Nl.environment,n.environment),C7t(a,Nl.tags,n.tags),r.status==="error"&&a.append(Nl.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function KI(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=rQ(),a=v.useCallback((c={})=>_Xe({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=v.useCallback((c={})=>Bcs({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=v.useCallback((c,u,d)=>{const f=zcs(u,d);return _Xe({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const E7t="1h";async function Eae(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:E7t,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 Ucs(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([Eae(e,"mastra_agent_duration_ms",t),Eae(e,"mastra_workflow_duration_ms",t),Eae(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:E7t}}})}const CXe={agents:au.AGENT,workflows:au.WORKFLOW_RUN,tools:au.TOOL};function Vcs(){const{data:e,isLoading:t,isError:n}=Ucs(),{getTracesHref:r,getBucketTracesHref:s}=KI(),{Link:a}=yn(),i=qs();return o.jsx(Lcs,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:CXe[l]},c.tsMs,"1h"))},actions:l=>o.jsx(jL,{href:r({rootEntityType:CXe[l]}),LinkComponent:a})})}function qcs(e){return e==="threads"||e==="resources"}function jae(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function Hcs({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:a}){const[i,l]=v.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,p=e.data?.reduce((y,b)=>y+b.runs,0)??0,h=t.data?.reduce((y,b)=>y+b.threadCount,0)??0,m=i==="threads"?e:t,g=typeof s=="function"?s(i):s;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&o.jsx(Ht.Summary,{value:p.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&o.jsx(Ht.Summary,{value:h.toLocaleString(),label:"Total threads"}),g?o.jsx(Ht.Actions,{children:g}):null]}),m.isLoading?o.jsx(Ht.Loading,{}):m.isError?o.jsx(Ht.Error,{message:"Failed to load memory data"}):o.jsx(Ht.Content,{children:o.jsxs(Dc,{defaultTab:"threads",value:i,onValueChange:y=>{qcs(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Mc,{children:[o.jsx(Rr,{value:"threads",children:"Threads"}),o.jsx(Rr,{value:"resources",children:"Resources"})]}),o.jsx(Xr,{value:"threads",children:d?o.jsxs(ve,{columns:"auto auto auto auto auto",...dbe,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(ve.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:jae(y.threadId)}),o.jsx(ve.NumberCell,{children:y.resourceId?jae(y.resourceId):"—"}),o.jsx(ve.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(ve.NumberCell,{children:y.tokens>0?Oc(y.tokens):"—"}),o.jsx(ve.NumberCell,{children:y.cost!=null?Cg(y.cost,y.costUnit):"—"})]});return b?o.jsx(ve.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(ve.RowStatic,{children:x},y.key)})]}):o.jsx(Ht.NoData,{message:"No thread activity yet"})}),o.jsx(Xr,{value:"resources",children:f?o.jsxs(ve,{columns:"auto auto auto auto",...dbe,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(ve.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:jae(y.resourceId)}),o.jsx(ve.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(ve.NumberCell,{children:y.tokens>0?Oc(y.tokens):"—"}),o.jsx(ve.NumberCell,{children:y.cost!=null?Cg(y.cost,y.costUnit):"—"})]});return b?o.jsx(ve.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(ve.RowStatic,{children:x},y.key)})]}):o.jsx(Ht.NoData,{message:"No resource activity yet"})})]})})]})}function TL(e,t,n){const r=e.get(t);if(r!==void 0)return r;const s=n();return e.set(t,s),s}const Tae=20;function Wcs(){const e=We(),{filters:t,filterKey:n}=Im();return yt({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:Tae}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:Tae}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:Tae})]),l=new Map,c=d=>TL(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.threadId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.threadId).map(d=>{const f=d.dimensions.threadId,p=l.get(f);return{threadId:f,resourceId:d.dimensions.resourceId??null,runs:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}const Nae=20;function Zcs(){const e=We(),{filters:t,filterKey:n}=Im();return yt({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:Nae}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:Nae}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:Nae})]),l=new Map,c=d=>TL(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.resourceId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.resourceId).map(d=>{const f=d.dimensions.resourceId,p=l.get(f);return{resourceId:f,threadCount:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}function Gcs(){const e=Wcs(),t=Zcs(),{getTracesHref:n}=KI(),{Link:r}=yn();return o.jsx(Hcs,{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 NL({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:a}){const i=t!=null;return o.jsxs(es,{children:[o.jsx(es.Label,{children:e}),o.jsx(es.Value,{className:i?void 0:"invisible",children:i?t:"—"}),a?o.jsx(es.Error,{}):s?o.jsx(es.Loading,{}):i?r!=null?o.jsx(es.Change,{changePct:r,prevValue:n}):o.jsx(es.NoChange,{}):o.jsx(es.NoData,{})]})}function Qcs(){const e=We(),{filters:t,filterKey:n}=Im();return yt({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 Ycs(){const e=We(),{filters:t,filterKey:n}=Im();return yt({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 Kcs(){const e=We(),{filters:t,filterKey:n}=Im();return yt({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 Xcs(){const e=We(),{filters:t,filterKey:n}=Im();return yt({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 Jcs(){const{data:e,isLoading:t,isError:n}=O7t();return o.jsx(NL,{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 eus(){const{data:e,isLoading:t,isError:n}=Kcs();return o.jsx(NL,{label:"Total Model Cost",value:e?.cost!=null?Cg(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?Cg(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function tus(){const{data:e,isLoading:t,isError:n}=Xcs();return o.jsx(NL,{label:"Total Tokens",value:e?.value!=null?Oc(e.value):null,prevValue:e?.previousValue!=null?Oc(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function nus(){const{data:e,isLoading:t,isError:n}=Ycs();return o.jsx(NL,{label:"Total Threads",value:e?.value!=null?Oc(e.value):null,prevValue:e?.previousValue!=null?Oc(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function rus(){const{data:e,isLoading:t,isError:n}=Qcs();return o.jsx(NL,{label:"Total Resources",value:e?.value!=null?Oc(e.value):null,prevValue:e?.previousValue!=null?Oc(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function sus({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=>aus(f,a));return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(QNe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(ZNe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function aus(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 ius({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const i=!!e&&e.length>0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Model Usage & Cost",description:"Token consumption by model."}),i&&(()=>{const l=e.reduce((d,f)=>d+(f.cost??0),0),c=new Set;for(const d of e)d.cost!=null&&d.costUnit&&c.add(d.costUnit);let u;return c.size===0?u=l>0?Cg(l):"—":c.size===1?u=l>0?Cg(l,[...c][0]):"—":u="Mixed",o.jsx(Ht.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(Ht.Actions,{children:s}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load model usage data"}):o.jsx(Ht.Content,{children:i?o.jsxs(ve,{columns:"auto auto auto auto auto auto",...dbe,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{sticky:"start",children:"Model"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(ve.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:l.model}),o.jsx(ve.NumberCell,{children:l.input}),o.jsx(ve.NumberCell,{children:l.output}),o.jsx(ve.NumberCell,{children:l.cacheRead}),o.jsx(ve.NumberCell,{children:l.cacheWrite}),o.jsx(ve.NumberCell,{highlight:!0,children:l.cost!=null?Cg(l.cost,l.costUnit):"—"})]});return c?o.jsx(ve.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(ve.RowStatic,{children:u},l.model)})]}):o.jsx(Ht.NoData,{message:"No model usage data yet"})})]})}function ous(){const e=We(),{filters:t,filterKey:n}=Im();return yt({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=>TL(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",p=c(f);p.input=d.value,u(p,d)}for(const d of s.groups){const f=d.dimensions.model??"unknown",p=c(f);p.output=d.value,u(p,d)}for(const d of a.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheRead=d.value}for(const d of i.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheWrite=d.value}return Array.from(l.entries()).map(([d,f])=>({model:d,input:Oc(f.input),output:Oc(f.output),cacheRead:Oc(f.cacheRead),cacheWrite:Oc(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function lus(){const{data:e,isLoading:t,isError:n}=ous(),{getTracesHref:r}=KI(),{Link:s}=yn();return o.jsx(ius,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:au.AGENT}),actions:o.jsx(jL,{href:r({rootEntityType:au.AGENT}),LinkComponent:s})})}function cus(e){return e==="tokens"||e==="cost"}function uus({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const[i,l]=v.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),p=new Set(f.map(b=>b.costUnit??"usd")),h=p.size<=1,m=h?[...p][0]??"usd":null,g=h?f.reduce((b,x)=>b+(x.cost??0),0):0,y=h&&g>0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&y?o.jsx(Ht.Summary,{value:Cg(g,m),label:"Total cost"}):o.jsx(Ht.Summary,{value:Oc(d),label:"Total tokens"})),u&&s?o.jsx(Ht.Actions,{children:s}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load token usage data"}):o.jsx(Ht.Content,{children:u?o.jsxs(Dc,{defaultTab:"tokens",value:i,onValueChange:b=>{cus(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Mc,{children:[o.jsx(Rr,{value:"tokens",children:"Tokens"}),o.jsx(Rr,{value:"cost",children:"Cost"})]}),o.jsx(Xr,{value:"tokens",children:o.jsx(AN,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:Fp.blueDark},{label:"Output",color:Fp.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:Oc})}),o.jsx(Xr,{value:"cost",children:y?o.jsx(AN,{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:Fp.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>Cg(b,m)}):o.jsx(Ht.NoData,{message:"No cost data yet"})})]}):o.jsx(Ht.NoData,{message:"No token usage data yet"})})]})}function dus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({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=>TL(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 fus(){const{data:e,isLoading:t,isError:n}=dus(),{getTracesHref:r}=KI(),{Link:s}=yn();return o.jsx(uus,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:au.AGENT,entityName:a.name}),actions:o.jsx(jL,{href:r({rootEntityType:au.AGENT}),LinkComponent:s})})}function ybe(e,t=Oc){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const pus=[{dataKey:"input",label:"Input tokens",color:Fp.blue,aggregate:ybe("input")},{dataKey:"output",label:"Output tokens",color:Fp.yellow,aggregate:ybe("output")}];function hus(e){return e==="tokens"||e==="cost"}function mus({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[a,i]=v.useState("tokens"),l=e??[],c=l.map(k=>({...k})),u=l.length>0,d=l.reduce((k,_)=>k+_.total,0),f=l.filter(k=>k.cost!=null&&k.cost>0),p=f.map(k=>({...k})),h=new Set(f.map(k=>k.costUnit).filter(k=>!!k)),m=h.size===1&&f.every(k=>k.costUnit!=null),g=m?[...h][0]??null:null,y=m?f.reduce((k,_)=>k+(_.cost??0),0):0,b=m&&y>0,x=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",S=[{dataKey:"cost",label:"Cost",color:Fp.purple,aggregate:ybe("cost",k=>Cg(k,g))}];return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Token usage over time",description:x}),u&&(a==="cost"&&b?o.jsx(Ht.Summary,{value:Cg(y,g),label:"Total cost"}):o.jsx(Ht.Summary,{value:Oc(d),label:"Total tokens"})),u&&s?o.jsx(Ht.Actions,{children:s}):null]}),n?o.jsx(Ht.Loading,{}):r?o.jsx(Ht.Error,{message:"Failed to load token usage timeline"}):o.jsx(Ht.Content,{children:u?o.jsxs(Dc,{defaultTab:"tokens",value:a,onValueChange:k=>{hus(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(Mc,{children:[o.jsx(Rr,{value:"tokens",children:"Tokens"}),o.jsx(Rr,{value:"cost",children:"Cost"})]}),o.jsx(Xr,{value:"tokens",children:o.jsx(IV,{data:c,series:pus})}),o.jsx(Xr,{value:"cost",children:b?o.jsx(IV,{data:p,series:S}):o.jsx(Ht.NoData,{message:"No cost data yet"})})]}):o.jsx(Ht.NoData,{message:"No token usage data yet"})})]})}function gus(e){return e==="24h"?"1h":"1d"}function vus(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 EXe(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 yus(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function bus(){const e=We(),{datePreset:t,filters:n,filterKey:r}=Im(),s=gus(t);return yt({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 EXe(l,a.series[0],"input"),EXe(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:vus(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:yus(u)}}),interval:s}}})}function xus(){const{data:e,isLoading:t,isError:n}=bus(),{getTracesHref:r}=KI(),{Link:s}=yn();return o.jsx(mus,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(jL,{href:r(),LinkComponent:s})})}function Iae({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(AN,{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:Fp.blueDark},{label:"Errors",color:Fp.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:Oc})}function wus({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:a,LinkComponent:i}){const[l,c]=v.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,g)=>m+g.completed+g.errors,0):0,p=m=>r?g=>r(m,g):void 0,h=m=>s?g=>s(m,g):void 0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(Ht.Summary,{value:Oc(f),label:"Total runs"}),u?o.jsx(Ht.Actions,{children:u}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load trace volume data"}):o.jsx(Ht.Content,{children:d?o.jsxs(Dc,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Mc,{children:[o.jsx(Rr,{value:"agents",children:"Agents"}),o.jsx(Rr,{value:"workflows",children:"Workflows"}),o.jsx(Rr,{value:"tools",children:"Tools"})]}),o.jsx(Xr,{value:"agents",children:e.agentData.length>0?o.jsx(Iae,{data:e.agentData,rowHrefs:p("agents"),errorHrefs:h("agents"),LinkComponent:i}):o.jsx(Ht.NoData,{message:"No agent data yet"})}),o.jsx(Xr,{value:"workflows",children:e.workflowData.length>0?o.jsx(Iae,{data:e.workflowData,rowHrefs:p("workflows"),errorHrefs:h("workflows"),LinkComponent:i}):o.jsx(Ht.NoData,{message:"No workflow data yet"})}),o.jsx(Xr,{value:"tools",children:e.toolData.length>0?o.jsx(Iae,{data:e.toolData,rowHrefs:p("tools"),errorHrefs:h("tools"),LinkComponent:i}):o.jsx(Ht.NoData,{message:"No tool data yet"})})]}):o.jsx(Ht.NoData,{message:"No trace volume data yet"})})]})}async function Aae(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=TL(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 Sus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([Aae(e,"mastra_agent_duration_ms",t),Aae(e,"mastra_workflow_duration_ms",t),Aae(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const Fz={agents:au.AGENT,workflows:au.WORKFLOW_RUN,tools:au.TOOL};function kus(){const{data:e,isLoading:t,isError:n}=Sus(),{getTracesHref:r,getLogsHref:s}=KI(),{Link:a}=yn();return o.jsx(wus,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:Fz[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:Fz[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(jL,{href:r({rootEntityType:Fz[i]}),LinkComponent:a}),o.jsx($cs,{href:s({rootEntityType:Fz[i],status:"error"}),LinkComponent:a})]})})}const Rae="period",zz="dateFrom",Bz="dateTo";function Ous(){const[e,t]=Ri(),n=e.get(Rae),r=Ocs(n)?n:"24h",s=v.useMemo(()=>{if(r!=="custom")return;const d=h=>{if(!h)return;const m=new Date(h);return Number.isNaN(m.getTime())?void 0:m},f=d(e.get(zz)),p=d(e.get(Bz));if(!(!f&&!p))return{from:f,to:p}},[r,e.toString()]),a=v.useMemo(()=>vcs(e),[e.toString()]),i=v.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d==="24h"?p.delete(Rae):p.set(Rae,d),d!=="custom"&&(p.delete(zz),p.delete(Bz)),p},{replace:!0})},[t]),l=v.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d?.from?p.set(zz,d.from.toISOString()):p.delete(zz),d?.to?p.set(Bz,d.to.toISOString()):p.delete(Bz),p},{replace:!0})},[t]),c=v.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return bcs(p,d),p},{replace:!0})},[t]),u=v.useRef(!1);return v.useEffect(()=>{if(u.current||(u.current=!0,mcs(e)))return;const d=w7t();d&&t(f=>{const p=new URLSearchParams(f);for(const[h,m]of d)p.append(h,m);return p},{replace:!0})},[]),o.jsx(Ccs,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(_us,{})})}function _us(){const[e]=Ri(),{error:t,isLoading:n}=O7t(),{filterTokens:r,setFilterTokens:s}=rQ(),[a,i]=v.useState(),{supportsMetrics:l,isInMemory:c,isLoading:u}=Pcs(),{data:d,isLoading:f}=iIe(),{data:p,isLoading:h}=rIe(),{data:m,isLoading:g}=aIe(),{data:y,isLoading:b}=sIe(),x=v.useMemo(()=>gcs({availableTags:d??[],availableEntityNames:p??[],availableServiceNames:m??[],availableEnvironments:y??[],loading:{tags:f,entityNames:h,serviceNames:g,environments:b}}),[d,p,m,y,f,h,g,b]),[S,k]=v.useState(()=>w7t()!==null),_=v.useCallback(()=>{pcs(e),k(!0),Le.success("Filters setting for Metrics saved")},[e]),C=v.useCallback(()=>{hcs(),k(!1),Le.success("Filters setting for Metrics cleared up")},[]),E=v.useCallback(()=>{s([])},[s]),j=v.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&&ys(t)?o.jsx(lr,{children:o.jsx(Hs,{})}):t&&xs(t)?o.jsx(lr,{children:o.jsx(Ms,{resource:"metrics"})}):t?o.jsx(lr,{children:o.jsx(qi,{title:"Failed to load metrics",message:t.message})}):o.jsxs(Ft,{width:"wide",height:"full",children:[o.jsxs(Ft.TopArea,{children:[o.jsx(Ft.Row,{children:o.jsxs(Ft.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(Ncs,{}),o.jsx(YNe,{fields:x,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(sus,{isLoading:n,filterFields:x,filterTokens:r,onFilterTokensChange:s,onClear:j,onRemoveAll:E,onSave:_,onRemoveSaved:S?C:void 0,autoFocusFilterFieldId:a})]}),u?null:l?o.jsxs("div",{className:"grid content-start gap-8 pb-10",children:[c&&o.jsx(En,{variant:"info",title:"Metrics are not persisted",children:o.jsx(En.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(fbe,{children:[o.jsx(Jcs,{}),o.jsx(eus,{}),o.jsx(tus,{}),o.jsx(nus,{}),o.jsx(rus,{})]}),o.jsxs(fbe,{children:[o.jsx(lus,{}),o.jsx(fus,{}),o.jsx(xus,{}),o.jsx(Gcs,{}),o.jsx(kus,{}),o.jsx(Vcs,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(Nf,{}),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(ce,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(Sa,{})]})})})]})}function Cus(){const{paths:e}=yn(),{data:t,isLoading:n,error:r}=t8t(),{isCmsAvailable:s}=X1(),[a,i]=v.useState(""),l=t?.promptBlocks??[];return r&&ys(r)?o.jsx(lr,{children:o.jsx(Hs,{})}):r&&xs(r)?o.jsx(lr,{children:o.jsx(Ms,{resource:"prompt blocks"})}):r?o.jsx(lr,{children:o.jsx(qi,{title:"Failed to load prompt blocks",message:r.message})}):l.length===0&&!n?o.jsx(lr,{children:o.jsx(UXr,{})}):o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsxs(Ft.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx($f,{onSearch:i,label:"Filter prompts",placeholder:"Filter by name or description"})}),s&&o.jsxs(ce,{as:ei,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(Zr,{}),"Create Prompt"]})]})}),o.jsx(BXr,{promptBlocks:l,isLoading:n,search:a})]})}function Eus(){return o.jsx(Ft,{width:"narrow",children:o.jsx(Ft.MainArea,{children:o.jsx(xQr,{children:o.jsx(Uye,{})})})})}const jus=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:WHt,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:sit,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Sa,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:dT,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:fit,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:ait,href:"https://mastra.ai/contact?ref=studio",external:!0}];function Tus(){return o.jsx(Ft,{width:"narrow",children:o.jsx(Ft.MainArea,{children:o.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:jus.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(Sa,{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 Nus(){const{data:e={},isLoading:t,error:n}=ih(),[r,s]=v.useState(""),[a,i]=v.useState("all");if(n&&ys(n))return o.jsx(lr,{children:o.jsx(Hs,{})});if(n&&xs(n))return o.jsx(lr,{children:o.jsx(Ms,{resource:"scorers"})});if(n)return o.jsx(lr,{children:o.jsx(qi,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(lr,{children:o.jsx(QYr,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsx(KYr,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(GYr,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}function Ius(){const{scorerId:e}=Sr(),[t,n]=Ri(),r=t.get("scoreId")??void 0,[s,a]=v.useState(r),[i,l]=v.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:c,error:u}=_Yr(e),{data:d={},isLoading:f,error:p}=Em(),{isLoading:h,error:m}=Hy(),{data:g=[],isLoading:y,error:b,isFetchingNextPage:x,hasNextPage:S,setEndOfListElement:k}=OYr({scorerId:e,entityId:i?.value==="all"?void 0:i?.value,entityType:i?.type==="ALL"?void 0:i?.type}),_=v.useMemo(()=>c?.agentIds?.filter(q=>d[q]).map(q=>({value:q,label:d[q].name,type:"AGENT"}))||[],[c?.agentIds,d]),C=v.useMemo(()=>c?.workflowIds?.map(q=>({value:q,label:q,type:"WORKFLOW"}))||[],[c?.workflowIds]),E=v.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},..._,...C],[_,C]),j=t.get("entity")??"all",N=E.find(q=>q.value===j);N&&N.value!==i?.value&&l(N),v.useEffect(()=>{if(u){const q=u instanceof Error?u.message:"Failed to load scorer";Le.error(`Error loading scorer: ${q}`)}},[u]),v.useEffect(()=>{if(p){const q=p instanceof Error?p.message:"Failed to load agents";Le.error(`Error loading agents: ${q}`)}},[p]),v.useEffect(()=>{if(m){const q=m instanceof Error?m.message:"Failed to load workflows";Le.error(`Error loading workflows: ${q}`)}},[m]);const I=q=>{q?.value&&n(M=>{const G=new URLSearchParams(M);return G.set("entity",q.value),G})};v.useEffect(()=>{const q=t.get("scoreId")??void 0;if(q===s)return;if(!q){a(void 0);return}g.find(G=>G.id===q)&&a(q)},[t,g]);const A=v.useCallback(q=>{a(q||void 0),n(M=>{const G=new URLSearchParams(M);return q?G.set("scoreId",q):G.delete("scoreId"),G})},[n]);if(!c)return null;const R=ys(u)||ys(p)||ys(m),L=u&&xs(u),D=!R&&!L&&(u||p||m),B=!y&&g.length===0,H=i?.value!=="all",F=c?.scorer?.source==="stored"?o.jsx($y,{owner:"scorer-detail",children:o.jsxs(ce,{variant:"default",as:ei,to:`/cms/scorers/${e}/edit`,size:"sm",children:[o.jsx(rm,{})," Edit"]})}):null;if(R||L||D||B&&!H){const q=(u instanceof Error?u.message:void 0)??(p instanceof Error?p.message:void 0)??(m instanceof Error?m.message:void 0)??"An unexpected error occurred";return o.jsxs(Ft,{width:"wide",height:"full",children:[F,o.jsx(Ft.MainArea,{isCentered:!0,children:R?o.jsx(Hs,{}):L?o.jsx(Ms,{resource:"scorers"}):D?o.jsx(qi,{title:"Failed to load scorer",message:q}):o.jsx(vYr,{})})]})}return o.jsxs(Ft,{width:"wide",children:[F,o.jsx(Ft.TopArea,{children:o.jsx(yYr,{selectedEntity:i,entityOptions:E,onEntityChange:I,onReset:()=>{n(q=>{const M=new URLSearchParams(q);return M.set("entity","all"),M})},isLoading:y||f||h})}),o.jsx(gYr,{scores:g,isLoading:y,selectedScoreId:s,isFetchingNextPage:x,hasNextPage:S,setEndOfListElement:k,onScoreClick:A,errorMsg:b?.message})]})}function Aus({label:e,description:t,htmlFor:n,className:r,children:s}){return o.jsxs("div",{className:X("flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",r),"data-slot":"settings-row",children:[o.jsxs("div",{children:[n?o.jsx(Dt,{htmlFor:n,className:"text-sm font-medium",children:e}):o.jsx("p",{className:"text-sm font-medium",children:e}),t&&o.jsx("p",{className:"text-neutral3 text-sm",children:t})]}),s]})}const j7t=[{value:"dark",label:"Dark",Icon:_Zt},{value:"light",label:"Light",Icon:DGt},{value:"system",label:"System",Icon:bit}],Rus=e=>j7t.some(t=>t.value===e);function Pus({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 $us=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=Kq(),{theme:r,setTheme:s}=B_();return o.jsx(Ft,{width:"narrow",children:o.jsxs(Ft.MainArea,{className:"mt-6 flex flex-col gap-5",children:[o.jsx(_ye,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(Aus,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(oa,{value:r,onValueChange:a=>{Rus(a)&&s(a)},children:[o.jsx(ca,{id:"theme",className:"w-full sm:w-48",children:o.jsx(la,{className:"inline-flex max-w-full min-w-0 items-center"})}),o.jsx(ua,{children:j7t.map(a=>o.jsx(Ar,{value:a.value,children:o.jsx(Pus,{option:a})},a.value))})]})})}),o.jsx(_ye,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(q$t,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function Mus(){const[e]=Ri(),t=qs(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(y7t,{redirectUri:n,onSuccess:r,initialMode:"signup"})}const T7t=e=>o.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("g",{clipPath:"url(#clip0_21999_22095)",children:o.jsx("path",{d:"M7.5 0.75C3.6325 0.75 0.5 3.8825 0.5 7.75C0.5 10.8475 2.50375 13.4637 5.28625 14.3912C5.63625 14.4525 5.7675 14.2425 5.7675 14.0587C5.7675 13.8925 5.75875 13.3412 5.75875 12.755C4 13.0787 3.545 12.3262 3.405 11.9325C3.32625 11.7312 2.985 11.11 2.6875 10.9437C2.4425 10.8125 2.0925 10.4887 2.67875 10.48C3.23 10.4712 3.62375 10.9875 3.755 11.1975C4.385 12.2562 5.39125 11.9587 5.79375 11.775C5.855 11.32 6.03875 11.0137 6.24 10.8387C4.6825 10.6637 3.055 10.06 3.055 7.3825C3.055 6.62125 3.32625 5.99125 3.7725 5.50125C3.7025 5.32625 3.4575 4.60875 3.8425 3.64625C3.8425 3.64625 4.42875 3.4625 5.7675 4.36375C6.3275 4.20625 6.9225 4.1275 7.5175 4.1275C8.1125 4.1275 8.7075 4.20625 9.2675 4.36375C10.6062 3.45375 11.1925 3.64625 11.1925 3.64625C11.5775 4.60875 11.3325 5.32625 11.2625 5.50125C11.7087 5.99125 11.98 6.6125 11.98 7.3825C11.98 10.0687 10.3438 10.6637 8.78625 10.8387C9.04 11.0575 9.25875 11.4775 9.25875 12.1337C9.25875 13.07 9.25 13.8225 9.25 14.0587C9.25 14.2425 9.38125 14.4612 9.73125 14.3912C11.1209 13.9221 12.3284 13.029 13.1839 11.8377C14.0393 10.6463 14.4996 9.21668 14.5 7.75C14.5 3.8825 11.3675 0.75 7.5 0.75Z",fill:"currentColor"})}),o.jsx("defs",{children:o.jsx("clipPath",{id:"clip0_21999_22095",children:o.jsx("rect",{width:"14",height:"14",fill:"currentColor",transform:"translate(0.5 0.75)"})})})]});function Dus(e){return e.replace(/\/$/,"").split("/").pop()}function sQ({children:e,className:t}){return o.jsx("div",{className:X("border border-border1 rounded-lg mt-12 py-8 lg:min-h-[25rem] transition-height px-4 lg:px-12",t),children:e})}function Lus({templates:e,linkComponent:t,className:n,isLoading:r}){const s=t||"a";return r?o.jsx("div",{className:X("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:X("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:X("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:X("grid [&:hover_p]:text-neutral5",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":a.imageURL}),children:[a.imageURL&&o.jsx("div",{className:X("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:X("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:X("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(Ld,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(xit,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(RD,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(hC,{})," ",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:X("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(T7t,{})," ",Dus(a.githubUrl)]})})]},a.slug)})})}function Fus({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:X("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:X("flex flex-wrap mx-auto sticky top-0 gap-4 bg-surface2 py-8",u),children:[o.jsx(vN,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(Cc,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(Cc,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(ce,{onClick:c,children:["Reset ",o.jsx(bs,{})]})]})}function zus(){const{data:e,isLoading:t}=GJn(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[a,i]=v.useState("all"),[l,c]=v.useState("all"),[u,d]=v.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(x=>{f.push({value:x,label:x})});const p=[{value:"all",label:"Any provider"}];(s||[]).forEach(x=>{p.push({value:x,label:x})});const h=(x,S)=>{S==="tag"?i(x):S==="provider"&&c(x)},m=x=>{d(x)},g=()=>{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(ds,{children:[o.jsx(Iwe,{children:o.jsxs(jgt,{children:[o.jsx(qe,{children:o.jsx(Kv,{})}),"Templates"]})}),o.jsxs("div",{className:X("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(Fus,{selectedTag:a,onTagChange:x=>h(x,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:x=>h(x,"provider"),providerOptions:p,searchTerm:u,onSearchChange:m,onReset:b?g:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(Lus,{templates:y,linkComponent:ei,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const Bus="1.54.0";function Uus({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(yf,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(wWt,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(sQ,{className:"text-neutral3 mb-8 content-center space-y-4",children:[o.jsxs("div",{className:X("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 Vus({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(sQ,{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:X("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(wit,{})]}),o.jsx(Cc,{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:X("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(Xt,{})," Loading variables..."]}):Object.entries(r).map(([p,h])=>o.jsxs(v.Fragment,{children:[o.jsx(CO,{name:`env-${p}`,labelIsHidden:!0,label:"Key",value:p,disabled:!0,className:"w-full"}),o.jsx(CO,{name:p,labelIsHidden:!0,label:"Value",value:h,onChange:i,errorMsg:s.includes(p)?"Value is required.":"",autoComplete:"off",className:"w-full"})]},p))}),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(Izt,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(ce,{className:X("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(Xt,{className:"h-4 w-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(ym,{})]})})]})})}function qus({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:X("grid mt-8 items-center"),children:o.jsxs("div",{className:X("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(Kv,{}),o.jsx("h2",{className:X({"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:X("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:X("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(Bx,{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(Rbe,{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(T7t,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(xNe,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function Hus(e){switch(e){case"running":return o.jsx(Xt,{});case"success":return o.jsx(xx,{});case"failed":return o.jsx(Wu,{});default:return null}}function Wus({stepId:e,step:t,isActive:n,position:r}){const s=a=>a.charAt(0).toUpperCase()+a.slice(1).replace(/-/g," ");return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3",vs.all,{"border border-dashed border-neutral2 bg-surface3":n}),children:[o.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-2",children:[o.jsxs("span",{className:X("flex min-w-6 justify-end text-ui-md",vs.colors,{"text-neutral5":n||t.status==="success","text-neutral3":!n&&t.status!=="success"}),children:[r,"."]}),o.jsxs("div",{children:[o.jsx("h4",{className:X("text-ui-md",vs.colors,{"text-neutral5":n||t.status==="success","text-neutral3":!n&&t.status!=="success"}),children:s(e)}),t.description&&o.jsx("p",{className:"text-ui-md text-neutral2 -mt-0.5",children:t.description})]})]}),o.jsx("div",{className:X("flex size-[1.75rem] items-center justify-center self-center rounded-full",vs.all,{"border border-neutral2 border-dashed":t.status==="pending","[&>svg]:text-white [&>svg]:w-4 [&>svg]:h-4":t.status!=="running","w-[1.75rem] h-[1.75rem]":t.status==="running","bg-accent1Dark shadow-glow-accent1":t.status==="success","bg-accent2Dark shadow-glow-accent2":t.status==="failed","scale-110":t.status==="success"||t.status==="failed"}),children:Hus(t.status)})]})}function Zus({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:X(n),children:t.map((r,s)=>o.jsx(Wus,{stepId:r.id,step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function Gus({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:X("relative flex h-8 items-center justify-end",vs.colors,{"bg-accent1Dark":r.status==="success"&&e?.[s-1]?.status==="success"}),children:o.jsx("div",{className:X("absolute right-0 z-10 flex size-[2rem] translate-x-[50%] items-center justify-center self-center rounded-full bg-surface3 text-ui-sm font-bold text-neutral3",vs.all,{"border border-neutral2 border-dashed":r.status==="pending","[&>svg]:text-surface1 [&>svg]:w-[1.1rem] [&>svg]:h-[1.1rem]":r.status!=="running","bg-accent1Dark text-white shadow-glow-accent1 scale-110":r.status==="success","bg-accent2Dark text-white shadow-glow-accent2 scale-110":r.status==="failed"}),children:r.status==="running"?o.jsx(Xt,{}):s+1})},r.id))}),o.jsxs("div",{className:X("text-center text-xs text-neutral3",vs.colors),children:[n," of ",t," steps completed"]})]})}function Qus({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=g=>g==="input"||g.endsWith(".input")||g.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(g)||/[0-9a-f]{8,}/.test(g)?!1:r?.allSteps?g in r.allSteps:!0,f=Object.entries(c).filter(([g,y])=>d(g)),p=f.length,h=()=>{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(([g,y])=>({id:g,status:y?.status,description:y?.description,title:g.charAt(0).toUpperCase()+g.slice(1).replace(/-/g," "),isActive:i?.id===g}));return o.jsxs(sQ,{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:h()}),(t?.runId||n)&&o.jsxs("div",{className:"text-ui-sm text-neutral3 mt-2",children:["Run ID: ",t?.runId??n]})]}),u&&p>0&&!["error"].includes(s)&&o.jsx("div",{className:"mx-auto w-full max-w-[30rem] px-6",children:o.jsx(Gus,{steps:m})}),l&&s==="error"&&o.jsxs("div",{className:X("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($Zt,{}),l||"Something went wrong"]}),u&&o.jsx(Zus,{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(Xt,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function Yus({name:e,installedEntities:t}){return o.jsxs(sQ,{className:X("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(wit,{}),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(xNe,{data:t})]})}function Kus(){const{templateSlug:e}=Sr(),[t,n]=Ri(),[r,s]=v.useState(""),[a,i]=v.useState(""),[l,c]=v.useState(""),[u,d]=v.useState({}),[f,p]=v.useState([]),[h,m]=v.useState(null),[g,y]=v.useState(!1),[b,x]=v.useState(""),[S,k]=v.useState(!1),[_,C]=v.useState(!1),[E,j]=v.useState([]),{data:N,isLoading:I}=QJn({repoOrSlug:e,owner:"mastra-ai"}),R=Bus?.includes("beta")??!1?"beta":"main",{data:L,isLoading:D}=YJn({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:R}),{data:B,isLoading:H}=KJn(),{mutateAsync:F,isPending:z}=XJn(),{mutateAsync:q}=JJn(),{streamInstall:M,streamResult:G,isStreaming:V}=ter(B),{observeInstall:$,streamResult:U,isStreaming:Z}=ner(B);v.useEffect(()=>{const ne=t.get("runId");ne&&!g&&!h&&!V&&!Z&&(console.info("🔄 Checking completed run after hot reload:",{runId:ne}),x(ne),q({runId:ne}).then(fe=>{const oe=fe.snapshot;if(oe?.status==="success"&&oe?.result?.success)y(!0);else if(oe?.result?.success===!1)if(oe?.result?.validationResults&&!oe?.result?.validationResults?.valid&&oe?.result?.validationResults?.remainingErrors>0){const{remainingErrors:he,errors:be}=oe.result.validationResults,xe=`Template installation completed but ${he} validation issue${he>1?"s":""} remain unresolved.`;m(xe),j(be||[])}else{const he=oe?.result?.message||oe?.result?.error||"Template installation failed";m(typeof he=="string"?he:String(he))}}).catch(fe=>{console.error("❌ Failed to fetch run details:",fe),m("Failed to retrieve installation status after reload")}))},[t,g,h,V,Z,q]),v.useEffect(()=>{const ne=t.get("runId"),fe=t.get("resume"),oe=t.get("provider");if(ne&&fe==="true"&&oe&&!V&&!Z&&!S&&!_&&B){x(ne),k(!0);try{q({runId:ne}).then(le=>{if(le.snapshot?.status==="running")return $.mutateAsync({runId:ne})}).then(()=>{n(le=>{const he=new URLSearchParams(le);return he.delete("resume"),he})}).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,V,Z,S,_,B,q,$,n]);const K=[{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(Ld,{})},{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(RD,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(Mv,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(BN,{})}],ee=[{...te[0]},{...te[1]},{...te[2]}].filter(ne=>ne.value!=="n/a");v.useEffect(()=>{L&&d(L)},[L]),v.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 J=ne=>{s(ne)},ae=async ne=>(i(ne.provider),c(ne.modelId),{message:"Model updated successfully"}),de=async()=>{const ne=Object.entries(u).reduce((fe,[oe,le])=>(le===""&&fe.push(oe),fe),[]);if(ne.length>0){p(ne);return}if(N){m(null),y(!1),x(""),C(!0);try{const oe={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:R,slug:N.slug,variables:u},{runId:le}=await F({});x(le),n(he=>{const be=new URLSearchParams(he);return be.set("runId",le),be.set("resume","true"),be.set("provider",r||"openai"),be}),await M.mutateAsync({inputData:oe,selectedModel:{provider:a,modelId:l},runId:le})}catch(fe){C(!1),m(fe?.message||"Template installation failed"),console.error("Template installation failed",fe)}}},Y=ne=>{const{name:fe,value:oe}=ne.target;oe.trim()===""?p(le=>[...le,fe]):p(le=>le.filter(he=>he!==fe)),d(le=>({...le,[fe]:oe}))};return o.jsx(ds,{children:o.jsx("div",{className:X("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(qus,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:te,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(V||Z)&&o.jsx(Qus,{name:N.title,streamResult:Z?U:G,runId:b,workflowInfo:B}),g&&o.jsx(Yus,{name:N.title,installedEntities:ee,linkComponent:ei}),h&&o.jsx(Uus,{errorMsg:h,validationErrors:E.length>0?E:G?.validationResults?.errors||U?.validationResults?.errors}),!V&&!Z&&!g&&!h&&o.jsx(Vus,{providerOptions:K,selectedProvider:r,onProviderChange:J,variables:u,setVariables:d,errors:f,setErrors:p,handleInstallTemplate:de,handleVariableChange:Y,isLoadingEnvVars:D||H,isInstalling:z,defaultModelProvider:a,defaultModelId:l,onModelUpdate:ae})]})]})})})}const Xus=()=>{const{toolId:e,agentId:t}=Sr();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(aXr,{toolId:e,agentId:t})})},Jus=()=>{const{toolId:e}=Sr();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(rcs,{toolId:e})})};function eds(){const{traceId:e}=Sr(),[t,n]=Ri(),r=qs(),s=t.get("spanId")||void 0,a=t.get("tab"),i=a==="scoring"?"scoring":a==="feedback"?"feedback":"details",l=t.get("scoreId")||void 0,[c,u]=v.useState(s??null),[d,f]=v.useState(),[p,h]=v.useState(i),[m,g]=v.useState(0),[y,b]=v.useState(!1),{data:x,isLoading:S,error:k}=oIe(e),_=v.useMemo(()=>x?.spans??[],[x?.spans]),C=v.useMemo(()=>_.find(ae=>ae.parentSpanId==null),[_]),{data:E,isLoading:j}=CL(e,c??"");v.useEffect(()=>g(0),[e,c]);const{data:N,isLoading:I}=ih(),{data:A,isLoading:R}=Yzt({traceId:e,spanId:c??void 0,page:m}),[L,D]=v.useState(0);v.useEffect(()=>D(0),[e,c]);const{data:B,isLoading:H}=i7t({traceId:e,page:L});v.useEffect(()=>{if(l&&A?.scores&&!d){const ae=A.scores.find(de=>de.id===l);ae&&f(ae)}},[l,A?.scores,d]);const F=v.useCallback(ae=>{const de=new URLSearchParams(t);for(const[Y,ne]of Object.entries(ae))ne===null||ne===""?de.delete(Y):de.set(Y,ne);n(de,{replace:!0})},[t,n]),z=v.useCallback(ae=>{const de=ae??null,Y=de===c;u(de),Y||(f(void 0),h("details"),F({spanId:de,tab:null,scoreId:null}))},[c,F]),q=v.useCallback(()=>{u(null),f(void 0),h("details"),F({spanId:null,tab:null,scoreId:null})},[F]),M=v.useCallback(ae=>{u(ae),f(void 0),h("details"),F({spanId:ae,tab:null,scoreId:null})},[F]),{handlePreviousSpan:G,handleNextSpan:V}=lIe(_,c,M),$=v.useCallback(ae=>{const de=ae;h(de),f(void 0),F({tab:de==="details"?null:de,scoreId:null})},[F]),U=v.useCallback(ae=>{f(ae),F({scoreId:ae.id})},[F]),Z=v.useCallback(()=>{f(void 0),F({scoreId:null})},[F]),K=v.useCallback(()=>{r("/observability")},[r]),te=v.useCallback(()=>{h("scoring"),C&&c!==C.spanId?(u(C.spanId),f(void 0),F({spanId:C.spanId,tab:"scoring",scoreId:null})):F({tab:"scoring"})},[C,c,F]),ee=C?o.jsx($y,{owner:"trace-detail",children:o.jsxs(Mr,{children:[o.jsxs(ce,{tooltip:"Evaluate Trace","aria-label":"Evaluate Trace",onClick:te,children:[o.jsx(hHt,{}),"Evaluate"]}),o.jsxs(ce,{tooltip:"Save as Dataset Item","aria-label":"Save as Dataset Item",onClick:()=>b(!0),children:[o.jsx(jd,{}),"Save"]})]})}):null,J=C?o.jsx(Ft.Row,{children:o.jsx(Ft.Column,{children:o.jsx(H9t,{rootSpan:C,numOfCol:3})})}):null;return k?o.jsxs(Ft,{height:"full",children:[ee,J&&o.jsx(Ft.TopArea,{children:J}),o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsx(Y9t,{error:k,resource:"traces",errorTitle:"Failed to load trace"})})]}):o.jsxs(Ft,{height:"full",className:"grid-rows-[auto_minmax(0,1fr)] content-normal",children:[ee,J&&o.jsx(Ft.TopArea,{children:J}),o.jsx(t7t,{rootSpanId:C?.spanId,traceId:e,isOpen:y,onClose:()=>b(!1)}),o.jsxs("div",{className:X("mt-4 grid min-h-0 items-stretch gap-4 overflow-hidden",c?"grid-cols-[2fr_3fr]":"grid-cols-[1fr]"),children:[o.jsx(eIe,{traceId:e,spans:_,isLoading:S,onClose:K,onSpanSelect:z,onEvaluateTrace:te,initialSpanId:c,placement:"trace-page",timelineChartWidth:c?"default":"wide"}),c&&!S&&o.jsxs("div",{className:X("grid h-full max-h-full min-h-0 gap-4 overflow-auto",d?"grid-rows-[1fr_1fr]":"grid-rows-[1fr]"),children:[o.jsx(KNe,{traceId:e,spanId:c,span:E?.span,isLoading:j,onClose:q,onPrevious:G,onNext:V,activeTab:p,onTabChange:$,feedbackTabBadge:B?.pagination?.total??void 0,feedbackTabSlot:()=>o.jsx(r7t,{feedbackData:B,onPageChange:D,isLoadingFeedbackData:H}),scoringTabBadge:A?.pagination?.total??void 0,scoringTabSlot:({span:ae,traceId:de,spanId:Y})=>o.jsxs("div",{className:"grid gap-6",children:[o.jsx(a7t,{traceId:de,isTopLevelSpan:!ae.parentSpanId,spanId:Y,entityType:ae.attributes?.agentId||ae.entityType===au.AGENT?"Agent":ae.attributes?.workflowId||ae.entityType===au.WORKFLOW_RUN?"Workflow":void 0,scorers:N,isLoadingScorers:I}),o.jsx(s7t,{scoresData:A,onPageChange:g,isLoadingScoresData:R,onScoreSelect:U})]})}),d&&o.jsx(bNe,{score:d,onClose:Z})]})]})]})}function tds(){const{data:e,isLoading:t,error:n}=Hy(),[r,s]=v.useState("");return n&&ys(n)?o.jsx(lr,{children:o.jsx(Hs,{})}):n&&xs(n)?o.jsx(lr,{children:o.jsx(Ms,{resource:"workflows"})}):n?o.jsx(lr,{children:o.jsx(qi,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(lr,{children:o.jsx(F8r,{})}):o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsxs(Ft.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx($f,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsxs(ce,{as:ei,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(TD,{}),"Schedules"]})]})}),o.jsx(L8r,{workflows:e||{},isLoading:t,search:r})]})}const nds={active:"bg-accent1",paused:"bg-accent3"},rds={active:"text-accent1",paused:"text-accent3"},N7t=({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 ${nds[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${rds[e]}`,children:e})]}),iT=e=>!e||e<=0?"—":new Date(e).toLocaleString(),$2=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 I7t({status:e}){const{icon:t,color:n}=sds(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 sds(e){switch(e){case"success":return{icon:o.jsx(fa,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(bs,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(Xt,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(BV,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(Nf,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(uT,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const jXe="auto auto auto auto 1fr";function ads(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 ids(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 ods=3e4,lds=5*6e4;function cds({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=yn();return t?o.jsx(ol,{columns:jXe}):e.length===0?o.jsx(ye,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(ve,{columns:jXe,className:"min-w-0",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Run"}),o.jsx(ve.TopCell,{children:"Status"}),o.jsx(ve.TopCell,{children:"Started"}),o.jsx(ve.TopCell,{children:"Duration"}),o.jsx(ve.TopCell,{children:" "})]}),e.map(c=>{const u=c.actualFireAt-c.scheduledFireAt,d=ids(u),f=`Scheduled ${iT(c.scheduledFireAt)} — published ${iT(c.actualFireAt)} (drift ${d})`,p=c.outcome==="failed",h=p?c.error:c.run?.error,m=Math.abs(u),g=!p&&m>ods&&m<=lds,y=`${c.scheduleId}-${c.runId}-${c.actualFireAt}`,b=!!(n&&c.runId&&!p),x=o.jsx("span",{className:b?"text-accent1 text-ui-sm font-mono whitespace-nowrap":"text-neutral3 text-ui-sm font-mono whitespace-nowrap",children:c.runId}),S=o.jsxs(o.Fragment,{children:[o.jsx(ve.Cell,{height:"compact",children:x}),o.jsx(ve.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[p?o.jsxs("span",{className:"text-ui-sm text-accent2 inline-flex items-center gap-1.5 whitespace-nowrap",children:[o.jsx(yf,{size:14}),"publish failed"]}):c.run?o.jsx(I7t,{status:c.run.status}):o.jsx("span",{className:"text-ui-sm text-neutral3 inline-flex items-center gap-1.5 whitespace-nowrap",children:"pending"}),h?o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(yf,{size:14})})}),o.jsx(Rn,{children:h})]}):null]})}),o.jsx(ve.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:f,children:$2(c.actualFireAt)}),g?o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(yf,{size:14})})}),o.jsxs(Rn,{children:["Published ",d," after the scheduled fire time"]})]}):null]})}),o.jsx(ve.Cell,{height:"compact",children:c.run?o.jsx("span",{children:ads(c.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(ve.Cell,{height:"compact",children:" "})]});return b?o.jsx(ve.RowLink,{to:l.workflowRunLink(n,c.runId),LinkComponent:i,children:S},y):o.jsx(ve.RowStatic,{children:S},y)}),o.jsx(ve.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const uds=e=>{const t=We();return yt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},TXe=25,dds=e=>{const t=We(),{inView:n,setRef:r}=W_(),s=M1({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:TXe,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<TXe))return u.triggers[u.triggers.length-1].actualFireAt},refetchInterval:u=>(u.state.data?.pages.flatMap(p=>p.triggers)??[]).some(p=>p.run?p.run.status==="pending"||p.run.status==="running"||p.run.status==="waiting":p.outcome==="published")?5e3:!1}),a=s.data?.pages.flatMap(u=>u?.triggers??[])??[],{hasNextPage:i,isFetchingNextPage:l,fetchNextPage:c}=s;return v.useEffect(()=>{n&&i&&!l&&c()},[n,i,l,c]),{...s,data:a,setEndOfListElement:r}},fds=e=>{const t=We(),n=Ur();return Mn({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"]}),Le.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{Le.error(r.message)}})};function Uz({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 tracking-wide uppercase",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function pds(){const{scheduleId:e}=Sr(),{paths:t}=yn(),{data:n,error:r}=uds(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=dds(e),d=fds(e);if(r&&ys(r))return o.jsx(lr,{children:o.jsx(Hs,{})});if(r&&xs(r))return o.jsx(lr,{children:o.jsx(Ms,{resource:"schedules"})});if(r)return o.jsx(lr,{children:o.jsx(qi,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,p=n?.agentId;return o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsx(Ft.Row,{className:"justify-end",children:o.jsxs(Ft.Column,{className:"flex justify-end gap-2",children:[o.jsxs(ce,{as:ei,to:t.schedulesLink(),variant:"ghost",children:[o.jsx(Ac,{}),"Back to schedules"]}),f?o.jsx(ce,{as:ei,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(ce,{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(Mbe,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(Of,{}),"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(Uz,{label:p?"Agent":"Workflow",children:f?o.jsx(ei,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):p?o.jsx(ei,{to:t.agentLink(p),className:"text-accent1 hover:underline",children:p}):"—"}),o.jsxs(Uz,{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(Uz,{label:"Status",children:o.jsx(N7t,{status:n.status})}),o.jsx(Uz,{label:"Next fire",children:o.jsx("span",{title:iT(n.nextFireAt),children:$2(n.nextFireAt)})})]}),o.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[o.jsx(ye,{variant:"ui-md",className:"mb-3",children:"Trigger history"}),i?o.jsx(qi,{title:"Failed to load trigger history",message:i.message}):o.jsx(cds,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const NXe="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function hds({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=yn(),a=v.useMemo(()=>{const i=n.toLowerCase();return i?e.filter(l=>l.id.toLowerCase().includes(i)||(l.workflowId??l.agentId??"").toLowerCase().includes(i)):e},[e,n]);return t?o.jsx(ol,{columns:NXe}):o.jsxs(ve,{columns:NXe,variant:"striped",className:"min-w-0",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Target"}),o.jsx(ve.TopCell,{children:"Schedule ID"}),o.jsx(ve.TopCell,{children:"Cron"}),o.jsx(ve.TopCell,{children:"Status"}),o.jsx(ve.TopCell,{children:"Next fire"}),o.jsx(ve.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(ve.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(ve.NoMatch,{message:"No schedules configured"}):null,a.map(i=>o.jsxs(ve.RowLink,{to:r.scheduleLink(i.id),LinkComponent:s,children:[o.jsx(ve.NameCell,{children:i.workflowId??i.agentId}),o.jsx(ve.Cell,{height:"compact",className:"min-w-0",children:o.jsx("span",{className:"text-ui-smd text-neutral3 block truncate font-mono",title:i.id,children:i.id})}),o.jsx(ve.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("code",{className:"text-ui-sm font-mono",children:i.cron}),i.timezone?o.jsx("span",{className:"text-neutral4 text-ui-xs",children:i.timezone}):null]})}),o.jsx(ve.Cell,{height:"compact",children:o.jsx(N7t,{status:i.status})}),o.jsx(ve.Cell,{height:"compact",children:o.jsx("span",{className:"whitespace-nowrap",title:iT(i.nextFireAt),children:$2(i.nextFireAt)})}),o.jsx(ve.Cell,{height:"compact",children:i.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(I7t,{status:i.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:iT(i.lastFireAt),children:i.lastFireAt?$2(i.lastFireAt):""})]}):i.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:iT(i.lastFireAt),children:$2(i.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},i.id))]})}function mds({workflowId:e}={}){const{data:t,isLoading:n,error:r}=Twe(e?{workflowId:e}:{}),[s,a]=v.useState("");return r?o.jsx(qi,{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($f,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(hds,{schedules:t??[],isLoading:n,search:s})})]})}function gds(){const[e]=Ri(),t=e.get("workflowId")??void 0,{error:n}=Twe(t?{workflowId:t}:{});return n&&ys(n)?o.jsx(lr,{children:o.jsx(Hs,{})}):n&&xs(n)?o.jsx(lr,{children:o.jsx(Ms,{resource:"schedules"})}):o.jsx(Ft,{children:o.jsx("div",{className:"h-full",children:o.jsx(mds,{workflowId:t})})})}function vds({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=oke({stepGraph:e}),[a,i]=v.useState(!1),[l,c,u]=ikt(r),[d]=okt(s),{edgeTypes:f,nodeTypes:p,styledEdges:h}=IDt({edges:d,workflowName:n,stepGraph:e});return v.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(akt,{nodes:l,edges:h,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:p,onNodesChange:u,children:[o.jsx(GEe,{position:"bottom-left"}),o.jsx(ckt,{variant:sy.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:o.jsx(Xt,{})})})}function yds(){const{stepDetail:e,closeStepDetail:t}=WH();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(f9,{className:"h-4 w-4",style:{color:ju.map}}),e.type==="nested-graph"&&o.jsx(Xu,{className:"h-4 w-4",style:{color:ju.workflow}}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx(ye,{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(ye,{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(bs,{className:"text-neutral3 h-4 w-4"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(R2,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(ike,{children:o.jsx(vds,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function bds(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function xds(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 wds({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(ye,{as:"p",variant:"ui-md",className:"text-neutral6 flex items-center gap-2 font-semibold",children:[o.jsx(qe,{children:o.jsx(BV,{})}),"Step suspended"]}),o.jsx(un,{variant:"warning",children:"Needs input"})]}),e.map((s,a)=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const l=i?.resumeSchema?fm(um(wx(i.resumeSchema))):hp(ur(),NT());return o.jsx(Sds,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function Sds({step:e,stepSchema:t,description:n,isStreaming:r,onResume:s}){const[a,i]=v.useState(!1);return o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(ye,{as:"p",variant:"ui-md",className:"text-neutral6 truncate font-medium",children:e.stepId}),n&&o.jsx(ye,{as:"p",variant:"ui-sm",className:"text-neutral3",children:n})]}),e.suspendPayload&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs(ye,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(qe,{children:o.jsx(EZt,{})}),"The step is asking"]}),o.jsxs(Tf,{open:a,onOpenChange:i,children:[o.jsxs($d,{className:"border-border1 bg-surface3 flex w-full items-center justify-between gap-2 rounded-lg border px-3 py-2.5",children:[o.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(qe,{children:o.jsx(pa,{className:X("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(ye,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:xds(e.suspendPayload,e.stepId)})]}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:bds(e.suspendPayload)})]}),o.jsx(Md,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Wr,{data:e.suspendPayload,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs(ye,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(qe,{children:o.jsx(NZt,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(IB,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(Of,{}),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 kds(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=v.useContext(Bl),{runId:a}=Sr(),i=gkt(e,r??""),l=fKn(),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(wds,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const Ods=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"})]}),_ds=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"})]}),Cds=e=>e.includes("."),Eds=e=>e==="input"||e.endsWith(".input"),jds=1;function Tds(e){return`${Number((e/1e3).toPrecision(3))}s`}function Nds(e,t){const n=Object.entries(e).filter(([i])=>!Eds(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,p=Math.max(d/a*100,jds);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:p,durationMs:d,isRunning:c,isNestedEntry:Cds(i)}})}const Ids=({status:e})=>o.jsxs(qe,{children:[e==="success"&&o.jsx(Ods,{className:"text-accent1"}),e==="failed"&&o.jsx(_ds,{className:"text-accent2"}),e==="suspended"&&o.jsx(BV,{className:"text-accent3"}),e==="waiting"&&o.jsx(Ofe,{className:"text-accent5"}),e==="skipped"&&o.jsx(Ofe,{className:"text-icon3"}),e==="running"&&o.jsx(ia,{className:"text-accent6 animate-spin"})]}),Ads={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function A7t(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const IXe=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},Rds=e=>{const t=e;return SDt({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},Pds=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=Rds(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:X("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(Ids,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ce,{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(IGt,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(hV,{indicators:c,className:"shrink-0"})}),o.jsx(ye,{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:A7t(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 ${Ads[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ce,{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(TGt,{})})}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral3 w-20 justify-self-end text-right tabular-nums",children:Tds(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function $ds(){const{steps:e}=F4(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=sH(),[a,i]=v.useState(()=>Date.now()),[l,c]=v.useState(!1),[u,d]=v.useState(null),f=v.useRef(null);Dwe(f,{enabled:!l});const p=Nds(e,a),h=p.some(m=>m.isRunning);return v.useEffect(()=>{if(!h)return;const m=setInterval(()=>i(Date.now()),100);return()=>clearInterval(m)},[h]),v.useEffect(()=>{if(l||p.length===0)return;const m=f.current;m&&(m.scrollTop=m.scrollHeight)},[l,p.length]),p.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(ye,{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(Na,{className:X("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:p.map((m,g)=>o.jsx(Pds,{row:m,index:g,isSelected:t===m.stepId,isHovered:n===m.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:y=>d({type:"input",stepId:y.stepId,data:IXe(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:IXe(y.step.output)})},`timeline-item-${m.stepId}-${g}`))})]})}),o.jsx(br,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(ykt,{data:u.data,title:`${A7t(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const Mds=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=WH();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(ADt,{workflowId:e,workflow:t,isLoading:n}),o.jsx(kds,{}),o.jsx($ds,{})]})}),r&&o.jsx("div",{className:"border-border1 min-h-0 w-[420px] overflow-hidden border-l",children:o.jsx(yds,{})})]})},AXe=()=>{const{workflowId:e}=Sr(),{data:t,isLoading:n,error:r}=H3(e);return r&&ys(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Hs,{})}):r&&xs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ms,{resource:"workflows"})}):o.jsx(_ke,{children:o.jsx(Mds,{workflowId:e,workflow:t??void 0,isLoading:n})})};function Dds(e,t){if(e==null)return{};var n,r,s=Swt(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 bbe(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 Lds(e){if(Array.isArray(e))return bbe(e)}function Fds(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function zds(e,t){if(e){if(typeof e=="string")return bbe(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)?bbe(e,t):void 0}}function Bds(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
721
+ `);return t!==-1&&t!==e.length-1}else{if(Array.isArray(e))return e.some(t=>pbe(t));if(e&&typeof e=="object")return Object.values(e).some(t=>pbe(t))}return!1}function Zos({children:e}){return o.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e})}function Gos({className:e,children:t}){return o.jsx("div",{className:X("mx-4 flex items-center justify-between gap-2 border-b border-border1 py-3",e),children:t})}function Qos({className:e,children:t}){return o.jsx("h3",{className:X("flex gap-2 text-ui-md text-neutral3 [&>b]:font-normal [&>b]:text-neutral2",e),children:t})}function Yos({className:e,children:t}){return o.jsx("dl",{className:X("grid grid-cols-[auto_1fr] gap-x-4 gap-y-1.5",e),children:t})}function Kos({className:e,children:t}){return o.jsx("dt",{className:X("shrink-0 py-0.5 text-ui-smd text-neutral2",e),children:t})}function Xos({className:e,children:t}){return o.jsx("dd",{className:X("min-w-0 truncate py-0.5 text-ui-smd text-neutral3",e),children:t})}function Jos({className:e,children:t}){return o.jsx("dt",{className:X("col-span-2 py-3 text-ui-sm tracking-widest text-neutral2 uppercase",e),children:t})}const els=Object.assign(Yos,{Key:Kos,Value:Xos,Header:Jos});function tls({children:e}){return o.jsxs("div",{className:"text-ui-sm text-neutral3 flex items-center justify-center gap-2 px-4 py-6",children:[o.jsx(Xt,{size:"sm",variant:"pulse",className:"text-neutral3"})," ",e??"Loading..."]})}function nls({children:e}){return o.jsx("p",{className:"text-ui-sm text-neutral2 px-4 py-6",children:e??"No data found."})}const zi=Object.assign(Bos,{Header:Gos,Heading:Qos,CloseButton:Uos,LoadingData:tls,NoData:nls,Content:Zos,KeyValueList:els,CodeSection:Wos}),ap=zi.KeyValueList;function rls(e){return e instanceof Date?e:new Date(e)}function sls({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:a,collapsed:i,onCollapsedChange:l}){const[c,u]=v.useState(!1),d=i??c,f=l??u,p=rls(e.timestamp),h=e.traceId,m=e.spanId;return o.jsxs(zi,{collapsed:d,children:[o.jsxs(zi.Header,{children:[o.jsxs(zi.Heading,{children:["Log ",o.jsx("b",{children:nr(p,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(Mr,{className:"ml-auto shrink-0",children:[l&&o.jsx(ce,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(Qq,{}):o.jsx(hwe,{})}),o.jsxs(Mr,{spacing:"close",children:[o.jsx(ce,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(Gq,{})}),o.jsx(ce,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(u3,{})})]}),o.jsx(zi.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(zi.Content,{children:[o.jsx("p",{className:"text-ui-md text-neutral4 font-mono wrap-break-word whitespace-pre-wrap",children:e.message}),(h||m)&&o.jsxs("div",{className:X("my-8 grid gap-2","[&>button]:justify-between [&>button]:overflow-hidden"),children:[h&&o.jsxs(Mr,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(ce,{size:"md",className:"min-w-0 flex-1 overflow-hidden",onClick:()=>n?.(h),children:[o.jsx(S7,{}),o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",h]})]}),o.jsx(Pa,{content:h,size:"md",tooltip:"Copy Trace ID to clipboard"})]}),m&&o.jsxs(Mr,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(ce,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!h||!r,onClick:()=>h&&r?.(h,m),children:[o.jsx(S7,{}),o.jsx("span",{children:"Span"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",m]})]}),o.jsx(Pa,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(ap,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(ap.Key,{children:"Entity Type"}),o.jsx(ap.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(ap.Key,{children:"Entity Name"}),o.jsx(ap.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(ap.Key,{children:"Service"}),o.jsx(ap.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(ap.Key,{children:"Environment"}),o.jsx(ap.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(ap.Key,{children:"Source"}),o.jsx(ap.Value,{children:e.source})]}),e.metadata&&Object.keys(e.metadata).length>0&&o.jsx(o.Fragment,{children:Object.entries(e.metadata).map(([g,y])=>o.jsxs(v.Fragment,{children:[o.jsx(ap.Key,{children:g}),o.jsx(ap.Value,{children:String(y)})]},g))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(zi.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function als({error:e,resource:t,errorTitle:n}){if(ys(e))return o.jsx(Hs,{});if(xs(e))return o.jsx(Ms,{resource:t});if(w4(e))return o.jsx(Lr,{iconSlot:o.jsx(k7,{}),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(x4(e,"logs"))return o.jsx(Lr,{iconSlot:o.jsx(k7,{}),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(qi,{title:n,message:r??"Unknown error"})}function ils({listSlot:e,logPanelSlot:t,tracePanelSlot:n,spanPanelSlot:r,logCollapsed:s}){const a=!!t;return o.jsxs("div",{className:X("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:X("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 ols={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 lls({level:e}){const t=ols[e];return o.jsx(To,{height:"compact",children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function cls({entityType:e,className:t}){const n=X("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(Xu,{className:n,"aria-hidden":!0});case"tool":return o.jsx(Ld,{className:n,"aria-hidden":!0});default:return null}}function uls({entityType:e,entityName:t}){const n=e??"";return o.jsxs(To,{height:"compact",className:"flex min-w-0 items-center gap-2",children:[o.jsx(cls,{entityType:n}),t?o.jsx("span",{className:"text-ui-smd min-w-0 truncate",children:t}):"-"]})}function dls({message:e}){return o.jsx(To,{height:"compact",className:"text-ui-smd text-neutral4 min-w-0 truncate font-mono",children:e})}function fls({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(To,{height:"compact",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(oEe,{children:t})}const Gl=Object.assign(N4,{Top:yZ,TopCell:aC,TopCellWithTooltip:bZ,TopCellSmart:$$t,RowWrapper:fEe,RowButton:I4,RowLink:M$t,Spacer:dEe,NoMatch:vZ,DateCell:lEe,TimeCell:cEe,LevelCell:lls,EntityCell:uls,MessageCell:dls,DataCell:fls,NextPageLoading:gZ}),wXe="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",pls=36,hls=8;function mls({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=v.useRef(null),u=X9t({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>pls,overscan:hls}),d=v.useRef(t);if(v.useEffect(()=>{d.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),d.current=t},[t]),t)return o.jsx(ol,{columns:wXe});const f=u.getVirtualItems(),p=u.getTotalSize(),h=f[0]?.start??0,m=f.length>0?Math.max(0,p-(f[f.length-1]?.end??0)):0;return o.jsxs(Gl,{columns:wXe,variant:"striped",scrollRef:c,className:"min-w-0",children:[o.jsxs(Gl.Top,{children:[o.jsx(Gl.TopCell,{children:"Date"}),o.jsx(Gl.TopCell,{children:"Time"}),o.jsx(Gl.TopCell,{children:"Level"}),o.jsx(Gl.TopCell,{children:"Entity"}),o.jsx(Gl.TopCell,{children:"Message"}),o.jsx(Gl.TopCell,{children:"Data"})]}),e.length===0?o.jsx(Gl.NoMatch,{message:"No logs match your search"}):o.jsxs(o.Fragment,{children:[o.jsx(Gl.Spacer,{height:h}),f.map(g=>{const y=e[g.index];if(!y)return null;const b=a.get(y);if(!b)return null;const x=b===i;return o.jsxs(Gl.RowButton,{ref:u.measureElement,"data-index":g.index,onClick:()=>l(y),featured:x,variant:y.level==="error"||y.level==="fatal"?"error":"default",children:[o.jsx(Gl.DateCell,{timestamp:y.timestamp}),o.jsx(Gl.TimeCell,{timestamp:y.timestamp}),o.jsx(Gl.LevelCell,{level:y.level}),o.jsx(Gl.EntityCell,{entityType:y.entityType,entityName:y.entityName}),o.jsx(Gl.MessageCell,{message:y.message}),o.jsx(Gl.DataCell,{data:y.data})]},b)}),o.jsx(Gl.Spacer,{height:m})]}),o.jsx(Gl.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function gls({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=>vls(f,a));return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(QNe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(ZNe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function vls(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 yls={"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"},Oae="MMM d, yyyy HH:mm",_ae="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function bls({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${yls[e]}`,description:_ae}:t&&n?{title:`No logs between ${nr(t,Oae)} and ${nr(n,Oae)}`,description:_ae}:t?{title:`No logs since ${nr(t,Oae)}`,description:_ae}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const xls=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=bls({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(k7,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(ce,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",children:["Logging Documentation ",o.jsx(mwe,{})]})})})},wls=20,Sls=1e4;function kls(e,t,n){if(e?.pagination?.hasMore)return n+1}function Ols(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 _ls(e){return x4(e.state.error,"logs")||w4(e.state.error)?!1:Sls}const Cls=({filters:e}={})=>{const t=We(),{inView:n,setRef:r}=W_(),s=M1({queryKey:["logs",e],queryFn:({pageParam:p})=>t.listLogsVNext({pagination:{page:p,perPage:wls},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:kls,select:Ols,retry:!1,refetchInterval:_ls}),{hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,data:c,isLoading:u,isError:d,error:f}=s;return v.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}},Dz={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},b7t=[{label:"Agent",entityType:Dz.AGENT},{label:"Workflow",entityType:Dz.WORKFLOW},{label:"Scorer",entityType:Dz.SCORER},{label:"Ingest",entityType:Dz.INGEST}],Els=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],Fx="rootEntityType",Gb="datePreset",Qb="dateFrom",Yb="dateTo",jls=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),Nl={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"},EL=Object.keys(Nl),vIe=new Set(["tags"]),yIe="mastra:logs:saved-filters";function Tls(e,t=yIe){const n=Pls(e),r=e.get(Gb);r&&n.set(Gb,r);const s=e.get(Qb);s&&n.set(Qb,s);const a=e.get(Yb);a&&n.set(Yb,a);try{localStorage.setItem(t,n.toString())}catch{}}function Nls(e=yIe){try{localStorage.removeItem(e)}catch{}}function SXe(e=yIe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function Ils(e){if(e.has(Gb)||e.has(Qb)||e.has(Yb)||e.has(Fx))return!0;for(const t of EL)if(e.has(Nl[t]))return!0;return!1}function Als({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:b7t.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:Els.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 Rls(e){const t=[],n=new Map([[Fx,"rootEntityType"]]);for(const s of EL)n.set(Nl[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),vIe.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 Pls(e){const t=new URLSearchParams,n=e.get(Fx);n&&t.set(Fx,n);for(const r of EL){const s=Nl[r];if(vIe.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 $ls(e,t){e.delete(Fx);for(const n of EL)e.delete(Nl[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(Fx,n.value);continue}const r=Nl[n.fieldId];if(r){if(vIe.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 Mls({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 Dls(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 Lls="Filters setting for Logs saved",Fls="Filters setting for Logs cleared up";function zls(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=v.useState(()=>SXe(r)!==null),c=v.useCallback(()=>{Tls(e,r),l(!0);const f=s?.saved??Lls;f!==!1&&Le.success(f)},[e,r,s?.saved]),u=v.useCallback(()=>{Nls(r),l(!1);const f=s?.cleared??Fls;f!==!1&&Le.success(f)},[r,s?.cleared]),d=v.useRef(!1);return v.useEffect(()=>{if(a||d.current||(d.current=!0,Ils(e)))return;const f=SXe(r);f&&t(p=>{const h=new URLSearchParams(p);for(const[m,g]of f)h.append(m,g);return h},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function Bls(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 Uls(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,Bls(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function Vls(e,t,n,r){const s=v.useMemo(()=>Uls(e),[e]),a=v.useMemo(()=>{const h=new Map;for(const[m,g]of e.entries()){const y=s.get(g);y&&h.set(y,{log:g,idx:m})}return h},[e,s]),l=(t?a.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=v.useCallback(h=>s.get(h),[s]),d=v.useCallback(h=>{const m=s.get(h);if(m){if(t===m){n({logId:null});return}n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}},[s,t,r,n]),f=l>0?()=>{const h=e[l-1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0,p=l>=0&&l<e.length-1?()=>{const h=e[l+1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0;return{logIdMap:s,getLogId:u,featuredLog:c,handleLogClick:d,handlePreviousLog:f,handleNextLog:p}}const hbe="logId",mbe="traceId",gbe="spanId",oP=1440*60*1e3,qls={"last-24h":oP,"last-3d":3*oP,"last-7d":7*oP,"last-14d":14*oP,"last-30d":30*oP};function Lz(e){e.delete(hbe),e.delete(mbe),e.delete(gbe)}function Hls(e,t,n){const{onRemoveAll:r}={},s=v.useMemo(()=>{const _=e.get(Gb);return _&&jls.has(_)?_:"last-24h"},[e]),a=e.get(Qb),i=e.get(Yb),l=v.useMemo(()=>{if(s==="custom"){if(!a)return;const C=new Date(a);return Number.isNaN(C.getTime())?void 0:C}if(s==="all")return;const _=qls[s];return _?new Date(Date.now()-_):void 0},[s,a]),c=v.useMemo(()=>{if(s!=="custom"||!i)return;const _=new Date(i);return Number.isNaN(_.getTime())?void 0:_},[s,i]),u=v.useRef(s);u.current=s;const d=e.get(hbe),f=e.get(mbe),p=e.get(gbe),h=v.useMemo(()=>b7t.find(_=>_.entityType===e.get(Fx)),[e]),m=v.useMemo(()=>Rls(e),[e]),g=v.useCallback(_=>{t(C=>{const E=new URLSearchParams(C);for(const[j,N]of Object.entries(_)){const I=j==="logId"?hbe:j==="traceId"?mbe:gbe;N?E.set(I,N):E.delete(I)}return E},{replace:!0})},[t]),y=v.useCallback(_=>{t(C=>{const E=new URLSearchParams(C);return $ls(E,_),Lz(E),E},{replace:!0})},[t]),b=y,x=v.useCallback((_,C)=>{if(u.current!=="custom")return;const E=C==="from"?Qb:Yb;t(j=>{const N=new URLSearchParams(j);return _?N.set(E,_.toISOString()):N.delete(E),Lz(N),N},{replace:!0})},[t]),S=v.useCallback(_=>{u.current=_,t(C=>{const E=new URLSearchParams(C);return _==="last-24h"?(E.delete(Gb),E.delete(Qb),E.delete(Yb)):_==="custom"?E.set(Gb,"custom"):(E.set(Gb,_),E.delete(Qb),E.delete(Yb)),Lz(E),E},{replace:!0})},[t]),k=v.useCallback(()=>{t(_=>{const C=new URLSearchParams(_);C.delete(Fx);for(const E of EL)C.delete(Nl[E]);return C.delete(Gb),C.delete(Qb),C.delete(Yb),Lz(C),C},{replace:!0}),r?.()},[t,r]);return v.useMemo(()=>({searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,featuredLogId:d,featuredTraceId:f,featuredSpanId:p,selectedEntityOption:h,filterTokens:m,handleFeaturedChange:g,handleFilterTokensChange:b,handleDateChange:x,handleDatePresetChange:S,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,p,h,m,g,b,x,S,k,y])}const kb=zi.KeyValueList;function Wls({spanId:e,span:t,isLoading:n,onClose:r}){const s=t?.startedAt&&t?.endedAt?new Date(t.endedAt).getTime()-new Date(t.startedAt).getTime():null;return o.jsxs(zi,{children:[o.jsxs(zi.Header,{children:[o.jsxs(zi.Heading,{children:["Span ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(zi.CloseButton,{onClick:r})]}),n?o.jsx(zi.LoadingData,{children:"Loading span..."}):t?o.jsxs(zi.Content,{children:[o.jsxs(kb,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(kb.Key,{children:"Type"}),o.jsx(kb.Value,{children:t.spanType})]}),t.startedAt&&o.jsxs(o.Fragment,{children:[o.jsx(kb.Key,{children:"Started"}),o.jsx(kb.Value,{children:nr(new Date(t.startedAt),"MMM dd, HH:mm:ss.SSS")})]}),t.endedAt&&o.jsxs(o.Fragment,{children:[o.jsx(kb.Key,{children:"Ended"}),o.jsx(kb.Value,{children:nr(new Date(t.endedAt),"MMM dd, HH:mm:ss.SSS")})]}),s!=null&&o.jsxs(o.Fragment,{children:[o.jsx(kb.Key,{children:"Duration"}),o.jsx(kb.Value,{children:s<1e3?`${s}ms`:`${(s/1e3).toFixed(2)}s`})]})]}),o.jsx("br",{}),o.jsx(zi.CodeSection,{title:"Input",icon:o.jsx(che,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(zi.CodeSection,{title:"Output",icon:o.jsx(uhe,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(zi.CodeSection,{title:"Metadata",icon:o.jsx(vw,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(zi.CodeSection,{title:"Attributes",icon:o.jsx(vw,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(zi.NoData,{children:"Span not found."})]})}function Zls({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:a}){const i=v.useMemo(()=>JNe(t??[]),[t]),[l,c]=v.useState([]);v.useEffect(()=>{i.length>0&&c(XNe(i))},[i]);const u=d=>{s?.(a===d?void 0:d)};return o.jsxs(zi,{children:[o.jsxs(zi.Header,{children:[o.jsxs(zi.Heading,{children:["Trace ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(zi.CloseButton,{onClick:r})]}),n?o.jsx(zi.LoadingData,{children:"Loading trace..."}):i.length===0?o.jsx(zi.NoData,{children:"No spans found for this trace."}):o.jsx(zi.Content,{children:o.jsx(Q9t,{hierarchicalSpans:i,onSpanClick:u,selectedSpanId:a??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}function Gls(){const[e,t]=Ri(),n=Hls(e,t),r=zls(e,t),[s,a]=v.useState(),[i,l]=v.useState(!1),{data:c=[],isPending:u}=iIe(),{data:d=[],isPending:f}=rIe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:p=[],isPending:h}=sIe(),{data:m=[],isPending:g}=aIe(),y=v.useMemo(()=>Als({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:p,loading:{tags:u,entityNames:f,serviceNames:g,environments:h}}),[c,d,m,p,u,f,g,h]),b=v.useMemo(()=>Mls({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:x=[],isLoading:S,error:k,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:E}=Cls({filters:b}),{logIdMap:j,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:R}=Vls(x,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:L,isLoading:D}=oIe(n.featuredTraceId??null),{data:B,isLoading:H}=CL(n.featuredTraceId??"",n.featuredSpanId??""),F=v.useCallback(()=>n.applyFilterTokens(Dls(y,n.filterTokens)),[y,n]),z=v.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),q=v.useCallback(K=>n.handleFeaturedChange({traceId:K,spanId:null}),[n]),M=v.useCallback((K,te)=>n.handleFeaturedChange({traceId:K,spanId:te}),[n]),G=v.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),V=v.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),$=v.useCallback(K=>n.handleFeaturedChange({spanId:K??null}),[n]),U=o.jsxs(Ft.TopArea,{children:[o.jsx(Ft.Row,{children:o.jsxs(Ft.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(G3,{preset:n.datePreset,onPresetChange:n.handleDatePresetChange,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,onDateChange:n.handleDateChange,disabled:S,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),o.jsx(YNe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:S,onStartTextFilter:a})]})}),o.jsx(gls,{isLoading:S,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:F,onRemoveAll:n.handleRemoveAll,onSave:r.handleSave,onRemoveSaved:r.hasSavedFilters?r.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(k)return o.jsxs(Ft,{width:"wide",height:"full",children:[U,o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsx(als,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const Z=!!n.selectedEntityOption||n.filterTokens.length>0;return x.length===0&&!S&&!Z?o.jsxs(Ft,{width:"wide",height:"full",children:[U,o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsx(xls,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Ft,{width:"wide",height:"full",children:[U,o.jsx(ils,{logCollapsed:i,listSlot:o.jsx(mls,{logs:x,isLoading:S,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:E,logIdMap:j,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(sls,{log:N,onClose:z,onTraceClick:q,onSpanClick:M,onPrevious:A,onNext:R,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(Zls,{traceId:n.featuredTraceId,spans:L?.spans,isLoading:D,onClose:G,onSpanSelect:$,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(Wls,{spanId:n.featuredSpanId,span:B?.span,isLoading:H,onClose:V}):null})]})}function Qls({server:e}){const{paths:t,Link:n}=yn(),s=We().options.baseUrl,a=s?`${s}/api/mcp/${e.id}/sse`:"",{data:i}=Ezt(e),l=Object.values(i||{}),c=l.length,u=l.filter(p=>p.toolType==="agent").length,d=l.filter(p=>p.toolType==="workflow").length,f=ky(e.name,50);return o.jsxs(ve.RowLink,{to:t.mcpServerLink(e.id),LinkComponent:n,children:[o.jsx(ve.NameCell,{children:f}),o.jsx(ve.DescriptionCell,{children:a}),o.jsx(ve.TextCell,{className:"text-center",children:u||""}),o.jsx(ve.TextCell,{className:"text-center",children:c||""}),o.jsx(ve.TextCell,{className:"text-center",children:d||""})]})}function Yls({mcpServers:e,isLoading:t,search:n=""}){const r=v.useMemo(()=>{const s=n.toLowerCase();return e.filter(a=>a.name?.toLowerCase().includes(s)||a.id?.toLowerCase().includes(s))},[e,n]);return t?o.jsx(ol,{columns:"auto 1fr auto auto auto"}):o.jsxs(ve,{columns:"auto 1fr auto auto auto",variant:"striped",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Name"}),o.jsx(ve.TopCell,{children:"URL"}),o.jsx(ve.TopCellSmart,{long:"Agents",short:o.jsx(Uo,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(ve.TopCellSmart,{long:"Tools",short:o.jsx(Ld,{}),tooltip:"Tools",className:"text-center"}),o.jsx(ve.TopCellSmart,{long:"Workflows",short:o.jsx(Xu,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(ve.NoMatch,{message:"No MCP Servers match your search"}):null,r.map(s=>o.jsx(Qls,{server:s},s.id))]})}const Kls=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(Nf,{}),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(ce,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(Sa,{})]})})}),Xls=()=>{const{data:e=[],isLoading:t,error:n}=IG(),[r,s]=v.useState("");return n&&ys(n)?o.jsx(lr,{children:o.jsx(Hs,{})}):n&&xs(n)?o.jsx(lr,{children:o.jsx(Ms,{resource:"MCP servers"})}):n?o.jsx(lr,{children:o.jsx(qi,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(lr,{children:o.jsx(Kls,{})}):o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx($f,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(Yls,{mcpServers:e,isLoading:t,search:r})]})},Jls=(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 ecs({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=yn(),i=v.useMemo(()=>Jls(e,t),[e,t]),l=v.useMemo(()=>i.filter(c=>c.id.toLowerCase().includes(r.toLowerCase())),[i,r]);return n?o.jsx(ol,{columns:"auto 1fr auto"}):o.jsxs(ve,{columns:"auto 1fr auto",variant:"striped",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Name"}),o.jsx(ve.TopCell,{children:"Description"}),o.jsx(ve.TopCellSmart,{long:"Agents",short:o.jsx(Uo,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(ve.NoMatch,{message:"No Tools match your search"}):null,l.map(c=>{const u=ky(c.id,50),d=ky(c.description??"",200),f=c.agents.length;return o.jsxs(ve.RowLink,{to:s.toolLink(c.id),LinkComponent:a,children:[o.jsx(ve.NameCell,{children:u}),o.jsx(ve.DescriptionCell,{children:d}),o.jsx(ve.TextCell,{className:"text-center",children:f||""})]},c.id)})]})}const tcs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(Nf,{}),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(ce,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(Sa,{})]})})}),ncs=()=>{const e=We();return Mn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new E_;Object.entries(r??{}).forEach(([a,i])=>{s.set(a,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(a){throw Le.error("Error executing dev tool"),console.error("Error executing dev tool:",a),a}}})},rcs=({toolId:e})=>{const{canExecute:t}=ul(),n=t("tools"),{data:r={}}=Em(),s=v.useMemo(()=>{for(const g of Object.values(r))if(g.tools){const y=Object.values(g.tools).find(b=>b.id===e);if(y)return y}return null},[r,e]),{data:a,isLoading:i,error:l}=VEr(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=ncs(),{requestContext:p}=_s();v.useEffect(()=>{if(l){const g=l instanceof Error?l.message:"Failed to load tool";Le.error(`Error loading tool: ${g}`)}},[l]);const h=async(g,y)=>{if(!c)return;const b={...p??{},...y??{}};return u({toolId:c.id,input:g,requestContext:b})},m=c?.inputSchema?fm(um(wx(c?.inputSchema))):ks({});return i?o.jsxs("div",{className:"p-6",children:[o.jsx(xt,{className:"mb-4 h-8 w-48"}),o.jsx(xt,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(ONe,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:h,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ye,{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(ye,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function scs({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}){const{data:c={},isLoading:u,isError:d,error:f}=RI(),{data:p={},isLoading:h,isError:m,error:g}=Em(),{navigate:y,paths:b}=yn();v.useEffect(()=>{if(d){const _=f instanceof Error?f.message:"Failed to load tools";Le.error(`Error loading tools: ${_}`)}},[d,f]),v.useEffect(()=>{if(m){const _=g instanceof Error?g.message:"Failed to load agents";Le.error(`Error loading agents: ${_}`)}},[m,g]);const x=new Map;Object.values(p).forEach(_=>{_.tools&&Object.values(_.tools).forEach(C=>{x.has(C.id)||x.set(C.id,C)})}),Object.values(c).forEach(_=>{x.has(_.id)||x.set(_.id,_)});const S=Array.from(x.values()).map(_=>({label:_.id,value:_.id})),k=_=>{t?t(_):_&&_!==e&&y(b.toolLink(_))};return o.jsx(ac,{options:S,value:e,onValueChange:k,placeholder:u||h?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||u||h||d||m,variant:l})}const acs=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=v.useState({sseUrl:"",httpStreamUrl:""});if(v.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(Oy,{children:o.jsx(ye,{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(Oy,{isDivided:!0,children:[o.jsxs("div",{className:"mx-auto w-full max-w-2xl px-8 py-12",children:[o.jsx(ye,{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(un,{icon:o.jsx(W9t,{className:"text-neutral6"}),className:"text-neutral4! rounded-r-sm",children:"Version"}),o.jsx(un,{className:"text-neutral4! rounded-l-sm",children:t.version_detail.version})]}),o.jsx(ye,{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(un,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"HTTP"}),children:"Regular HTTP Endpoint"}),o.jsx(ye,{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(ye,{className:"bg-surface4 rounded-lg px-2 py-1",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx(Pa,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(un,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"SSE"}),children:"Server-Sent Events"}),o.jsx(ye,{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(ye,{className:"bg-surface4 rounded-lg px-2 py-1",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx(Pa,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(un,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"CLI"}),children:"Command Line"}),o.jsx(ye,{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(ye,{className:"bg-surface4 rounded-lg px-2 py-1",children:a}),o.jsx("div",{className:"pt-1",children:o.jsx(Pa,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"border-border1 h-full overflow-y-scroll border-l",children:o.jsx(ics,{server:t})})]})},ics=({server:e})=>{const{data:t={},isLoading:n}=Ezt(e);if(n)return null;const r=Object.keys(t);return o.jsxs("div",{className:"overflow-y-scroll p-5",children:[o.jsxs("div",{className:"text-neutral6 flex items-center gap-2",children:[o.jsx(qe,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(hC,{})}),o.jsx(ye,{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(lcs,{tool:a,serverId:e.id},s)})})]})};function ocs(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 lcs=({tool:e,serverId:t})=>{const n=v.useRef(null),{Link:r,paths:s}=yn(),a=Jzt[e.toolType||"tool"],i=ocs(e._meta);return o.jsxs(Df,{onClick:()=>n.current?.click(),children:[o.jsx(Z2t,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Ff,{children:[o.jsx(Lf,{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(un,{className:"py-0 text-[10px]",children:"App"})]})}),o.jsx(th,{children:e.description})]})]})},ccs=()=>{const{serverId:e}=Sr(),{data:t=[],isLoading:n}=IG(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(acs,{isLoading:n,server:r})})};function ucs(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 dcs=({toolId:e,serverId:t})=>{const{canExecute:n}=ul(),r=n("tools"),s=We(),{data:a,isLoading:i,error:l}=vNe(t,e),{mutateAsync:c,isPending:u,data:d}=MGr(t,e),f=a?ucs(a._meta):void 0,{data:p}=yt({queryKey:["mcp-app-resource",t,f],queryFn:async()=>f?(await s.readMcpServerResource(t,f)).contents[0]?.text??null:null,enabled:!!f}),h=v.useCallback(async(y,b)=>await c(b),[c]);v.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";Le.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(xt,{className:"mb-4 h-8 w-48"}),o.jsx(xt,{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(ye,{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(ye,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let g;try{g=fm(um(a.inputSchema))}catch(y){console.error("Error processing input schema:",y),Le.error("Failed to process tool input schema."),g=ks({})}return o.jsxs("div",{className:"flex flex-col gap-4",children:[p&&o.jsx("div",{className:"border-border1 border-b p-4",children:o.jsx(Czt,{html:p,toolName:a.name??a.id,onToolCall:h})}),o.jsx(ONe,{executionResult:d,isExecutingTool:u,zodInputSchema:g,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},fcs=()=>{const{serverId:e,toolId:t}=Sr(),{data:n,isLoading:r}=vNe(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(dcs,{toolId:t,serverId:e})})},x7t=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],RN="rootEntityType",PN={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"},nQ=Object.keys(PN),bIe="mastra:metrics:saved-filters";function pcs(e){const t=ycs(e);try{localStorage.setItem(bIe,t.toString())}catch{}}function hcs(){try{localStorage.removeItem(bIe)}catch{}}function w7t(){try{const e=localStorage.getItem(bIe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function mcs(e){if(e.has(RN))return!0;for(const t of nQ)if(e.has(PN[t]))return!0;return!1}function gcs({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:x7t.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 vcs(e){const t=[],n=new Map([[RN,"rootEntityType"]]);for(const s of nQ)n.set(PN[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 ycs(e){const t=new URLSearchParams,n=e.getAll(RN);for(const r of n)t.append(RN,r);for(const r of nQ){const s=PN[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function bcs(e,t){e.delete(RN);for(const n of nQ)e.delete(PN[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?RN:PN[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 xcs="Any";function kXe(e){const t=e.trim();return t===""||t===xcs}const wcs=new Set(x7t.map(e=>e.entityType));function OXe(e){const t=e.trim();return wcs.has(t)?t:void 0}function Scs(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=>!kXe(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?OXe(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(kXe(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=OXe(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const S7t=[{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"}],kcs=new Set(S7t.map(e=>e.value));function Ocs(e){return typeof e=="string"&&(kcs.has(e)||e==="custom")}const k7t=v.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function rQ(){return v.useContext(k7t)}function _cs(e,t){return e!=="custom"?S7t.find(n=>n.value===e)?.label??e:t?.from?t.to?`${nr(t.from,"MMM d, yyyy")} – ${nr(t.to,"MMM d, yyyy")}`:nr(t.from,"MMM d, yyyy"):"Custom range"}function Ccs({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:a,onCustomRangeChange:i,tracesBasePath:l,logsBasePath:c}){const u=v.useMemo(()=>JSON.stringify(n),[n]),d=v.useMemo(()=>n,[u]),f=v.useMemo(()=>Scs(d),[d]),p=v.useMemo(()=>JSON.stringify(f),[f]),h=_cs(t,a),m=v.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:a,setCustomRange:i??(()=>{}),dateRangeLabel:h,filterTokens:d,setFilterTokens:s,dimensionalFilter:f,dimensionalFilterKey:p,tracesBasePath:l,logsBasePath:c}),[t,r,a,i,h,d,s,f,p,l,c]);return o.jsx(k7t.Provider,{value:m,children:e})}const Ecs=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function jcs(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 Tcs(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 Ncs(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=rQ(),s=v.useRef(e);s.current=e;const a=v.useRef(n);return a.current=n,o.jsx(G3,{preset:jcs(e),onPresetChange:i=>{const l=Tcs(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:Ecs})}const vbe=1440*60*1e3,Ics={"24h":vbe,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function Acs(e,t,n){if(e!=="custom"){const r=Ics[e]??vbe;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-vbe),end:t?.to??new Date(n)}}function Im(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=rQ(),s=v.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=v.useMemo(()=>Acs(e,t,i),[e,t,i]),c=v.useMemo(()=>({timestamp:l,...n}),[l,r]),u=v.useMemo(()=>`${a}|${r}`,[a,r]);return{datePreset:e,customRange:t,timestamp:l,filters:c,dimensionalFilter:n,filterKey:u}}function O7t(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}const Rcs=new Set(["ObservabilityStorageClickhouseVNext","ObservabilityStorageDuckDB","ObservabilityInMemory","ObservabilitySpanner","ObservabilityStoragePostgresVNext"]),Pcs=()=>{const{data:e,isLoading:t}=R4(),n=e?.observabilityStorageType;return{supportsMetrics:e?.observabilityStorageCapabilities?.metrics??(n?Rcs.has(n):!1),isInMemory:n==="ObservabilityInMemory",isLoading:t}};function jL({href:e,LinkComponent:t="a"}){return o.jsx(ce,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(xEn,{})})}function $cs({href:e,LinkComponent:t="a"}){return o.jsx(ce,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(njn,{})})}const Mcs=[{dataKey:"p50",label:"p50",color:Fp.blue,aggregate:e=>({value:e.length>0?`${Math.round(e.reduce((t,n)=>t+n.p50,0)/e.length)}`:"0",suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:Fp.yellow,aggregate:e=>({value:e.length>0?`${Math.round(e.reduce((t,n)=>t+n.p95,0)/e.length)}`:"0",suffix:"avg ms"})}];function Dcs(e){return e==="agents"||e==="workflows"||e==="tools"}function Cae({data:e,onPointClick:t}){return e.length===0?o.jsx(Ht.NoData,{message:"No latency data yet"}):o.jsx(IV,{data:e,series:Mcs,onPointClick:t?n=>{const r=n;typeof r?.tsMs=="number"&&Number.isFinite(r.tsMs)&&t(r)}:void 0})}function Lcs({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]=v.useState("agents"),p=c[d]?d:u,h=typeof s=="function"?s(p):s,m=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),g=e?Object.values(e).filter(Array.isArray).flat().map(b=>b.p50).filter(b=>typeof b=="number"):[],y=g.length>0?`${Math.round(g.reduce((b,x)=>b+x,0)/g.length)}ms`:"—";return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(Ht.Summary,{value:y,label:"Avg p50"}),h?o.jsx(Ht.Actions,{children:h}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load latency data"}):o.jsx(Ht.Content,{children:m?o.jsxs(Dc,{value:p,onValueChange:b=>{Dcs(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(Mc,{children:[o.jsx(Rr,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(Rr,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(Rr,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(Xr,{value:"agents",children:o.jsx(Cae,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(Xr,{value:"workflows",children:o.jsx(Cae,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(Xr,{value:"tools",children:o.jsx(Cae,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Ht.NoData,{message:"No latency data yet"})})]})}function Fcs(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 zcs(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 _7t(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=Fcs(s);l&&e.set(t,l)}function Po(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function C7t(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function _Xe({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/observability"}){const a=new URLSearchParams;a.set(kw,"branches"),_7t(a,Ow,_w,Cw,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Dx,i),r.status&&a.set(Lx,r.status),Po(a,Tl.entityName,r.entityName??n.entityName),Po(a,Tl.threadId,r.threadId??n.threadId),Po(a,Tl.resourceId,r.resourceId??n.resourceId),Po(a,Tl.entityId,n.entityId),Po(a,Tl.runId,n.runId),Po(a,Tl.sessionId,n.sessionId),Po(a,Tl.requestId,n.requestId),Po(a,Tl.userId,n.userId),Po(a,Tl.organizationId,n.organizationId),Po(a,Tl.experimentId,n.experimentId),Po(a,Tl.serviceName,n.serviceName),Po(a,Tl.environment,n.environment),C7t(a,Tl.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function Bcs({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;_7t(a,Gb,Qb,Yb,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Fx,i),Po(a,Nl.entityName,r.entityName??n.entityName),Po(a,Nl.threadId,r.threadId??n.threadId),Po(a,Nl.resourceId,r.resourceId??n.resourceId),Po(a,Nl.runId,n.runId),Po(a,Nl.sessionId,n.sessionId),Po(a,Nl.requestId,n.requestId),Po(a,Nl.userId,n.userId),Po(a,Nl.organizationId,n.organizationId),Po(a,Nl.experimentId,n.experimentId),Po(a,Nl.serviceName,n.serviceName),Po(a,Nl.environment,n.environment),C7t(a,Nl.tags,n.tags),r.status==="error"&&a.append(Nl.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function KI(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=rQ(),a=v.useCallback((c={})=>_Xe({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=v.useCallback((c={})=>Bcs({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=v.useCallback((c,u,d)=>{const f=zcs(u,d);return _Xe({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const E7t="1h";async function Eae(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:E7t,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 Ucs(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([Eae(e,"mastra_agent_duration_ms",t),Eae(e,"mastra_workflow_duration_ms",t),Eae(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:E7t}}})}const CXe={agents:au.AGENT,workflows:au.WORKFLOW_RUN,tools:au.TOOL};function Vcs(){const{data:e,isLoading:t,isError:n}=Ucs(),{getTracesHref:r,getBucketTracesHref:s}=KI(),{Link:a}=yn(),i=qs();return o.jsx(Lcs,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:CXe[l]},c.tsMs,"1h"))},actions:l=>o.jsx(jL,{href:r({rootEntityType:CXe[l]}),LinkComponent:a})})}function qcs(e){return e==="threads"||e==="resources"}function jae(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function Hcs({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:a}){const[i,l]=v.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,p=e.data?.reduce((y,b)=>y+b.runs,0)??0,h=t.data?.reduce((y,b)=>y+b.threadCount,0)??0,m=i==="threads"?e:t,g=typeof s=="function"?s(i):s;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&o.jsx(Ht.Summary,{value:p.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&o.jsx(Ht.Summary,{value:h.toLocaleString(),label:"Total threads"}),g?o.jsx(Ht.Actions,{children:g}):null]}),m.isLoading?o.jsx(Ht.Loading,{}):m.isError?o.jsx(Ht.Error,{message:"Failed to load memory data"}):o.jsx(Ht.Content,{children:o.jsxs(Dc,{defaultTab:"threads",value:i,onValueChange:y=>{qcs(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Mc,{children:[o.jsx(Rr,{value:"threads",children:"Threads"}),o.jsx(Rr,{value:"resources",children:"Resources"})]}),o.jsx(Xr,{value:"threads",children:d?o.jsxs(ve,{columns:"auto auto auto auto auto",...dbe,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(ve.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:jae(y.threadId)}),o.jsx(ve.NumberCell,{children:y.resourceId?jae(y.resourceId):"—"}),o.jsx(ve.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(ve.NumberCell,{children:y.tokens>0?Oc(y.tokens):"—"}),o.jsx(ve.NumberCell,{children:y.cost!=null?Cg(y.cost,y.costUnit):"—"})]});return b?o.jsx(ve.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(ve.RowStatic,{children:x},y.key)})]}):o.jsx(Ht.NoData,{message:"No thread activity yet"})}),o.jsx(Xr,{value:"resources",children:f?o.jsxs(ve,{columns:"auto auto auto auto",...dbe,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(ve.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:jae(y.resourceId)}),o.jsx(ve.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(ve.NumberCell,{children:y.tokens>0?Oc(y.tokens):"—"}),o.jsx(ve.NumberCell,{children:y.cost!=null?Cg(y.cost,y.costUnit):"—"})]});return b?o.jsx(ve.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(ve.RowStatic,{children:x},y.key)})]}):o.jsx(Ht.NoData,{message:"No resource activity yet"})})]})})]})}function TL(e,t,n){const r=e.get(t);if(r!==void 0)return r;const s=n();return e.set(t,s),s}const Tae=20;function Wcs(){const e=We(),{filters:t,filterKey:n}=Im();return yt({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:Tae}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:Tae}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:Tae})]),l=new Map,c=d=>TL(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.threadId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.threadId).map(d=>{const f=d.dimensions.threadId,p=l.get(f);return{threadId:f,resourceId:d.dimensions.resourceId??null,runs:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}const Nae=20;function Zcs(){const e=We(),{filters:t,filterKey:n}=Im();return yt({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:Nae}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:Nae}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:Nae})]),l=new Map,c=d=>TL(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.resourceId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.resourceId).map(d=>{const f=d.dimensions.resourceId,p=l.get(f);return{resourceId:f,threadCount:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}function Gcs(){const e=Wcs(),t=Zcs(),{getTracesHref:n}=KI(),{Link:r}=yn();return o.jsx(Hcs,{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 NL({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:a}){const i=t!=null;return o.jsxs(es,{children:[o.jsx(es.Label,{children:e}),o.jsx(es.Value,{className:i?void 0:"invisible",children:i?t:"—"}),a?o.jsx(es.Error,{}):s?o.jsx(es.Loading,{}):i?r!=null?o.jsx(es.Change,{changePct:r,prevValue:n}):o.jsx(es.NoChange,{}):o.jsx(es.NoData,{})]})}function Qcs(){const e=We(),{filters:t,filterKey:n}=Im();return yt({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 Ycs(){const e=We(),{filters:t,filterKey:n}=Im();return yt({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 Kcs(){const e=We(),{filters:t,filterKey:n}=Im();return yt({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 Xcs(){const e=We(),{filters:t,filterKey:n}=Im();return yt({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 Jcs(){const{data:e,isLoading:t,isError:n}=O7t();return o.jsx(NL,{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 eus(){const{data:e,isLoading:t,isError:n}=Kcs();return o.jsx(NL,{label:"Total Model Cost",value:e?.cost!=null?Cg(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?Cg(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function tus(){const{data:e,isLoading:t,isError:n}=Xcs();return o.jsx(NL,{label:"Total Tokens",value:e?.value!=null?Oc(e.value):null,prevValue:e?.previousValue!=null?Oc(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function nus(){const{data:e,isLoading:t,isError:n}=Ycs();return o.jsx(NL,{label:"Total Threads",value:e?.value!=null?Oc(e.value):null,prevValue:e?.previousValue!=null?Oc(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function rus(){const{data:e,isLoading:t,isError:n}=Qcs();return o.jsx(NL,{label:"Total Resources",value:e?.value!=null?Oc(e.value):null,prevValue:e?.previousValue!=null?Oc(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function sus({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=>aus(f,a));return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(QNe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(ZNe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function aus(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 ius({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const i=!!e&&e.length>0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Model Usage & Cost",description:"Token consumption by model."}),i&&(()=>{const l=e.reduce((d,f)=>d+(f.cost??0),0),c=new Set;for(const d of e)d.cost!=null&&d.costUnit&&c.add(d.costUnit);let u;return c.size===0?u=l>0?Cg(l):"—":c.size===1?u=l>0?Cg(l,[...c][0]):"—":u="Mixed",o.jsx(Ht.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(Ht.Actions,{children:s}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load model usage data"}):o.jsx(Ht.Content,{children:i?o.jsxs(ve,{columns:"auto auto auto auto auto auto",...dbe,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{sticky:"start",children:"Model"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(ve.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:l.model}),o.jsx(ve.NumberCell,{children:l.input}),o.jsx(ve.NumberCell,{children:l.output}),o.jsx(ve.NumberCell,{children:l.cacheRead}),o.jsx(ve.NumberCell,{children:l.cacheWrite}),o.jsx(ve.NumberCell,{highlight:!0,children:l.cost!=null?Cg(l.cost,l.costUnit):"—"})]});return c?o.jsx(ve.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(ve.RowStatic,{children:u},l.model)})]}):o.jsx(Ht.NoData,{message:"No model usage data yet"})})]})}function ous(){const e=We(),{filters:t,filterKey:n}=Im();return yt({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=>TL(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",p=c(f);p.input=d.value,u(p,d)}for(const d of s.groups){const f=d.dimensions.model??"unknown",p=c(f);p.output=d.value,u(p,d)}for(const d of a.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheRead=d.value}for(const d of i.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheWrite=d.value}return Array.from(l.entries()).map(([d,f])=>({model:d,input:Oc(f.input),output:Oc(f.output),cacheRead:Oc(f.cacheRead),cacheWrite:Oc(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function lus(){const{data:e,isLoading:t,isError:n}=ous(),{getTracesHref:r}=KI(),{Link:s}=yn();return o.jsx(ius,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:au.AGENT}),actions:o.jsx(jL,{href:r({rootEntityType:au.AGENT}),LinkComponent:s})})}function cus(e){return e==="tokens"||e==="cost"}function uus({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const[i,l]=v.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),p=new Set(f.map(b=>b.costUnit??"usd")),h=p.size<=1,m=h?[...p][0]??"usd":null,g=h?f.reduce((b,x)=>b+(x.cost??0),0):0,y=h&&g>0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&y?o.jsx(Ht.Summary,{value:Cg(g,m),label:"Total cost"}):o.jsx(Ht.Summary,{value:Oc(d),label:"Total tokens"})),u&&s?o.jsx(Ht.Actions,{children:s}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load token usage data"}):o.jsx(Ht.Content,{children:u?o.jsxs(Dc,{defaultTab:"tokens",value:i,onValueChange:b=>{cus(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Mc,{children:[o.jsx(Rr,{value:"tokens",children:"Tokens"}),o.jsx(Rr,{value:"cost",children:"Cost"})]}),o.jsx(Xr,{value:"tokens",children:o.jsx(AN,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:Fp.blueDark},{label:"Output",color:Fp.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:Oc})}),o.jsx(Xr,{value:"cost",children:y?o.jsx(AN,{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:Fp.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>Cg(b,m)}):o.jsx(Ht.NoData,{message:"No cost data yet"})})]}):o.jsx(Ht.NoData,{message:"No token usage data yet"})})]})}function dus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({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=>TL(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 fus(){const{data:e,isLoading:t,isError:n}=dus(),{getTracesHref:r}=KI(),{Link:s}=yn();return o.jsx(uus,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:au.AGENT,entityName:a.name}),actions:o.jsx(jL,{href:r({rootEntityType:au.AGENT}),LinkComponent:s})})}function ybe(e,t=Oc){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const pus=[{dataKey:"input",label:"Input tokens",color:Fp.blue,aggregate:ybe("input")},{dataKey:"output",label:"Output tokens",color:Fp.yellow,aggregate:ybe("output")}];function hus(e){return e==="tokens"||e==="cost"}function mus({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[a,i]=v.useState("tokens"),l=e??[],c=l.map(k=>({...k})),u=l.length>0,d=l.reduce((k,_)=>k+_.total,0),f=l.filter(k=>k.cost!=null&&k.cost>0),p=f.map(k=>({...k})),h=new Set(f.map(k=>k.costUnit).filter(k=>!!k)),m=h.size===1&&f.every(k=>k.costUnit!=null),g=m?[...h][0]??null:null,y=m?f.reduce((k,_)=>k+(_.cost??0),0):0,b=m&&y>0,x=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",S=[{dataKey:"cost",label:"Cost",color:Fp.purple,aggregate:ybe("cost",k=>Cg(k,g))}];return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Token usage over time",description:x}),u&&(a==="cost"&&b?o.jsx(Ht.Summary,{value:Cg(y,g),label:"Total cost"}):o.jsx(Ht.Summary,{value:Oc(d),label:"Total tokens"})),u&&s?o.jsx(Ht.Actions,{children:s}):null]}),n?o.jsx(Ht.Loading,{}):r?o.jsx(Ht.Error,{message:"Failed to load token usage timeline"}):o.jsx(Ht.Content,{children:u?o.jsxs(Dc,{defaultTab:"tokens",value:a,onValueChange:k=>{hus(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(Mc,{children:[o.jsx(Rr,{value:"tokens",children:"Tokens"}),o.jsx(Rr,{value:"cost",children:"Cost"})]}),o.jsx(Xr,{value:"tokens",children:o.jsx(IV,{data:c,series:pus})}),o.jsx(Xr,{value:"cost",children:b?o.jsx(IV,{data:p,series:S}):o.jsx(Ht.NoData,{message:"No cost data yet"})})]}):o.jsx(Ht.NoData,{message:"No token usage data yet"})})]})}function gus(e){return e==="24h"?"1h":"1d"}function vus(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 EXe(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 yus(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function bus(){const e=We(),{datePreset:t,filters:n,filterKey:r}=Im(),s=gus(t);return yt({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 EXe(l,a.series[0],"input"),EXe(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:vus(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:yus(u)}}),interval:s}}})}function xus(){const{data:e,isLoading:t,isError:n}=bus(),{getTracesHref:r}=KI(),{Link:s}=yn();return o.jsx(mus,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(jL,{href:r(),LinkComponent:s})})}function Iae({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(AN,{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:Fp.blueDark},{label:"Errors",color:Fp.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:Oc})}function wus({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:a,LinkComponent:i}){const[l,c]=v.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,g)=>m+g.completed+g.errors,0):0,p=m=>r?g=>r(m,g):void 0,h=m=>s?g=>s(m,g):void 0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(Ht.Summary,{value:Oc(f),label:"Total runs"}),u?o.jsx(Ht.Actions,{children:u}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load trace volume data"}):o.jsx(Ht.Content,{children:d?o.jsxs(Dc,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Mc,{children:[o.jsx(Rr,{value:"agents",children:"Agents"}),o.jsx(Rr,{value:"workflows",children:"Workflows"}),o.jsx(Rr,{value:"tools",children:"Tools"})]}),o.jsx(Xr,{value:"agents",children:e.agentData.length>0?o.jsx(Iae,{data:e.agentData,rowHrefs:p("agents"),errorHrefs:h("agents"),LinkComponent:i}):o.jsx(Ht.NoData,{message:"No agent data yet"})}),o.jsx(Xr,{value:"workflows",children:e.workflowData.length>0?o.jsx(Iae,{data:e.workflowData,rowHrefs:p("workflows"),errorHrefs:h("workflows"),LinkComponent:i}):o.jsx(Ht.NoData,{message:"No workflow data yet"})}),o.jsx(Xr,{value:"tools",children:e.toolData.length>0?o.jsx(Iae,{data:e.toolData,rowHrefs:p("tools"),errorHrefs:h("tools"),LinkComponent:i}):o.jsx(Ht.NoData,{message:"No tool data yet"})})]}):o.jsx(Ht.NoData,{message:"No trace volume data yet"})})]})}async function Aae(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=TL(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 Sus(){const e=We(),{filters:t,filterKey:n}=Im();return yt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([Aae(e,"mastra_agent_duration_ms",t),Aae(e,"mastra_workflow_duration_ms",t),Aae(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const Fz={agents:au.AGENT,workflows:au.WORKFLOW_RUN,tools:au.TOOL};function kus(){const{data:e,isLoading:t,isError:n}=Sus(),{getTracesHref:r,getLogsHref:s}=KI(),{Link:a}=yn();return o.jsx(wus,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:Fz[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:Fz[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(jL,{href:r({rootEntityType:Fz[i]}),LinkComponent:a}),o.jsx($cs,{href:s({rootEntityType:Fz[i],status:"error"}),LinkComponent:a})]})})}const Rae="period",zz="dateFrom",Bz="dateTo";function Ous(){const[e,t]=Ri(),n=e.get(Rae),r=Ocs(n)?n:"24h",s=v.useMemo(()=>{if(r!=="custom")return;const d=h=>{if(!h)return;const m=new Date(h);return Number.isNaN(m.getTime())?void 0:m},f=d(e.get(zz)),p=d(e.get(Bz));if(!(!f&&!p))return{from:f,to:p}},[r,e.toString()]),a=v.useMemo(()=>vcs(e),[e.toString()]),i=v.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d==="24h"?p.delete(Rae):p.set(Rae,d),d!=="custom"&&(p.delete(zz),p.delete(Bz)),p},{replace:!0})},[t]),l=v.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d?.from?p.set(zz,d.from.toISOString()):p.delete(zz),d?.to?p.set(Bz,d.to.toISOString()):p.delete(Bz),p},{replace:!0})},[t]),c=v.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return bcs(p,d),p},{replace:!0})},[t]),u=v.useRef(!1);return v.useEffect(()=>{if(u.current||(u.current=!0,mcs(e)))return;const d=w7t();d&&t(f=>{const p=new URLSearchParams(f);for(const[h,m]of d)p.append(h,m);return p},{replace:!0})},[]),o.jsx(Ccs,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(_us,{})})}function _us(){const[e]=Ri(),{error:t,isLoading:n}=O7t(),{filterTokens:r,setFilterTokens:s}=rQ(),[a,i]=v.useState(),{supportsMetrics:l,isInMemory:c,isLoading:u}=Pcs(),{data:d,isLoading:f}=iIe(),{data:p,isLoading:h}=rIe(),{data:m,isLoading:g}=aIe(),{data:y,isLoading:b}=sIe(),x=v.useMemo(()=>gcs({availableTags:d??[],availableEntityNames:p??[],availableServiceNames:m??[],availableEnvironments:y??[],loading:{tags:f,entityNames:h,serviceNames:g,environments:b}}),[d,p,m,y,f,h,g,b]),[S,k]=v.useState(()=>w7t()!==null),_=v.useCallback(()=>{pcs(e),k(!0),Le.success("Filters setting for Metrics saved")},[e]),C=v.useCallback(()=>{hcs(),k(!1),Le.success("Filters setting for Metrics cleared up")},[]),E=v.useCallback(()=>{s([])},[s]),j=v.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&&ys(t)?o.jsx(lr,{children:o.jsx(Hs,{})}):t&&xs(t)?o.jsx(lr,{children:o.jsx(Ms,{resource:"metrics"})}):t?o.jsx(lr,{children:o.jsx(qi,{title:"Failed to load metrics",message:t.message})}):o.jsxs(Ft,{width:"wide",height:"full",children:[o.jsxs(Ft.TopArea,{children:[o.jsx(Ft.Row,{children:o.jsxs(Ft.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(Ncs,{}),o.jsx(YNe,{fields:x,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(sus,{isLoading:n,filterFields:x,filterTokens:r,onFilterTokensChange:s,onClear:j,onRemoveAll:E,onSave:_,onRemoveSaved:S?C:void 0,autoFocusFilterFieldId:a})]}),u?null:l?o.jsxs("div",{className:"grid content-start gap-8 pb-10",children:[c&&o.jsx(En,{variant:"info",title:"Metrics are not persisted",children:o.jsx(En.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(fbe,{children:[o.jsx(Jcs,{}),o.jsx(eus,{}),o.jsx(tus,{}),o.jsx(nus,{}),o.jsx(rus,{})]}),o.jsxs(fbe,{children:[o.jsx(lus,{}),o.jsx(fus,{}),o.jsx(xus,{}),o.jsx(Gcs,{}),o.jsx(kus,{}),o.jsx(Vcs,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Lr,{iconSlot:o.jsx(Nf,{}),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(ce,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(Sa,{})]})})})]})}function Cus(){const{paths:e}=yn(),{data:t,isLoading:n,error:r}=t8t(),{isCmsAvailable:s}=X1(),[a,i]=v.useState(""),l=t?.promptBlocks??[];return r&&ys(r)?o.jsx(lr,{children:o.jsx(Hs,{})}):r&&xs(r)?o.jsx(lr,{children:o.jsx(Ms,{resource:"prompt blocks"})}):r?o.jsx(lr,{children:o.jsx(qi,{title:"Failed to load prompt blocks",message:r.message})}):l.length===0&&!n?o.jsx(lr,{children:o.jsx(UXr,{})}):o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsxs(Ft.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx($f,{onSearch:i,label:"Filter prompts",placeholder:"Filter by name or description"})}),s&&o.jsxs(ce,{as:ei,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(Zr,{}),"Create Prompt"]})]})}),o.jsx(BXr,{promptBlocks:l,isLoading:n,search:a})]})}function Eus(){return o.jsx(Ft,{width:"narrow",children:o.jsx(Ft.MainArea,{children:o.jsx(xQr,{children:o.jsx(Uye,{})})})})}const jus=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:WHt,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:sit,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Sa,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:dT,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:fit,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:ait,href:"https://mastra.ai/contact?ref=studio",external:!0}];function Tus(){return o.jsx(Ft,{width:"narrow",children:o.jsx(Ft.MainArea,{children:o.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:jus.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(Sa,{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 Nus(){const{data:e={},isLoading:t,error:n}=ih(),[r,s]=v.useState(""),[a,i]=v.useState("all");if(n&&ys(n))return o.jsx(lr,{children:o.jsx(Hs,{})});if(n&&xs(n))return o.jsx(lr,{children:o.jsx(Ms,{resource:"scorers"})});if(n)return o.jsx(lr,{children:o.jsx(qi,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(lr,{children:o.jsx(QYr,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsx(KYr,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(GYr,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}function Ius(){const{scorerId:e}=Sr(),[t,n]=Ri(),r=t.get("scoreId")??void 0,[s,a]=v.useState(r),[i,l]=v.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:c,error:u}=_Yr(e),{data:d={},isLoading:f,error:p}=Em(),{isLoading:h,error:m}=Hy(),{data:g=[],isLoading:y,error:b,isFetchingNextPage:x,hasNextPage:S,setEndOfListElement:k}=OYr({scorerId:e,entityId:i?.value==="all"?void 0:i?.value,entityType:i?.type==="ALL"?void 0:i?.type}),_=v.useMemo(()=>c?.agentIds?.filter(q=>d[q]).map(q=>({value:q,label:d[q].name,type:"AGENT"}))||[],[c?.agentIds,d]),C=v.useMemo(()=>c?.workflowIds?.map(q=>({value:q,label:q,type:"WORKFLOW"}))||[],[c?.workflowIds]),E=v.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},..._,...C],[_,C]),j=t.get("entity")??"all",N=E.find(q=>q.value===j);N&&N.value!==i?.value&&l(N),v.useEffect(()=>{if(u){const q=u instanceof Error?u.message:"Failed to load scorer";Le.error(`Error loading scorer: ${q}`)}},[u]),v.useEffect(()=>{if(p){const q=p instanceof Error?p.message:"Failed to load agents";Le.error(`Error loading agents: ${q}`)}},[p]),v.useEffect(()=>{if(m){const q=m instanceof Error?m.message:"Failed to load workflows";Le.error(`Error loading workflows: ${q}`)}},[m]);const I=q=>{q?.value&&n(M=>{const G=new URLSearchParams(M);return G.set("entity",q.value),G})};v.useEffect(()=>{const q=t.get("scoreId")??void 0;if(q===s)return;if(!q){a(void 0);return}g.find(G=>G.id===q)&&a(q)},[t,g]);const A=v.useCallback(q=>{a(q||void 0),n(M=>{const G=new URLSearchParams(M);return q?G.set("scoreId",q):G.delete("scoreId"),G})},[n]);if(!c)return null;const R=ys(u)||ys(p)||ys(m),L=u&&xs(u),D=!R&&!L&&(u||p||m),B=!y&&g.length===0,H=i?.value!=="all",F=c?.scorer?.source==="stored"?o.jsx($y,{owner:"scorer-detail",children:o.jsxs(ce,{variant:"default",as:ei,to:`/cms/scorers/${e}/edit`,size:"sm",children:[o.jsx(rm,{})," Edit"]})}):null;if(R||L||D||B&&!H){const q=(u instanceof Error?u.message:void 0)??(p instanceof Error?p.message:void 0)??(m instanceof Error?m.message:void 0)??"An unexpected error occurred";return o.jsxs(Ft,{width:"wide",height:"full",children:[F,o.jsx(Ft.MainArea,{isCentered:!0,children:R?o.jsx(Hs,{}):L?o.jsx(Ms,{resource:"scorers"}):D?o.jsx(qi,{title:"Failed to load scorer",message:q}):o.jsx(vYr,{})})]})}return o.jsxs(Ft,{width:"wide",children:[F,o.jsx(Ft.TopArea,{children:o.jsx(yYr,{selectedEntity:i,entityOptions:E,onEntityChange:I,onReset:()=>{n(q=>{const M=new URLSearchParams(q);return M.set("entity","all"),M})},isLoading:y||f||h})}),o.jsx(gYr,{scores:g,isLoading:y,selectedScoreId:s,isFetchingNextPage:x,hasNextPage:S,setEndOfListElement:k,onScoreClick:A,errorMsg:b?.message})]})}function Aus({label:e,description:t,htmlFor:n,className:r,children:s}){return o.jsxs("div",{className:X("flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",r),"data-slot":"settings-row",children:[o.jsxs("div",{children:[n?o.jsx(Dt,{htmlFor:n,className:"text-sm font-medium",children:e}):o.jsx("p",{className:"text-sm font-medium",children:e}),t&&o.jsx("p",{className:"text-neutral3 text-sm",children:t})]}),s]})}const j7t=[{value:"dark",label:"Dark",Icon:_Zt},{value:"light",label:"Light",Icon:DGt},{value:"system",label:"System",Icon:bit}],Rus=e=>j7t.some(t=>t.value===e);function Pus({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 $us=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=Kq(),{theme:r,setTheme:s}=B_();return o.jsx(Ft,{width:"narrow",children:o.jsxs(Ft.MainArea,{className:"mt-6 flex flex-col gap-5",children:[o.jsx(_ye,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(Aus,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(oa,{value:r,onValueChange:a=>{Rus(a)&&s(a)},children:[o.jsx(ca,{id:"theme",className:"w-full sm:w-48",children:o.jsx(la,{className:"inline-flex max-w-full min-w-0 items-center"})}),o.jsx(ua,{children:j7t.map(a=>o.jsx(Ar,{value:a.value,children:o.jsx(Pus,{option:a})},a.value))})]})})}),o.jsx(_ye,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(q$t,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function Mus(){const[e]=Ri(),t=qs(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(y7t,{redirectUri:n,onSuccess:r,initialMode:"signup"})}const T7t=e=>o.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("g",{clipPath:"url(#clip0_21999_22095)",children:o.jsx("path",{d:"M7.5 0.75C3.6325 0.75 0.5 3.8825 0.5 7.75C0.5 10.8475 2.50375 13.4637 5.28625 14.3912C5.63625 14.4525 5.7675 14.2425 5.7675 14.0587C5.7675 13.8925 5.75875 13.3412 5.75875 12.755C4 13.0787 3.545 12.3262 3.405 11.9325C3.32625 11.7312 2.985 11.11 2.6875 10.9437C2.4425 10.8125 2.0925 10.4887 2.67875 10.48C3.23 10.4712 3.62375 10.9875 3.755 11.1975C4.385 12.2562 5.39125 11.9587 5.79375 11.775C5.855 11.32 6.03875 11.0137 6.24 10.8387C4.6825 10.6637 3.055 10.06 3.055 7.3825C3.055 6.62125 3.32625 5.99125 3.7725 5.50125C3.7025 5.32625 3.4575 4.60875 3.8425 3.64625C3.8425 3.64625 4.42875 3.4625 5.7675 4.36375C6.3275 4.20625 6.9225 4.1275 7.5175 4.1275C8.1125 4.1275 8.7075 4.20625 9.2675 4.36375C10.6062 3.45375 11.1925 3.64625 11.1925 3.64625C11.5775 4.60875 11.3325 5.32625 11.2625 5.50125C11.7087 5.99125 11.98 6.6125 11.98 7.3825C11.98 10.0687 10.3438 10.6637 8.78625 10.8387C9.04 11.0575 9.25875 11.4775 9.25875 12.1337C9.25875 13.07 9.25 13.8225 9.25 14.0587C9.25 14.2425 9.38125 14.4612 9.73125 14.3912C11.1209 13.9221 12.3284 13.029 13.1839 11.8377C14.0393 10.6463 14.4996 9.21668 14.5 7.75C14.5 3.8825 11.3675 0.75 7.5 0.75Z",fill:"currentColor"})}),o.jsx("defs",{children:o.jsx("clipPath",{id:"clip0_21999_22095",children:o.jsx("rect",{width:"14",height:"14",fill:"currentColor",transform:"translate(0.5 0.75)"})})})]});function Dus(e){return e.replace(/\/$/,"").split("/").pop()}function sQ({children:e,className:t}){return o.jsx("div",{className:X("border border-border1 rounded-lg mt-12 py-8 lg:min-h-[25rem] transition-height px-4 lg:px-12",t),children:e})}function Lus({templates:e,linkComponent:t,className:n,isLoading:r}){const s=t||"a";return r?o.jsx("div",{className:X("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:X("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:X("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:X("grid [&:hover_p]:text-neutral5",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":a.imageURL}),children:[a.imageURL&&o.jsx("div",{className:X("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:X("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:X("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(Ld,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(xit,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(RD,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(hC,{})," ",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:X("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(T7t,{})," ",Dus(a.githubUrl)]})})]},a.slug)})})}function Fus({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:X("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:X("flex flex-wrap mx-auto sticky top-0 gap-4 bg-surface2 py-8",u),children:[o.jsx(vN,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(Cc,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(Cc,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(ce,{onClick:c,children:["Reset ",o.jsx(bs,{})]})]})}function zus(){const{data:e,isLoading:t}=GJn(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[a,i]=v.useState("all"),[l,c]=v.useState("all"),[u,d]=v.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(x=>{f.push({value:x,label:x})});const p=[{value:"all",label:"Any provider"}];(s||[]).forEach(x=>{p.push({value:x,label:x})});const h=(x,S)=>{S==="tag"?i(x):S==="provider"&&c(x)},m=x=>{d(x)},g=()=>{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(ds,{children:[o.jsx(Iwe,{children:o.jsxs(jgt,{children:[o.jsx(qe,{children:o.jsx(Kv,{})}),"Templates"]})}),o.jsxs("div",{className:X("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(Fus,{selectedTag:a,onTagChange:x=>h(x,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:x=>h(x,"provider"),providerOptions:p,searchTerm:u,onSearchChange:m,onReset:b?g:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(Lus,{templates:y,linkComponent:ei,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const Bus="1.55.0-alpha.0";function Uus({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(yf,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(wWt,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(sQ,{className:"text-neutral3 mb-8 content-center space-y-4",children:[o.jsxs("div",{className:X("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 Vus({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(sQ,{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:X("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(wit,{})]}),o.jsx(Cc,{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:X("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(Xt,{})," Loading variables..."]}):Object.entries(r).map(([p,h])=>o.jsxs(v.Fragment,{children:[o.jsx(CO,{name:`env-${p}`,labelIsHidden:!0,label:"Key",value:p,disabled:!0,className:"w-full"}),o.jsx(CO,{name:p,labelIsHidden:!0,label:"Value",value:h,onChange:i,errorMsg:s.includes(p)?"Value is required.":"",autoComplete:"off",className:"w-full"})]},p))}),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(Izt,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(ce,{className:X("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(Xt,{className:"h-4 w-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(ym,{})]})})]})})}function qus({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:X("grid mt-8 items-center"),children:o.jsxs("div",{className:X("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(Kv,{}),o.jsx("h2",{className:X({"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:X("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:X("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(Bx,{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(Rbe,{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(T7t,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(xNe,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function Hus(e){switch(e){case"running":return o.jsx(Xt,{});case"success":return o.jsx(xx,{});case"failed":return o.jsx(Wu,{});default:return null}}function Wus({stepId:e,step:t,isActive:n,position:r}){const s=a=>a.charAt(0).toUpperCase()+a.slice(1).replace(/-/g," ");return o.jsxs("div",{className:X("grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3",vs.all,{"border border-dashed border-neutral2 bg-surface3":n}),children:[o.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-2",children:[o.jsxs("span",{className:X("flex min-w-6 justify-end text-ui-md",vs.colors,{"text-neutral5":n||t.status==="success","text-neutral3":!n&&t.status!=="success"}),children:[r,"."]}),o.jsxs("div",{children:[o.jsx("h4",{className:X("text-ui-md",vs.colors,{"text-neutral5":n||t.status==="success","text-neutral3":!n&&t.status!=="success"}),children:s(e)}),t.description&&o.jsx("p",{className:"text-ui-md text-neutral2 -mt-0.5",children:t.description})]})]}),o.jsx("div",{className:X("flex size-[1.75rem] items-center justify-center self-center rounded-full",vs.all,{"border border-neutral2 border-dashed":t.status==="pending","[&>svg]:text-white [&>svg]:w-4 [&>svg]:h-4":t.status!=="running","w-[1.75rem] h-[1.75rem]":t.status==="running","bg-accent1Dark shadow-glow-accent1":t.status==="success","bg-accent2Dark shadow-glow-accent2":t.status==="failed","scale-110":t.status==="success"||t.status==="failed"}),children:Hus(t.status)})]})}function Zus({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:X(n),children:t.map((r,s)=>o.jsx(Wus,{stepId:r.id,step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function Gus({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:X("relative flex h-8 items-center justify-end",vs.colors,{"bg-accent1Dark":r.status==="success"&&e?.[s-1]?.status==="success"}),children:o.jsx("div",{className:X("absolute right-0 z-10 flex size-[2rem] translate-x-[50%] items-center justify-center self-center rounded-full bg-surface3 text-ui-sm font-bold text-neutral3",vs.all,{"border border-neutral2 border-dashed":r.status==="pending","[&>svg]:text-surface1 [&>svg]:w-[1.1rem] [&>svg]:h-[1.1rem]":r.status!=="running","bg-accent1Dark text-white shadow-glow-accent1 scale-110":r.status==="success","bg-accent2Dark text-white shadow-glow-accent2 scale-110":r.status==="failed"}),children:r.status==="running"?o.jsx(Xt,{}):s+1})},r.id))}),o.jsxs("div",{className:X("text-center text-xs text-neutral3",vs.colors),children:[n," of ",t," steps completed"]})]})}function Qus({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=g=>g==="input"||g.endsWith(".input")||g.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(g)||/[0-9a-f]{8,}/.test(g)?!1:r?.allSteps?g in r.allSteps:!0,f=Object.entries(c).filter(([g,y])=>d(g)),p=f.length,h=()=>{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(([g,y])=>({id:g,status:y?.status,description:y?.description,title:g.charAt(0).toUpperCase()+g.slice(1).replace(/-/g," "),isActive:i?.id===g}));return o.jsxs(sQ,{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:h()}),(t?.runId||n)&&o.jsxs("div",{className:"text-ui-sm text-neutral3 mt-2",children:["Run ID: ",t?.runId??n]})]}),u&&p>0&&!["error"].includes(s)&&o.jsx("div",{className:"mx-auto w-full max-w-[30rem] px-6",children:o.jsx(Gus,{steps:m})}),l&&s==="error"&&o.jsxs("div",{className:X("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($Zt,{}),l||"Something went wrong"]}),u&&o.jsx(Zus,{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(Xt,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function Yus({name:e,installedEntities:t}){return o.jsxs(sQ,{className:X("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(wit,{}),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(xNe,{data:t})]})}function Kus(){const{templateSlug:e}=Sr(),[t,n]=Ri(),[r,s]=v.useState(""),[a,i]=v.useState(""),[l,c]=v.useState(""),[u,d]=v.useState({}),[f,p]=v.useState([]),[h,m]=v.useState(null),[g,y]=v.useState(!1),[b,x]=v.useState(""),[S,k]=v.useState(!1),[_,C]=v.useState(!1),[E,j]=v.useState([]),{data:N,isLoading:I}=QJn({repoOrSlug:e,owner:"mastra-ai"}),R=Bus?.includes("beta")??!1?"beta":"main",{data:L,isLoading:D}=YJn({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:R}),{data:B,isLoading:H}=KJn(),{mutateAsync:F,isPending:z}=XJn(),{mutateAsync:q}=JJn(),{streamInstall:M,streamResult:G,isStreaming:V}=ter(B),{observeInstall:$,streamResult:U,isStreaming:Z}=ner(B);v.useEffect(()=>{const ne=t.get("runId");ne&&!g&&!h&&!V&&!Z&&(console.info("🔄 Checking completed run after hot reload:",{runId:ne}),x(ne),q({runId:ne}).then(fe=>{const oe=fe.snapshot;if(oe?.status==="success"&&oe?.result?.success)y(!0);else if(oe?.result?.success===!1)if(oe?.result?.validationResults&&!oe?.result?.validationResults?.valid&&oe?.result?.validationResults?.remainingErrors>0){const{remainingErrors:he,errors:be}=oe.result.validationResults,xe=`Template installation completed but ${he} validation issue${he>1?"s":""} remain unresolved.`;m(xe),j(be||[])}else{const he=oe?.result?.message||oe?.result?.error||"Template installation failed";m(typeof he=="string"?he:String(he))}}).catch(fe=>{console.error("❌ Failed to fetch run details:",fe),m("Failed to retrieve installation status after reload")}))},[t,g,h,V,Z,q]),v.useEffect(()=>{const ne=t.get("runId"),fe=t.get("resume"),oe=t.get("provider");if(ne&&fe==="true"&&oe&&!V&&!Z&&!S&&!_&&B){x(ne),k(!0);try{q({runId:ne}).then(le=>{if(le.snapshot?.status==="running")return $.mutateAsync({runId:ne})}).then(()=>{n(le=>{const he=new URLSearchParams(le);return he.delete("resume"),he})}).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,V,Z,S,_,B,q,$,n]);const K=[{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(Ld,{})},{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(RD,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(Mv,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(BN,{})}],ee=[{...te[0]},{...te[1]},{...te[2]}].filter(ne=>ne.value!=="n/a");v.useEffect(()=>{L&&d(L)},[L]),v.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 J=ne=>{s(ne)},ae=async ne=>(i(ne.provider),c(ne.modelId),{message:"Model updated successfully"}),de=async()=>{const ne=Object.entries(u).reduce((fe,[oe,le])=>(le===""&&fe.push(oe),fe),[]);if(ne.length>0){p(ne);return}if(N){m(null),y(!1),x(""),C(!0);try{const oe={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:R,slug:N.slug,variables:u},{runId:le}=await F({});x(le),n(he=>{const be=new URLSearchParams(he);return be.set("runId",le),be.set("resume","true"),be.set("provider",r||"openai"),be}),await M.mutateAsync({inputData:oe,selectedModel:{provider:a,modelId:l},runId:le})}catch(fe){C(!1),m(fe?.message||"Template installation failed"),console.error("Template installation failed",fe)}}},Y=ne=>{const{name:fe,value:oe}=ne.target;oe.trim()===""?p(le=>[...le,fe]):p(le=>le.filter(he=>he!==fe)),d(le=>({...le,[fe]:oe}))};return o.jsx(ds,{children:o.jsx("div",{className:X("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(qus,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:te,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(V||Z)&&o.jsx(Qus,{name:N.title,streamResult:Z?U:G,runId:b,workflowInfo:B}),g&&o.jsx(Yus,{name:N.title,installedEntities:ee,linkComponent:ei}),h&&o.jsx(Uus,{errorMsg:h,validationErrors:E.length>0?E:G?.validationResults?.errors||U?.validationResults?.errors}),!V&&!Z&&!g&&!h&&o.jsx(Vus,{providerOptions:K,selectedProvider:r,onProviderChange:J,variables:u,setVariables:d,errors:f,setErrors:p,handleInstallTemplate:de,handleVariableChange:Y,isLoadingEnvVars:D||H,isInstalling:z,defaultModelProvider:a,defaultModelId:l,onModelUpdate:ae})]})]})})})}const Xus=()=>{const{toolId:e,agentId:t}=Sr();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(aXr,{toolId:e,agentId:t})})},Jus=()=>{const{toolId:e}=Sr();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(rcs,{toolId:e})})};function eds(){const{traceId:e}=Sr(),[t,n]=Ri(),r=qs(),s=t.get("spanId")||void 0,a=t.get("tab"),i=a==="scoring"?"scoring":a==="feedback"?"feedback":"details",l=t.get("scoreId")||void 0,[c,u]=v.useState(s??null),[d,f]=v.useState(),[p,h]=v.useState(i),[m,g]=v.useState(0),[y,b]=v.useState(!1),{data:x,isLoading:S,error:k}=oIe(e),_=v.useMemo(()=>x?.spans??[],[x?.spans]),C=v.useMemo(()=>_.find(ae=>ae.parentSpanId==null),[_]),{data:E,isLoading:j}=CL(e,c??"");v.useEffect(()=>g(0),[e,c]);const{data:N,isLoading:I}=ih(),{data:A,isLoading:R}=Yzt({traceId:e,spanId:c??void 0,page:m}),[L,D]=v.useState(0);v.useEffect(()=>D(0),[e,c]);const{data:B,isLoading:H}=i7t({traceId:e,page:L});v.useEffect(()=>{if(l&&A?.scores&&!d){const ae=A.scores.find(de=>de.id===l);ae&&f(ae)}},[l,A?.scores,d]);const F=v.useCallback(ae=>{const de=new URLSearchParams(t);for(const[Y,ne]of Object.entries(ae))ne===null||ne===""?de.delete(Y):de.set(Y,ne);n(de,{replace:!0})},[t,n]),z=v.useCallback(ae=>{const de=ae??null,Y=de===c;u(de),Y||(f(void 0),h("details"),F({spanId:de,tab:null,scoreId:null}))},[c,F]),q=v.useCallback(()=>{u(null),f(void 0),h("details"),F({spanId:null,tab:null,scoreId:null})},[F]),M=v.useCallback(ae=>{u(ae),f(void 0),h("details"),F({spanId:ae,tab:null,scoreId:null})},[F]),{handlePreviousSpan:G,handleNextSpan:V}=lIe(_,c,M),$=v.useCallback(ae=>{const de=ae;h(de),f(void 0),F({tab:de==="details"?null:de,scoreId:null})},[F]),U=v.useCallback(ae=>{f(ae),F({scoreId:ae.id})},[F]),Z=v.useCallback(()=>{f(void 0),F({scoreId:null})},[F]),K=v.useCallback(()=>{r("/observability")},[r]),te=v.useCallback(()=>{h("scoring"),C&&c!==C.spanId?(u(C.spanId),f(void 0),F({spanId:C.spanId,tab:"scoring",scoreId:null})):F({tab:"scoring"})},[C,c,F]),ee=C?o.jsx($y,{owner:"trace-detail",children:o.jsxs(Mr,{children:[o.jsxs(ce,{tooltip:"Evaluate Trace","aria-label":"Evaluate Trace",onClick:te,children:[o.jsx(hHt,{}),"Evaluate"]}),o.jsxs(ce,{tooltip:"Save as Dataset Item","aria-label":"Save as Dataset Item",onClick:()=>b(!0),children:[o.jsx(jd,{}),"Save"]})]})}):null,J=C?o.jsx(Ft.Row,{children:o.jsx(Ft.Column,{children:o.jsx(H9t,{rootSpan:C,numOfCol:3})})}):null;return k?o.jsxs(Ft,{height:"full",children:[ee,J&&o.jsx(Ft.TopArea,{children:J}),o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsx(Y9t,{error:k,resource:"traces",errorTitle:"Failed to load trace"})})]}):o.jsxs(Ft,{height:"full",className:"grid-rows-[auto_minmax(0,1fr)] content-normal",children:[ee,J&&o.jsx(Ft.TopArea,{children:J}),o.jsx(t7t,{rootSpanId:C?.spanId,traceId:e,isOpen:y,onClose:()=>b(!1)}),o.jsxs("div",{className:X("mt-4 grid min-h-0 items-stretch gap-4 overflow-hidden",c?"grid-cols-[2fr_3fr]":"grid-cols-[1fr]"),children:[o.jsx(eIe,{traceId:e,spans:_,isLoading:S,onClose:K,onSpanSelect:z,onEvaluateTrace:te,initialSpanId:c,placement:"trace-page",timelineChartWidth:c?"default":"wide"}),c&&!S&&o.jsxs("div",{className:X("grid h-full max-h-full min-h-0 gap-4 overflow-auto",d?"grid-rows-[1fr_1fr]":"grid-rows-[1fr]"),children:[o.jsx(KNe,{traceId:e,spanId:c,span:E?.span,isLoading:j,onClose:q,onPrevious:G,onNext:V,activeTab:p,onTabChange:$,feedbackTabBadge:B?.pagination?.total??void 0,feedbackTabSlot:()=>o.jsx(r7t,{feedbackData:B,onPageChange:D,isLoadingFeedbackData:H}),scoringTabBadge:A?.pagination?.total??void 0,scoringTabSlot:({span:ae,traceId:de,spanId:Y})=>o.jsxs("div",{className:"grid gap-6",children:[o.jsx(a7t,{traceId:de,isTopLevelSpan:!ae.parentSpanId,spanId:Y,entityType:ae.attributes?.agentId||ae.entityType===au.AGENT?"Agent":ae.attributes?.workflowId||ae.entityType===au.WORKFLOW_RUN?"Workflow":void 0,scorers:N,isLoadingScorers:I}),o.jsx(s7t,{scoresData:A,onPageChange:g,isLoadingScoresData:R,onScoreSelect:U})]})}),d&&o.jsx(bNe,{score:d,onClose:Z})]})]})]})}function tds(){const{data:e,isLoading:t,error:n}=Hy(),[r,s]=v.useState("");return n&&ys(n)?o.jsx(lr,{children:o.jsx(Hs,{})}):n&&xs(n)?o.jsx(lr,{children:o.jsx(Ms,{resource:"workflows"})}):n?o.jsx(lr,{children:o.jsx(qi,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(lr,{children:o.jsx(F8r,{})}):o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsxs(Ft.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx($f,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsxs(ce,{as:ei,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(TD,{}),"Schedules"]})]})}),o.jsx(L8r,{workflows:e||{},isLoading:t,search:r})]})}const nds={active:"bg-accent1",paused:"bg-accent3"},rds={active:"text-accent1",paused:"text-accent3"},N7t=({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 ${nds[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${rds[e]}`,children:e})]}),iT=e=>!e||e<=0?"—":new Date(e).toLocaleString(),$2=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 I7t({status:e}){const{icon:t,color:n}=sds(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 sds(e){switch(e){case"success":return{icon:o.jsx(fa,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(bs,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(Xt,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(BV,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(Nf,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(uT,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const jXe="auto auto auto auto 1fr";function ads(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 ids(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 ods=3e4,lds=5*6e4;function cds({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=yn();return t?o.jsx(ol,{columns:jXe}):e.length===0?o.jsx(ye,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(ve,{columns:jXe,className:"min-w-0",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Run"}),o.jsx(ve.TopCell,{children:"Status"}),o.jsx(ve.TopCell,{children:"Started"}),o.jsx(ve.TopCell,{children:"Duration"}),o.jsx(ve.TopCell,{children:" "})]}),e.map(c=>{const u=c.actualFireAt-c.scheduledFireAt,d=ids(u),f=`Scheduled ${iT(c.scheduledFireAt)} — published ${iT(c.actualFireAt)} (drift ${d})`,p=c.outcome==="failed",h=p?c.error:c.run?.error,m=Math.abs(u),g=!p&&m>ods&&m<=lds,y=`${c.scheduleId}-${c.runId}-${c.actualFireAt}`,b=!!(n&&c.runId&&!p),x=o.jsx("span",{className:b?"text-accent1 text-ui-sm font-mono whitespace-nowrap":"text-neutral3 text-ui-sm font-mono whitespace-nowrap",children:c.runId}),S=o.jsxs(o.Fragment,{children:[o.jsx(ve.Cell,{height:"compact",children:x}),o.jsx(ve.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[p?o.jsxs("span",{className:"text-ui-sm text-accent2 inline-flex items-center gap-1.5 whitespace-nowrap",children:[o.jsx(yf,{size:14}),"publish failed"]}):c.run?o.jsx(I7t,{status:c.run.status}):o.jsx("span",{className:"text-ui-sm text-neutral3 inline-flex items-center gap-1.5 whitespace-nowrap",children:"pending"}),h?o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(yf,{size:14})})}),o.jsx(Rn,{children:h})]}):null]})}),o.jsx(ve.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:f,children:$2(c.actualFireAt)}),g?o.jsxs(Pn,{children:[o.jsx(An,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(yf,{size:14})})}),o.jsxs(Rn,{children:["Published ",d," after the scheduled fire time"]})]}):null]})}),o.jsx(ve.Cell,{height:"compact",children:c.run?o.jsx("span",{children:ads(c.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(ve.Cell,{height:"compact",children:" "})]});return b?o.jsx(ve.RowLink,{to:l.workflowRunLink(n,c.runId),LinkComponent:i,children:S},y):o.jsx(ve.RowStatic,{children:S},y)}),o.jsx(ve.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const uds=e=>{const t=We();return yt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},TXe=25,dds=e=>{const t=We(),{inView:n,setRef:r}=W_(),s=M1({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:TXe,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<TXe))return u.triggers[u.triggers.length-1].actualFireAt},refetchInterval:u=>(u.state.data?.pages.flatMap(p=>p.triggers)??[]).some(p=>p.run?p.run.status==="pending"||p.run.status==="running"||p.run.status==="waiting":p.outcome==="published")?5e3:!1}),a=s.data?.pages.flatMap(u=>u?.triggers??[])??[],{hasNextPage:i,isFetchingNextPage:l,fetchNextPage:c}=s;return v.useEffect(()=>{n&&i&&!l&&c()},[n,i,l,c]),{...s,data:a,setEndOfListElement:r}},fds=e=>{const t=We(),n=Ur();return Mn({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"]}),Le.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{Le.error(r.message)}})};function Uz({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ye,{variant:"ui-xs",className:"text-neutral4 tracking-wide uppercase",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function pds(){const{scheduleId:e}=Sr(),{paths:t}=yn(),{data:n,error:r}=uds(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=dds(e),d=fds(e);if(r&&ys(r))return o.jsx(lr,{children:o.jsx(Hs,{})});if(r&&xs(r))return o.jsx(lr,{children:o.jsx(Ms,{resource:"schedules"})});if(r)return o.jsx(lr,{children:o.jsx(qi,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,p=n?.agentId;return o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsx(Ft.Row,{className:"justify-end",children:o.jsxs(Ft.Column,{className:"flex justify-end gap-2",children:[o.jsxs(ce,{as:ei,to:t.schedulesLink(),variant:"ghost",children:[o.jsx(Ac,{}),"Back to schedules"]}),f?o.jsx(ce,{as:ei,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(ce,{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(Mbe,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(Of,{}),"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(Uz,{label:p?"Agent":"Workflow",children:f?o.jsx(ei,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):p?o.jsx(ei,{to:t.agentLink(p),className:"text-accent1 hover:underline",children:p}):"—"}),o.jsxs(Uz,{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(Uz,{label:"Status",children:o.jsx(N7t,{status:n.status})}),o.jsx(Uz,{label:"Next fire",children:o.jsx("span",{title:iT(n.nextFireAt),children:$2(n.nextFireAt)})})]}),o.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[o.jsx(ye,{variant:"ui-md",className:"mb-3",children:"Trigger history"}),i?o.jsx(qi,{title:"Failed to load trigger history",message:i.message}):o.jsx(cds,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const NXe="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function hds({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=yn(),a=v.useMemo(()=>{const i=n.toLowerCase();return i?e.filter(l=>l.id.toLowerCase().includes(i)||(l.workflowId??l.agentId??"").toLowerCase().includes(i)):e},[e,n]);return t?o.jsx(ol,{columns:NXe}):o.jsxs(ve,{columns:NXe,variant:"striped",className:"min-w-0",children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Target"}),o.jsx(ve.TopCell,{children:"Schedule ID"}),o.jsx(ve.TopCell,{children:"Cron"}),o.jsx(ve.TopCell,{children:"Status"}),o.jsx(ve.TopCell,{children:"Next fire"}),o.jsx(ve.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(ve.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(ve.NoMatch,{message:"No schedules configured"}):null,a.map(i=>o.jsxs(ve.RowLink,{to:r.scheduleLink(i.id),LinkComponent:s,children:[o.jsx(ve.NameCell,{children:i.workflowId??i.agentId}),o.jsx(ve.Cell,{height:"compact",className:"min-w-0",children:o.jsx("span",{className:"text-ui-smd text-neutral3 block truncate font-mono",title:i.id,children:i.id})}),o.jsx(ve.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("code",{className:"text-ui-sm font-mono",children:i.cron}),i.timezone?o.jsx("span",{className:"text-neutral4 text-ui-xs",children:i.timezone}):null]})}),o.jsx(ve.Cell,{height:"compact",children:o.jsx(N7t,{status:i.status})}),o.jsx(ve.Cell,{height:"compact",children:o.jsx("span",{className:"whitespace-nowrap",title:iT(i.nextFireAt),children:$2(i.nextFireAt)})}),o.jsx(ve.Cell,{height:"compact",children:i.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(I7t,{status:i.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:iT(i.lastFireAt),children:i.lastFireAt?$2(i.lastFireAt):""})]}):i.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:iT(i.lastFireAt),children:$2(i.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},i.id))]})}function mds({workflowId:e}={}){const{data:t,isLoading:n,error:r}=Twe(e?{workflowId:e}:{}),[s,a]=v.useState("");return r?o.jsx(qi,{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($f,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(hds,{schedules:t??[],isLoading:n,search:s})})]})}function gds(){const[e]=Ri(),t=e.get("workflowId")??void 0,{error:n}=Twe(t?{workflowId:t}:{});return n&&ys(n)?o.jsx(lr,{children:o.jsx(Hs,{})}):n&&xs(n)?o.jsx(lr,{children:o.jsx(Ms,{resource:"schedules"})}):o.jsx(Ft,{children:o.jsx("div",{className:"h-full",children:o.jsx(mds,{workflowId:t})})})}function vds({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=oke({stepGraph:e}),[a,i]=v.useState(!1),[l,c,u]=ikt(r),[d]=okt(s),{edgeTypes:f,nodeTypes:p,styledEdges:h}=IDt({edges:d,workflowName:n,stepGraph:e});return v.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(akt,{nodes:l,edges:h,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:p,onNodesChange:u,children:[o.jsx(GEe,{position:"bottom-left"}),o.jsx(ckt,{variant:sy.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:o.jsx(Xt,{})})})}function yds(){const{stepDetail:e,closeStepDetail:t}=WH();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(f9,{className:"h-4 w-4",style:{color:ju.map}}),e.type==="nested-graph"&&o.jsx(Xu,{className:"h-4 w-4",style:{color:ju.workflow}}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx(ye,{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(ye,{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(bs,{className:"text-neutral3 h-4 w-4"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(R2,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(ike,{children:o.jsx(vds,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function bds(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function xds(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 wds({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(ye,{as:"p",variant:"ui-md",className:"text-neutral6 flex items-center gap-2 font-semibold",children:[o.jsx(qe,{children:o.jsx(BV,{})}),"Step suspended"]}),o.jsx(un,{variant:"warning",children:"Needs input"})]}),e.map((s,a)=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const l=i?.resumeSchema?fm(um(wx(i.resumeSchema))):hp(ur(),NT());return o.jsx(Sds,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function Sds({step:e,stepSchema:t,description:n,isStreaming:r,onResume:s}){const[a,i]=v.useState(!1);return o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(ye,{as:"p",variant:"ui-md",className:"text-neutral6 truncate font-medium",children:e.stepId}),n&&o.jsx(ye,{as:"p",variant:"ui-sm",className:"text-neutral3",children:n})]}),e.suspendPayload&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs(ye,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(qe,{children:o.jsx(EZt,{})}),"The step is asking"]}),o.jsxs(Tf,{open:a,onOpenChange:i,children:[o.jsxs($d,{className:"border-border1 bg-surface3 flex w-full items-center justify-between gap-2 rounded-lg border px-3 py-2.5",children:[o.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(qe,{children:o.jsx(pa,{className:X("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(ye,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:xds(e.suspendPayload,e.stepId)})]}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:bds(e.suspendPayload)})]}),o.jsx(Md,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Wr,{data:e.suspendPayload,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs(ye,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(qe,{children:o.jsx(NZt,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(IB,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(Of,{}),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 kds(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=v.useContext(Bl),{runId:a}=Sr(),i=gkt(e,r??""),l=fKn(),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(wds,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const Ods=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"})]}),_ds=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"})]}),Cds=e=>e.includes("."),Eds=e=>e==="input"||e.endsWith(".input"),jds=1;function Tds(e){return`${Number((e/1e3).toPrecision(3))}s`}function Nds(e,t){const n=Object.entries(e).filter(([i])=>!Eds(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,p=Math.max(d/a*100,jds);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:p,durationMs:d,isRunning:c,isNestedEntry:Cds(i)}})}const Ids=({status:e})=>o.jsxs(qe,{children:[e==="success"&&o.jsx(Ods,{className:"text-accent1"}),e==="failed"&&o.jsx(_ds,{className:"text-accent2"}),e==="suspended"&&o.jsx(BV,{className:"text-accent3"}),e==="waiting"&&o.jsx(Ofe,{className:"text-accent5"}),e==="skipped"&&o.jsx(Ofe,{className:"text-icon3"}),e==="running"&&o.jsx(ia,{className:"text-accent6 animate-spin"})]}),Ads={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function A7t(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const IXe=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},Rds=e=>{const t=e;return SDt({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},Pds=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=Rds(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:X("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(Ids,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ce,{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(IGt,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(hV,{indicators:c,className:"shrink-0"})}),o.jsx(ye,{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:A7t(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 ${Ads[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ce,{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(TGt,{})})}),o.jsx(ye,{as:"span",variant:"ui-sm",className:"text-neutral3 w-20 justify-self-end text-right tabular-nums",children:Tds(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function $ds(){const{steps:e}=F4(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=sH(),[a,i]=v.useState(()=>Date.now()),[l,c]=v.useState(!1),[u,d]=v.useState(null),f=v.useRef(null);Dwe(f,{enabled:!l});const p=Nds(e,a),h=p.some(m=>m.isRunning);return v.useEffect(()=>{if(!h)return;const m=setInterval(()=>i(Date.now()),100);return()=>clearInterval(m)},[h]),v.useEffect(()=>{if(l||p.length===0)return;const m=f.current;m&&(m.scrollTop=m.scrollHeight)},[l,p.length]),p.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(ye,{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(Na,{className:X("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:p.map((m,g)=>o.jsx(Pds,{row:m,index:g,isSelected:t===m.stepId,isHovered:n===m.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:y=>d({type:"input",stepId:y.stepId,data:IXe(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:IXe(y.step.output)})},`timeline-item-${m.stepId}-${g}`))})]})}),o.jsx(br,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(ykt,{data:u.data,title:`${A7t(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const Mds=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=WH();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(ADt,{workflowId:e,workflow:t,isLoading:n}),o.jsx(kds,{}),o.jsx($ds,{})]})}),r&&o.jsx("div",{className:"border-border1 min-h-0 w-[420px] overflow-hidden border-l",children:o.jsx(yds,{})})]})},AXe=()=>{const{workflowId:e}=Sr(),{data:t,isLoading:n,error:r}=H3(e);return r&&ys(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Hs,{})}):r&&xs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ms,{resource:"workflows"})}):o.jsx(_ke,{children:o.jsx(Mds,{workflowId:e,workflow:t??void 0,isLoading:n})})};function Dds(e,t){if(e==null)return{};var n,r,s=Swt(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 bbe(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 Lds(e){if(Array.isArray(e))return bbe(e)}function Fds(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function zds(e,t){if(e){if(typeof e=="string")return bbe(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)?bbe(e,t):void 0}}function Bds(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
722
722
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function xbe(e){return Lds(e)||Fds(e)||zds(e)||Bds()}function _D(e){"@babel/helpers - typeof";return _D=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},_D(e)}function Uds(e,t){if(_D(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(_D(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Vds(e){var t=Uds(e,"string");return _D(t)=="symbol"?t:t+""}function R7t(e,t,n){return(t=Vds(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function RXe(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 wj(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?RXe(Object(n),!0).forEach(function(r){R7t(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):RXe(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function qds(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 Pae={};function Hds(e){if(e.length===0||e.length===1)return e;var t=e.join(".");return Pae[t]||(Pae[t]=qds(e)),Pae[t]}function Wds(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=Hds(r);return s.reduce(function(a,i){return wj(wj({},a),n[i])},t)}function PXe(e){return e.join(" ")}function Zds(e,t){var n=0;return function(r){return n+=1,r.map(function(s,a){return P7t({node:s,stylesheet:e,useInlineStyles:t,key:"code-segment-".concat(n,"-").concat(a)})})}}function P7t(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=Zds(n,a),p;if(!a)p=wj(wj({},l),{},{className:PXe(l.className)});else{var h=Object.keys(n).reduce(function(b,x){return x.split(".").forEach(function(S){b.includes(S)||b.push(S)}),b},[]),m=l.className&&l.className.includes("token")?["token"]:[],g=l.className&&m.concat(l.className.filter(function(b){return!h.includes(b)}));p=wj(wj({},l),{},{className:PXe(g)||void 0,style:Wds(l.className,Object.assign({},l.style,s),n)})}var y=f(t.children);return Fe.createElement(u,UO({key:i},p),y)}}const Gds=(function(e,t){var n=e.listLanguages();return n.indexOf(t)!==-1});var Qds=["language","children","style","customStyle","codeTagProps","useInlineStyles","showLineNumbers","showInlineLineNumbers","startingLineNumber","lineNumberContainerStyle","lineNumberStyle","wrapLines","wrapLongLines","lineProps","renderer","PreTag","CodeTag","code","astGenerator"];function $Xe(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 Ew(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?$Xe(Object(n),!0).forEach(function(r){R7t(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):$Xe(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var Yds=/\n/g;function Kds(e){return e.match(Yds)}function Xds(e){var t=e.lines,n=e.startingLineNumber,r=e.style;return t.map(function(s,a){var i=a+n;return Fe.createElement("span",{key:"line-".concat(a),className:"react-syntax-highlighter-line-number",style:typeof r=="function"?r(i):r},"".concat(i,`
723
723
  `))})}function Jds(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 Fe.createElement("code",{style:Object.assign({},n,s)},Xds({lines:t.replace(/\n$/,"").split(`
724
724
  `),style:i,startingLineNumber:l}))}function efs(e){return"".concat(e.toString().length,".25em")}function $7t(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 M7t(e,t,n){var r={display:"inline-block",minWidth:efs(n),paddingRight:"1em",textAlign:"right",userSelect:"none"},s=typeof e=="function"?e(t):e,a=Ew(Ew({},r),s);return a}function l9(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,p=e.wrapLines,h=p===void 0?!1:p,m=h?Ew({},typeof l=="function"?l(n):l):{};if(m.className=m.className?[].concat(xbe(m.className.trim().split(/\s+/)),xbe(u)):u,n&&a){var g=M7t(r,n,s);t.unshift($7t(n,g))}return f&d&&(m.style=Ew({display:"flex"},m.style)),{type:"element",tagName:"span",properties:m,children:t}}function D7t(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(l9({children:[s],className:xbe(new Set(t))}));else if(s.children){var a=t.concat(s.properties.className);D7t(s.children,a).forEach(function(i){return n.push(i)})}}return n}function tfs(e,t,n,r,s,a,i,l,c){var u,d=D7t(e.value),f=[],p=-1,h=0;function m(_,C){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return l9({children:_,lineNumber:C,lineNumberStyle:l,largestLineNumber:i,showInlineLineNumbers:s,lineProps:n,className:E,showLineNumbers:r,wrapLongLines:c,wrapLines:t})}function g(_,C){if(r&&C&&s){var E=M7t(l,C,i);_.unshift($7t(C,E))}return _}function y(_,C){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return t||E.length>0?m(_,C,E):g(_,C)}for(var b=function(){var C=d[h],E=C.children[0].value,j=Kds(E);if(j){var N=E.split(`