@mastra/deployer-cloud 1.65.0-alpha.1 → 1.65.0-alpha.2
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-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./core-W-bmkix6.js","./engine-compile-BkERmzkH.js","./preload-helper-PPVm8Dsz.js","./engine-javascript-CSIo_1eZ.js","./html-C2L_23MC.js","./javascript-ySlJ1b_l.js","./css-BPhBrDlE.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{_ as Fa}from"./preload-helper-PPVm8Dsz.js";function zGt(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 Ej=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Vl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var vX={exports:{}},lR={};var uMe;function BGt(){if(uMe)return lR;uMe=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 lR.Fragment=t,lR.jsx=n,lR.jsxs=n,lR}var dMe;function UGt(){return dMe||(dMe=1,vX.exports=BGt()),vX.exports}var o=UGt(),yX={exports:{}},Gr={},fMe;function qGt(){if(fMe)return Gr;fMe=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(U){return U===null||typeof U!="object"?null:(U=h&&U[h]||U["@@iterator"],typeof U=="function"?U:null)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y=Object.assign,b={};function x(U,P,B){this.props=U,this.context=P,this.refs=b,this.updater=B||v}x.prototype.isReactComponent={},x.prototype.setState=function(U,P){if(typeof U!="object"&&typeof U!="function"&&U!=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,U,P,"setState")},x.prototype.forceUpdate=function(U){this.updater.enqueueForceUpdate(this,U,"forceUpdate")};function S(){}S.prototype=x.prototype;function k(U,P,B){this.props=U,this.context=P,this.refs=b,this.updater=B||v}var _=k.prototype=new S;_.constructor=k,y(_,x.prototype),_.isPureReactComponent=!0;var C=Array.isArray;function T(){}var E={H:null,A:null,T:null,S:null},N=Object.prototype.hasOwnProperty;function I(U,P,B){var Z=B.ref;return{$$typeof:t,type:U,key:P,ref:Z!==void 0?Z:null,props:B}}function A(U,P){return I(U.type,P,U.props)}function R(U){return typeof U=="object"&&U!==null&&U.$$typeof===t}function L(U){var P={"=":"=0",":":"=2"};return"$"+U.replace(/[=:]/g,function(B){return P[B]})}var M=/\/+/g;function F(U,P){return typeof U=="object"&&U!==null&&U.key!=null?L(""+U.key):P.toString(36)}function H(U){switch(U.status){case"fulfilled":return U.value;case"rejected":throw U.reason;default:switch(typeof U.status=="string"?U.then(T,T):(U.status="pending",U.then(function(P){U.status==="pending"&&(U.status="fulfilled",U.value=P)},function(P){U.status==="pending"&&(U.status="rejected",U.reason=P)})),U.status){case"fulfilled":return U.value;case"rejected":throw U.reason}}throw U}function z(U,P,B,Z,Y){var te=typeof U;(te==="undefined"||te==="boolean")&&(U=null);var J=!1;if(U===null)J=!0;else switch(te){case"bigint":case"string":case"number":J=!0;break;case"object":switch(U.$$typeof){case t:case n:J=!0;break;case f:return J=U._init,z(J(U._payload),P,B,Z,Y)}}if(J)return Y=Y(U),J=Z===""?"."+F(U,0):Z,C(Y)?(B="",J!=null&&(B=J.replace(M,"$&/")+"/"),z(Y,P,B,"",function(oe){return oe})):Y!=null&&(R(Y)&&(Y=A(Y,B+(Y.key==null||U&&U.key===Y.key?"":(""+Y.key).replace(M,"$&/")+"/")+J)),P.push(Y)),1;J=0;var ee=Z===""?".":Z+":";if(C(U))for(var re=0;re<U.length;re++)Z=U[re],te=ee+F(Z,re),J+=z(Z,P,B,te,Y);else if(re=m(U),typeof re=="function")for(U=re.call(U),re=0;!(Z=U.next()).done;)Z=Z.value,te=ee+F(Z,re++),J+=z(Z,P,B,te,Y);else if(te==="object"){if(typeof U.then=="function")return z(H(U),P,B,Z,Y);throw P=String(U),Error("Objects are not valid as a React child (found: "+(P==="[object Object]"?"object with keys {"+Object.keys(U).join(", ")+"}":P)+"). If you meant to render a collection of children, use an array instead.")}return J}function q(U,P,B){if(U==null)return U;var Z=[],Y=0;return z(U,Z,"","",function(te){return P.call(B,te,Y++)}),Z}function V(U){if(U._status===-1){var P=U._result;P=P(),P.then(function(B){(U._status===0||U._status===-1)&&(U._status=1,U._result=B)},function(B){(U._status===0||U._status===-1)&&(U._status=2,U._result=B)}),U._status===-1&&(U._status=0,U._result=P)}if(U._status===1)return U._result.default;throw U._result}var D=typeof reportError=="function"?reportError:function(U){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var P=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof U=="object"&&U!==null&&typeof U.message=="string"?String(U.message):String(U),error:U});if(!window.dispatchEvent(P))return}else if(typeof e=="object"&&typeof e.emit=="function"){e.emit("uncaughtException",U);return}console.error(U)},G={map:q,forEach:function(U,P,B){q(U,function(){P.apply(this,arguments)},B)},count:function(U){var P=0;return q(U,function(){P++}),P},toArray:function(U){return q(U,function(P){return P})||[]},only:function(U){if(!R(U))throw Error("React.Children.only expected to receive a single React element child.");return U}};return Gr.Activity=p,Gr.Children=G,Gr.Component=x,Gr.Fragment=r,Gr.Profiler=a,Gr.PureComponent=k,Gr.StrictMode=s,Gr.Suspense=u,Gr.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=E,Gr.__COMPILER_RUNTIME={__proto__:null,c:function(U){return E.H.useMemoCache(U)}},Gr.cache=function(U){return function(){return U.apply(null,arguments)}},Gr.cacheSignal=function(){return null},Gr.cloneElement=function(U,P,B){if(U==null)throw Error("The argument must be a React element, but you passed "+U+".");var Z=y({},U.props),Y=U.key;if(P!=null)for(te in P.key!==void 0&&(Y=""+P.key),P)!N.call(P,te)||te==="key"||te==="__self"||te==="__source"||te==="ref"&&P.ref===void 0||(Z[te]=P[te]);var te=arguments.length-2;if(te===1)Z.children=B;else if(1<te){for(var J=Array(te),ee=0;ee<te;ee++)J[ee]=arguments[ee+2];Z.children=J}return I(U.type,Y,Z)},Gr.createContext=function(U){return U={$$typeof:l,_currentValue:U,_currentValue2:U,_threadCount:0,Provider:null,Consumer:null},U.Provider=U,U.Consumer={$$typeof:i,_context:U},U},Gr.createElement=function(U,P,B){var Z,Y={},te=null;if(P!=null)for(Z in P.key!==void 0&&(te=""+P.key),P)N.call(P,Z)&&Z!=="key"&&Z!=="__self"&&Z!=="__source"&&(Y[Z]=P[Z]);var J=arguments.length-2;if(J===1)Y.children=B;else if(1<J){for(var ee=Array(J),re=0;re<J;re++)ee[re]=arguments[re+2];Y.children=ee}if(U&&U.defaultProps)for(Z in J=U.defaultProps,J)Y[Z]===void 0&&(Y[Z]=J[Z]);return I(U,te,Y)},Gr.createRef=function(){return{current:null}},Gr.forwardRef=function(U){return{$$typeof:c,render:U}},Gr.isValidElement=R,Gr.lazy=function(U){return{$$typeof:f,_payload:{_status:-1,_result:U},_init:V}},Gr.memo=function(U,P){return{$$typeof:d,type:U,compare:P===void 0?null:P}},Gr.startTransition=function(U){var P=E.T,B={};E.T=B;try{var Z=U(),Y=E.S;Y!==null&&Y(B,Z),typeof Z=="object"&&Z!==null&&typeof Z.then=="function"&&Z.then(T,D)}catch(te){D(te)}finally{P!==null&&B.types!==null&&(P.types=B.types),E.T=P}},Gr.unstable_useCacheRefresh=function(){return E.H.useCacheRefresh()},Gr.use=function(U){return E.H.use(U)},Gr.useActionState=function(U,P,B){return E.H.useActionState(U,P,B)},Gr.useCallback=function(U,P){return E.H.useCallback(U,P)},Gr.useContext=function(U){return E.H.useContext(U)},Gr.useDebugValue=function(){},Gr.useDeferredValue=function(U,P){return E.H.useDeferredValue(U,P)},Gr.useEffect=function(U,P){return E.H.useEffect(U,P)},Gr.useEffectEvent=function(U){return E.H.useEffectEvent(U)},Gr.useId=function(){return E.H.useId()},Gr.useImperativeHandle=function(U,P,B){return E.H.useImperativeHandle(U,P,B)},Gr.useInsertionEffect=function(U,P){return E.H.useInsertionEffect(U,P)},Gr.useLayoutEffect=function(U,P){return E.H.useLayoutEffect(U,P)},Gr.useMemo=function(U,P){return E.H.useMemo(U,P)},Gr.useOptimistic=function(U,P){return E.H.useOptimistic(U,P)},Gr.useReducer=function(U,P,B){return E.H.useReducer(U,P,B)},Gr.useRef=function(U){return E.H.useRef(U)},Gr.useState=function(U){return E.H.useState(U)},Gr.useSyncExternalStore=function(U,P,B){return E.H.useSyncExternalStore(U,P,B)},Gr.useTransition=function(){return E.H.useTransition()},Gr.version="19.2.7",Gr}var pMe;function eI(){return pMe||(pMe=1,yX.exports=qGt()),yX.exports}var g=eI();const Fe=Vl(g),tI=zGt({__proto__:null,default:Fe},[g]);var bX={exports:{}},cR={},xX={exports:{}},wX={};var hMe;function VGt(){return hMe||(hMe=1,(function(e){function t(H,z){var q=H.length;H.push(z);e:for(;0<q;){var V=q-1>>>1,D=H[V];if(0<s(D,z))H[V]=z,H[q]=D,q=V;else break e}}function n(H){return H.length===0?null:H[0]}function r(H){if(H.length===0)return null;var z=H[0],q=H.pop();if(q!==z){H[0]=q;e:for(var V=0,D=H.length,G=D>>>1;V<G;){var U=2*(V+1)-1,P=H[U],B=U+1,Z=H[B];if(0>s(P,q))B<D&&0>s(Z,P)?(H[V]=Z,H[B]=q,V=B):(H[V]=P,H[U]=q,V=U);else if(B<D&&0>s(Z,q))H[V]=Z,H[B]=q,V=B;else break e}}return z}function s(H,z){var q=H.sortIndex-z.sortIndex;return q!==0?q:H.id-z.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,v=!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 z=n(u);z!==null;){if(z.callback===null)r(u);else if(z.startTime<=H)r(u),z.sortIndex=z.expirationTime,t(c,z);else break;z=n(u)}}function _(H){if(v=!1,k(H),!m)if(n(c)!==null)m=!0,C||(C=!0,R());else{var z=n(u);z!==null&&F(_,z.startTime-H)}}var C=!1,T=-1,E=5,N=-1;function I(){return y?!0:!(e.unstable_now()-N<E)}function A(){if(y=!1,C){var H=e.unstable_now();N=H;var z=!0;try{e:{m=!1,v&&(v=!1,x(T),T=-1),h=!0;var q=p;try{t:{for(k(H),f=n(c);f!==null&&!(f.expirationTime>H&&I());){var V=f.callback;if(typeof V=="function"){f.callback=null,p=f.priorityLevel;var D=V(f.expirationTime<=H);if(H=e.unstable_now(),typeof D=="function"){f.callback=D,k(H),z=!0;break t}f===n(c)&&r(c),k(H)}else r(c);f=n(c)}if(f!==null)z=!0;else{var G=n(u);G!==null&&F(_,G.startTime-H),z=!1}}break e}finally{f=null,p=q,h=!1}z=void 0}}finally{z?R():C=!1}}}var R;if(typeof S=="function")R=function(){S(A)};else if(typeof MessageChannel<"u"){var L=new MessageChannel,M=L.port2;L.port1.onmessage=A,R=function(){M.postMessage(null)}}else R=function(){b(A,0)};function F(H,z){T=b(function(){H(e.unstable_now())},z)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(H){H.callback=null},e.unstable_forceFrameRate=function(H){0>H||125<H?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):E=0<H?Math.floor(1e3/H):5},e.unstable_getCurrentPriorityLevel=function(){return p},e.unstable_next=function(H){switch(p){case 1:case 2:case 3:var z=3;break;default:z=p}var q=p;p=z;try{return H()}finally{p=q}},e.unstable_requestPaint=function(){y=!0},e.unstable_runWithPriority=function(H,z){switch(H){case 1:case 2:case 3:case 4:case 5:break;default:H=3}var q=p;p=H;try{return z()}finally{p=q}},e.unstable_scheduleCallback=function(H,z,q){var V=e.unstable_now();switch(typeof q=="object"&&q!==null?(q=q.delay,q=typeof q=="number"&&0<q?V+q:V):q=V,H){case 1:var D=-1;break;case 2:D=250;break;case 5:D=1073741823;break;case 4:D=1e4;break;default:D=5e3}return D=q+D,H={id:d++,callback:z,priorityLevel:H,startTime:q,expirationTime:D,sortIndex:-1},q>V?(H.sortIndex=q,t(u,H),n(c)===null&&H===n(u)&&(v?(x(T),T=-1):v=!0,F(_,q-V))):(H.sortIndex=D,t(c,H),m||h||(m=!0,C||(C=!0,R()))),H},e.unstable_shouldYield=I,e.unstable_wrapCallback=function(H){var z=p;return function(){var q=p;p=z;try{return H.apply(this,arguments)}finally{p=q}}}})(wX)),wX}var mMe;function HGt(){return mMe||(mMe=1,xX.exports=VGt()),xX.exports}var SX={exports:{}},Iu={};var gMe;function WGt(){if(gMe)return Iu;gMe=1;var e=eI();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 Iu.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,Iu.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)},Iu.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()}},Iu.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))},Iu.prefetchDNS=function(c){typeof c=="string"&&r.d.D(c)},Iu.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})}},Iu.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)},Iu.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})}},Iu.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)},Iu.requestFormReset=function(c){r.d.r(c)},Iu.unstable_batchedUpdates=function(c,u){return c(u)},Iu.useFormState=function(c,u,d){return i.H.useFormState(c,u,d)},Iu.useFormStatus=function(){return i.H.useHostTransitionStatus()},Iu.version="19.2.7",Iu}var vMe;function Jlt(){if(vMe)return SX.exports;vMe=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(),SX.exports=WGt(),SX.exports}var yMe;function ZGt(){if(yMe)return cR;yMe=1;var e={env:{}};var t=HGt(),n=eI(),r=Jlt();function s(w){var O="https://react.dev/errors/"+w;if(1<arguments.length){O+="?args[]="+encodeURIComponent(arguments[1]);for(var j=2;j<arguments.length;j++)O+="&args[]="+encodeURIComponent(arguments[j])}return"Minified React error #"+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,j=w;if(w.alternate)for(;O.return;)O=O.return;else{w=O;do O=w,(O.flags&4098)!==0&&(j=O.return),w=O.return;while(w)}return O.tag===3?j: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 j=w,$=O;;){var W=j.return;if(W===null)break;var Q=W.alternate;if(Q===null){if($=W.return,$!==null){j=$;continue}break}if(W.child===Q.child){for(Q=W.child;Q;){if(Q===j)return u(W),w;if(Q===$)return u(W),O;Q=Q.sibling}throw Error(s(188))}if(j.return!==$.return)j=W,$=Q;else{for(var ie=!1,ke=W.child;ke;){if(ke===j){ie=!0,j=W,$=Q;break}if(ke===$){ie=!0,$=W,j=Q;break}ke=ke.sibling}if(!ie){for(ke=Q.child;ke;){if(ke===j){ie=!0,j=Q,$=W;break}if(ke===$){ie=!0,$=Q,j=W;break}ke=ke.sibling}if(!ie)throw Error(s(189))}}if(j.alternate!==$)throw Error(s(190))}if(j.tag!==3)throw Error(s(188));return j.stateNode.current===j?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"),v=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"),T=Symbol.for("react.suspense_list"),E=Symbol.for("react.memo"),N=Symbol.for("react.lazy"),I=Symbol.for("react.activity"),A=Symbol.for("react.memo_cache_sentinel"),R=Symbol.iterator;function L(w){return w===null||typeof w!="object"?null:(w=R&&w[R]||w["@@iterator"],typeof w=="function"?w:null)}var M=Symbol.for("react.client.reference");function F(w){if(w==null)return null;if(typeof w=="function")return w.$$typeof===M?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 T:return"SuspenseList";case I:return"Activity"}if(typeof w=="object")switch(w.$$typeof){case v: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 E:return O=w.displayName||null,O!==null?O:F(w.type)||"Memo";case N:O=w._payload,w=w._init;try{return F(w(O))}catch{}}return null}var H=Array.isArray,z=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,q=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,V={pending:!1,data:null,method:null,action:null},D=[],G=-1;function U(w){return{current:w}}function P(w){0>G||(w.current=D[G],D[G]=null,G--)}function B(w,O){G++,D[G]=w.current,w.current=O}var Z=U(null),Y=U(null),te=U(null),J=U(null);function ee(w,O){switch(B(te,O),B(Y,w),B(Z,null),O.nodeType){case 9:case 11:w=(w=O.documentElement)&&(w=w.namespaceURI)?R2e(w):0;break;default:if(w=O.tagName,O=O.namespaceURI)O=R2e(O),w=P2e(O,w);else switch(w){case"svg":w=1;break;case"math":w=2;break;default:w=0}}P(Z),B(Z,w)}function re(){P(Z),P(Y),P(te)}function oe(w){w.memoizedState!==null&&B(J,w);var O=Z.current,j=P2e(O,w.type);O!==j&&(B(Y,w),B(Z,j))}function X(w){Y.current===w&&(P(Z),P(Y)),J.current===w&&(P(J),sR._currentValue=V)}var ne,se;function fe(w){if(ne===void 0)try{throw Error()}catch(j){var O=j.stack.trim().match(/\n( *(at )?)/);ne=O&&O[1]||"",se=-1<j.stack.indexOf(`
|
|
3
3
|
at`)?" (<anonymous>)":-1<j.stack.indexOf("@")?"@unknown:0:0":""}return`
|
|
4
4
|
`+ne+w+se}var ce=!1;function xe(w,O){if(!w||ce)return"";ce=!0;var j=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var $={DetermineComponentFrameRoot:function(){try{if(O){var At=function(){throw Error()};if(Object.defineProperty(At.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(At,[])}catch(gt){var ct=gt}Reflect.construct(w,[],At)}else{try{At.call()}catch(gt){ct=gt}w.call(At.prototype)}}else{try{throw Error()}catch(gt){ct=gt}(At=w())&&typeof At.catch=="function"&&At.catch(function(){})}}catch(gt){if(gt&&ct&&typeof gt.stack=="string")return[gt.stack,ct.stack]}return[null,null]}};$.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var W=Object.getOwnPropertyDescriptor($.DetermineComponentFrameRoot,"name");W&&W.configurable&&Object.defineProperty($.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var Q=$.DetermineComponentFrameRoot(),ie=Q[0],ke=Q[1];if(ie&&ke){var Ue=ie.split(`
|
|
@@ -103,7 +103,7 @@ ${n}
|
|
|
103
103
|
`);l!=="[DONE]"&&a.enqueue(JSON.parse(l))},r=s=>{let a=o3e.exec(t);for(;a;)n(t.slice(0,a.index),s),t=t.slice(a.index+a[0].length),a=o3e.exec(t)};return new TransformStream({transform(s,a){t+=e.decode(s,{stream:!0}),r(a)},flush(s){t+=e.decode(),r(s),t&&n(t,s)}})}function w6(e){return e.status==="failed"&&e.error&&(e.error=GV(e.error,{fallbackMessage:"Unknown workflow error",supportSerialization:!1})),e}var Shn=class extends Ha{workflowId;runId;constructor(e,t,n){super(e),this.workflowId=t,this.runId=n}createChunkTransformStream(){return apt()}cancelRun(){return this.request(`/workflows/${this.workflowId}/runs/${this.runId}/cancel`,{method:"POST"})}cancel(){return this.request(`/workflows/${this.workflowId}/runs/${this.runId}/cancel`,{method:"POST"})}start(e){const t=lr(e.requestContext);return this.request(`/workflows/${this.workflowId}/start?runId=${this.runId}`,{method:"POST",body:{inputData:e?.inputData,initialState:e?.initialState,requestContext:t,tracingOptions:e.tracingOptions,perStep:e.perStep}})}resume({step:e,resumeData:t,tracingOptions:n,perStep:r,forEachIndex:s,...a}){const i=lr(a.requestContext);return this.request(`/workflows/${this.workflowId}/resume?runId=${this.runId}`,{method:"POST",body:{step:e,resumeData:t,requestContext:i,tracingOptions:n,perStep:r,forEachIndex:s}})}startAsync(e){const t=new URLSearchParams;t.set("runId",this.runId);const n=lr(e.requestContext);return this.request(`/workflows/${this.workflowId}/start-async?${t.toString()}`,{method:"POST",body:{inputData:e.inputData,initialState:e.initialState,requestContext:n,tracingOptions:e.tracingOptions,resourceId:e.resourceId,perStep:e.perStep}}).then(w6)}async stream(e){const t=new URLSearchParams;t.set("runId",this.runId);const n=lr(e.requestContext),r=await this.request(`/workflows/${this.workflowId}/stream?${t.toString()}`,{method:"POST",body:{inputData:e.inputData,initialState:e.initialState,requestContext:n,tracingOptions:e.tracingOptions,resourceId:e.resourceId,perStep:e.perStep,closeOnSuspend:e.closeOnSuspend},stream:!0});if(!r.ok)throw new Error(`Failed to stream workflow: ${r.statusText}`);if(!r.body)throw new Error("Response body is null");return r.body.pipeThrough(this.createChunkTransformStream())}async observe(e){const t=new URLSearchParams;t.set("runId",this.runId),e?.offset!==void 0&&t.set("offset",String(e.offset));const n=await this.request(`/workflows/${this.workflowId}/observe?${t.toString()}`,{method:"POST",stream:!0});if(!n.ok)throw new Error(`Failed to observe workflow stream: ${n.statusText}`);if(!n.body)throw new Error("Response body is null");return n.body.pipeThrough(this.createChunkTransformStream())}async observeStream(){return this.observe()}resumeAsync(e){const t=lr(e.requestContext);return this.request(`/workflows/${this.workflowId}/resume-async?runId=${this.runId}`,{method:"POST",body:{step:e.step,resumeData:e.resumeData,requestContext:t,tracingOptions:e.tracingOptions,perStep:e.perStep,forEachIndex:e.forEachIndex}}).then(w6)}resumeNoWait(e){const t=lr(e.requestContext);return this.request(`/workflows/${this.workflowId}/resume-no-wait?runId=${this.runId}`,{method:"POST",body:{step:e.step,resumeData:e.resumeData,requestContext:t,tracingOptions:e.tracingOptions,perStep:e.perStep,forEachIndex:e.forEachIndex}})}async resumeStream(e){const t=new URLSearchParams;t.set("runId",this.runId);const n=lr(e.requestContext),r=await this.request(`/workflows/${this.workflowId}/resume-stream?${t.toString()}`,{method:"POST",body:{step:e.step,resumeData:e.resumeData,requestContext:n,tracingOptions:e.tracingOptions,perStep:e.perStep,forEachIndex:e.forEachIndex},stream:!0});if(!r.ok)throw new Error(`Failed to stream vNext workflow: ${r.statusText}`);if(!r.body)throw new Error("Response body is null");return r.body.pipeThrough(this.createChunkTransformStream())}restart(e){const t=lr(e.requestContext);return this.request(`/workflows/${this.workflowId}/restart?runId=${this.runId}`,{method:"POST",body:{requestContext:t,tracingOptions:e.tracingOptions}})}restartAsync(e){const t=lr(e?.requestContext);return this.request(`/workflows/${this.workflowId}/restart-async?runId=${this.runId}`,{method:"POST",body:{requestContext:t,tracingOptions:e?.tracingOptions}}).then(w6)}timeTravel({requestContext:e,...t}){const n=lr(e);return this.request(`/workflows/${this.workflowId}/time-travel?runId=${this.runId}`,{method:"POST",body:{...t,requestContext:n}})}timeTravelAsync({requestContext:e,...t}){const n=lr(e);return this.request(`/workflows/${this.workflowId}/time-travel-async?runId=${this.runId}`,{method:"POST",body:{...t,requestContext:n}}).then(w6)}async timeTravelStream({requestContext:e,...t}){const n=lr(e),r=await this.request(`/workflows/${this.workflowId}/time-travel-stream?runId=${this.runId}`,{method:"POST",body:{...t,requestContext:n},stream:!0});if(!r.ok)throw new Error(`Failed to time travel workflow: ${r.statusText}`);if(!r.body)throw new Error("Response body is null");return r.body.pipeThrough(this.createChunkTransformStream())}};const khn="";var Ohn=class extends Ha{workflowId;constructor(t,n){super(t),this.workflowId=n}details(t){return this.request(`/workflows/${this.workflowId}${sn(t)}`)}runs(t,n){const r=vw(lr(n)),s=new URLSearchParams;return t?.fromDate&&s.set("fromDate",t.fromDate.toISOString()),t?.toDate&&s.set("toDate",t.toDate.toISOString()),t?.page!==void 0&&s.set("page",String(t.page)),t?.perPage!==void 0&&s.set("perPage",String(t.perPage)),t?.limit!==null&&t?.limit!==void 0&&(t.limit===!1?s.set("limit","false"):typeof t.limit=="number"&&t.limit>0&&Number.isInteger(t.limit)&&s.set("limit",String(t.limit))),t?.offset!==null&&t?.offset!==void 0&&!isNaN(Number(t?.offset))&&s.set("offset",String(t.offset)),t?.resourceId&&s.set("resourceId",t.resourceId),t?.status&&s.set("status",t.status),r&&s.set("requestContext",r),s.size?this.request(`/workflows/${this.workflowId}/runs?${s}`):this.request(`/workflows/${this.workflowId}/runs`)}runById(t,n){const r=new URLSearchParams;n?.fields&&n.fields.length>0&&r.set("fields",n.fields.join(",")),n?.withNestedWorkflows!==void 0&&r.set("withNestedWorkflows",String(n.withNestedWorkflows));const s=vw(lr(n?.requestContext));s&&r.set("requestContext",s);const a=r.size>0?`?${r.toString()}`:"";return this.request(`/workflows/${this.workflowId}/runs/${t}${a}`)}deleteRunById(t){return this.request(`/workflows/${this.workflowId}/runs/${t}`,{method:"DELETE"})}async getSchema(){const t=await this.details();return{inputSchema:t.inputSchema?s3e(t.inputSchema):null,outputSchema:t.outputSchema?s3e(t.outputSchema):null}}async createRun(t){const n=new URLSearchParams;t?.runId&&n.set("runId",t.runId);const r=await this.request(`/workflows/${this.workflowId}/create-run?${n.toString()}`,{method:"POST",body:{resourceId:t?.resourceId,disableScorers:t?.disableScorers}});return new Shn(this.options,this.workflowId,r.runId)}static createRecordStream(t){const n=new TextEncoder;return new ReadableStream({async start(r){try{for await(const s of t){const a=JSON.stringify(s)+khn;r.enqueue(n.encode(a))}r.close()}catch(s){r.error(s)}}})}};function _hn(e){const t=e.replace(/\x1E/g,`
|
|
104
104
|
|
|
105
105
|
`),n=t.match(/\r?\n\r?\n/);if(!n||n.index===void 0)return{rest:t};const r=n[0].length;return{eventBlock:t.slice(0,n.index),rest:t.slice(n.index+r)}}function l3e(e){const t=e.trim();if(!t)return{};const n=t.split(/\r?\n/).filter(a=>a.startsWith("data:")).map(a=>a.slice(5).trimStart()),r=n.length>0?n.join(`
|
|
106
|
-
`):t;if(!r||r==="[DONE]")return{done:!0};let s;try{s=JSON.parse(r)}catch(a){throw new Error(`Failed to parse A2A stream event: ${a instanceof Error?a.message:"unknown parse error"}`)}if(s&&typeof s=="object"&&"error"in s&&s.error)throw new Cx(200,"OK",`A2A stream error - ${JSON.stringify(s.error)}`,s.error);return s&&typeof s=="object"&&"result"in s?{event:s.result}:{event:s}}async function*f7(e){const t=e.getReader(),n=new TextDecoder;let r="";try{for(;;){const{done:s,value:a}=await t.read();for(s?r+=n.decode():r+=n.decode(a,{stream:!0});;){const{eventBlock:i,rest:l}=_hn(r);if(r=l,!i)break;const c=l3e(i);if(c.done)return;c.event&&(yield c.event)}if(s)break}if(r.trim()){const s=l3e(r);!s.done&&s.event&&(yield s.event)}}finally{t.releaseLock()}}const Chn=["ES256","ES384","ES512","RS256","RS384","RS512","PS256","PS384","PS512"];function Ehn(e){const t=structuredClone(e);return delete t.signatures,t}function Thn(e){const t=globalThis.CryptoKey;return typeof t<"u"&&e instanceof t}function jhn(e){return e.includes("-----BEGIN ")}function Nhn(e){return e.includes("-----BEGIN CERTIFICATE-----")}async function Ihn(e,t){if(Thn(e)||e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(typeof e=="string"){if(t.startsWith("HS"))return new TextEncoder().encode(e);if(!jhn(e))throw new Error("Expected a PEM-encoded public key or certificate string for Agent Card verification");return Nhn(e)?Cpn(e,t):_pn(e,t)}return Epn(e,t)}async function Ahn(e,t){const n=e.signatures??[];if(n.length===0)return e;const r=Qpn(Ehn(e));if(!r)throw new Cx(200,"OK","Failed to canonicalize A2A Agent Card for signature verification");const s=t.algorithms??[...Chn],a=Kfn(r),i=[];for(const[l,c]of n.entries())try{const u=`${c.protected}.${a}.${c.signature}`,d=$pn(u);if(typeof d.alg!="string")throw new Error('Agent Card signature is missing a protected "alg" header');if(!s.includes(d.alg))throw new Error(`Agent Card signature algorithm "${d.alg}" is not allowed`);const f=await t.keyProvider({agentCard:e,signature:c,protectedHeader:d,alg:d.alg,kid:typeof d.kid=="string"?d.kid:void 0,jku:typeof d.jku=="string"?d.jku:void 0,index:l});if(!f)throw new Error("No verification key was provided for Agent Card signature verification");return await Ppn(u,await Ihn(f,d.alg),{algorithms:s}),e}catch(u){i.push(u instanceof Error?u.message:"Unknown verification failure")}throw new Cx(200,"OK",`A2A Agent Card signature verification failed: ${i.join("; ")}`)}function Rhn(e){const t=e.error,n=t?.message??"Unknown A2A JSON-RPC error";return typeof t?.code=="number"?new Qfn(t.code,n,t.data):new Cx(200,"OK",`A2A JSON-RPC error - ${n}`,t)}function YE(e){if("error"in e&&e.error)throw Rhn(e);if("result"in e)return e.result;throw new Cx(200,"OK","A2A JSON-RPC response did not include a result",e)}async function p7(e,t){if(e.body)return e.body;const n=Array.from(e.headers.entries()).map(([a,i])=>`${a}: ${i}`).join(", ");let r="";try{r=await e.text()}catch{}const s=[`A2A ${t} stream response did not include a body`,`(status: ${e.status} ${e.statusText})`,n?`headers: ${n}`:"",r?`body: ${r}`:""].filter(Boolean).join(" ");throw new Cx(e.status,e.statusText,s)}var Phn=class extends Ha{agentId;constructor(e,t){super(e),this.agentId=t}async getAgentCard(e){const t=await this.request(`/.well-known/${this.agentId}/agent-card.json`);return e?.verifySignature?Ahn(t,e.verifySignature):t}async getCard(e){return this.getAgentCard(e)}async getExtendedAgentCard(){return YE(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"agent/getAuthenticatedExtendedCard"}}))}async sendMessage(e){return this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"message/send",params:e}})}async*sendMessageStream(e){yield*f7(await p7(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"message/stream",params:e},stream:!0}),"message/stream"))}async sendStreamingMessage(e){return this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"message/stream",params:e},stream:!0})}async getTask(e){return this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/get",params:e}})}async cancelTask(e){return this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/cancel",params:e}})}async*resubscribeTask(e){yield*f7(await p7(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/resubscribe",params:e},stream:!0}),"tasks/resubscribe"))}async setTaskPushNotificationConfig(e){return YE(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/pushNotificationConfig/set",params:e}}))}async getTaskPushNotificationConfig(e){return YE(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/pushNotificationConfig/get",params:e}}))}async listTaskPushNotificationConfig(e){return YE(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/pushNotificationConfig/list",params:e}}))}async deleteTaskPushNotificationConfig(e){YE(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/pushNotificationConfig/delete",params:e}}))}},$hn=class extends Ha{agentId;constructor(e,t){super(e),this.agentId=t}async rpc(e,t){return YE(await this.request(`/a2a/${this.agentId}`,{method:"POST",headers:{"A2A-Version":"1.0"},body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:e,params:t}}))}async getAgentCard(){const e=await this.request(`/.well-known/${this.agentId}/agent-card.json`,{headers:{"A2A-Version":"1.0"}});return Lpn.fromJSON(e)}async sendMessage(e){const t=await this.rpc("message/send",e3e.toJSON(e));return Vpn.fromJSON(t)}async*sendMessageStream(e){const t=await this.request(`/a2a/${this.agentId}`,{method:"POST",headers:{"A2A-Version":"1.0"},body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"message/stream",params:e3e.toJSON(e)},stream:!0});for await(const n of f7(await p7(t,"message/stream")))yield t3e.fromJSON(n)}async getTask(e){const t=await this.rpc("tasks/get",Fpn.toJSON(e));return f1.fromJSON(t)}async listTasks(e){const t=await this.rpc("tasks/list",zpn.toJSON(e));return Bpn.fromJSON(t)}async cancelTask(e){const t=await this.rpc("tasks/cancel",Upn.toJSON(e));return f1.fromJSON(t)}async*resubscribeTask(e){const t=await this.request(`/a2a/${this.agentId}`,{method:"POST",headers:{"A2A-Version":"1.0"},body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/resubscribe",params:qpn.toJSON(e)},stream:!0});for await(const n of f7(await p7(t,"tasks/resubscribe")))yield t3e.fromJSON(n)}},Mhn=class extends Ha{serverId;toolId;constructor(e,t,n){super(e),this.serverId=t,this.toolId=n}details(e){return this.request(`/mcp/${encodeURIComponent(this.serverId)}/tools/${encodeURIComponent(this.toolId)}${sn(e)}`)}execute(e){const t={};return e.data!==void 0&&(t.data=e.data),e.requestContext!==void 0&&(t.requestContext=e.requestContext),this.request(`/mcp/${encodeURIComponent(this.serverId)}/tools/${encodeURIComponent(this.toolId)}/execute`,{method:"POST",body:t})}},Dhn=class extends Ha{actionId;constructor(e,t){super(e),this.actionId=t}transformWorkflowResult(e){return e.status==="success"?{success:e.result.success||!1,applied:e.result.applied||!1,branchName:e.result.branchName,message:e.result.message||"Agent builder action completed",validationResults:e.result.validationResults,error:e.result.error,errors:e.result.errors,stepResults:e.result.stepResults}:e.status==="failed"?{success:!1,applied:!1,message:`Agent builder action failed: ${e.error.message}`,error:e.error.message}:{success:!1,applied:!1,message:"Agent builder action was suspended",error:"Workflow suspended - manual intervention required"}}createRecordParserTransform(){return apt()}async createRun(e){const t=new URLSearchParams;e?.runId&&t.set("runId",e.runId);const n=`/agent-builder/${this.actionId}/create-run${t.toString()?`?${t.toString()}`:""}`;return this.request(n,{method:"POST"})}async startAsync(e,t){const n=new URLSearchParams;t&&n.set("runId",t);const r=lr(e.requestContext),{requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/start-async${n.toString()?`?${n.toString()}`:""}`,l=await this.request(i,{method:"POST",body:{...a,requestContext:r}});return this.transformWorkflowResult(l)}async startActionRun(e,t){const n=new URLSearchParams;n.set("runId",t);const r=lr(e.requestContext),{requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/start?${n.toString()}`;return this.request(i,{method:"POST",body:{...a,requestContext:r}})}async resume(e,t){const n=new URLSearchParams;n.set("runId",t);const r=lr(e.requestContext),{requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/resume?${n.toString()}`;return this.request(i,{method:"POST",body:{...a,requestContext:r}})}async resumeAsync(e,t){const n=new URLSearchParams;n.set("runId",t);const r=lr(e.requestContext),{requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/resume-async?${n.toString()}`,l=await this.request(i,{method:"POST",body:{...a,requestContext:r}});return this.transformWorkflowResult(l)}async stream(e,t){if(!t)throw new Error("runId is required to stream an agent builder action");const n=new URLSearchParams;n.set("runId",t);const r=lr(e.requestContext),{requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/stream?${n.toString()}`,l=await this.request(i,{method:"POST",body:{...a,requestContext:r},stream:!0});if(!l.ok)throw new Error(`Failed to stream agent builder action: ${l.statusText}`);if(!l.body)throw new Error("Response body is null");return l.body.pipeThrough(this.createRecordParserTransform())}async observeStream(e){const t=new URLSearchParams;t.set("runId",e.runId);const n=`/agent-builder/${this.actionId}/observe?${t.toString()}`,r=await this.request(n,{method:"POST",stream:!0});if(!r.ok)throw new Error(`Failed to observe agent builder action stream: ${r.statusText}`);if(!r.body)throw new Error("Response body is null");return r.body.pipeThrough(this.createRecordParserTransform())}async observeStreamLegacy(e){const t=new URLSearchParams;t.set("runId",e.runId);const n=`/agent-builder/${this.actionId}/observe-stream-legacy?${t.toString()}`,r=await this.request(n,{method:"POST",stream:!0});if(!r.ok)throw new Error(`Failed to observe agent builder action stream legacy: ${r.statusText}`);if(!r.body)throw new Error("Response body is null");return r.body.pipeThrough(this.createRecordParserTransform())}async resumeStream(e){const t=new URLSearchParams;t.set("runId",e.runId);const n=lr(e.requestContext),{runId:r,requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/resume-stream?${t.toString()}`,l=await this.request(i,{method:"POST",body:{...a,requestContext:n},stream:!0});if(!l.ok)throw new Error(`Failed to resume agent builder action stream: ${l.statusText}`);if(!l.body)throw new Error("Response body is null");return l.body.pipeThrough(this.createRecordParserTransform())}async runById(e,t){const n=new URLSearchParams;t?.fields&&t.fields.length>0&&n.set("fields",t.fields.join(",")),t?.withNestedWorkflows!==void 0&&n.set("withNestedWorkflows",String(t.withNestedWorkflows));const r=n.size>0?`?${n.toString()}`:"",s=`/agent-builder/${this.actionId}/runs/${e}${r}`;return this.request(s,{method:"GET"})}async details(){return await this.request(`/agent-builder/${this.actionId}`)}async runs(e){const t=new URLSearchParams;e?.fromDate&&t.set("fromDate",e.fromDate.toISOString()),e?.toDate&&t.set("toDate",e.toDate.toISOString()),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.page!==void 0&&t.set("page",String(e.page)),e?.limit!==null&&e?.limit!==void 0&&(e.limit===!1?t.set("limit","false"):typeof e.limit=="number"&&e.limit>0&&Number.isInteger(e.limit)&&t.set("limit",String(e.limit))),e?.offset!==null&&e?.offset!==void 0&&!isNaN(Number(e?.offset))&&t.set("offset",String(e.offset)),e?.resourceId&&t.set("resourceId",e.resourceId);const n=`/agent-builder/${this.actionId}/runs${t.toString()?`?${t.toString()}`:""}`;return this.request(n,{method:"GET"})}async cancelRun(e){const t=`/agent-builder/${this.actionId}/runs/${e}/cancel`;return this.request(t,{method:"POST"})}},Lhn=class extends Ha{constructor(e){super(e)}getTrace(e){return this.request(`/observability/traces/${e}`)}getTraceLight(e){return this.request(`/observability/traces/${e}/light`)}getSpan(e,t){return this.request(`/observability/traces/${e}/spans/${t}`)}getTraceTrajectory(e){return this.request(`/observability/traces/${e}/trajectory`)}getTraces(e){const{pagination:t,filters:n}=e,{page:r,perPage:s,dateRange:a}=t||{},{name:i,spanType:l,entityId:c,entityType:u}=n||{},d=new URLSearchParams;if(r!==void 0&&d.set("page",String(r)),s!==void 0&&d.set("perPage",String(s)),i&&d.set("name",i),l!==void 0&&d.set("spanType",String(l)),c&&u&&(d.set("entityId",c),d.set("entityType",u)),a){const p=JSON.stringify({start:a.start instanceof Date?a.start.toISOString():a.start,end:a.end instanceof Date?a.end.toISOString():a.end});d.set("dateRange",p)}const f=d.toString();return this.request(`/observability/traces${f?`?${f}`:""}`)}listTraces(e={}){const t=uf(e,["filters","pagination","orderBy"]);return this.request(`/observability/traces${t?`?${t}`:""}`)}listTracesLight(e={}){const t=uf(e,["filters","pagination","orderBy"]);return this.request(`/observability/traces/light${t?`?${t}`:""}`)}listBranches(e={}){const t=uf(e,["filters","pagination","orderBy"]);return this.request(`/observability/branches${t?`?${t}`:""}`)}getBranch(e){const{traceId:t,spanId:n,depth:r}=e,s=r!==void 0?`?depth=${r}`:"";return this.request(`/observability/traces/${encodeURIComponent(t)}/branches/${encodeURIComponent(n)}${s}`)}listScoresBySpan(e){const{traceId:t,spanId:n,...r}=e,s=uf(r);return this.request(`/observability/traces/${encodeURIComponent(t)}/${encodeURIComponent(n)}/scores${s?`?${s}`:""}`)}score(e){return this.request("/observability/traces/score",{method:"POST",body:{...e}})}listLogs(e={}){const t=uf(e,["filters","pagination","orderBy"]);return this.request(`/observability/logs${t?`?${t}`:""}`)}listScores(e={}){const t=uf(e,["filters","pagination","orderBy"]);return this.request(`/observability/scores${t?`?${t}`:""}`)}createScore(e){return this.request("/observability/scores",{method:"POST",body:e})}getScoreAggregate(e){return this.request("/observability/scores/aggregate",{method:"POST",body:e})}getScoreBreakdown(e){return this.request("/observability/scores/breakdown",{method:"POST",body:e})}getScoreTimeSeries(e){return this.request("/observability/scores/timeseries",{method:"POST",body:e})}getScorePercentiles(e){return this.request("/observability/scores/percentiles",{method:"POST",body:e})}listFeedback(e={}){const t=uf(e,["filters","pagination","orderBy"]);return this.request(`/observability/feedback${t?`?${t}`:""}`)}createFeedback(e){return this.request("/observability/feedback",{method:"POST",body:e})}updateFeedbackReviewStatus(e){return this.request(`/observability/feedback/${encodeURIComponent(e.feedbackId)}/review-status`,{method:"PATCH",body:{reviewStatus:e.reviewStatus}})}getFeedbackAggregate(e){return this.request("/observability/feedback/aggregate",{method:"POST",body:e})}getFeedbackBreakdown(e){return this.request("/observability/feedback/breakdown",{method:"POST",body:e})}getFeedbackTimeSeries(e){return this.request("/observability/feedback/timeseries",{method:"POST",body:e})}getFeedbackPercentiles(e){return this.request("/observability/feedback/percentiles",{method:"POST",body:e})}getMetricAggregate(e){return this.request("/observability/metrics/aggregate",{method:"POST",body:e})}getMetricBreakdown(e){return this.request("/observability/metrics/breakdown",{method:"POST",body:e})}getMetricTimeSeries(e){return this.request("/observability/metrics/timeseries",{method:"POST",body:e})}getMetricPercentiles(e){return this.request("/observability/metrics/percentiles",{method:"POST",body:e})}getMetricNames(e={}){const t=uf(e);return this.request(`/observability/discovery/metric-names${t?`?${t}`:""}`)}getMetricLabelKeys(e){const t=uf(e);return this.request(`/observability/discovery/metric-label-keys${t?`?${t}`:""}`)}getMetricLabelValues(e){const t=uf(e);return this.request(`/observability/discovery/metric-label-values${t?`?${t}`:""}`)}getEntityTypes(){return this.request("/observability/discovery/entity-types")}getEntityNames(e={}){const t=uf(e);return this.request(`/observability/discovery/entity-names${t?`?${t}`:""}`)}getServiceNames(){return this.request("/observability/discovery/service-names")}getEnvironments(){return this.request("/observability/discovery/environments")}getTags(e={}){const t=uf(e);return this.request(`/observability/discovery/tags${t?`?${t}`:""}`)}},Fhn=class extends Ha{storedAgentId;constructor(e,t){super(e),this.storedAgentId=t}details(e,t){const n=sn(e),r=t?.status?`status=${t.status}`:"",s=`/stored/agents/${encodeURIComponent(this.storedAgentId)}${n}${r?`${n?"&":"?"}${r}`:""}`;return this.request(s)}update(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}${sn(t)}`,{method:"PATCH",body:e})}export(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/export`,{method:"POST",body:e})}openChangeRequest(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/change-request`,{method:"POST",body:e})}delete(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}${sn(e)}`,{method:"DELETE"})}dependents(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/dependents${sn(e)}`)}favorite(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/favorite${sn(e)}`,{method:"PUT"})}unfavorite(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/favorite${sn(e)}`,{method:"DELETE"})}listVersions(e,t){const n=new URLSearchParams;e?.page!==void 0&&n.set("page",String(e.page)),e?.perPage!==void 0&&n.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&n.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&n.set("orderBy[direction]",e.orderBy.direction));const r=n.toString(),s=sn(t);return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions${r?`?${r}`:""}${s?`${r?"&":"?"}${s.slice(1)}`:""}`)}createVersion(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions${sn(t)}`,{method:"POST",body:e||{}})}getVersion(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions/${encodeURIComponent(e)}${sn(t)}`)}activateVersion(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions/${encodeURIComponent(e)}/activate${sn(t)}`,{method:"POST"})}restoreVersion(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions/${encodeURIComponent(e)}/restore${sn(t)}`,{method:"POST"})}deleteVersion(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions/${encodeURIComponent(e)}${sn(t)}`,{method:"DELETE"})}compareVersions(e,t,n){const r=new URLSearchParams;r.set("from",e),r.set("to",t);const s=sn(n);return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions/compare?${r.toString()}${s?`&${s.slice(1)}`:""}`)}},zhn=class extends Ha{dynamicWorkflowId;constructor(e,t){super(e),this.dynamicWorkflowId=t}details(){return this.request(`/stored/workflows/${encodeURIComponent(this.dynamicWorkflowId)}`)}delete(){return this.request(`/stored/workflows/${encodeURIComponent(this.dynamicWorkflowId)}`,{method:"DELETE"})}},Bhn=class extends Ha{storedPromptBlockId;constructor(e,t){super(e),this.storedPromptBlockId=t}details(e,t){const n=sn(e),r=t?.status?`status=${t.status}`:"",s=`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}${n}${r?`${n?"&":"?"}${r}`:""}`;return this.request(s)}update(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}${sn(t)}`,{method:"PATCH",body:e})}delete(e){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}${sn(e)}`,{method:"DELETE"})}listVersions(e,t){const n=new URLSearchParams;e?.page!==void 0&&n.set("page",String(e.page)),e?.perPage!==void 0&&n.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&n.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&n.set("orderBy[direction]",e.orderBy.direction));const r=n.toString(),s=sn(t,r?"&":"?");return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions${r?`?${r}`:""}${s}`)}createVersion(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions${sn(t)}`,{method:"POST",body:e||{}})}getVersion(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions/${encodeURIComponent(e)}${sn(t)}`)}activateVersion(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions/${encodeURIComponent(e)}/activate${sn(t)}`,{method:"POST"})}restoreVersion(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions/${encodeURIComponent(e)}/restore${sn(t)}`,{method:"POST"})}deleteVersion(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions/${encodeURIComponent(e)}${sn(t)}`,{method:"DELETE"})}compareVersions(e,t,n){const r=new URLSearchParams;r.set("from",e),r.set("to",t);const s=sn(n,"&");return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions/compare?${r.toString()}${s}`)}},Uhn=class extends Ha{storedMCPClientId;constructor(e,t){super(e),this.storedMCPClientId=t}details(e){return this.request(`/stored/mcp-clients/${encodeURIComponent(this.storedMCPClientId)}${sn(e)}`)}update(e,t){return this.request(`/stored/mcp-clients/${encodeURIComponent(this.storedMCPClientId)}${sn(t)}`,{method:"PATCH",body:e})}delete(e){return this.request(`/stored/mcp-clients/${encodeURIComponent(this.storedMCPClientId)}${sn(e)}`,{method:"DELETE"})}},qhn=class extends Ha{storedScorerId;constructor(e,t){super(e),this.storedScorerId=t}details(e,t){const n=sn(e),r=t?.status?`status=${t.status}`:"",s=n?"&":"?",a=`/stored/scorers/${encodeURIComponent(this.storedScorerId)}${n}${r?`${n?s:"?"}${r}`:""}`;return this.request(a)}update(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}${sn(t)}`,{method:"PATCH",body:e})}delete(e){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}${sn(e)}`,{method:"DELETE"})}listVersions(e,t){const n=new URLSearchParams;e?.page!==void 0&&n.set("page",String(e.page)),e?.perPage!==void 0&&n.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&n.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&n.set("orderBy[direction]",e.orderBy.direction));const r=n.toString(),s=sn(t);return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions${r?`?${r}`:""}${s?`${r?"&":"?"}${s.slice(1)}`:""}`)}createVersion(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions${sn(t)}`,{method:"POST",body:e||{}})}getVersion(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions/${encodeURIComponent(e)}${sn(t)}`)}activateVersion(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions/${encodeURIComponent(e)}/activate${sn(t)}`,{method:"POST"})}restoreVersion(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions/${encodeURIComponent(e)}/restore${sn(t)}`,{method:"POST"})}deleteVersion(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions/${encodeURIComponent(e)}${sn(t)}`,{method:"DELETE"})}compareVersions(e,t,n){const r=new URLSearchParams;r.set("from",e),r.set("to",t);const s=sn(n);return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions/compare?${r.toString()}${s?`&${s.slice(1)}`:""}`)}},Vhn=class extends Ha{providerId;constructor(e,t){super(e),this.providerId=t}listToolkits(){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/toolkits`)}listTools(e){const t=new URLSearchParams;e?.toolkit&&t.set("toolkit",e.toolkit),e?.search&&t.set("search",e.search),e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage));const n=t.toString();return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/tools${n?`?${n}`:""}`)}getToolSchema(e){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/tools/${encodeURIComponent(e)}/schema`)}authorize(e){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/authorize`,{method:"POST",body:e})}getAuthStatus(e){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/auth-status/${encodeURIComponent(e)}`)}getConnectionStatus(e){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connection-status`,{method:"POST",body:e})}listConnections(e){const t=new URLSearchParams;return t.set("toolkit",e.toolkit),e.authorId&&t.set("authorId",e.authorId),e.page!==void 0&&e.page!==null&&t.set("page",String(e.page)),e.perPage!==void 0&&e.perPage!==null&&t.set("perPage",String(e.perPage)),e.scope&&t.set("scope",e.scope),this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connections?${t.toString()}`)}listConnectionFields(e){const t=new URLSearchParams;return t.set("toolkit",e.toolkit),this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connection-fields?${t.toString()}`)}disconnectConnection(e,t){const n=new URLSearchParams;t?.toolkit&&n.set("toolkit",t.toolkit),t?.force&&n.set("force","true");const r=n.toString();return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connections/${encodeURIComponent(e)}${r?`?${r}`:""}`,{method:"DELETE"})}updateConnection(e,t){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connections/${encodeURIComponent(e)}`,{method:"PATCH",body:t})}getConnectionUsage(e,t){const n=new URLSearchParams;t?.toolkit&&n.set("toolkit",t.toolkit);const r=n.toString();return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connections/${encodeURIComponent(e)}/usage${r?`?${r}`:""}`)}getHealth(){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/health`)}},Hhn=class extends Ha{providerId;constructor(e,t){super(e),this.providerId=t}details(){return this.request(`/processor-providers/${encodeURIComponent(this.providerId)}`)}},Whn=class extends Ha{workspaceId;skillName;skillPath;basePath;pathQuery;constructor(e,t,n,r){super(e),this.workspaceId=t,this.skillName=n,this.skillPath=r,this.basePath=`/workspaces/${encodeURIComponent(this.workspaceId)}/skills/${encodeURIComponent(this.skillName)}`,this.pathQuery=this.skillPath?`?path=${encodeURIComponent(this.skillPath)}`:""}details(){return this.request(`${this.basePath}${this.pathQuery}`)}listReferences(){return this.request(`${this.basePath}/references${this.pathQuery}`)}getReference(e){return this.request(`${this.basePath}/references/${encodeURIComponent(e)}${this.pathQuery}`)}},Zhn=class extends Ha{workspaceId;constructor(t,n){super(t),this.workspaceId=n}get basePath(){return`/workspaces/${encodeURIComponent(this.workspaceId)}`}info(){return this.request(this.basePath)}readFile(t,n){const r=new URLSearchParams;return r.set("path",t),n&&r.set("encoding",n),this.request(`${this.basePath}/fs/read?${r.toString()}`)}writeFile(t,n,r){return this.request(`${this.basePath}/fs/write`,{method:"POST",body:{path:t,content:n,encoding:r?.encoding,recursive:r?.recursive}})}listFiles(t,n){const r=new URLSearchParams;return r.set("path",t),n!==void 0&&r.set("recursive",String(n)),this.request(`${this.basePath}/fs/list?${r.toString()}`)}delete(t,n){const r=new URLSearchParams;return r.set("path",t),n?.recursive!==void 0&&r.set("recursive",String(n.recursive)),n?.force!==void 0&&r.set("force",String(n.force)),this.request(`${this.basePath}/fs/delete?${r.toString()}`,{method:"DELETE"})}mkdir(t,n){return this.request(`${this.basePath}/fs/mkdir`,{method:"POST",body:{path:t,recursive:n}})}stat(t){const n=new URLSearchParams;return n.set("path",t),this.request(`${this.basePath}/fs/stat?${n.toString()}`)}search(t){const n=new URLSearchParams;return n.set("query",t.query),t.topK!==void 0&&n.set("topK",String(t.topK)),t.mode&&n.set("mode",t.mode),t.minScore!==void 0&&n.set("minScore",String(t.minScore)),this.request(`${this.basePath}/search?${n.toString()}`)}index(t){return this.request(`${this.basePath}/index`,{method:"POST",body:t})}listSkills(){return this.request(`${this.basePath}/skills`)}searchSkills(t){const n=new URLSearchParams;return n.set("query",t.query),t.topK!==void 0&&n.set("topK",String(t.topK)),t.minScore!==void 0&&n.set("minScore",String(t.minScore)),t.skillNames&&t.skillNames.length>0&&n.set("skillNames",t.skillNames.join(",")),t.includeReferences!==void 0&&n.set("includeReferences",String(t.includeReferences)),this.request(`${this.basePath}/skills/search?${n.toString()}`)}getSkill(t,n){return new Whn(this.options,this.workspaceId,t,n)}},Ghn=class extends Ha{storedSkillId;constructor(e,t){super(e),this.storedSkillId=t}details(e){return this.request(`/stored/skills/${encodeURIComponent(this.storedSkillId)}${sn(e)}`)}update(e,t){return this.request(`/stored/skills/${encodeURIComponent(this.storedSkillId)}${sn(t)}`,{method:"PATCH",body:e})}delete(e){return this.request(`/stored/skills/${encodeURIComponent(this.storedSkillId)}${sn(e)}`,{method:"DELETE"})}favorite(e){return this.request(`/stored/skills/${encodeURIComponent(this.storedSkillId)}/favorite${sn(e)}`,{method:"PUT"})}unfavorite(e){return this.request(`/stored/skills/${encodeURIComponent(this.storedSkillId)}/favorite${sn(e)}`,{method:"DELETE"})}};function Qhn(e){return e.flatMap(t=>t.type==="message"?t.content:[]).map(t=>typeof t?.text=="string"?t.text:"").filter(Boolean).join("")}function h7(e){return{...e,output_text:Qhn(e.output)}}function Yhn(e){return e.type!=="message"?e:{...e,content:e.content??[]}}function Khn(e){return typeof e=="object"&&e!==null&&"response"in e&&(e.type==="response.created"||e.type==="response.in_progress"||e.type==="response.completed")?{...e,response:h7(e.response)}:typeof e=="object"&&e!==null&&"output"in e?h7(e):typeof e=="object"&&e!==null&&"item"in e&&(e.type==="response.output_item.added"||e.type==="response.output_item.done")?{...e,item:Yhn(e.item)}:e}function c3e(e){const t=e.replace(/\r\n/g,`
|
|
106
|
+
`):t;if(!r||r==="[DONE]")return{done:!0};let s;try{s=JSON.parse(r)}catch(a){throw new Error(`Failed to parse A2A stream event: ${a instanceof Error?a.message:"unknown parse error"}`)}if(s&&typeof s=="object"&&"error"in s&&s.error)throw new Cx(200,"OK",`A2A stream error - ${JSON.stringify(s.error)}`,s.error);return s&&typeof s=="object"&&"result"in s?{event:s.result}:{event:s}}async function*f7(e){const t=e.getReader(),n=new TextDecoder;let r="";try{for(;;){const{done:s,value:a}=await t.read();for(s?r+=n.decode():r+=n.decode(a,{stream:!0});;){const{eventBlock:i,rest:l}=_hn(r);if(r=l,!i)break;const c=l3e(i);if(c.done)return;c.event&&(yield c.event)}if(s)break}if(r.trim()){const s=l3e(r);!s.done&&s.event&&(yield s.event)}}finally{t.releaseLock()}}const Chn=["ES256","ES384","ES512","RS256","RS384","RS512","PS256","PS384","PS512"];function Ehn(e){const t=structuredClone(e);return delete t.signatures,t}function Thn(e){const t=globalThis.CryptoKey;return typeof t<"u"&&e instanceof t}function jhn(e){return e.includes("-----BEGIN ")}function Nhn(e){return e.includes("-----BEGIN CERTIFICATE-----")}async function Ihn(e,t){if(Thn(e)||e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(typeof e=="string"){if(t.startsWith("HS"))return new TextEncoder().encode(e);if(!jhn(e))throw new Error("Expected a PEM-encoded public key or certificate string for Agent Card verification");return Nhn(e)?Cpn(e,t):_pn(e,t)}return Epn(e,t)}async function Ahn(e,t){const n=e.signatures??[];if(n.length===0)return e;const r=Qpn(Ehn(e));if(!r)throw new Cx(200,"OK","Failed to canonicalize A2A Agent Card for signature verification");const s=t.algorithms??[...Chn],a=Kfn(r),i=[];for(const[l,c]of n.entries())try{const u=`${c.protected}.${a}.${c.signature}`,d=$pn(u);if(typeof d.alg!="string")throw new Error('Agent Card signature is missing a protected "alg" header');if(!s.includes(d.alg))throw new Error(`Agent Card signature algorithm "${d.alg}" is not allowed`);const f=await t.keyProvider({agentCard:e,signature:c,protectedHeader:d,alg:d.alg,kid:typeof d.kid=="string"?d.kid:void 0,jku:typeof d.jku=="string"?d.jku:void 0,index:l});if(!f)throw new Error("No verification key was provided for Agent Card signature verification");return await Ppn(u,await Ihn(f,d.alg),{algorithms:s}),e}catch(u){i.push(u instanceof Error?u.message:"Unknown verification failure")}throw new Cx(200,"OK",`A2A Agent Card signature verification failed: ${i.join("; ")}`)}function Rhn(e){const t=e.error,n=t?.message??"Unknown A2A JSON-RPC error";return typeof t?.code=="number"?new Qfn(t.code,n,t.data):new Cx(200,"OK",`A2A JSON-RPC error - ${n}`,t)}function YE(e){if("error"in e&&e.error)throw Rhn(e);if("result"in e)return e.result;throw new Cx(200,"OK","A2A JSON-RPC response did not include a result",e)}async function p7(e,t){if(e.body)return e.body;const n=Array.from(e.headers.entries()).map(([a,i])=>`${a}: ${i}`).join(", ");let r="";try{r=await e.text()}catch{}const s=[`A2A ${t} stream response did not include a body`,`(status: ${e.status} ${e.statusText})`,n?`headers: ${n}`:"",r?`body: ${r}`:""].filter(Boolean).join(" ");throw new Cx(e.status,e.statusText,s)}var Phn=class extends Ha{agentId;constructor(e,t){super(e),this.agentId=t}async getAgentCard(e){const t=await this.request(`/.well-known/${this.agentId}/agent-card.json`);return e?.verifySignature?Ahn(t,e.verifySignature):t}async getCard(e){return this.getAgentCard(e)}async getExtendedAgentCard(){return YE(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"agent/getAuthenticatedExtendedCard"}}))}async sendMessage(e){return this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"message/send",params:e}})}async*sendMessageStream(e){yield*f7(await p7(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"message/stream",params:e},stream:!0}),"message/stream"))}async sendStreamingMessage(e){return this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"message/stream",params:e},stream:!0})}async getTask(e){return this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/get",params:e}})}async cancelTask(e){return this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/cancel",params:e}})}async*resubscribeTask(e){yield*f7(await p7(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/resubscribe",params:e},stream:!0}),"tasks/resubscribe"))}async setTaskPushNotificationConfig(e){return YE(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/pushNotificationConfig/set",params:e}}))}async getTaskPushNotificationConfig(e){return YE(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/pushNotificationConfig/get",params:e}}))}async listTaskPushNotificationConfig(e){return YE(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/pushNotificationConfig/list",params:e}}))}async deleteTaskPushNotificationConfig(e){YE(await this.request(`/a2a/${this.agentId}`,{method:"POST",body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/pushNotificationConfig/delete",params:e}}))}},$hn=class extends Ha{agentId;constructor(e,t){super(e),this.agentId=t}async rpc(e,t){return YE(await this.request(`/a2a/${this.agentId}`,{method:"POST",headers:{"A2A-Version":"1.0"},body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:e,params:t}}))}async getAgentCard(){const e=await this.request(`/.well-known/${this.agentId}/agent-card.json`,{headers:{"A2A-Version":"1.0"}});return Lpn.fromJSON(e)}async sendMessage(e){const t=await this.rpc("message/send",e3e.toJSON(e));return Vpn.fromJSON(t)}async*sendMessageStream(e){const t=await this.request(`/a2a/${this.agentId}`,{method:"POST",headers:{"A2A-Version":"1.0"},body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"message/stream",params:e3e.toJSON(e)},stream:!0});for await(const n of f7(await p7(t,"message/stream")))yield t3e.fromJSON(n)}async getTask(e){const t=await this.rpc("tasks/get",Fpn.toJSON(e));return f1.fromJSON(t)}async listTasks(e){const t=await this.rpc("tasks/list",zpn.toJSON(e));return Bpn.fromJSON(t)}async cancelTask(e){const t=await this.rpc("tasks/cancel",Upn.toJSON(e));return f1.fromJSON(t)}async*resubscribeTask(e){const t=await this.request(`/a2a/${this.agentId}`,{method:"POST",headers:{"A2A-Version":"1.0"},body:{jsonrpc:"2.0",id:crypto.randomUUID(),method:"tasks/resubscribe",params:qpn.toJSON(e)},stream:!0});for await(const n of f7(await p7(t,"tasks/resubscribe")))yield t3e.fromJSON(n)}},Mhn=class extends Ha{serverId;toolId;constructor(e,t,n){super(e),this.serverId=t,this.toolId=n}details(e){return this.request(`/mcp/${encodeURIComponent(this.serverId)}/tools/${encodeURIComponent(this.toolId)}${sn(e)}`)}execute(e){const t={};return e.data!==void 0&&(t.data=e.data),e.requestContext!==void 0&&(t.requestContext=e.requestContext),this.request(`/mcp/${encodeURIComponent(this.serverId)}/tools/${encodeURIComponent(this.toolId)}/execute`,{method:"POST",body:t})}},Dhn=class extends Ha{actionId;constructor(e,t){super(e),this.actionId=t}transformWorkflowResult(e){return e.status==="success"?{success:e.result.success||!1,applied:e.result.applied||!1,branchName:e.result.branchName,message:e.result.message||"Agent builder action completed",validationResults:e.result.validationResults,error:e.result.error,errors:e.result.errors,stepResults:e.result.stepResults}:e.status==="failed"?{success:!1,applied:!1,message:`Agent builder action failed: ${e.error.message}`,error:e.error.message}:{success:!1,applied:!1,message:"Agent builder action was suspended",error:"Workflow suspended - manual intervention required"}}createRecordParserTransform(){return apt()}async createRun(e){const t=new URLSearchParams;e?.runId&&t.set("runId",e.runId);const n=`/agent-builder/${this.actionId}/create-run${t.toString()?`?${t.toString()}`:""}`;return this.request(n,{method:"POST"})}async startAsync(e,t){const n=new URLSearchParams;t&&n.set("runId",t);const r=lr(e.requestContext),{requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/start-async${n.toString()?`?${n.toString()}`:""}`,l=await this.request(i,{method:"POST",body:{...a,requestContext:r}});return this.transformWorkflowResult(l)}async startActionRun(e,t){const n=new URLSearchParams;n.set("runId",t);const r=lr(e.requestContext),{requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/start?${n.toString()}`;return this.request(i,{method:"POST",body:{...a,requestContext:r}})}async resume(e,t){const n=new URLSearchParams;n.set("runId",t);const r=lr(e.requestContext),{requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/resume?${n.toString()}`;return this.request(i,{method:"POST",body:{...a,requestContext:r}})}async resumeAsync(e,t){const n=new URLSearchParams;n.set("runId",t);const r=lr(e.requestContext),{requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/resume-async?${n.toString()}`,l=await this.request(i,{method:"POST",body:{...a,requestContext:r}});return this.transformWorkflowResult(l)}async stream(e,t){if(!t)throw new Error("runId is required to stream an agent builder action");const n=new URLSearchParams;n.set("runId",t);const r=lr(e.requestContext),{requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/stream?${n.toString()}`,l=await this.request(i,{method:"POST",body:{...a,requestContext:r},stream:!0});if(!l.ok)throw new Error(`Failed to stream agent builder action: ${l.statusText}`);if(!l.body)throw new Error("Response body is null");return l.body.pipeThrough(this.createRecordParserTransform())}async observeStream(e){const t=new URLSearchParams;t.set("runId",e.runId);const n=`/agent-builder/${this.actionId}/observe?${t.toString()}`,r=await this.request(n,{method:"POST",stream:!0});if(!r.ok)throw new Error(`Failed to observe agent builder action stream: ${r.statusText}`);if(!r.body)throw new Error("Response body is null");return r.body.pipeThrough(this.createRecordParserTransform())}async observeStreamLegacy(e){const t=new URLSearchParams;t.set("runId",e.runId);const n=`/agent-builder/${this.actionId}/observe-stream-legacy?${t.toString()}`,r=await this.request(n,{method:"POST",stream:!0});if(!r.ok)throw new Error(`Failed to observe agent builder action stream legacy: ${r.statusText}`);if(!r.body)throw new Error("Response body is null");return r.body.pipeThrough(this.createRecordParserTransform())}async resumeStream(e){const t=new URLSearchParams;t.set("runId",e.runId);const n=lr(e.requestContext),{runId:r,requestContext:s,...a}=e,i=`/agent-builder/${this.actionId}/resume-stream?${t.toString()}`,l=await this.request(i,{method:"POST",body:{...a,requestContext:n},stream:!0});if(!l.ok)throw new Error(`Failed to resume agent builder action stream: ${l.statusText}`);if(!l.body)throw new Error("Response body is null");return l.body.pipeThrough(this.createRecordParserTransform())}async runById(e,t){const n=new URLSearchParams;t?.fields&&t.fields.length>0&&n.set("fields",t.fields.join(",")),t?.withNestedWorkflows!==void 0&&n.set("withNestedWorkflows",String(t.withNestedWorkflows));const r=n.size>0?`?${n.toString()}`:"",s=`/agent-builder/${this.actionId}/runs/${e}${r}`;return this.request(s,{method:"GET"})}async details(){return await this.request(`/agent-builder/${this.actionId}`)}async runs(e){const t=new URLSearchParams;e?.fromDate&&t.set("fromDate",e.fromDate.toISOString()),e?.toDate&&t.set("toDate",e.toDate.toISOString()),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.page!==void 0&&t.set("page",String(e.page)),e?.limit!==null&&e?.limit!==void 0&&(e.limit===!1?t.set("limit","false"):typeof e.limit=="number"&&e.limit>0&&Number.isInteger(e.limit)&&t.set("limit",String(e.limit))),e?.offset!==null&&e?.offset!==void 0&&!isNaN(Number(e?.offset))&&t.set("offset",String(e.offset)),e?.resourceId&&t.set("resourceId",e.resourceId);const n=`/agent-builder/${this.actionId}/runs${t.toString()?`?${t.toString()}`:""}`;return this.request(n,{method:"GET"})}async cancelRun(e){const t=`/agent-builder/${this.actionId}/runs/${e}/cancel`;return this.request(t,{method:"POST"})}},Lhn=class extends Ha{constructor(e){super(e)}getTrace(e){return this.request(`/observability/traces/${e}`)}getTraceLight(e){return this.request(`/observability/traces/${e}/light`)}getSpan(e,t){return this.request(`/observability/traces/${e}/spans/${t}`)}getTraceTrajectory(e){return this.request(`/observability/traces/${e}/trajectory`)}getTraces(e){const{pagination:t,filters:n}=e,{page:r,perPage:s,dateRange:a}=t||{},{name:i,spanType:l,entityId:c,entityType:u}=n||{},d=new URLSearchParams;if(r!==void 0&&d.set("page",String(r)),s!==void 0&&d.set("perPage",String(s)),i&&d.set("name",i),l!==void 0&&d.set("spanType",String(l)),c&&u&&(d.set("entityId",c),d.set("entityType",u)),a){const p=JSON.stringify({start:a.start instanceof Date?a.start.toISOString():a.start,end:a.end instanceof Date?a.end.toISOString():a.end});d.set("dateRange",p)}const f=d.toString();return this.request(`/observability/traces${f?`?${f}`:""}`)}listTraces(e={}){const t=uf(e,["filters","pagination","orderBy"]);return this.request(`/observability/traces${t?`?${t}`:""}`)}queryTraces(e){return this.request("/observability/traces/query",{method:"POST",body:e})}listTracesLight(e={}){const t=uf(e,["filters","pagination","orderBy"]);return this.request(`/observability/traces/light${t?`?${t}`:""}`)}listBranches(e={}){const t=uf(e,["filters","pagination","orderBy"]);return this.request(`/observability/branches${t?`?${t}`:""}`)}getBranch(e){const{traceId:t,spanId:n,depth:r}=e,s=r!==void 0?`?depth=${r}`:"";return this.request(`/observability/traces/${encodeURIComponent(t)}/branches/${encodeURIComponent(n)}${s}`)}listScoresBySpan(e){const{traceId:t,spanId:n,...r}=e,s=uf(r);return this.request(`/observability/traces/${encodeURIComponent(t)}/${encodeURIComponent(n)}/scores${s?`?${s}`:""}`)}score(e){return this.request("/observability/traces/score",{method:"POST",body:{...e}})}listLogs(e={}){const t=uf(e,["filters","pagination","orderBy"]);return this.request(`/observability/logs${t?`?${t}`:""}`)}listScores(e={}){const t=uf(e,["filters","pagination","orderBy"]);return this.request(`/observability/scores${t?`?${t}`:""}`)}createScore(e){return this.request("/observability/scores",{method:"POST",body:e})}getScoreAggregate(e){return this.request("/observability/scores/aggregate",{method:"POST",body:e})}getScoreBreakdown(e){return this.request("/observability/scores/breakdown",{method:"POST",body:e})}getScoreTimeSeries(e){return this.request("/observability/scores/timeseries",{method:"POST",body:e})}getScorePercentiles(e){return this.request("/observability/scores/percentiles",{method:"POST",body:e})}listFeedback(e={}){const t=uf(e,["filters","pagination","orderBy"]);return this.request(`/observability/feedback${t?`?${t}`:""}`)}createFeedback(e){return this.request("/observability/feedback",{method:"POST",body:e})}updateFeedbackReviewStatus(e){return this.request(`/observability/feedback/${encodeURIComponent(e.feedbackId)}/review-status`,{method:"PATCH",body:{reviewStatus:e.reviewStatus}})}getFeedbackAggregate(e){return this.request("/observability/feedback/aggregate",{method:"POST",body:e})}getFeedbackBreakdown(e){return this.request("/observability/feedback/breakdown",{method:"POST",body:e})}getFeedbackTimeSeries(e){return this.request("/observability/feedback/timeseries",{method:"POST",body:e})}getFeedbackPercentiles(e){return this.request("/observability/feedback/percentiles",{method:"POST",body:e})}getMetricAggregate(e){return this.request("/observability/metrics/aggregate",{method:"POST",body:e})}getMetricBreakdown(e){return this.request("/observability/metrics/breakdown",{method:"POST",body:e})}getMetricTimeSeries(e){return this.request("/observability/metrics/timeseries",{method:"POST",body:e})}getMetricPercentiles(e){return this.request("/observability/metrics/percentiles",{method:"POST",body:e})}getMetricNames(e={}){const t=uf(e);return this.request(`/observability/discovery/metric-names${t?`?${t}`:""}`)}getMetricLabelKeys(e){const t=uf(e);return this.request(`/observability/discovery/metric-label-keys${t?`?${t}`:""}`)}getMetricLabelValues(e){const t=uf(e);return this.request(`/observability/discovery/metric-label-values${t?`?${t}`:""}`)}getEntityTypes(){return this.request("/observability/discovery/entity-types")}getEntityNames(e={}){const t=uf(e);return this.request(`/observability/discovery/entity-names${t?`?${t}`:""}`)}getServiceNames(){return this.request("/observability/discovery/service-names")}getEnvironments(){return this.request("/observability/discovery/environments")}getTags(e={}){const t=uf(e);return this.request(`/observability/discovery/tags${t?`?${t}`:""}`)}},Fhn=class extends Ha{storedAgentId;constructor(e,t){super(e),this.storedAgentId=t}details(e,t){const n=sn(e),r=t?.status?`status=${t.status}`:"",s=`/stored/agents/${encodeURIComponent(this.storedAgentId)}${n}${r?`${n?"&":"?"}${r}`:""}`;return this.request(s)}update(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}${sn(t)}`,{method:"PATCH",body:e})}export(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/export`,{method:"POST",body:e})}openChangeRequest(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/change-request`,{method:"POST",body:e})}delete(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}${sn(e)}`,{method:"DELETE"})}dependents(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/dependents${sn(e)}`)}favorite(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/favorite${sn(e)}`,{method:"PUT"})}unfavorite(e){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/favorite${sn(e)}`,{method:"DELETE"})}listVersions(e,t){const n=new URLSearchParams;e?.page!==void 0&&n.set("page",String(e.page)),e?.perPage!==void 0&&n.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&n.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&n.set("orderBy[direction]",e.orderBy.direction));const r=n.toString(),s=sn(t);return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions${r?`?${r}`:""}${s?`${r?"&":"?"}${s.slice(1)}`:""}`)}createVersion(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions${sn(t)}`,{method:"POST",body:e||{}})}getVersion(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions/${encodeURIComponent(e)}${sn(t)}`)}activateVersion(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions/${encodeURIComponent(e)}/activate${sn(t)}`,{method:"POST"})}restoreVersion(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions/${encodeURIComponent(e)}/restore${sn(t)}`,{method:"POST"})}deleteVersion(e,t){return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions/${encodeURIComponent(e)}${sn(t)}`,{method:"DELETE"})}compareVersions(e,t,n){const r=new URLSearchParams;r.set("from",e),r.set("to",t);const s=sn(n);return this.request(`/stored/agents/${encodeURIComponent(this.storedAgentId)}/versions/compare?${r.toString()}${s?`&${s.slice(1)}`:""}`)}},zhn=class extends Ha{dynamicWorkflowId;constructor(e,t){super(e),this.dynamicWorkflowId=t}details(){return this.request(`/stored/workflows/${encodeURIComponent(this.dynamicWorkflowId)}`)}delete(){return this.request(`/stored/workflows/${encodeURIComponent(this.dynamicWorkflowId)}`,{method:"DELETE"})}},Bhn=class extends Ha{storedPromptBlockId;constructor(e,t){super(e),this.storedPromptBlockId=t}details(e,t){const n=sn(e),r=t?.status?`status=${t.status}`:"",s=`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}${n}${r?`${n?"&":"?"}${r}`:""}`;return this.request(s)}update(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}${sn(t)}`,{method:"PATCH",body:e})}delete(e){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}${sn(e)}`,{method:"DELETE"})}listVersions(e,t){const n=new URLSearchParams;e?.page!==void 0&&n.set("page",String(e.page)),e?.perPage!==void 0&&n.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&n.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&n.set("orderBy[direction]",e.orderBy.direction));const r=n.toString(),s=sn(t,r?"&":"?");return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions${r?`?${r}`:""}${s}`)}createVersion(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions${sn(t)}`,{method:"POST",body:e||{}})}getVersion(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions/${encodeURIComponent(e)}${sn(t)}`)}activateVersion(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions/${encodeURIComponent(e)}/activate${sn(t)}`,{method:"POST"})}restoreVersion(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions/${encodeURIComponent(e)}/restore${sn(t)}`,{method:"POST"})}deleteVersion(e,t){return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions/${encodeURIComponent(e)}${sn(t)}`,{method:"DELETE"})}compareVersions(e,t,n){const r=new URLSearchParams;r.set("from",e),r.set("to",t);const s=sn(n,"&");return this.request(`/stored/prompt-blocks/${encodeURIComponent(this.storedPromptBlockId)}/versions/compare?${r.toString()}${s}`)}},Uhn=class extends Ha{storedMCPClientId;constructor(e,t){super(e),this.storedMCPClientId=t}details(e){return this.request(`/stored/mcp-clients/${encodeURIComponent(this.storedMCPClientId)}${sn(e)}`)}update(e,t){return this.request(`/stored/mcp-clients/${encodeURIComponent(this.storedMCPClientId)}${sn(t)}`,{method:"PATCH",body:e})}delete(e){return this.request(`/stored/mcp-clients/${encodeURIComponent(this.storedMCPClientId)}${sn(e)}`,{method:"DELETE"})}},qhn=class extends Ha{storedScorerId;constructor(e,t){super(e),this.storedScorerId=t}details(e,t){const n=sn(e),r=t?.status?`status=${t.status}`:"",s=n?"&":"?",a=`/stored/scorers/${encodeURIComponent(this.storedScorerId)}${n}${r?`${n?s:"?"}${r}`:""}`;return this.request(a)}update(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}${sn(t)}`,{method:"PATCH",body:e})}delete(e){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}${sn(e)}`,{method:"DELETE"})}listVersions(e,t){const n=new URLSearchParams;e?.page!==void 0&&n.set("page",String(e.page)),e?.perPage!==void 0&&n.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&n.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&n.set("orderBy[direction]",e.orderBy.direction));const r=n.toString(),s=sn(t);return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions${r?`?${r}`:""}${s?`${r?"&":"?"}${s.slice(1)}`:""}`)}createVersion(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions${sn(t)}`,{method:"POST",body:e||{}})}getVersion(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions/${encodeURIComponent(e)}${sn(t)}`)}activateVersion(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions/${encodeURIComponent(e)}/activate${sn(t)}`,{method:"POST"})}restoreVersion(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions/${encodeURIComponent(e)}/restore${sn(t)}`,{method:"POST"})}deleteVersion(e,t){return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions/${encodeURIComponent(e)}${sn(t)}`,{method:"DELETE"})}compareVersions(e,t,n){const r=new URLSearchParams;r.set("from",e),r.set("to",t);const s=sn(n);return this.request(`/stored/scorers/${encodeURIComponent(this.storedScorerId)}/versions/compare?${r.toString()}${s?`&${s.slice(1)}`:""}`)}},Vhn=class extends Ha{providerId;constructor(e,t){super(e),this.providerId=t}listToolkits(){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/toolkits`)}listTools(e){const t=new URLSearchParams;e?.toolkit&&t.set("toolkit",e.toolkit),e?.search&&t.set("search",e.search),e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage));const n=t.toString();return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/tools${n?`?${n}`:""}`)}getToolSchema(e){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/tools/${encodeURIComponent(e)}/schema`)}authorize(e){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/authorize`,{method:"POST",body:e})}getAuthStatus(e){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/auth-status/${encodeURIComponent(e)}`)}getConnectionStatus(e){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connection-status`,{method:"POST",body:e})}listConnections(e){const t=new URLSearchParams;return t.set("toolkit",e.toolkit),e.authorId&&t.set("authorId",e.authorId),e.page!==void 0&&e.page!==null&&t.set("page",String(e.page)),e.perPage!==void 0&&e.perPage!==null&&t.set("perPage",String(e.perPage)),e.scope&&t.set("scope",e.scope),this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connections?${t.toString()}`)}listConnectionFields(e){const t=new URLSearchParams;return t.set("toolkit",e.toolkit),this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connection-fields?${t.toString()}`)}disconnectConnection(e,t){const n=new URLSearchParams;t?.toolkit&&n.set("toolkit",t.toolkit),t?.force&&n.set("force","true");const r=n.toString();return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connections/${encodeURIComponent(e)}${r?`?${r}`:""}`,{method:"DELETE"})}updateConnection(e,t){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connections/${encodeURIComponent(e)}`,{method:"PATCH",body:t})}getConnectionUsage(e,t){const n=new URLSearchParams;t?.toolkit&&n.set("toolkit",t.toolkit);const r=n.toString();return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/connections/${encodeURIComponent(e)}/usage${r?`?${r}`:""}`)}getHealth(){return this.request(`/tool-providers/${encodeURIComponent(this.providerId)}/health`)}},Hhn=class extends Ha{providerId;constructor(e,t){super(e),this.providerId=t}details(){return this.request(`/processor-providers/${encodeURIComponent(this.providerId)}`)}},Whn=class extends Ha{workspaceId;skillName;skillPath;basePath;pathQuery;constructor(e,t,n,r){super(e),this.workspaceId=t,this.skillName=n,this.skillPath=r,this.basePath=`/workspaces/${encodeURIComponent(this.workspaceId)}/skills/${encodeURIComponent(this.skillName)}`,this.pathQuery=this.skillPath?`?path=${encodeURIComponent(this.skillPath)}`:""}details(){return this.request(`${this.basePath}${this.pathQuery}`)}listReferences(){return this.request(`${this.basePath}/references${this.pathQuery}`)}getReference(e){return this.request(`${this.basePath}/references/${encodeURIComponent(e)}${this.pathQuery}`)}},Zhn=class extends Ha{workspaceId;constructor(t,n){super(t),this.workspaceId=n}get basePath(){return`/workspaces/${encodeURIComponent(this.workspaceId)}`}info(){return this.request(this.basePath)}readFile(t,n){const r=new URLSearchParams;return r.set("path",t),n&&r.set("encoding",n),this.request(`${this.basePath}/fs/read?${r.toString()}`)}writeFile(t,n,r){return this.request(`${this.basePath}/fs/write`,{method:"POST",body:{path:t,content:n,encoding:r?.encoding,recursive:r?.recursive}})}listFiles(t,n){const r=new URLSearchParams;return r.set("path",t),n!==void 0&&r.set("recursive",String(n)),this.request(`${this.basePath}/fs/list?${r.toString()}`)}delete(t,n){const r=new URLSearchParams;return r.set("path",t),n?.recursive!==void 0&&r.set("recursive",String(n.recursive)),n?.force!==void 0&&r.set("force",String(n.force)),this.request(`${this.basePath}/fs/delete?${r.toString()}`,{method:"DELETE"})}mkdir(t,n){return this.request(`${this.basePath}/fs/mkdir`,{method:"POST",body:{path:t,recursive:n}})}stat(t){const n=new URLSearchParams;return n.set("path",t),this.request(`${this.basePath}/fs/stat?${n.toString()}`)}search(t){const n=new URLSearchParams;return n.set("query",t.query),t.topK!==void 0&&n.set("topK",String(t.topK)),t.mode&&n.set("mode",t.mode),t.minScore!==void 0&&n.set("minScore",String(t.minScore)),this.request(`${this.basePath}/search?${n.toString()}`)}index(t){return this.request(`${this.basePath}/index`,{method:"POST",body:t})}listSkills(){return this.request(`${this.basePath}/skills`)}searchSkills(t){const n=new URLSearchParams;return n.set("query",t.query),t.topK!==void 0&&n.set("topK",String(t.topK)),t.minScore!==void 0&&n.set("minScore",String(t.minScore)),t.skillNames&&t.skillNames.length>0&&n.set("skillNames",t.skillNames.join(",")),t.includeReferences!==void 0&&n.set("includeReferences",String(t.includeReferences)),this.request(`${this.basePath}/skills/search?${n.toString()}`)}getSkill(t,n){return new Whn(this.options,this.workspaceId,t,n)}},Ghn=class extends Ha{storedSkillId;constructor(e,t){super(e),this.storedSkillId=t}details(e){return this.request(`/stored/skills/${encodeURIComponent(this.storedSkillId)}${sn(e)}`)}update(e,t){return this.request(`/stored/skills/${encodeURIComponent(this.storedSkillId)}${sn(t)}`,{method:"PATCH",body:e})}delete(e){return this.request(`/stored/skills/${encodeURIComponent(this.storedSkillId)}${sn(e)}`,{method:"DELETE"})}favorite(e){return this.request(`/stored/skills/${encodeURIComponent(this.storedSkillId)}/favorite${sn(e)}`,{method:"PUT"})}unfavorite(e){return this.request(`/stored/skills/${encodeURIComponent(this.storedSkillId)}/favorite${sn(e)}`,{method:"DELETE"})}};function Qhn(e){return e.flatMap(t=>t.type==="message"?t.content:[]).map(t=>typeof t?.text=="string"?t.text:"").filter(Boolean).join("")}function h7(e){return{...e,output_text:Qhn(e.output)}}function Yhn(e){return e.type!=="message"?e:{...e,content:e.content??[]}}function Khn(e){return typeof e=="object"&&e!==null&&"response"in e&&(e.type==="response.created"||e.type==="response.in_progress"||e.type==="response.completed")?{...e,response:h7(e.response)}:typeof e=="object"&&e!==null&&"output"in e?h7(e):typeof e=="object"&&e!==null&&"item"in e&&(e.type==="response.output_item.added"||e.type==="response.output_item.done")?{...e,item:Yhn(e.item)}:e}function c3e(e){const t=e.replace(/\r\n/g,`
|
|
107
107
|
`).trim();if(!t)return null;const n=t.split(`
|
|
108
108
|
`).filter(s=>s.startsWith("data:")).map(s=>s.slice(5).trim());if(!n.length)return null;const r=n.join(`
|
|
109
109
|
`);return r==="[DONE]"?null:Khn(JSON.parse(r))}var Xhn=class{response;constructor(e){this.response=e}asResponse(){return this.response}async*[Symbol.asyncIterator](){if(!this.response.body)return;const e=this.response.body.getReader(),t=new TextDecoder;let n="",r=!1;try{for(;;){const{done:a,value:i}=await e.read();n+=t.decode(i??new Uint8Array,{stream:!a});let l=n.indexOf(`
|
|
@@ -114,7 +114,7 @@ ${n}
|
|
|
114
114
|
\r
|
|
115
115
|
`),length:4},{index:k.indexOf(`
|
|
116
116
|
|
|
117
|
-
`),length:2},{index:k.indexOf("\r\r"),length:2}].filter(C=>C.index!==-1);return _.length===0?null:_.reduce((C,T)=>T.index<C.index?T:C)},m=async k=>{const _=k.body.getReader();i=_;const C=new TextDecoder;let T="";try{for(;!a;){const{done:E,value:N}=await _.read();if(E)return a?{kind:"cancelled"}:{kind:"done"};T+=C.decode(N,{stream:!0});let I;for(;(I=h(T))!==null;){const A=T.slice(0,I.index);T=T.slice(I.index+I.length);for(const R of A.split(/\r\n|\n|\r/)){if(!R.startsWith("data:"))continue;const L=R.slice(5).trim();if(!L)continue;let M;try{M=amn(JSON.parse(L))}catch{continue}try{e.onEvent(M)}catch(F){return a||v(F),{kind:"consumer_error"}}}}}return{kind:"cancelled"}}catch(E){return a?{kind:"cancelled"}:{kind:"transport_error",error:E}}finally{i===_&&(i=null),_.cancel().catch(()=>{})}},v=k=>{try{e.onError?.(k)}catch{}},y=k=>{v(k.kind==="transport_error"?k.error:p())},b=async k=>{try{return await m(k)}catch(_){return a?{kind:"cancelled"}:{kind:"transport_error",error:_}}},x=await f();return(async k=>{let _=k;for(;!a;){let C=await b(_);if(a||C.kind==="cancelled"||C.kind==="consumer_error")return;if(!r){y(C);return}let T=0,E;for(;!E;){if(T>=r.maxRetries){y(C);return}if(T++,await d(s(T)),a)return;try{E=await f()}catch(N){C={kind:"transport_error",error:N}}}if(a){E.body?.cancel().catch(()=>{});return}_=E;try{e.onReconnect?.()}catch{}}})(x),{unsubscribe:()=>{a=!0,u(),i?.cancel().catch(()=>{})}}}async sendMessage(e,t){const{content:n,files:r}=typeof e=="string"?{content:e,files:void 0}:e,s=lr(t?.requestContext);await this.request(this.url(`${this.base()}/messages`),{method:"POST",body:{message:n,...r?.length?{files:r}:{},...s?{requestContext:s}:{}}})}async abort(){await this.request(this.url(`${this.base()}/abort`),{method:"POST"})}async approveTool(e,t,n){const r=lr(n?.requestContext);await this.request(this.url(`${this.base()}/tool-approval`),{method:"POST",body:{toolCallId:e,approved:t,...r?{requestContext:r}:{}}})}async respondToToolSuspension(e,t,n){const r=lr(n?.requestContext);await this.request(this.url(`${this.base()}/tool-suspension`),{method:"POST",body:{toolCallId:e,resumeData:t,...r?{requestContext:r}:{}}})}async steer(e,t){const n=lr(t?.requestContext);await this.request(this.url(`${this.base()}/steer`),{method:"POST",body:{message:e,...n?{requestContext:n}:{}}})}state(e){const t=e?.threadId?`${this.base()}?threadId=${encodeURIComponent(e.threadId)}`:this.base();return this.request(this.url(t))}async setState(e){await this.request(this.url(`${this.base()}/state`),{method:"PUT",body:{state:e}})}async switchMode(e){await this.request(this.url(`${this.base()}/mode`),{method:"POST",body:{modeId:e}})}async switchModel(e,t){await this.request(this.url(`${this.base()}/model`),{method:"POST",body:{modelId:e,scope:t?.scope,modeId:t?.modeId}})}async listThreads(e){const t=typeof e=="number"?{limit:e}:e??{},n=new URLSearchParams;t.limit!=null&&n.set("limit",String(t.limit)),t.tags&&Object.keys(t.tags).length>0&&n.set("tags",JSON.stringify(t.tags));const r=n.toString()?`?${n.toString()}`:"";return(await this.request(this.url(`${this.base()}/threads${r}`))).threads}async switchThread(e){await this.request(this.url(`${this.base()}/thread`),{method:"POST",body:{threadId:e}})}async createThread(e){return this.request(this.url(`${this.base()}/threads`),{method:"POST",body:{title:e}})}async deleteThread(e){await this.request(this.url(`${this.base()}/threads/${encodeURIComponent(e)}`),{method:"DELETE"})}async renameThread(e,t){await this.request(this.url(`${this.base()}/threads/${encodeURIComponent(e)}`),{method:"PUT",body:{title:t}})}async cloneThread(e){return this.request(this.url(`${this.base()}/threads/clone`),{method:"POST",body:e??{}})}async listMessages(e,t){const n=t!=null?`?limit=${t}`:"";return(await this.request(this.url(`${this.base()}/threads/${encodeURIComponent(e)}/messages${n}`))).messages.map(ipt)}async followUp(e,t){const n=lr(t?.requestContext);await this.request(this.url(`${this.base()}/follow-up`),{method:"POST",body:{message:e,...n?{requestContext:n}:{}}})}async getOMRecord(){return(await this.request(this.url(`${this.base()}/om`))).record}async setResourceId(e){await this.request(this.url(`${this.base()}/resource`),{method:"POST",body:{newResourceId:e}})}async getResourceIds(){return(await this.request(this.url(`${this.base()}/resources`))).resourceIds}async getGoal(){return(await this.request(this.url(`${this.base()}/goal`))).goal}async setGoal(e,t){return(await this.request(this.url(`${this.base()}/goal`),{method:"POST",body:{objective:e,...t}})).goal}async updateGoal(e){return(await this.request(this.url(`${this.base()}/goal`),{method:"PUT",body:e})).goal}async clearGoal(){await this.request(this.url(`${this.base()}/goal`),{method:"DELETE"})}async getPermissions(){return this.request(this.url(`${this.base()}/permissions`))}async setPermissionForCategory(e,t){await this.request(this.url(`${this.base()}/permissions/category`),{method:"PUT",body:{category:e,policy:t}})}async setPermissionForTool(e,t){await this.request(this.url(`${this.base()}/permissions/tool`),{method:"PUT",body:{toolName:e,policy:t}})}async sendNotification(e){return this.request(this.url(`${this.base()}/notifications`),{method:"POST",body:e})}},omn=class extends Ha{controllerId;constructor(e,t){super(e),this.controllerId=t}basePath(){return`/agent-controller/${encodeURIComponent(this.controllerId)}`}async listModes(){return(await this.request(`${this.basePath()}/modes`)).modes}async listModels(){return(await this.request(`${this.basePath()}/models`)).models}async listActiveRuns(){return(await this.request(`${this.basePath()}/active-runs`)).runs}async workspaceStatus(){return this.request(`${this.basePath()}/workspace`)}session(e,t){return new imn(this.options,this.controllerId,e,t)}},DP=class extends Ha{observability;conversations;responses;channels;constructor(e){super(e),this.observability=new Lhn(e),this.conversations=new xhn(e),this.responses=new Jhn(e),this.channels=new emn(e)}listAgents(e,t){const n=vw(lr(e)),r=new URLSearchParams;n&&r.set("requestContext",n),t&&r.set("partial","true");const s=r.toString();return this.request(`/agents${s?`?${s}`:""}`)}listAgentsModelProviders(){return this.request("/agents/providers")}getAgent(e,t){return new phn(this.options,e,t)}async listAgentControllers(){return(await this.request("/agent-controller")).agentControllers}getAgentController(e){return new omn(this.options,e)}async listMemoryThreads(e={}){const t=new URLSearchParams;e.resourceId&&t.set("resourceId",e.resourceId),e.metadata&&t.set("metadata",JSON.stringify(e.metadata)),e.agentId&&t.set("agentId",e.agentId),e.page!==void 0&&t.set("page",e.page.toString()),e.perPage!==void 0&&t.set("perPage",e.perPage.toString()),e.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction));const n=t.toString(),r=await this.request(`/memory/threads${n?`?${n}`:""}${sn(e.requestContext,n?"&":"?")}`);return"threads"in r?r:{threads:r,total:r.length,page:e.page??0,perPage:e.perPage??100,hasMore:!1}}getMemoryConfig(e){return this.request(`/memory/config?agentId=${e.agentId}${sn(e.requestContext,"&")}`)}createMemoryThread(e){return this.request(`/memory/threads?agentId=${e.agentId}${sn(e.requestContext,"&")}`,{method:"POST",body:e})}getMemoryThread({threadId:e,agentId:t}){return new hhn(this.options,e,t)}listThreadMessages(e,t={}){let n="";const r=t.includeSystemReminders===void 0?"":`includeSystemReminders=${t.includeSystemReminders}`;return t.networkId?n=`/memory/network/threads/${e}/messages?networkId=${t.networkId}${r?`&${r}`:""}${sn(t.requestContext,"&")}`:t.agentId?n=`/memory/threads/${e}/messages?agentId=${t.agentId}${r?`&${r}`:""}${sn(t.requestContext,"&")}`:n=`/memory/threads/${e}/messages${r?`?${r}`:""}${sn(t.requestContext,r?"&":"?")}`,this.request(n)}deleteThread(e,t){if(!t||!!t.agentId==!!t.networkId)throw new Error("MastraClient.deleteThread() requires exactly one of agentId or networkId. The server cannot resolve which memory store owns the thread without one, and passing both is ambiguous.");const n=t.agentId?`/memory/threads/${e}?agentId=${t.agentId}${sn(t.requestContext,"&")}`:`/memory/network/threads/${e}?networkId=${t.networkId}${sn(t.requestContext,"&")}`;return this.request(n,{method:"DELETE"})}saveMessageToMemory(e){return this.request(`/memory/save-messages?agentId=${e.agentId}${sn(e.requestContext,"&")}`,{method:"POST",body:e})}getMemoryStatus(e,t,n){const r=new URLSearchParams({agentId:e});n?.resourceId&&r.set("resourceId",n.resourceId),n?.threadId&&r.set("threadId",n.threadId);const s=r.toString();return this.request(`/memory/status?${s}${sn(t,"&")}`)}getObservationalMemory(e){const t=new URLSearchParams({agentId:e.agentId});e.resourceId&&t.set("resourceId",e.resourceId),e.threadId&&t.set("threadId",e.threadId),e.from&&t.set("from",e.from instanceof Date?e.from.toISOString():e.from),e.to&&t.set("to",e.to instanceof Date?e.to.toISOString():e.to),e.offset!=null&&t.set("offset",String(e.offset)),e.limit!=null&&t.set("limit",String(e.limit));const n=t.toString();return this.request(`/memory/observational-memory?${n}${sn(e.requestContext,"&")}`)}awaitBufferStatus(e){return this.request(`/memory/observational-memory/buffer-status${sn(e.requestContext)}`,{method:"POST",body:{agentId:e.agentId,resourceId:e.resourceId,threadId:e.threadId}})}listTools(e){const t=vw(lr(e)),n=new URLSearchParams;t&&n.set("requestContext",t);const r=n.toString();return this.request(`/tools${r?`?${r}`:""}`)}getTool(e){return new vhn(this.options,e)}listProcessors(e){const t=vw(lr(e)),n=new URLSearchParams;t&&n.set("requestContext",t);const r=n.toString();return this.request(`/processors${r?`?${r}`:""}`)}getProcessor(e){return new yhn(this.options,e)}listWorkflows(e,t){const n=vw(lr(e)),r=new URLSearchParams;n&&r.set("requestContext",n),t&&r.set("partial","true");const s=r.toString();return this.request(`/workflows${s?`?${s}`:""}`)}listWorkflowRunCounts(e){const t=vw(lr(e)),n=new URLSearchParams;t&&n.set("requestContext",t);const r=n.toString();return this.request(`/workflows/run-counts${r?`?${r}`:""}`)}getWorkflow(e){return new Ohn(this.options,e)}getAgentBuilderActions(){return this.request("/agent-builder")}getAgentBuilderAction(e){return new Dhn(this.options,e)}getVector(e){return new ghn(this.options,e)}listLogs(e){const{transportId:t,fromDate:n,toDate:r,logLevel:s,filters:a,page:i,perPage:l}=e,c=a?Object.entries(a).map(([d,f])=>`${d}:${f}`):[],u=new URLSearchParams;if(t&&u.set("transportId",t),n&&u.set("fromDate",n.toISOString()),r&&u.set("toDate",r.toISOString()),s&&u.set("logLevel",s),i!==void 0&&u.set("page",String(i)),l!==void 0&&u.set("perPage",String(l)),c)if(Array.isArray(c))for(const d of c)u.append("filters",d);else u.set("filters",c);return u.size?this.request(`/logs?${u}`):this.request("/logs")}getLogForRun(e){const{runId:t,transportId:n,fromDate:r,toDate:s,logLevel:a,filters:i,page:l,perPage:c}=e,u=i?Object.entries(i).map(([f,p])=>`${f}:${p}`):[],d=new URLSearchParams;if(t&&d.set("runId",t),n&&d.set("transportId",n),r&&d.set("fromDate",r.toISOString()),s&&d.set("toDate",s.toISOString()),a&&d.set("logLevel",a),l!==void 0&&d.set("page",String(l)),c!==void 0&&d.set("perPage",String(c)),u)if(Array.isArray(u))for(const f of u)d.append("filters",f);else d.set("filters",u);return d.size?this.request(`/logs/${t}?${d}`):this.request(`/logs/${t}`)}listLogTransports(){return this.request("/logs/transports")}getMcpServers(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));const n=t.toString();return this.request(`/mcp/v0/servers${n?`?${n}`:""}`)}getMcpServerDetails(e,t){const n=new URLSearchParams;t?.version&&n.set("version",t.version);const r=n.toString();return this.request(`/mcp/v0/servers/${e}${r?`?${r}`:""}`)}getMcpServerTools(e){return this.request(`/mcp/${e}/tools`)}getMcpServerTool(e,t){return new Mhn(this.options,e,t)}getMcpServerResources(e){return this.request(`/mcp/${encodeURIComponent(e)}/resources`)}readMcpServerResource(e,t){return this.request(`/mcp/${encodeURIComponent(e)}/resources/read`,{method:"POST",body:{uri:t}})}getA2A(e){return new Phn(this.options,e)}getA2AV1(e){return new $hn(this.options,e)}getWorkingMemory({agentId:e,threadId:t,resourceId:n,requestContext:r}){return this.request(`/memory/threads/${t}/working-memory?agentId=${e}&resourceId=${n}${sn(r,"&")}`)}searchMemory({agentId:e,resourceId:t,threadId:n,searchQuery:r,memoryConfig:s,requestContext:a}){const i=new URLSearchParams({searchQuery:r,resourceId:t,agentId:e});return n&&i.append("threadId",n),s&&i.append("memoryConfig",JSON.stringify(s)),this.request(`/memory/search?${i}${sn(a,"&")}`)}updateWorkingMemory({agentId:e,threadId:t,workingMemory:n,resourceId:r,requestContext:s}){return this.request(`/memory/threads/${t}/working-memory?agentId=${e}${sn(s,"&")}`,{method:"POST",body:{workingMemory:n,resourceId:r}})}listScorers(e){return this.request(`/scores/scorers${sn(e)}`)}getScorer(e){return this.request(`/scores/scorers/${encodeURIComponent(e)}`)}listScoresByScorerId(e){const{page:t,perPage:n,scorerId:r,entityId:s,entityType:a}=e,i=new URLSearchParams;s&&i.set("entityId",s),a&&i.set("entityType",a),t!==void 0&&i.set("page",String(t)),n!==void 0&&i.set("perPage",String(n));const l=i.toString();return this.request(`/scores/scorer/${encodeURIComponent(r)}${l?`?${l}`:""}`)}listScoresByRunId(e){const{runId:t,page:n,perPage:r}=e,s=new URLSearchParams;n!==void 0&&s.set("page",String(n)),r!==void 0&&s.set("perPage",String(r));const a=s.toString();return this.request(`/scores/run/${encodeURIComponent(t)}${a?`?${a}`:""}`)}listScoresByEntityId(e){const{entityId:t,entityType:n,page:r,perPage:s}=e,a=new URLSearchParams;r!==void 0&&a.set("page",String(r)),s!==void 0&&a.set("perPage",String(s));const i=a.toString();return this.request(`/scores/entity/${encodeURIComponent(n)}/${encodeURIComponent(t)}${i?`?${i}`:""}`)}saveScore(e){return this.request("/scores",{method:"POST",body:e})}getTrace(e){return this.observability.getTrace(e)}getTraceLight(e){return this.observability.getTraceLight(e)}getSpan(e,t){return this.observability.getSpan(e,t)}getTraceTrajectory(e){return this.observability.getTraceTrajectory(e)}getTraces(e){return this.observability.getTraces(e)}listTraces(e={}){return this.observability.listTraces(e)}listTracesLight(e={}){return this.observability.listTracesLight(e)}listBranches(e={}){return this.observability.listBranches(e)}getBranch(e){return this.observability.getBranch(e)}listScoresBySpan(e){return this.observability.listScoresBySpan(e)}score(e){return this.observability.score(e)}listLogsVNext(e={}){return this.observability.listLogs(e)}listScores(e={}){return this.observability.listScores(e)}createScore(e){return this.observability.createScore(e)}getScoreAggregate(e){return this.observability.getScoreAggregate(e)}getScoreBreakdown(e){return this.observability.getScoreBreakdown(e)}getScoreTimeSeries(e){return this.observability.getScoreTimeSeries(e)}getScorePercentiles(e){return this.observability.getScorePercentiles(e)}listFeedback(e={}){return this.observability.listFeedback(e)}createFeedback(e){return this.observability.createFeedback(e)}updateFeedbackReviewStatus(e){return this.observability.updateFeedbackReviewStatus(e)}getFeedbackAggregate(e){return this.observability.getFeedbackAggregate(e)}getFeedbackBreakdown(e){return this.observability.getFeedbackBreakdown(e)}getFeedbackTimeSeries(e){return this.observability.getFeedbackTimeSeries(e)}getFeedbackPercentiles(e){return this.observability.getFeedbackPercentiles(e)}getMetricAggregate(e){return this.observability.getMetricAggregate(e)}getMetricBreakdown(e){return this.observability.getMetricBreakdown(e)}getMetricTimeSeries(e){return this.observability.getMetricTimeSeries(e)}getMetricPercentiles(e){return this.observability.getMetricPercentiles(e)}getMetricNames(e={}){return this.observability.getMetricNames(e)}getMetricLabelKeys(e){return this.observability.getMetricLabelKeys(e)}getMetricLabelValues(e){return this.observability.getMetricLabelValues(e)}getEntityTypes(){return this.observability.getEntityTypes()}getEntityNames(e={}){return this.observability.getEntityNames(e)}getServiceNames(){return this.observability.getServiceNames()}getEnvironments(){return this.observability.getEnvironments()}getTags(e={}){return this.observability.getTags(e)}listStoredAgents(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction)),e?.status&&t.set("status",e.status),e?.authorId&&t.set("authorId",e.authorId),e?.visibility&&t.set("visibility",e.visibility),e?.metadata&&t.set("metadata",JSON.stringify(e.metadata)),e?.favoritedOnly&&t.set("favoritedOnly","true"),e?.pinFavoritedFor&&t.set("pinFavoritedFor",e.pinFavoritedFor);const n=t.toString();return this.request(`/stored/agents${n?`?${n}`:""}`)}createStoredAgent(e){return this.request("/stored/agents",{method:"POST",body:e})}getStoredAgent(e){return new Fhn(this.options,e)}listDynamicWorkflows(e){const t=new URLSearchParams;e?.status&&t.set("status",e.status),e?.authorId&&t.set("authorId",e.authorId);const n=t.toString();return this.request(`/stored/workflows${n?`?${n}`:""}`)}upsertDynamicWorkflow(e){return this.request("/stored/workflows",{method:"POST",body:e})}getDynamicWorkflow(e){return new zhn(this.options,e)}listStoredPromptBlocks(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction)),e?.authorId&&t.set("authorId",e.authorId),e?.status&&t.set("status",e.status),e?.metadata&&t.set("metadata",JSON.stringify(e.metadata));const n=t.toString();return this.request(`/stored/prompt-blocks${n?`?${n}`:""}`)}createStoredPromptBlock(e){return this.request("/stored/prompt-blocks",{method:"POST",body:e})}getStoredPromptBlock(e){return new Bhn(this.options,e)}listStoredScorers(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction)),e?.authorId&&t.set("authorId",e.authorId),e?.metadata&&t.set("metadata",JSON.stringify(e.metadata));const n=t.toString();return this.request(`/stored/scorers${n?`?${n}`:""}`)}createStoredScorer(e){return this.request("/stored/scorers",{method:"POST",body:e})}getStoredScorer(e){return new qhn(this.options,e)}listStoredMCPClients(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction)),e?.authorId&&t.set("authorId",e.authorId),e?.metadata&&t.set("metadata",JSON.stringify(e.metadata));const n=t.toString();return this.request(`/stored/mcp-clients${n?`?${n}`:""}`)}createStoredMCPClient(e){return this.request("/stored/mcp-clients",{method:"POST",body:e})}getStoredMCPClient(e){return new Uhn(this.options,e)}listStoredSkills(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction)),e?.authorId&&t.set("authorId",e.authorId),e?.visibility&&t.set("visibility",e.visibility),e?.metadata&&t.set("metadata",JSON.stringify(e.metadata)),e?.favoritedOnly&&t.set("favoritedOnly","true"),e?.pinFavoritedFor&&t.set("pinFavoritedFor",e.pinFavoritedFor);const n=t.toString();return this.request(`/stored/skills${n?`?${n}`:""}`)}createStoredSkill(e){return this.request("/stored/skills",{method:"POST",body:e})}getStoredSkill(e){return new Ghn(this.options,e)}listToolProviders(){return this.request("/tool-providers")}getToolProvider(e){return new Vhn(this.options,e)}getProcessorProviders(){return this.request("/processor-providers")}getProcessorProvider(e){return new Hhn(this.options,e)}getSystemPackages(){return this.request("/system/packages")}getBuilderSettings(){return this.request("/editor/builder/settings")}getBuilderAvailableModels(){return this.request("/editor/builder/models/available")}getPermissionPatterns(){return this.request("/auth/permission-patterns")}getInfrastructureStatus(){return this.request("/editor/builder/infrastructure")}listBuilderRegistries(){return this.request("/editor/builder/registries")}searchBuilderRegistry(e,t){const n=new URLSearchParams({q:t.q});return t.limit!==void 0&&n.set("limit",String(t.limit)),this.request(`/editor/builder/registries/${encodeURIComponent(e)}/search?${n.toString()}`)}getBuilderRegistryPopular(e,t){const n=new URLSearchParams;t?.limit!==void 0&&n.set("limit",String(t.limit)),t?.offset!==void 0&&n.set("offset",String(t.offset));const r=n.toString();return this.request(`/editor/builder/registries/${encodeURIComponent(e)}/popular${r?`?${r}`:""}`)}getBuilderRegistryPreview(e,t){const n=new URLSearchParams({owner:t.owner,repo:t.repo,path:t.path});return this.request(`/editor/builder/registries/${encodeURIComponent(e)}/preview?${n.toString()}`)}installBuilderRegistrySkill(e,t){return this.request(`/editor/builder/registries/${encodeURIComponent(e)}/install`,{method:"POST",body:t})}listWorkspaces(){return this.request("/workspaces")}getWorkspace(e){return new Zhn(this.options,e)}listStoredWorkspaces(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.authorId&&t.set("authorId",e.authorId),e?.orderBy?.field&&t.set("orderBy[field]",e.orderBy.field),e?.orderBy?.direction&&t.set("orderBy[direction]",e.orderBy.direction);const n=t.toString();return this.request(`/stored/workspaces${n?`?${n}`:""}`)}getStoredWorkspace(e){return this.request(`/stored/workspaces/${encodeURIComponent(e)}`)}listVectors(){return this.request("/vectors")}listEmbedders(){return this.request("/embedders")}listDatasets(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage));const n=t.toString();return this.request(`/datasets${n?`?${n}`:""}`)}getDataset(e,t){const n=tJ(t);return this.request(`/datasets/${encodeURIComponent(e)}${n}`)}createDataset(e){return this.request("/datasets",{method:"POST",body:e})}updateDataset(e){const{datasetId:t,organizationId:n,projectId:r,...s}=e,a=tJ({organizationId:n,projectId:r});return this.request(`/datasets/${encodeURIComponent(t)}${a}`,{method:"PATCH",body:s})}deleteDataset(e,t){const n=tJ(t);return this.request(`/datasets/${encodeURIComponent(e)}${n}`,{method:"DELETE"})}listDatasetItems(e,t){const n=new URLSearchParams;t?.page!==void 0&&n.set("page",String(t.page)),t?.perPage!==void 0&&n.set("perPage",String(t.perPage)),t?.search&&n.set("search",t.search),t?.version!=null&&n.set("version",String(t.version));const r=n.toString();return this.request(`/datasets/${encodeURIComponent(e)}/items${r?`?${r}`:""}`)}getDatasetItem(e,t){return this.request(`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`)}addDatasetItem(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/items`,{method:"POST",body:n})}updateDatasetItem(e){const{datasetId:t,itemId:n,...r}=e;return this.request(`/datasets/${encodeURIComponent(t)}/items/${encodeURIComponent(n)}`,{method:"PATCH",body:r})}deleteDatasetItem(e,t){return this.request(`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`,{method:"DELETE"})}batchInsertDatasetItems(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/items/batch`,{method:"POST",body:n})}batchDeleteDatasetItems(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/items/batch`,{method:"DELETE",body:n})}generateDatasetItems(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/generate-items`,{method:"POST",body:n})}clusterFailures(e){return this.request("/datasets/cluster-failures",{method:"POST",body:e})}getItemHistory(e,t){return this.request(`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}/history`)}getDatasetItemVersion(e,t,n){return this.request(`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}/versions/${n}`)}listDatasetVersions(e,t){const n=new URLSearchParams;t?.page!==void 0&&n.set("page",String(t.page)),t?.perPage!==void 0&&n.set("perPage",String(t.perPage));const r=n.toString();return this.request(`/datasets/${encodeURIComponent(e)}/versions${r?`?${r}`:""}`)}listExperiments(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.experimentSetId!==void 0&&t.set("experimentSetId",e.experimentSetId),e?.comparisonId!==void 0&&t.set("comparisonId",e.comparisonId),e?.variantId!==void 0&&t.set("variantId",e.variantId),e?.trialIndex!==void 0&&t.set("trialIndex",String(e.trialIndex));const n=t.toString();return this.request(`/experiments${n?`?${n}`:""}`)}getExperimentReviewSummary(){return this.request("/experiments/review-summary")}listDatasetExperiments(e,t){const n=new URLSearchParams;t?.page!==void 0&&n.set("page",String(t.page)),t?.perPage!==void 0&&n.set("perPage",String(t.perPage)),t?.experimentSetId!==void 0&&n.set("experimentSetId",t.experimentSetId),t?.comparisonId!==void 0&&n.set("comparisonId",t.comparisonId),t?.variantId!==void 0&&n.set("variantId",t.variantId),t?.trialIndex!==void 0&&n.set("trialIndex",String(t.trialIndex));const r=n.toString();return this.request(`/datasets/${encodeURIComponent(e)}/experiments${r?`?${r}`:""}`)}getDatasetExperiment(e,t){return this.request(`/datasets/${encodeURIComponent(e)}/experiments/${encodeURIComponent(t)}`)}updateDatasetExperiment(e){const{datasetId:t,experimentId:n,...r}=e;return this.request(`/datasets/${encodeURIComponent(t)}/experiments/${encodeURIComponent(n)}`,{method:"PATCH",body:r})}listDatasetExperimentResults(e,t,n){const r=new URLSearchParams;n?.page!==void 0&&r.set("page",String(n.page)),n?.perPage!==void 0&&r.set("perPage",String(n.perPage));const s=r.toString();return this.request(`/datasets/${encodeURIComponent(e)}/experiments/${encodeURIComponent(t)}/results${s?`?${s}`:""}`)}updateDatasetExperimentResult(e){const{datasetId:t,experimentId:n,resultId:r,...s}=e;return this.request(`/datasets/${encodeURIComponent(t)}/experiments/${encodeURIComponent(n)}/results/${encodeURIComponent(r)}`,{method:"PATCH",body:s})}triggerDatasetExperiment(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/experiments`,{method:"POST",body:n})}createDatasetExperiment(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/experiments`,{method:"POST",body:{...n,start:!1}})}runExperimentItem(e){const{datasetId:t,experimentId:n,itemId:r,...s}=e;return this.request(`/datasets/${encodeURIComponent(t)}/experiments/${encodeURIComponent(n)}/items/${encodeURIComponent(r)}/run`,{method:"POST",body:s})}submitExperimentResult(e){const{datasetId:t,experimentId:n,...r}=e;return this.request(`/datasets/${encodeURIComponent(t)}/experiments/${encodeURIComponent(n)}/results`,{method:"POST",body:r})}finalizeExperiment(e){const{datasetId:t,experimentId:n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/experiments/${encodeURIComponent(n)}/finalize`,{method:"POST",body:{}})}updateExperimentResult(e){const{datasetId:t,experimentId:n,resultId:r,...s}=e;return this.request(`/datasets/${encodeURIComponent(t)}/experiments/${encodeURIComponent(n)}/results/${encodeURIComponent(r)}`,{method:"PATCH",body:s})}compareExperiments(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/compare`,{method:"POST",body:n})}listBackgroundTasks(e={}){const t=new URLSearchParams;e.agentId&&t.set("agentId",e.agentId),e.status&&t.set("status",e.status),e.runId&&t.set("runId",e.runId),e.threadId&&t.set("threadId",e.threadId),e.resourceId&&t.set("resourceId",e.resourceId),e.toolName&&t.set("toolName",e.toolName),e.toolCallId&&t.set("toolCallId",e.toolCallId),e.fromDate&&t.set("fromDate",e.fromDate.toISOString()),e.toDate&&t.set("toDate",e.toDate.toISOString()),e.dateFilterBy&&t.set("dateFilterBy",e.dateFilterBy),e.orderBy&&t.set("orderBy",e.orderBy),e.orderDirection&&t.set("orderDirection",e.orderDirection),e.page!==void 0&&t.set("page",String(e.page)),e.perPage!==void 0&&t.set("perPage",String(e.perPage));const n=t.toString();return this.request(`/background-tasks${n?`?${n}`:""}`)}getBackgroundTask(e){return this.request(`/background-tasks/${encodeURIComponent(e)}`)}async streamBackgroundTasks(e={}){const t=new URLSearchParams;e.agentId&&t.set("agentId",e.agentId),e.runId&&t.set("runId",e.runId),e.threadId&&t.set("threadId",e.threadId),e.resourceId&&t.set("resourceId",e.resourceId),e.taskId&&t.set("taskId",e.taskId);const n=t.toString(),r=await this.request(`/background-tasks/stream${n?`?${n}`:""}`,{stream:!0});if(!r.ok)throw new Error(`Failed to stream background tasks: ${r.statusText}`);if(!r.body)throw new Error("Response body is null");return r.body.pipeThrough(whn())}listSchedules(e={}){const t=new URLSearchParams;e.agentId&&t.set("agentId",e.agentId),e.workflowId&&t.set("workflowId",e.workflowId),e.status&&t.set("status",e.status),e.threadId&&t.set("threadId",e.threadId),e.resourceId&&t.set("resourceId",e.resourceId),e.name&&t.set("name",e.name);const n=t.toString();return this.request(`/schedules${n?`?${n}`:""}`)}getSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}`)}createSchedule(e){return this.request("/schedules",{method:"POST",body:e})}updateSchedule(e,t){return this.request(`/schedules/${encodeURIComponent(e)}`,{method:"PATCH",body:t})}deleteSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}`,{method:"DELETE"})}runSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}/run`,{method:"POST"})}listScheduleTriggers(e,t={}){const n=new URLSearchParams;t.limit!==void 0&&n.set("limit",String(t.limit)),t.fromActualFireAt!==void 0&&n.set("fromActualFireAt",String(t.fromActualFireAt)),t.toActualFireAt!==void 0&&n.set("toActualFireAt",String(t.toActualFireAt));const r=n.toString();return this.request(`/schedules/${encodeURIComponent(e)}/triggers${r?`?${r}`:""}`)}pauseSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}/pause`,{method:"POST"})}resumeSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}/resume`,{method:"POST"})}},lmn=class{id;description;inputSchema;outputSchema;execute;constructor(e){this.id=e.id,this.description=e.description,this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.execute=e.execute}};function Dg(e){return new lmn(e)}const cmn=()=>!0;async function umn(e,t={},n=3,r={}){let s=0,a=null;const i=r.shouldRetryResponse??cmn;for(;s<n;){let l;try{l=await fetch(e,t)}catch(u){a=u instanceof Error?u:new Error(String(u))}if(l){if(l.ok)return l;if(a=new Error(`Request failed with status: ${l.status} ${l.statusText}`),!i(l))throw a}if(s++,s>=n)break;const c=Math.min(1e3*Math.pow(2,s),1e4);await new Promise(u=>setTimeout(u,c))}throw a||new Error("Request failed after multiple retry attempts")}function Vhe(e,t){if(e===t)return!0;if(e==null||t==null)return e===t;if(typeof e!=typeof t||Array.isArray(e)!==Array.isArray(t)||e instanceof Date!=t instanceof Date)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length!==t.length?!1:e.every((n,r)=>Vhe(n,t[r]));if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(typeof e=="object"&&typeof t=="object"){const n=e,r=t,s=Object.keys(n),a=Object.keys(r);return s.length!==a.length?!1:s.every(i=>Object.prototype.hasOwnProperty.call(r,i)&&Vhe(n[i],r[i]))}return!1}function mg(e,t,n){const r=e?.mastra,s=r?.toolPayloadTransform?.[t]?.[n]??r?.toolPayloadProjection?.[t]?.[n];if(s&&Object.prototype.hasOwnProperty.call(s,"projected")&&!Object.prototype.hasOwnProperty.call(s,"transformed")){const{projected:a,...i}=s;return{...i,transformed:a}}return s}function Mu(e){return!!(e&&Object.prototype.hasOwnProperty.call(e,"transformed"))}var opt="vercel.ai.error",dmn=Symbol.for(opt),u3e,d3e,f3e=class lpt extends(d3e=Error,u3e=dmn,d3e){constructor({name:t,message:n,cause:r}){super(n),this[u3e]=!0,this.name=t,this.cause=r}static isInstance(t){return lpt.hasMarker(t,opt)}static hasMarker(t,n){const r=Symbol.for(n);return t!=null&&typeof t=="object"&&r in t&&typeof t[r]=="boolean"&&t[r]===!0}},cpt="AI_InvalidArgumentError",upt=`vercel.ai.error.${cpt}`,fmn=Symbol.for(upt),p3e,h3e,pmn=class extends(h3e=f3e,p3e=fmn,h3e){constructor({message:t,cause:n,argument:r}){super({name:cpt,message:t,cause:n}),this[p3e]=!0,this.argument=r}static isInstance(t){return f3e.hasMarker(t,upt)}},{btoa:hmn,atob:mmn}=globalThis;function dpt(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=mmn(t);return Uint8Array.from(n,r=>r.codePointAt(0))}function Hhe(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return hmn(t)}var gmn=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const s=()=>{const a=n.length,i=new Array(t);for(let l=0;l<t;l++)i[l]=n[Math.random()*a|0];return i.join("")};if(e==null)return s;if(n.includes(r))throw new pmn({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${s()}`};gmn();function vmn({mediaType:e,url:t,supportedUrls:n}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(n).map(([r,s])=>{const a=r.toLowerCase();return a==="*"||a==="*/*"?{mediaTypePrefix:"",regexes:s}:{mediaTypePrefix:a.replace(/\*/,""),regexes:s}}).filter(({mediaTypePrefix:r})=>e.startsWith(r)).flatMap(({regexes:r})=>r).some(r=>r.test(t))}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");new TextDecoder;function IO(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Hhe(new Uint8Array(e)):Hhe(e)}function ymn(e){if(e.role!=="signal")return!1;const t=e.content?.metadata;if(!t||typeof t!="object")return!1;const n=t.signal;return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.transient===!0}function fpt(e){if(e.type==="user-message")return{type:"user",tagName:e.tagName??"user"};if(e.type==="system-reminder")return{type:"reactive",tagName:e.tagName??"system-reminder"};if(e.type==="user"||e.type==="state"||e.type==="notification")return{type:e.type,tagName:e.tagName??e.type};if(e.type==="reactive")return{type:"reactive",tagName:e.tagName??"system-reminder"};throw new Error(`Invalid signal type: ${e.type}. Use a supported signal type and set tagName for custom XML tags.`)}function bmn(e){const{type:t,tagName:n}=fpt(e);return{...e,type:t,tagName:n,id:e.id??crypto.randomUUID(),createdAt:e.createdAt instanceof Date?e.createdAt:e.createdAt?new Date(e.createdAt):new Date,acceptedAt:e.acceptedAt instanceof Date?e.acceptedAt:e.acceptedAt?new Date(e.acceptedAt):void 0}}function ppt(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function xmn(e){return ppt(e).replaceAll('"',""")}const wmn=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function hpt(e,t){if(!wmn.test(e))throw new Error(`Invalid signal XML ${t}: ${e}`)}function Smn(e){if(!e)return"";const t=Object.entries(e).filter(n=>n[1]!==null&&n[1]!==void 0).map(([n,r])=>(hpt(n,"attribute name"),`${n}="${xmn(String(r))}"`)).join(" ");return t?` ${t}`:""}function Whe(e){const t=e.tagName??fpt(e).tagName;hpt(t,"tag name");const n=Smn(e.attributes);return e.contents?`<${t}${n}>${ppt(e.contents)}</${t}>`:`<${t}${n} />`}function kmn(e){if(typeof e=="string")return e;if(Array.isArray(e)){const n=[];for(const r of e){if(typeof r=="string"){n.push({type:"text",text:r});continue}const s=m3e(r);if(!s)return;n.push(...s)}return v3e(n)}const t=m3e(e);return t?v3e(t):void 0}function m3e(e){if(!e||typeof e!="object")return;const t=e;if(t.role==="user"&&"content"in t){const r=t.content;if(typeof r=="string")return[{type:"text",text:r}];if(Array.isArray(r)){const s=[];for(const a of r){const i=g3e(a);if(!i)return;s.push(i)}return s}return}const n=g3e(t);return n?[n]:void 0}function g3e(e){if(!e||typeof e!="object")return;const t=e,n=t.providerOptions&&typeof t.providerOptions=="object"&&!Array.isArray(t.providerOptions)?t.providerOptions:void 0;if(t.type==="text"&&typeof t.text=="string")return{type:"text",text:t.text,...n?{providerOptions:n}:{}};if(t.type==="file"||t.type==="image"){const r=t.type==="image"?t.image??t.data:t.data;if(typeof r!="string")return;const s=typeof t.mediaType=="string"?t.mediaType:typeof t.mimeType=="string"?t.mimeType:t.type==="image"?"image/png":"";return s?{type:"file",data:r,mediaType:s,...typeof t.filename=="string"?{filename:t.filename}:{},...n?{providerOptions:n}:{}}:void 0}}function v3e(e){if(e.length===0)return;const t=e[0];return e.length===1&&t?.type==="text"?t.text:e}function Omn(e){return typeof e=="string"?[{type:"text",text:e}]:e.map(t=>t.type==="file"?{type:"file",data:t.data instanceof URL?t.data.toString():IO(t.data),mediaType:t.mediaType,...t.filename?{filename:t.filename}:{},...t.providerOptions?{providerOptions:t.providerOptions}:{}}:{type:"text",text:t.text,...t.providerOptions?{providerOptions:t.providerOptions}:{}})}function _mn(e){const t=[];for(const n of e){const r=n.providerMetadata;if(n.type==="text")t.push({type:"text",text:n.text,...r?{providerOptions:r}:{}});else if(n.type==="file"&&typeof n.data=="string"){const s=n;t.push({type:"file",data:s.data,mediaType:typeof s.mimeType=="string"?s.mimeType:"",...typeof s.filename=="string"?{filename:s.filename}:{},...r?{providerOptions:r}:{}})}}return t}function mpt(e){return e.length===1&&e[0]?.type==="text"&&!e[0].providerOptions?e[0].text:e.map(t=>t.type==="file"?{type:"file",data:t.data,mediaType:t.mediaType,...t.filename?{filename:t.filename}:{},...t.providerOptions?{providerOptions:t.providerOptions}:{}}:{type:"text",text:t.text,...t.providerOptions?{providerOptions:t.providerOptions}:{}})}function Cmn(e){return e?Object.keys(e).some(t=>{const n=e[t];return n!=null}):!1}function Emn(e,t){let n=!1;const r=[];for(const s of t)!n&&s.type==="text"?(n=!0,r.push({...s,text:Whe({...e,contents:s.text})})):r.push(s);if(!n){const s=Whe({type:e.type,tagName:e.tagName,attributes:e.attributes});r.unshift({type:"text",text:s})}return r}function Tmn(e,t){const n=e.type==="user",r=Cmn(e.attributes),s=t.some(i=>i.providerOptions);let a;return n&&!r?a=t.length===1&&t[0]?.type==="text"&&!t[0].providerOptions?t[0].text:t:t.every(i=>i.type==="text")&&!s?a=Whe({...e,contents:t.map(i=>i.text).join(`
|
|
117
|
+
`),length:2},{index:k.indexOf("\r\r"),length:2}].filter(C=>C.index!==-1);return _.length===0?null:_.reduce((C,T)=>T.index<C.index?T:C)},m=async k=>{const _=k.body.getReader();i=_;const C=new TextDecoder;let T="";try{for(;!a;){const{done:E,value:N}=await _.read();if(E)return a?{kind:"cancelled"}:{kind:"done"};T+=C.decode(N,{stream:!0});let I;for(;(I=h(T))!==null;){const A=T.slice(0,I.index);T=T.slice(I.index+I.length);for(const R of A.split(/\r\n|\n|\r/)){if(!R.startsWith("data:"))continue;const L=R.slice(5).trim();if(!L)continue;let M;try{M=amn(JSON.parse(L))}catch{continue}try{e.onEvent(M)}catch(F){return a||v(F),{kind:"consumer_error"}}}}}return{kind:"cancelled"}}catch(E){return a?{kind:"cancelled"}:{kind:"transport_error",error:E}}finally{i===_&&(i=null),_.cancel().catch(()=>{})}},v=k=>{try{e.onError?.(k)}catch{}},y=k=>{v(k.kind==="transport_error"?k.error:p())},b=async k=>{try{return await m(k)}catch(_){return a?{kind:"cancelled"}:{kind:"transport_error",error:_}}},x=await f();return(async k=>{let _=k;for(;!a;){let C=await b(_);if(a||C.kind==="cancelled"||C.kind==="consumer_error")return;if(!r){y(C);return}let T=0,E;for(;!E;){if(T>=r.maxRetries){y(C);return}if(T++,await d(s(T)),a)return;try{E=await f()}catch(N){C={kind:"transport_error",error:N}}}if(a){E.body?.cancel().catch(()=>{});return}_=E;try{e.onReconnect?.()}catch{}}})(x),{unsubscribe:()=>{a=!0,u(),i?.cancel().catch(()=>{})}}}async sendMessage(e,t){const{content:n,files:r}=typeof e=="string"?{content:e,files:void 0}:e,s=lr(t?.requestContext);await this.request(this.url(`${this.base()}/messages`),{method:"POST",body:{message:n,...r?.length?{files:r}:{},...s?{requestContext:s}:{}}})}async abort(){await this.request(this.url(`${this.base()}/abort`),{method:"POST"})}async approveTool(e,t,n){const r=lr(n?.requestContext);await this.request(this.url(`${this.base()}/tool-approval`),{method:"POST",body:{toolCallId:e,approved:t,...r?{requestContext:r}:{}}})}async respondToToolSuspension(e,t,n){const r=lr(n?.requestContext);await this.request(this.url(`${this.base()}/tool-suspension`),{method:"POST",body:{toolCallId:e,resumeData:t,...r?{requestContext:r}:{}}})}async steer(e,t){const n=lr(t?.requestContext);await this.request(this.url(`${this.base()}/steer`),{method:"POST",body:{message:e,...n?{requestContext:n}:{}}})}state(e){const t=e?.threadId?`${this.base()}?threadId=${encodeURIComponent(e.threadId)}`:this.base();return this.request(this.url(t))}async setState(e){await this.request(this.url(`${this.base()}/state`),{method:"PUT",body:{state:e}})}async switchMode(e){await this.request(this.url(`${this.base()}/mode`),{method:"POST",body:{modeId:e}})}async switchModel(e,t){await this.request(this.url(`${this.base()}/model`),{method:"POST",body:{modelId:e,scope:t?.scope,modeId:t?.modeId}})}async listThreads(e){const t=typeof e=="number"?{limit:e}:e??{},n=new URLSearchParams;t.limit!=null&&n.set("limit",String(t.limit)),t.tags&&Object.keys(t.tags).length>0&&n.set("tags",JSON.stringify(t.tags));const r=n.toString()?`?${n.toString()}`:"";return(await this.request(this.url(`${this.base()}/threads${r}`))).threads}async switchThread(e){await this.request(this.url(`${this.base()}/thread`),{method:"POST",body:{threadId:e}})}async createThread(e){return this.request(this.url(`${this.base()}/threads`),{method:"POST",body:{title:e}})}async deleteThread(e){await this.request(this.url(`${this.base()}/threads/${encodeURIComponent(e)}`),{method:"DELETE"})}async renameThread(e,t){await this.request(this.url(`${this.base()}/threads/${encodeURIComponent(e)}`),{method:"PUT",body:{title:t}})}async cloneThread(e){return this.request(this.url(`${this.base()}/threads/clone`),{method:"POST",body:e??{}})}async listMessages(e,t){const n=t!=null?`?limit=${t}`:"";return(await this.request(this.url(`${this.base()}/threads/${encodeURIComponent(e)}/messages${n}`))).messages.map(ipt)}async followUp(e,t){const n=lr(t?.requestContext);await this.request(this.url(`${this.base()}/follow-up`),{method:"POST",body:{message:e,...n?{requestContext:n}:{}}})}async getOMRecord(){return(await this.request(this.url(`${this.base()}/om`))).record}async setResourceId(e){await this.request(this.url(`${this.base()}/resource`),{method:"POST",body:{newResourceId:e}})}async getResourceIds(){return(await this.request(this.url(`${this.base()}/resources`))).resourceIds}async getGoal(){return(await this.request(this.url(`${this.base()}/goal`))).goal}async setGoal(e,t){return(await this.request(this.url(`${this.base()}/goal`),{method:"POST",body:{objective:e,...t}})).goal}async updateGoal(e){return(await this.request(this.url(`${this.base()}/goal`),{method:"PUT",body:e})).goal}async clearGoal(){await this.request(this.url(`${this.base()}/goal`),{method:"DELETE"})}async getPermissions(){return this.request(this.url(`${this.base()}/permissions`))}async setPermissionForCategory(e,t){await this.request(this.url(`${this.base()}/permissions/category`),{method:"PUT",body:{category:e,policy:t}})}async setPermissionForTool(e,t){await this.request(this.url(`${this.base()}/permissions/tool`),{method:"PUT",body:{toolName:e,policy:t}})}async sendNotification(e){return this.request(this.url(`${this.base()}/notifications`),{method:"POST",body:e})}},omn=class extends Ha{controllerId;constructor(e,t){super(e),this.controllerId=t}basePath(){return`/agent-controller/${encodeURIComponent(this.controllerId)}`}async listModes(){return(await this.request(`${this.basePath()}/modes`)).modes}async listModels(){return(await this.request(`${this.basePath()}/models`)).models}async listActiveRuns(){return(await this.request(`${this.basePath()}/active-runs`)).runs}async workspaceStatus(){return this.request(`${this.basePath()}/workspace`)}session(e,t){return new imn(this.options,this.controllerId,e,t)}},DP=class extends Ha{observability;conversations;responses;channels;constructor(e){super(e),this.observability=new Lhn(e),this.conversations=new xhn(e),this.responses=new Jhn(e),this.channels=new emn(e)}listAgents(e,t){const n=vw(lr(e)),r=new URLSearchParams;n&&r.set("requestContext",n),t&&r.set("partial","true");const s=r.toString();return this.request(`/agents${s?`?${s}`:""}`)}listAgentsModelProviders(){return this.request("/agents/providers")}getAgent(e,t){return new phn(this.options,e,t)}async listAgentControllers(){return(await this.request("/agent-controller")).agentControllers}getAgentController(e){return new omn(this.options,e)}async listMemoryThreads(e={}){const t=new URLSearchParams;e.resourceId&&t.set("resourceId",e.resourceId),e.metadata&&t.set("metadata",JSON.stringify(e.metadata)),e.agentId&&t.set("agentId",e.agentId),e.page!==void 0&&t.set("page",e.page.toString()),e.perPage!==void 0&&t.set("perPage",e.perPage.toString()),e.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction));const n=t.toString(),r=await this.request(`/memory/threads${n?`?${n}`:""}${sn(e.requestContext,n?"&":"?")}`);return"threads"in r?r:{threads:r,total:r.length,page:e.page??0,perPage:e.perPage??100,hasMore:!1}}getMemoryConfig(e){return this.request(`/memory/config?agentId=${e.agentId}${sn(e.requestContext,"&")}`)}createMemoryThread(e){return this.request(`/memory/threads?agentId=${e.agentId}${sn(e.requestContext,"&")}`,{method:"POST",body:e})}getMemoryThread({threadId:e,agentId:t}){return new hhn(this.options,e,t)}listThreadMessages(e,t={}){let n="";const r=t.includeSystemReminders===void 0?"":`includeSystemReminders=${t.includeSystemReminders}`;return t.networkId?n=`/memory/network/threads/${e}/messages?networkId=${t.networkId}${r?`&${r}`:""}${sn(t.requestContext,"&")}`:t.agentId?n=`/memory/threads/${e}/messages?agentId=${t.agentId}${r?`&${r}`:""}${sn(t.requestContext,"&")}`:n=`/memory/threads/${e}/messages${r?`?${r}`:""}${sn(t.requestContext,r?"&":"?")}`,this.request(n)}deleteThread(e,t){if(!t||!!t.agentId==!!t.networkId)throw new Error("MastraClient.deleteThread() requires exactly one of agentId or networkId. The server cannot resolve which memory store owns the thread without one, and passing both is ambiguous.");const n=t.agentId?`/memory/threads/${e}?agentId=${t.agentId}${sn(t.requestContext,"&")}`:`/memory/network/threads/${e}?networkId=${t.networkId}${sn(t.requestContext,"&")}`;return this.request(n,{method:"DELETE"})}saveMessageToMemory(e){return this.request(`/memory/save-messages?agentId=${e.agentId}${sn(e.requestContext,"&")}`,{method:"POST",body:e})}getMemoryStatus(e,t,n){const r=new URLSearchParams({agentId:e});n?.resourceId&&r.set("resourceId",n.resourceId),n?.threadId&&r.set("threadId",n.threadId);const s=r.toString();return this.request(`/memory/status?${s}${sn(t,"&")}`)}getObservationalMemory(e){const t=new URLSearchParams({agentId:e.agentId});e.resourceId&&t.set("resourceId",e.resourceId),e.threadId&&t.set("threadId",e.threadId),e.from&&t.set("from",e.from instanceof Date?e.from.toISOString():e.from),e.to&&t.set("to",e.to instanceof Date?e.to.toISOString():e.to),e.offset!=null&&t.set("offset",String(e.offset)),e.limit!=null&&t.set("limit",String(e.limit));const n=t.toString();return this.request(`/memory/observational-memory?${n}${sn(e.requestContext,"&")}`)}awaitBufferStatus(e){return this.request(`/memory/observational-memory/buffer-status${sn(e.requestContext)}`,{method:"POST",body:{agentId:e.agentId,resourceId:e.resourceId,threadId:e.threadId}})}listTools(e){const t=vw(lr(e)),n=new URLSearchParams;t&&n.set("requestContext",t);const r=n.toString();return this.request(`/tools${r?`?${r}`:""}`)}getTool(e){return new vhn(this.options,e)}listProcessors(e){const t=vw(lr(e)),n=new URLSearchParams;t&&n.set("requestContext",t);const r=n.toString();return this.request(`/processors${r?`?${r}`:""}`)}getProcessor(e){return new yhn(this.options,e)}listWorkflows(e,t){const n=vw(lr(e)),r=new URLSearchParams;n&&r.set("requestContext",n),t&&r.set("partial","true");const s=r.toString();return this.request(`/workflows${s?`?${s}`:""}`)}listWorkflowRunCounts(e){const t=vw(lr(e)),n=new URLSearchParams;t&&n.set("requestContext",t);const r=n.toString();return this.request(`/workflows/run-counts${r?`?${r}`:""}`)}getWorkflow(e){return new Ohn(this.options,e)}getAgentBuilderActions(){return this.request("/agent-builder")}getAgentBuilderAction(e){return new Dhn(this.options,e)}getVector(e){return new ghn(this.options,e)}listLogs(e){const{transportId:t,fromDate:n,toDate:r,logLevel:s,filters:a,page:i,perPage:l}=e,c=a?Object.entries(a).map(([d,f])=>`${d}:${f}`):[],u=new URLSearchParams;if(t&&u.set("transportId",t),n&&u.set("fromDate",n.toISOString()),r&&u.set("toDate",r.toISOString()),s&&u.set("logLevel",s),i!==void 0&&u.set("page",String(i)),l!==void 0&&u.set("perPage",String(l)),c)if(Array.isArray(c))for(const d of c)u.append("filters",d);else u.set("filters",c);return u.size?this.request(`/logs?${u}`):this.request("/logs")}getLogForRun(e){const{runId:t,transportId:n,fromDate:r,toDate:s,logLevel:a,filters:i,page:l,perPage:c}=e,u=i?Object.entries(i).map(([f,p])=>`${f}:${p}`):[],d=new URLSearchParams;if(t&&d.set("runId",t),n&&d.set("transportId",n),r&&d.set("fromDate",r.toISOString()),s&&d.set("toDate",s.toISOString()),a&&d.set("logLevel",a),l!==void 0&&d.set("page",String(l)),c!==void 0&&d.set("perPage",String(c)),u)if(Array.isArray(u))for(const f of u)d.append("filters",f);else d.set("filters",u);return d.size?this.request(`/logs/${t}?${d}`):this.request(`/logs/${t}`)}listLogTransports(){return this.request("/logs/transports")}getMcpServers(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));const n=t.toString();return this.request(`/mcp/v0/servers${n?`?${n}`:""}`)}getMcpServerDetails(e,t){const n=new URLSearchParams;t?.version&&n.set("version",t.version);const r=n.toString();return this.request(`/mcp/v0/servers/${e}${r?`?${r}`:""}`)}getMcpServerTools(e){return this.request(`/mcp/${e}/tools`)}getMcpServerTool(e,t){return new Mhn(this.options,e,t)}getMcpServerResources(e){return this.request(`/mcp/${encodeURIComponent(e)}/resources`)}readMcpServerResource(e,t){return this.request(`/mcp/${encodeURIComponent(e)}/resources/read`,{method:"POST",body:{uri:t}})}getA2A(e){return new Phn(this.options,e)}getA2AV1(e){return new $hn(this.options,e)}getWorkingMemory({agentId:e,threadId:t,resourceId:n,requestContext:r}){return this.request(`/memory/threads/${t}/working-memory?agentId=${e}&resourceId=${n}${sn(r,"&")}`)}searchMemory({agentId:e,resourceId:t,threadId:n,searchQuery:r,memoryConfig:s,requestContext:a}){const i=new URLSearchParams({searchQuery:r,resourceId:t,agentId:e});return n&&i.append("threadId",n),s&&i.append("memoryConfig",JSON.stringify(s)),this.request(`/memory/search?${i}${sn(a,"&")}`)}updateWorkingMemory({agentId:e,threadId:t,workingMemory:n,resourceId:r,requestContext:s}){return this.request(`/memory/threads/${t}/working-memory?agentId=${e}${sn(s,"&")}`,{method:"POST",body:{workingMemory:n,resourceId:r}})}listScorers(e){return this.request(`/scores/scorers${sn(e)}`)}getScorer(e){return this.request(`/scores/scorers/${encodeURIComponent(e)}`)}listScoresByScorerId(e){const{page:t,perPage:n,scorerId:r,entityId:s,entityType:a}=e,i=new URLSearchParams;s&&i.set("entityId",s),a&&i.set("entityType",a),t!==void 0&&i.set("page",String(t)),n!==void 0&&i.set("perPage",String(n));const l=i.toString();return this.request(`/scores/scorer/${encodeURIComponent(r)}${l?`?${l}`:""}`)}listScoresByRunId(e){const{runId:t,page:n,perPage:r}=e,s=new URLSearchParams;n!==void 0&&s.set("page",String(n)),r!==void 0&&s.set("perPage",String(r));const a=s.toString();return this.request(`/scores/run/${encodeURIComponent(t)}${a?`?${a}`:""}`)}listScoresByEntityId(e){const{entityId:t,entityType:n,page:r,perPage:s}=e,a=new URLSearchParams;r!==void 0&&a.set("page",String(r)),s!==void 0&&a.set("perPage",String(s));const i=a.toString();return this.request(`/scores/entity/${encodeURIComponent(n)}/${encodeURIComponent(t)}${i?`?${i}`:""}`)}saveScore(e){return this.request("/scores",{method:"POST",body:e})}getTrace(e){return this.observability.getTrace(e)}getTraceLight(e){return this.observability.getTraceLight(e)}getSpan(e,t){return this.observability.getSpan(e,t)}getTraceTrajectory(e){return this.observability.getTraceTrajectory(e)}getTraces(e){return this.observability.getTraces(e)}listTraces(e={}){return this.observability.listTraces(e)}queryTraces(e){return this.observability.queryTraces(e)}listTracesLight(e={}){return this.observability.listTracesLight(e)}listBranches(e={}){return this.observability.listBranches(e)}getBranch(e){return this.observability.getBranch(e)}listScoresBySpan(e){return this.observability.listScoresBySpan(e)}score(e){return this.observability.score(e)}listLogsVNext(e={}){return this.observability.listLogs(e)}listScores(e={}){return this.observability.listScores(e)}createScore(e){return this.observability.createScore(e)}getScoreAggregate(e){return this.observability.getScoreAggregate(e)}getScoreBreakdown(e){return this.observability.getScoreBreakdown(e)}getScoreTimeSeries(e){return this.observability.getScoreTimeSeries(e)}getScorePercentiles(e){return this.observability.getScorePercentiles(e)}listFeedback(e={}){return this.observability.listFeedback(e)}createFeedback(e){return this.observability.createFeedback(e)}updateFeedbackReviewStatus(e){return this.observability.updateFeedbackReviewStatus(e)}getFeedbackAggregate(e){return this.observability.getFeedbackAggregate(e)}getFeedbackBreakdown(e){return this.observability.getFeedbackBreakdown(e)}getFeedbackTimeSeries(e){return this.observability.getFeedbackTimeSeries(e)}getFeedbackPercentiles(e){return this.observability.getFeedbackPercentiles(e)}getMetricAggregate(e){return this.observability.getMetricAggregate(e)}getMetricBreakdown(e){return this.observability.getMetricBreakdown(e)}getMetricTimeSeries(e){return this.observability.getMetricTimeSeries(e)}getMetricPercentiles(e){return this.observability.getMetricPercentiles(e)}getMetricNames(e={}){return this.observability.getMetricNames(e)}getMetricLabelKeys(e){return this.observability.getMetricLabelKeys(e)}getMetricLabelValues(e){return this.observability.getMetricLabelValues(e)}getEntityTypes(){return this.observability.getEntityTypes()}getEntityNames(e={}){return this.observability.getEntityNames(e)}getServiceNames(){return this.observability.getServiceNames()}getEnvironments(){return this.observability.getEnvironments()}getTags(e={}){return this.observability.getTags(e)}listStoredAgents(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction)),e?.status&&t.set("status",e.status),e?.authorId&&t.set("authorId",e.authorId),e?.visibility&&t.set("visibility",e.visibility),e?.metadata&&t.set("metadata",JSON.stringify(e.metadata)),e?.favoritedOnly&&t.set("favoritedOnly","true"),e?.pinFavoritedFor&&t.set("pinFavoritedFor",e.pinFavoritedFor);const n=t.toString();return this.request(`/stored/agents${n?`?${n}`:""}`)}createStoredAgent(e){return this.request("/stored/agents",{method:"POST",body:e})}getStoredAgent(e){return new Fhn(this.options,e)}listDynamicWorkflows(e){const t=new URLSearchParams;e?.status&&t.set("status",e.status),e?.authorId&&t.set("authorId",e.authorId);const n=t.toString();return this.request(`/stored/workflows${n?`?${n}`:""}`)}upsertDynamicWorkflow(e){return this.request("/stored/workflows",{method:"POST",body:e})}getDynamicWorkflow(e){return new zhn(this.options,e)}listStoredPromptBlocks(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction)),e?.authorId&&t.set("authorId",e.authorId),e?.status&&t.set("status",e.status),e?.metadata&&t.set("metadata",JSON.stringify(e.metadata));const n=t.toString();return this.request(`/stored/prompt-blocks${n?`?${n}`:""}`)}createStoredPromptBlock(e){return this.request("/stored/prompt-blocks",{method:"POST",body:e})}getStoredPromptBlock(e){return new Bhn(this.options,e)}listStoredScorers(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction)),e?.authorId&&t.set("authorId",e.authorId),e?.metadata&&t.set("metadata",JSON.stringify(e.metadata));const n=t.toString();return this.request(`/stored/scorers${n?`?${n}`:""}`)}createStoredScorer(e){return this.request("/stored/scorers",{method:"POST",body:e})}getStoredScorer(e){return new qhn(this.options,e)}listStoredMCPClients(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction)),e?.authorId&&t.set("authorId",e.authorId),e?.metadata&&t.set("metadata",JSON.stringify(e.metadata));const n=t.toString();return this.request(`/stored/mcp-clients${n?`?${n}`:""}`)}createStoredMCPClient(e){return this.request("/stored/mcp-clients",{method:"POST",body:e})}getStoredMCPClient(e){return new Uhn(this.options,e)}listStoredSkills(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.orderBy&&(e.orderBy.field&&t.set("orderBy[field]",e.orderBy.field),e.orderBy.direction&&t.set("orderBy[direction]",e.orderBy.direction)),e?.authorId&&t.set("authorId",e.authorId),e?.visibility&&t.set("visibility",e.visibility),e?.metadata&&t.set("metadata",JSON.stringify(e.metadata)),e?.favoritedOnly&&t.set("favoritedOnly","true"),e?.pinFavoritedFor&&t.set("pinFavoritedFor",e.pinFavoritedFor);const n=t.toString();return this.request(`/stored/skills${n?`?${n}`:""}`)}createStoredSkill(e){return this.request("/stored/skills",{method:"POST",body:e})}getStoredSkill(e){return new Ghn(this.options,e)}listToolProviders(){return this.request("/tool-providers")}getToolProvider(e){return new Vhn(this.options,e)}getProcessorProviders(){return this.request("/processor-providers")}getProcessorProvider(e){return new Hhn(this.options,e)}getSystemPackages(){return this.request("/system/packages")}getBuilderSettings(){return this.request("/editor/builder/settings")}getBuilderAvailableModels(){return this.request("/editor/builder/models/available")}getPermissionPatterns(){return this.request("/auth/permission-patterns")}getInfrastructureStatus(){return this.request("/editor/builder/infrastructure")}listBuilderRegistries(){return this.request("/editor/builder/registries")}searchBuilderRegistry(e,t){const n=new URLSearchParams({q:t.q});return t.limit!==void 0&&n.set("limit",String(t.limit)),this.request(`/editor/builder/registries/${encodeURIComponent(e)}/search?${n.toString()}`)}getBuilderRegistryPopular(e,t){const n=new URLSearchParams;t?.limit!==void 0&&n.set("limit",String(t.limit)),t?.offset!==void 0&&n.set("offset",String(t.offset));const r=n.toString();return this.request(`/editor/builder/registries/${encodeURIComponent(e)}/popular${r?`?${r}`:""}`)}getBuilderRegistryPreview(e,t){const n=new URLSearchParams({owner:t.owner,repo:t.repo,path:t.path});return this.request(`/editor/builder/registries/${encodeURIComponent(e)}/preview?${n.toString()}`)}installBuilderRegistrySkill(e,t){return this.request(`/editor/builder/registries/${encodeURIComponent(e)}/install`,{method:"POST",body:t})}listWorkspaces(){return this.request("/workspaces")}getWorkspace(e){return new Zhn(this.options,e)}listStoredWorkspaces(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.authorId&&t.set("authorId",e.authorId),e?.orderBy?.field&&t.set("orderBy[field]",e.orderBy.field),e?.orderBy?.direction&&t.set("orderBy[direction]",e.orderBy.direction);const n=t.toString();return this.request(`/stored/workspaces${n?`?${n}`:""}`)}getStoredWorkspace(e){return this.request(`/stored/workspaces/${encodeURIComponent(e)}`)}listVectors(){return this.request("/vectors")}listEmbedders(){return this.request("/embedders")}listDatasets(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage));const n=t.toString();return this.request(`/datasets${n?`?${n}`:""}`)}getDataset(e,t){const n=tJ(t);return this.request(`/datasets/${encodeURIComponent(e)}${n}`)}createDataset(e){return this.request("/datasets",{method:"POST",body:e})}updateDataset(e){const{datasetId:t,organizationId:n,projectId:r,...s}=e,a=tJ({organizationId:n,projectId:r});return this.request(`/datasets/${encodeURIComponent(t)}${a}`,{method:"PATCH",body:s})}deleteDataset(e,t){const n=tJ(t);return this.request(`/datasets/${encodeURIComponent(e)}${n}`,{method:"DELETE"})}listDatasetItems(e,t){const n=new URLSearchParams;t?.page!==void 0&&n.set("page",String(t.page)),t?.perPage!==void 0&&n.set("perPage",String(t.perPage)),t?.search&&n.set("search",t.search),t?.version!=null&&n.set("version",String(t.version));const r=n.toString();return this.request(`/datasets/${encodeURIComponent(e)}/items${r?`?${r}`:""}`)}getDatasetItem(e,t){return this.request(`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`)}addDatasetItem(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/items`,{method:"POST",body:n})}updateDatasetItem(e){const{datasetId:t,itemId:n,...r}=e;return this.request(`/datasets/${encodeURIComponent(t)}/items/${encodeURIComponent(n)}`,{method:"PATCH",body:r})}deleteDatasetItem(e,t){return this.request(`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}`,{method:"DELETE"})}batchInsertDatasetItems(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/items/batch`,{method:"POST",body:n})}batchDeleteDatasetItems(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/items/batch`,{method:"DELETE",body:n})}generateDatasetItems(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/generate-items`,{method:"POST",body:n})}clusterFailures(e){return this.request("/datasets/cluster-failures",{method:"POST",body:e})}getItemHistory(e,t){return this.request(`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}/history`)}getDatasetItemVersion(e,t,n){return this.request(`/datasets/${encodeURIComponent(e)}/items/${encodeURIComponent(t)}/versions/${n}`)}listDatasetVersions(e,t){const n=new URLSearchParams;t?.page!==void 0&&n.set("page",String(t.page)),t?.perPage!==void 0&&n.set("perPage",String(t.perPage));const r=n.toString();return this.request(`/datasets/${encodeURIComponent(e)}/versions${r?`?${r}`:""}`)}listExperiments(e){const t=new URLSearchParams;e?.page!==void 0&&t.set("page",String(e.page)),e?.perPage!==void 0&&t.set("perPage",String(e.perPage)),e?.experimentSetId!==void 0&&t.set("experimentSetId",e.experimentSetId),e?.comparisonId!==void 0&&t.set("comparisonId",e.comparisonId),e?.variantId!==void 0&&t.set("variantId",e.variantId),e?.trialIndex!==void 0&&t.set("trialIndex",String(e.trialIndex));const n=t.toString();return this.request(`/experiments${n?`?${n}`:""}`)}getExperimentReviewSummary(){return this.request("/experiments/review-summary")}listDatasetExperiments(e,t){const n=new URLSearchParams;t?.page!==void 0&&n.set("page",String(t.page)),t?.perPage!==void 0&&n.set("perPage",String(t.perPage)),t?.experimentSetId!==void 0&&n.set("experimentSetId",t.experimentSetId),t?.comparisonId!==void 0&&n.set("comparisonId",t.comparisonId),t?.variantId!==void 0&&n.set("variantId",t.variantId),t?.trialIndex!==void 0&&n.set("trialIndex",String(t.trialIndex));const r=n.toString();return this.request(`/datasets/${encodeURIComponent(e)}/experiments${r?`?${r}`:""}`)}getDatasetExperiment(e,t){return this.request(`/datasets/${encodeURIComponent(e)}/experiments/${encodeURIComponent(t)}`)}updateDatasetExperiment(e){const{datasetId:t,experimentId:n,...r}=e;return this.request(`/datasets/${encodeURIComponent(t)}/experiments/${encodeURIComponent(n)}`,{method:"PATCH",body:r})}listDatasetExperimentResults(e,t,n){const r=new URLSearchParams;n?.page!==void 0&&r.set("page",String(n.page)),n?.perPage!==void 0&&r.set("perPage",String(n.perPage));const s=r.toString();return this.request(`/datasets/${encodeURIComponent(e)}/experiments/${encodeURIComponent(t)}/results${s?`?${s}`:""}`)}updateDatasetExperimentResult(e){const{datasetId:t,experimentId:n,resultId:r,...s}=e;return this.request(`/datasets/${encodeURIComponent(t)}/experiments/${encodeURIComponent(n)}/results/${encodeURIComponent(r)}`,{method:"PATCH",body:s})}triggerDatasetExperiment(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/experiments`,{method:"POST",body:n})}createDatasetExperiment(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/experiments`,{method:"POST",body:{...n,start:!1}})}runExperimentItem(e){const{datasetId:t,experimentId:n,itemId:r,...s}=e;return this.request(`/datasets/${encodeURIComponent(t)}/experiments/${encodeURIComponent(n)}/items/${encodeURIComponent(r)}/run`,{method:"POST",body:s})}submitExperimentResult(e){const{datasetId:t,experimentId:n,...r}=e;return this.request(`/datasets/${encodeURIComponent(t)}/experiments/${encodeURIComponent(n)}/results`,{method:"POST",body:r})}finalizeExperiment(e){const{datasetId:t,experimentId:n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/experiments/${encodeURIComponent(n)}/finalize`,{method:"POST",body:{}})}updateExperimentResult(e){const{datasetId:t,experimentId:n,resultId:r,...s}=e;return this.request(`/datasets/${encodeURIComponent(t)}/experiments/${encodeURIComponent(n)}/results/${encodeURIComponent(r)}`,{method:"PATCH",body:s})}compareExperiments(e){const{datasetId:t,...n}=e;return this.request(`/datasets/${encodeURIComponent(t)}/compare`,{method:"POST",body:n})}listBackgroundTasks(e={}){const t=new URLSearchParams;e.agentId&&t.set("agentId",e.agentId),e.status&&t.set("status",e.status),e.runId&&t.set("runId",e.runId),e.threadId&&t.set("threadId",e.threadId),e.resourceId&&t.set("resourceId",e.resourceId),e.toolName&&t.set("toolName",e.toolName),e.toolCallId&&t.set("toolCallId",e.toolCallId),e.fromDate&&t.set("fromDate",e.fromDate.toISOString()),e.toDate&&t.set("toDate",e.toDate.toISOString()),e.dateFilterBy&&t.set("dateFilterBy",e.dateFilterBy),e.orderBy&&t.set("orderBy",e.orderBy),e.orderDirection&&t.set("orderDirection",e.orderDirection),e.page!==void 0&&t.set("page",String(e.page)),e.perPage!==void 0&&t.set("perPage",String(e.perPage));const n=t.toString();return this.request(`/background-tasks${n?`?${n}`:""}`)}getBackgroundTask(e){return this.request(`/background-tasks/${encodeURIComponent(e)}`)}async streamBackgroundTasks(e={}){const t=new URLSearchParams;e.agentId&&t.set("agentId",e.agentId),e.runId&&t.set("runId",e.runId),e.threadId&&t.set("threadId",e.threadId),e.resourceId&&t.set("resourceId",e.resourceId),e.taskId&&t.set("taskId",e.taskId);const n=t.toString(),r=await this.request(`/background-tasks/stream${n?`?${n}`:""}`,{stream:!0});if(!r.ok)throw new Error(`Failed to stream background tasks: ${r.statusText}`);if(!r.body)throw new Error("Response body is null");return r.body.pipeThrough(whn())}listSchedules(e={}){const t=new URLSearchParams;e.agentId&&t.set("agentId",e.agentId),e.workflowId&&t.set("workflowId",e.workflowId),e.status&&t.set("status",e.status),e.threadId&&t.set("threadId",e.threadId),e.resourceId&&t.set("resourceId",e.resourceId),e.name&&t.set("name",e.name);const n=t.toString();return this.request(`/schedules${n?`?${n}`:""}`)}getSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}`)}createSchedule(e){return this.request("/schedules",{method:"POST",body:e})}updateSchedule(e,t){return this.request(`/schedules/${encodeURIComponent(e)}`,{method:"PATCH",body:t})}deleteSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}`,{method:"DELETE"})}runSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}/run`,{method:"POST"})}listScheduleTriggers(e,t={}){const n=new URLSearchParams;t.limit!==void 0&&n.set("limit",String(t.limit)),t.fromActualFireAt!==void 0&&n.set("fromActualFireAt",String(t.fromActualFireAt)),t.toActualFireAt!==void 0&&n.set("toActualFireAt",String(t.toActualFireAt));const r=n.toString();return this.request(`/schedules/${encodeURIComponent(e)}/triggers${r?`?${r}`:""}`)}pauseSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}/pause`,{method:"POST"})}resumeSchedule(e){return this.request(`/schedules/${encodeURIComponent(e)}/resume`,{method:"POST"})}},lmn=class{id;description;inputSchema;outputSchema;execute;constructor(e){this.id=e.id,this.description=e.description,this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.execute=e.execute}};function Dg(e){return new lmn(e)}const cmn=()=>!0;async function umn(e,t={},n=3,r={}){let s=0,a=null;const i=r.shouldRetryResponse??cmn;for(;s<n;){let l;try{l=await fetch(e,t)}catch(u){a=u instanceof Error?u:new Error(String(u))}if(l){if(l.ok)return l;if(a=new Error(`Request failed with status: ${l.status} ${l.statusText}`),!i(l))throw a}if(s++,s>=n)break;const c=Math.min(1e3*Math.pow(2,s),1e4);await new Promise(u=>setTimeout(u,c))}throw a||new Error("Request failed after multiple retry attempts")}function Vhe(e,t){if(e===t)return!0;if(e==null||t==null)return e===t;if(typeof e!=typeof t||Array.isArray(e)!==Array.isArray(t)||e instanceof Date!=t instanceof Date)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length!==t.length?!1:e.every((n,r)=>Vhe(n,t[r]));if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(typeof e=="object"&&typeof t=="object"){const n=e,r=t,s=Object.keys(n),a=Object.keys(r);return s.length!==a.length?!1:s.every(i=>Object.prototype.hasOwnProperty.call(r,i)&&Vhe(n[i],r[i]))}return!1}function mg(e,t,n){const r=e?.mastra,s=r?.toolPayloadTransform?.[t]?.[n]??r?.toolPayloadProjection?.[t]?.[n];if(s&&Object.prototype.hasOwnProperty.call(s,"projected")&&!Object.prototype.hasOwnProperty.call(s,"transformed")){const{projected:a,...i}=s;return{...i,transformed:a}}return s}function Mu(e){return!!(e&&Object.prototype.hasOwnProperty.call(e,"transformed"))}var opt="vercel.ai.error",dmn=Symbol.for(opt),u3e,d3e,f3e=class lpt extends(d3e=Error,u3e=dmn,d3e){constructor({name:t,message:n,cause:r}){super(n),this[u3e]=!0,this.name=t,this.cause=r}static isInstance(t){return lpt.hasMarker(t,opt)}static hasMarker(t,n){const r=Symbol.for(n);return t!=null&&typeof t=="object"&&r in t&&typeof t[r]=="boolean"&&t[r]===!0}},cpt="AI_InvalidArgumentError",upt=`vercel.ai.error.${cpt}`,fmn=Symbol.for(upt),p3e,h3e,pmn=class extends(h3e=f3e,p3e=fmn,h3e){constructor({message:t,cause:n,argument:r}){super({name:cpt,message:t,cause:n}),this[p3e]=!0,this.argument=r}static isInstance(t){return f3e.hasMarker(t,upt)}},{btoa:hmn,atob:mmn}=globalThis;function dpt(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=mmn(t);return Uint8Array.from(n,r=>r.codePointAt(0))}function Hhe(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return hmn(t)}var gmn=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const s=()=>{const a=n.length,i=new Array(t);for(let l=0;l<t;l++)i[l]=n[Math.random()*a|0];return i.join("")};if(e==null)return s;if(n.includes(r))throw new pmn({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${s()}`};gmn();function vmn({mediaType:e,url:t,supportedUrls:n}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(n).map(([r,s])=>{const a=r.toLowerCase();return a==="*"||a==="*/*"?{mediaTypePrefix:"",regexes:s}:{mediaTypePrefix:a.replace(/\*/,""),regexes:s}}).filter(({mediaTypePrefix:r})=>e.startsWith(r)).flatMap(({regexes:r})=>r).some(r=>r.test(t))}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");new TextDecoder;function IO(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Hhe(new Uint8Array(e)):Hhe(e)}function ymn(e){if(e.role!=="signal")return!1;const t=e.content?.metadata;if(!t||typeof t!="object")return!1;const n=t.signal;return!!n&&typeof n=="object"&&!Array.isArray(n)&&n.transient===!0}function fpt(e){if(e.type==="user-message")return{type:"user",tagName:e.tagName??"user"};if(e.type==="system-reminder")return{type:"reactive",tagName:e.tagName??"system-reminder"};if(e.type==="user"||e.type==="state"||e.type==="notification")return{type:e.type,tagName:e.tagName??e.type};if(e.type==="reactive")return{type:"reactive",tagName:e.tagName??"system-reminder"};throw new Error(`Invalid signal type: ${e.type}. Use a supported signal type and set tagName for custom XML tags.`)}function bmn(e){const{type:t,tagName:n}=fpt(e);return{...e,type:t,tagName:n,id:e.id??crypto.randomUUID(),createdAt:e.createdAt instanceof Date?e.createdAt:e.createdAt?new Date(e.createdAt):new Date,acceptedAt:e.acceptedAt instanceof Date?e.acceptedAt:e.acceptedAt?new Date(e.acceptedAt):void 0}}function ppt(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function xmn(e){return ppt(e).replaceAll('"',""")}const wmn=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function hpt(e,t){if(!wmn.test(e))throw new Error(`Invalid signal XML ${t}: ${e}`)}function Smn(e){if(!e)return"";const t=Object.entries(e).filter(n=>n[1]!==null&&n[1]!==void 0).map(([n,r])=>(hpt(n,"attribute name"),`${n}="${xmn(String(r))}"`)).join(" ");return t?` ${t}`:""}function Whe(e){const t=e.tagName??fpt(e).tagName;hpt(t,"tag name");const n=Smn(e.attributes);return e.contents?`<${t}${n}>${ppt(e.contents)}</${t}>`:`<${t}${n} />`}function kmn(e){if(typeof e=="string")return e;if(Array.isArray(e)){const n=[];for(const r of e){if(typeof r=="string"){n.push({type:"text",text:r});continue}const s=m3e(r);if(!s)return;n.push(...s)}return v3e(n)}const t=m3e(e);return t?v3e(t):void 0}function m3e(e){if(!e||typeof e!="object")return;const t=e;if(t.role==="user"&&"content"in t){const r=t.content;if(typeof r=="string")return[{type:"text",text:r}];if(Array.isArray(r)){const s=[];for(const a of r){const i=g3e(a);if(!i)return;s.push(i)}return s}return}const n=g3e(t);return n?[n]:void 0}function g3e(e){if(!e||typeof e!="object")return;const t=e,n=t.providerOptions&&typeof t.providerOptions=="object"&&!Array.isArray(t.providerOptions)?t.providerOptions:void 0;if(t.type==="text"&&typeof t.text=="string")return{type:"text",text:t.text,...n?{providerOptions:n}:{}};if(t.type==="file"||t.type==="image"){const r=t.type==="image"?t.image??t.data:t.data;if(typeof r!="string")return;const s=typeof t.mediaType=="string"?t.mediaType:typeof t.mimeType=="string"?t.mimeType:t.type==="image"?"image/png":"";return s?{type:"file",data:r,mediaType:s,...typeof t.filename=="string"?{filename:t.filename}:{},...n?{providerOptions:n}:{}}:void 0}}function v3e(e){if(e.length===0)return;const t=e[0];return e.length===1&&t?.type==="text"?t.text:e}function Omn(e){return typeof e=="string"?[{type:"text",text:e}]:e.map(t=>t.type==="file"?{type:"file",data:t.data instanceof URL?t.data.toString():IO(t.data),mediaType:t.mediaType,...t.filename?{filename:t.filename}:{},...t.providerOptions?{providerOptions:t.providerOptions}:{}}:{type:"text",text:t.text,...t.providerOptions?{providerOptions:t.providerOptions}:{}})}function _mn(e){const t=[];for(const n of e){const r=n.providerMetadata;if(n.type==="text")t.push({type:"text",text:n.text,...r?{providerOptions:r}:{}});else if(n.type==="file"&&typeof n.data=="string"){const s=n;t.push({type:"file",data:s.data,mediaType:typeof s.mimeType=="string"?s.mimeType:"",...typeof s.filename=="string"?{filename:s.filename}:{},...r?{providerOptions:r}:{}})}}return t}function mpt(e){return e.length===1&&e[0]?.type==="text"&&!e[0].providerOptions?e[0].text:e.map(t=>t.type==="file"?{type:"file",data:t.data,mediaType:t.mediaType,...t.filename?{filename:t.filename}:{},...t.providerOptions?{providerOptions:t.providerOptions}:{}}:{type:"text",text:t.text,...t.providerOptions?{providerOptions:t.providerOptions}:{}})}function Cmn(e){return e?Object.keys(e).some(t=>{const n=e[t];return n!=null}):!1}function Emn(e,t){let n=!1;const r=[];for(const s of t)!n&&s.type==="text"?(n=!0,r.push({...s,text:Whe({...e,contents:s.text})})):r.push(s);if(!n){const s=Whe({type:e.type,tagName:e.tagName,attributes:e.attributes});r.unshift({type:"text",text:s})}return r}function Tmn(e,t){const n=e.type==="user",r=Cmn(e.attributes),s=t.some(i=>i.providerOptions);let a;return n&&!r?a=t.length===1&&t[0]?.type==="text"&&!t[0].providerOptions?t[0].text:t:t.every(i=>i.type==="text")&&!s?a=Whe({...e,contents:t.map(i=>i.text).join(`
|
|
118
118
|
`)}):a=Emn(e,t),{role:"user",content:a,...e.providerOptions?{providerOptions:e.providerOptions}:{}}}function jmn(e,t){return{type:e.type==="user"?"data-user-message":"data-signal",data:{id:e.id,type:e.type,tagName:e.tagName,contents:mpt(t),createdAt:e.createdAt.toISOString(),...e.acceptedAt?{acceptedAt:e.acceptedAt.toISOString()}:{},...e.attributes?{attributes:e.attributes}:{},...e.metadata?{metadata:e.metadata}:{},...e.providerOptions?{providerOptions:e.providerOptions}:{},...e.transient?{transient:!0}:{}},transient:!0}}function Nmn(e,t,n){const r=t.length>0?t.map(s=>s.type==="file"?{type:"file",data:s.data,mimeType:s.mediaType,...s.filename?{filename:s.filename}:{},...s.providerOptions?{providerMetadata:s.providerOptions}:{}}:{type:"text",text:s.text,...s.providerOptions?{providerMetadata:s.providerOptions}:{}}):[{type:"text",text:""}];return{id:e.id,role:"signal",createdAt:e.createdAt,threadId:n?.threadId,resourceId:n?.resourceId,type:e.tagName,content:{format:2,parts:r,...e.providerOptions?{providerMetadata:e.providerOptions}:{},metadata:{signal:{id:e.id,type:e.type,tagName:e.tagName,createdAt:e.createdAt.toISOString(),...e.acceptedAt?{acceptedAt:e.acceptedAt.toISOString()}:{},...e.attributes?{attributes:e.attributes}:{},...e.metadata?{metadata:e.metadata}:{},...e.transient?{transient:!0}:{}}}}}}function y3e(e){return!e||typeof e!="object"||Array.isArray(e)?!1:e.__isCreatedSignal===!0}function m7(e){if(e.type==="state"&&e.transient!==void 0)throw new Error("state signals cannot be transient");const t=bmn(e),n=Omn(t.contents),r={...t,__isCreatedSignal:!0,toDBMessage:s=>Nmn(t,n,s),toLLMMessage:()=>Tmn(t,n),toDataPart:()=>jmn(t,n)};if(r.type==="state"){const{transient:s,...a}=r;return{...a,type:r.type}}return{...r,type:r.type}}function Imn(e){const t=e.content.metadata?.signal,n=t&&typeof t=="object"&&!Array.isArray(t)?t:void 0,r=typeof n?.type=="string"?n.type:e.type??"user-message",s=typeof n?.tagName=="string"?n.tagName:void 0,a=kmn(n&&"contents"in n?n.contents:void 0),i=mpt(_mn(e.content.parts)),l=a??i,c=e.content.providerMetadata,u={id:typeof n?.id=="string"?n.id:e.id,createdAt:typeof n?.createdAt=="string"?n.createdAt:e.createdAt,acceptedAt:typeof n?.acceptedAt=="string"?n.acceptedAt:void 0,attributes:n?.attributes&&typeof n.attributes=="object"&&!Array.isArray(n.attributes)?n.attributes:void 0,metadata:n?.metadata&&typeof n.metadata=="object"&&!Array.isArray(n.metadata)?n.metadata:void 0,providerOptions:c&&typeof c=="object"&&!Array.isArray(c)?c:void 0};if(r==="state"&&n?.transient!==void 0)throw new Error("state signals cannot be transient");return m7(r==="state"?{...u,type:r,tagName:s,contents:l}:{...u,type:r,tagName:s,contents:l,transient:n?.transient===!0?!0:void 0})}function g7(e){if(!e.startsWith("data:"))return{isDataUri:!1,base64Content:e};const t=e.indexOf(",");if(t===-1)return{isDataUri:!0,base64Content:e};const n=e.substring(5,t),r=e.substring(t+1),s=n.indexOf(";");return{isDataUri:!0,mimeType:(s!==-1?n.substring(0,s):n)||void 0,base64Content:r}}function Twe(e,t="application/octet-stream"){return e.startsWith("data:")?e:`data:${t};base64,${e}`}function Zhe(e,t){if(typeof e=="string")return e;if(e instanceof URL)return e.toString();if(e instanceof Uint8Array||e instanceof ArrayBuffer||globalThis.Buffer&&Buffer.isBuffer(e)){const n=IO(e);return t&&!n.startsWith("data:")?`data:${t};base64,${n}`:n}return String(e)}function b3e(e){return e instanceof URL?e.toString():typeof e=="string"?e.length:e instanceof Uint8Array||e instanceof ArrayBuffer?e.byteLength:e}function Amn(e){try{return new URL(e),!0}catch{if(e.startsWith("//"))try{return new URL(`https:${e}`),!0}catch{return!1}return!1}}function Fj(e,t){const n=g7(e),r=n.isDataUri&&n.mimeType?n.mimeType:t;return n.isDataUri?{type:"dataUri",mimeType:r,data:e}:e.startsWith("file-")?{type:"providerFileId",mimeType:r,data:e}:Amn(e)?{type:"url",mimeType:r,data:e}:{type:"raw",mimeType:r,data:e}}function iH(e){const t=e;return{mediaType:t.mimeType??t.mediaType,data:t.data??t.url}}const Rmn=/^[a-zA-Z0-9_-]+$/,x3e="unknown_tool";function fu(e){return typeof e!="string"?x3e:Rmn.test(e)?e:x3e}function Pmn(e){if(e.role==="system")return e;if(typeof e.content=="string"&&(e.role==="assistant"||e.role==="user"))return{...e,content:[{type:"text",text:e.content}]};if(typeof e.content=="string")throw new Error(`Saw text content for input CoreMessage, but the role is ${e.role}. This is only allowed for "system", "assistant", and "user" roles.`);const t={user:[],assistant:[],tool:[]},n=e.role;for(const r of e.content){const s=`Saw incompatible message content part type ${r.type} for message role ${n}`;switch(r.type){case"text":if(n==="tool")throw new Error(s);t[n].push(r);break;case"redacted-reasoning":case"reasoning":if(n!=="assistant")throw new Error(s);t[n].push(r);break;case"tool-call":if(n==="tool"||n==="user")throw new Error(s);t[n].push({...r,toolName:fu(r.toolName)});break;case"tool-result":if(n==="assistant"||n==="user")throw new Error(s);t[n].push({...r,toolName:fu(r.toolName)});break;case"image":{if(n==="tool"||n==="assistant")throw new Error(s);let a;if(r.image instanceof URL||r.image instanceof Uint8Array)a=r.image;else if(Buffer.isBuffer(r.image)||r.image instanceof ArrayBuffer)a=new Uint8Array(r.image);else{const i=Fj(r.image,r.mimeType);if(i.type==="raw")a=new Uint8Array(Buffer.from(r.image,"base64"));else if(i.type==="providerFileId"){const{image:l,type:c,...u}=r;t[n].push({...u,type:"file",data:r.image,mimeType:i.mimeType||"application/octet-stream"});break}else a=new URL(r.image)}t[n].push({...r,image:a});break}case"file":if(n==="tool")throw new Error(s);t[n].push({...r,data:r.data instanceof URL||typeof r.data=="string"?r.data:IO(r.data)});break}}if(n==="tool")return{...e,content:t[n]};if(n==="user")return{...e,content:t[n]};if(n==="assistant")return{...e,content:t[n]};throw new Error(`Encountered unknown role ${n} when converting V4 CoreMessage -> V4 LanguageModelV1Prompt, input message: ${JSON.stringify(e,null,2)}`)}function $mn(e){if(e.role==="system")return e;if(typeof e.content=="string"&&(e.role==="assistant"||e.role==="user"))return{role:e.role,content:[{type:"text",text:e.content}],providerOptions:e.providerOptions};if(typeof e.content=="string")throw new Error(`Saw text content for input ModelMessage, but the role is ${e.role}. This is only allowed for "system", "assistant", and "user" roles.`);const t={user:[],assistant:[],tool:[]},n=e.role;for(const r of e.content??[]){if(!r||typeof r!="object")continue;const s=`Saw incompatible message content part type ${r.type} for message role ${n}`;switch(r.type){case"text":if(n==="tool")throw new Error(s);t[n].push(r);break;case"reasoning":if(n==="tool"||n==="user")throw new Error(s);t[n].push(r);break;case"tool-call":if(n!=="assistant")throw new Error(s);t[n].push({...r,toolName:fu(r.toolName)});break;case"tool-result":if(n==="user")throw new Error(s);t[n].push({...r,toolName:fu(r.toolName),output:r.output??{type:"json",value:null}});break;case"file":if(n==="tool")throw new Error(s);t[n].push({...r,data:r.data instanceof ArrayBuffer?new Uint8Array(r.data):r.data});break;case"image":if(n==="tool")throw new Error(s);t[n].push({...r,mediaType:r.mediaType||"image/unknown",type:"file",data:r.image instanceof ArrayBuffer?new Uint8Array(r.image):r.image});break}}if(n==="tool")return{...e,content:t[n]};if(n==="user")return{...e,content:t[n]};if(n==="assistant")return{...e,content:t[n]};throw new Error(`Encountered unknown role ${n} when converting V5 ModelMessage -> V5 LanguageModelV2Message, input message: ${JSON.stringify(e,null,2)}`)}function gpt(e,t){return e.map(n=>{if(n.role!=="tool")return n;let r=!1;const s=n.content.map(a=>{if(a.type!=="tool-result")return a;const i=a.output;if(!i||i.type!=="content"||!Array.isArray(i.value))return a;let l=!1;const c=i.value.map(u=>{if(u==null||typeof u!="object")return u;const d=u;return d.type!=="media"||typeof d.data!="string"?u:(l=!0,t(d,typeof d.mediaType=="string"?d.mediaType:""))});return l?(r=!0,{...a,output:{...i,value:c}}):a});return r?{...n,content:s}:n})}function Mmn(e){return gpt(e,(t,n)=>n.startsWith("image/")?{type:"image-data",data:t.data,mediaType:n}:{type:"file-data",data:t.data,mediaType:n})}function Dmn(e){return gpt(e,(t,n)=>({type:"file",data:{type:"data",data:t.data},mediaType:n}))}var Lmn={},Ghe={},vpt="vercel.ai.error",Fmn=Symbol.for(vpt),w3e,S3e,Ju=class ypt extends(S3e=Error,w3e=Fmn,S3e){constructor({name:t,message:n,cause:r}){super(n),this[w3e]=!0,this.name=t,this.cause=r}static isInstance(t){return ypt.hasMarker(t,vpt)}static hasMarker(t,n){const r=Symbol.for(n);return t!=null&&typeof t=="object"&&r in t&&typeof t[r]=="boolean"&&t[r]===!0}},bpt="AI_APICallError",xpt=`vercel.ai.error.${bpt}`,zmn=Symbol.for(xpt),k3e,O3e,Sf=class extends(O3e=Ju,k3e=zmn,O3e){constructor({message:t,url:n,requestBodyValues:r,statusCode:s,responseHeaders:a,responseBody:i,cause:l,isRetryable:c=s!=null&&(s===408||s===409||s===429||s>=500),data:u}){super({name:bpt,message:t,cause:l}),this[k3e]=!0,this.url=n,this.requestBodyValues=r,this.statusCode=s,this.responseHeaders=a,this.responseBody=i,this.isRetryable=c,this.data=u}static isInstance(t){return Ju.hasMarker(t,xpt)}},wpt="AI_EmptyResponseBodyError",Spt=`vercel.ai.error.${wpt}`,Bmn=Symbol.for(Spt),_3e,C3e,Umn=class extends(C3e=Ju,_3e=Bmn,C3e){constructor({message:t="Empty response body"}={}){super({name:wpt,message:t}),this[_3e]=!0}static isInstance(t){return Ju.hasMarker(t,Spt)}};function jwe(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var kpt="AI_InvalidArgumentError",Opt=`vercel.ai.error.${kpt}`,qmn=Symbol.for(Opt),E3e,T3e,Vmn=class extends(T3e=Ju,E3e=qmn,T3e){constructor({message:t,cause:n,argument:r}){super({name:kpt,message:t,cause:n}),this[E3e]=!0,this.argument=r}static isInstance(t){return Ju.hasMarker(t,Opt)}},_pt="AI_JSONParseError",Cpt=`vercel.ai.error.${_pt}`,Hmn=Symbol.for(Cpt),j3e,N3e,v7=class extends(N3e=Ju,j3e=Hmn,N3e){constructor({text:t,cause:n}){super({name:_pt,message:`JSON parsing failed: Text: ${t}.
|
|
119
119
|
Error message: ${jwe(n)}`,cause:n}),this[j3e]=!0,this.text=t}static isInstance(t){return Ju.hasMarker(t,Cpt)}},Ept="AI_TypeValidationError",Tpt=`vercel.ai.error.${Ept}`,Wmn=Symbol.for(Tpt),I3e,A3e,N2=class Qhe extends(A3e=Ju,I3e=Wmn,A3e){constructor({value:t,cause:n}){super({name:Ept,message:`Type validation failed: Value: ${JSON.stringify(t)}.
|
|
120
120
|
Error message: ${jwe(n)}`,cause:n}),this[I3e]=!0,this.value=t}static isInstance(t){return Ju.hasMarker(t,Tpt)}static wrap({value:t,cause:n}){return Qhe.isInstance(n)&&n.value===t?n:new Qhe({value:t,cause:n})}},R3e=class extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}};const P3e=10,Zmn=13,ZS=32;function aJ(e){}function Gmn(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=aJ,onError:n=aJ,onRetry:r=aJ,onComment:s}=e,a=[];let i=!0,l,c="",u=0,d;function f(b){if(i&&(i=!1,b.charCodeAt(0)===239&&b.charCodeAt(1)===187&&b.charCodeAt(2)===191&&(b=b.slice(3))),a.length===0){const k=p(b);k!==""&&a.push(k);return}if(b.indexOf(`
|
|
@@ -231,7 +231,7 @@ attempted value: ${i}
|
|
|
231
231
|
\${}
|
|
232
232
|
}
|
|
233
233
|
}`,{label:"class",detail:"definition",type:"keyword"}),df('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),df('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],USt=cOe.concat([df("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),df("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),df("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),c9e=new W0t,qSt=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function $R(e){return(t,n)=>{let r=t.node.getChild("VariableDefinition");return r&&n(r,e),!0}}const GUn=["FunctionDeclaration"],QUn={FunctionDeclaration:$R("function"),ClassDeclaration:$R("class"),ClassExpression:()=>!0,EnumDeclaration:$R("constant"),TypeAliasDeclaration:$R("type"),NamespaceDeclaration:$R("namespace"),VariableDefinition(e,t){e.matchContext(GUn)||t(e,"variable")},TypeDefinition(e,t){t(e,"type")},__proto__:null};function VSt(e,t){let n=c9e.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(za.IncludeAnonymous).iterate(i=>{if(s)s=!1;else if(i.name){let l=QUn[i.name];if(l&&l(i,a)||qSt.has(i.name))return!1}else if(i.to-i.from>8192){for(let l of VSt(e,i.node))r.push(l);return!1}}),c9e.set(t,r),r}const GB=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,uOe=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function HSt(e){let t=yi(e.state).resolveInner(e.pos,-1);if(uOe.indexOf(t.name)>-1)return null;let n=t.name=="VariableName"||t.to-t.from<20&&GB.test(e.state.sliceDoc(t.from,t.to));if(!n&&!e.explicit)return null;let r=[];for(let s=t;s;s=s.parent)qSt.has(s.name)&&(r=r.concat(VSt(e.state.doc,s)));return{options:r,from:n?t.from:e.pos,validFor:GB}}function ote(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 WSt(e){let t=r=>e.state.doc.sliceString(r.from,r.to),n=yi(e.state).resolveInner(e.pos,-1);return n.name=="PropertyName"?ote(t,n.parent,t(n)):(n.name=="."||n.name=="?.")&&n.parent.name=="MemberExpression"?ote(t,n.parent,""):uOe.indexOf(n.name)>-1?null:n.name=="VariableName"||n.to-n.from<20&&GB.test(t(n))?{path:[],name:t(n)}:n.name=="MemberExpression"?ote(t,n,""):e.explicit?{path:[],name:""}:null}function YUn(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 KUn(e){let t=new Map;return n=>{let r=WSt(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=YUn(s,!r.path.length)),{from:n.pos-r.name.length,options:a,validFor:GB}}}const om=ZO.define({name:"javascript",parser:ZUn.configure({props:[aC.add({IfStatement:ij({except:/^\s*({|else\b)/}),TryStatement:ij({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:H8n,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:V8n({closing:"}"}),ArrowFunction:e=>e.baseIndent+e.unit,"TemplateString BlockComment":()=>null,"Statement Property":ij({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}}),iC.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":qke,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:"$"}}),ZSt={test:e=>/^JSX/.test(e.name),facet:uW({commentTokens:{block:{open:"{/*",close:"*/}"}}})},dOe=om.configure({dialect:"ts"},"typescript"),fOe=om.configure({dialect:"jsx",props:[zke.add(e=>e.isTop?[ZSt]:void 0)]}),pOe=om.configure({dialect:"jsx ts",props:[zke.add(e=>e.isTop?[ZSt]:void 0)]},"typescript");let GSt=e=>({label:e,type:"keyword"});const QSt="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(GSt),XUn=QSt.concat(["declare","implements","private","protected","public"].map(GSt));function QB(e={}){let t=e.jsx?e.typescript?pOe:fOe:e.typescript?dOe:om,n=e.typescript?USt.concat(XUn):cOe.concat(QSt);return new QO(t,[om.data.of({autocomplete:N9n(uOe,Z1t(n))}),om.data.of({autocomplete:HSt}),e.jsx?YSt:[]])}function JUn(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 u9e(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 eqn=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),YSt=$t.inputHandler.of((e,t,n,r,s)=>{if((eqn?e.composing:e.compositionStarted)||e.state.readOnly||t!=n||r!=">"&&r!="/"||!om.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:i}=a,l=i.changeByRange(c=>{var u;let{head:d}=c,f=yi(i).resolveInner(d-1,-1),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=u9e(i.doc,m.firstChild,d))||((u=m.firstChild)===null||u===void 0?void 0:u.name)=="JSXFragmentTag")){let v=`${p}>`;return{range:wt.cursor(d+v.length,-1),changes:{from:d,insert:v}}}}else if(r==">"){let h=JUn(f);if(h&&h.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(i.doc.sliceString(d,d+2))&&(p=u9e(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 tqn(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 om.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(nqn(u,r.doc,c))}return s}}function d9e(e,t,n,r){return n.line(e+r.line).from+t+(e==1?r.col-1:-1)}function nqn(e,t,n){let r=d9e(e.line,e.column,t,n),s={from:r,to:e.endLine!=null&&e.endColumn!=1?d9e(e.endLine,e.endColumn,t,n):r,message:e.message,source:e.ruleId?"eslint:"+e.ruleId:"eslint",severity:e.severity==1?"warning":"error"};if(e.fix){let{range:a,text:i}=e.fix,l=a[0]+n.pos-r,c=a[1]+n.pos-r;s.actions=[{name:"fix",apply(u,d){u.dispatch({changes:{from:d+l,to:d+c,insert:i},scrollIntoView:!0})}}]}return s}const wF=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:YSt,completionPath:WSt,esLint:tqn,javascript:QB,javascriptLanguage:om,jsxLanguage:fOe,localCompletionSource:HSt,scopeCompletionSource:KUn,snippets:cOe,tsxLanguage:pOe,typescriptLanguage:dOe,typescriptSnippets:USt},Symbol.toStringTag,{value:"Module"})),MR=["_blank","_self","_top","_parent"],lte=["ascii","utf-8","utf-16","latin1","latin1"],cte=["get","post","put","delete"],ute=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],up=["true","false"],Jn={},rqn={a:{attrs:{href:null,ping:null,type:null,media:null,target:MR,hreflang:null}},abbr:Jn,address:Jn,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:Jn,aside:Jn,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:Jn,base:{attrs:{href:null,target:MR}},bdi:Jn,bdo:Jn,blockquote:{attrs:{cite:null}},body:Jn,br:Jn,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:ute,formmethod:cte,formnovalidate:["novalidate"],formtarget:MR,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:Jn,center:Jn,cite:Jn,code:Jn,col:{attrs:{span:null}},colgroup:{attrs:{span:null}},command:{attrs:{type:["command","checkbox","radio"],label:null,icon:null,radiogroup:null,command:null,title:null,disabled:["disabled"],checked:["checked"]}},data:{attrs:{value:null}},datagrid:{attrs:{disabled:["disabled"],multiple:["multiple"]}},datalist:{attrs:{data:null}},dd:Jn,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:Jn,div:Jn,dl:Jn,dt:Jn,em:Jn,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:Jn,figure:Jn,footer:Jn,form:{attrs:{action:null,name:null,"accept-charset":lte,autocomplete:["on","off"],enctype:ute,method:cte,novalidate:["novalidate"],target:MR}},h1:Jn,h2:Jn,h3:Jn,h4:Jn,h5:Jn,h6:Jn,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:Jn,hgroup:Jn,hr:Jn,html:{attrs:{manifest:null}},i:Jn,iframe:{attrs:{src:null,srcdoc:null,name:null,width:null,height:null,sandbox:["allow-top-navigation","allow-same-origin","allow-forms","allow-scripts"],seamless:["seamless"]}},img:{attrs:{alt:null,src:null,ismap:null,usemap:null,width:null,height:null,crossorigin:["anonymous","use-credentials"]}},input:{attrs:{alt:null,dirname:null,form:null,formaction:null,height:null,list:null,max:null,maxlength:null,min:null,name:null,pattern:null,placeholder:null,size:null,src:null,step:null,value:null,width:null,accept:["audio/*","video/*","image/*"],autocomplete:["on","off"],autofocus:["autofocus"],checked:["checked"],disabled:["disabled"],formenctype:ute,formmethod:cte,formnovalidate:["novalidate"],formtarget:MR,multiple:["multiple"],readonly:["readonly"],required:["required"],type:["hidden","text","search","tel","url","email","password","datetime","date","month","week","time","datetime-local","number","range","color","checkbox","radio","file","submit","image","reset","button"]}},ins:{attrs:{cite:null,datetime:null}},kbd:Jn,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:Jn,li:{attrs:{value:null}},link:{attrs:{href:null,type:null,hreflang:null,media:null,sizes:["all","16x16","16x16 32x32","16x16 32x32 64x64"]}},map:{attrs:{name:null}},mark:Jn,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:lte,name:["viewport","application-name","author","description","generator","keywords"],"http-equiv":["content-language","content-type","default-style","refresh"]}},meter:{attrs:{value:null,min:null,low:null,high:null,max:null,optimum:null}},nav:Jn,noscript:Jn,object:{attrs:{data:null,type:null,name:null,usemap:null,form:null,width:null,height:null,typemustmatch:["typemustmatch"]}},ol:{attrs:{reversed:["reversed"],start:null,type:["1","a","A","i","I"]},children:["li","script","template","ul","ol"]},optgroup:{attrs:{disabled:["disabled"],label:null}},option:{attrs:{disabled:["disabled"],label:null,selected:["selected"],value:null}},output:{attrs:{for:null,form:null,name:null}},p:Jn,param:{attrs:{name:null,value:null}},pre:Jn,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:Jn,rt:Jn,ruby:Jn,samp:Jn,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:lte}},section:Jn,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:Jn,source:{attrs:{src:null,type:null,media:null}},span:Jn,strong:Jn,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:Jn,summary:Jn,sup:Jn,table:Jn,tbody:Jn,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:Jn,textarea:{attrs:{dirname:null,form:null,maxlength:null,name:null,placeholder:null,rows:null,cols:null,autofocus:["autofocus"],disabled:["disabled"],readonly:["readonly"],required:["required"],wrap:["soft","hard"]}},tfoot:Jn,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:Jn,time:{attrs:{datetime:null}},title:Jn,tr:Jn,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:Jn,video:{attrs:{src:null,poster:null,width:null,height:null,crossorigin:["anonymous","use-credentials"],preload:["auto","metadata","none"],autoplay:["autoplay"],mediagroup:["movie"],muted:["muted"],controls:["controls"]}},wbr:Jn},KSt={accesskey:null,class:null,contenteditable:up,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:up,autocorrect:up,autocapitalize:up,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":up,"aria-autocomplete":["inline","list","both","none"],"aria-busy":up,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":up,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":up,"aria-hidden":up,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":up,"aria-multiselectable":up,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":up,"aria-relevant":null,"aria-required":up,"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},XSt="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 XSt)KSt[e]=null;class $M{constructor(t,n){this.tags={...rqn,...t},this.globalAttrs={...KSt,...n},this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}}$M.default=new $M;function rN(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 sN(e,t=!1){for(;e;e=e.parent)if(e.name=="Element")if(t)t=!1;else return e;return null}function JSt(e,t,n){let r=n.tags[rN(e,sN(t))];return r?.children||n.allTags}function hOe(e,t){let n=[];for(let r=sN(t);r&&!r.type.isTop;r=sN(r.parent)){let s=rN(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 ekt=/^[:\-\.\w\u00b7-\uffff]*$/;function f9e(e,t,n,r,s){let a=/\s*>/.test(e.sliceDoc(s,s+5))?"":">",i=sN(n,n.name=="StartTag"||n.name=="TagName");return{from:r,to:s,options:JSt(e.doc,i,t).map(l=>({label:l,type:"type"})).concat(hOe(e.doc,n).map((l,c)=>({label:"/"+l,apply:"/"+l+a,type:"type",boost:99-c}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function p9e(e,t,n,r){let s=/\s*>/.test(e.sliceDoc(r,r+5))?"":">";return{from:n,to:r,options:hOe(e.doc,t).map((a,i)=>({label:a,apply:a+s,type:"type",boost:99-i})),validFor:ekt}}function sqn(e,t,n,r){let s=[],a=0;for(let i of JSt(e.doc,n,t))s.push({label:"<"+i,type:"type"});for(let i of hOe(e.doc,n))s.push({label:"</"+i+">",type:"type",boost:99-a++});return{from:r,to:r,options:s,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function aqn(e,t,n,r,s){let a=sN(n),i=a?t.tags[rN(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:ekt}}function iqn(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=sN(n),p=f?t.tags[rN(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 tkt(e,t){let{state:n,pos:r}=t,s=yi(n).resolveInner(r,-1),a=s.resolve(r);for(let i=r,l;a==s&&(l=s.childBefore(i));){let c=l.lastChild;if(!c||!c.type.isError||c.from<c.to)break;a=s=l,i=c.from}return s.name=="TagName"?s.parent&&/CloseTag$/.test(s.parent.name)?p9e(n,s,s.from,r):f9e(n,e,s,s.from,r):s.name=="StartTag"||s.name=="IncompleteTag"?f9e(n,e,s,r,r):s.name=="StartCloseTag"||s.name=="IncompleteCloseTag"?p9e(n,s,r,r):s.name=="OpenTag"||s.name=="SelfClosingTag"||s.name=="AttributeName"?aqn(n,e,s,s.name=="AttributeName"?s.from:r,r):s.name=="Is"||s.name=="AttributeValue"||s.name=="UnquotedAttributeValue"?iqn(n,e,s,s.name=="Is"?r:s.from,r):t.explicit&&(a.name=="Element"||a.name=="Text"||a.name=="Document")?sqn(n,e,s,r):null}function oqn(e){return tkt($M.default,e)}function lqn(e){let{extraTags:t,extraGlobalAttributes:n}=e,r=n||t?new $M(t,n):$M.default;return s=>tkt(r,s)}const cqn=om.parser.configure({top:"SingleExpression"}),nkt=[{tag:"script",attrs:e=>e.type=="text/typescript"||e.lang=="ts",parser:dOe.parser},{tag:"script",attrs:e=>e.type=="text/babel"||e.type=="text/jsx",parser:fOe.parser},{tag:"script",attrs:e=>e.type=="text/typescript-jsx",parser:pOe.parser},{tag:"script",attrs(e){return/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(e.type)},parser:cqn},{tag:"script",attrs(e){return!e.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(e.type)},parser:om.parser},{tag:"style",attrs(e){return(!e.lang||e.lang=="css")&&(!e.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(e.type))},parser:ZB.parser}],rkt=[{name:"style",parser:ZB.parser.configure({top:"Styles"})}].concat(XSt.map(e=>({name:e,parser:om.parser}))),skt=ZO.define({name:"html",parser:PBn.configure({props:[aC.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}}),iC.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}}}),z1t.add({"OpenTag CloseTag":e=>e.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:"<!--",close:"-->"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-_"}}),e9=skt.configure({wrap:$St(nkt,rkt)});function uqn(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=$St((e.nestedLanguages||[]).concat(nkt),(e.nestedAttributes||[]).concat(rkt)));let r=n?skt.configure({wrap:n,dialect:t}):t?e9.configure({dialect:t}):e9;return new QO(r,[e9.data.of({autocomplete:lqn(e)}),e.autoCloseTags!==!1?dqn:[],QB().support,gUn().support])}const h9e=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" ")),dqn=$t.inputHandler.of((e,t,n,r,s)=>{if(e.composing||e.state.readOnly||t!=n||r!=">"&&r!="/"||!e9.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:i}=a,l=i.changeByRange(c=>{var u,d,f;let p=i.doc.sliceString(c.from-1,c.to)==r,{head:h}=c,m=yi(i).resolveInner(h,-1),v;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"&&(v=rN(i.doc,y.parent,h))&&!h9e.has(v)){let b=h+(i.doc.sliceString(h,h+1)===">"?1:0),x=`</${v}>`;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"&&(v=rN(i.doc,y,h))&&!h9e.has(v)){let b=h+(i.doc.sliceString(h,h+1)===">"?1:0),x=`${v}>`;return{range:wt.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)}),akt=uW({commentTokens:{block:{open:"<!--",close:"-->"}}}),ikt=new $r,okt=M7n.configure({props:[iC.add(e=>!e.is("Block")||e.is("Document")||bve(e)!=null||fqn(e)?void 0:(t,n)=>({from:n.doc.lineAt(t.from).to,to:t.to})),ikt.add(bve),aC.add({Document:()=>null}),Iw.add({Document:akt})]});function bve(e){let t=/^(?:ATX|Setext)Heading(\d)$/.exec(e.name);return t?+t[1]:void 0}function fqn(e){return e.name=="OrderedList"||e.name=="BulletList"}function pqn(e,t){let n=e;for(;;){let r=n.nextSibling,s;if(!r||(s=bve(r.type))!=null&&s<=t)break;n=r}return n.to}const hqn=T1t.of((e,t,n)=>{for(let r=yi(e).resolveInner(n,-1);r&&!(r.from<t);r=r.parent){let s=r.type.prop(ikt);if(s==null)continue;let a=pqn(r,s);if(a>n)return{from:n,to:a}}return null});function mOe(e){return new Ip(akt,e,[],"markdown")}const lkt=mOe(okt),mqn=okt.configure([Z7n,Q7n,G7n,Y7n,{props:[iC.add({Table:(e,t)=>({from:t.doc.lineAt(e.from).to,to:e.to})})]}]),XO=mOe(mqn);function gqn(e,t){return n=>{if(n&&e){let r=null;if(n=/\S*/.exec(n)[0],typeof e=="function"?r=e(n):r=pg.matchLanguageName(e,n,!0),r instanceof pg)return r.support?r.support.language.parser:GO.getSkippingParser(r.load());if(r)return r.parser}return t?t.parser:null}}class dte{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(+ukt(this.item,t)[2]+n):"";return this.spaceBefore+r+this.type+this.spaceAfter}}function ckt(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 dte(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 dte(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 dte(a.parent,c,c+d,i[1],u,f,a))}}return r}function ukt(e,t){return/^(\s*)(\d+)(?=[.)])/.exec(t.sliceString(e.from,e.from+10))}function fte(e,t,n,r=0){for(let s=-1,a=e;;){if(a.name=="ListItem"){let l=ukt(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 gOe(e,t){let n=/^[ \t]*/.exec(e)[0].length;if(!n||t.facet(CI)!=" ")return e;let r=Ug(e,4,n),s="";for(let a=r;a>0;)a>=4?(s+=" ",a-=4):(s+=" ",a--);return s+e.slice(n)}const dkt=(e={})=>({state:t,dispatch:n})=>{let r=yi(t),{doc:s}=t,a=null,i=t.changeByRange(l=>{if(!l.empty||!XO.isActiveAt(t,l.from,-1)&&!XO.isActiveAt(t,l.from,1))return a={range:l};let c=l.from,u=s.lineAt(c),d=ckt(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"&&fte(f.item,s,C,-2),S&&S.node.name=="OrderedList"&&fte(S.item,s,C),{range:wt.cursor(k+_.length),changes:C}}else{let S=g9e(d,t,u);return{range:wt.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"&&fte(f.item,s,h);let m=f.item&&f.item.from<u.from,v="";if(!m||/^[\s\d.)\-+*>]*/.exec(u.text)[0].length>=f.to)for(let b=0,x=d.length-1;b<=x;b++)v+=b==x&&!m?d[b].marker(s,1):d[b].blank(b<x?Ug(u.text,4,d[b+1].from)-v.length:null);let y=c;for(;y>u.from&&/\s/.test(u.text.charAt(y-u.from-1));)y--;return v=gOe(v,t),vqn(f.node,t.doc)&&(v=g9e(d,t,u)+t.lineBreak+v),h.push({from:y,to:c,insert:t.lineBreak+v}),{range:wt.cursor(y+v.length+1),changes:h}});return a?!1:(n(t.update(i,{scrollIntoView:!0,userEvent:"input"})),!0)},fkt=dkt();function m9e(e){return e.name=="QuoteMark"||e.name=="ListMark"}function vqn(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 g9e(e,t,n){let r="";for(let s=0,a=e.length-2;s<=a;s++)r+=e[s].blank(s<a?Ug(n.text,4,e[s+1].from)-r.length:null,s<a);return gOe(r,t)}function yqn(e,t){let n=e.resolveInner(t,-1),r=t;m9e(n)&&(r=n.from,n=n.parent);for(let s;s=n.childBefore(r);)if(m9e(s))r=s.from;else if(s.name=="OrderedList"||s.name=="BulletList")n=s.lastChild,r=n.to;else break;return n}const pkt=({state:e,dispatch:t})=>{let n=yi(e),r=null,s=e.changeByRange(a=>{let i=a.from,{doc:l}=e;if(a.empty&&XO.isActiveAt(e,a.from)){let c=l.lineAt(i),u=ckt(yqn(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:wt.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(Ug(c.text,4,d.to)-Ug(c.text,4,d.from));return p==c.from&&(h=gOe(h,e)),{range:wt.cursor(p+h.length),changes:{from:p,to:c.from+d.to,insert:h}}}if(p<i)return{range:wt.cursor(p),changes:{from:p,to:i}}}}}return r={range:a}});return r?!1:(t(e.update(s,{scrollIntoView:!0,userEvent:"delete"})),!0)},hkt=[{key:"Enter",run:fkt},{key:"Backspace",run:pkt}],mkt=uqn({matchClosingTags:!1});function vOe(e={}){let{codeLanguages:t,defaultCodeLanguage:n,addKeymap:r=!0,base:{parser:s}=lkt,completeHTMLTags:a=!0,pasteURLAsLink:i=!0,htmlTagLanguage:l=mkt}=e;if(!(s instanceof hW))throw new RangeError("Base parser provided to `markdown` should be a Markdown parser");let c=e.extensions?[e.extensions]:[],u=[l.support,hqn],d;i&&u.push(gkt),n instanceof QO?(u.push(n.support),d=n.language):n&&(d=n);let f=t||d?gqn(t,d):void 0;c.push(L7n({codeParser:f,htmlParser:l.language.parser})),r&&u.push(ih.high(_I.of(hkt)));let p=mOe(s.configure(c));return a&&u.push(p.data.of({autocomplete:bqn})),new QO(p,u)}function bqn(e){let{state:t,pos:n}=e,r=/<[:\-\.\w\u00b7-\uffff]*$/.exec(t.sliceDoc(n-25,n));if(!r)return null;let s=yi(t).resolveInner(n,-1);for(;s&&!s.type.isTop;){if(s.name=="CodeBlock"||s.name=="FencedCode"||s.name=="ProcessingInstructionBlock"||s.name=="CommentBlock"||s.name=="Link"||s.name=="Image")return null;s=s.parent}return{from:n-r[0].length,to:n,options:xqn(),validFor:/^<[:\-\.\w\u00b7-\uffff]*$/}}let pte=null;function xqn(){if(pte)return pte;let e=oqn(new Zke(gs.create({extensions:mkt}),0,!0));return pte=e?e.options:[]}const wqn=/code|horizontalrule|html|link|comment|processing|escape|entity|image|mark|url/i,gkt=$t.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),!XO.isActiveAt(t.state,r.from,1)))return!1;let a=yi(t.state),i=!1;return a.iterate({from:r.from,to:r.to,enter:l=>{(l.from>r.from||wqn.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)}}),Sqn=Object.freeze(Object.defineProperty({__proto__:null,commonmarkLanguage:lkt,deleteMarkupBackward:pkt,insertNewlineContinueMarkup:fkt,insertNewlineContinueMarkupCommand:dkt,markdown:vOe,markdownKeymap:hkt,markdownLanguage:XO,pasteURLAsLink:gkt},Symbol.toStringTag,{value:"Module"}));function JO(){return JO=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},JO.apply(null,arguments)}var kqn=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=$t.theme(i,{dark:t==="dark"}),d=Yg.define(a),f=[u,lS(d)];return f},Oqn={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)"},_qn=[{tag:de.comment,color:"#6272a4"},{tag:de.string,color:"#f1fa8c"},{tag:de.atom,color:"#bd93f9"},{tag:de.meta,color:"#f8f8f2"},{tag:[de.keyword,de.operator,de.tagName],color:"#ff79c6"},{tag:[de.function(de.propertyName),de.propertyName],color:"#66d9ef"},{tag:[de.definition(de.variableName),de.function(de.variableName),de.className,de.attributeName],color:"#50fa7b"},{tag:de.atom,color:"#bd93f9"}],TI=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 kqn({theme:r,settings:JO({},Oqn,a),styles:[..._qn,...l]})};TI();function vkt(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 Cqn=e=>{let{state:t}=e,n=t.doc.lineAt(t.selection.main.from),r=bOe(e.state,n.from);return r.line?Eqn(e):r.block?jqn(e):!1};function yOe(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 Eqn=yOe(Aqn,0),Tqn=yOe(ykt,0),jqn=yOe((e,t)=>ykt(e,t,Iqn(t)),0);function bOe(e,t){let n=e.languageDataAt("commentTokens",t,1);return n.length?n[0]:{}}const DR=50;function Nqn(e,{open:t,close:n},r,s){let a=e.sliceDoc(r-DR,r),i=e.sliceDoc(s,s+DR),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*DR?d=f=e.sliceDoc(r,s):(d=e.sliceDoc(r,r+DR),f=e.sliceDoc(s-DR,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 Iqn(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 ykt(e,t,n=t.selection.ranges){let r=n.map(a=>bOe(t,a.from).block);if(!r.every(a=>a))return null;let s=n.map((a,i)=>Nqn(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 Aqn(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=bOe(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 xve=zy.define(),Rqn=zy.define(),Pqn=kn.define(),bkt=kn.define({combine(e){return By(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)})}}),xkt=xl.define({create(){return Jv.empty},update(e,t){let n=t.state.facet(bkt),r=t.annotation(xve);if(r){let c=Ef.fromTransaction(t,r.selection),u=r.side,d=u==0?e.undone:e.done;return c?d=YB(d,d.length,n.minDepth,c):d=kkt(d,t.startState.selection),new Jv(u==0?r.rest:d,u==0?d:r.rest)}let s=t.annotation(Rqn);if((s=="full"||s=="before")&&(e=e.isolate()),t.annotation(Rl.addToHistory)===!1)return t.changes.empty?e:e.addMapping(t.changes.desc);let a=Ef.fromTransaction(t),i=t.annotation(Rl.time),l=t.annotation(Rl.userEvent);return a?e=e.addChanges(a,i,l,n,t):t.selection&&(e=e.addSelection(t.startState.selection,i,l,n.newGroupDelay)),(s=="full"||s=="after")&&(e=e.isolate()),e},toJSON(e){return{done:e.done.map(t=>t.toJSON()),undone:e.undone.map(t=>t.toJSON())}},fromJSON(e){return new Jv(e.done.map(Ef.fromJSON),e.undone.map(Ef.fromJSON))}});function $qn(e={}){return[xkt,bkt.of(e),$t.domEventHandlers({beforeinput(t,n){let r=t.inputType=="historyUndo"?wkt:t.inputType=="historyRedo"?wve:null;return r?(t.preventDefault(),r(n)):!1}})]}function mW(e,t){return function({state:n,dispatch:r}){if(!t&&n.readOnly)return!1;let s=n.field(xkt,!1);if(!s)return!1;let a=s.pop(e,n,t);return a?(r(a),!0):!1}}const wkt=mW(0,!1),wve=mW(1,!1),Mqn=mW(0,!0),Dqn=mW(1,!0);class Ef{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 Ef(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 Ef(t.changes&&Il.fromJSON(t.changes),[],t.mapped&&cy.fromJSON(t.mapped),t.startSelection&&wt.fromJSON(t.startSelection),t.selectionsAfter.map(wt.fromJSON))}static fromTransaction(t,n){let r=Qh;for(let s of t.startState.facet(Pqn)){let a=s(t);a.length&&(r=r.concat(a))}return!r.length&&t.changes.empty?null:new Ef(t.changes.invert(t.startState.doc),r,void 0,n||t.startState.selection,Qh)}static selection(t){return new Ef(void 0,Qh,void 0,void 0,t)}}function YB(e,t,n,r){let s=t+1>n+20?t-n-1:0,a=e.slice(s,t);return a.push(r),a}function Lqn(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 Fqn(e,t){return e.ranges.length==t.ranges.length&&e.ranges.filter((n,r)=>n.empty!=t.ranges[r].empty).length===0}function Skt(e,t){return e.length?t.length?e.concat(t):e:t}const Qh=[],zqn=200;function kkt(e,t){if(e.length){let n=e[e.length-1],r=n.selectionsAfter.slice(Math.max(0,n.selectionsAfter.length-zqn));return r.length&&r[r.length-1].eq(t)?e:(r.push(t),YB(e,e.length-1,1e9,n.setSelAfter(r)))}else return[Ef.selection([t])]}function Bqn(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 hte(e,t){if(!e.length)return e;let n=e.length,r=Qh;for(;n;){let s=Uqn(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?[Ef.selection(r)]:Qh}function Uqn(e,t,n){let r=Skt(e.selectionsAfter.length?e.selectionsAfter.map(l=>l.map(t)):Qh,n);if(!e.changes)return Ef.selection(r);let s=e.changes.map(t),a=t.mapDesc(e.changes,!0),i=e.mapped?e.mapped.composeDesc(a):a;return new Ef(s,vr.mapEffects(e.effects,t),i,e.startSelection.map(a),r)}const qqn=/^(input\.type|delete)($|\.)/;class Jv{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 Jv(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||qqn.test(r))&&(!l.selectionsAfter.length&&n-this.prevTime<s.newGroupDelay&&s.joinToEvent(a,Lqn(l.changes,t.changes))||r=="input.type.compose")?i=YB(i,i.length-1,s.minDepth,new Ef(t.changes.compose(l.changes),Skt(vr.mapEffects(t.effects,l.changes),l.effects),l.mapped,l.startSelection,Qh)):i=YB(i,i.length,s.minDepth,t),new Jv(i,Qh,n,r)}addSelection(t,n,r,s){let a=this.done.length?this.done[this.done.length-1].selectionsAfter:Qh;return a.length>0&&n-this.prevTime<s&&r==this.prevUserEvent&&r&&/^select($|\.)/.test(r)&&Fqn(a[a.length-1],t)?this:new Jv(kkt(this.done,t),this.undone,n,r)}addMapping(t){return new Jv(hte(this.done,t),hte(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:xve.of({side:t,rest:Bqn(s),selection:i}),userEvent:t==0?"select.undo":"select.redo",scrollIntoView:!0});if(a.changes){let l=s.length==1?Qh:s.slice(0,s.length-1);return a.mapped&&(l=hte(l,a.mapped)),n.update({changes:a.changes,selection:a.startSelection,effects:a.effects,annotations:xve.of({side:t,rest:l,selection:i}),filter:!1,userEvent:t==0?"undo":"redo",scrollIntoView:!0})}else return null}}Jv.empty=new Jv(Qh,Qh);const Vqn=[{key:"Mod-z",run:wkt,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:wve,preventDefault:!0},{linux:"Ctrl-Shift-z",run:wve,preventDefault:!0},{key:"Mod-u",run:Mqn,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:Dqn,preventDefault:!0}];function jI(e,t){return wt.create(e.ranges.map(t),e.mainIndex)}function Kg(e,t){return e.update({selection:t,scrollIntoView:!0,userEvent:"select"})}function Xg({state:e,dispatch:t},n){let r=jI(e.selection,n);return r.eq(e.selection,!0)?!1:(t(Kg(e,r)),!0)}function gW(e,t){return wt.cursor(t?e.to:e.from)}function Okt(e,t){return Xg(e,n=>n.empty?e.moveByChar(n,t):gW(n,t))}function ad(e){return e.textDirectionAt(e.state.selection.main.head)==Ci.LTR}const _kt=e=>Okt(e,!ad(e)),Ckt=e=>Okt(e,ad(e));function Ekt(e,t){return Xg(e,n=>n.empty?e.moveByGroup(n,t):gW(n,t))}const Hqn=e=>Ekt(e,!ad(e)),Wqn=e=>Ekt(e,ad(e));function Zqn(e,t,n){if(t.type.prop(n))return!0;let r=t.to-t.from;return r&&(r>2||/[^\s,.;:]/.test(e.sliceDoc(t.from,t.to)))||t.firstChild}function vW(e,t,n){let r=yi(e).resolveInner(t.head),s=n?$r.closedBy:$r.openedBy;for(let c=t.head;;){let u=n?r.childAfter(c):r.childBefore(c);if(!u)break;Zqn(e,u,s)?r=u:c=n?u.to:u.from}let a=r.type.prop(s),i,l;return a&&(i=n?Xv(e,r.from,1):Xv(e,r.to,-1))&&i.matched?l=n?i.end.to:i.end.from:l=n?r.to:r.from,wt.cursor(l,n?-1:1)}const Gqn=e=>Xg(e,t=>vW(e.state,t,!ad(e))),Qqn=e=>Xg(e,t=>vW(e.state,t,ad(e)));function Tkt(e,t){return Xg(e,n=>{if(!n.empty)return gW(n,t);let r=e.moveVertically(n,t);return r.head!=n.head?r:e.moveToLineBoundary(n,t)})}const jkt=e=>Tkt(e,!1),Nkt=e=>Tkt(e,!0);function Ikt(e){let t=e.scrollDOM.clientHeight<e.scrollDOM.scrollHeight-2,n=0,r=0,s;if(t){for(let a of e.state.facet($t.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 Akt(e,t){let n=Ikt(e),{state:r}=e,s=jI(r.selection,i=>i.empty?e.moveVertically(i,t,n.height):gW(i,t));if(s.eq(r.selection))return!1;let a;if(n.selfScroll){let i=e.coordsAtPos(r.selection.main.head),l=e.scrollDOM.getBoundingClientRect(),c=l.top+n.marginTop,u=l.bottom-n.marginBottom;i&&i.top>c&&i.bottom<u&&(a=$t.scrollIntoView(s.main.head,{y:"start",yMargin:i.top-c}))}return e.dispatch(Kg(r,s),{effects:a}),!0}const v9e=e=>Akt(e,!1),Sve=e=>Akt(e,!0);function cS(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=wt.cursor(r.from+a))}return s}const Yqn=e=>Xg(e,t=>cS(e,t,!0)),Kqn=e=>Xg(e,t=>cS(e,t,!1)),Xqn=e=>Xg(e,t=>cS(e,t,!ad(e))),Jqn=e=>Xg(e,t=>cS(e,t,ad(e))),eVn=e=>Xg(e,t=>wt.cursor(e.lineBlockAt(t.head).from,1)),tVn=e=>Xg(e,t=>wt.cursor(e.lineBlockAt(t.head).to,-1));function nVn(e,t,n){let r=!1,s=jI(e.selection,a=>{let i=Xv(e,a.head,-1)||Xv(e,a.head,1)||a.head>0&&Xv(e,a.head-1,1)||a.head<e.doc.length&&Xv(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 wt.cursor(l)});return r?(t(Kg(e,s)),!0):!1}const rVn=({state:e,dispatch:t})=>nVn(e,t);function Dm(e,t,n){let r=jI(e.state.selection,s=>{s.undirectional&&s.head>=s.anchor!=t&&(s=wt.range(s.head,s.anchor));let a=n(s);return wt.range(s.anchor,a.head,a.goalColumn,a.bidiLevel||void 0,a.assoc)});return r.eq(e.state.selection)?!1:(e.dispatch(Kg(e.state,r)),!0)}function Rkt(e,t){return Dm(e,t,n=>e.moveByChar(n,t))}const Pkt=e=>Rkt(e,!ad(e)),$kt=e=>Rkt(e,ad(e));function Mkt(e,t){return Dm(e,t,n=>e.moveByGroup(n,t))}const sVn=e=>Mkt(e,!ad(e)),aVn=e=>Mkt(e,ad(e)),iVn=e=>{let t=!ad(e);return Dm(e,t,n=>vW(e.state,n,t))},oVn=e=>{let t=ad(e);return Dm(e,t,n=>vW(e.state,n,t))};function Dkt(e,t){return Dm(e,t,n=>e.moveVertically(n,t))}const Lkt=e=>Dkt(e,!1),Fkt=e=>Dkt(e,!0);function zkt(e,t){return Dm(e,t,n=>e.moveVertically(n,t,Ikt(e).height))}const y9e=e=>zkt(e,!1),b9e=e=>zkt(e,!0),lVn=e=>Dm(e,!0,t=>cS(e,t,!0)),cVn=e=>Dm(e,!1,t=>cS(e,t,!1)),uVn=e=>{let t=!ad(e);return Dm(e,t,n=>cS(e,n,t))},dVn=e=>{let t=ad(e);return Dm(e,t,n=>cS(e,n,t))},fVn=e=>Dm(e,!1,t=>wt.cursor(e.lineBlockAt(t.head).from)),pVn=e=>Dm(e,!0,t=>wt.cursor(e.lineBlockAt(t.head).to)),x9e=({state:e,dispatch:t})=>(t(Kg(e,{anchor:0})),!0),w9e=({state:e,dispatch:t})=>(t(Kg(e,{anchor:e.doc.length})),!0),S9e=({state:e,dispatch:t})=>(t(Kg(e,{anchor:e.selection.main.anchor,head:0})),!0),k9e=({state:e,dispatch:t})=>(t(Kg(e,{anchor:e.selection.main.anchor,head:e.doc.length})),!0),hVn=({state:e,dispatch:t})=>(t(e.update({selection:{anchor:0,head:e.doc.length},userEvent:"select"})),!0),mVn=({state:e,dispatch:t})=>{let n=yW(e).map(({from:r,to:s})=>wt.range(r,Math.min(s+1,e.doc.length)));return t(e.update({selection:wt.create(n),userEvent:"select"})),!0},gVn=({state:e,dispatch:t})=>{let n=jI(e.selection,r=>{let s=yi(e),a=s.resolveStack(r.from,1);if(r.empty){let i=s.resolveStack(r.from,-1);i.node.from>=a.node.from&&i.node.to<=a.node.to&&(a=i)}for(let i=a;i;i=i.next){let{node:l}=i;if((l.from<r.from&&l.to>=r.to||l.to>r.to&&l.from<=r.from)&&i.next)return wt.range(l.to,l.from)}return r});return n.eq(e.selection)?!1:(t(Kg(e,n)),!0)};function Bkt(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(Kg(n,wt.create(s,s.length-1))),!0)}const vVn=e=>Bkt(e,!1),yVn=e=>Bkt(e,!0),bVn=({state:e,dispatch:t})=>{let n=e.selection,r=null;return n.ranges.length>1?r=wt.create([n.main]):n.main.empty||(r=wt.create([wt.cursor(n.main.head)])),r?(t(Kg(e,r)),!0):!1};function r4(e,t){if(e.state.readOnly)return!1;let n="delete.selection",{state:r}=e,s=r.changeByRange(a=>{let{from:i,to:l}=a;if(i==l){let c=t(a);c<i?(n="delete.backward",c=SF(e,c,!1)):c>i&&(n="delete.forward",c=SF(e,c,!0)),i=Math.min(i,c),l=Math.max(l,c)}else i=SF(e,i,!1),l=SF(e,l,!0);return i==l?{range:a}:{changes:{from:i,to:l},range:wt.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"?$t.announce.of(r.phrase("Selection deleted")):void 0})),!0)}function SF(e,t,n){if(e instanceof $t)for(let r of e.state.facet($t.atomicRanges).map(s=>s(e)))r.between(t,t,(s,a)=>{s<t&&a>t&&(t=n?a:s)});return t}const Ukt=(e,t,n)=>r4(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=Ug(l,a.tabSize),d=u%YO(a)||YO(a);for(let f=0;f<d&&l[l.length-1-f]==" ";f++)s--;c=s}else c=Ic(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=Ic(i.text,c-i.from,!1,!1)+i.from);return c}),kve=e=>Ukt(e,!1,!0),qkt=e=>Ukt(e,!0,!1),Vkt=(e,t)=>r4(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=Ic(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}),Hkt=e=>Vkt(e,!1),xVn=e=>Vkt(e,!0),wVn=e=>r4(e,t=>{let n=e.lineBlockAt(t.head).to;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),SVn=e=>r4(e,t=>{let n=e.moveToLineBoundary(t,!1).head;return t.head>n?n:Math.max(0,t.head-1)}),kVn=e=>r4(e,t=>{let n=e.moveToLineBoundary(t,!0).head;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),OVn=({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:wt.cursor(r.from)}));return t(e.update(n,{scrollIntoView:!0,userEvent:"input"})),!0},_Vn=({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:Ic(a.text,s-a.from,!1)+a.from,l=s==a.to?s+1:Ic(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:wt.cursor(l)}});return n.changes.empty?!1:(t(e.update(n,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function yW(e){let t=[],n=-1;for(let r of e.selection.ranges){let s=e.doc.lineAt(r.from),a=e.doc.lineAt(r.to);if(!r.empty&&r.to==a.from&&(a=e.doc.lineAt(r.to-1)),n>=s.number){let i=t[t.length-1];i.to=a.to,i.ranges.push(r)}else t.push({from:s.from,to:a.to,ranges:[r]});n=a.number+1}return t}function Wkt(e,t,n){if(e.readOnly)return!1;let r=[],s=[];for(let a of yW(e)){if(n?a.to==e.doc.length:a.from==0)continue;let i=e.doc.lineAt(n?a.to+1:a.from-1),l=i.length+1;if(n){r.push({from:a.to,to:i.to},{from:a.from,insert:i.text+e.lineBreak});for(let c of a.ranges)s.push(wt.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(wt.range(c.anchor-l,c.head-l))}}return r.length?(t(e.update({changes:r,scrollIntoView:!0,selection:wt.create(s,e.selection.mainIndex),userEvent:"move.line"})),!0):!1}const CVn=({state:e,dispatch:t})=>Wkt(e,t,!1),EVn=({state:e,dispatch:t})=>Wkt(e,t,!0);function Zkt(e,t,n){if(e.readOnly)return!1;let r=[];for(let a of yW(e))n?r.push({from:a.from,insert:e.doc.slice(a.from,a.to)+e.lineBreak}):r.push({from:a.to,insert:e.lineBreak+e.doc.slice(a.from,a.to)});let s=e.changes(r);return t(e.update({changes:s,selection:e.selection.map(s,n?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}const TVn=({state:e,dispatch:t})=>Zkt(e,t,!1),jVn=({state:e,dispatch:t})=>Zkt(e,t,!0),NVn=e=>{if(e.state.readOnly)return!1;let{state:t}=e,n=t.changes(yW(t).map(({from:s,to:a})=>(s>0?s--:a<t.doc.length&&a++,{from:s,to:a}))),r=jI(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 IVn(e,t){if(/\(\)|\[\]|\{\}/.test(e.sliceDoc(t-1,t+1)))return{from:t,to:t};let n=yi(e).resolveInner(t),r=n.childBefore(t),s=n.childAfter(t),a;return r&&s&&r.to<=t&&s.from>=t&&(a=r.type.prop($r.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 O9e=Gkt(!1),AVn=Gkt(!0);function Gkt(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&&IVn(t,a);e&&(a=i=(i<=l.to?l:t.doc.lineAt(i)).to);let u=new dW(t,{simulateBreak:a,simulateDoubleBreak:!!c}),d=Bke(u,a);for(d==null&&(d=Ug(/^\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=["",EM(t,d)];return c&&f.push(EM(t,u.lineIndent(l.from,-1))),{changes:{from:a,to:i,insert:wa.of(f)},range:wt.cursor(a+1+f[1].length)}});return n(t.update(r,{scrollIntoView:!0,userEvent:"input"})),!0}}function xOe(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:wt.range(a.mapPos(r.anchor,1),a.mapPos(r.head,1))}})}const RVn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=Object.create(null),r=new dW(e,{overrideIndentation:a=>{let i=n[a];return i??-1}}),s=xOe(e,(a,i,l)=>{let c=Bke(r,a.from);if(c==null)return;/\S/.test(a.text)||(c=0);let u=/^\s*/.exec(a.text)[0],d=EM(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},Qkt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(xOe(e,(n,r)=>{r.push({from:n.from,insert:e.facet(CI)})}),{userEvent:"input.indent"})),!0),Ykt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(xOe(e,(n,r)=>{let s=/^\s*/.exec(n.text)[0];if(!s)return;let a=Ug(s,e.tabSize),i=0,l=EM(e,Math.max(0,a-YO(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),PVn=e=>(e.setTabFocusMode(),!0),$Vn=[{key:"Ctrl-b",run:_kt,shift:Pkt,preventDefault:!0},{key:"Ctrl-f",run:Ckt,shift:$kt},{key:"Ctrl-p",run:jkt,shift:Lkt},{key:"Ctrl-n",run:Nkt,shift:Fkt},{key:"Ctrl-a",run:eVn,shift:fVn},{key:"Ctrl-e",run:tVn,shift:pVn},{key:"Ctrl-d",run:qkt},{key:"Ctrl-h",run:kve},{key:"Ctrl-k",run:wVn},{key:"Ctrl-Alt-h",run:Hkt},{key:"Ctrl-o",run:OVn},{key:"Ctrl-t",run:_Vn},{key:"Ctrl-v",run:Sve}],MVn=[{key:"ArrowLeft",run:_kt,shift:Pkt,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:Hqn,shift:sVn,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:Xqn,shift:uVn,preventDefault:!0},{key:"ArrowRight",run:Ckt,shift:$kt,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:Wqn,shift:aVn,preventDefault:!0},{mac:"Cmd-ArrowRight",run:Jqn,shift:dVn,preventDefault:!0},{key:"ArrowUp",run:jkt,shift:Lkt,preventDefault:!0},{mac:"Cmd-ArrowUp",run:x9e,shift:S9e},{mac:"Ctrl-ArrowUp",run:v9e,shift:y9e},{key:"ArrowDown",run:Nkt,shift:Fkt,preventDefault:!0},{mac:"Cmd-ArrowDown",run:w9e,shift:k9e},{mac:"Ctrl-ArrowDown",run:Sve,shift:b9e},{key:"PageUp",run:v9e,shift:y9e},{key:"PageDown",run:Sve,shift:b9e},{key:"Home",run:Kqn,shift:cVn,preventDefault:!0},{key:"Mod-Home",run:x9e,shift:S9e},{key:"End",run:Yqn,shift:lVn,preventDefault:!0},{key:"Mod-End",run:w9e,shift:k9e},{key:"Enter",run:O9e,shift:O9e},{key:"Mod-a",run:hVn},{key:"Backspace",run:kve,shift:kve,preventDefault:!0},{key:"Delete",run:qkt,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:Hkt,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:xVn,preventDefault:!0},{mac:"Mod-Backspace",run:SVn,preventDefault:!0},{mac:"Mod-Delete",run:kVn,preventDefault:!0}].concat($Vn.map(e=>({mac:e.key,run:e.run,shift:e.shift}))),DVn=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:Gqn,shift:iVn},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:Qqn,shift:oVn},{key:"Alt-ArrowUp",run:CVn},{key:"Shift-Alt-ArrowUp",run:TVn},{key:"Alt-ArrowDown",run:EVn},{key:"Shift-Alt-ArrowDown",run:jVn},{key:"Mod-Alt-ArrowUp",run:vVn},{key:"Mod-Alt-ArrowDown",run:yVn},{key:"Escape",run:bVn},{key:"Mod-Enter",run:AVn},{key:"Alt-l",mac:"Ctrl-l",run:mVn},{key:"Mod-i",run:gVn,preventDefault:!0},{key:"Mod-[",run:Ykt},{key:"Mod-]",run:Qkt},{key:"Mod-Alt-\\",run:RVn},{key:"Shift-Mod-k",run:NVn},{key:"Shift-Mod-\\",run:rVn},{key:"Mod-/",run:Cqn},{key:"Alt-A",run:Tqn},{key:"Ctrl-m",mac:"Shift-Alt-m",run:PVn}].concat(MVn),LVn={key:"Tab",run:Qkt,shift:Ykt},_9e=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class $x{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(_9e(l)):_9e,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 vf(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=Ske(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=Uv(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"&&($x.prototype[Symbol.iterator]=function(){return this});const Kkt={from:-1,to:-1,match:/.*/.exec(""),precise:!0},wOe="gm"+(/x/.unicode==null?"":"u");class Xkt{constructor(t,n,r,s=0,a=t.length){if(this.text=t,this.to=a,this.curLine="",this.done=!1,this.value=Kkt,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new Jkt(t,n,r,s,a);this.re=new RegExp(n,wOe+(r?.ignoreCase?"i":"")),this.test=r?.test,this.iter=t.iter();let i=t.lineAt(s);this.curLineStart=i.from,this.matchPos=KB(t,s),this.getLine(this.curLineStart)}getLine(t){this.iter.next(t),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let t=this.matchPos-this.curLineStart;;){this.re.lastIndex=t;let n=this.matchPos<=this.to&&this.re.exec(this.curLine);if(n){let r=this.curLineStart+n.index,s=r+n[0].length;if(this.matchPos=KB(this.text,s+(r==s?1:0)),r==this.curLineStart+this.curLine.length&&this.nextLine(),(r<s||r>this.value.to)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,precise:!0,match:n},this;t=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length<this.to)this.nextLine(),t=0;else return this.done=!0,this}}}const mte=new WeakMap;class lj{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let s=mte.get(t);if(!s||s.from>=r||s.to<=n){let l=new lj(n,t.sliceString(n,r));return mte.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)),mte.set(t,new lj(i,a)),new lj(n,a.slice(n-i,r-i))}}class Jkt{constructor(t,n,r,s,a){this.text=t,this.to=a,this.done=!1,this.value=Kkt,this.matchPos=KB(t,s),this.re=new RegExp(n,wOe+(r?.ignoreCase?"i":"")),this.test=r?.test,this.flat=lj.get(t,s,this.chunkEnd(s+5e3))}chunkEnd(t){return t>=this.to?this.to:this.text.lineAt(t).to}next(){for(;;){let t=this.re.lastIndex=this.matchPos-this.flat.from,n=this.re.exec(this.flat.text);if(n&&!n[0]&&n.index==t&&(this.re.lastIndex=t+1,n=this.re.exec(this.flat.text)),n){let r=this.flat.from+n.index,s=r+n[0].length;if((this.flat.to>=this.to||n.index+n[0].length<=this.flat.text.length-10)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,precise:!0,match:n},this.matchPos=KB(this.text,s+(r==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=lj.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(Xkt.prototype[Symbol.iterator]=Jkt.prototype[Symbol.iterator]=function(){return this});function FVn(e){try{return new RegExp(e,wOe),!0}catch{return!1}}function KB(e,t){if(t>=e.length)return t;let n=e.lineAt(t),r;for(;t<n.to&&(r=n.text.charCodeAt(t-n.from))>=56320&&r<57344;)t++;return t}const zVn=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:s}=w8n(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))),v=wt.cursor(m.from+Math.max(0,Math.min(p,m.length)));e.dispatch({effects:[r,$t.scrollIntoView(v.from,{y:"center"})],selection:v})}),!0},BVn={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},UVn=kn.define({combine(e){return By(e,BVn,{highlightWordAroundCursor:(t,n)=>t||n,minSelectionLength:Math.min,maxMatches:Math.min})}});function qVn(e){return[GVn,ZVn]}const VVn=Nn.mark({class:"cm-selectionMatch"}),HVn=Nn.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function C9e(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 WVn(e,t,n,r){return e(t.sliceDoc(n,n+1))==wo.Word&&e(t.sliceDoc(r-1,r))==wo.Word}const ZVn=_o.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(UVn),{state:n}=e,r=n.selection;if(r.ranges.length>1)return Nn.none;let s=r.main,a,i=null;if(s.empty){if(!t.highlightWordAroundCursor)return Nn.none;let c=n.wordAt(s.head);if(!c)return Nn.none;i=n.charCategorizer(s.head),a=n.sliceDoc(c.from,c.to)}else{let c=s.to-s.from;if(c<t.minSelectionLength||c>200)return Nn.none;if(t.wholeWords){if(a=n.sliceDoc(s.from,s.to),i=n.charCategorizer(s.head),!(C9e(i,n,s.from,s.to)&&WVn(i,n,s.from,s.to)))return Nn.none}else if(a=n.sliceDoc(s.from,s.to),!a)return Nn.none}let l=[];for(let c of e.visibleRanges){let u=new $x(n.doc,a,c.from,c.to);for(;!u.next().done;){let{from:d,to:f}=u.value;if((!i||C9e(i,n,d,f))&&(s.empty&&d<=s.from&&f>=s.to?l.push(HVn.range(d,f)):(d>=s.to||f<=s.from)&&l.push(VVn.range(d,f)),l.length>t.maxMatches))return Nn.none}}return Nn.set(l)}},{decorations:e=>e.decorations}),GVn=$t.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),QVn=({state:e,dispatch:t})=>{let{selection:n}=e,r=wt.create(n.ranges.map(s=>e.wordAt(s.head)||wt.cursor(s.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function YVn(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 $x(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(i)return null;l=new $x(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 KVn=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(a=>a.from===a.to))return QVn({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=YVn(e,r);return s?(t(e.update({selection:e.selection.addRange(wt.range(s.from,s.to),!1),effects:$t.scrollIntoView(s.to)})),!0):!1},NI=kn.define({combine(e){return By(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new dHn(t),scrollToMatch:t=>$t.scrollIntoView(t)})}});class eOt{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||FVn(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!t.wholeWord,this.test=t.test}unquote(t){return this.literal?t:t.replace(/\\([nrt\\])/g,(n,r)=>r=="n"?`
|
|
234
|
-
`:r=="r"?"\r":r=="t"?" ":"\\")}eq(t){return this.search==t.search&&this.replace==t.replace&&this.caseSensitive==t.caseSensitive&&this.regexp==t.regexp&&this.wholeWord==t.wholeWord&&this.test==t.test}create(){return this.regexp?new rHn(this):new eHn(this)}getCursor(t,n=0,r){let s=t.doc?t:gs.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?rT(this,s,n,r):nT(this,s,n,r)}}class tOt{constructor(t){this.spec=t}}function XVn(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 nT(e,t,n,r){let s;return e.wholeWord&&(s=JVn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=XVn(e.test,t,s)),new $x(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function JVn(e,t){return(n,r,s,a)=>((a>n||a+s.length<r)&&(a=Math.max(0,n-2),s=e.sliceString(a,Math.min(e.length,r+2))),(t(XB(s,n-a))!=wo.Word||t(JB(s,n-a))!=wo.Word)&&(t(JB(s,r-a))!=wo.Word||t(XB(s,r-a))!=wo.Word))}class eHn extends tOt{constructor(t){super(t)}nextMatch(t,n,r){let s=nT(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=nT(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=nT(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=nT(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=nT(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 tHn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function rT(e,t,n,r){let s;return e.wholeWord&&(s=nHn(t.charCategorizer(t.selection.main.head))),e.test&&(s=tHn(e.test,t,s)),new Xkt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function XB(e,t){return e.slice(Ic(e,t,!1),t)}function JB(e,t){return e.slice(t,Ic(e,t))}function nHn(e){return(t,n,r)=>!r[0].length||(e(XB(r.input,r.index))!=wo.Word||e(JB(r.input,r.index))!=wo.Word)&&(e(JB(r.input,r.index+r[0].length))!=wo.Word||e(XB(r.input,r.index+r[0].length))!=wo.Word)}class rHn extends tOt{nextMatch(t,n,r){let s=rT(this.spec,t,r,t.doc.length).next();return s.done&&(s=rT(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=rT(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=rT(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=rT(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 MM=vr.define(),SOe=vr.define(),Yw=xl.define({create(e){return new gte(Ove(e).create(),null)},update(e,t){for(let n of t.effects)n.is(MM)?e=new gte(n.value.create(),e.panel):n.is(SOe)&&(e=new gte(e.query,n.value?kOe:null));return e},provide:e=>CM.from(e,t=>t.panel)});class gte{constructor(t,n){this.query=t,this.panel=n}}const sHn=Nn.mark({class:"cm-searchMatch"}),aHn=Nn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),iHn=_o.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Yw))}update(e){let t=e.state.field(Yw);(t!=e.startState.field(Yw)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return Nn.none;let{view:n}=this,r=new Wd;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?aHn:sHn)})}return r.finish()}},{decorations:e=>e.decorations});function s4(e){return t=>{let n=t.state.field(Yw,!1);return n&&n.query.spec.valid?e(t,n):sOt(t)}}const eU=s4((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=wt.single(r.from,r.to),a=e.state.facet(NI);return e.dispatch({selection:s,effects:[OOe(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),rOt(e),!0}),tU=s4((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let a=wt.single(s.from,s.to),i=e.state.facet(NI);return e.dispatch({selection:a,effects:[OOe(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),rOt(e),!0}),oHn=s4((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:wt.create(n.map(r=>wt.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),lHn=({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 $x(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(i=a.length),a.push(wt.range(l.value.from,l.value.to))}return t(e.update({selection:wt.create(a,i),userEvent:"select.search.matches"})),!0},E9e=s4((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($t.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=wt.single(i.from,i.to).map(f),d.push(OOe(e,i)),d.push(n.facet(NI).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),cHn=s4((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:$t.announce.of(r),userEvent:"input.replace.all"}),!0});function kOe(e){return e.state.facet(NI).createPanel(e)}function Ove(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(NI);return new eOt({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 nOt(e){let t=Fke(e,kOe);return t&&t.dom.querySelector("[main-field]")}function rOt(e){let t=nOt(e);t&&t==e.root.activeElement&&t.select()}const sOt=e=>{let t=e.state.field(Yw,!1);if(t&&t.panel){let n=nOt(e);if(n&&n!=e.root.activeElement){let r=Ove(e.state,t.query.spec);r.valid&&e.dispatch({effects:MM.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[SOe.of(!0),t?MM.of(Ove(e.state,t.query.spec)):vr.appendConfig.of(pHn)]});return!0},aOt=e=>{let t=e.state.field(Yw,!1);if(!t||!t.panel)return!1;let n=Fke(e,kOe);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:SOe.of(!1)}),!0},uHn=[{key:"Mod-f",run:sOt,scope:"editor search-panel"},{key:"F3",run:eU,shift:tU,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:eU,shift:tU,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:aOt,scope:"editor search-panel"},{key:"Mod-Shift-l",run:lHn},{key:"Mod-Alt-g",run:zVn},{key:"Mod-d",run:KVn,preventDefault:!0}];class dHn{constructor(t){this.view=t;let n=this.query=t.state.field(Yw).query.spec;this.commit=this.commit.bind(this),this.searchField=fi("input",{value:n.search,placeholder:dp(t,"Find"),"aria-label":dp(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=fi("input",{value:n.replace,placeholder:dp(t,"Replace"),"aria-label":dp(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=fi("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=fi("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=fi("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return fi("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=fi("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>eU(t),[dp(t,"next")]),r("prev",()=>tU(t),[dp(t,"previous")]),r("select",()=>oHn(t),[dp(t,"all")]),fi("label",null,[this.caseField,dp(t,"match case")]),fi("label",null,[this.reField,dp(t,"regexp")]),fi("label",null,[this.wordField,dp(t,"by word")]),...t.state.readOnly?[]:[fi("br"),this.replaceField,r("replace",()=>E9e(t),[dp(t,"replace")]),r("replaceAll",()=>cHn(t),[dp(t,"replace all")])],fi("button",{name:"close",onclick:()=>aOt(t),"aria-label":dp(t,"close"),type:"button"},["×"])])}commit(){let t=new eOt({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:MM.of(t)}))}keydown(t){Izn(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?tU:eU)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),E9e(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(MM)&&!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(NI).top}}function dp(e,t){return e.state.phrase(t)}const kF=30,OF=/[\s\.,:;?!]/;function OOe(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),s=e.state.doc.lineAt(n).to,a=Math.max(r.from,t-kF),i=Math.min(s,n+kF),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<kF;c++)if(!OF.test(l[c+1])&&OF.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-kF;c--)if(!OF.test(l[c-1])&&OF.test(l[c])){l=l.slice(0,c);break}}return $t.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const fHn=$t.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"}}),pHn=[Yw,ih.low(iHn),fHn];class T9e{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class Nk{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(DM).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new Wd,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((v,y)=>Math.min(v,y.to),f&&f.from>p?f.from:1e8)):(p=f.from,h=f.to,l.push(f),d++);d<a.length;){let v=a[d];if(v.from==p&&(v.to>v.from||v.to==p))l.push(v),d++,h=Math.min(v.to,h);else{h=Math.min(v.from,h);break}}let m=CHn(l);if(l.some(v=>v.from==v.to||v.from==v.to-1&&r.doc.lineAt(v.from).to==v.from))i.add(p,p,Nn.widget({widget:new SHn(m),diagnostics:l.slice()}));else{let v=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(p,h,Nn.mark({class:"cm-lintRange cm-lintRange-"+m+v,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>h)}))}c=h;for(let v=0;v<l.length;v++)l[v].to<=c&&l.splice(v--,1)}let u=i.finish();return new Nk(u,n,aN(u))}}function aN(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 T9e(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new T9e(r.from,a,r.diagnostic)}}),r}function hHn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(DM).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(iOt))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function mHn(e,t){return e.field(Ap,!1)?t:t.concat(vr.appendConfig.of(EHn))}const iOt=vr.define(),_Oe=vr.define(),oOt=vr.define(),Ap=xl.define({create(){return new Nk(Nn.none,null,null)},update(e,t){if(t.docChanged&&e.diagnostics.size){let n=e.diagnostics.map(t.changes),r=null,s=e.panel;if(e.selected){let a=t.changes.mapPos(e.selected.from,1);r=aN(n,e.selected.diagnostic,a)||aN(n,null,a)}!n.size&&s&&t.state.facet(DM).autoPanel&&(s=null),e=new Nk(n,s,r)}for(let n of t.effects)if(n.is(iOt)){let r=t.state.facet(DM).autoPanel?n.value.length?LM.open:null:e.panel;e=Nk.init(n.value,r,t.state)}else n.is(_Oe)?e=new Nk(e.diagnostics,n.value?LM.open:null,e.selected):n.is(oOt)&&(e=new Nk(e.diagnostics,e.panel,n.value));return e},provide:e=>[CM.from(e,t=>t.panel),$t.decorations.from(e,t=>t.diagnostics)]}),gHn=Nn.mark({class:"cm-lintRange cm-lintRange-active"});function vHn(e,t,n){let{diagnostics:r}=e.state.field(Ap),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(DM).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:yHn(e,s)}}}:null}function yHn(e,t){return fi("ul",{class:"cm-tooltip-lint"},t.map(n=>cOt(e,n,!1)))}const bHn=e=>{let t=e.state.field(Ap,!1);(!t||!t.panel)&&e.dispatch({effects:mHn(e.state,[_Oe.of(!0)])});let n=Fke(e,LM.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},j9e=e=>{let t=e.state.field(Ap,!1);return!t||!t.panel?!1:(e.dispatch({effects:_Oe.of(!1)}),!0)},xHn=e=>{let t=e.state.field(Ap,!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)},wHn=[{key:"Mod-Shift-m",run:bHn,preventDefault:!0},{key:"F8",run:xHn}],DM=kn.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...By(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:N9e,tooltipFilter:N9e,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 N9e(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function lOt(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 cOt(e,t,n){var r;let s=n?lOt(t.actions):[];return fi("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},fi("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=aN(e.state.field(Ap).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),fi("u",u.slice(d,d+1)),u.slice(d+1)],p=a.markClass?" "+a.markClass:"";return fi("button",{type:"button",class:"cm-diagnosticAction"+p,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&fi("div",{class:"cm-diagnosticSource"},t.source))}class SHn extends oh{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return fi("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class I9e{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=cOt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class LM{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)j9e(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=lOt(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=aN(this.view.state.field(Ap).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=fi("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=fi("div",{class:"cm-panel-lint"},this.list,fi("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>j9e(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Ap).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(Ap),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 I9e(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 I9e(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(Ap),r=aN(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:oOt.of(r)})}static open(t){return new LM(t)}}function kHn(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 _F(e){return kHn(`<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 OHn=$t.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:_F("#d11")},".cm-lintRange-warning":{backgroundImage:_F("orange")},".cm-lintRange-info":{backgroundImage:_F("#999")},".cm-lintRange-hint":{backgroundImage:_F("#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 _Hn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function CHn(e){let t="hint",n=1;for(let r of e){let s=_Hn(r.severity);s>n&&(n=s,t=r.severity)}return t}const EHn=[Ap,$t.decorations.compute([Ap],e=>{let{selected:t,panel:n}=e.field(Ap);return!t||!n||t.from==t.to?Nn.none:Nn.set([gHn.range(t.from,t.to)])}),b8n(vHn,{hideOn:hHn}),OHn];var A9e=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(g7n)),t.defaultKeymap!==!1&&(a=a.concat(DVn)),t.searchKeymap!==!1&&(a=a.concat(uHn)),t.historyKeymap!==!1&&(a=a.concat(Vqn)),t.foldKeymap!==!1&&(a=a.concat(t9n)),t.completionKeymap!==!1&&(a=a.concat(rSt)),t.lintKeymap!==!1&&(a=a.concat(wHn));var i=[];return t.lineNumbers!==!1&&i.push(I8n()),t.highlightActiveLineGutter!==!1&&i.push(P8n()),t.highlightSpecialChars!==!1&&i.push(Zzn()),t.history!==!1&&i.push($qn()),t.foldGutter!==!1&&i.push(a9n()),t.drawSelection!==!1&&i.push(Dzn()),t.dropCursor!==!1&&i.push(Uzn()),t.allowMultipleSelections!==!1&&i.push(gs.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(Z8n()),t.syntaxHighlighting!==!1&&i.push(lS(c9n,{fallback:!0})),t.bracketMatching!==!1&&i.push(g9n()),t.closeBrackets!==!1&&i.push(f7n()),t.autocompletion!==!1&&i.push(nSt()),t.rectangularSelection!==!1&&i.push(o8n()),s!==!1&&i.push(u8n()),t.highlightActiveLine!==!1&&i.push(Jzn()),t.highlightSelectionMatches!==!1&&i.push(qVn()),t.tabSize&&typeof t.tabSize=="number"&&i.push(CI.of(" ".repeat(t.tabSize))),i.concat([_I.of(a.flat())]).filter(Boolean)};const THn="#e5c07b",R9e="#e06c75",jHn="#56b6c2",NHn="#ffffff",t9="#abb2bf",_ve="#7d8799",IHn="#61afef",AHn="#98c379",P9e="#d19a66",RHn="#c678dd",PHn="#21252b",$9e="#2c313a",M9e="#282c34",vte="#353a42",$Hn="#3E4451",D9e="#528bff",MHn=$t.theme({"&":{color:t9,backgroundColor:M9e},".cm-content":{caretColor:D9e},".cm-cursor, .cm-dropCursor":{borderLeftColor:D9e},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:$Hn},".cm-panels":{backgroundColor:PHn,color:t9},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:"1px solid #457dff"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:"#6199ff2f"},".cm-activeLine":{backgroundColor:"#6699ff0b"},".cm-selectionMatch":{backgroundColor:"#aafe661a"},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bad0f847"},".cm-gutters":{backgroundColor:M9e,color:_ve,border:"none"},".cm-activeLineGutter":{backgroundColor:$9e},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:vte},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:vte,borderBottomColor:vte},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:$9e,color:t9}}},{dark:!0}),DHn=Yg.define([{tag:de.keyword,color:RHn},{tag:[de.name,de.deleted,de.character,de.propertyName,de.macroName],color:R9e},{tag:[de.function(de.variableName),de.labelName],color:IHn},{tag:[de.color,de.constant(de.name),de.standard(de.name)],color:P9e},{tag:[de.definition(de.name),de.separator],color:t9},{tag:[de.typeName,de.className,de.number,de.changed,de.annotation,de.modifier,de.self,de.namespace],color:THn},{tag:[de.operator,de.operatorKeyword,de.url,de.escape,de.regexp,de.link,de.special(de.string)],color:jHn},{tag:[de.meta,de.comment],color:_ve},{tag:de.strong,fontWeight:"bold"},{tag:de.emphasis,fontStyle:"italic"},{tag:de.strikethrough,textDecoration:"line-through"},{tag:de.link,color:_ve,textDecoration:"underline"},{tag:de.heading,fontWeight:"bold",color:R9e},{tag:[de.atom,de.bool,de.special(de.variableName)],color:P9e},{tag:[de.processingInstruction,de.string,de.inserted],color:AHn},{tag:de.invalid,color:NHn}]),LHn=[MHn,lS(DHn)];var FHn=$t.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),zHn=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,v=[];switch(s&&v.unshift(_I.of([LVn])),m&&(typeof m=="boolean"?v.unshift(A9e()):v.unshift(A9e(m))),p&&v.unshift(r8n(p)),d){case"light":v.push(FHn);break;case"dark":v.push(LHn);break;case"none":break;default:v.push(d);break}return i===!1&&v.push($t.editable.of(!1)),c&&v.push(gs.readOnly.of(!0)),[...v]},BHn=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 UHn{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 L9e{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 yte=null,qHn=()=>typeof window>"u"?new L9e:(yte||(yte=new L9e),yte),VHn=$t.theme({"& .cm-scroller":{height:"100% !important"}}),F9e=null,bte=null;function HHn(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===F9e||(F9e=i,bte=$t.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a}})),bte}var z9e=zy.define(),WHn=200,ZHn=[];function GHn(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?ZHn: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,v=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,T=C===void 0?null:C,E=e.placeholder,N=E===void 0?"":E,I=e.editable,A=I===void 0?!0:I,R=e.readOnly,L=R===void 0?!1:R,M=e.indentWithTab,F=M===void 0?!0:M,H=e.basicSetup,z=H===void 0?!0:H,q=e.root,V=e.initialState,D=g.useState(),G=D[0],U=D[1],P=g.useState(),B=P[0],Z=P[1],Y=g.useState(),te=Y[0],J=Y[1],ee=g.useState(()=>({current:null}))[0],re=g.useState(()=>({current:null}))[0],oe=HHn(h,v,b,S,_,T),X=$t.updateListener.of(fe=>{if(fe.docChanged&&typeof r=="function"&&!fe.transactions.some(pe=>pe.annotation(z9e))){ee.current?ee.current.reset():(ee.current=new UHn(()=>{if(re.current){var pe=re.current;re.current=null,pe()}ee.current=null},WHn),qHn().add(ee.current));var ce=fe.state.doc,xe=ce.toString();r(xe,fe)}s&&s(BHn(fe))}),ne=zHn({theme:f,editable:A,readOnly:L,placeholder:N,indentWithTab:F,basicSetup:z}),se=[X,...oe?[oe]:[],VHn,...ne];return i&&typeof i=="function"&&se.push($t.updateListener.of(i)),se=se.concat(c),g.useLayoutEffect(()=>{if(G&&!te){var fe={doc:t,selection:n,extensions:se},ce=V?gs.fromJSON(V.json,fe,V.fields):gs.create(fe);if(J(ce),!B){var xe=new $t({state:ce,parent:G,root:q});Z(xe),a&&a(xe,ce)}}return()=>{B&&(J(void 0),Z(void 0))}},[G,te]),g.useEffect(()=>{e.container&&U(e.container)},[e.container]),g.useEffect(()=>()=>{B&&(B.destroy(),Z(void 0)),ee.current&&(ee.current.cancel(),ee.current=null)},[B]),g.useEffect(()=>{u&&B&&B.focus()},[u,B]),g.useEffect(()=>{B&&B.dispatch({effects:vr.reconfigure.of(se)})},[f,c,h,v,b,S,_,T,N,A,L,F,z,r,i]),g.useEffect(()=>{if(t!==void 0){var fe=B?B.state.doc.toString():"";if(B&&t!==fe){var ce=ee.current&&!ee.current.isDone,xe=()=>{B&&t!==B.state.doc.toString()&&B.dispatch({changes:{from:0,to:B.state.doc.toString().length,insert:t||""},annotations:[z9e.of(!0)]})};ce?re.current=xe:xe()}}},[t,B]),{state:te,setState:J,view:B,setView:Z,container:G,setContainer:U}}var QHn=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],nd=g.forwardRef((e,t)=>{var n=e.className,r=e.value,s=r===void 0?"":r,a=e.selection,i=e.extensions,l=i===void 0?[]:i,c=e.onChange,u=e.onStatistics,d=e.onCreateEditor,f=e.onUpdate,p=e.autoFocus,h=e.theme,m=h===void 0?"light":h,v=e.height,y=e.minHeight,b=e.maxHeight,x=e.width,S=e.minWidth,k=e.maxWidth,_=e.basicSetup,C=e.placeholder,T=e.indentWithTab,E=e.editable,N=e.readOnly,I=e.root,A=e.initialState,R=vkt(e,QHn),L=g.useRef(null),M=GHn({root:I,value:s,autoFocus:p,theme:m,height:v,minHeight:y,maxHeight:b,width:x,minWidth:S,maxWidth:k,basicSetup:_,placeholder:C,indentWithTab:T,editable:E,readOnly:N,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),F=M.state,H=M.view,z=M.container,q=M.setContainer;g.useImperativeHandle(t,()=>({editor:L.current,state:F,view:H}),[L,z,F,H]);var V=g.useCallback(G=>{L.current=G,q(G)},[q]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var D=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",JO({ref:V,className:""+D+(n?" "+n:"")},R))});nd.displayName="CodeMirror";const YHn={js:"javascript",javascript:"javascript",mjs:"javascript",cjs:"javascript",node:"javascript",ts:"typescript",typescript:"typescript",mts:"typescript",cts:"typescript",tsx:"tsx",jsx:"jsx",json:"json",json5:"json",md:"markdown",markdown:"markdown",py:"python",python:"python",sh:"bash",bash:"bash",shell:"bash",zsh:"bash",yml:"yaml",yaml:"yaml",diff:"diff",patch:"diff",css:"css",scss:"css",html:"html",htm:"html",xml:"xml",svg:"xml",sql:"sql"};let xte=null;function KHn(){return xte||(xte=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Fa(()=>import("./core-YJJ4l2n4.js"),__vite__mapDeps([0,1,2]),import.meta.url),Fa(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[Fa(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Fa(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Fa(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Fa(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Fa(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Fa(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Fa(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Fa(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Fa(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Fa(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Fa(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Fa(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Fa(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Fa(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([4,5,6]),import.meta.url),Fa(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Fa(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),xte}async function XHn(e,t){const n=YHn[t?.toLowerCase()];if(!n)return null;const r=await KHn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function JHn(e){return new QO(Vke.define(e))}const uOt=[pg.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return Fa(()=>Promise.resolve().then(()=>wF),void 0,import.meta.url).then(e=>e.javascript())}}),pg.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return Fa(()=>Promise.resolve().then(()=>T9n),void 0,import.meta.url).then(e=>e.json())}}),pg.of({name:"JSX",extensions:["jsx"],load(){return Fa(()=>Promise.resolve().then(()=>wF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),pg.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return Fa(()=>Promise.resolve().then(()=>Sqn),void 0,import.meta.url).then(e=>e.markdown())}}),pg.of({name:"TSX",extensions:["tsx"],load(){return Fa(()=>Promise.resolve().then(()=>wF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),pg.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return Fa(()=>Promise.resolve().then(()=>wF),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),pg.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return Fa(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>JHn(e.shell))}})];function eWn(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 tWn(e){const t=eWn(e);return nSt({override:[nWn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function nWn(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 v=u.state.sliceDoc(p,p+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:p,insert:v},selection:{anchor:f+v.length}})}}));return{from:a,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const rWn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,sWn=Nn.mark({class:"cm-variable-highlight"}),B9e=new g1t({regexp:rWn,decoration:()=>sWn}),aWn=_o.fromClass(class{decorations;constructor(e){this.decorations=B9e.createDeco(e)}update(e){this.decorations=B9e.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),iWn=aWn;function oWn(){const e=TI({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:[de.className,de.propertyName],color:"var(--neutral6)"},{tag:de.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[de.heading1,de.heading2,de.heading3,de.heading4,de.heading5,de.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:de.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:de.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:de.link,color:"var(--accent3)",textDecoration:"underline"},{tag:de.url,color:"var(--accent3)"},{tag:de.monospace,color:"var(--neutral6)"},{tag:de.strikethrough,textDecoration:"line-through"},{tag:de.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=$t.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 lWn(){const e=$t.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=Yg.define([{tag:[de.comment,de.bracket],color:"var(--neutral2)"},{tag:[de.string,de.meta,de.regexp],color:"var(--accent1)"},{tag:[de.atom,de.bool,de.special(de.variableName)],color:"var(--accent6)"},{tag:[de.keyword,de.operator,de.tagName],color:"var(--accent2)"},{tag:[de.function(de.propertyName),de.propertyName],color:"var(--accent5)"},{tag:[de.definition(de.variableName),de.function(de.variableName),de.className,de.attributeName],color:"var(--accent3)"},{tag:[de.variableName,de.number],color:"var(--accent5)"},{tag:[de.name,de.quote],color:"var(--accent1)"},{tag:de.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[de.heading1,de.heading2,de.heading3,de.heading4,de.heading5,de.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[de.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[de.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:de.link,color:"var(--accent3)",textDecoration:"underline"},{tag:de.url,color:"var(--accent3)"},{tag:de.monospace,color:"var(--neutral6)"},{tag:de.strikethrough,textDecoration:"line-through"},{tag:[de.deleted],color:"var(--accent2)"},{tag:de.invalid,color:"var(--error)"},{tag:[de.standard(de.tagName)],color:"var(--accent1)"}]);return[e,lS(t)]}const r0=()=>{const e=rC().resolvedTheme==="dark";return g.useMemo(()=>e?oWn():lWn(),[e])},cWn=co(K("relative overflow-hidden font-mono outline-hidden focus-within:outline-hidden focus:outline-hidden","duration-normal transition-colors ease-out-custom"),{variants:{variant:{default:"rounded-md border border-border1 bg-surface3 p-1 focus-within:border-neutral6/20",embedded:"rounded-none border-none bg-transparent p-0"}},defaultVariants:{variant:"default"}}),uWn=ih.highest($t.editorAttributes.of({style:"outline: none"})),dWn=ih.highest($t.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),fWn=[uWn,dWn],Qr=g.forwardRef(({data:e,value:t,onChange:n,showCopyButton:r=!0,className:s,language:a="json",highlightVariables:i=!1,placeholder:l,schema:c,autoFocus:u,lineNumbers:d=!0,lineWrapping:f=!0,editable:p,variant:h,...m},v)=>{const y=r0(),b=e?JSON.stringify(e,null,2):t??"",x=g.useMemo(()=>{const S=[...fWn];return f&&S.push($t.lineWrapping),a==="json"?S.push(Fp):a==="markdown"&&S.push(vOe({base:XO,codeLanguages:uOt})),i&&a==="markdown"&&S.push(iWn),c&&a==="markdown"&&S.push(tWn(c)),p===!1&&S.push(gs.readOnly.of(!0)),S},[a,i,c,p,f]);return o.jsxs("div",{className:K(cWn({variant:h}),s),...m,children:[r&&o.jsx(ka,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(nd,{ref:v,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}})]})}),pWn=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},hWn=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=r0(),{settings:r,setSettings:s}=VH(),a=r?.tracingOptions,i=g.useMemo(()=>pWn(a),[a]),[l,c]=g.useState(()=>i),u=g.useRef(!1);g.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(ve,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),o.jsx(nd,{value:l,onChange:d,theme:n,extensions:[Fp],className:K("overflow-y-scroll bg-surface3 rounded-lg overflow-hidden p-3",e)}),o.jsx("div",{className:"flex items-center justify-end",children:o.jsx(le,{type:"button",onClick:f,children:"Save"})})]})},mWn=()=>{const[e,t]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx(le,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(We,{children:o.jsx(P0e,{})})})}),o.jsx(yn,{children:"Run Options"})]}),o.jsx(hr,{open:e,onOpenChange:t,children:o.jsxs(mr,{children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Run Options"}),o.jsx(Cs,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx(jr,{children:o.jsx(hWn,{onSaved:()=>t(!1)})})]})})]})};function gWn({status:e}){switch(e){case"running":return o.jsx(Ut,{});case"failed":return o.jsx(or,{className:"text-accent2"});case"canceled":return o.jsx($c,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(a1,{className:"text-neutral3"});case"suspended":return o.jsx(EV,{className:"text-accent3"});case"success":return o.jsx(qr,{className:"text-accent1"});default:return o.jsx(a1,{className:"text-neutral3"})}}function dOt({status:e}){return o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx(We,{"aria-label":e,className:"shrink-0",children:o.jsx(gWn,{status:e})})}),o.jsx(yn,{children:e})]})}var wte,U9e;function COe(){if(U9e)return wte;U9e=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([v,y]){d(v)&&f.setNode(v,y)}),Object.values(this._edgeObjs).forEach(function(v){f.hasNode(v.v)&&f.hasNode(v.w)&&f.setEdge(v,p.edge(v))});var h={};function m(v){var y=p.parent(v);return y===void 0||f.hasNode(y)?(h[v]=y,y):y in h?h[y]:m(y)}return this._isCompound&&f.nodes().forEach(v=>f.setParent(v,m(v))),f}setDefaultEdgeLabel(d){return this._defaultEdgeLabelFn=d,typeof d!="function"&&(this._defaultEdgeLabelFn=()=>d),this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(d,f){var p=this,h=arguments;return d.reduce(function(m,v){return h.length>1?p.setEdge(m,v,f):p.setEdge(m,v),v}),this}setEdge(){var d,f,p,h,m=!1,v=arguments[0];typeof v=="object"&&v!==null&&"v"in v?(d=v.v,f=v.w,p=v.name,arguments.length===2&&(h=arguments[1],m=!0)):(d=v,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 v=h;h=m,m=v}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 v=h;h=m,m=v}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 wte=r,wte}var Ste,q9e;function vWn(){return q9e||(q9e=1,Ste="2.2.4"),Ste}var kte,V9e;function yWn(){return V9e||(V9e=1,kte={Graph:COe(),version:vWn()}),kte}var Ote,H9e;function bWn(){if(H9e)return Ote;H9e=1;var e=COe();Ote={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 Ote}var _te,W9e;function xWn(){if(W9e)return _te;W9e=1,_te=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 _te}var Cte,Z9e;function fOt(){if(Z9e)return Cte;Z9e=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 Cte=e,Cte}var Ete,G9e;function pOt(){if(G9e)return Ete;G9e=1;var e=fOt();Ete=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,v=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<v.distance&&(v.distance=b,v.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 Ete}var Tte,Q9e;function wWn(){if(Q9e)return Tte;Q9e=1;var e=pOt();Tte=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return Tte}var jte,Y9e;function hOt(){if(Y9e)return jte;Y9e=1,jte=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 jte}var Nte,K9e;function SWn(){if(K9e)return Nte;K9e=1;var e=hOt();Nte=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return Nte}var Ite,X9e;function kWn(){if(X9e)return Ite;X9e=1,Ite=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],v=f[p],y=h.distance+m.distance;y<v.distance&&(v.distance=y,v.predecessor=m.predecessor)})})}),i}return Ite}var Ate,J9e;function mOt(){if(J9e)return Ate;J9e=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 Ate=e,e.CycleException=t,Ate}var Rte,e7e;function OWn(){if(e7e)return Rte;e7e=1;var e=mOt();Rte=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return Rte}var Pte,t7e;function gOt(){if(t7e)return Pte;t7e=1,Pte=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 Pte}var $te,n7e;function _Wn(){if(n7e)return $te;n7e=1;var e=gOt();$te=t;function t(n,r){return e(n,r,"post")}return $te}var Mte,r7e;function CWn(){if(r7e)return Mte;r7e=1;var e=gOt();Mte=t;function t(n,r){return e(n,r,"pre")}return Mte}var Dte,s7e;function EWn(){if(s7e)return Dte;s7e=1;var e=COe(),t=fOt();Dte=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 Dte}var Lte,a7e;function TWn(){return a7e||(a7e=1,Lte={components:xWn(),dijkstra:pOt(),dijkstraAll:wWn(),findCycles:SWn(),floydWarshall:kWn(),isAcyclic:OWn(),postorder:_Wn(),preorder:CWn(),prim:EWn(),tarjan:hOt(),topsort:mOt()}),Lte}var Fte,i7e;function Vg(){if(i7e)return Fte;i7e=1;var e=yWn();return Fte={Graph:e.Graph,json:bWn(),alg:TWn(),version:e.version},Fte}var zte,o7e;function jWn(){if(o7e)return zte;o7e=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 zte=e,zte}var Bte,l7e;function NWn(){if(l7e)return Bte;l7e=1;let e=Vg().Graph,t=jWn();Bte=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],v;for(;u.nodeCount();){for(;v=m.dequeue();)a(u,d,f,v);for(;v=h.dequeue();)a(u,d,f,v);if(u.nodeCount()){for(let y=d.length-2;y>0;--y)if(v=d[y].dequeue(),v){p=p.concat(a(u,d,f,v,!0));break}}}return p}function a(u,d,f,p,h){let m=h?[]:void 0;return u.inEdges(p.v).forEach(v=>{let y=u.edge(v),b=u.node(v.v);h&&m.push({v:v.v,w:v.w}),b.out-=y,l(d,f,b)}),u.outEdges(p.v).forEach(v=>{let y=u.edge(v),b=v.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),v=p+1;return f.nodes().forEach(y=>{l(m,v,f.node(y))}),{graph:f,buckets:m,zeroIdx:v}}function l(u,d,f){f.out?f.in?u[f.out-f.in+d].enqueue(f):u[u.length-1].enqueue(f):u[0].enqueue(f)}function c(u){const d=[];for(let f=0;f<u;f++)d.push(f);return d}return Bte}var Ute,c7e;function $l(){if(c7e)return Ute;c7e=1;let e=Vg().Graph;Ute={addBorderNode:d,addDummyNode:t,applyWithChunking:h,asNonCompoundGraph:r,buildLayerMatrix:l,intersectRect:i,mapValues:C,maxRank:m,normalizeRanks:c,notime:b,partition:v,pick:_,predecessorWeights:a,range:k,removeEmptyRanks:u,simplify:n,successorWeights:s,time:y,uniqueId:S,zipObject:T};function t(E,N,I,A){for(var R=A;E.hasNode(R);)R=S(A);return I.dummy=N,E.setNode(R,I),R}function n(E){let N=new e().setGraph(E.graph());return E.nodes().forEach(I=>N.setNode(I,E.node(I))),E.edges().forEach(I=>{let A=N.edge(I.v,I.w)||{weight:0,minlen:1},R=E.edge(I);N.setEdge(I.v,I.w,{weight:A.weight+R.weight,minlen:Math.max(A.minlen,R.minlen)})}),N}function r(E){let N=new e({multigraph:E.isMultigraph()}).setGraph(E.graph());return E.nodes().forEach(I=>{E.children(I).length||N.setNode(I,E.node(I))}),E.edges().forEach(I=>{N.setEdge(I,E.edge(I))}),N}function s(E){let N=E.nodes().map(I=>{let A={};return E.outEdges(I).forEach(R=>{A[R.w]=(A[R.w]||0)+E.edge(R).weight}),A});return T(E.nodes(),N)}function a(E){let N=E.nodes().map(I=>{let A={};return E.inEdges(I).forEach(R=>{A[R.v]=(A[R.v]||0)+E.edge(R).weight}),A});return T(E.nodes(),N)}function i(E,N){let I=E.x,A=E.y,R=N.x-I,L=N.y-A,M=E.width/2,F=E.height/2;if(!R&&!L)throw new Error("Not possible to find intersection inside of the rectangle");let H,z;return Math.abs(L)*M>Math.abs(R)*F?(L<0&&(F=-F),H=F*R/L,z=F):(R<0&&(M=-M),H=M,z=M*L/R),{x:I+H,y:A+z}}function l(E){let N=k(m(E)+1).map(()=>[]);return E.nodes().forEach(I=>{let A=E.node(I),R=A.rank;R!==void 0&&(N[R][A.order]=I)}),N}function c(E){let N=E.nodes().map(A=>{let R=E.node(A).rank;return R===void 0?Number.MAX_VALUE:R}),I=h(Math.min,N);E.nodes().forEach(A=>{let R=E.node(A);Object.hasOwn(R,"rank")&&(R.rank-=I)})}function u(E){let N=E.nodes().map(M=>E.node(M).rank),I=h(Math.min,N),A=[];E.nodes().forEach(M=>{let F=E.node(M).rank-I;A[F]||(A[F]=[]),A[F].push(M)});let R=0,L=E.graph().nodeRankFactor;Array.from(A).forEach((M,F)=>{M===void 0&&F%L!==0?--R:M!==void 0&&R&&M.forEach(H=>E.node(H).rank+=R)})}function d(E,N,I,A){let R={width:0,height:0};return arguments.length>=4&&(R.rank=I,R.order=A),t(E,"border",R,N)}function f(E,N=p){const I=[];for(let A=0;A<E.length;A+=N){const R=E.slice(A,A+N);I.push(R)}return I}const p=65535;function h(E,N){if(N.length>p){const I=f(N);return E.apply(null,I.map(A=>E.apply(null,A)))}else return E.apply(null,N)}function m(E){const I=E.nodes().map(A=>{let R=E.node(A).rank;return R===void 0?Number.MIN_VALUE:R});return h(Math.max,I)}function v(E,N){let I={lhs:[],rhs:[]};return E.forEach(A=>{N(A)?I.lhs.push(A):I.rhs.push(A)}),I}function y(E,N){let I=Date.now();try{return N()}finally{console.log(E+" time: "+(Date.now()-I)+"ms")}}function b(E,N){return N()}let x=0;function S(E){var N=++x;return E+(""+N)}function k(E,N,I=1){N==null&&(N=E,E=0);let A=L=>L<N;I<0&&(A=L=>N<L);const R=[];for(let L=E;A(L);L+=I)R.push(L);return R}function _(E,N){const I={};for(const A of N)E[A]!==void 0&&(I[A]=E[A]);return I}function C(E,N){let I=N;return typeof N=="string"&&(I=A=>A[N]),Object.entries(E).reduce((A,[R,L])=>(A[R]=I(L,R),A),{})}function T(E,N){return E.reduce((I,A,R)=>(I[A]=N[R],I),{})}return Ute}var qte,u7e;function IWn(){if(u7e)return qte;u7e=1;let e=NWn(),t=$l().uniqueId;qte={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 qte}var Vte,d7e;function AWn(){if(d7e)return Vte;d7e=1;let e=$l();Vte={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,v;for(v=0,++l;l<u;++v,++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),v===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 Vte}var Hte,f7e;function nU(){if(f7e)return Hte;f7e=1;const{applyWithChunking:e}=$l();Hte={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 Hte}var Wte,p7e;function vOt(){if(p7e)return Wte;p7e=1;var e=Vg().Graph,t=nU().slack;Wte=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 Wte}var Zte,h7e;function RWn(){if(h7e)return Zte;h7e=1;var e=vOt(),t=nU().slack,n=nU().longestPath,r=Vg().alg.preorder,s=Vg().alg.postorder,a=$l().simplify;Zte=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,T=!0,E=S.edge(k,C),N=0;return E||(T=!1,E=S.edge(C,k)),N=E.weight,S.nodeEdges(k).forEach(I=>{var A=I.v===k,R=A?I.w:I.v;if(R!==C){var L=A===T,M=S.edge(I).weight;if(N+=L?M:-M,y(x,k,R)){var F=x.edge(k,R).cutvalue;N+=L?-F:F}}}),N}function d(x,S){arguments.length<2&&(S=x.nodes()[0]),f(x,{},1,S)}function f(x,S,k,_,C){var T=k,E=x.node(_);return S[_]=!0,x.neighbors(_).forEach(N=>{Object.hasOwn(S,N)||(k=f(x,S,k,N,_))}),E.low=T,E.lim=k++,C?E.parent=C:delete E.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 T=x.node(_),E=x.node(C),N=T,I=!1;T.lim>E.lim&&(N=E,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,T=k.w;x.removeEdge(C,T),x.setEdge(_.v,_.w,{}),d(x),l(x,S),v(x,S)}function v(x,S){var k=x.nodes().find(C=>!S.node(C).parent),_=r(x,k);_=_.slice(1),_.forEach(C=>{var T=x.node(C).parent,E=S.edge(C,T),N=!1;E||(E=S.edge(T,C),N=!0),S.node(C).rank=S.node(T).rank+(N?E.minlen:-E.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 Zte}var Gte,m7e;function PWn(){if(m7e)return Gte;m7e=1;var e=nU(),t=e.longestPath,n=vOt(),r=RWn();Gte=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 Gte}var Qte,g7e;function $Wn(){if(g7e)return Qte;g7e=1,Qte=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 Qte}var Yte,v7e;function MWn(){if(v7e)return Yte;v7e=1;let e=$l();Yte={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"),v=e.addBorderNode(i,"_bb"),y=i.node(p);i.setParent(m,p),y.borderTop=m,i.setParent(v,p),y.borderBottom=v,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,v,{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 Yte}var Kte,y7e;function DWn(){if(y7e)return Kte;y7e=1;let e=$l();Kte=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 Kte}var Xte,b7e;function LWn(){if(b7e)return Xte;b7e=1,Xte={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 Xte}var Jte,x7e;function FWn(){if(x7e)return Jte;x7e=1;let e=$l();Jte=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 Jte}var ene,w7e;function zWn(){if(w7e)return ene;w7e=1;let e=$l().zipObject;ene=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 ene}var tne,S7e;function BWn(){if(S7e)return tne;S7e=1,tne=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 tne}var nne,k7e;function UWn(){if(k7e)return nne;k7e=1;let e=$l();nne=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 nne}var rne,O7e;function qWn(){if(O7e)return rne;O7e=1;let e=$l();rne=t;function t(s,a){let i=e.partition(s,m=>Object.hasOwn(m,"barycenter")),l=i.lhs,c=i.rhs.sort((m,v)=>v.i-m.i),u=[],d=0,f=0,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 rne}var sne,_7e;function VWn(){if(_7e)return sne;_7e=1;let e=BWn(),t=UWn(),n=qWn();sne=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 v=e(i,d);v.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(v,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 sne}var ane,C7e;function HWn(){if(C7e)return ane;C7e=1;let e=Vg().Graph,t=$l();ane=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,v=u.edge(m,d),y=v!==void 0?v.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 ane}var ine,E7e;function WWn(){if(E7e)return ine;E7e=1,ine=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 ine}var one,T7e;function ZWn(){if(T7e)return one;T7e=1;let e=FWn(),t=zWn(),n=VWn(),r=HWn(),s=WWn(),a=Vg().Graph,i=$l();one=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"),v=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:v,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,v=(y,b)=>{m.has(y)||m.set(y,[]),m.get(y).push(b)};for(const y of f.nodes()){const b=f.node(y);if(typeof b.rank=="number"&&v(b.rank,y),typeof b.minRank=="number"&&typeof b.maxRank=="number")for(let x=b.minRank;x<=b.maxRank;x++)x!==b.rank&&v(x,y)}return 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 v=m.graph().root,y=n(m,v,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,v)=>f.node(m).order=v))}return one}var lne,j7e;function GWn(){if(j7e)return lne;j7e=1;let e=Vg().Graph,t=$l();lne={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,T=0,E=k.length,N=_[_.length-1];return _.forEach((I,A)=>{let R=s(y,I),L=R?y.node(R).order:E;(R||I===N)&&(_.slice(T,A+1).forEach(M=>{y.predecessors(M).forEach(F=>{let H=y.node(F),z=H.order;(z<C||L<z)&&!(H.dummy&&y.node(M).dummy)&&a(x,F,M)})}),T=A+1,C=L)}),_}return b.length&&b.reduce(S),x}function r(y,b){let x={};function S(_,C,T,E,N){let I;t.range(C,T).forEach(A=>{I=_[A],y.node(I).dummy&&y.predecessors(I).forEach(R=>{let L=y.node(R);L.dummy&&(L.order<E||L.order>N)&&a(x,R,I)})})}function k(_,C){let T=-1,E,N=0;return C.forEach((I,A)=>{if(y.node(I).dummy==="border"){let R=y.predecessors(I);R.length&&(E=y.node(R[0]).order,S(C,N,A,T,E),N=A,T=E)}S(C,N,C.length,E,_.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(T=>{T.forEach((E,N)=>{k[E]=E,_[E]=E,C[E]=N})}),b.forEach(T=>{let E=-1;T.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 M=I[R];_[N]===N&&E<C[M]&&!i(x,N,M)&&(_[M]=N,_[N]=k[N]=k[M],E=C[M])}}})}),{root:k,align:_}}function c(y,b,x,S,k){let _={},C=u(y,b,x,k),T=k?"borderLeft":"borderRight";function E(A,R){let L=C.nodes(),M=L.pop(),F={};for(;M;)F[M]?A(M):(F[M]=!0,L.push(M),L=L.concat(R(M))),M=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((M,F)=>Math.min(M,_[F.w]-C.edge(F)),Number.POSITIVE_INFINITY),L=y.node(A);R!==Number.POSITIVE_INFINITY&&L.borderType!==T&&(_[A]=Math.max(_[A],R))}return E(N,C.predecessors.bind(C)),E(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(T=>{let E;T.forEach(N=>{let I=x[N];if(k.setNode(I),E){var A=x[E],R=k.edge(A,I);k.setEdge(A,I,Math.max(C(y,N,E),R||0))}E=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(([T,E])=>{let N=v(y,T)/2;k=Math.max(E+N,k),_=Math.min(E-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 T=_+C,E=y[T];if(E===b)return;let N=Object.values(E),I=S-t.applyWithChunking(Math.min,N);C!=="l"&&(I=k-t.applyWithChunking(Math.max,N)),I&&(y[T]=t.mapValues(E,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(T=>{T==="r"&&(k=k.map(A=>Object.values(A).reverse()));let E=(C==="u"?y.predecessors:y.successors).bind(y),N=l(y,k,x,E),I=c(y,k,N.root,N.align,T==="r");T==="r"&&(I=t.mapValues(I,A=>-A)),S[C+T]=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),T=S.node(_),E=0,N;if(E+=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&&(E+=x?N:-N),N=0,E+=(C.dummy?b:y)/2,E+=(T.dummy?b:y)/2,E+=T.width/2,Object.hasOwn(T,"labelpos"))switch(T.labelpos.toLowerCase()){case"l":N=T.width/2;break;case"r":N=-T.width/2;break}return N&&(E+=x?N:-N),N=0,E}}function v(y,b){return y.node(b).width}return lne}var cne,N7e;function QWn(){if(N7e)return cne;N7e=1;let e=$l(),t=GWn().positionX;cne=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 cne}var une,I7e;function YWn(){if(I7e)return une;I7e=1;let e=IWn(),t=AWn(),n=PWn(),r=$l().normalizeRanks,s=$Wn(),a=$l().removeEmptyRanks,i=MWn(),l=DWn(),c=LWn(),u=ZWn(),d=QWn(),f=$l(),p=Vg().Graph;une=h;function h(P,B){let Z=B&&B.debugTiming?f.time:f.notime;Z("layout",()=>{let Y=Z(" buildLayoutGraph",()=>E(P));Z(" runLayout",()=>m(Y,Z,B)),Z(" updateInputGraph",()=>v(P,Y))})}function m(P,B,Z){B(" makeSpaceForEdgeLabels",()=>N(P)),B(" removeSelfEdges",()=>q(P)),B(" acyclic",()=>e.run(P)),B(" nestingGraph.run",()=>i.run(P)),B(" rank",()=>n(f.asNonCompoundGraph(P))),B(" injectEdgeLabelProxies",()=>I(P)),B(" removeEmptyRanks",()=>a(P)),B(" nestingGraph.cleanup",()=>i.cleanup(P)),B(" normalizeRanks",()=>r(P)),B(" assignRankMinMax",()=>A(P)),B(" removeEdgeLabelProxies",()=>R(P)),B(" normalize.run",()=>t.run(P)),B(" parentDummyChains",()=>s(P)),B(" addBorderSegments",()=>l(P)),B(" order",()=>u(P,Z)),B(" insertSelfEdges",()=>V(P)),B(" adjustCoordinateSystem",()=>c.adjust(P)),B(" position",()=>d(P)),B(" positionSelfEdges",()=>D(P)),B(" removeBorderNodes",()=>z(P)),B(" normalize.undo",()=>t.undo(P)),B(" fixupEdgeLabelCoords",()=>F(P)),B(" undoCoordinateSystem",()=>c.undo(P)),B(" translateGraph",()=>L(P)),B(" assignNodeIntersects",()=>M(P)),B(" reversePoints",()=>H(P)),B(" acyclic.undo",()=>e.undo(P))}function v(P,B){P.nodes().forEach(Z=>{let Y=P.node(Z),te=B.node(Z);Y&&(Y.x=te.x,Y.y=te.y,Y.rank=te.rank,B.children(Z).length&&(Y.width=te.width,Y.height=te.height))}),P.edges().forEach(Z=>{let Y=P.edge(Z),te=B.edge(Z);Y.points=te.points,Object.hasOwn(te,"x")&&(Y.x=te.x,Y.y=te.y)}),P.graph().width=B.graph().width,P.graph().height=B.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"},T=["labelpos"];function E(P){let B=new p({multigraph:!0,compound:!0}),Z=U(P.graph());return B.setGraph(Object.assign({},b,G(Z,y),f.pick(Z,x))),P.nodes().forEach(Y=>{let te=U(P.node(Y));const J=G(te,S);Object.keys(k).forEach(ee=>{J[ee]===void 0&&(J[ee]=k[ee])}),B.setNode(Y,J),B.setParent(Y,P.parent(Y))}),P.edges().forEach(Y=>{let te=U(P.edge(Y));B.setEdge(Y,Object.assign({},C,G(te,_),f.pick(te,T)))}),B}function N(P){let B=P.graph();B.ranksep/=2,P.edges().forEach(Z=>{let Y=P.edge(Z);Y.minlen*=2,Y.labelpos.toLowerCase()!=="c"&&(B.rankdir==="TB"||B.rankdir==="BT"?Y.width+=Y.labeloffset:Y.height+=Y.labeloffset)})}function I(P){P.edges().forEach(B=>{let Z=P.edge(B);if(Z.width&&Z.height){let Y=P.node(B.v),J={rank:(P.node(B.w).rank-Y.rank)/2+Y.rank,e:B};f.addDummyNode(P,"edge-proxy",J,"_ep")}})}function A(P){let B=0;P.nodes().forEach(Z=>{let Y=P.node(Z);Y.borderTop&&(Y.minRank=P.node(Y.borderTop).rank,Y.maxRank=P.node(Y.borderBottom).rank,B=Math.max(B,Y.maxRank))}),P.graph().maxRank=B}function R(P){P.nodes().forEach(B=>{let Z=P.node(B);Z.dummy==="edge-proxy"&&(P.edge(Z.e).labelRank=Z.rank,P.removeNode(B))})}function L(P){let B=Number.POSITIVE_INFINITY,Z=0,Y=Number.POSITIVE_INFINITY,te=0,J=P.graph(),ee=J.marginx||0,re=J.marginy||0;function oe(X){let ne=X.x,se=X.y,fe=X.width,ce=X.height;B=Math.min(B,ne-fe/2),Z=Math.max(Z,ne+fe/2),Y=Math.min(Y,se-ce/2),te=Math.max(te,se+ce/2)}P.nodes().forEach(X=>oe(P.node(X))),P.edges().forEach(X=>{let ne=P.edge(X);Object.hasOwn(ne,"x")&&oe(ne)}),B-=ee,Y-=re,P.nodes().forEach(X=>{let ne=P.node(X);ne.x-=B,ne.y-=Y}),P.edges().forEach(X=>{let ne=P.edge(X);ne.points.forEach(se=>{se.x-=B,se.y-=Y}),Object.hasOwn(ne,"x")&&(ne.x-=B),Object.hasOwn(ne,"y")&&(ne.y-=Y)}),J.width=Z-B+ee,J.height=te-Y+re}function M(P){P.edges().forEach(B=>{let Z=P.edge(B),Y=P.node(B.v),te=P.node(B.w),J,ee;Z.points?(J=Z.points[0],ee=Z.points[Z.points.length-1]):(Z.points=[],J=te,ee=Y),Z.points.unshift(f.intersectRect(Y,J)),Z.points.push(f.intersectRect(te,ee))})}function F(P){P.edges().forEach(B=>{let Z=P.edge(B);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(P){P.edges().forEach(B=>{let Z=P.edge(B);Z.reversed&&Z.points.reverse()})}function z(P){P.nodes().forEach(B=>{if(P.children(B).length){let Z=P.node(B),Y=P.node(Z.borderTop),te=P.node(Z.borderBottom),J=P.node(Z.borderLeft[Z.borderLeft.length-1]),ee=P.node(Z.borderRight[Z.borderRight.length-1]);Z.width=Math.abs(ee.x-J.x),Z.height=Math.abs(te.y-Y.y),Z.x=J.x+Z.width/2,Z.y=Y.y+Z.height/2}}),P.nodes().forEach(B=>{P.node(B).dummy==="border"&&P.removeNode(B)})}function q(P){P.edges().forEach(B=>{if(B.v===B.w){var Z=P.node(B.v);Z.selfEdges||(Z.selfEdges=[]),Z.selfEdges.push({e:B,label:P.edge(B)}),P.removeEdge(B)}})}function V(P){var B=f.buildLayerMatrix(P);B.forEach(Z=>{var Y=0;Z.forEach((te,J)=>{var ee=P.node(te);ee.order=J+Y,(ee.selfEdges||[]).forEach(re=>{f.addDummyNode(P,"selfedge",{width:re.label.width,height:re.label.height,rank:ee.rank,order:J+ ++Y,e:re.e,label:re.label},"_se")}),delete ee.selfEdges})})}function D(P){P.nodes().forEach(B=>{var Z=P.node(B);if(Z.dummy==="selfedge"){var Y=P.node(Z.e.v),te=Y.x+Y.width/2,J=Y.y,ee=Z.x-te,re=Y.height/2;P.setEdge(Z.e,Z.label),P.removeNode(B),Z.label.points=[{x:te+2*ee/3,y:J-re},{x:te+5*ee/6,y:J-re},{x:te+ee,y:J},{x:te+5*ee/6,y:J+re},{x:te+2*ee/3,y:J+re}],Z.label.x=Z.x,Z.label.y=Z.y}})}function G(P,B){return f.mapValues(f.pick(P,B),Number)}function U(P){var B={};return P&&Object.entries(P).forEach(([Z,Y])=>{typeof Z=="string"&&(Z=Z.toLowerCase()),B[Z]=Y}),B}return une}var dne,A7e;function KWn(){if(A7e)return dne;A7e=1;let e=$l(),t=Vg().Graph;dne={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 dne}var fne,R7e;function XWn(){return R7e||(R7e=1,fne="1.1.8"),fne}var pne,P7e;function JWn(){return P7e||(P7e=1,pne={graphlib:Vg(),layout:YWn(),debug:KWn(),util:{time:$l().time,notime:$l().notime},version:XWn()}),pne}var eZn=JWn();const $7e=Vl(eZn);function Gl(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=Gl(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var tZn={value:()=>{}};function bW(){for(var e=0,t=arguments.length,n={},r;e<t;++e){if(!(r=arguments[e]+"")||r in n||/[\s.]/.test(r))throw new Error("illegal type: "+r);n[r]=[]}return new n9(n)}function n9(e){this._=e}function nZn(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",s=n.indexOf(".");if(s>=0&&(r=n.slice(s+1),n=n.slice(0,s)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}n9.prototype=bW.prototype={constructor:n9,on:function(e,t){var n=this._,r=nZn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=rZn(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]=M7e(n[s],e.name,t);else if(t==null)for(s in n)n[s]=M7e(n[s],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new n9(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),r=0,s,a;r<s;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(a=this._[e],r=0,s=a.length;r<s;++r)a[r].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],s=0,a=r.length;s<a;++s)r[s].value.apply(t,n)}};function rZn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function M7e(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=tZn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Cve="http://www.w3.org/1999/xhtml";const D7e={svg:"http://www.w3.org/2000/svg",xhtml:Cve,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function xW(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),D7e.hasOwnProperty(t)?{space:D7e[t],local:e}:e}function sZn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Cve&&t.documentElement.namespaceURI===Cve?t.createElement(e):t.createElementNS(n,e)}}function aZn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function yOt(e){var t=xW(e);return(t.local?aZn:sZn)(t)}function iZn(){}function EOe(e){return e==null?iZn:function(){return this.querySelector(e)}}function oZn(e){typeof e!="function"&&(e=EOe(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 eh(r,this._parents)}function lZn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function cZn(){return[]}function bOt(e){return e==null?cZn:function(){return this.querySelectorAll(e)}}function uZn(e){return function(){return lZn(e.apply(this,arguments))}}function dZn(e){typeof e=="function"?e=uZn(e):e=bOt(e);for(var t=this._groups,n=t.length,r=[],s=[],a=0;a<n;++a)for(var i=t[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&(r.push(e.call(c,c.__data__,u,i)),s.push(c));return new eh(r,s)}function xOt(e){return function(){return this.matches(e)}}function wOt(e){return function(t){return t.matches(e)}}var fZn=Array.prototype.find;function pZn(e){return function(){return fZn.call(this.children,e)}}function hZn(){return this.firstElementChild}function mZn(e){return this.select(e==null?hZn:pZn(typeof e=="function"?e:wOt(e)))}var gZn=Array.prototype.filter;function vZn(){return Array.from(this.children)}function yZn(e){return function(){return gZn.call(this.children,e)}}function bZn(e){return this.selectAll(e==null?vZn:yZn(typeof e=="function"?e:wOt(e)))}function xZn(e){typeof e!="function"&&(e=xOt(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 eh(r,this._parents)}function SOt(e){return new Array(e.length)}function wZn(){return new eh(this._enter||this._groups.map(SOt),this._parents)}function rU(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}rU.prototype={constructor:rU,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}};function SZn(e){return function(){return e}}function kZn(e,t,n,r,s,a){for(var i=0,l,c=t.length,u=a.length;i<u;++i)(l=t[i])?(l.__data__=a[i],r[i]=l):n[i]=new rU(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function OZn(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 rU(e,a[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(p[l])===c&&(s[l]=c)}function _Zn(e){return e.__data__}function CZn(e,t){if(!arguments.length)return Array.from(this,_Zn);var n=t?OZn:kZn,r=this._parents,s=this._groups;typeof e!="function"&&(e=SZn(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=EZn(e.call(d,d&&d.__data__,u,r)),m=h.length,v=l[u]=new Array(m),y=i[u]=new Array(m),b=c[u]=new Array(p);n(d,f,v,y,b,h,t);for(var x=0,S=0,k,_;x<m;++x)if(k=v[x]){for(x>=S&&(S=x+1);!(_=y[S])&&++S<m;);k._next=_||null}}return i=new eh(i,r),i._enter=l,i._exit=c,i}function EZn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function TZn(){return new eh(this._exit||this._groups.map(SOt),this._parents)}function jZn(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 NZn(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 eh(l,this._parents)}function IZn(){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 AZn(e){e||(e=RZn);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 eh(s,this._parents).order()}function RZn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function PZn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function $Zn(){return Array.from(this)}function MZn(){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 DZn(){let e=0;for(const t of this)++e;return e}function LZn(){return!this.node()}function FZn(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 zZn(e){return function(){this.removeAttribute(e)}}function BZn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function UZn(e,t){return function(){this.setAttribute(e,t)}}function qZn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function VZn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function HZn(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 WZn(e,t){var n=xW(e);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((t==null?n.local?BZn:zZn:typeof t=="function"?n.local?HZn:VZn:n.local?qZn:UZn)(n,t))}function kOt(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function ZZn(e){return function(){this.style.removeProperty(e)}}function GZn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function QZn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function YZn(e,t,n){return arguments.length>1?this.each((t==null?ZZn:typeof t=="function"?QZn:GZn)(e,t,n??"")):iN(this.node(),e)}function iN(e,t){return e.style.getPropertyValue(t)||kOt(e).getComputedStyle(e,null).getPropertyValue(t)}function KZn(e){return function(){delete this[e]}}function XZn(e,t){return function(){this[e]=t}}function JZn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function eGn(e,t){return arguments.length>1?this.each((t==null?KZn:typeof t=="function"?JZn:XZn)(e,t)):this.node()[e]}function OOt(e){return e.trim().split(/^|\s+/)}function TOe(e){return e.classList||new _Ot(e)}function _Ot(e){this._node=e,this._names=OOt(e.getAttribute("class")||"")}_Ot.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 COt(e,t){for(var n=TOe(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function EOt(e,t){for(var n=TOe(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function tGn(e){return function(){COt(this,e)}}function nGn(e){return function(){EOt(this,e)}}function rGn(e,t){return function(){(t.apply(this,arguments)?COt:EOt)(this,e)}}function sGn(e,t){var n=OOt(e+"");if(arguments.length<2){for(var r=TOe(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?rGn:t?tGn:nGn)(n,t))}function aGn(){this.textContent=""}function iGn(e){return function(){this.textContent=e}}function oGn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function lGn(e){return arguments.length?this.each(e==null?aGn:(typeof e=="function"?oGn:iGn)(e)):this.node().textContent}function cGn(){this.innerHTML=""}function uGn(e){return function(){this.innerHTML=e}}function dGn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function fGn(e){return arguments.length?this.each(e==null?cGn:(typeof e=="function"?dGn:uGn)(e)):this.node().innerHTML}function pGn(){this.nextSibling&&this.parentNode.appendChild(this)}function hGn(){return this.each(pGn)}function mGn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function gGn(){return this.each(mGn)}function vGn(e){var t=typeof e=="function"?e:yOt(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function yGn(){return null}function bGn(e,t){var n=typeof e=="function"?e:yOt(e),r=t==null?yGn:typeof t=="function"?t:EOe(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function xGn(){var e=this.parentNode;e&&e.removeChild(this)}function wGn(){return this.each(xGn)}function SGn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function kGn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function OGn(e){return this.select(e?kGn:SGn)}function _Gn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function CGn(e){return function(t){e.call(this,t,this.__data__)}}function EGn(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 TGn(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 jGn(e,t,n){return function(){var r=this.__on,s,a=CGn(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 NGn(e,t,n){var r=EGn(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?jGn:TGn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function TOt(e,t,n){var r=kOt(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 IGn(e,t){return function(){return TOt(this,e,t)}}function AGn(e,t){return function(){return TOt(this,e,t.apply(this,arguments))}}function RGn(e,t){return this.each((typeof t=="function"?AGn:IGn)(e,t))}function*PGn(){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 jOt=[null];function eh(e,t){this._groups=e,this._parents=t}function a4(){return new eh([[document.documentElement]],jOt)}function $Gn(){return this}eh.prototype=a4.prototype={constructor:eh,select:oZn,selectAll:dZn,selectChild:mZn,selectChildren:bZn,filter:xZn,data:CZn,enter:wZn,exit:TZn,join:jZn,merge:NZn,selection:$Gn,order:IZn,sort:AZn,call:PZn,nodes:$Zn,node:MZn,size:DZn,empty:LZn,each:FZn,attr:WZn,style:YZn,property:eGn,classed:sGn,text:lGn,html:fGn,raise:hGn,lower:gGn,append:vGn,insert:bGn,remove:wGn,clone:OGn,datum:_Gn,on:NGn,dispatch:RGn,[Symbol.iterator]:PGn};function Tp(e){return typeof e=="string"?new eh([[document.querySelector(e)]],[document.documentElement]):new eh([[e]],jOt)}function MGn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function hg(e,t){if(e=MGn(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 DGn={passive:!1},FM={capture:!0,passive:!1};function hne(e){e.stopImmediatePropagation()}function cj(e){e.preventDefault(),e.stopImmediatePropagation()}function NOt(e){var t=e.document.documentElement,n=Tp(e).on("dragstart.drag",cj,FM);"onselectstart"in t?n.on("selectstart.drag",cj,FM):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function IOt(e,t){var n=e.document.documentElement,r=Tp(e).on("dragstart.drag",null);t&&(r.on("click.drag",cj,FM),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 CF=e=>()=>e;function Eve(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}})}Eve.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function LGn(e){return!e.ctrlKey&&!e.button}function FGn(){return this.parentNode}function zGn(e,t){return t??{x:e.x,y:e.y}}function BGn(){return navigator.maxTouchPoints||"ontouchstart"in this}function AOt(){var e=LGn,t=FGn,n=zGn,r=BGn,s={},a=bW("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,DGn).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&&(Tp(k.view).on("mousemove.drag",m,FM).on("mouseup.drag",v,FM),NOt(k.view),hne(k),u=!1,l=k.clientX,c=k.clientY,C("start",k))}}function m(k){if(cj(k),!u){var _=k.clientX-l,C=k.clientY-c;u=_*_+C*C>f}s.mouse("drag",k)}function v(k){Tp(k.view).on("mousemove.drag mouseup.drag",null),IOt(k.view,u),cj(k),s.mouse("end",k)}function y(k,_){if(e.call(this,k,_)){var C=k.changedTouches,T=t.call(this,k,_),E=C.length,N,I;for(N=0;N<E;++N)(I=S(this,T,k,_,C[N].identifier,C[N]))&&(hne(k),I("start",k,C[N]))}}function b(k){var _=k.changedTouches,C=_.length,T,E;for(T=0;T<C;++T)(E=s[_[T].identifier])&&(cj(k),E("drag",k,_[T]))}function x(k){var _=k.changedTouches,C=_.length,T,E;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),T=0;T<C;++T)(E=s[_[T].identifier])&&(hne(k),E("end",k,_[T]))}function S(k,_,C,T,E,N){var I=a.copy(),A=hg(N||C,_),R,L,M;if((M=n.call(k,new Eve("beforestart",{sourceEvent:C,target:p,identifier:E,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),T))!=null)return R=M.x-A[0]||0,L=M.y-A[1]||0,function F(H,z,q){var V=A,D;switch(H){case"start":s[E]=F,D=i++;break;case"end":delete s[E],--i;case"drag":A=hg(q||z,_),D=i;break}I.call(H,k,new Eve(H,{sourceEvent:z,subject:M,target:p,identifier:E,active:D,x:A[0]+R,y:A[1]+L,dx:A[0]-V[0],dy:A[1]-V[1],dispatch:I}),T)}}return p.filter=function(k){return arguments.length?(e=typeof k=="function"?k:CF(!!k),p):e},p.container=function(k){return arguments.length?(t=typeof k=="function"?k:CF(k),p):t},p.subject=function(k){return arguments.length?(n=typeof k=="function"?k:CF(k),p):n},p.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:CF(!!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 jOe(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function ROt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function i4(){}var zM=.7,sU=1/zM,uj="\\s*([+-]?\\d+)\\s*",BM="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",uy="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",UGn=/^#([0-9a-f]{3,8})$/,qGn=new RegExp(`^rgb\\(${uj},${uj},${uj}\\)$`),VGn=new RegExp(`^rgb\\(${uy},${uy},${uy}\\)$`),HGn=new RegExp(`^rgba\\(${uj},${uj},${uj},${BM}\\)$`),WGn=new RegExp(`^rgba\\(${uy},${uy},${uy},${BM}\\)$`),ZGn=new RegExp(`^hsl\\(${BM},${uy},${uy}\\)$`),GGn=new RegExp(`^hsla\\(${BM},${uy},${uy},${BM}\\)$`),L7e={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};jOe(i4,e_,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:F7e,formatHex:F7e,formatHex8:QGn,formatHsl:YGn,formatRgb:z7e,toString:z7e});function F7e(){return this.rgb().formatHex()}function QGn(){return this.rgb().formatHex8()}function YGn(){return POt(this).formatHsl()}function z7e(){return this.rgb().formatRgb()}function e_(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=UGn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?B7e(t):n===3?new Tf(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=qGn.exec(e))?new Tf(t[1],t[2],t[3],1):(t=VGn.exec(e))?new Tf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=HGn.exec(e))?EF(t[1],t[2],t[3],t[4]):(t=WGn.exec(e))?EF(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=ZGn.exec(e))?V7e(t[1],t[2]/100,t[3]/100,1):(t=GGn.exec(e))?V7e(t[1],t[2]/100,t[3]/100,t[4]):L7e.hasOwnProperty(e)?B7e(L7e[e]):e==="transparent"?new Tf(NaN,NaN,NaN,0):null}function B7e(e){return new Tf(e>>16&255,e>>8&255,e&255,1)}function EF(e,t,n,r){return r<=0&&(e=t=n=NaN),new Tf(e,t,n,r)}function KGn(e){return e instanceof i4||(e=e_(e)),e?(e=e.rgb(),new Tf(e.r,e.g,e.b,e.opacity)):new Tf}function Tve(e,t,n,r){return arguments.length===1?KGn(e):new Tf(e,t,n,r??1)}function Tf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}jOe(Tf,Tve,ROt(i4,{brighter(e){return e=e==null?sU:Math.pow(sU,e),new Tf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?zM:Math.pow(zM,e),new Tf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Tf(lO(this.r),lO(this.g),lO(this.b),aU(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:U7e,formatHex:U7e,formatHex8:XGn,formatRgb:q7e,toString:q7e}));function U7e(){return`#${Bk(this.r)}${Bk(this.g)}${Bk(this.b)}`}function XGn(){return`#${Bk(this.r)}${Bk(this.g)}${Bk(this.b)}${Bk((isNaN(this.opacity)?1:this.opacity)*255)}`}function q7e(){const e=aU(this.opacity);return`${e===1?"rgb(":"rgba("}${lO(this.r)}, ${lO(this.g)}, ${lO(this.b)}${e===1?")":`, ${e})`}`}function aU(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function lO(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Bk(e){return e=lO(e),(e<16?"0":"")+e.toString(16)}function V7e(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new wg(e,t,n,r)}function POt(e){if(e instanceof wg)return new wg(e.h,e.s,e.l,e.opacity);if(e instanceof i4||(e=e_(e)),!e)return new wg;if(e instanceof wg)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 wg(i,l,c,e.opacity)}function JGn(e,t,n,r){return arguments.length===1?POt(e):new wg(e,t,n,r??1)}function wg(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}jOe(wg,JGn,ROt(i4,{brighter(e){return e=e==null?sU:Math.pow(sU,e),new wg(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?zM:Math.pow(zM,e),new wg(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 Tf(mne(e>=240?e-240:e+120,s,r),mne(e,s,r),mne(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new wg(H7e(this.h),TF(this.s),TF(this.l),aU(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=aU(this.opacity);return`${e===1?"hsl(":"hsla("}${H7e(this.h)}, ${TF(this.s)*100}%, ${TF(this.l)*100}%${e===1?")":`, ${e})`}`}}));function H7e(e){return e=(e||0)%360,e<0?e+360:e}function TF(e){return Math.max(0,Math.min(1,e||0))}function mne(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 NOe=e=>()=>e;function eQn(e,t){return function(n){return e+n*t}}function tQn(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 nQn(e){return(e=+e)==1?$Ot:function(t,n){return n-t?tQn(t,n,e):NOe(isNaN(t)?n:t)}}function $Ot(e,t){var n=t-e;return n?eQn(e,n):NOe(isNaN(e)?t:e)}const iU=(function e(t){var n=nQn(t);function r(s,a){var i=n((s=Tve(s)).r,(a=Tve(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=$Ot(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 rQn(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 sQn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function aQn(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]=gx(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 iQn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function gg(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function oQn(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]=gx(e[s],t[s]):r[s]=t[s];return function(a){for(s in n)r[s]=n[s](a);return r}}var jve=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,gne=new RegExp(jve.source,"g");function lQn(e){return function(){return e}}function cQn(e){return function(t){return e(t)+""}}function MOt(e,t){var n=jve.lastIndex=gne.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=jve.exec(e))&&(s=gne.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:gg(r,s)})),n=gne.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?cQn(c[0].x):lQn(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 gx(e,t){var n=typeof t,r;return t==null||n==="boolean"?NOe(t):(n==="number"?gg:n==="string"?(r=e_(t))?(t=r,iU):MOt:t instanceof e_?iU:t instanceof Date?iQn:sQn(t)?rQn:Array.isArray(t)?aQn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?oQn:gg)(e,t)}function IOe(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var W7e=180/Math.PI,Nve={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function DOt(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)*W7e,skewX:Math.atan(c)*W7e,scaleX:i,scaleY:l}}var jF;function uQn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Nve:DOt(t.a,t.b,t.c,t.d,t.e,t.f)}function dQn(e){return e==null||(jF||(jF=document.createElementNS("http://www.w3.org/2000/svg","g")),jF.setAttribute("transform",e),!(e=jF.transform.baseVal.consolidate()))?Nve:(e=e.matrix,DOt(e.a,e.b,e.c,e.d,e.e,e.f))}function LOt(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 v=h.push("translate(",null,t,null,n);m.push({i:v-4,x:gg(u,f)},{i:v-2,x:gg(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:gg(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:gg(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,p,h,m){if(u!==f||d!==p){var v=h.push(s(h)+"scale(",null,",",null,")");m.push({i:v-4,x:gg(u,f)},{i:v-2,x:gg(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,v=p.length,y;++m<v;)f[(y=p[m]).i]=y.x(h);return f.join("")}}}var fQn=LOt(uQn,"px, ","px)","deg)"),pQn=LOt(dQn,", ",")",")"),hQn=1e-12;function Z7e(e){return((e=Math.exp(e))+1/e)/2}function mQn(e){return((e=Math.exp(e))-1/e)/2}function gQn(e){return((e=Math.exp(2*e))-1)/(e+1)}const r9=(function e(t,n,r){function s(a,i){var l=a[0],c=a[1],u=a[2],d=i[0],f=i[1],p=i[2],h=d-l,m=f-c,v=h*h+m*m,y,b;if(v<hQn)b=Math.log(p/u)/t,y=function(T){return[l+T*h,c+T*m,u*Math.exp(t*T*b)]};else{var x=Math.sqrt(v),S=(p*p-u*u+r*v)/(2*u*n*x),k=(p*p-u*u-r*v)/(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(T){var E=T*b,N=Z7e(_),I=u/(n*x)*(N*gQn(t*E+_)-mQn(_));return[l+I*h,c+I*m,u*N/Z7e(t*E+_)]}}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 vQn(e,t){t===void 0&&(t=e,e=gx);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 oN=0,t$=0,LR=0,FOt=1e3,oU,n$,lU=0,t_=0,wW=0,UM=typeof performance=="object"&&performance.now?performance:Date,zOt=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function AOe(){return t_||(zOt(yQn),t_=UM.now()+wW)}function yQn(){t_=0}function cU(){this._call=this._time=this._next=null}cU.prototype=BOt.prototype={constructor:cU,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?AOe():+n)+(t==null?0:+t),!this._next&&n$!==this&&(n$?n$._next=this:oU=this,n$=this),this._call=e,this._time=n,Ive()},stop:function(){this._call&&(this._call=null,this._time=1/0,Ive())}};function BOt(e,t,n){var r=new cU;return r.restart(e,t,n),r}function bQn(){AOe(),++oN;for(var e=oU,t;e;)(t=t_-e._time)>=0&&e._call.call(void 0,t),e=e._next;--oN}function G7e(){t_=(lU=UM.now())+wW,oN=t$=0;try{bQn()}finally{oN=0,wQn(),t_=0}}function xQn(){var e=UM.now(),t=e-lU;t>FOt&&(wW-=t,lU=e)}function wQn(){for(var e,t=oU,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:oU=n);n$=e,Ive(r)}function Ive(e){if(!oN){t$&&(t$=clearTimeout(t$));var t=e-t_;t>24?(e<1/0&&(t$=setTimeout(G7e,e-UM.now()-wW)),LR&&(LR=clearInterval(LR))):(LR||(lU=UM.now(),LR=setInterval(xQn,FOt)),oN=1,zOt(G7e))}}function Q7e(e,t,n){var r=new cU;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var SQn=bW("start","end","cancel","interrupt"),kQn=[],UOt=0,Y7e=1,Ave=2,s9=3,K7e=4,Rve=5,a9=6;function SW(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;OQn(e,n,{name:t,index:r,group:s,on:SQn,tween:kQn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:UOt})}function ROe(e,t){var n=Jg(e,t);if(n.state>UOt)throw new Error("too late; already scheduled");return n}function Uy(e,t){var n=Jg(e,t);if(n.state>s9)throw new Error("too late; already running");return n}function Jg(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function OQn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=BOt(a,0,n.time);function a(u){n.state=Y7e,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!==Y7e)return c();for(d in r)if(h=r[d],h.name===n.name){if(h.state===s9)return Q7e(i);h.state===K7e?(h.state=a9,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete r[d]):+d<t&&(h.state=a9,h.timer.stop(),h.on.call("cancel",e,e.__data__,h.index,h.group),delete r[d])}if(Q7e(function(){n.state===s9&&(n.state=K7e,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Ave,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Ave){for(n.state=s9,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=Rve,1),f=-1,p=s.length;++f<p;)s[f].call(e,d);n.state===Rve&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=a9,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function i9(e,t){var n=e.__transition,r,s,a=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((r=n[i]).name!==t){a=!1;continue}s=r.state>Ave&&r.state<Rve,r.state=a9,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function _Qn(e){return this.each(function(){i9(this,e)})}function CQn(e,t){var n,r;return function(){var s=Uy(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 EQn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=Uy(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 TQn(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Jg(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?CQn:EQn)(n,e,t))}function POe(e,t,n){var r=e._id;return e.each(function(){var s=Uy(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return Jg(s,r).value[t]}}function qOt(e,t){var n;return(typeof t=="number"?gg:t instanceof e_?iU:(n=e_(t))?(t=n,iU):MOt)(e,t)}function jQn(e){return function(){this.removeAttribute(e)}}function NQn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function IQn(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 AQn(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 RQn(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 PQn(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 $Qn(e,t){var n=xW(e),r=n==="transform"?pQn:qOt;return this.attrTween(e,typeof t=="function"?(n.local?PQn:RQn)(n,r,POe(this,"attr."+e,t)):t==null?(n.local?NQn:jQn)(n):(n.local?AQn:IQn)(n,r,t))}function MQn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function DQn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function LQn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&DQn(e,a)),n}return s._value=t,s}function FQn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&MQn(e,a)),n}return s._value=t,s}function zQn(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(t==null)return this.tween(n,null);if(typeof t!="function")throw new Error;var r=xW(e);return this.tween(n,(r.local?LQn:FQn)(r,t))}function BQn(e,t){return function(){ROe(this,e).delay=+t.apply(this,arguments)}}function UQn(e,t){return t=+t,function(){ROe(this,e).delay=t}}function qQn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?BQn:UQn)(t,e)):Jg(this.node(),t).delay}function VQn(e,t){return function(){Uy(this,e).duration=+t.apply(this,arguments)}}function HQn(e,t){return t=+t,function(){Uy(this,e).duration=t}}function WQn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?VQn:HQn)(t,e)):Jg(this.node(),t).duration}function ZQn(e,t){if(typeof t!="function")throw new Error;return function(){Uy(this,e).ease=t}}function GQn(e){var t=this._id;return arguments.length?this.each(ZQn(t,e)):Jg(this.node(),t).ease}function QQn(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Uy(this,e).ease=n}}function YQn(e){if(typeof e!="function")throw new Error;return this.each(QQn(this._id,e))}function KQn(e){typeof e!="function"&&(e=xOt(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 Mx(r,this._parents,this._name,this._id)}function XQn(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 Mx(i,this._parents,this._name,this._id)}function JQn(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 eYn(e,t,n){var r,s,a=JQn(t)?ROe:Uy;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function tYn(e,t){var n=this._id;return arguments.length<2?Jg(this.node(),n).on.on(e):this.each(eYn(n,e,t))}function nYn(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function rYn(){return this.on("end.remove",nYn(this._id))}function sYn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=EOe(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,SW(u[p],t,n,p,u,Jg(d,n)));return new Mx(a,this._parents,t,n)}function aYn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=bOt(e));for(var r=this._groups,s=r.length,a=[],i=[],l=0;l<s;++l)for(var c=r[l],u=c.length,d,f=0;f<u;++f)if(d=c[f]){for(var p=e.call(d,d.__data__,f,c),h,m=Jg(d,n),v=0,y=p.length;v<y;++v)(h=p[v])&&SW(h,t,n,v,p,m);a.push(p),i.push(d)}return new Mx(a,i,t,n)}var iYn=a4.prototype.constructor;function oYn(){return new iYn(this._groups,this._parents)}function lYn(e,t){var n,r,s;return function(){var a=iN(this,e),i=(this.style.removeProperty(e),iN(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function VOt(e){return function(){this.style.removeProperty(e)}}function cYn(e,t,n){var r,s=n+"",a;return function(){var i=iN(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function uYn(e,t,n){var r,s,a;return function(){var i=iN(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),iN(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function dYn(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=Uy(this,e),u=c.on,d=c.value[a]==null?l||(l=VOt(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function fYn(e,t,n){var r=(e+="")=="transform"?fQn:qOt;return t==null?this.styleTween(e,lYn(e,r)).on("end.style."+e,VOt(e)):typeof t=="function"?this.styleTween(e,uYn(e,r,POe(this,"style."+e,t))).each(dYn(this._id,e)):this.styleTween(e,cYn(e,r,t),n).on("end.style."+e,null)}function pYn(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function hYn(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&pYn(e,i,n)),r}return a._value=t,a}function mYn(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,hYn(e,t,n??""))}function gYn(e){return function(){this.textContent=e}}function vYn(e){return function(){var t=e(this);this.textContent=t??""}}function yYn(e){return this.tween("text",typeof e=="function"?vYn(POe(this,"text",e)):gYn(e==null?"":e+""))}function bYn(e){return function(t){this.textContent=e.call(this,t)}}function xYn(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&bYn(s)),t}return r._value=e,r}function wYn(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,xYn(e))}function SYn(){for(var e=this._name,t=this._id,n=HOt(),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=Jg(c,t);SW(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new Mx(r,this._parents,e,n)}function kYn(){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=Uy(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 OYn=0;function Mx(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function HOt(){return++OYn}var Ob=a4.prototype;Mx.prototype={constructor:Mx,select:sYn,selectAll:aYn,selectChild:Ob.selectChild,selectChildren:Ob.selectChildren,filter:KQn,merge:XQn,selection:oYn,transition:SYn,call:Ob.call,nodes:Ob.nodes,node:Ob.node,size:Ob.size,empty:Ob.empty,each:Ob.each,on:tYn,attr:$Qn,attrTween:zQn,style:fYn,styleTween:mYn,text:yYn,textTween:wYn,remove:rYn,tween:TQn,delay:qQn,duration:WQn,ease:GQn,easeVarying:YQn,end:kYn,[Symbol.iterator]:Ob[Symbol.iterator]};function _Yn(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var CYn={time:null,delay:0,duration:250,ease:_Yn};function EYn(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 TYn(e){var t,n;e instanceof Mx?(t=e._id,e=e._name):(t=HOt(),(n=CYn).time=AOe(),e=e==null?null:e+"");for(var r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&SW(c,e,t,u,i,n||EYn(c,t));return new Mx(r,this._parents,e,t)}a4.prototype.interrupt=_Qn;a4.prototype.transition=TYn;const NF=e=>()=>e;function jYn(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 sx(e,t,n){this.k=e,this.x=t,this.y=n}sx.prototype={constructor:sx,scale:function(e){return e===1?this:new sx(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new sx(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var kW=new sx(1,0,0);WOt.prototype=sx.prototype;function WOt(e){for(;!e.__zoom;)if(!(e=e.parentNode))return kW;return e.__zoom}function vne(e){e.stopImmediatePropagation()}function FR(e){e.preventDefault(),e.stopImmediatePropagation()}function NYn(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function IYn(){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 X7e(){return this.__zoom||kW}function AYn(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function RYn(){return navigator.maxTouchPoints||"ontouchstart"in this}function PYn(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 ZOt(){var e=NYn,t=IYn,n=PYn,r=AYn,s=RYn,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=r9,u=bW("start","zoom","end"),d,f,p,h=500,m=150,v=0,y=10;function b(M){M.property("__zoom",X7e).on("wheel.zoom",E,{passive:!1}).on("mousedown.zoom",N).on("dblclick.zoom",I).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",R).on("touchend.zoom touchcancel.zoom",L).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(M,F,H,z){var q=M.selection?M.selection():M;q.property("__zoom",X7e),M!==q?_(M,F,H,z):q.interrupt().each(function(){C(this,arguments).event(z).start().zoom(null,typeof F=="function"?F.apply(this,arguments):F).end()})},b.scaleBy=function(M,F,H,z){b.scaleTo(M,function(){var q=this.__zoom.k,V=typeof F=="function"?F.apply(this,arguments):F;return q*V},H,z)},b.scaleTo=function(M,F,H,z){b.transform(M,function(){var q=t.apply(this,arguments),V=this.__zoom,D=H==null?k(q):typeof H=="function"?H.apply(this,arguments):H,G=V.invert(D),U=typeof F=="function"?F.apply(this,arguments):F;return n(S(x(V,U),D,G),q,i)},H,z)},b.translateBy=function(M,F,H,z){b.transform(M,function(){return n(this.__zoom.translate(typeof F=="function"?F.apply(this,arguments):F,typeof H=="function"?H.apply(this,arguments):H),t.apply(this,arguments),i)},null,z)},b.translateTo=function(M,F,H,z,q){b.transform(M,function(){var V=t.apply(this,arguments),D=this.__zoom,G=z==null?k(V):typeof z=="function"?z.apply(this,arguments):z;return n(kW.translate(G[0],G[1]).scale(D.k).translate(typeof F=="function"?-F.apply(this,arguments):-F,typeof H=="function"?-H.apply(this,arguments):-H),V,i)},z,q)};function x(M,F){return F=Math.max(a[0],Math.min(a[1],F)),F===M.k?M:new sx(F,M.x,M.y)}function S(M,F,H){var z=F[0]-H[0]*M.k,q=F[1]-H[1]*M.k;return z===M.x&&q===M.y?M:new sx(M.k,z,q)}function k(M){return[(+M[0][0]+ +M[1][0])/2,(+M[0][1]+ +M[1][1])/2]}function _(M,F,H,z){M.on("start.zoom",function(){C(this,arguments).event(z).start()}).on("interrupt.zoom end.zoom",function(){C(this,arguments).event(z).end()}).tween("zoom",function(){var q=this,V=arguments,D=C(q,V).event(z),G=t.apply(q,V),U=H==null?k(G):typeof H=="function"?H.apply(q,V):H,P=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),B=q.__zoom,Z=typeof F=="function"?F.apply(q,V):F,Y=c(B.invert(U).concat(P/B.k),Z.invert(U).concat(P/Z.k));return function(te){if(te===1)te=Z;else{var J=Y(te),ee=P/J[2];te=new sx(ee,U[0]-J[0]*ee,U[1]-J[1]*ee)}D.zoom(null,te)}})}function C(M,F,H){return!H&&M.__zooming||new T(M,F)}function T(M,F){this.that=M,this.args=F,this.active=0,this.sourceEvent=null,this.extent=t.apply(M,F),this.taps=0}T.prototype={event:function(M){return M&&(this.sourceEvent=M),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(M,F){return this.mouse&&M!=="mouse"&&(this.mouse[1]=F.invert(this.mouse[0])),this.touch0&&M!=="touch"&&(this.touch0[1]=F.invert(this.touch0[0])),this.touch1&&M!=="touch"&&(this.touch1[1]=F.invert(this.touch1[0])),this.that.__zoom=F,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(M){var F=Tp(this.that).datum();u.call(M,this.that,new jYn(M,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),F)}};function E(M,...F){if(!e.apply(this,arguments))return;var H=C(this,F).event(M),z=this.__zoom,q=Math.max(a[0],Math.min(a[1],z.k*Math.pow(2,r.apply(this,arguments)))),V=hg(M);if(H.wheel)(H.mouse[0][0]!==V[0]||H.mouse[0][1]!==V[1])&&(H.mouse[1]=z.invert(H.mouse[0]=V)),clearTimeout(H.wheel);else{if(z.k===q)return;H.mouse=[V,z.invert(V)],i9(this),H.start()}FR(M),H.wheel=setTimeout(D,m),H.zoom("mouse",n(S(x(z,q),H.mouse[0],H.mouse[1]),H.extent,i));function D(){H.wheel=null,H.end()}}function N(M,...F){if(p||!e.apply(this,arguments))return;var H=M.currentTarget,z=C(this,F,!0).event(M),q=Tp(M.view).on("mousemove.zoom",U,!0).on("mouseup.zoom",P,!0),V=hg(M,H),D=M.clientX,G=M.clientY;NOt(M.view),vne(M),z.mouse=[V,this.__zoom.invert(V)],i9(this),z.start();function U(B){if(FR(B),!z.moved){var Z=B.clientX-D,Y=B.clientY-G;z.moved=Z*Z+Y*Y>v}z.event(B).zoom("mouse",n(S(z.that.__zoom,z.mouse[0]=hg(B,H),z.mouse[1]),z.extent,i))}function P(B){q.on("mousemove.zoom mouseup.zoom",null),IOt(B.view,z.moved),FR(B),z.event(B).end()}}function I(M,...F){if(e.apply(this,arguments)){var H=this.__zoom,z=hg(M.changedTouches?M.changedTouches[0]:M,this),q=H.invert(z),V=H.k*(M.shiftKey?.5:2),D=n(S(x(H,V),z,q),t.apply(this,F),i);FR(M),l>0?Tp(this).transition().duration(l).call(_,D,z,M):Tp(this).call(b.transform,D,z,M)}}function A(M,...F){if(e.apply(this,arguments)){var H=M.touches,z=H.length,q=C(this,F,M.changedTouches.length===z).event(M),V,D,G,U;for(vne(M),D=0;D<z;++D)G=H[D],U=hg(G,this),U=[U,this.__zoom.invert(U),G.identifier],q.touch0?!q.touch1&&q.touch0[2]!==U[2]&&(q.touch1=U,q.taps=0):(q.touch0=U,V=!0,q.taps=1+!!d);d&&(d=clearTimeout(d)),V&&(q.taps<2&&(f=U[0],d=setTimeout(function(){d=null},h)),i9(this),q.start())}}function R(M,...F){if(this.__zooming){var H=C(this,F).event(M),z=M.changedTouches,q=z.length,V,D,G,U;for(FR(M),V=0;V<q;++V)D=z[V],G=hg(D,this),H.touch0&&H.touch0[2]===D.identifier?H.touch0[0]=G:H.touch1&&H.touch1[2]===D.identifier&&(H.touch1[0]=G);if(D=H.that.__zoom,H.touch1){var P=H.touch0[0],B=H.touch0[1],Z=H.touch1[0],Y=H.touch1[1],te=(te=Z[0]-P[0])*te+(te=Z[1]-P[1])*te,J=(J=Y[0]-B[0])*J+(J=Y[1]-B[1])*J;D=x(D,Math.sqrt(te/J)),G=[(P[0]+Z[0])/2,(P[1]+Z[1])/2],U=[(B[0]+Y[0])/2,(B[1]+Y[1])/2]}else if(H.touch0)G=H.touch0[0],U=H.touch0[1];else return;H.zoom("touch",n(S(D,G,U),H.extent,i))}}function L(M,...F){if(this.__zooming){var H=C(this,F).event(M),z=M.changedTouches,q=z.length,V,D;for(vne(M),p&&clearTimeout(p),p=setTimeout(function(){p=null},h),V=0;V<q;++V)D=z[V],H.touch0&&H.touch0[2]===D.identifier?delete H.touch0:H.touch1&&H.touch1[2]===D.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&&(D=hg(D,this),Math.hypot(f[0]-D[0],f[1]-D[1])<y)){var G=Tp(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(M){return arguments.length?(r=typeof M=="function"?M:NF(+M),b):r},b.filter=function(M){return arguments.length?(e=typeof M=="function"?M:NF(!!M),b):e},b.touchable=function(M){return arguments.length?(s=typeof M=="function"?M:NF(!!M),b):s},b.extent=function(M){return arguments.length?(t=typeof M=="function"?M:NF([[+M[0][0],+M[0][1]],[+M[1][0],+M[1][1]]]),b):t},b.scaleExtent=function(M){return arguments.length?(a[0]=+M[0],a[1]=+M[1],b):[a[0],a[1]]},b.translateExtent=function(M){return arguments.length?(i[0][0]=+M[0][0],i[1][0]=+M[1][0],i[0][1]=+M[0][1],i[1][1]=+M[1][1],b):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},b.constrain=function(M){return arguments.length?(n=M,b):n},b.duration=function(M){return arguments.length?(l=+M,b):l},b.interpolate=function(M){return arguments.length?(c=M,b):c},b.on=function(){var M=u.on.apply(u,arguments);return M===u?b:M},b.clickDistance=function(M){return arguments.length?(v=(M=+M)*M,b):Math.sqrt(v)},b.tapDistance=function(M){return arguments.length?(y=+M,b):y},b}const ky={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."},qM=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],GOt=["Enter"," ","Escape"],QOt={"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 lN;(function(e){e.Strict="strict",e.Loose="loose"})(lN||(lN={}));var cO;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(cO||(cO={}));var VM;(function(e){e.Partial="partial",e.Full="full"})(VM||(VM={}));const YOt={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var kw;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(kw||(kw={}));var HM;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(HM||(HM={}));var nr;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(nr||(nr={}));const J7e={[nr.Left]:nr.Right,[nr.Right]:nr.Left,[nr.Top]:nr.Bottom,[nr.Bottom]:nr.Top};function KOt(e){return e===null?null:e?"valid":"invalid"}const XOt=e=>"id"in e&&"source"in e&&"target"in e,$Yn=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),$Oe=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),o4=(e,t=[0,0])=>{const{width:n,height:r}=s0(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},MYn=(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):$Oe(s)?s:t.nodeLookup.get(s.id));const l=i?uU(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return OW(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return _W(n)},l4=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},r=!1;return e.forEach(s=>{(t.filter===void 0||t.filter(s))&&(n=OW(n,uU(s)),r=!0)}),r?_W(n):{x:0,y:0,width:0,height:0}},MOe=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...u4(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,v=WM(l,uN(u)),y=(h??0)*(m??0),b=a&&v>0;(!u.internals.handleBounds||b||v>=y||u.dragging)&&c.push(u)}return c},DYn=(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 LYn(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 FYn({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=LYn(e,i),c=l4(l),u=DOe(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 JOt({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",ky.error005());else{const h=l.measured.width,m=l.measured.height;h&&m&&(f=[[c,u],[c+h,u+m]])}else l&&dN(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=dN(f)?n_(t,f,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&a?.("015",ky.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 zYn({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(v=>v.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=DYn(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 cN=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),n_=(e={x:0,y:0},t,n)=>({x:cN(e.x,t[0][0],t[1][0]-(n?.width??0)),y:cN(e.y,t[0][1],t[1][1]-(n?.height??0))});function e_t(e,t,n){const{width:r,height:s}=s0(n),{x:a,y:i}=n.internals.positionAbsolute;return n_(e,[[a,i],[a+r,i+s]],t)}const eBe=(e,t,n)=>e<t?cN(Math.abs(e-t),1,t)/t:e>n?-cN(Math.abs(e-n),1,t)/t:0,t_t=(e,t,n=15,r=40)=>{const s=eBe(e.x,r,t.width-r)*n,a=eBe(e.y,r,t.height-r)*n;return[s,a]},OW=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),Pve=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),_W=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),uN=(e,t=[0,0])=>{const{x:n,y:r}=$Oe(e)?e.internals.positionAbsolute:o4(e,t);return{x:n,y:r,width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}},uU=(e,t=[0,0])=>{const{x:n,y:r}=$Oe(e)?e.internals.positionAbsolute:o4(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)}},n_t=(e,t)=>_W(OW(Pve(e),Pve(t))),WM=(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)},tBe=e=>Eg(e.width)&&Eg(e.height)&&Eg(e.x)&&Eg(e.y),Eg=e=>!isNaN(e)&&isFinite(e),BYn=(e,t)=>{},c4=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),u4=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?c4(l,i):l},dU=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function xE(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 UYn(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=xE(e,n),s=xE(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=xE(e.top??e.y??0,n),s=xE(e.bottom??e.y??0,n),a=xE(e.left??e.x??0,t),i=xE(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 qYn(e,t,n,r,s,a){const{x:i,y:l}=dU(e,[t,n,r]),{x:c,y:u}=dU({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=s-c,f=a-u;return{left:Math.floor(i),top:Math.floor(l),right:Math.floor(d),bottom:Math.floor(f)}}const DOe=(e,t,n,r,s,a)=>{const i=UYn(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=cN(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,v=qYn(e,h,m,d,t,n),y={left:Math.min(v.left-i.left,0),top:Math.min(v.top-i.top,0),right:Math.min(v.right-i.right,0),bottom:Math.min(v.bottom-i.bottom,0)};return{x:h-y.left+y.right,y:m-y.top+y.bottom,zoom:d}},ZM=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function dN(e){return e!=null&&e!=="parent"}function s0(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function r_t(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function s_t(e,t={width:0,height:0},n,r,s){const a={...e},i=r.get(n);if(i){const l=i.origin||s;a.x+=i.internals.positionAbsolute.x-(t.width??0)*l[0],a.y+=i.internals.positionAbsolute.y-(t.height??0)*l[1]}return a}function nBe(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function VYn(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function HYn(e){return{...QOt,...e||{}}}function U$(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=Tg(e),l=u4({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?c4(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const LOe=e=>({width:e.offsetWidth,height:e.offsetHeight}),a_t=e=>e?.getRootNode?.()||window?.document,WYn=["INPUT","SELECT","TEXTAREA"];function i_t(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:WYn.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const o_t=e=>"clientX"in e,Tg=(e,t)=>{const n=o_t(e),r=n?e.clientX:e.touches?.[0].clientX,s=n?e.clientY:e.touches?.[0].clientY;return{x:r-(t?.left??0),y:s-(t?.top??0)}},rBe=(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,...LOe(i)}})};function l_t({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:s,sourceControlY:a,targetControlX:i,targetControlY:l}){const c=e*.125+s*.375+i*.375+n*.125,u=t*.125+a*.375+l*.375+r*.125,d=Math.abs(c-e),f=Math.abs(u-t);return[c,u,d,f]}function IF(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function sBe({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case nr.Left:return[t-IF(t-r,a),n];case nr.Right:return[t+IF(r-t,a),n];case nr.Top:return[t,n-IF(n-s,a)];case nr.Bottom:return[t,n+IF(s-n,a)]}}function FOe({sourceX:e,sourceY:t,sourcePosition:n=nr.Bottom,targetX:r,targetY:s,targetPosition:a=nr.Top,curvature:i=.25}){const[l,c]=sBe({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=sBe({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,p,h,m]=l_t({sourceX:e,sourceY:t,targetX:r,targetY:s,sourceControlX:l,sourceControlY:c,targetControlX:u,targetControlY:d});return[`M${e},${t} C${l},${c} ${u},${d} ${r},${s}`,f,p,h,m]}function c_t({sourceX:e,sourceY:t,targetX:n,targetY:r}){const s=Math.abs(n-e)/2,a=n<e?n+s:n-s,i=Math.abs(r-t)/2,l=r<t?r+i:r-i;return[a,l,s,i]}function ZYn({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 GYn({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=OW(uU(e),uU(t));a.x===a.x2&&(a.x2+=1),a.y===a.y2&&(a.y2+=1);const i={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:r/s[2]};return WM(i,_W(a))>0}const QYn=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,YYn=(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)),KYn=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||QYn;let s;return XOt(e)?s={...e}:s={...e,id:r(e)},YYn(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function u_t({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=c_t({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const aBe={[nr.Left]:{x:-1,y:0},[nr.Right]:{x:1,y:0},[nr.Top]:{x:0,y:-1},[nr.Bottom]:{x:0,y:1}},XYn=({source:e,sourcePosition:t=nr.Bottom,target:n})=>t===nr.Left||t===nr.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},iBe=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function JYn({source:e,sourcePosition:t=nr.Bottom,target:n,targetPosition:r=nr.Top,center:s,offset:a,stepPosition:i}){const l=aBe[t],c=aBe[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=XYn({source:u,sourcePosition:t,target:d}),p=f.x!==0?"x":"y",h=f[p];let m=[],v,y;const b={x:0,y:0},x={x:0,y:0},[,,S,k]=c_t({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[p]*c[p]===-1){p==="x"?(v=s.x??u.x+(d.x-u.x)*i,y=s.y??(u.y+d.y)/2):(v=s.x??(u.x+d.x)/2,y=s.y??u.y+(d.y-u.y)*i);const E=[{x:v,y:u.y},{x:v,y:d.y}],N=[{x:u.x,y},{x:d.x,y}];l[p]===h?m=p==="x"?E:N:m=p==="x"?N:E}else{const E=[{x:u.x,y:d.y}],N=[{x:d.x,y:u.y}];if(p==="x"?m=l.x===h?N:E:m=l.y===h?E:N,t===r){const M=Math.abs(e[p]-n[p]);if(M<=a){const F=Math.min(a-1,a-M);l[p]===h?b[p]=(u[p]>e[p]?-1:1)*F:x[p]=(d[p]>n[p]?-1:1)*F}}if(t!==r){const M=p==="x"?"y":"x",F=l[p]===c[M],H=u[M]>d[M],z=u[M]<d[M];(l[p]===1&&(!F&&H||F&&z)||l[p]!==1&&(!F&&z||F&&H))&&(m=p==="x"?E:N)}const I={x:u.x+b.x,y:u.y+b.y},A={x:d.x+x.x,y:d.y+x.y},R=Math.max(Math.abs(I.x-m[0].x),Math.abs(A.x-m[0].x)),L=Math.max(Math.abs(I.y-m[0].y),Math.abs(A.y-m[0].y));R>=L?(v=(I.x+A.x)/2,y=m[0].y):(v=m[0].x,y=(I.y+A.y)/2)}const _={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],v,y,S,k]}function eKn(e,t,n,r){const s=Math.min(iBe(e,t)/2,iBe(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 $ve({sourceX:e,sourceY:t,sourcePosition:n=nr.Bottom,targetX:r,targetY:s,targetPosition:a=nr.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,p,h,m,v]=JYn({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+=eKn(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,v]}function oBe(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function tKn(e){const{sourceNode:t,targetNode:n}=e;if(!oBe(t)||!oBe(n))return null;const r=t.internals.handleBounds||lBe(t.handles),s=n.internals.handleBounds||lBe(n.handles),a=cBe(r?.source??[],e.sourceHandle),i=cBe(e.connectionMode===lN.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!a||!i)return e.onError?.("008",ky.error008(a?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=a?.position||nr.Bottom,c=i?.position||nr.Top,u=r_(t,a,l),d=r_(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function lBe(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 r_(e,t,n=nr.Left,r=!1){const s=(t?.x??0)+e.internals.positionAbsolute.x,a=(t?.y??0)+e.internals.positionAbsolute.y,{width:i,height:l}=t??s0(e);if(r)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case nr.Top:return{x:s+i/2,y:a};case nr.Right:return{x:s+i,y:a+l/2};case nr.Bottom:return{x:s+i/2,y:a+l};case nr.Left:return{x:s,y:a+l/2}}}function cBe(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function Mve(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function nKn(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=Mve(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 d_t=1e3,rKn=10,zOe={nodeOrigin:[0,0],nodeExtent:qM,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},sKn={...zOe,checkEquality:!0};function BOe(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function aKn(e,t,n){const r=BOe(zOe,n);for(const s of e.values())if(s.parentId)qOe(s,e,t,r);else{const a=o4(s,r.nodeOrigin),i=dN(s.extent)?s.extent:r.nodeExtent,l=n_(a,i,s0(s));s.internals.positionAbsolute=l}}function iKn(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 UOe(e){return e==="manual"}function Dve(e,t,n,r={}){const s=BOe(sKn,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!UOe(s.zIndexMode)?d_t:0;let c=e.length>0,u=!1;t.clear(),n.clear();for(const d of e){let f=i.get(d.id);if(s.checkEquality&&d===f?.internals.userNode)t.set(d.id,f);else{const p=o4(d,s.nodeOrigin),h=dN(d.extent)?d.extent:s.nodeExtent,m=n_(p,h,s0(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:iKn(d,f),z:f_t(d,l,s.zIndexMode),userNode:d}},t.set(d.id,f)}(f.measured===void 0||f.measured.width===void 0||f.measured.height===void 0)&&!f.hidden&&(c=!1),d.parentId&&qOe(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function oKn(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 qOe(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=BOe(zOe,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}oKn(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*rKn),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!UOe(c)?d_t:0,{x:p,y:h,z:m}=lKn(e,d,i,l,f,c),{positionAbsolute:v}=e.internals,y=p!==v.x||h!==v.y;(y||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:p,y:h}:v,z:m}})}function f_t(e,t,n){const r=Eg(e.zIndex)?e.zIndex:0;return UOe(n)?r:r+(e.selected?t:0)}function lKn(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=s0(e),u=o4(e,n),d=dN(e.extent)?n_(u,e.extent,c):u;let f=n_({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=e_t(f,c,t));const p=f_t(e,s,a),h=t.internals.z??0;return{x:f.x,y:f.y,z:h>=p?h+1:p}}function VOe(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??uN(l),u=n_t(c,i.rect);a.set(i.parentId,{expandedRect:u,parent:l})}return a.size>0&&a.forEach(({expandedRect:i,parent:l},c)=>{const u=l.internals.positionAbsolute,d=s0(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)),v=Math.max(d.height,Math.round(i.height)),y=(m-d.width)*f[0],b=(v-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:v+(h?f[1]*h-b:0)}})}),s}function cKn(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 v=LOe(h.nodeElement),y=m.measured.width!==v.width||m.measured.height!==v.height;if(!!(v.width&&v.height&&(y||!m.internals.handleBounds||h.force))){const x=h.nodeElement.getBoundingClientRect(),S=dN(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=e_t(k,v,t.get(m.parentId)):S&&(k=n_(k,S,v));const _={...m,measured:v,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:rBe("source",h.nodeElement,x,f,m.id),target:rBe("target",h.nodeElement,x,f,m.id)}}};t.set(m.id,_),m.parentId&&qOe(_,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,y&&(u.push({id:m.id,type:"dimensions",dimensions:v}),m.expandParent&&m.parentId&&p.push({id:m.id,parentId:m.parentId,rect:uN(_,s)}))}}if(p.length>0){const h=VOe(p,t,n,s);u.push(...h)}return{changes:u,updatedInternals:c}}async function uKn({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 uBe(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 p_t(e,t,n){e.clear(),t.clear();for(const r of n){const{source:s,target:a,sourceHandle:i=null,targetHandle:l=null}=r,c={edgeId:r.id,source:s,target:a,sourceHandle:i,targetHandle:l},u=`${s}-${i}--${a}-${l}`,d=`${a}-${l}--${s}-${i}`;uBe("source",c,d,e,s,i),uBe("target",c,u,e,a,l),t.set(r.id,r)}}function h_t(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:h_t(n,t):!1}function dBe(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 dKn(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!h_t(i,e))&&(i.draggable||t&&typeof i.draggable>"u")){const l=e.get(a);l&&s.set(a,{id:a,position:l.position||{x:0,y:0},distance:{x:n.x-l.internals.positionAbsolute.x,y:n.y-l.internals.positionAbsolute.y},extent:l.extent,parentId:l.parentId,origin:l.origin,expandParent:l.expandParent,internals:{positionAbsolute:l.internals.positionAbsolute||{x:0,y:0}},measured:{width:l.measured.width??0,height:l.measured.height??0}})}return s}function yne({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 fKn({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=c4(a,t);return{x:i.x-a.x,y:i.y-a.y}}function pKn({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,v=null;function y({noDragClassName:x,handleSelector:S,domNode:k,isSelectable:_,nodeId:C,nodeClickDistance:T=0}){p=Tp(k);function E({x:R,y:L}){const{nodeLookup:M,nodeExtent:F,snapGrid:H,snapToGrid:z,nodeOrigin:q,onNodeDrag:V,onSelectionDrag:D,onError:G,updateNodePositions:U}=t();a={x:R,y:L};let P=!1;const B=l.size>1,Z=B&&F?Pve(l4(l)):null,Y=B&&z?fKn({dragItems:l,snapGrid:H,x:R,y:L}):null;for(const[te,J]of l){if(!M.has(te))continue;let ee={x:R-J.distance.x,y:L-J.distance.y};z&&(ee=Y?{x:Math.round(ee.x+Y.x),y:Math.round(ee.y+Y.y)}:c4(ee,H));let re=null;if(B&&F&&!J.extent&&Z){const{positionAbsolute:ne}=J.internals,se=ne.x-Z.x+F[0][0],fe=ne.x+J.measured.width-Z.x2+F[1][0],ce=ne.y-Z.y+F[0][1],xe=ne.y+J.measured.height-Z.y2+F[1][1];re=[[se,ce],[fe,xe]]}const{position:oe,positionAbsolute:X}=JOt({nodeId:te,nextPosition:ee,nodeLookup:M,nodeExtent:re||F,nodeOrigin:q,onError:G});P=P||J.position.x!==oe.x||J.position.y!==oe.y,J.position=oe,J.internals.positionAbsolute=X}if(m=m||P,!!P&&(U(l,!0),v&&(r||V||!C&&D))){const[te,J]=yne({nodeId:C,dragItems:l,nodeLookup:M});r?.(v,l,te,J),V?.(v,te,J),C||D?.(v,J)}}async function N(){if(!d)return;const{transform:R,panBy:L,autoPanSpeed:M,autoPanOnNodeDrag:F}=t();if(!F){c=!1,cancelAnimationFrame(i);return}const[H,z]=t_t(u,d,M);(H!==0||z!==0)&&(a.x=(a.x??0)-H/R[2],a.y=(a.y??0)-z/R[2],await L({x:H,y:z})&&E(a)),i=requestAnimationFrame(N)}function I(R){const{nodeLookup:L,multiSelectionActive:M,nodesDraggable:F,transform:H,snapGrid:z,snapToGrid:q,selectNodesOnDrag:V,onNodeDragStart:D,onSelectionDragStart:G,unselectNodesAndEdges:U}=t();f=!0,(!V||!_)&&!M&&C&&(L.get(C)?.selected||U()),_&&V&&C&&e?.(C);const P=U$(R.sourceEvent,{transform:H,snapGrid:z,snapToGrid:q,containerBounds:d});if(a=P,l=dKn(L,F,P,C),l.size>0&&(n||D||!C&&G)){const[B,Z]=yne({nodeId:C,dragItems:l,nodeLookup:L});n?.(R.sourceEvent,l,B,Z),D?.(R.sourceEvent,B,Z),C||G?.(R.sourceEvent,Z)}}const A=AOt().clickDistance(T).on("start",R=>{const{domNode:L,nodeDragThreshold:M,transform:F,snapGrid:H,snapToGrid:z}=t();d=L?.getBoundingClientRect()||null,h=!1,m=!1,v=R.sourceEvent,M===0&&I(R),a=U$(R.sourceEvent,{transform:F,snapGrid:H,snapToGrid:z,containerBounds:d}),u=Tg(R.sourceEvent,d)}).on("drag",R=>{const{autoPanOnNodeDrag:L,transform:M,snapGrid:F,snapToGrid:H,nodeDragThreshold:z,nodeLookup:q}=t(),V=U$(R.sourceEvent,{transform:M,snapGrid:F,snapToGrid:H,containerBounds:d});if(v=R.sourceEvent,(R.sourceEvent.type==="touchmove"&&R.sourceEvent.touches.length>1||C&&!q.has(C))&&(h=!0),!h){if(!c&&L&&f&&(c=!0,N()),!f){const D=Tg(R.sourceEvent,d),G=D.x-u.x,U=D.y-u.y;Math.sqrt(G*G+U*U)>z&&I(R)}(a.x!==V.xSnapped||a.y!==V.ySnapped)&&l&&f&&(u=Tg(R.sourceEvent,d),E(V))}}).on("end",R=>{if(!(!f||h)&&(c=!1,f=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:L,updateNodePositions:M,onNodeDragStop:F,onSelectionDragStop:H}=t();if(m&&(M(l,!1),m=!1),s||F||!C&&H){const[z,q]=yne({nodeId:C,dragItems:l,nodeLookup:L,dragging:!1});s?.(R.sourceEvent,l,z,q),F?.(R.sourceEvent,z,q),C||H?.(R.sourceEvent,q)}}}).filter(R=>{const L=R.target;return!R.button&&(!x||!dBe(L,`.${x}`,k))&&(!S||dBe(L,S,k))});p.call(A)}function b(){p?.on(".drag",null)}return{update:y,destroy:b}}function hKn(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())WM(s,uN(a))>0&&r.push(a);return r}const mKn=250;function gKn(e,t,n,r){let s=[],a=1/0;const i=hKn(e,n,t+mKn);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}=r_(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 m_t(e,t,n,r,s,a=!1){const i=r.get(e);if(!i)return null;const l=s==="strict"?i.internals.handleBounds?.[t]:[...i.internals.handleBounds?.source??[],...i.internals.handleBounds?.target??[]],c=(n?l?.find(u=>u.id===n):l?.[0])??null;return c&&a?{...c,...r_(i,c,c.position,!0)}:c}function g_t(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function vKn(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const v_t=()=>!0;function yKn(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:v,onConnectEnd:y,isValidConnection:b=v_t,onReconnectEnd:x,updateConnection:S,getTransform:k,getFromHandle:_,autoPanSpeed:C,dragThreshold:T=1,handleDomNode:E}){const N=a_t(e.target);let I=0,A;const{x:R,y:L}=Tg(e),M=g_t(a,E),F=l?.getBoundingClientRect();let H=!1;if(!F||!M)return;const z=m_t(s,M,r,c,t);if(!z)return;let q=Tg(e,F),V=!1,D=null,G=!1,U=null;function P(){if(!d||!F)return;const[oe,X]=t_t(q,F,C);p({x:oe,y:X}),I=requestAnimationFrame(P)}const B={...z,nodeId:s,type:M,position:z.position},Z=c.get(s);let te={inProgress:!0,isValid:null,from:r_(Z,B,nr.Left,!0),fromHandle:B,fromPosition:B.position,fromNode:Z,to:q,toHandle:null,toPosition:J7e[B.position],toNode:null,pointer:q};function J(){H=!0,S(te),m?.(e,{nodeId:s,handleId:r,handleType:M})}T===0&&J();function ee(oe){if(!H){const{x:xe,y:pe}=Tg(oe),we=xe-R,Ne=pe-L;if(!(we*we+Ne*Ne>T*T))return;J()}if(!_()||!B){re(oe);return}const X=k();q=Tg(oe,F),A=gKn(u4(q,X,!1,[1,1]),n,c,B),V||(P(),V=!0);const ne=y_t(oe,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});U=ne.handleDomNode,D=ne.connection,G=vKn(!!A,ne.isValid);const se=c.get(s),fe=se?r_(se,B,nr.Left,!0):te.from,ce={...te,from:fe,isValid:G,to:ne.toHandle&&G?dU({x:ne.toHandle.x,y:ne.toHandle.y},X):q,toHandle:ne.toHandle,toPosition:G&&ne.toHandle?ne.toHandle.position:J7e[B.position],toNode:ne.toHandle?c.get(ne.toHandle.nodeId):null,pointer:q};S(ce),te=ce}function re(oe){if(!("touches"in oe&&oe.touches.length>0)){if(H){(A||U)&&D&&G&&v?.(D);const{inProgress:X,...ne}=te,se={...ne,toPosition:te.toHandle?te.toPosition:null};y?.(oe,se),a&&x?.(oe,se)}h(),cancelAnimationFrame(I),V=!1,G=!1,D=null,U=null,N.removeEventListener("mousemove",ee),N.removeEventListener("mouseup",re),N.removeEventListener("touchmove",ee),N.removeEventListener("touchend",re)}}N.addEventListener("mousemove",ee),N.addEventListener("mouseup",re),N.addEventListener("touchmove",ee),N.addEventListener("touchend",re)}function y_t(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=v_t,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}=Tg(e),v=i.elementFromPoint(h,m),y=v?.classList.contains(`${l}-flow__handle`)?v:p,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){const x=g_t(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 T={source:f?S:r,sourceHandle:f?k:s,target:f?r:S,targetHandle:f?s:k};b.connection=T;const N=_&&C&&(n===lN.Strict?f&&x==="source"||!f&&x==="target":S!==r||k!==s);b.isValid=N&&u(T),b.toHandle=m_t(S,x,k,d,n,!0)}return b}const Lve={onPointerDown:yKn,isValid:y_t};function bKn({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Tp(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&&ZM()?10:1,C=-S.sourceEvent.deltaY*(S.sourceEvent.deltaMode===1?.05:S.sourceEvent.deltaMode?1:.002)*d,T=k[2]*Math.pow(2,C*_);t.scaleTo(T)};let v=[0,0];const y=S=>{(S.sourceEvent.type==="mousedown"||S.sourceEvent.type==="touchstart")&&(v=[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]-v[0],_[1]-v[1]];v=_;const T=r()*Math.max(k[2],Math.log(k[2]))*(h?-1:1),E={x:k[0]-C[0]*T,y:k[1]-C[1]*T},N=[[0,0],[c,u]];t.setViewportConstrained({x:E.x,y:E.y,zoom:k[2]},N,l)},x=ZOt().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:hg}}const CW=e=>({x:e.x,y:e.y,zoom:e.k}),bne=({x:e,y:t,zoom:n})=>kW.translate(e,t).scale(n),OT=(e,t)=>e.target.closest(`.${t}`),b_t=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),xKn=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,xne=(e,t=0,n=xKn,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},x_t=e=>{const t=e.ctrlKey&&ZM()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function wKn({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(OT(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=hg(d),b=x_t(d),x=f*Math.pow(2,b);r.scaleTo(n,x,y,d);return}const p=d.deltaMode===1?20:1;let h=s===cO.Vertical?0:d.deltaX*p,m=s===cO.Horizontal?0:d.deltaY*p;!ZM()&&d.shiftKey&&s!==cO.Vertical&&(h=d.deltaY*p,m=0),r.translateBy(n,-(h/f)*a,-(m/f)*a,{internal:!0});const v=CW(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(d,v),e.panScrollTimeout=setTimeout(()=>{u?.(d,v),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l?.(d,v))}}function SKn({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=OT(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function kKn({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=CW(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 OKn({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&b_t(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,CW(a.transform))}}function _Kn({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&b_t(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=CW(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function CKn({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"&&(OT(f,`${u}-flow__node`)||OT(f,`${u}-flow__edge`)))return!0;if(!r&&!p&&!s&&!a&&!n||i||d&&!m||OT(f,l)&&m||OT(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 v=Array.isArray(r)&&r.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||m)&&v}}function EKn({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=ZOt().scaleExtent([t,n]).translateExtent(r),p=Tp(e).call(f);x({x:s.x,y:s.y,zoom:cN(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const h=p.on("wheel.zoom"),m=p.on("dblclick.zoom");f.wheelDelta(x_t);function v(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?gx:r9).transform(xne(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:R,onPaneContextMenu:L,userSelectionActive:M,panOnScroll:F,panOnDrag:H,panOnScrollMode:z,panOnScrollSpeed:q,preventScrolling:V,zoomOnPinch:D,zoomOnScroll:G,zoomOnDoubleClick:U,zoomActivationKeyPressed:P,lib:B,onTransformChange:Z,connectionInProgress:Y,paneClickDistance:te,selectionOnDrag:J}){M&&!u.isZoomingOrPanning&&b();const ee=F&&!P&&!M;f.clickDistance(J?1/0:!Eg(te)||te<0?0:te);const re=ee?wKn({zoomPanValues:u,noWheelClassName:A,d3Selection:p,d3Zoom:f,panOnScrollMode:z,panOnScrollSpeed:q,zoomOnPinch:D,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):SKn({noWheelClassName:A,preventScrolling:V,d3ZoomHandler:h});if(p.on("wheel.zoom",re,{passive:!1}),!M){const X=kKn({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",X);const ne=OKn({zoomPanValues:u,panOnDrag:H,onPaneContextMenu:!!L,onPanZoom:a,onTransformChange:Z});f.on("zoom",ne);const se=_Kn({zoomPanValues:u,panOnDrag:H,panOnScroll:F,onPaneContextMenu:L,onPanZoomEnd:l,onDraggingChange:c});f.on("end",se)}const oe=CKn({zoomActivationKeyPressed:P,panOnDrag:H,zoomOnScroll:G,panOnScroll:F,zoomOnDoubleClick:U,zoomOnPinch:D,userSelectionActive:M,noPanClassName:R,noWheelClassName:A,lib:B,connectionInProgress:Y});f.filter(oe),U?p.on("dblclick.zoom",m):p.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,R,L){const M=bne(A),F=f?.constrain()(M,R,L);return F&&await v(F),new Promise(H=>H(F))}async function S(A,R){const L=bne(A);return await v(L,R),new Promise(M=>M(L))}function k(A){if(p){const R=bne(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?WOt(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"?gx:r9).scaleTo(xne(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function T(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?gx:r9).scaleBy(xne(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function E(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const R=!Eg(A)||A<0?0:A;f?.clickDistance(R)}return{update:y,destroy:b,setViewport:S,setViewportConstrained:x,getViewport:_,scaleTo:C,scaleBy:T,setScaleExtent:E,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var fN;(function(e){e.Line="line",e.Handle="handle"})(fN||(fN={}));function TKn({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 fBe(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 X0(e,t){return Math.max(0,t-e)}function J0(e,t){return Math.max(0,e-t)}function AF(e,t,n){return Math.max(0,t-e,e-n)}function pBe(e,t){return e?!t:t}function jKn(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:v,maxWidth:y,minHeight:b,maxHeight:x}=r,{x:S,y:k,width:_,height:C,aspectRatio:T}=e;let E=Math.floor(d?h-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=_+(c?-E:E),A=C+(u?-N:N),R=-a[0]*_,L=-a[1]*C;let M=AF(I,v,y),F=AF(A,b,x);if(i){let q=0,V=0;c&&E<0?q=X0(S+E+R,i[0][0]):!c&&E>0&&(q=J0(S+I+R,i[1][0])),u&&N<0?V=X0(k+N+L,i[0][1]):!u&&N>0&&(V=J0(k+A+L,i[1][1])),M=Math.max(M,q),F=Math.max(F,V)}if(l){let q=0,V=0;c&&E>0?q=J0(S+E,l[0][0]):!c&&E<0&&(q=X0(S+I,l[1][0])),u&&N>0?V=J0(k+N,l[0][1]):!u&&N<0&&(V=X0(k+A,l[1][1])),M=Math.max(M,q),F=Math.max(F,V)}if(s){if(d){const q=AF(I/T,b,x)*T;if(M=Math.max(M,q),i){let V=0;!c&&!u||c&&!u&&p?V=J0(k+L+I/T,i[1][1])*T:V=X0(k+L+(c?E:-E)/T,i[0][1])*T,M=Math.max(M,V)}if(l){let V=0;!c&&!u||c&&!u&&p?V=X0(k+I/T,l[1][1])*T:V=J0(k+(c?E:-E)/T,l[0][1])*T,M=Math.max(M,V)}}if(f){const q=AF(A*T,v,y)/T;if(F=Math.max(F,q),i){let V=0;!c&&!u||u&&!c&&p?V=J0(S+A*T+R,i[1][0])/T:V=X0(S+(u?N:-N)*T+R,i[0][0])/T,F=Math.max(F,V)}if(l){let V=0;!c&&!u||u&&!c&&p?V=X0(S+A*T,l[1][0])/T:V=J0(S+(u?N:-N)*T,l[0][0])/T,F=Math.max(F,V)}}}N=N+(N<0?F:-F),E=E+(E<0?M:-M),s&&(p?I>A*T?N=(pBe(c,u)?-E:E)/T:E=(pBe(c,u)?-N:N)*T:d?(N=E/T,u=c):(E=N*T,c=u));const H=c?S+E:S,z=u?k+N:k;return{width:_+(c?-E:E),height:C+(u?-N:N),x:a[0]*E*(c?-1:1)+H,y:a[1]*N*(u?-1:1)+z}}const w_t={width:0,height:0,x:0,y:0},NKn={...w_t,pointerX:0,pointerY:0,aspectRatio:1};function IKn(e){return[[0,0],[e.measured.width,e.measured.height]]}function AKn(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 RKn({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=Tp(e);let i={controlDirection:fBe("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:v,shouldResize:y}){let b={...w_t},x={...NKn};i={boundaries:d,resizeDirection:p,keepAspectRatio:f,controlDirection:fBe(u)};let S,k=null,_=[],C,T,E,N=!1;const I=AOt().on("start",A=>{const{nodeLookup:R,transform:L,snapGrid:M,snapToGrid:F,nodeOrigin:H,paneDomNode:z}=n();if(S=R.get(t),!S)return;k=z?.getBoundingClientRect()??null;const{xSnapped:q,ySnapped:V}=U$(A.sourceEvent,{transform:L,snapGrid:M,snapToGrid:F,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:q,pointerY:V,aspectRatio:b.width/b.height},C=void 0,S.parentId&&(S.extent==="parent"||S.expandParent)&&(C=R.get(S.parentId),T=C&&S.extent==="parent"?IKn(C):void 0),_=[],E=void 0;for(const[D,G]of R)if(G.parentId===t&&(_.push({id:D,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const U=AKn(G,S,G.origin??H);E?E=[[Math.min(U[0][0],E[0][0]),Math.min(U[0][1],E[0][1])],[Math.max(U[1][0],E[1][0]),Math.max(U[1][1],E[1][1])]]:E=U}h?.(A,{...b})}).on("drag",A=>{const{transform:R,snapGrid:L,snapToGrid:M,nodeOrigin:F}=n(),H=U$(A.sourceEvent,{transform:R,snapGrid:L,snapToGrid:M,containerBounds:k}),z=[];if(!S)return;const{x:q,y:V,width:D,height:G}=b,U={},P=S.origin??F,{width:B,height:Z,x:Y,y:te}=jKn(x,i.controlDirection,H,i.boundaries,i.keepAspectRatio,P,T,E),J=B!==D,ee=Z!==G,re=Y!==q&&J,oe=te!==V&ⅇif(!re&&!oe&&!J&&!ee)return;if((re||oe||P[0]===1||P[1]===1)&&(U.x=re?Y:b.x,U.y=oe?te:b.y,b.x=U.x,b.y=U.y,_.length>0)){const fe=Y-q,ce=te-V;for(const xe of _)xe.position={x:xe.position.x-fe+P[0]*(B-D),y:xe.position.y-ce+P[1]*(Z-G)},z.push(xe)}if((J||ee)&&(U.width=J&&(!i.resizeDirection||i.resizeDirection==="horizontal")?B:b.width,U.height=ee&&(!i.resizeDirection||i.resizeDirection==="vertical")?Z:b.height,b.width=U.width,b.height=U.height),C&&S.expandParent){const fe=P[0]*(U.width??0);U.x&&U.x<fe&&(b.x=fe,x.x=x.x-(U.x-fe));const ce=P[1]*(U.height??0);U.y&&U.y<ce&&(b.y=ce,x.y=x.y-(U.y-ce))}const X=TKn({width:b.width,prevWidth:D,height:b.height,prevHeight:G,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),ne={...b,direction:X};y?.(A,ne)!==!1&&(N=!0,m?.(A,ne),r(U,z))}).on("end",A=>{N&&(v?.(A,{...b}),s?.({...b}),N=!1)});a.call(I)}function c(){a.on(".drag",null)}return{update:l,destroy:c}}const PKn={},hBe=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:()=>{(PKn?"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},$Kn=e=>e?hBe(e):hBe,{useDebugValue:MKn}=Fe,{useSyncExternalStoreWithSelector:DKn}=sNn,LKn=e=>e;function S_t(e,t=LKn,n){const r=DKn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return MKn(r),r}const mBe=(e,t)=>{const n=$Kn(e),r=(s,a=t)=>S_t(n,s,a);return Object.assign(r,n),r},FKn=(e,t)=>e?mBe(e,t):mBe;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 EW=g.createContext(null),zKn=EW.Provider,k_t=ky.error001();function Ws(e,t){const n=g.useContext(EW);if(n===null)throw new Error(k_t);return S_t(n,e,t)}function To(){const e=g.useContext(EW);if(e===null)throw new Error(k_t);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const gBe={display:"none"},BKn={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},O_t="react-flow__node-desc",__t="react-flow__edge-desc",UKn="react-flow__aria-live",qKn=e=>e.ariaLiveMessage,VKn=e=>e.ariaLabelConfig;function HKn({rfId:e}){const t=Ws(qKn);return o.jsx("div",{id:`${UKn}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:BKn,children:t})}function WKn({rfId:e,disableKeyboardA11y:t}){const n=Ws(VKn);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${O_t}-${e}`,style:gBe,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${__t}-${e}`,style:gBe,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(HKn,{rfId:e})]})}const d4=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:Gl(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});d4.displayName="Panel";function ZKn({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(d4,{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 GKn=e=>{const t=[],n=[];for(const[,r]of e.nodeLookup)r.selected&&t.push(r.internals.userNode);for(const[,r]of e.edgeLookup)r.selected&&n.push(r);return{selectedNodes:t,selectedEdges:n}},RF=e=>e.id;function QKn(e,t){return io(e.selectedNodes.map(RF),t.selectedNodes.map(RF))&&io(e.selectedEdges.map(RF),t.selectedEdges.map(RF))}function YKn({onSelectionChange:e}){const t=To(),{selectedNodes:n,selectedEdges:r}=Ws(GKn,QKn);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const KKn=e=>!!e.onSelectionChangeHandlers;function XKn({onSelectionChange:e}){const t=Ws(KKn);return e||t?o.jsx(YKn,{onSelectionChange:e}):null}const Fve=typeof window<"u"?g.useLayoutEffect:g.useEffect,C_t=[0,0],JKn={x:0,y:0,zoom:1},eXn=["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"],vBe=[...eXn,"rfId"],tXn=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}),yBe={translateExtent:qM,nodeOrigin:C_t,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function nXn(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Ws(tXn,io),u=To();Fve(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=yBe,l()}),[]);const d=g.useRef(yBe);return Fve(()=>{for(const f of vBe){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:HYn(p)}):f==="fitView"?u.setState({fitViewQueued:p}):f==="fitViewOptions"?u.setState({fitViewOptions:p}):u.setState({[f]:p})))}d.current=e},vBe.map(f=>e[f])),null}function bBe(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function rXn(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=bBe(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:bBe()?.matches?"dark":"light"}const xBe=typeof document<"u"?document:null;function GM(e=null,t={target:xBe,actInsideInputWithModifier:!0}){const[n,r]=g.useState(!1),s=g.useRef(!1),a=g.useRef(new Set([])),[i,l]=g.useMemo(()=>{if(e!==null){const u=(Array.isArray(e)?e:[e]).filter(f=>typeof f=="string").map(f=>f.replace("+",`
|
|
234
|
+
`:r=="r"?"\r":r=="t"?" ":"\\")}eq(t){return this.search==t.search&&this.replace==t.replace&&this.caseSensitive==t.caseSensitive&&this.regexp==t.regexp&&this.wholeWord==t.wholeWord&&this.test==t.test}create(){return this.regexp?new rHn(this):new eHn(this)}getCursor(t,n=0,r){let s=t.doc?t:gs.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?rT(this,s,n,r):nT(this,s,n,r)}}class tOt{constructor(t){this.spec=t}}function XVn(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 nT(e,t,n,r){let s;return e.wholeWord&&(s=JVn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=XVn(e.test,t,s)),new $x(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function JVn(e,t){return(n,r,s,a)=>((a>n||a+s.length<r)&&(a=Math.max(0,n-2),s=e.sliceString(a,Math.min(e.length,r+2))),(t(XB(s,n-a))!=wo.Word||t(JB(s,n-a))!=wo.Word)&&(t(JB(s,r-a))!=wo.Word||t(XB(s,r-a))!=wo.Word))}class eHn extends tOt{constructor(t){super(t)}nextMatch(t,n,r){let s=nT(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=nT(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=nT(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=nT(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=nT(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 tHn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function rT(e,t,n,r){let s;return e.wholeWord&&(s=nHn(t.charCategorizer(t.selection.main.head))),e.test&&(s=tHn(e.test,t,s)),new Xkt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function XB(e,t){return e.slice(Ic(e,t,!1),t)}function JB(e,t){return e.slice(t,Ic(e,t))}function nHn(e){return(t,n,r)=>!r[0].length||(e(XB(r.input,r.index))!=wo.Word||e(JB(r.input,r.index))!=wo.Word)&&(e(JB(r.input,r.index+r[0].length))!=wo.Word||e(XB(r.input,r.index+r[0].length))!=wo.Word)}class rHn extends tOt{nextMatch(t,n,r){let s=rT(this.spec,t,r,t.doc.length).next();return s.done&&(s=rT(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=rT(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=rT(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=rT(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 MM=vr.define(),SOe=vr.define(),Yw=xl.define({create(e){return new gte(Ove(e).create(),null)},update(e,t){for(let n of t.effects)n.is(MM)?e=new gte(n.value.create(),e.panel):n.is(SOe)&&(e=new gte(e.query,n.value?kOe:null));return e},provide:e=>CM.from(e,t=>t.panel)});class gte{constructor(t,n){this.query=t,this.panel=n}}const sHn=Nn.mark({class:"cm-searchMatch"}),aHn=Nn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),iHn=_o.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Yw))}update(e){let t=e.state.field(Yw);(t!=e.startState.field(Yw)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return Nn.none;let{view:n}=this,r=new Wd;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?aHn:sHn)})}return r.finish()}},{decorations:e=>e.decorations});function s4(e){return t=>{let n=t.state.field(Yw,!1);return n&&n.query.spec.valid?e(t,n):sOt(t)}}const eU=s4((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=wt.single(r.from,r.to),a=e.state.facet(NI);return e.dispatch({selection:s,effects:[OOe(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),rOt(e),!0}),tU=s4((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let a=wt.single(s.from,s.to),i=e.state.facet(NI);return e.dispatch({selection:a,effects:[OOe(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),rOt(e),!0}),oHn=s4((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:wt.create(n.map(r=>wt.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),lHn=({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 $x(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(i=a.length),a.push(wt.range(l.value.from,l.value.to))}return t(e.update({selection:wt.create(a,i),userEvent:"select.search.matches"})),!0},E9e=s4((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($t.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=wt.single(i.from,i.to).map(f),d.push(OOe(e,i)),d.push(n.facet(NI).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),cHn=s4((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:$t.announce.of(r),userEvent:"input.replace.all"}),!0});function kOe(e){return e.state.facet(NI).createPanel(e)}function Ove(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(NI);return new eOt({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 nOt(e){let t=Fke(e,kOe);return t&&t.dom.querySelector("[main-field]")}function rOt(e){let t=nOt(e);t&&t==e.root.activeElement&&t.select()}const sOt=e=>{let t=e.state.field(Yw,!1);if(t&&t.panel){let n=nOt(e);if(n&&n!=e.root.activeElement){let r=Ove(e.state,t.query.spec);r.valid&&e.dispatch({effects:MM.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[SOe.of(!0),t?MM.of(Ove(e.state,t.query.spec)):vr.appendConfig.of(pHn)]});return!0},aOt=e=>{let t=e.state.field(Yw,!1);if(!t||!t.panel)return!1;let n=Fke(e,kOe);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:SOe.of(!1)}),!0},uHn=[{key:"Mod-f",run:sOt,scope:"editor search-panel"},{key:"F3",run:eU,shift:tU,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:eU,shift:tU,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:aOt,scope:"editor search-panel"},{key:"Mod-Shift-l",run:lHn},{key:"Mod-Alt-g",run:zVn},{key:"Mod-d",run:KVn,preventDefault:!0}];class dHn{constructor(t){this.view=t;let n=this.query=t.state.field(Yw).query.spec;this.commit=this.commit.bind(this),this.searchField=fi("input",{value:n.search,placeholder:dp(t,"Find"),"aria-label":dp(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=fi("input",{value:n.replace,placeholder:dp(t,"Replace"),"aria-label":dp(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=fi("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=fi("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=fi("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return fi("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=fi("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>eU(t),[dp(t,"next")]),r("prev",()=>tU(t),[dp(t,"previous")]),r("select",()=>oHn(t),[dp(t,"all")]),fi("label",null,[this.caseField,dp(t,"match case")]),fi("label",null,[this.reField,dp(t,"regexp")]),fi("label",null,[this.wordField,dp(t,"by word")]),...t.state.readOnly?[]:[fi("br"),this.replaceField,r("replace",()=>E9e(t),[dp(t,"replace")]),r("replaceAll",()=>cHn(t),[dp(t,"replace all")])],fi("button",{name:"close",onclick:()=>aOt(t),"aria-label":dp(t,"close"),type:"button"},["×"])])}commit(){let t=new eOt({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:MM.of(t)}))}keydown(t){Izn(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?tU:eU)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),E9e(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(MM)&&!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(NI).top}}function dp(e,t){return e.state.phrase(t)}const kF=30,OF=/[\s\.,:;?!]/;function OOe(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),s=e.state.doc.lineAt(n).to,a=Math.max(r.from,t-kF),i=Math.min(s,n+kF),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<kF;c++)if(!OF.test(l[c+1])&&OF.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-kF;c--)if(!OF.test(l[c-1])&&OF.test(l[c])){l=l.slice(0,c);break}}return $t.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const fHn=$t.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"}}),pHn=[Yw,ih.low(iHn),fHn];class T9e{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class Nk{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(DM).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new Wd,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((v,y)=>Math.min(v,y.to),f&&f.from>p?f.from:1e8)):(p=f.from,h=f.to,l.push(f),d++);d<a.length;){let v=a[d];if(v.from==p&&(v.to>v.from||v.to==p))l.push(v),d++,h=Math.min(v.to,h);else{h=Math.min(v.from,h);break}}let m=CHn(l);if(l.some(v=>v.from==v.to||v.from==v.to-1&&r.doc.lineAt(v.from).to==v.from))i.add(p,p,Nn.widget({widget:new SHn(m),diagnostics:l.slice()}));else{let v=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(p,h,Nn.mark({class:"cm-lintRange cm-lintRange-"+m+v,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>h)}))}c=h;for(let v=0;v<l.length;v++)l[v].to<=c&&l.splice(v--,1)}let u=i.finish();return new Nk(u,n,aN(u))}}function aN(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 T9e(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new T9e(r.from,a,r.diagnostic)}}),r}function hHn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(DM).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(iOt))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function mHn(e,t){return e.field(Ap,!1)?t:t.concat(vr.appendConfig.of(EHn))}const iOt=vr.define(),_Oe=vr.define(),oOt=vr.define(),Ap=xl.define({create(){return new Nk(Nn.none,null,null)},update(e,t){if(t.docChanged&&e.diagnostics.size){let n=e.diagnostics.map(t.changes),r=null,s=e.panel;if(e.selected){let a=t.changes.mapPos(e.selected.from,1);r=aN(n,e.selected.diagnostic,a)||aN(n,null,a)}!n.size&&s&&t.state.facet(DM).autoPanel&&(s=null),e=new Nk(n,s,r)}for(let n of t.effects)if(n.is(iOt)){let r=t.state.facet(DM).autoPanel?n.value.length?LM.open:null:e.panel;e=Nk.init(n.value,r,t.state)}else n.is(_Oe)?e=new Nk(e.diagnostics,n.value?LM.open:null,e.selected):n.is(oOt)&&(e=new Nk(e.diagnostics,e.panel,n.value));return e},provide:e=>[CM.from(e,t=>t.panel),$t.decorations.from(e,t=>t.diagnostics)]}),gHn=Nn.mark({class:"cm-lintRange cm-lintRange-active"});function vHn(e,t,n){let{diagnostics:r}=e.state.field(Ap),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(DM).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:yHn(e,s)}}}:null}function yHn(e,t){return fi("ul",{class:"cm-tooltip-lint"},t.map(n=>cOt(e,n,!1)))}const bHn=e=>{let t=e.state.field(Ap,!1);(!t||!t.panel)&&e.dispatch({effects:mHn(e.state,[_Oe.of(!0)])});let n=Fke(e,LM.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},j9e=e=>{let t=e.state.field(Ap,!1);return!t||!t.panel?!1:(e.dispatch({effects:_Oe.of(!1)}),!0)},xHn=e=>{let t=e.state.field(Ap,!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)},wHn=[{key:"Mod-Shift-m",run:bHn,preventDefault:!0},{key:"F8",run:xHn}],DM=kn.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...By(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:N9e,tooltipFilter:N9e,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 N9e(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function lOt(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 cOt(e,t,n){var r;let s=n?lOt(t.actions):[];return fi("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},fi("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=aN(e.state.field(Ap).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),fi("u",u.slice(d,d+1)),u.slice(d+1)],p=a.markClass?" "+a.markClass:"";return fi("button",{type:"button",class:"cm-diagnosticAction"+p,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&fi("div",{class:"cm-diagnosticSource"},t.source))}class SHn extends oh{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return fi("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class I9e{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=cOt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class LM{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)j9e(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=lOt(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=aN(this.view.state.field(Ap).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=fi("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=fi("div",{class:"cm-panel-lint"},this.list,fi("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>j9e(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Ap).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(Ap),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 I9e(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 I9e(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(Ap),r=aN(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:oOt.of(r)})}static open(t){return new LM(t)}}function kHn(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 _F(e){return kHn(`<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 OHn=$t.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:_F("#d11")},".cm-lintRange-warning":{backgroundImage:_F("orange")},".cm-lintRange-info":{backgroundImage:_F("#999")},".cm-lintRange-hint":{backgroundImage:_F("#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 _Hn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function CHn(e){let t="hint",n=1;for(let r of e){let s=_Hn(r.severity);s>n&&(n=s,t=r.severity)}return t}const EHn=[Ap,$t.decorations.compute([Ap],e=>{let{selected:t,panel:n}=e.field(Ap);return!t||!n||t.from==t.to?Nn.none:Nn.set([gHn.range(t.from,t.to)])}),b8n(vHn,{hideOn:hHn}),OHn];var A9e=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(g7n)),t.defaultKeymap!==!1&&(a=a.concat(DVn)),t.searchKeymap!==!1&&(a=a.concat(uHn)),t.historyKeymap!==!1&&(a=a.concat(Vqn)),t.foldKeymap!==!1&&(a=a.concat(t9n)),t.completionKeymap!==!1&&(a=a.concat(rSt)),t.lintKeymap!==!1&&(a=a.concat(wHn));var i=[];return t.lineNumbers!==!1&&i.push(I8n()),t.highlightActiveLineGutter!==!1&&i.push(P8n()),t.highlightSpecialChars!==!1&&i.push(Zzn()),t.history!==!1&&i.push($qn()),t.foldGutter!==!1&&i.push(a9n()),t.drawSelection!==!1&&i.push(Dzn()),t.dropCursor!==!1&&i.push(Uzn()),t.allowMultipleSelections!==!1&&i.push(gs.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(Z8n()),t.syntaxHighlighting!==!1&&i.push(lS(c9n,{fallback:!0})),t.bracketMatching!==!1&&i.push(g9n()),t.closeBrackets!==!1&&i.push(f7n()),t.autocompletion!==!1&&i.push(nSt()),t.rectangularSelection!==!1&&i.push(o8n()),s!==!1&&i.push(u8n()),t.highlightActiveLine!==!1&&i.push(Jzn()),t.highlightSelectionMatches!==!1&&i.push(qVn()),t.tabSize&&typeof t.tabSize=="number"&&i.push(CI.of(" ".repeat(t.tabSize))),i.concat([_I.of(a.flat())]).filter(Boolean)};const THn="#e5c07b",R9e="#e06c75",jHn="#56b6c2",NHn="#ffffff",t9="#abb2bf",_ve="#7d8799",IHn="#61afef",AHn="#98c379",P9e="#d19a66",RHn="#c678dd",PHn="#21252b",$9e="#2c313a",M9e="#282c34",vte="#353a42",$Hn="#3E4451",D9e="#528bff",MHn=$t.theme({"&":{color:t9,backgroundColor:M9e},".cm-content":{caretColor:D9e},".cm-cursor, .cm-dropCursor":{borderLeftColor:D9e},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:$Hn},".cm-panels":{backgroundColor:PHn,color:t9},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:"1px solid #457dff"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:"#6199ff2f"},".cm-activeLine":{backgroundColor:"#6699ff0b"},".cm-selectionMatch":{backgroundColor:"#aafe661a"},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bad0f847"},".cm-gutters":{backgroundColor:M9e,color:_ve,border:"none"},".cm-activeLineGutter":{backgroundColor:$9e},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:vte},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:vte,borderBottomColor:vte},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:$9e,color:t9}}},{dark:!0}),DHn=Yg.define([{tag:de.keyword,color:RHn},{tag:[de.name,de.deleted,de.character,de.propertyName,de.macroName],color:R9e},{tag:[de.function(de.variableName),de.labelName],color:IHn},{tag:[de.color,de.constant(de.name),de.standard(de.name)],color:P9e},{tag:[de.definition(de.name),de.separator],color:t9},{tag:[de.typeName,de.className,de.number,de.changed,de.annotation,de.modifier,de.self,de.namespace],color:THn},{tag:[de.operator,de.operatorKeyword,de.url,de.escape,de.regexp,de.link,de.special(de.string)],color:jHn},{tag:[de.meta,de.comment],color:_ve},{tag:de.strong,fontWeight:"bold"},{tag:de.emphasis,fontStyle:"italic"},{tag:de.strikethrough,textDecoration:"line-through"},{tag:de.link,color:_ve,textDecoration:"underline"},{tag:de.heading,fontWeight:"bold",color:R9e},{tag:[de.atom,de.bool,de.special(de.variableName)],color:P9e},{tag:[de.processingInstruction,de.string,de.inserted],color:AHn},{tag:de.invalid,color:NHn}]),LHn=[MHn,lS(DHn)];var FHn=$t.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),zHn=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,v=[];switch(s&&v.unshift(_I.of([LVn])),m&&(typeof m=="boolean"?v.unshift(A9e()):v.unshift(A9e(m))),p&&v.unshift(r8n(p)),d){case"light":v.push(FHn);break;case"dark":v.push(LHn);break;case"none":break;default:v.push(d);break}return i===!1&&v.push($t.editable.of(!1)),c&&v.push(gs.readOnly.of(!0)),[...v]},BHn=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 UHn{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 L9e{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 yte=null,qHn=()=>typeof window>"u"?new L9e:(yte||(yte=new L9e),yte),VHn=$t.theme({"& .cm-scroller":{height:"100% !important"}}),F9e=null,bte=null;function HHn(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===F9e||(F9e=i,bte=$t.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a}})),bte}var z9e=zy.define(),WHn=200,ZHn=[];function GHn(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?ZHn: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,v=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,T=C===void 0?null:C,E=e.placeholder,N=E===void 0?"":E,I=e.editable,A=I===void 0?!0:I,R=e.readOnly,L=R===void 0?!1:R,M=e.indentWithTab,F=M===void 0?!0:M,H=e.basicSetup,z=H===void 0?!0:H,q=e.root,V=e.initialState,D=g.useState(),G=D[0],U=D[1],P=g.useState(),B=P[0],Z=P[1],Y=g.useState(),te=Y[0],J=Y[1],ee=g.useState(()=>({current:null}))[0],re=g.useState(()=>({current:null}))[0],oe=HHn(h,v,b,S,_,T),X=$t.updateListener.of(fe=>{if(fe.docChanged&&typeof r=="function"&&!fe.transactions.some(pe=>pe.annotation(z9e))){ee.current?ee.current.reset():(ee.current=new UHn(()=>{if(re.current){var pe=re.current;re.current=null,pe()}ee.current=null},WHn),qHn().add(ee.current));var ce=fe.state.doc,xe=ce.toString();r(xe,fe)}s&&s(BHn(fe))}),ne=zHn({theme:f,editable:A,readOnly:L,placeholder:N,indentWithTab:F,basicSetup:z}),se=[X,...oe?[oe]:[],VHn,...ne];return i&&typeof i=="function"&&se.push($t.updateListener.of(i)),se=se.concat(c),g.useLayoutEffect(()=>{if(G&&!te){var fe={doc:t,selection:n,extensions:se},ce=V?gs.fromJSON(V.json,fe,V.fields):gs.create(fe);if(J(ce),!B){var xe=new $t({state:ce,parent:G,root:q});Z(xe),a&&a(xe,ce)}}return()=>{B&&(J(void 0),Z(void 0))}},[G,te]),g.useEffect(()=>{e.container&&U(e.container)},[e.container]),g.useEffect(()=>()=>{B&&(B.destroy(),Z(void 0)),ee.current&&(ee.current.cancel(),ee.current=null)},[B]),g.useEffect(()=>{u&&B&&B.focus()},[u,B]),g.useEffect(()=>{B&&B.dispatch({effects:vr.reconfigure.of(se)})},[f,c,h,v,b,S,_,T,N,A,L,F,z,r,i]),g.useEffect(()=>{if(t!==void 0){var fe=B?B.state.doc.toString():"";if(B&&t!==fe){var ce=ee.current&&!ee.current.isDone,xe=()=>{B&&t!==B.state.doc.toString()&&B.dispatch({changes:{from:0,to:B.state.doc.toString().length,insert:t||""},annotations:[z9e.of(!0)]})};ce?re.current=xe:xe()}}},[t,B]),{state:te,setState:J,view:B,setView:Z,container:G,setContainer:U}}var QHn=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],nd=g.forwardRef((e,t)=>{var n=e.className,r=e.value,s=r===void 0?"":r,a=e.selection,i=e.extensions,l=i===void 0?[]:i,c=e.onChange,u=e.onStatistics,d=e.onCreateEditor,f=e.onUpdate,p=e.autoFocus,h=e.theme,m=h===void 0?"light":h,v=e.height,y=e.minHeight,b=e.maxHeight,x=e.width,S=e.minWidth,k=e.maxWidth,_=e.basicSetup,C=e.placeholder,T=e.indentWithTab,E=e.editable,N=e.readOnly,I=e.root,A=e.initialState,R=vkt(e,QHn),L=g.useRef(null),M=GHn({root:I,value:s,autoFocus:p,theme:m,height:v,minHeight:y,maxHeight:b,width:x,minWidth:S,maxWidth:k,basicSetup:_,placeholder:C,indentWithTab:T,editable:E,readOnly:N,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),F=M.state,H=M.view,z=M.container,q=M.setContainer;g.useImperativeHandle(t,()=>({editor:L.current,state:F,view:H}),[L,z,F,H]);var V=g.useCallback(G=>{L.current=G,q(G)},[q]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var D=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",JO({ref:V,className:""+D+(n?" "+n:"")},R))});nd.displayName="CodeMirror";const YHn={js:"javascript",javascript:"javascript",mjs:"javascript",cjs:"javascript",node:"javascript",ts:"typescript",typescript:"typescript",mts:"typescript",cts:"typescript",tsx:"tsx",jsx:"jsx",json:"json",json5:"json",md:"markdown",markdown:"markdown",py:"python",python:"python",sh:"bash",bash:"bash",shell:"bash",zsh:"bash",yml:"yaml",yaml:"yaml",diff:"diff",patch:"diff",css:"css",scss:"css",html:"html",htm:"html",xml:"xml",svg:"xml",sql:"sql"};let xte=null;function KHn(){return xte||(xte=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Fa(()=>import("./core-W-bmkix6.js"),__vite__mapDeps([0,1,2]),import.meta.url),Fa(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[Fa(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Fa(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Fa(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Fa(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Fa(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Fa(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Fa(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Fa(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Fa(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Fa(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Fa(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Fa(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Fa(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Fa(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([4,5,6]),import.meta.url),Fa(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Fa(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),xte}async function XHn(e,t){const n=YHn[t?.toLowerCase()];if(!n)return null;const r=await KHn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function JHn(e){return new QO(Vke.define(e))}const uOt=[pg.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return Fa(()=>Promise.resolve().then(()=>wF),void 0,import.meta.url).then(e=>e.javascript())}}),pg.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return Fa(()=>Promise.resolve().then(()=>T9n),void 0,import.meta.url).then(e=>e.json())}}),pg.of({name:"JSX",extensions:["jsx"],load(){return Fa(()=>Promise.resolve().then(()=>wF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),pg.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return Fa(()=>Promise.resolve().then(()=>Sqn),void 0,import.meta.url).then(e=>e.markdown())}}),pg.of({name:"TSX",extensions:["tsx"],load(){return Fa(()=>Promise.resolve().then(()=>wF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),pg.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return Fa(()=>Promise.resolve().then(()=>wF),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),pg.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return Fa(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>JHn(e.shell))}})];function eWn(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 tWn(e){const t=eWn(e);return nSt({override:[nWn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function nWn(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 v=u.state.sliceDoc(p,p+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:p,insert:v},selection:{anchor:f+v.length}})}}));return{from:a,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const rWn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,sWn=Nn.mark({class:"cm-variable-highlight"}),B9e=new g1t({regexp:rWn,decoration:()=>sWn}),aWn=_o.fromClass(class{decorations;constructor(e){this.decorations=B9e.createDeco(e)}update(e){this.decorations=B9e.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),iWn=aWn;function oWn(){const e=TI({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:[de.className,de.propertyName],color:"var(--neutral6)"},{tag:de.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[de.heading1,de.heading2,de.heading3,de.heading4,de.heading5,de.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:de.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:de.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:de.link,color:"var(--accent3)",textDecoration:"underline"},{tag:de.url,color:"var(--accent3)"},{tag:de.monospace,color:"var(--neutral6)"},{tag:de.strikethrough,textDecoration:"line-through"},{tag:de.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=$t.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 lWn(){const e=$t.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=Yg.define([{tag:[de.comment,de.bracket],color:"var(--neutral2)"},{tag:[de.string,de.meta,de.regexp],color:"var(--accent1)"},{tag:[de.atom,de.bool,de.special(de.variableName)],color:"var(--accent6)"},{tag:[de.keyword,de.operator,de.tagName],color:"var(--accent2)"},{tag:[de.function(de.propertyName),de.propertyName],color:"var(--accent5)"},{tag:[de.definition(de.variableName),de.function(de.variableName),de.className,de.attributeName],color:"var(--accent3)"},{tag:[de.variableName,de.number],color:"var(--accent5)"},{tag:[de.name,de.quote],color:"var(--accent1)"},{tag:de.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[de.heading1,de.heading2,de.heading3,de.heading4,de.heading5,de.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[de.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[de.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:de.link,color:"var(--accent3)",textDecoration:"underline"},{tag:de.url,color:"var(--accent3)"},{tag:de.monospace,color:"var(--neutral6)"},{tag:de.strikethrough,textDecoration:"line-through"},{tag:[de.deleted],color:"var(--accent2)"},{tag:de.invalid,color:"var(--error)"},{tag:[de.standard(de.tagName)],color:"var(--accent1)"}]);return[e,lS(t)]}const r0=()=>{const e=rC().resolvedTheme==="dark";return g.useMemo(()=>e?oWn():lWn(),[e])},cWn=co(K("relative overflow-hidden font-mono outline-hidden focus-within:outline-hidden focus:outline-hidden","duration-normal transition-colors ease-out-custom"),{variants:{variant:{default:"rounded-md border border-border1 bg-surface3 p-1 focus-within:border-neutral6/20",embedded:"rounded-none border-none bg-transparent p-0"}},defaultVariants:{variant:"default"}}),uWn=ih.highest($t.editorAttributes.of({style:"outline: none"})),dWn=ih.highest($t.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),fWn=[uWn,dWn],Qr=g.forwardRef(({data:e,value:t,onChange:n,showCopyButton:r=!0,className:s,language:a="json",highlightVariables:i=!1,placeholder:l,schema:c,autoFocus:u,lineNumbers:d=!0,lineWrapping:f=!0,editable:p,variant:h,...m},v)=>{const y=r0(),b=e?JSON.stringify(e,null,2):t??"",x=g.useMemo(()=>{const S=[...fWn];return f&&S.push($t.lineWrapping),a==="json"?S.push(Fp):a==="markdown"&&S.push(vOe({base:XO,codeLanguages:uOt})),i&&a==="markdown"&&S.push(iWn),c&&a==="markdown"&&S.push(tWn(c)),p===!1&&S.push(gs.readOnly.of(!0)),S},[a,i,c,p,f]);return o.jsxs("div",{className:K(cWn({variant:h}),s),...m,children:[r&&o.jsx(ka,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(nd,{ref:v,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}})]})}),pWn=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},hWn=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=r0(),{settings:r,setSettings:s}=VH(),a=r?.tracingOptions,i=g.useMemo(()=>pWn(a),[a]),[l,c]=g.useState(()=>i),u=g.useRef(!1);g.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(ve,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),o.jsx(nd,{value:l,onChange:d,theme:n,extensions:[Fp],className:K("overflow-y-scroll bg-surface3 rounded-lg overflow-hidden p-3",e)}),o.jsx("div",{className:"flex items-center justify-end",children:o.jsx(le,{type:"button",onClick:f,children:"Save"})})]})},mWn=()=>{const[e,t]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx(le,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(We,{children:o.jsx(P0e,{})})})}),o.jsx(yn,{children:"Run Options"})]}),o.jsx(hr,{open:e,onOpenChange:t,children:o.jsxs(mr,{children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Run Options"}),o.jsx(Cs,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx(jr,{children:o.jsx(hWn,{onSaved:()=>t(!1)})})]})})]})};function gWn({status:e}){switch(e){case"running":return o.jsx(Ut,{});case"failed":return o.jsx(or,{className:"text-accent2"});case"canceled":return o.jsx($c,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(a1,{className:"text-neutral3"});case"suspended":return o.jsx(EV,{className:"text-accent3"});case"success":return o.jsx(qr,{className:"text-accent1"});default:return o.jsx(a1,{className:"text-neutral3"})}}function dOt({status:e}){return o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx(We,{"aria-label":e,className:"shrink-0",children:o.jsx(gWn,{status:e})})}),o.jsx(yn,{children:e})]})}var wte,U9e;function COe(){if(U9e)return wte;U9e=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([v,y]){d(v)&&f.setNode(v,y)}),Object.values(this._edgeObjs).forEach(function(v){f.hasNode(v.v)&&f.hasNode(v.w)&&f.setEdge(v,p.edge(v))});var h={};function m(v){var y=p.parent(v);return y===void 0||f.hasNode(y)?(h[v]=y,y):y in h?h[y]:m(y)}return this._isCompound&&f.nodes().forEach(v=>f.setParent(v,m(v))),f}setDefaultEdgeLabel(d){return this._defaultEdgeLabelFn=d,typeof d!="function"&&(this._defaultEdgeLabelFn=()=>d),this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(d,f){var p=this,h=arguments;return d.reduce(function(m,v){return h.length>1?p.setEdge(m,v,f):p.setEdge(m,v),v}),this}setEdge(){var d,f,p,h,m=!1,v=arguments[0];typeof v=="object"&&v!==null&&"v"in v?(d=v.v,f=v.w,p=v.name,arguments.length===2&&(h=arguments[1],m=!0)):(d=v,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 v=h;h=m,m=v}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 v=h;h=m,m=v}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 wte=r,wte}var Ste,q9e;function vWn(){return q9e||(q9e=1,Ste="2.2.4"),Ste}var kte,V9e;function yWn(){return V9e||(V9e=1,kte={Graph:COe(),version:vWn()}),kte}var Ote,H9e;function bWn(){if(H9e)return Ote;H9e=1;var e=COe();Ote={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 Ote}var _te,W9e;function xWn(){if(W9e)return _te;W9e=1,_te=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 _te}var Cte,Z9e;function fOt(){if(Z9e)return Cte;Z9e=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 Cte=e,Cte}var Ete,G9e;function pOt(){if(G9e)return Ete;G9e=1;var e=fOt();Ete=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,v=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<v.distance&&(v.distance=b,v.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 Ete}var Tte,Q9e;function wWn(){if(Q9e)return Tte;Q9e=1;var e=pOt();Tte=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return Tte}var jte,Y9e;function hOt(){if(Y9e)return jte;Y9e=1,jte=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 jte}var Nte,K9e;function SWn(){if(K9e)return Nte;K9e=1;var e=hOt();Nte=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return Nte}var Ite,X9e;function kWn(){if(X9e)return Ite;X9e=1,Ite=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],v=f[p],y=h.distance+m.distance;y<v.distance&&(v.distance=y,v.predecessor=m.predecessor)})})}),i}return Ite}var Ate,J9e;function mOt(){if(J9e)return Ate;J9e=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 Ate=e,e.CycleException=t,Ate}var Rte,e7e;function OWn(){if(e7e)return Rte;e7e=1;var e=mOt();Rte=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return Rte}var Pte,t7e;function gOt(){if(t7e)return Pte;t7e=1,Pte=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 Pte}var $te,n7e;function _Wn(){if(n7e)return $te;n7e=1;var e=gOt();$te=t;function t(n,r){return e(n,r,"post")}return $te}var Mte,r7e;function CWn(){if(r7e)return Mte;r7e=1;var e=gOt();Mte=t;function t(n,r){return e(n,r,"pre")}return Mte}var Dte,s7e;function EWn(){if(s7e)return Dte;s7e=1;var e=COe(),t=fOt();Dte=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 Dte}var Lte,a7e;function TWn(){return a7e||(a7e=1,Lte={components:xWn(),dijkstra:pOt(),dijkstraAll:wWn(),findCycles:SWn(),floydWarshall:kWn(),isAcyclic:OWn(),postorder:_Wn(),preorder:CWn(),prim:EWn(),tarjan:hOt(),topsort:mOt()}),Lte}var Fte,i7e;function Vg(){if(i7e)return Fte;i7e=1;var e=yWn();return Fte={Graph:e.Graph,json:bWn(),alg:TWn(),version:e.version},Fte}var zte,o7e;function jWn(){if(o7e)return zte;o7e=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 zte=e,zte}var Bte,l7e;function NWn(){if(l7e)return Bte;l7e=1;let e=Vg().Graph,t=jWn();Bte=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],v;for(;u.nodeCount();){for(;v=m.dequeue();)a(u,d,f,v);for(;v=h.dequeue();)a(u,d,f,v);if(u.nodeCount()){for(let y=d.length-2;y>0;--y)if(v=d[y].dequeue(),v){p=p.concat(a(u,d,f,v,!0));break}}}return p}function a(u,d,f,p,h){let m=h?[]:void 0;return u.inEdges(p.v).forEach(v=>{let y=u.edge(v),b=u.node(v.v);h&&m.push({v:v.v,w:v.w}),b.out-=y,l(d,f,b)}),u.outEdges(p.v).forEach(v=>{let y=u.edge(v),b=v.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),v=p+1;return f.nodes().forEach(y=>{l(m,v,f.node(y))}),{graph:f,buckets:m,zeroIdx:v}}function l(u,d,f){f.out?f.in?u[f.out-f.in+d].enqueue(f):u[u.length-1].enqueue(f):u[0].enqueue(f)}function c(u){const d=[];for(let f=0;f<u;f++)d.push(f);return d}return Bte}var Ute,c7e;function $l(){if(c7e)return Ute;c7e=1;let e=Vg().Graph;Ute={addBorderNode:d,addDummyNode:t,applyWithChunking:h,asNonCompoundGraph:r,buildLayerMatrix:l,intersectRect:i,mapValues:C,maxRank:m,normalizeRanks:c,notime:b,partition:v,pick:_,predecessorWeights:a,range:k,removeEmptyRanks:u,simplify:n,successorWeights:s,time:y,uniqueId:S,zipObject:T};function t(E,N,I,A){for(var R=A;E.hasNode(R);)R=S(A);return I.dummy=N,E.setNode(R,I),R}function n(E){let N=new e().setGraph(E.graph());return E.nodes().forEach(I=>N.setNode(I,E.node(I))),E.edges().forEach(I=>{let A=N.edge(I.v,I.w)||{weight:0,minlen:1},R=E.edge(I);N.setEdge(I.v,I.w,{weight:A.weight+R.weight,minlen:Math.max(A.minlen,R.minlen)})}),N}function r(E){let N=new e({multigraph:E.isMultigraph()}).setGraph(E.graph());return E.nodes().forEach(I=>{E.children(I).length||N.setNode(I,E.node(I))}),E.edges().forEach(I=>{N.setEdge(I,E.edge(I))}),N}function s(E){let N=E.nodes().map(I=>{let A={};return E.outEdges(I).forEach(R=>{A[R.w]=(A[R.w]||0)+E.edge(R).weight}),A});return T(E.nodes(),N)}function a(E){let N=E.nodes().map(I=>{let A={};return E.inEdges(I).forEach(R=>{A[R.v]=(A[R.v]||0)+E.edge(R).weight}),A});return T(E.nodes(),N)}function i(E,N){let I=E.x,A=E.y,R=N.x-I,L=N.y-A,M=E.width/2,F=E.height/2;if(!R&&!L)throw new Error("Not possible to find intersection inside of the rectangle");let H,z;return Math.abs(L)*M>Math.abs(R)*F?(L<0&&(F=-F),H=F*R/L,z=F):(R<0&&(M=-M),H=M,z=M*L/R),{x:I+H,y:A+z}}function l(E){let N=k(m(E)+1).map(()=>[]);return E.nodes().forEach(I=>{let A=E.node(I),R=A.rank;R!==void 0&&(N[R][A.order]=I)}),N}function c(E){let N=E.nodes().map(A=>{let R=E.node(A).rank;return R===void 0?Number.MAX_VALUE:R}),I=h(Math.min,N);E.nodes().forEach(A=>{let R=E.node(A);Object.hasOwn(R,"rank")&&(R.rank-=I)})}function u(E){let N=E.nodes().map(M=>E.node(M).rank),I=h(Math.min,N),A=[];E.nodes().forEach(M=>{let F=E.node(M).rank-I;A[F]||(A[F]=[]),A[F].push(M)});let R=0,L=E.graph().nodeRankFactor;Array.from(A).forEach((M,F)=>{M===void 0&&F%L!==0?--R:M!==void 0&&R&&M.forEach(H=>E.node(H).rank+=R)})}function d(E,N,I,A){let R={width:0,height:0};return arguments.length>=4&&(R.rank=I,R.order=A),t(E,"border",R,N)}function f(E,N=p){const I=[];for(let A=0;A<E.length;A+=N){const R=E.slice(A,A+N);I.push(R)}return I}const p=65535;function h(E,N){if(N.length>p){const I=f(N);return E.apply(null,I.map(A=>E.apply(null,A)))}else return E.apply(null,N)}function m(E){const I=E.nodes().map(A=>{let R=E.node(A).rank;return R===void 0?Number.MIN_VALUE:R});return h(Math.max,I)}function v(E,N){let I={lhs:[],rhs:[]};return E.forEach(A=>{N(A)?I.lhs.push(A):I.rhs.push(A)}),I}function y(E,N){let I=Date.now();try{return N()}finally{console.log(E+" time: "+(Date.now()-I)+"ms")}}function b(E,N){return N()}let x=0;function S(E){var N=++x;return E+(""+N)}function k(E,N,I=1){N==null&&(N=E,E=0);let A=L=>L<N;I<0&&(A=L=>N<L);const R=[];for(let L=E;A(L);L+=I)R.push(L);return R}function _(E,N){const I={};for(const A of N)E[A]!==void 0&&(I[A]=E[A]);return I}function C(E,N){let I=N;return typeof N=="string"&&(I=A=>A[N]),Object.entries(E).reduce((A,[R,L])=>(A[R]=I(L,R),A),{})}function T(E,N){return E.reduce((I,A,R)=>(I[A]=N[R],I),{})}return Ute}var qte,u7e;function IWn(){if(u7e)return qte;u7e=1;let e=NWn(),t=$l().uniqueId;qte={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 qte}var Vte,d7e;function AWn(){if(d7e)return Vte;d7e=1;let e=$l();Vte={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,v;for(v=0,++l;l<u;++v,++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),v===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 Vte}var Hte,f7e;function nU(){if(f7e)return Hte;f7e=1;const{applyWithChunking:e}=$l();Hte={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 Hte}var Wte,p7e;function vOt(){if(p7e)return Wte;p7e=1;var e=Vg().Graph,t=nU().slack;Wte=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 Wte}var Zte,h7e;function RWn(){if(h7e)return Zte;h7e=1;var e=vOt(),t=nU().slack,n=nU().longestPath,r=Vg().alg.preorder,s=Vg().alg.postorder,a=$l().simplify;Zte=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,T=!0,E=S.edge(k,C),N=0;return E||(T=!1,E=S.edge(C,k)),N=E.weight,S.nodeEdges(k).forEach(I=>{var A=I.v===k,R=A?I.w:I.v;if(R!==C){var L=A===T,M=S.edge(I).weight;if(N+=L?M:-M,y(x,k,R)){var F=x.edge(k,R).cutvalue;N+=L?-F:F}}}),N}function d(x,S){arguments.length<2&&(S=x.nodes()[0]),f(x,{},1,S)}function f(x,S,k,_,C){var T=k,E=x.node(_);return S[_]=!0,x.neighbors(_).forEach(N=>{Object.hasOwn(S,N)||(k=f(x,S,k,N,_))}),E.low=T,E.lim=k++,C?E.parent=C:delete E.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 T=x.node(_),E=x.node(C),N=T,I=!1;T.lim>E.lim&&(N=E,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,T=k.w;x.removeEdge(C,T),x.setEdge(_.v,_.w,{}),d(x),l(x,S),v(x,S)}function v(x,S){var k=x.nodes().find(C=>!S.node(C).parent),_=r(x,k);_=_.slice(1),_.forEach(C=>{var T=x.node(C).parent,E=S.edge(C,T),N=!1;E||(E=S.edge(T,C),N=!0),S.node(C).rank=S.node(T).rank+(N?E.minlen:-E.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 Zte}var Gte,m7e;function PWn(){if(m7e)return Gte;m7e=1;var e=nU(),t=e.longestPath,n=vOt(),r=RWn();Gte=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 Gte}var Qte,g7e;function $Wn(){if(g7e)return Qte;g7e=1,Qte=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 Qte}var Yte,v7e;function MWn(){if(v7e)return Yte;v7e=1;let e=$l();Yte={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"),v=e.addBorderNode(i,"_bb"),y=i.node(p);i.setParent(m,p),y.borderTop=m,i.setParent(v,p),y.borderBottom=v,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,v,{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 Yte}var Kte,y7e;function DWn(){if(y7e)return Kte;y7e=1;let e=$l();Kte=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 Kte}var Xte,b7e;function LWn(){if(b7e)return Xte;b7e=1,Xte={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 Xte}var Jte,x7e;function FWn(){if(x7e)return Jte;x7e=1;let e=$l();Jte=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 Jte}var ene,w7e;function zWn(){if(w7e)return ene;w7e=1;let e=$l().zipObject;ene=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 ene}var tne,S7e;function BWn(){if(S7e)return tne;S7e=1,tne=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 tne}var nne,k7e;function UWn(){if(k7e)return nne;k7e=1;let e=$l();nne=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 nne}var rne,O7e;function qWn(){if(O7e)return rne;O7e=1;let e=$l();rne=t;function t(s,a){let i=e.partition(s,m=>Object.hasOwn(m,"barycenter")),l=i.lhs,c=i.rhs.sort((m,v)=>v.i-m.i),u=[],d=0,f=0,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 rne}var sne,_7e;function VWn(){if(_7e)return sne;_7e=1;let e=BWn(),t=UWn(),n=qWn();sne=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 v=e(i,d);v.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(v,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 sne}var ane,C7e;function HWn(){if(C7e)return ane;C7e=1;let e=Vg().Graph,t=$l();ane=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,v=u.edge(m,d),y=v!==void 0?v.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 ane}var ine,E7e;function WWn(){if(E7e)return ine;E7e=1,ine=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 ine}var one,T7e;function ZWn(){if(T7e)return one;T7e=1;let e=FWn(),t=zWn(),n=VWn(),r=HWn(),s=WWn(),a=Vg().Graph,i=$l();one=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"),v=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:v,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,v=(y,b)=>{m.has(y)||m.set(y,[]),m.get(y).push(b)};for(const y of f.nodes()){const b=f.node(y);if(typeof b.rank=="number"&&v(b.rank,y),typeof b.minRank=="number"&&typeof b.maxRank=="number")for(let x=b.minRank;x<=b.maxRank;x++)x!==b.rank&&v(x,y)}return 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 v=m.graph().root,y=n(m,v,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,v)=>f.node(m).order=v))}return one}var lne,j7e;function GWn(){if(j7e)return lne;j7e=1;let e=Vg().Graph,t=$l();lne={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,T=0,E=k.length,N=_[_.length-1];return _.forEach((I,A)=>{let R=s(y,I),L=R?y.node(R).order:E;(R||I===N)&&(_.slice(T,A+1).forEach(M=>{y.predecessors(M).forEach(F=>{let H=y.node(F),z=H.order;(z<C||L<z)&&!(H.dummy&&y.node(M).dummy)&&a(x,F,M)})}),T=A+1,C=L)}),_}return b.length&&b.reduce(S),x}function r(y,b){let x={};function S(_,C,T,E,N){let I;t.range(C,T).forEach(A=>{I=_[A],y.node(I).dummy&&y.predecessors(I).forEach(R=>{let L=y.node(R);L.dummy&&(L.order<E||L.order>N)&&a(x,R,I)})})}function k(_,C){let T=-1,E,N=0;return C.forEach((I,A)=>{if(y.node(I).dummy==="border"){let R=y.predecessors(I);R.length&&(E=y.node(R[0]).order,S(C,N,A,T,E),N=A,T=E)}S(C,N,C.length,E,_.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(T=>{T.forEach((E,N)=>{k[E]=E,_[E]=E,C[E]=N})}),b.forEach(T=>{let E=-1;T.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 M=I[R];_[N]===N&&E<C[M]&&!i(x,N,M)&&(_[M]=N,_[N]=k[N]=k[M],E=C[M])}}})}),{root:k,align:_}}function c(y,b,x,S,k){let _={},C=u(y,b,x,k),T=k?"borderLeft":"borderRight";function E(A,R){let L=C.nodes(),M=L.pop(),F={};for(;M;)F[M]?A(M):(F[M]=!0,L.push(M),L=L.concat(R(M))),M=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((M,F)=>Math.min(M,_[F.w]-C.edge(F)),Number.POSITIVE_INFINITY),L=y.node(A);R!==Number.POSITIVE_INFINITY&&L.borderType!==T&&(_[A]=Math.max(_[A],R))}return E(N,C.predecessors.bind(C)),E(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(T=>{let E;T.forEach(N=>{let I=x[N];if(k.setNode(I),E){var A=x[E],R=k.edge(A,I);k.setEdge(A,I,Math.max(C(y,N,E),R||0))}E=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(([T,E])=>{let N=v(y,T)/2;k=Math.max(E+N,k),_=Math.min(E-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 T=_+C,E=y[T];if(E===b)return;let N=Object.values(E),I=S-t.applyWithChunking(Math.min,N);C!=="l"&&(I=k-t.applyWithChunking(Math.max,N)),I&&(y[T]=t.mapValues(E,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(T=>{T==="r"&&(k=k.map(A=>Object.values(A).reverse()));let E=(C==="u"?y.predecessors:y.successors).bind(y),N=l(y,k,x,E),I=c(y,k,N.root,N.align,T==="r");T==="r"&&(I=t.mapValues(I,A=>-A)),S[C+T]=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),T=S.node(_),E=0,N;if(E+=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&&(E+=x?N:-N),N=0,E+=(C.dummy?b:y)/2,E+=(T.dummy?b:y)/2,E+=T.width/2,Object.hasOwn(T,"labelpos"))switch(T.labelpos.toLowerCase()){case"l":N=T.width/2;break;case"r":N=-T.width/2;break}return N&&(E+=x?N:-N),N=0,E}}function v(y,b){return y.node(b).width}return lne}var cne,N7e;function QWn(){if(N7e)return cne;N7e=1;let e=$l(),t=GWn().positionX;cne=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 cne}var une,I7e;function YWn(){if(I7e)return une;I7e=1;let e=IWn(),t=AWn(),n=PWn(),r=$l().normalizeRanks,s=$Wn(),a=$l().removeEmptyRanks,i=MWn(),l=DWn(),c=LWn(),u=ZWn(),d=QWn(),f=$l(),p=Vg().Graph;une=h;function h(P,B){let Z=B&&B.debugTiming?f.time:f.notime;Z("layout",()=>{let Y=Z(" buildLayoutGraph",()=>E(P));Z(" runLayout",()=>m(Y,Z,B)),Z(" updateInputGraph",()=>v(P,Y))})}function m(P,B,Z){B(" makeSpaceForEdgeLabels",()=>N(P)),B(" removeSelfEdges",()=>q(P)),B(" acyclic",()=>e.run(P)),B(" nestingGraph.run",()=>i.run(P)),B(" rank",()=>n(f.asNonCompoundGraph(P))),B(" injectEdgeLabelProxies",()=>I(P)),B(" removeEmptyRanks",()=>a(P)),B(" nestingGraph.cleanup",()=>i.cleanup(P)),B(" normalizeRanks",()=>r(P)),B(" assignRankMinMax",()=>A(P)),B(" removeEdgeLabelProxies",()=>R(P)),B(" normalize.run",()=>t.run(P)),B(" parentDummyChains",()=>s(P)),B(" addBorderSegments",()=>l(P)),B(" order",()=>u(P,Z)),B(" insertSelfEdges",()=>V(P)),B(" adjustCoordinateSystem",()=>c.adjust(P)),B(" position",()=>d(P)),B(" positionSelfEdges",()=>D(P)),B(" removeBorderNodes",()=>z(P)),B(" normalize.undo",()=>t.undo(P)),B(" fixupEdgeLabelCoords",()=>F(P)),B(" undoCoordinateSystem",()=>c.undo(P)),B(" translateGraph",()=>L(P)),B(" assignNodeIntersects",()=>M(P)),B(" reversePoints",()=>H(P)),B(" acyclic.undo",()=>e.undo(P))}function v(P,B){P.nodes().forEach(Z=>{let Y=P.node(Z),te=B.node(Z);Y&&(Y.x=te.x,Y.y=te.y,Y.rank=te.rank,B.children(Z).length&&(Y.width=te.width,Y.height=te.height))}),P.edges().forEach(Z=>{let Y=P.edge(Z),te=B.edge(Z);Y.points=te.points,Object.hasOwn(te,"x")&&(Y.x=te.x,Y.y=te.y)}),P.graph().width=B.graph().width,P.graph().height=B.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"},T=["labelpos"];function E(P){let B=new p({multigraph:!0,compound:!0}),Z=U(P.graph());return B.setGraph(Object.assign({},b,G(Z,y),f.pick(Z,x))),P.nodes().forEach(Y=>{let te=U(P.node(Y));const J=G(te,S);Object.keys(k).forEach(ee=>{J[ee]===void 0&&(J[ee]=k[ee])}),B.setNode(Y,J),B.setParent(Y,P.parent(Y))}),P.edges().forEach(Y=>{let te=U(P.edge(Y));B.setEdge(Y,Object.assign({},C,G(te,_),f.pick(te,T)))}),B}function N(P){let B=P.graph();B.ranksep/=2,P.edges().forEach(Z=>{let Y=P.edge(Z);Y.minlen*=2,Y.labelpos.toLowerCase()!=="c"&&(B.rankdir==="TB"||B.rankdir==="BT"?Y.width+=Y.labeloffset:Y.height+=Y.labeloffset)})}function I(P){P.edges().forEach(B=>{let Z=P.edge(B);if(Z.width&&Z.height){let Y=P.node(B.v),J={rank:(P.node(B.w).rank-Y.rank)/2+Y.rank,e:B};f.addDummyNode(P,"edge-proxy",J,"_ep")}})}function A(P){let B=0;P.nodes().forEach(Z=>{let Y=P.node(Z);Y.borderTop&&(Y.minRank=P.node(Y.borderTop).rank,Y.maxRank=P.node(Y.borderBottom).rank,B=Math.max(B,Y.maxRank))}),P.graph().maxRank=B}function R(P){P.nodes().forEach(B=>{let Z=P.node(B);Z.dummy==="edge-proxy"&&(P.edge(Z.e).labelRank=Z.rank,P.removeNode(B))})}function L(P){let B=Number.POSITIVE_INFINITY,Z=0,Y=Number.POSITIVE_INFINITY,te=0,J=P.graph(),ee=J.marginx||0,re=J.marginy||0;function oe(X){let ne=X.x,se=X.y,fe=X.width,ce=X.height;B=Math.min(B,ne-fe/2),Z=Math.max(Z,ne+fe/2),Y=Math.min(Y,se-ce/2),te=Math.max(te,se+ce/2)}P.nodes().forEach(X=>oe(P.node(X))),P.edges().forEach(X=>{let ne=P.edge(X);Object.hasOwn(ne,"x")&&oe(ne)}),B-=ee,Y-=re,P.nodes().forEach(X=>{let ne=P.node(X);ne.x-=B,ne.y-=Y}),P.edges().forEach(X=>{let ne=P.edge(X);ne.points.forEach(se=>{se.x-=B,se.y-=Y}),Object.hasOwn(ne,"x")&&(ne.x-=B),Object.hasOwn(ne,"y")&&(ne.y-=Y)}),J.width=Z-B+ee,J.height=te-Y+re}function M(P){P.edges().forEach(B=>{let Z=P.edge(B),Y=P.node(B.v),te=P.node(B.w),J,ee;Z.points?(J=Z.points[0],ee=Z.points[Z.points.length-1]):(Z.points=[],J=te,ee=Y),Z.points.unshift(f.intersectRect(Y,J)),Z.points.push(f.intersectRect(te,ee))})}function F(P){P.edges().forEach(B=>{let Z=P.edge(B);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(P){P.edges().forEach(B=>{let Z=P.edge(B);Z.reversed&&Z.points.reverse()})}function z(P){P.nodes().forEach(B=>{if(P.children(B).length){let Z=P.node(B),Y=P.node(Z.borderTop),te=P.node(Z.borderBottom),J=P.node(Z.borderLeft[Z.borderLeft.length-1]),ee=P.node(Z.borderRight[Z.borderRight.length-1]);Z.width=Math.abs(ee.x-J.x),Z.height=Math.abs(te.y-Y.y),Z.x=J.x+Z.width/2,Z.y=Y.y+Z.height/2}}),P.nodes().forEach(B=>{P.node(B).dummy==="border"&&P.removeNode(B)})}function q(P){P.edges().forEach(B=>{if(B.v===B.w){var Z=P.node(B.v);Z.selfEdges||(Z.selfEdges=[]),Z.selfEdges.push({e:B,label:P.edge(B)}),P.removeEdge(B)}})}function V(P){var B=f.buildLayerMatrix(P);B.forEach(Z=>{var Y=0;Z.forEach((te,J)=>{var ee=P.node(te);ee.order=J+Y,(ee.selfEdges||[]).forEach(re=>{f.addDummyNode(P,"selfedge",{width:re.label.width,height:re.label.height,rank:ee.rank,order:J+ ++Y,e:re.e,label:re.label},"_se")}),delete ee.selfEdges})})}function D(P){P.nodes().forEach(B=>{var Z=P.node(B);if(Z.dummy==="selfedge"){var Y=P.node(Z.e.v),te=Y.x+Y.width/2,J=Y.y,ee=Z.x-te,re=Y.height/2;P.setEdge(Z.e,Z.label),P.removeNode(B),Z.label.points=[{x:te+2*ee/3,y:J-re},{x:te+5*ee/6,y:J-re},{x:te+ee,y:J},{x:te+5*ee/6,y:J+re},{x:te+2*ee/3,y:J+re}],Z.label.x=Z.x,Z.label.y=Z.y}})}function G(P,B){return f.mapValues(f.pick(P,B),Number)}function U(P){var B={};return P&&Object.entries(P).forEach(([Z,Y])=>{typeof Z=="string"&&(Z=Z.toLowerCase()),B[Z]=Y}),B}return une}var dne,A7e;function KWn(){if(A7e)return dne;A7e=1;let e=$l(),t=Vg().Graph;dne={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 dne}var fne,R7e;function XWn(){return R7e||(R7e=1,fne="1.1.8"),fne}var pne,P7e;function JWn(){return P7e||(P7e=1,pne={graphlib:Vg(),layout:YWn(),debug:KWn(),util:{time:$l().time,notime:$l().notime},version:XWn()}),pne}var eZn=JWn();const $7e=Vl(eZn);function Gl(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=Gl(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var tZn={value:()=>{}};function bW(){for(var e=0,t=arguments.length,n={},r;e<t;++e){if(!(r=arguments[e]+"")||r in n||/[\s.]/.test(r))throw new Error("illegal type: "+r);n[r]=[]}return new n9(n)}function n9(e){this._=e}function nZn(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",s=n.indexOf(".");if(s>=0&&(r=n.slice(s+1),n=n.slice(0,s)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}n9.prototype=bW.prototype={constructor:n9,on:function(e,t){var n=this._,r=nZn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=rZn(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]=M7e(n[s],e.name,t);else if(t==null)for(s in n)n[s]=M7e(n[s],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new n9(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),r=0,s,a;r<s;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(a=this._[e],r=0,s=a.length;r<s;++r)a[r].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],s=0,a=r.length;s<a;++s)r[s].value.apply(t,n)}};function rZn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function M7e(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=tZn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Cve="http://www.w3.org/1999/xhtml";const D7e={svg:"http://www.w3.org/2000/svg",xhtml:Cve,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function xW(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),D7e.hasOwnProperty(t)?{space:D7e[t],local:e}:e}function sZn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Cve&&t.documentElement.namespaceURI===Cve?t.createElement(e):t.createElementNS(n,e)}}function aZn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function yOt(e){var t=xW(e);return(t.local?aZn:sZn)(t)}function iZn(){}function EOe(e){return e==null?iZn:function(){return this.querySelector(e)}}function oZn(e){typeof e!="function"&&(e=EOe(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 eh(r,this._parents)}function lZn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function cZn(){return[]}function bOt(e){return e==null?cZn:function(){return this.querySelectorAll(e)}}function uZn(e){return function(){return lZn(e.apply(this,arguments))}}function dZn(e){typeof e=="function"?e=uZn(e):e=bOt(e);for(var t=this._groups,n=t.length,r=[],s=[],a=0;a<n;++a)for(var i=t[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&(r.push(e.call(c,c.__data__,u,i)),s.push(c));return new eh(r,s)}function xOt(e){return function(){return this.matches(e)}}function wOt(e){return function(t){return t.matches(e)}}var fZn=Array.prototype.find;function pZn(e){return function(){return fZn.call(this.children,e)}}function hZn(){return this.firstElementChild}function mZn(e){return this.select(e==null?hZn:pZn(typeof e=="function"?e:wOt(e)))}var gZn=Array.prototype.filter;function vZn(){return Array.from(this.children)}function yZn(e){return function(){return gZn.call(this.children,e)}}function bZn(e){return this.selectAll(e==null?vZn:yZn(typeof e=="function"?e:wOt(e)))}function xZn(e){typeof e!="function"&&(e=xOt(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 eh(r,this._parents)}function SOt(e){return new Array(e.length)}function wZn(){return new eh(this._enter||this._groups.map(SOt),this._parents)}function rU(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}rU.prototype={constructor:rU,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}};function SZn(e){return function(){return e}}function kZn(e,t,n,r,s,a){for(var i=0,l,c=t.length,u=a.length;i<u;++i)(l=t[i])?(l.__data__=a[i],r[i]=l):n[i]=new rU(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function OZn(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 rU(e,a[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(p[l])===c&&(s[l]=c)}function _Zn(e){return e.__data__}function CZn(e,t){if(!arguments.length)return Array.from(this,_Zn);var n=t?OZn:kZn,r=this._parents,s=this._groups;typeof e!="function"&&(e=SZn(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=EZn(e.call(d,d&&d.__data__,u,r)),m=h.length,v=l[u]=new Array(m),y=i[u]=new Array(m),b=c[u]=new Array(p);n(d,f,v,y,b,h,t);for(var x=0,S=0,k,_;x<m;++x)if(k=v[x]){for(x>=S&&(S=x+1);!(_=y[S])&&++S<m;);k._next=_||null}}return i=new eh(i,r),i._enter=l,i._exit=c,i}function EZn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function TZn(){return new eh(this._exit||this._groups.map(SOt),this._parents)}function jZn(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 NZn(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 eh(l,this._parents)}function IZn(){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 AZn(e){e||(e=RZn);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 eh(s,this._parents).order()}function RZn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function PZn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function $Zn(){return Array.from(this)}function MZn(){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 DZn(){let e=0;for(const t of this)++e;return e}function LZn(){return!this.node()}function FZn(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 zZn(e){return function(){this.removeAttribute(e)}}function BZn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function UZn(e,t){return function(){this.setAttribute(e,t)}}function qZn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function VZn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function HZn(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 WZn(e,t){var n=xW(e);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((t==null?n.local?BZn:zZn:typeof t=="function"?n.local?HZn:VZn:n.local?qZn:UZn)(n,t))}function kOt(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function ZZn(e){return function(){this.style.removeProperty(e)}}function GZn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function QZn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function YZn(e,t,n){return arguments.length>1?this.each((t==null?ZZn:typeof t=="function"?QZn:GZn)(e,t,n??"")):iN(this.node(),e)}function iN(e,t){return e.style.getPropertyValue(t)||kOt(e).getComputedStyle(e,null).getPropertyValue(t)}function KZn(e){return function(){delete this[e]}}function XZn(e,t){return function(){this[e]=t}}function JZn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function eGn(e,t){return arguments.length>1?this.each((t==null?KZn:typeof t=="function"?JZn:XZn)(e,t)):this.node()[e]}function OOt(e){return e.trim().split(/^|\s+/)}function TOe(e){return e.classList||new _Ot(e)}function _Ot(e){this._node=e,this._names=OOt(e.getAttribute("class")||"")}_Ot.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 COt(e,t){for(var n=TOe(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function EOt(e,t){for(var n=TOe(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function tGn(e){return function(){COt(this,e)}}function nGn(e){return function(){EOt(this,e)}}function rGn(e,t){return function(){(t.apply(this,arguments)?COt:EOt)(this,e)}}function sGn(e,t){var n=OOt(e+"");if(arguments.length<2){for(var r=TOe(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?rGn:t?tGn:nGn)(n,t))}function aGn(){this.textContent=""}function iGn(e){return function(){this.textContent=e}}function oGn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function lGn(e){return arguments.length?this.each(e==null?aGn:(typeof e=="function"?oGn:iGn)(e)):this.node().textContent}function cGn(){this.innerHTML=""}function uGn(e){return function(){this.innerHTML=e}}function dGn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function fGn(e){return arguments.length?this.each(e==null?cGn:(typeof e=="function"?dGn:uGn)(e)):this.node().innerHTML}function pGn(){this.nextSibling&&this.parentNode.appendChild(this)}function hGn(){return this.each(pGn)}function mGn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function gGn(){return this.each(mGn)}function vGn(e){var t=typeof e=="function"?e:yOt(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function yGn(){return null}function bGn(e,t){var n=typeof e=="function"?e:yOt(e),r=t==null?yGn:typeof t=="function"?t:EOe(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function xGn(){var e=this.parentNode;e&&e.removeChild(this)}function wGn(){return this.each(xGn)}function SGn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function kGn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function OGn(e){return this.select(e?kGn:SGn)}function _Gn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function CGn(e){return function(t){e.call(this,t,this.__data__)}}function EGn(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 TGn(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 jGn(e,t,n){return function(){var r=this.__on,s,a=CGn(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 NGn(e,t,n){var r=EGn(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?jGn:TGn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function TOt(e,t,n){var r=kOt(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 IGn(e,t){return function(){return TOt(this,e,t)}}function AGn(e,t){return function(){return TOt(this,e,t.apply(this,arguments))}}function RGn(e,t){return this.each((typeof t=="function"?AGn:IGn)(e,t))}function*PGn(){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 jOt=[null];function eh(e,t){this._groups=e,this._parents=t}function a4(){return new eh([[document.documentElement]],jOt)}function $Gn(){return this}eh.prototype=a4.prototype={constructor:eh,select:oZn,selectAll:dZn,selectChild:mZn,selectChildren:bZn,filter:xZn,data:CZn,enter:wZn,exit:TZn,join:jZn,merge:NZn,selection:$Gn,order:IZn,sort:AZn,call:PZn,nodes:$Zn,node:MZn,size:DZn,empty:LZn,each:FZn,attr:WZn,style:YZn,property:eGn,classed:sGn,text:lGn,html:fGn,raise:hGn,lower:gGn,append:vGn,insert:bGn,remove:wGn,clone:OGn,datum:_Gn,on:NGn,dispatch:RGn,[Symbol.iterator]:PGn};function Tp(e){return typeof e=="string"?new eh([[document.querySelector(e)]],[document.documentElement]):new eh([[e]],jOt)}function MGn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function hg(e,t){if(e=MGn(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 DGn={passive:!1},FM={capture:!0,passive:!1};function hne(e){e.stopImmediatePropagation()}function cj(e){e.preventDefault(),e.stopImmediatePropagation()}function NOt(e){var t=e.document.documentElement,n=Tp(e).on("dragstart.drag",cj,FM);"onselectstart"in t?n.on("selectstart.drag",cj,FM):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function IOt(e,t){var n=e.document.documentElement,r=Tp(e).on("dragstart.drag",null);t&&(r.on("click.drag",cj,FM),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 CF=e=>()=>e;function Eve(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}})}Eve.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function LGn(e){return!e.ctrlKey&&!e.button}function FGn(){return this.parentNode}function zGn(e,t){return t??{x:e.x,y:e.y}}function BGn(){return navigator.maxTouchPoints||"ontouchstart"in this}function AOt(){var e=LGn,t=FGn,n=zGn,r=BGn,s={},a=bW("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,DGn).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&&(Tp(k.view).on("mousemove.drag",m,FM).on("mouseup.drag",v,FM),NOt(k.view),hne(k),u=!1,l=k.clientX,c=k.clientY,C("start",k))}}function m(k){if(cj(k),!u){var _=k.clientX-l,C=k.clientY-c;u=_*_+C*C>f}s.mouse("drag",k)}function v(k){Tp(k.view).on("mousemove.drag mouseup.drag",null),IOt(k.view,u),cj(k),s.mouse("end",k)}function y(k,_){if(e.call(this,k,_)){var C=k.changedTouches,T=t.call(this,k,_),E=C.length,N,I;for(N=0;N<E;++N)(I=S(this,T,k,_,C[N].identifier,C[N]))&&(hne(k),I("start",k,C[N]))}}function b(k){var _=k.changedTouches,C=_.length,T,E;for(T=0;T<C;++T)(E=s[_[T].identifier])&&(cj(k),E("drag",k,_[T]))}function x(k){var _=k.changedTouches,C=_.length,T,E;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),T=0;T<C;++T)(E=s[_[T].identifier])&&(hne(k),E("end",k,_[T]))}function S(k,_,C,T,E,N){var I=a.copy(),A=hg(N||C,_),R,L,M;if((M=n.call(k,new Eve("beforestart",{sourceEvent:C,target:p,identifier:E,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),T))!=null)return R=M.x-A[0]||0,L=M.y-A[1]||0,function F(H,z,q){var V=A,D;switch(H){case"start":s[E]=F,D=i++;break;case"end":delete s[E],--i;case"drag":A=hg(q||z,_),D=i;break}I.call(H,k,new Eve(H,{sourceEvent:z,subject:M,target:p,identifier:E,active:D,x:A[0]+R,y:A[1]+L,dx:A[0]-V[0],dy:A[1]-V[1],dispatch:I}),T)}}return p.filter=function(k){return arguments.length?(e=typeof k=="function"?k:CF(!!k),p):e},p.container=function(k){return arguments.length?(t=typeof k=="function"?k:CF(k),p):t},p.subject=function(k){return arguments.length?(n=typeof k=="function"?k:CF(k),p):n},p.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:CF(!!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 jOe(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function ROt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function i4(){}var zM=.7,sU=1/zM,uj="\\s*([+-]?\\d+)\\s*",BM="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",uy="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",UGn=/^#([0-9a-f]{3,8})$/,qGn=new RegExp(`^rgb\\(${uj},${uj},${uj}\\)$`),VGn=new RegExp(`^rgb\\(${uy},${uy},${uy}\\)$`),HGn=new RegExp(`^rgba\\(${uj},${uj},${uj},${BM}\\)$`),WGn=new RegExp(`^rgba\\(${uy},${uy},${uy},${BM}\\)$`),ZGn=new RegExp(`^hsl\\(${BM},${uy},${uy}\\)$`),GGn=new RegExp(`^hsla\\(${BM},${uy},${uy},${BM}\\)$`),L7e={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};jOe(i4,e_,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:F7e,formatHex:F7e,formatHex8:QGn,formatHsl:YGn,formatRgb:z7e,toString:z7e});function F7e(){return this.rgb().formatHex()}function QGn(){return this.rgb().formatHex8()}function YGn(){return POt(this).formatHsl()}function z7e(){return this.rgb().formatRgb()}function e_(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=UGn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?B7e(t):n===3?new Tf(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=qGn.exec(e))?new Tf(t[1],t[2],t[3],1):(t=VGn.exec(e))?new Tf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=HGn.exec(e))?EF(t[1],t[2],t[3],t[4]):(t=WGn.exec(e))?EF(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=ZGn.exec(e))?V7e(t[1],t[2]/100,t[3]/100,1):(t=GGn.exec(e))?V7e(t[1],t[2]/100,t[3]/100,t[4]):L7e.hasOwnProperty(e)?B7e(L7e[e]):e==="transparent"?new Tf(NaN,NaN,NaN,0):null}function B7e(e){return new Tf(e>>16&255,e>>8&255,e&255,1)}function EF(e,t,n,r){return r<=0&&(e=t=n=NaN),new Tf(e,t,n,r)}function KGn(e){return e instanceof i4||(e=e_(e)),e?(e=e.rgb(),new Tf(e.r,e.g,e.b,e.opacity)):new Tf}function Tve(e,t,n,r){return arguments.length===1?KGn(e):new Tf(e,t,n,r??1)}function Tf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}jOe(Tf,Tve,ROt(i4,{brighter(e){return e=e==null?sU:Math.pow(sU,e),new Tf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?zM:Math.pow(zM,e),new Tf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Tf(lO(this.r),lO(this.g),lO(this.b),aU(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:U7e,formatHex:U7e,formatHex8:XGn,formatRgb:q7e,toString:q7e}));function U7e(){return`#${Bk(this.r)}${Bk(this.g)}${Bk(this.b)}`}function XGn(){return`#${Bk(this.r)}${Bk(this.g)}${Bk(this.b)}${Bk((isNaN(this.opacity)?1:this.opacity)*255)}`}function q7e(){const e=aU(this.opacity);return`${e===1?"rgb(":"rgba("}${lO(this.r)}, ${lO(this.g)}, ${lO(this.b)}${e===1?")":`, ${e})`}`}function aU(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function lO(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Bk(e){return e=lO(e),(e<16?"0":"")+e.toString(16)}function V7e(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new wg(e,t,n,r)}function POt(e){if(e instanceof wg)return new wg(e.h,e.s,e.l,e.opacity);if(e instanceof i4||(e=e_(e)),!e)return new wg;if(e instanceof wg)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 wg(i,l,c,e.opacity)}function JGn(e,t,n,r){return arguments.length===1?POt(e):new wg(e,t,n,r??1)}function wg(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}jOe(wg,JGn,ROt(i4,{brighter(e){return e=e==null?sU:Math.pow(sU,e),new wg(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?zM:Math.pow(zM,e),new wg(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 Tf(mne(e>=240?e-240:e+120,s,r),mne(e,s,r),mne(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new wg(H7e(this.h),TF(this.s),TF(this.l),aU(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=aU(this.opacity);return`${e===1?"hsl(":"hsla("}${H7e(this.h)}, ${TF(this.s)*100}%, ${TF(this.l)*100}%${e===1?")":`, ${e})`}`}}));function H7e(e){return e=(e||0)%360,e<0?e+360:e}function TF(e){return Math.max(0,Math.min(1,e||0))}function mne(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 NOe=e=>()=>e;function eQn(e,t){return function(n){return e+n*t}}function tQn(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 nQn(e){return(e=+e)==1?$Ot:function(t,n){return n-t?tQn(t,n,e):NOe(isNaN(t)?n:t)}}function $Ot(e,t){var n=t-e;return n?eQn(e,n):NOe(isNaN(e)?t:e)}const iU=(function e(t){var n=nQn(t);function r(s,a){var i=n((s=Tve(s)).r,(a=Tve(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=$Ot(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 rQn(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 sQn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function aQn(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]=gx(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 iQn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function gg(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function oQn(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]=gx(e[s],t[s]):r[s]=t[s];return function(a){for(s in n)r[s]=n[s](a);return r}}var jve=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,gne=new RegExp(jve.source,"g");function lQn(e){return function(){return e}}function cQn(e){return function(t){return e(t)+""}}function MOt(e,t){var n=jve.lastIndex=gne.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=jve.exec(e))&&(s=gne.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:gg(r,s)})),n=gne.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?cQn(c[0].x):lQn(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 gx(e,t){var n=typeof t,r;return t==null||n==="boolean"?NOe(t):(n==="number"?gg:n==="string"?(r=e_(t))?(t=r,iU):MOt:t instanceof e_?iU:t instanceof Date?iQn:sQn(t)?rQn:Array.isArray(t)?aQn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?oQn:gg)(e,t)}function IOe(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var W7e=180/Math.PI,Nve={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function DOt(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)*W7e,skewX:Math.atan(c)*W7e,scaleX:i,scaleY:l}}var jF;function uQn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Nve:DOt(t.a,t.b,t.c,t.d,t.e,t.f)}function dQn(e){return e==null||(jF||(jF=document.createElementNS("http://www.w3.org/2000/svg","g")),jF.setAttribute("transform",e),!(e=jF.transform.baseVal.consolidate()))?Nve:(e=e.matrix,DOt(e.a,e.b,e.c,e.d,e.e,e.f))}function LOt(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 v=h.push("translate(",null,t,null,n);m.push({i:v-4,x:gg(u,f)},{i:v-2,x:gg(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:gg(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:gg(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,p,h,m){if(u!==f||d!==p){var v=h.push(s(h)+"scale(",null,",",null,")");m.push({i:v-4,x:gg(u,f)},{i:v-2,x:gg(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,v=p.length,y;++m<v;)f[(y=p[m]).i]=y.x(h);return f.join("")}}}var fQn=LOt(uQn,"px, ","px)","deg)"),pQn=LOt(dQn,", ",")",")"),hQn=1e-12;function Z7e(e){return((e=Math.exp(e))+1/e)/2}function mQn(e){return((e=Math.exp(e))-1/e)/2}function gQn(e){return((e=Math.exp(2*e))-1)/(e+1)}const r9=(function e(t,n,r){function s(a,i){var l=a[0],c=a[1],u=a[2],d=i[0],f=i[1],p=i[2],h=d-l,m=f-c,v=h*h+m*m,y,b;if(v<hQn)b=Math.log(p/u)/t,y=function(T){return[l+T*h,c+T*m,u*Math.exp(t*T*b)]};else{var x=Math.sqrt(v),S=(p*p-u*u+r*v)/(2*u*n*x),k=(p*p-u*u-r*v)/(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(T){var E=T*b,N=Z7e(_),I=u/(n*x)*(N*gQn(t*E+_)-mQn(_));return[l+I*h,c+I*m,u*N/Z7e(t*E+_)]}}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 vQn(e,t){t===void 0&&(t=e,e=gx);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 oN=0,t$=0,LR=0,FOt=1e3,oU,n$,lU=0,t_=0,wW=0,UM=typeof performance=="object"&&performance.now?performance:Date,zOt=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function AOe(){return t_||(zOt(yQn),t_=UM.now()+wW)}function yQn(){t_=0}function cU(){this._call=this._time=this._next=null}cU.prototype=BOt.prototype={constructor:cU,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?AOe():+n)+(t==null?0:+t),!this._next&&n$!==this&&(n$?n$._next=this:oU=this,n$=this),this._call=e,this._time=n,Ive()},stop:function(){this._call&&(this._call=null,this._time=1/0,Ive())}};function BOt(e,t,n){var r=new cU;return r.restart(e,t,n),r}function bQn(){AOe(),++oN;for(var e=oU,t;e;)(t=t_-e._time)>=0&&e._call.call(void 0,t),e=e._next;--oN}function G7e(){t_=(lU=UM.now())+wW,oN=t$=0;try{bQn()}finally{oN=0,wQn(),t_=0}}function xQn(){var e=UM.now(),t=e-lU;t>FOt&&(wW-=t,lU=e)}function wQn(){for(var e,t=oU,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:oU=n);n$=e,Ive(r)}function Ive(e){if(!oN){t$&&(t$=clearTimeout(t$));var t=e-t_;t>24?(e<1/0&&(t$=setTimeout(G7e,e-UM.now()-wW)),LR&&(LR=clearInterval(LR))):(LR||(lU=UM.now(),LR=setInterval(xQn,FOt)),oN=1,zOt(G7e))}}function Q7e(e,t,n){var r=new cU;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var SQn=bW("start","end","cancel","interrupt"),kQn=[],UOt=0,Y7e=1,Ave=2,s9=3,K7e=4,Rve=5,a9=6;function SW(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;OQn(e,n,{name:t,index:r,group:s,on:SQn,tween:kQn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:UOt})}function ROe(e,t){var n=Jg(e,t);if(n.state>UOt)throw new Error("too late; already scheduled");return n}function Uy(e,t){var n=Jg(e,t);if(n.state>s9)throw new Error("too late; already running");return n}function Jg(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function OQn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=BOt(a,0,n.time);function a(u){n.state=Y7e,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!==Y7e)return c();for(d in r)if(h=r[d],h.name===n.name){if(h.state===s9)return Q7e(i);h.state===K7e?(h.state=a9,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete r[d]):+d<t&&(h.state=a9,h.timer.stop(),h.on.call("cancel",e,e.__data__,h.index,h.group),delete r[d])}if(Q7e(function(){n.state===s9&&(n.state=K7e,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Ave,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Ave){for(n.state=s9,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=Rve,1),f=-1,p=s.length;++f<p;)s[f].call(e,d);n.state===Rve&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=a9,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function i9(e,t){var n=e.__transition,r,s,a=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((r=n[i]).name!==t){a=!1;continue}s=r.state>Ave&&r.state<Rve,r.state=a9,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function _Qn(e){return this.each(function(){i9(this,e)})}function CQn(e,t){var n,r;return function(){var s=Uy(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 EQn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=Uy(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 TQn(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Jg(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?CQn:EQn)(n,e,t))}function POe(e,t,n){var r=e._id;return e.each(function(){var s=Uy(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return Jg(s,r).value[t]}}function qOt(e,t){var n;return(typeof t=="number"?gg:t instanceof e_?iU:(n=e_(t))?(t=n,iU):MOt)(e,t)}function jQn(e){return function(){this.removeAttribute(e)}}function NQn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function IQn(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 AQn(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 RQn(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 PQn(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 $Qn(e,t){var n=xW(e),r=n==="transform"?pQn:qOt;return this.attrTween(e,typeof t=="function"?(n.local?PQn:RQn)(n,r,POe(this,"attr."+e,t)):t==null?(n.local?NQn:jQn)(n):(n.local?AQn:IQn)(n,r,t))}function MQn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function DQn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function LQn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&DQn(e,a)),n}return s._value=t,s}function FQn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&MQn(e,a)),n}return s._value=t,s}function zQn(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(t==null)return this.tween(n,null);if(typeof t!="function")throw new Error;var r=xW(e);return this.tween(n,(r.local?LQn:FQn)(r,t))}function BQn(e,t){return function(){ROe(this,e).delay=+t.apply(this,arguments)}}function UQn(e,t){return t=+t,function(){ROe(this,e).delay=t}}function qQn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?BQn:UQn)(t,e)):Jg(this.node(),t).delay}function VQn(e,t){return function(){Uy(this,e).duration=+t.apply(this,arguments)}}function HQn(e,t){return t=+t,function(){Uy(this,e).duration=t}}function WQn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?VQn:HQn)(t,e)):Jg(this.node(),t).duration}function ZQn(e,t){if(typeof t!="function")throw new Error;return function(){Uy(this,e).ease=t}}function GQn(e){var t=this._id;return arguments.length?this.each(ZQn(t,e)):Jg(this.node(),t).ease}function QQn(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Uy(this,e).ease=n}}function YQn(e){if(typeof e!="function")throw new Error;return this.each(QQn(this._id,e))}function KQn(e){typeof e!="function"&&(e=xOt(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 Mx(r,this._parents,this._name,this._id)}function XQn(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 Mx(i,this._parents,this._name,this._id)}function JQn(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 eYn(e,t,n){var r,s,a=JQn(t)?ROe:Uy;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function tYn(e,t){var n=this._id;return arguments.length<2?Jg(this.node(),n).on.on(e):this.each(eYn(n,e,t))}function nYn(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function rYn(){return this.on("end.remove",nYn(this._id))}function sYn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=EOe(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,SW(u[p],t,n,p,u,Jg(d,n)));return new Mx(a,this._parents,t,n)}function aYn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=bOt(e));for(var r=this._groups,s=r.length,a=[],i=[],l=0;l<s;++l)for(var c=r[l],u=c.length,d,f=0;f<u;++f)if(d=c[f]){for(var p=e.call(d,d.__data__,f,c),h,m=Jg(d,n),v=0,y=p.length;v<y;++v)(h=p[v])&&SW(h,t,n,v,p,m);a.push(p),i.push(d)}return new Mx(a,i,t,n)}var iYn=a4.prototype.constructor;function oYn(){return new iYn(this._groups,this._parents)}function lYn(e,t){var n,r,s;return function(){var a=iN(this,e),i=(this.style.removeProperty(e),iN(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function VOt(e){return function(){this.style.removeProperty(e)}}function cYn(e,t,n){var r,s=n+"",a;return function(){var i=iN(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function uYn(e,t,n){var r,s,a;return function(){var i=iN(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),iN(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function dYn(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=Uy(this,e),u=c.on,d=c.value[a]==null?l||(l=VOt(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function fYn(e,t,n){var r=(e+="")=="transform"?fQn:qOt;return t==null?this.styleTween(e,lYn(e,r)).on("end.style."+e,VOt(e)):typeof t=="function"?this.styleTween(e,uYn(e,r,POe(this,"style."+e,t))).each(dYn(this._id,e)):this.styleTween(e,cYn(e,r,t),n).on("end.style."+e,null)}function pYn(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function hYn(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&pYn(e,i,n)),r}return a._value=t,a}function mYn(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,hYn(e,t,n??""))}function gYn(e){return function(){this.textContent=e}}function vYn(e){return function(){var t=e(this);this.textContent=t??""}}function yYn(e){return this.tween("text",typeof e=="function"?vYn(POe(this,"text",e)):gYn(e==null?"":e+""))}function bYn(e){return function(t){this.textContent=e.call(this,t)}}function xYn(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&bYn(s)),t}return r._value=e,r}function wYn(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,xYn(e))}function SYn(){for(var e=this._name,t=this._id,n=HOt(),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=Jg(c,t);SW(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new Mx(r,this._parents,e,n)}function kYn(){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=Uy(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 OYn=0;function Mx(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function HOt(){return++OYn}var Ob=a4.prototype;Mx.prototype={constructor:Mx,select:sYn,selectAll:aYn,selectChild:Ob.selectChild,selectChildren:Ob.selectChildren,filter:KQn,merge:XQn,selection:oYn,transition:SYn,call:Ob.call,nodes:Ob.nodes,node:Ob.node,size:Ob.size,empty:Ob.empty,each:Ob.each,on:tYn,attr:$Qn,attrTween:zQn,style:fYn,styleTween:mYn,text:yYn,textTween:wYn,remove:rYn,tween:TQn,delay:qQn,duration:WQn,ease:GQn,easeVarying:YQn,end:kYn,[Symbol.iterator]:Ob[Symbol.iterator]};function _Yn(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var CYn={time:null,delay:0,duration:250,ease:_Yn};function EYn(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 TYn(e){var t,n;e instanceof Mx?(t=e._id,e=e._name):(t=HOt(),(n=CYn).time=AOe(),e=e==null?null:e+"");for(var r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&SW(c,e,t,u,i,n||EYn(c,t));return new Mx(r,this._parents,e,t)}a4.prototype.interrupt=_Qn;a4.prototype.transition=TYn;const NF=e=>()=>e;function jYn(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 sx(e,t,n){this.k=e,this.x=t,this.y=n}sx.prototype={constructor:sx,scale:function(e){return e===1?this:new sx(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new sx(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var kW=new sx(1,0,0);WOt.prototype=sx.prototype;function WOt(e){for(;!e.__zoom;)if(!(e=e.parentNode))return kW;return e.__zoom}function vne(e){e.stopImmediatePropagation()}function FR(e){e.preventDefault(),e.stopImmediatePropagation()}function NYn(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function IYn(){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 X7e(){return this.__zoom||kW}function AYn(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function RYn(){return navigator.maxTouchPoints||"ontouchstart"in this}function PYn(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 ZOt(){var e=NYn,t=IYn,n=PYn,r=AYn,s=RYn,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=r9,u=bW("start","zoom","end"),d,f,p,h=500,m=150,v=0,y=10;function b(M){M.property("__zoom",X7e).on("wheel.zoom",E,{passive:!1}).on("mousedown.zoom",N).on("dblclick.zoom",I).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",R).on("touchend.zoom touchcancel.zoom",L).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(M,F,H,z){var q=M.selection?M.selection():M;q.property("__zoom",X7e),M!==q?_(M,F,H,z):q.interrupt().each(function(){C(this,arguments).event(z).start().zoom(null,typeof F=="function"?F.apply(this,arguments):F).end()})},b.scaleBy=function(M,F,H,z){b.scaleTo(M,function(){var q=this.__zoom.k,V=typeof F=="function"?F.apply(this,arguments):F;return q*V},H,z)},b.scaleTo=function(M,F,H,z){b.transform(M,function(){var q=t.apply(this,arguments),V=this.__zoom,D=H==null?k(q):typeof H=="function"?H.apply(this,arguments):H,G=V.invert(D),U=typeof F=="function"?F.apply(this,arguments):F;return n(S(x(V,U),D,G),q,i)},H,z)},b.translateBy=function(M,F,H,z){b.transform(M,function(){return n(this.__zoom.translate(typeof F=="function"?F.apply(this,arguments):F,typeof H=="function"?H.apply(this,arguments):H),t.apply(this,arguments),i)},null,z)},b.translateTo=function(M,F,H,z,q){b.transform(M,function(){var V=t.apply(this,arguments),D=this.__zoom,G=z==null?k(V):typeof z=="function"?z.apply(this,arguments):z;return n(kW.translate(G[0],G[1]).scale(D.k).translate(typeof F=="function"?-F.apply(this,arguments):-F,typeof H=="function"?-H.apply(this,arguments):-H),V,i)},z,q)};function x(M,F){return F=Math.max(a[0],Math.min(a[1],F)),F===M.k?M:new sx(F,M.x,M.y)}function S(M,F,H){var z=F[0]-H[0]*M.k,q=F[1]-H[1]*M.k;return z===M.x&&q===M.y?M:new sx(M.k,z,q)}function k(M){return[(+M[0][0]+ +M[1][0])/2,(+M[0][1]+ +M[1][1])/2]}function _(M,F,H,z){M.on("start.zoom",function(){C(this,arguments).event(z).start()}).on("interrupt.zoom end.zoom",function(){C(this,arguments).event(z).end()}).tween("zoom",function(){var q=this,V=arguments,D=C(q,V).event(z),G=t.apply(q,V),U=H==null?k(G):typeof H=="function"?H.apply(q,V):H,P=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),B=q.__zoom,Z=typeof F=="function"?F.apply(q,V):F,Y=c(B.invert(U).concat(P/B.k),Z.invert(U).concat(P/Z.k));return function(te){if(te===1)te=Z;else{var J=Y(te),ee=P/J[2];te=new sx(ee,U[0]-J[0]*ee,U[1]-J[1]*ee)}D.zoom(null,te)}})}function C(M,F,H){return!H&&M.__zooming||new T(M,F)}function T(M,F){this.that=M,this.args=F,this.active=0,this.sourceEvent=null,this.extent=t.apply(M,F),this.taps=0}T.prototype={event:function(M){return M&&(this.sourceEvent=M),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(M,F){return this.mouse&&M!=="mouse"&&(this.mouse[1]=F.invert(this.mouse[0])),this.touch0&&M!=="touch"&&(this.touch0[1]=F.invert(this.touch0[0])),this.touch1&&M!=="touch"&&(this.touch1[1]=F.invert(this.touch1[0])),this.that.__zoom=F,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(M){var F=Tp(this.that).datum();u.call(M,this.that,new jYn(M,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),F)}};function E(M,...F){if(!e.apply(this,arguments))return;var H=C(this,F).event(M),z=this.__zoom,q=Math.max(a[0],Math.min(a[1],z.k*Math.pow(2,r.apply(this,arguments)))),V=hg(M);if(H.wheel)(H.mouse[0][0]!==V[0]||H.mouse[0][1]!==V[1])&&(H.mouse[1]=z.invert(H.mouse[0]=V)),clearTimeout(H.wheel);else{if(z.k===q)return;H.mouse=[V,z.invert(V)],i9(this),H.start()}FR(M),H.wheel=setTimeout(D,m),H.zoom("mouse",n(S(x(z,q),H.mouse[0],H.mouse[1]),H.extent,i));function D(){H.wheel=null,H.end()}}function N(M,...F){if(p||!e.apply(this,arguments))return;var H=M.currentTarget,z=C(this,F,!0).event(M),q=Tp(M.view).on("mousemove.zoom",U,!0).on("mouseup.zoom",P,!0),V=hg(M,H),D=M.clientX,G=M.clientY;NOt(M.view),vne(M),z.mouse=[V,this.__zoom.invert(V)],i9(this),z.start();function U(B){if(FR(B),!z.moved){var Z=B.clientX-D,Y=B.clientY-G;z.moved=Z*Z+Y*Y>v}z.event(B).zoom("mouse",n(S(z.that.__zoom,z.mouse[0]=hg(B,H),z.mouse[1]),z.extent,i))}function P(B){q.on("mousemove.zoom mouseup.zoom",null),IOt(B.view,z.moved),FR(B),z.event(B).end()}}function I(M,...F){if(e.apply(this,arguments)){var H=this.__zoom,z=hg(M.changedTouches?M.changedTouches[0]:M,this),q=H.invert(z),V=H.k*(M.shiftKey?.5:2),D=n(S(x(H,V),z,q),t.apply(this,F),i);FR(M),l>0?Tp(this).transition().duration(l).call(_,D,z,M):Tp(this).call(b.transform,D,z,M)}}function A(M,...F){if(e.apply(this,arguments)){var H=M.touches,z=H.length,q=C(this,F,M.changedTouches.length===z).event(M),V,D,G,U;for(vne(M),D=0;D<z;++D)G=H[D],U=hg(G,this),U=[U,this.__zoom.invert(U),G.identifier],q.touch0?!q.touch1&&q.touch0[2]!==U[2]&&(q.touch1=U,q.taps=0):(q.touch0=U,V=!0,q.taps=1+!!d);d&&(d=clearTimeout(d)),V&&(q.taps<2&&(f=U[0],d=setTimeout(function(){d=null},h)),i9(this),q.start())}}function R(M,...F){if(this.__zooming){var H=C(this,F).event(M),z=M.changedTouches,q=z.length,V,D,G,U;for(FR(M),V=0;V<q;++V)D=z[V],G=hg(D,this),H.touch0&&H.touch0[2]===D.identifier?H.touch0[0]=G:H.touch1&&H.touch1[2]===D.identifier&&(H.touch1[0]=G);if(D=H.that.__zoom,H.touch1){var P=H.touch0[0],B=H.touch0[1],Z=H.touch1[0],Y=H.touch1[1],te=(te=Z[0]-P[0])*te+(te=Z[1]-P[1])*te,J=(J=Y[0]-B[0])*J+(J=Y[1]-B[1])*J;D=x(D,Math.sqrt(te/J)),G=[(P[0]+Z[0])/2,(P[1]+Z[1])/2],U=[(B[0]+Y[0])/2,(B[1]+Y[1])/2]}else if(H.touch0)G=H.touch0[0],U=H.touch0[1];else return;H.zoom("touch",n(S(D,G,U),H.extent,i))}}function L(M,...F){if(this.__zooming){var H=C(this,F).event(M),z=M.changedTouches,q=z.length,V,D;for(vne(M),p&&clearTimeout(p),p=setTimeout(function(){p=null},h),V=0;V<q;++V)D=z[V],H.touch0&&H.touch0[2]===D.identifier?delete H.touch0:H.touch1&&H.touch1[2]===D.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&&(D=hg(D,this),Math.hypot(f[0]-D[0],f[1]-D[1])<y)){var G=Tp(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(M){return arguments.length?(r=typeof M=="function"?M:NF(+M),b):r},b.filter=function(M){return arguments.length?(e=typeof M=="function"?M:NF(!!M),b):e},b.touchable=function(M){return arguments.length?(s=typeof M=="function"?M:NF(!!M),b):s},b.extent=function(M){return arguments.length?(t=typeof M=="function"?M:NF([[+M[0][0],+M[0][1]],[+M[1][0],+M[1][1]]]),b):t},b.scaleExtent=function(M){return arguments.length?(a[0]=+M[0],a[1]=+M[1],b):[a[0],a[1]]},b.translateExtent=function(M){return arguments.length?(i[0][0]=+M[0][0],i[1][0]=+M[1][0],i[0][1]=+M[0][1],i[1][1]=+M[1][1],b):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},b.constrain=function(M){return arguments.length?(n=M,b):n},b.duration=function(M){return arguments.length?(l=+M,b):l},b.interpolate=function(M){return arguments.length?(c=M,b):c},b.on=function(){var M=u.on.apply(u,arguments);return M===u?b:M},b.clickDistance=function(M){return arguments.length?(v=(M=+M)*M,b):Math.sqrt(v)},b.tapDistance=function(M){return arguments.length?(y=+M,b):y},b}const ky={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."},qM=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],GOt=["Enter"," ","Escape"],QOt={"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 lN;(function(e){e.Strict="strict",e.Loose="loose"})(lN||(lN={}));var cO;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(cO||(cO={}));var VM;(function(e){e.Partial="partial",e.Full="full"})(VM||(VM={}));const YOt={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var kw;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(kw||(kw={}));var HM;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(HM||(HM={}));var nr;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(nr||(nr={}));const J7e={[nr.Left]:nr.Right,[nr.Right]:nr.Left,[nr.Top]:nr.Bottom,[nr.Bottom]:nr.Top};function KOt(e){return e===null?null:e?"valid":"invalid"}const XOt=e=>"id"in e&&"source"in e&&"target"in e,$Yn=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),$Oe=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),o4=(e,t=[0,0])=>{const{width:n,height:r}=s0(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},MYn=(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):$Oe(s)?s:t.nodeLookup.get(s.id));const l=i?uU(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return OW(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return _W(n)},l4=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},r=!1;return e.forEach(s=>{(t.filter===void 0||t.filter(s))&&(n=OW(n,uU(s)),r=!0)}),r?_W(n):{x:0,y:0,width:0,height:0}},MOe=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...u4(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,v=WM(l,uN(u)),y=(h??0)*(m??0),b=a&&v>0;(!u.internals.handleBounds||b||v>=y||u.dragging)&&c.push(u)}return c},DYn=(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 LYn(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 FYn({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=LYn(e,i),c=l4(l),u=DOe(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 JOt({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",ky.error005());else{const h=l.measured.width,m=l.measured.height;h&&m&&(f=[[c,u],[c+h,u+m]])}else l&&dN(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=dN(f)?n_(t,f,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&a?.("015",ky.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 zYn({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(v=>v.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=DYn(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 cN=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),n_=(e={x:0,y:0},t,n)=>({x:cN(e.x,t[0][0],t[1][0]-(n?.width??0)),y:cN(e.y,t[0][1],t[1][1]-(n?.height??0))});function e_t(e,t,n){const{width:r,height:s}=s0(n),{x:a,y:i}=n.internals.positionAbsolute;return n_(e,[[a,i],[a+r,i+s]],t)}const eBe=(e,t,n)=>e<t?cN(Math.abs(e-t),1,t)/t:e>n?-cN(Math.abs(e-n),1,t)/t:0,t_t=(e,t,n=15,r=40)=>{const s=eBe(e.x,r,t.width-r)*n,a=eBe(e.y,r,t.height-r)*n;return[s,a]},OW=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),Pve=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),_W=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),uN=(e,t=[0,0])=>{const{x:n,y:r}=$Oe(e)?e.internals.positionAbsolute:o4(e,t);return{x:n,y:r,width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}},uU=(e,t=[0,0])=>{const{x:n,y:r}=$Oe(e)?e.internals.positionAbsolute:o4(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)}},n_t=(e,t)=>_W(OW(Pve(e),Pve(t))),WM=(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)},tBe=e=>Eg(e.width)&&Eg(e.height)&&Eg(e.x)&&Eg(e.y),Eg=e=>!isNaN(e)&&isFinite(e),BYn=(e,t)=>{},c4=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),u4=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?c4(l,i):l},dU=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function xE(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 UYn(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=xE(e,n),s=xE(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=xE(e.top??e.y??0,n),s=xE(e.bottom??e.y??0,n),a=xE(e.left??e.x??0,t),i=xE(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 qYn(e,t,n,r,s,a){const{x:i,y:l}=dU(e,[t,n,r]),{x:c,y:u}=dU({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=s-c,f=a-u;return{left:Math.floor(i),top:Math.floor(l),right:Math.floor(d),bottom:Math.floor(f)}}const DOe=(e,t,n,r,s,a)=>{const i=UYn(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=cN(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,v=qYn(e,h,m,d,t,n),y={left:Math.min(v.left-i.left,0),top:Math.min(v.top-i.top,0),right:Math.min(v.right-i.right,0),bottom:Math.min(v.bottom-i.bottom,0)};return{x:h-y.left+y.right,y:m-y.top+y.bottom,zoom:d}},ZM=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function dN(e){return e!=null&&e!=="parent"}function s0(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function r_t(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function s_t(e,t={width:0,height:0},n,r,s){const a={...e},i=r.get(n);if(i){const l=i.origin||s;a.x+=i.internals.positionAbsolute.x-(t.width??0)*l[0],a.y+=i.internals.positionAbsolute.y-(t.height??0)*l[1]}return a}function nBe(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function VYn(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function HYn(e){return{...QOt,...e||{}}}function U$(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=Tg(e),l=u4({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?c4(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const LOe=e=>({width:e.offsetWidth,height:e.offsetHeight}),a_t=e=>e?.getRootNode?.()||window?.document,WYn=["INPUT","SELECT","TEXTAREA"];function i_t(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:WYn.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const o_t=e=>"clientX"in e,Tg=(e,t)=>{const n=o_t(e),r=n?e.clientX:e.touches?.[0].clientX,s=n?e.clientY:e.touches?.[0].clientY;return{x:r-(t?.left??0),y:s-(t?.top??0)}},rBe=(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,...LOe(i)}})};function l_t({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:s,sourceControlY:a,targetControlX:i,targetControlY:l}){const c=e*.125+s*.375+i*.375+n*.125,u=t*.125+a*.375+l*.375+r*.125,d=Math.abs(c-e),f=Math.abs(u-t);return[c,u,d,f]}function IF(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function sBe({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case nr.Left:return[t-IF(t-r,a),n];case nr.Right:return[t+IF(r-t,a),n];case nr.Top:return[t,n-IF(n-s,a)];case nr.Bottom:return[t,n+IF(s-n,a)]}}function FOe({sourceX:e,sourceY:t,sourcePosition:n=nr.Bottom,targetX:r,targetY:s,targetPosition:a=nr.Top,curvature:i=.25}){const[l,c]=sBe({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=sBe({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,p,h,m]=l_t({sourceX:e,sourceY:t,targetX:r,targetY:s,sourceControlX:l,sourceControlY:c,targetControlX:u,targetControlY:d});return[`M${e},${t} C${l},${c} ${u},${d} ${r},${s}`,f,p,h,m]}function c_t({sourceX:e,sourceY:t,targetX:n,targetY:r}){const s=Math.abs(n-e)/2,a=n<e?n+s:n-s,i=Math.abs(r-t)/2,l=r<t?r+i:r-i;return[a,l,s,i]}function ZYn({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 GYn({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=OW(uU(e),uU(t));a.x===a.x2&&(a.x2+=1),a.y===a.y2&&(a.y2+=1);const i={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:r/s[2]};return WM(i,_W(a))>0}const QYn=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,YYn=(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)),KYn=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||QYn;let s;return XOt(e)?s={...e}:s={...e,id:r(e)},YYn(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function u_t({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=c_t({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const aBe={[nr.Left]:{x:-1,y:0},[nr.Right]:{x:1,y:0},[nr.Top]:{x:0,y:-1},[nr.Bottom]:{x:0,y:1}},XYn=({source:e,sourcePosition:t=nr.Bottom,target:n})=>t===nr.Left||t===nr.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},iBe=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function JYn({source:e,sourcePosition:t=nr.Bottom,target:n,targetPosition:r=nr.Top,center:s,offset:a,stepPosition:i}){const l=aBe[t],c=aBe[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=XYn({source:u,sourcePosition:t,target:d}),p=f.x!==0?"x":"y",h=f[p];let m=[],v,y;const b={x:0,y:0},x={x:0,y:0},[,,S,k]=c_t({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[p]*c[p]===-1){p==="x"?(v=s.x??u.x+(d.x-u.x)*i,y=s.y??(u.y+d.y)/2):(v=s.x??(u.x+d.x)/2,y=s.y??u.y+(d.y-u.y)*i);const E=[{x:v,y:u.y},{x:v,y:d.y}],N=[{x:u.x,y},{x:d.x,y}];l[p]===h?m=p==="x"?E:N:m=p==="x"?N:E}else{const E=[{x:u.x,y:d.y}],N=[{x:d.x,y:u.y}];if(p==="x"?m=l.x===h?N:E:m=l.y===h?E:N,t===r){const M=Math.abs(e[p]-n[p]);if(M<=a){const F=Math.min(a-1,a-M);l[p]===h?b[p]=(u[p]>e[p]?-1:1)*F:x[p]=(d[p]>n[p]?-1:1)*F}}if(t!==r){const M=p==="x"?"y":"x",F=l[p]===c[M],H=u[M]>d[M],z=u[M]<d[M];(l[p]===1&&(!F&&H||F&&z)||l[p]!==1&&(!F&&z||F&&H))&&(m=p==="x"?E:N)}const I={x:u.x+b.x,y:u.y+b.y},A={x:d.x+x.x,y:d.y+x.y},R=Math.max(Math.abs(I.x-m[0].x),Math.abs(A.x-m[0].x)),L=Math.max(Math.abs(I.y-m[0].y),Math.abs(A.y-m[0].y));R>=L?(v=(I.x+A.x)/2,y=m[0].y):(v=m[0].x,y=(I.y+A.y)/2)}const _={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],v,y,S,k]}function eKn(e,t,n,r){const s=Math.min(iBe(e,t)/2,iBe(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 $ve({sourceX:e,sourceY:t,sourcePosition:n=nr.Bottom,targetX:r,targetY:s,targetPosition:a=nr.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,p,h,m,v]=JYn({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+=eKn(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,v]}function oBe(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function tKn(e){const{sourceNode:t,targetNode:n}=e;if(!oBe(t)||!oBe(n))return null;const r=t.internals.handleBounds||lBe(t.handles),s=n.internals.handleBounds||lBe(n.handles),a=cBe(r?.source??[],e.sourceHandle),i=cBe(e.connectionMode===lN.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!a||!i)return e.onError?.("008",ky.error008(a?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=a?.position||nr.Bottom,c=i?.position||nr.Top,u=r_(t,a,l),d=r_(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function lBe(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 r_(e,t,n=nr.Left,r=!1){const s=(t?.x??0)+e.internals.positionAbsolute.x,a=(t?.y??0)+e.internals.positionAbsolute.y,{width:i,height:l}=t??s0(e);if(r)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case nr.Top:return{x:s+i/2,y:a};case nr.Right:return{x:s+i,y:a+l/2};case nr.Bottom:return{x:s+i/2,y:a+l};case nr.Left:return{x:s,y:a+l/2}}}function cBe(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function Mve(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function nKn(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=Mve(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 d_t=1e3,rKn=10,zOe={nodeOrigin:[0,0],nodeExtent:qM,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},sKn={...zOe,checkEquality:!0};function BOe(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function aKn(e,t,n){const r=BOe(zOe,n);for(const s of e.values())if(s.parentId)qOe(s,e,t,r);else{const a=o4(s,r.nodeOrigin),i=dN(s.extent)?s.extent:r.nodeExtent,l=n_(a,i,s0(s));s.internals.positionAbsolute=l}}function iKn(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 UOe(e){return e==="manual"}function Dve(e,t,n,r={}){const s=BOe(sKn,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!UOe(s.zIndexMode)?d_t:0;let c=e.length>0,u=!1;t.clear(),n.clear();for(const d of e){let f=i.get(d.id);if(s.checkEquality&&d===f?.internals.userNode)t.set(d.id,f);else{const p=o4(d,s.nodeOrigin),h=dN(d.extent)?d.extent:s.nodeExtent,m=n_(p,h,s0(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:iKn(d,f),z:f_t(d,l,s.zIndexMode),userNode:d}},t.set(d.id,f)}(f.measured===void 0||f.measured.width===void 0||f.measured.height===void 0)&&!f.hidden&&(c=!1),d.parentId&&qOe(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function oKn(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 qOe(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=BOe(zOe,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}oKn(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*rKn),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!UOe(c)?d_t:0,{x:p,y:h,z:m}=lKn(e,d,i,l,f,c),{positionAbsolute:v}=e.internals,y=p!==v.x||h!==v.y;(y||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:p,y:h}:v,z:m}})}function f_t(e,t,n){const r=Eg(e.zIndex)?e.zIndex:0;return UOe(n)?r:r+(e.selected?t:0)}function lKn(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=s0(e),u=o4(e,n),d=dN(e.extent)?n_(u,e.extent,c):u;let f=n_({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=e_t(f,c,t));const p=f_t(e,s,a),h=t.internals.z??0;return{x:f.x,y:f.y,z:h>=p?h+1:p}}function VOe(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??uN(l),u=n_t(c,i.rect);a.set(i.parentId,{expandedRect:u,parent:l})}return a.size>0&&a.forEach(({expandedRect:i,parent:l},c)=>{const u=l.internals.positionAbsolute,d=s0(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)),v=Math.max(d.height,Math.round(i.height)),y=(m-d.width)*f[0],b=(v-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:v+(h?f[1]*h-b:0)}})}),s}function cKn(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 v=LOe(h.nodeElement),y=m.measured.width!==v.width||m.measured.height!==v.height;if(!!(v.width&&v.height&&(y||!m.internals.handleBounds||h.force))){const x=h.nodeElement.getBoundingClientRect(),S=dN(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=e_t(k,v,t.get(m.parentId)):S&&(k=n_(k,S,v));const _={...m,measured:v,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:rBe("source",h.nodeElement,x,f,m.id),target:rBe("target",h.nodeElement,x,f,m.id)}}};t.set(m.id,_),m.parentId&&qOe(_,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,y&&(u.push({id:m.id,type:"dimensions",dimensions:v}),m.expandParent&&m.parentId&&p.push({id:m.id,parentId:m.parentId,rect:uN(_,s)}))}}if(p.length>0){const h=VOe(p,t,n,s);u.push(...h)}return{changes:u,updatedInternals:c}}async function uKn({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 uBe(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 p_t(e,t,n){e.clear(),t.clear();for(const r of n){const{source:s,target:a,sourceHandle:i=null,targetHandle:l=null}=r,c={edgeId:r.id,source:s,target:a,sourceHandle:i,targetHandle:l},u=`${s}-${i}--${a}-${l}`,d=`${a}-${l}--${s}-${i}`;uBe("source",c,d,e,s,i),uBe("target",c,u,e,a,l),t.set(r.id,r)}}function h_t(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:h_t(n,t):!1}function dBe(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 dKn(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!h_t(i,e))&&(i.draggable||t&&typeof i.draggable>"u")){const l=e.get(a);l&&s.set(a,{id:a,position:l.position||{x:0,y:0},distance:{x:n.x-l.internals.positionAbsolute.x,y:n.y-l.internals.positionAbsolute.y},extent:l.extent,parentId:l.parentId,origin:l.origin,expandParent:l.expandParent,internals:{positionAbsolute:l.internals.positionAbsolute||{x:0,y:0}},measured:{width:l.measured.width??0,height:l.measured.height??0}})}return s}function yne({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 fKn({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=c4(a,t);return{x:i.x-a.x,y:i.y-a.y}}function pKn({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,v=null;function y({noDragClassName:x,handleSelector:S,domNode:k,isSelectable:_,nodeId:C,nodeClickDistance:T=0}){p=Tp(k);function E({x:R,y:L}){const{nodeLookup:M,nodeExtent:F,snapGrid:H,snapToGrid:z,nodeOrigin:q,onNodeDrag:V,onSelectionDrag:D,onError:G,updateNodePositions:U}=t();a={x:R,y:L};let P=!1;const B=l.size>1,Z=B&&F?Pve(l4(l)):null,Y=B&&z?fKn({dragItems:l,snapGrid:H,x:R,y:L}):null;for(const[te,J]of l){if(!M.has(te))continue;let ee={x:R-J.distance.x,y:L-J.distance.y};z&&(ee=Y?{x:Math.round(ee.x+Y.x),y:Math.round(ee.y+Y.y)}:c4(ee,H));let re=null;if(B&&F&&!J.extent&&Z){const{positionAbsolute:ne}=J.internals,se=ne.x-Z.x+F[0][0],fe=ne.x+J.measured.width-Z.x2+F[1][0],ce=ne.y-Z.y+F[0][1],xe=ne.y+J.measured.height-Z.y2+F[1][1];re=[[se,ce],[fe,xe]]}const{position:oe,positionAbsolute:X}=JOt({nodeId:te,nextPosition:ee,nodeLookup:M,nodeExtent:re||F,nodeOrigin:q,onError:G});P=P||J.position.x!==oe.x||J.position.y!==oe.y,J.position=oe,J.internals.positionAbsolute=X}if(m=m||P,!!P&&(U(l,!0),v&&(r||V||!C&&D))){const[te,J]=yne({nodeId:C,dragItems:l,nodeLookup:M});r?.(v,l,te,J),V?.(v,te,J),C||D?.(v,J)}}async function N(){if(!d)return;const{transform:R,panBy:L,autoPanSpeed:M,autoPanOnNodeDrag:F}=t();if(!F){c=!1,cancelAnimationFrame(i);return}const[H,z]=t_t(u,d,M);(H!==0||z!==0)&&(a.x=(a.x??0)-H/R[2],a.y=(a.y??0)-z/R[2],await L({x:H,y:z})&&E(a)),i=requestAnimationFrame(N)}function I(R){const{nodeLookup:L,multiSelectionActive:M,nodesDraggable:F,transform:H,snapGrid:z,snapToGrid:q,selectNodesOnDrag:V,onNodeDragStart:D,onSelectionDragStart:G,unselectNodesAndEdges:U}=t();f=!0,(!V||!_)&&!M&&C&&(L.get(C)?.selected||U()),_&&V&&C&&e?.(C);const P=U$(R.sourceEvent,{transform:H,snapGrid:z,snapToGrid:q,containerBounds:d});if(a=P,l=dKn(L,F,P,C),l.size>0&&(n||D||!C&&G)){const[B,Z]=yne({nodeId:C,dragItems:l,nodeLookup:L});n?.(R.sourceEvent,l,B,Z),D?.(R.sourceEvent,B,Z),C||G?.(R.sourceEvent,Z)}}const A=AOt().clickDistance(T).on("start",R=>{const{domNode:L,nodeDragThreshold:M,transform:F,snapGrid:H,snapToGrid:z}=t();d=L?.getBoundingClientRect()||null,h=!1,m=!1,v=R.sourceEvent,M===0&&I(R),a=U$(R.sourceEvent,{transform:F,snapGrid:H,snapToGrid:z,containerBounds:d}),u=Tg(R.sourceEvent,d)}).on("drag",R=>{const{autoPanOnNodeDrag:L,transform:M,snapGrid:F,snapToGrid:H,nodeDragThreshold:z,nodeLookup:q}=t(),V=U$(R.sourceEvent,{transform:M,snapGrid:F,snapToGrid:H,containerBounds:d});if(v=R.sourceEvent,(R.sourceEvent.type==="touchmove"&&R.sourceEvent.touches.length>1||C&&!q.has(C))&&(h=!0),!h){if(!c&&L&&f&&(c=!0,N()),!f){const D=Tg(R.sourceEvent,d),G=D.x-u.x,U=D.y-u.y;Math.sqrt(G*G+U*U)>z&&I(R)}(a.x!==V.xSnapped||a.y!==V.ySnapped)&&l&&f&&(u=Tg(R.sourceEvent,d),E(V))}}).on("end",R=>{if(!(!f||h)&&(c=!1,f=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:L,updateNodePositions:M,onNodeDragStop:F,onSelectionDragStop:H}=t();if(m&&(M(l,!1),m=!1),s||F||!C&&H){const[z,q]=yne({nodeId:C,dragItems:l,nodeLookup:L,dragging:!1});s?.(R.sourceEvent,l,z,q),F?.(R.sourceEvent,z,q),C||H?.(R.sourceEvent,q)}}}).filter(R=>{const L=R.target;return!R.button&&(!x||!dBe(L,`.${x}`,k))&&(!S||dBe(L,S,k))});p.call(A)}function b(){p?.on(".drag",null)}return{update:y,destroy:b}}function hKn(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())WM(s,uN(a))>0&&r.push(a);return r}const mKn=250;function gKn(e,t,n,r){let s=[],a=1/0;const i=hKn(e,n,t+mKn);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}=r_(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 m_t(e,t,n,r,s,a=!1){const i=r.get(e);if(!i)return null;const l=s==="strict"?i.internals.handleBounds?.[t]:[...i.internals.handleBounds?.source??[],...i.internals.handleBounds?.target??[]],c=(n?l?.find(u=>u.id===n):l?.[0])??null;return c&&a?{...c,...r_(i,c,c.position,!0)}:c}function g_t(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function vKn(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const v_t=()=>!0;function yKn(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:v,onConnectEnd:y,isValidConnection:b=v_t,onReconnectEnd:x,updateConnection:S,getTransform:k,getFromHandle:_,autoPanSpeed:C,dragThreshold:T=1,handleDomNode:E}){const N=a_t(e.target);let I=0,A;const{x:R,y:L}=Tg(e),M=g_t(a,E),F=l?.getBoundingClientRect();let H=!1;if(!F||!M)return;const z=m_t(s,M,r,c,t);if(!z)return;let q=Tg(e,F),V=!1,D=null,G=!1,U=null;function P(){if(!d||!F)return;const[oe,X]=t_t(q,F,C);p({x:oe,y:X}),I=requestAnimationFrame(P)}const B={...z,nodeId:s,type:M,position:z.position},Z=c.get(s);let te={inProgress:!0,isValid:null,from:r_(Z,B,nr.Left,!0),fromHandle:B,fromPosition:B.position,fromNode:Z,to:q,toHandle:null,toPosition:J7e[B.position],toNode:null,pointer:q};function J(){H=!0,S(te),m?.(e,{nodeId:s,handleId:r,handleType:M})}T===0&&J();function ee(oe){if(!H){const{x:xe,y:pe}=Tg(oe),we=xe-R,Ne=pe-L;if(!(we*we+Ne*Ne>T*T))return;J()}if(!_()||!B){re(oe);return}const X=k();q=Tg(oe,F),A=gKn(u4(q,X,!1,[1,1]),n,c,B),V||(P(),V=!0);const ne=y_t(oe,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});U=ne.handleDomNode,D=ne.connection,G=vKn(!!A,ne.isValid);const se=c.get(s),fe=se?r_(se,B,nr.Left,!0):te.from,ce={...te,from:fe,isValid:G,to:ne.toHandle&&G?dU({x:ne.toHandle.x,y:ne.toHandle.y},X):q,toHandle:ne.toHandle,toPosition:G&&ne.toHandle?ne.toHandle.position:J7e[B.position],toNode:ne.toHandle?c.get(ne.toHandle.nodeId):null,pointer:q};S(ce),te=ce}function re(oe){if(!("touches"in oe&&oe.touches.length>0)){if(H){(A||U)&&D&&G&&v?.(D);const{inProgress:X,...ne}=te,se={...ne,toPosition:te.toHandle?te.toPosition:null};y?.(oe,se),a&&x?.(oe,se)}h(),cancelAnimationFrame(I),V=!1,G=!1,D=null,U=null,N.removeEventListener("mousemove",ee),N.removeEventListener("mouseup",re),N.removeEventListener("touchmove",ee),N.removeEventListener("touchend",re)}}N.addEventListener("mousemove",ee),N.addEventListener("mouseup",re),N.addEventListener("touchmove",ee),N.addEventListener("touchend",re)}function y_t(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=v_t,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}=Tg(e),v=i.elementFromPoint(h,m),y=v?.classList.contains(`${l}-flow__handle`)?v:p,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){const x=g_t(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 T={source:f?S:r,sourceHandle:f?k:s,target:f?r:S,targetHandle:f?s:k};b.connection=T;const N=_&&C&&(n===lN.Strict?f&&x==="source"||!f&&x==="target":S!==r||k!==s);b.isValid=N&&u(T),b.toHandle=m_t(S,x,k,d,n,!0)}return b}const Lve={onPointerDown:yKn,isValid:y_t};function bKn({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Tp(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&&ZM()?10:1,C=-S.sourceEvent.deltaY*(S.sourceEvent.deltaMode===1?.05:S.sourceEvent.deltaMode?1:.002)*d,T=k[2]*Math.pow(2,C*_);t.scaleTo(T)};let v=[0,0];const y=S=>{(S.sourceEvent.type==="mousedown"||S.sourceEvent.type==="touchstart")&&(v=[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]-v[0],_[1]-v[1]];v=_;const T=r()*Math.max(k[2],Math.log(k[2]))*(h?-1:1),E={x:k[0]-C[0]*T,y:k[1]-C[1]*T},N=[[0,0],[c,u]];t.setViewportConstrained({x:E.x,y:E.y,zoom:k[2]},N,l)},x=ZOt().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:hg}}const CW=e=>({x:e.x,y:e.y,zoom:e.k}),bne=({x:e,y:t,zoom:n})=>kW.translate(e,t).scale(n),OT=(e,t)=>e.target.closest(`.${t}`),b_t=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),xKn=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,xne=(e,t=0,n=xKn,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},x_t=e=>{const t=e.ctrlKey&&ZM()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function wKn({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(OT(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=hg(d),b=x_t(d),x=f*Math.pow(2,b);r.scaleTo(n,x,y,d);return}const p=d.deltaMode===1?20:1;let h=s===cO.Vertical?0:d.deltaX*p,m=s===cO.Horizontal?0:d.deltaY*p;!ZM()&&d.shiftKey&&s!==cO.Vertical&&(h=d.deltaY*p,m=0),r.translateBy(n,-(h/f)*a,-(m/f)*a,{internal:!0});const v=CW(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(d,v),e.panScrollTimeout=setTimeout(()=>{u?.(d,v),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l?.(d,v))}}function SKn({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=OT(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function kKn({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=CW(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 OKn({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&b_t(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,CW(a.transform))}}function _Kn({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&b_t(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=CW(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function CKn({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"&&(OT(f,`${u}-flow__node`)||OT(f,`${u}-flow__edge`)))return!0;if(!r&&!p&&!s&&!a&&!n||i||d&&!m||OT(f,l)&&m||OT(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 v=Array.isArray(r)&&r.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||m)&&v}}function EKn({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=ZOt().scaleExtent([t,n]).translateExtent(r),p=Tp(e).call(f);x({x:s.x,y:s.y,zoom:cN(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const h=p.on("wheel.zoom"),m=p.on("dblclick.zoom");f.wheelDelta(x_t);function v(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?gx:r9).transform(xne(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:R,onPaneContextMenu:L,userSelectionActive:M,panOnScroll:F,panOnDrag:H,panOnScrollMode:z,panOnScrollSpeed:q,preventScrolling:V,zoomOnPinch:D,zoomOnScroll:G,zoomOnDoubleClick:U,zoomActivationKeyPressed:P,lib:B,onTransformChange:Z,connectionInProgress:Y,paneClickDistance:te,selectionOnDrag:J}){M&&!u.isZoomingOrPanning&&b();const ee=F&&!P&&!M;f.clickDistance(J?1/0:!Eg(te)||te<0?0:te);const re=ee?wKn({zoomPanValues:u,noWheelClassName:A,d3Selection:p,d3Zoom:f,panOnScrollMode:z,panOnScrollSpeed:q,zoomOnPinch:D,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):SKn({noWheelClassName:A,preventScrolling:V,d3ZoomHandler:h});if(p.on("wheel.zoom",re,{passive:!1}),!M){const X=kKn({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",X);const ne=OKn({zoomPanValues:u,panOnDrag:H,onPaneContextMenu:!!L,onPanZoom:a,onTransformChange:Z});f.on("zoom",ne);const se=_Kn({zoomPanValues:u,panOnDrag:H,panOnScroll:F,onPaneContextMenu:L,onPanZoomEnd:l,onDraggingChange:c});f.on("end",se)}const oe=CKn({zoomActivationKeyPressed:P,panOnDrag:H,zoomOnScroll:G,panOnScroll:F,zoomOnDoubleClick:U,zoomOnPinch:D,userSelectionActive:M,noPanClassName:R,noWheelClassName:A,lib:B,connectionInProgress:Y});f.filter(oe),U?p.on("dblclick.zoom",m):p.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,R,L){const M=bne(A),F=f?.constrain()(M,R,L);return F&&await v(F),new Promise(H=>H(F))}async function S(A,R){const L=bne(A);return await v(L,R),new Promise(M=>M(L))}function k(A){if(p){const R=bne(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?WOt(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"?gx:r9).scaleTo(xne(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function T(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?gx:r9).scaleBy(xne(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function E(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const R=!Eg(A)||A<0?0:A;f?.clickDistance(R)}return{update:y,destroy:b,setViewport:S,setViewportConstrained:x,getViewport:_,scaleTo:C,scaleBy:T,setScaleExtent:E,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var fN;(function(e){e.Line="line",e.Handle="handle"})(fN||(fN={}));function TKn({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 fBe(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 X0(e,t){return Math.max(0,t-e)}function J0(e,t){return Math.max(0,e-t)}function AF(e,t,n){return Math.max(0,t-e,e-n)}function pBe(e,t){return e?!t:t}function jKn(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:v,maxWidth:y,minHeight:b,maxHeight:x}=r,{x:S,y:k,width:_,height:C,aspectRatio:T}=e;let E=Math.floor(d?h-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=_+(c?-E:E),A=C+(u?-N:N),R=-a[0]*_,L=-a[1]*C;let M=AF(I,v,y),F=AF(A,b,x);if(i){let q=0,V=0;c&&E<0?q=X0(S+E+R,i[0][0]):!c&&E>0&&(q=J0(S+I+R,i[1][0])),u&&N<0?V=X0(k+N+L,i[0][1]):!u&&N>0&&(V=J0(k+A+L,i[1][1])),M=Math.max(M,q),F=Math.max(F,V)}if(l){let q=0,V=0;c&&E>0?q=J0(S+E,l[0][0]):!c&&E<0&&(q=X0(S+I,l[1][0])),u&&N>0?V=J0(k+N,l[0][1]):!u&&N<0&&(V=X0(k+A,l[1][1])),M=Math.max(M,q),F=Math.max(F,V)}if(s){if(d){const q=AF(I/T,b,x)*T;if(M=Math.max(M,q),i){let V=0;!c&&!u||c&&!u&&p?V=J0(k+L+I/T,i[1][1])*T:V=X0(k+L+(c?E:-E)/T,i[0][1])*T,M=Math.max(M,V)}if(l){let V=0;!c&&!u||c&&!u&&p?V=X0(k+I/T,l[1][1])*T:V=J0(k+(c?E:-E)/T,l[0][1])*T,M=Math.max(M,V)}}if(f){const q=AF(A*T,v,y)/T;if(F=Math.max(F,q),i){let V=0;!c&&!u||u&&!c&&p?V=J0(S+A*T+R,i[1][0])/T:V=X0(S+(u?N:-N)*T+R,i[0][0])/T,F=Math.max(F,V)}if(l){let V=0;!c&&!u||u&&!c&&p?V=X0(S+A*T,l[1][0])/T:V=J0(S+(u?N:-N)*T,l[0][0])/T,F=Math.max(F,V)}}}N=N+(N<0?F:-F),E=E+(E<0?M:-M),s&&(p?I>A*T?N=(pBe(c,u)?-E:E)/T:E=(pBe(c,u)?-N:N)*T:d?(N=E/T,u=c):(E=N*T,c=u));const H=c?S+E:S,z=u?k+N:k;return{width:_+(c?-E:E),height:C+(u?-N:N),x:a[0]*E*(c?-1:1)+H,y:a[1]*N*(u?-1:1)+z}}const w_t={width:0,height:0,x:0,y:0},NKn={...w_t,pointerX:0,pointerY:0,aspectRatio:1};function IKn(e){return[[0,0],[e.measured.width,e.measured.height]]}function AKn(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 RKn({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=Tp(e);let i={controlDirection:fBe("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:v,shouldResize:y}){let b={...w_t},x={...NKn};i={boundaries:d,resizeDirection:p,keepAspectRatio:f,controlDirection:fBe(u)};let S,k=null,_=[],C,T,E,N=!1;const I=AOt().on("start",A=>{const{nodeLookup:R,transform:L,snapGrid:M,snapToGrid:F,nodeOrigin:H,paneDomNode:z}=n();if(S=R.get(t),!S)return;k=z?.getBoundingClientRect()??null;const{xSnapped:q,ySnapped:V}=U$(A.sourceEvent,{transform:L,snapGrid:M,snapToGrid:F,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:q,pointerY:V,aspectRatio:b.width/b.height},C=void 0,S.parentId&&(S.extent==="parent"||S.expandParent)&&(C=R.get(S.parentId),T=C&&S.extent==="parent"?IKn(C):void 0),_=[],E=void 0;for(const[D,G]of R)if(G.parentId===t&&(_.push({id:D,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const U=AKn(G,S,G.origin??H);E?E=[[Math.min(U[0][0],E[0][0]),Math.min(U[0][1],E[0][1])],[Math.max(U[1][0],E[1][0]),Math.max(U[1][1],E[1][1])]]:E=U}h?.(A,{...b})}).on("drag",A=>{const{transform:R,snapGrid:L,snapToGrid:M,nodeOrigin:F}=n(),H=U$(A.sourceEvent,{transform:R,snapGrid:L,snapToGrid:M,containerBounds:k}),z=[];if(!S)return;const{x:q,y:V,width:D,height:G}=b,U={},P=S.origin??F,{width:B,height:Z,x:Y,y:te}=jKn(x,i.controlDirection,H,i.boundaries,i.keepAspectRatio,P,T,E),J=B!==D,ee=Z!==G,re=Y!==q&&J,oe=te!==V&ⅇif(!re&&!oe&&!J&&!ee)return;if((re||oe||P[0]===1||P[1]===1)&&(U.x=re?Y:b.x,U.y=oe?te:b.y,b.x=U.x,b.y=U.y,_.length>0)){const fe=Y-q,ce=te-V;for(const xe of _)xe.position={x:xe.position.x-fe+P[0]*(B-D),y:xe.position.y-ce+P[1]*(Z-G)},z.push(xe)}if((J||ee)&&(U.width=J&&(!i.resizeDirection||i.resizeDirection==="horizontal")?B:b.width,U.height=ee&&(!i.resizeDirection||i.resizeDirection==="vertical")?Z:b.height,b.width=U.width,b.height=U.height),C&&S.expandParent){const fe=P[0]*(U.width??0);U.x&&U.x<fe&&(b.x=fe,x.x=x.x-(U.x-fe));const ce=P[1]*(U.height??0);U.y&&U.y<ce&&(b.y=ce,x.y=x.y-(U.y-ce))}const X=TKn({width:b.width,prevWidth:D,height:b.height,prevHeight:G,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),ne={...b,direction:X};y?.(A,ne)!==!1&&(N=!0,m?.(A,ne),r(U,z))}).on("end",A=>{N&&(v?.(A,{...b}),s?.({...b}),N=!1)});a.call(I)}function c(){a.on(".drag",null)}return{update:l,destroy:c}}const PKn={},hBe=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:()=>{(PKn?"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},$Kn=e=>e?hBe(e):hBe,{useDebugValue:MKn}=Fe,{useSyncExternalStoreWithSelector:DKn}=sNn,LKn=e=>e;function S_t(e,t=LKn,n){const r=DKn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return MKn(r),r}const mBe=(e,t)=>{const n=$Kn(e),r=(s,a=t)=>S_t(n,s,a);return Object.assign(r,n),r},FKn=(e,t)=>e?mBe(e,t):mBe;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 EW=g.createContext(null),zKn=EW.Provider,k_t=ky.error001();function Ws(e,t){const n=g.useContext(EW);if(n===null)throw new Error(k_t);return S_t(n,e,t)}function To(){const e=g.useContext(EW);if(e===null)throw new Error(k_t);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const gBe={display:"none"},BKn={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},O_t="react-flow__node-desc",__t="react-flow__edge-desc",UKn="react-flow__aria-live",qKn=e=>e.ariaLiveMessage,VKn=e=>e.ariaLabelConfig;function HKn({rfId:e}){const t=Ws(qKn);return o.jsx("div",{id:`${UKn}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:BKn,children:t})}function WKn({rfId:e,disableKeyboardA11y:t}){const n=Ws(VKn);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${O_t}-${e}`,style:gBe,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${__t}-${e}`,style:gBe,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(HKn,{rfId:e})]})}const d4=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:Gl(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});d4.displayName="Panel";function ZKn({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(d4,{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 GKn=e=>{const t=[],n=[];for(const[,r]of e.nodeLookup)r.selected&&t.push(r.internals.userNode);for(const[,r]of e.edgeLookup)r.selected&&n.push(r);return{selectedNodes:t,selectedEdges:n}},RF=e=>e.id;function QKn(e,t){return io(e.selectedNodes.map(RF),t.selectedNodes.map(RF))&&io(e.selectedEdges.map(RF),t.selectedEdges.map(RF))}function YKn({onSelectionChange:e}){const t=To(),{selectedNodes:n,selectedEdges:r}=Ws(GKn,QKn);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const KKn=e=>!!e.onSelectionChangeHandlers;function XKn({onSelectionChange:e}){const t=Ws(KKn);return e||t?o.jsx(YKn,{onSelectionChange:e}):null}const Fve=typeof window<"u"?g.useLayoutEffect:g.useEffect,C_t=[0,0],JKn={x:0,y:0,zoom:1},eXn=["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"],vBe=[...eXn,"rfId"],tXn=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}),yBe={translateExtent:qM,nodeOrigin:C_t,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function nXn(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Ws(tXn,io),u=To();Fve(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=yBe,l()}),[]);const d=g.useRef(yBe);return Fve(()=>{for(const f of vBe){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:HYn(p)}):f==="fitView"?u.setState({fitViewQueued:p}):f==="fitViewOptions"?u.setState({fitViewOptions:p}):u.setState({[f]:p})))}d.current=e},vBe.map(f=>e[f])),null}function bBe(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function rXn(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=bBe(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:bBe()?.matches?"dark":"light"}const xBe=typeof document<"u"?document:null;function GM(e=null,t={target:xBe,actInsideInputWithModifier:!0}){const[n,r]=g.useState(!1),s=g.useRef(!1),a=g.useRef(new Set([])),[i,l]=g.useMemo(()=>{if(e!==null){const u=(Array.isArray(e)?e:[e]).filter(f=>typeof f=="string").map(f=>f.replace("+",`
|
|
235
235
|
`).replace(`
|
|
236
236
|
|
|
237
237
|
`,`
|
|
@@ -642,7 +642,7 @@ Token usage: ${n} input + ${r} output = ${s} total`:`The model stopped generatin
|
|
|
642
642
|
"groundTruth": "Expected result (optional)",
|
|
643
643
|
"metadata": { "key": "value" } // optional
|
|
644
644
|
}
|
|
645
|
-
]`})]})]})}function jms({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(We,{children:o.jsx(uc,{className:"h-4 w-4"})}),o.jsxs("span",{className:"text-sm font-medium",children:[e.length," validation error",e.length!==1?"s":""]})]}),o.jsx("ul",{className:"text-accent2/80 space-y-1 text-sm",children:n.map((s,a)=>o.jsxs("li",{className:"flex gap-2",children:[o.jsx("span",{className:"shrink-0",children:"•"}),o.jsx("span",{children:s.message})]},a))}),r>0&&o.jsxs("div",{className:"text-accent2/60 mt-2 text-xs",children:["+",r," more error",r!==1?"s":""]})]})}function Nms({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=g.useState("upload"),[i,l]=g.useState(null),[c,u]=g.useState({current:0,total:0}),[d,f]=g.useState(null),[p,h]=g.useState(!1),{parseFile:m,isParsing:v,error:y}=_hs(),{batchInsertItems:b}=bi(),x=g.useCallback(async I=>{try{const A=await m(I);l(A),a("preview")}catch{}},[m]),S=g.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=g.useCallback(()=>{n(!1),r?.(),d&&d.success>0&&ze.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]),_=g.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,T=()=>{switch(s){case"upload":return o.jsx(Tms,{onFileSelect:x,isParsing:v,error:y?.message});case"preview":return i?o.jsx("div",{className:"flex flex-col gap-4",children:i.errors.length>0?o.jsxs(o.Fragment,{children:[o.jsx(jms,{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(Ems,{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(Ut,{}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-neutral1 text-lg font-medium",children:"Importing items..."}),o.jsxs("div",{className:"text-neutral4 mt-1 text-sm",children:[c.current," of ",c.total]})]})]});case"complete":return o.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[o.jsx("div",{className:"text-4xl",children:d&&d.errors===0?"✓":"⚠"}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-neutral1 text-lg font-medium",children:"Import Complete"}),o.jsxs("div",{className:"text-neutral4 mt-1 text-sm",children:[d?.success??0," item",d?.success!==1?"s":""," imported",d&&d.errors>0&&o.jsxs("span",{className:"text-accent2",children:[" ","(",d.errors," error",d.errors!==1?"s":"",")"]})]})]})]})}},E=()=>{switch(s){case"upload":return o.jsx(le,{onClick:_,children:"Cancel"});case"preview":return o.jsxs(o.Fragment,{children:[o.jsx(le,{onClick:()=>a("upload"),children:"Back"}),o.jsxs(le,{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(le,{variant:"primary",onClick:k,children:"Done"})}},N={upload:"Import JSON",preview:"Preview Data",importing:"Importing",complete:"Import Complete"};return o.jsx(hr,{open:t,onOpenChange:_,children:o.jsxs(mr,{className:"max-h-[90vh] max-w-2xl",children:[o.jsxs(gr,{children:[o.jsx(ur,{children:N[s]}),o.jsx(Cs,{children:"Import dataset items from a JSON file."})]}),o.jsx(jr,{className:"max-h-[50vh] min-h-[200px] overflow-y-auto",children:T()}),o.jsx(Ul,{className:"flex justify-end gap-2 px-6 pt-4",children:E()})]})})}function Ims(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"?!0:!!e.closest('[role="dialog"]:not([data-item-panel])')}function FVt({active:e,onPrevious:t,onNext:n,onClose:r}){g.useEffect(()=>{if(!e)return;const s=a=>{a.defaultPrevented||Ims(a.target)||(a.key==="PageUp"?(a.preventDefault(),t?.()):a.key==="PageDown"?(a.preventDefault(),n?.()):a.key==="Escape"&&(a.preventDefault(),r()))};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,t,n,r])}const zVt=g.createContext(null);function Ams({datasetId:e,items:t,isLoadingItems:n,children:r}){const s=Vr(),i=Vgt("/datasets/:datasetId/items/:itemId")?.params.itemId,l=g.useCallback(h=>{s(`/datasets/${e}/items/${encodeURIComponent(h)}`)},[s,e]),c=g.useCallback(()=>{s(`/datasets/${e}`)},[s,e]),u=g.useMemo(()=>i?t.findIndex(h=>h.id===i):-1,[t,i]),d=g.useMemo(()=>{if(u<=0)return;const h=t[u-1].id;return()=>l(h)},[u,t,l]),f=g.useMemo(()=>{if(u<0||u>=t.length-1)return;const h=t[u+1].id;return()=>l(h)},[u,t,l]);FVt({active:!!i,onPrevious:d,onNext:f,onClose:c});const p=g.useMemo(()=>({datasetId:e,items:t,isLoadingItems:n,currentItemId:i,openItem:l,close:c,goToPreviousItem:d,goToNextItem:f}),[e,t,n,i,l,c,d,f]);return o.jsx(zVt.Provider,{value:p,children:r})}function BVt(){const e=g.useContext(zVt);if(!e)throw new Error("useDatasetItemPanel must be used within a DatasetItemPanelProvider");return e}function Rms({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,leftSlot:r,rightSlot:s}){const[a,i]=Ma(),{activeVersion:l}=cRe(a,i),[c,u]=g.useState(!1),[d,f]=g.useState(!1),[p,h]=g.useState(!1),[m,v]=g.useState([]),[y,b]=g.useState(!1),[x,S]=g.useState([]),[k,_]=g.useState(!1),[C,T]=g.useState([]),[E,N]=g.useState(0),[I,A]=g.useState(""),[R]=YH(I,300),{data:L}=My(e),{data:M=[],isLoading:F,setEndOfListElement:H,isFetchingNextPage:z,hasNextPage:q}=W1(e,R||void 0,l),{deleteItems:V}=bi(),{currentItemId:D,openItem:G,close:U}=BVt(),P=oe=>{D===oe?U():G(oe)},B=oe=>{v(oe),h(!0)},Z=oe=>{S(oe),b(!0)},Y=oe=>{b(oe),oe||(S([]),N(X=>X+1))},te=oe=>{T(oe),_(!0)},J=async()=>{await V.mutateAsync({datasetId:e,itemIds:C}),ze.success(`Deleted ${C.length} items`),_(!1),T([]),N(oe=>oe+1)},ee=oe=>{h(!1),v([]),N(X=>X+1),n?.(oe)},re=oe=>{h(oe),oe||(v([]),N(X=>X+1))};return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"grid h-full overflow-auto",children:o.jsx(Cms,{items:M,leftSlot:r,rightSlot:s,isLoading:F,onItemClick:P,featuredItemId:D,onAddClick:t??(()=>{}),onImportClick:()=>u(!0),onImportJsonClick:()=>f(!0),onBulkDeleteClick:te,onCreateDatasetClick:B,onAddToDatasetClick:Z,datasetName:L?.name,clearSelectionTrigger:E,setEndOfListElement:H,isFetchingNextPage:z,hasNextPage:q,searchQuery:I,activeSearchQuery:R,onSearchChange:A,currentDatasetVersion:L?.version})}),o.jsx(wms,{datasetId:e,open:c,onOpenChange:u}),o.jsx(Nms,{datasetId:e,open:d,onOpenChange:f}),o.jsx(tms,{open:p,onOpenChange:re,items:m,onSuccess:ee}),o.jsx(nms,{open:y,onOpenChange:Y,items:x,currentDatasetId:e}),o.jsx(Mt,{open:k,onOpenChange:_,children:o.jsxs(Mt.Content,{children:[o.jsxs(Mt.Header,{children:[o.jsx(Mt.Title,{children:"Delete Items"}),o.jsxs(Mt.Description,{children:["Are you sure you want to delete ",C.length," item",C.length!==1?"s":"","? This action cannot be undone."]})]}),o.jsxs(Mt.Footer,{children:[o.jsx(Mt.Cancel,{children:"Cancel"}),o.jsx(Mt.Action,{onClick:J,children:V.isPending?"Deleting...":"Delete"})]})]})})]})}function UVt({selectedScorers:e,setSelectedScorers:t,disabled:n=!1,container:r,label:s="Scorers (Optional)",helperText:a}){const{data:i,isLoading:l}=uh(),c=Object.entries(i??{}).filter(([,u])=>u.isRegistered).map(([u,d])=>({value:u,label:d.scorer?.config?.name||u,description:d.scorer?.config?.description||""}));return o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Pt,{children:s}),a?o.jsx("p",{className:"text-muted-foreground text-xs",children:a}):null,o.jsx(yl,{multiple:!0,options:c,value:e,onValueChange:t,placeholder:"Select scorers...",searchPlaceholder:"Search scorers...",emptyText:"No scorers available",disabled:n||l,container:r})]})}function qVt({overrideEnabled:e,onOverrideEnabledChange:t,selectedScorerIds:n,onSelectedScorerIdsChange:r,disabled:s=!1}){return o.jsxs("div",{className:"grid gap-3",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(Bl,{id:"override-dataset-scorers",checked:e,onCheckedChange:t,disabled:s}),o.jsx(Pt,{htmlFor:"override-dataset-scorers",children:"Override dataset scorers"})]}),o.jsx("p",{className:"text-muted-foreground text-xs",children:e?"Only selected scorers run for this item. Leave empty to run no scorers.":"Use scorers attached to the dataset."}),e?o.jsx(UVt,{selectedScorers:n,setSelectedScorers:r,disabled:s,label:"Item scorers",helperText:"Choose from scorers that can be resolved by this Mastra instance."}):null]})}function Pms(e){if(!(e instanceof Error))return null;const t=e.message.match(/- ({.*})$/);if(!t)return null;try{const n=JSON.parse(t[1]);if(n.field&&Array.isArray(n.errors))return{field:n.field,errors:n.errors}}catch{}return null}function qie({field:e,errors:t}){return t.length?o.jsx("div",{className:"mt-2 space-y-1",children:t.map((n,r)=>o.jsxs("p",{className:"text-destructive text-xs",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function $ms({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=g.useState("{}"),[i,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState(""),[p,h]=g.useState(!1),[m,v]=g.useState([]),[y,b]=g.useState(""),[x,S]=g.useState(null),{addItem:k}=bi(),_=()=>{a("{}"),l(""),u(""),f(""),h(!1),v([]),b(""),S(null)},C=R=>{_(),n(R)},T=async R=>{R.preventDefault();let L;try{L=JSON.parse(s)}catch{ze.error("Input must be valid JSON");return}let M;if(i.trim())try{M=JSON.parse(i)}catch{ze.error("Ground Truth must be valid JSON");return}let F;if(c.trim())try{F=JSON.parse(c)}catch{ze.error("Expected Trajectory must be valid JSON");return}let H;if(d.trim())try{const q=JSON.parse(d);if(!Array.isArray(q)){ze.error("Tool Mocks must be a JSON array");return}H=q}catch{ze.error("Tool Mocks must be valid JSON");return}let z;if(y.trim())try{z=JSON.parse(y)}catch{ze.error("Request Context must be valid JSON");return}try{await k.mutateAsync({datasetId:e,input:L,groundTruth:M,expectedTrajectory:F,toolMocks:H,scorerIds:p?m:void 0,requestContext:z}),ze.success("Item added successfully"),C(!1),r?.()}catch(q){const V=Pms(q);V?S(V):ze.error(`Failed to add item: ${q instanceof Error?q.message:"Unknown error"}`)}},E=R=>{a(R),x?.field==="input"&&S(null)},N=R=>{l(R),x?.field==="groundTruth"&&S(null)},I=R=>{f(R),x?.field==="toolMocks"&&S(null)},A=()=>{C(!1)};return o.jsxs(Sa,{dialogTitle:"Add Item",dialogDescription:"Create a new dataset item",isOpen:t,onClose:A,level:1,children:[o.jsx(Sa.Top,{children:"Add Item"}),o.jsxs(Sa.Content,{children:[o.jsx(Sa.Header,{children:o.jsx(Sa.Heading,{children:"Add Item"})}),o.jsxs("form",{onSubmit:T,className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Pt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Qr,{value:s,onChange:E,showCopyButton:!1,className:"min-h-[240px]"}),x?.field==="input"&&o.jsx(qie,{field:"input",errors:x.errors})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Pt,{htmlFor:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),o.jsx(Qr,{value:i,onChange:N,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="groundTruth"&&o.jsx(qie,{field:"groundTruth",errors:x.errors})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Pt,{htmlFor:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),o.jsx(Qr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[200px]"})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Pt,{htmlFor:"item-tool-mocks",children:"Tool Mocks (JSON array, optional)"}),o.jsx(Qr,{value:d,onChange:I,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="toolMocks"&&o.jsx(qie,{field:"toolMocks",errors:x.errors})]}),o.jsx(qVt,{overrideEnabled:p,onOverrideEnabledChange:h,selectedScorerIds:m,onSelectedScorerIdsChange:v,disabled:k.isPending}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Pt,{htmlFor:"item-request-context",children:"Request Context (JSON, optional)"}),o.jsx(Qr,{value:y,onChange:b,showCopyButton:!1,className:"min-h-[200px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(le,{type:"button",onClick:A,children:"Cancel"}),o.jsx(le,{type:"submit",variant:"primary",disabled:k.isPending,children:k.isPending?"Adding...":"Add Item"})]})]})]})]})}function Mms({item:e}){return o.jsx(Aa,{withMargins:!1,children:o.jsxs(Aa.Column,{children:[o.jsxs(Aa.Title,{size:"smaller",children:[o.jsx(NV,{}),o.jsx("span",{className:"truncate",children:e.id}),o.jsx(ka,{content:e.id,tooltip:`Copy item ID: ${e.id}`})]}),o.jsxs(Aa.Description,{children:[o.jsxs(Pl,{children:[o.jsx(MQt,{})," Created ",dr(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")]}),e.datasetVersion!=null&&o.jsxs(Pl,{children:[o.jsx(lI,{})," Version v",e.datasetVersion]})]})]})})}function uRe({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(X7r,{children:[o.jsx(Sa.CodeSection,{title:"Input",icon:o.jsx(wx,{}),codeStr:t}),o.jsx(Sa.CodeSection,{title:"Ground Truth",icon:o.jsx(rm,{}),codeStr:n}),s&&o.jsx(Sa.CodeSection,{title:"Expected Trajectory",icon:o.jsx(I0e,{}),codeStr:s}),o.jsx(Sa.CodeSection,{title:"Scorers",icon:o.jsx(PV,{}),codeStr:e.scorerIds===void 0?"Inherited from dataset":JSON.stringify(e.scorerIds,null,2)}),o.jsx(Sa.CodeSection,{title:"Metadata",icon:o.jsx(cI,{}),codeStr:r})]})}function Vie({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 Dms({inputValue:e,setInputValue:t,groundTruthValue:n,setGroundTruthValue:r,metadataValue:s,setMetadataValue:a,trajectoryValue:i,setTrajectoryValue:l,toolMocksValue:c,setToolMocksValue:u,scorerOverrideEnabled:d,setScorerOverrideEnabled:f,selectedScorerIds:p,setSelectedScorerIds:h,requestContextValue:m,setRequestContextValue:v,validationErrors:y,onSave:b,onCancel:x,isSaving:S}){return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"mb-4",children:o.jsxs("h3",{className:"flex items-center gap-2 text-lg font-medium",children:[o.jsx(Qp,{className:"h-5 w-5"})," Edit Item"]})}),o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Pt,{children:"Input (JSON) *"}),o.jsx(Qr,{value:e,onChange:t,showCopyButton:!1,className:"min-h-[120px]"}),y?.field==="input"&&o.jsx(Vie,{field:"input",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Pt,{children:"Ground Truth (JSON, optional)"}),o.jsx(Qr,{value:n,onChange:r,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="groundTruth"&&o.jsx(Vie,{field:"groundTruth",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Pt,{children:"Expected Trajectory (JSON, optional)"}),o.jsx(Qr,{value:i,onChange:l,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Pt,{children:"Tool Mocks (JSON array, optional)"}),o.jsxs("p",{className:"text-muted-foreground text-xs",children:["Ordered static mocks served in place of executing the tool. Each entry is"," ",o.jsx("code",{children:'{ "toolName", "args", "output" }'}),". Calling a mocked tool with non-matching args fails the item; unmocked tools run live."]}),o.jsx(Qr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="toolMocks"&&o.jsx(Vie,{field:"toolMocks",errors:y.errors})]}),o.jsx(qVt,{overrideEnabled:d,onOverrideEnabledChange:f,selectedScorerIds:p,onSelectedScorerIdsChange:h,disabled:S}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Pt,{children:"Request Context (JSON, optional)"}),o.jsx(Qr,{value:m,onChange:v,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Pt,{children:"Metadata (JSON, optional)"}),o.jsx(Qr,{value:s,onChange:a,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex gap-2 pt-4",children:[o.jsx(le,{variant:"primary",onClick:b,disabled:S,children:S?"Saving...":"Save Changes"}),o.jsx(le,{onClick:x,disabled:S,children:"Cancel"})]})]})]})}const Lms=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function Fms({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:a,isLoading:i}=zm(),{data:l,isLoading:c}=Gy(),{data:u,isLoading:d}=uh(),f=e==="agent"?Object.entries(a??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="workflow"?Object.entries(l??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="scorer"?Object.entries(u??{}).map(([v,y])=>({value:v,label:y.scorer?.config?.name??v})):[],p=e==="agent"&&i||e==="workflow"&&c||e==="scorer"&&d,h=v=>{t(v),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(Pt,{children:"Target Type"}),o.jsx(yl,{options:Lms,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(Pt,{children:m}),o.jsx(yl,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:p,container:s})]})]})}function zms({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return wm(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(Pt,{children:"Request Context"}),o.jsx(K3,{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 sY({initialDatasetId:e,initialDatasetVersion:t,initialScorerIds:n,initialTargetType:r,initialTargetId:s,initialName:a,initialDescription:i,open:l,onOpenChange:c,onSuccess:u}){const d=g.useRef(null),[f,p]=g.useState(a??""),[h,m]=g.useState(i??""),[v,y]=g.useState(e??""),[b,x]=g.useState(t??null),[S,k]=g.useState(r??""),[_,C]=g.useState(s??""),[T,E]=g.useState(n??[]),[N,I]=g.useState({}),[A,R]=g.useState(""),{triggerExperiment:L}=bi(),{data:M}=My(v),F=M?.requestContextSchema,H=!!(F&&Object.keys(F).length>0),z=!!(v&&S&&_&&f.trim()),q=L.isPending,V=B=>{y(B),x(null),I({})},D=()=>{p(a??""),m(i??""),y(e??""),x(t??null),k(r??""),C(s??""),E(n??[]),I({}),R("")},G=()=>{if(H){const B=Object.entries(N).filter(([,Z])=>Z!==void 0&&Z!=="");return B.length>0?Object.fromEntries(B):void 0}if(A.trim()){let B;try{B=JSON.parse(A)}catch{throw new Error("Request Context must be valid JSON")}if(!B||typeof B!="object"||Array.isArray(B))throw new Error("Request Context must be a JSON object");return B}},U=async()=>{if(!v||!S||!_||!f.trim())return;let B;try{B=G()}catch(Z){const Y=Z instanceof Error?Z.message:"Request Context must be valid JSON";gu.error(Y);return}try{const Z=await L.mutateAsync({datasetId:v,name:f.trim(),description:h.trim()||void 0,targetType:S,targetId:_,scorerIds:T.length>0?T:void 0,version:b??void 0,requestContext:B});gu.success("Experiment triggered successfully"),c(!1),u?.(Z.experimentId),D()}catch(Z){const Y=Z instanceof Error?Z.message:"Failed to trigger experiment";gu.error(Y)}},P=()=>{q||(c(!1),D())};return o.jsx(hr,{open:l,onOpenChange:P,children:o.jsxs(mr,{ref:d,children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Run Experiment"}),o.jsx(Cs,{children:b!=null?`Execute items from version v${b} of the dataset against a target.`:"Execute dataset items against a target."})]}),o.jsxs(jr,{className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Pt,{htmlFor:"experiment-name",children:"Name *"}),o.jsx(Cn,{id:"experiment-name",value:f,onChange:B=>p(B.target.value),placeholder:"Enter experiment name",autoFocus:!0,disabled:q})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Pt,{htmlFor:"experiment-description",children:"Description"}),o.jsx(Cn,{id:"experiment-description",value:h,onChange:B=>m(B.target.value),placeholder:"Enter experiment description (optional)",disabled:q})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Pt,{children:"Dataset"}),o.jsx(lms,{value:v,onValueChange:V,container:d})]}),v&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Pt,{children:"Version"}),o.jsx(DVt,{datasetId:v,value:b,onValueChange:x,container:d})]})]}),o.jsx(Fms,{targetType:S,setTargetType:k,targetId:_,setTargetId:C,container:d}),o.jsx(UVt,{selectedScorers:T,setSelectedScorers:E,disabled:q,container:d}),H?o.jsx(zms,{requestContextSchema:F,onChange:I}):o.jsxs("div",{className:"space-y-2",children:[o.jsx(Pt,{children:"Request Context (JSON, optional)"}),o.jsx(Qr,{value:A,onChange:R,showCopyButton:!1,className:"min-h-[80px]"})]})]}),o.jsxs(Ul,{className:"px-6 pt-4",children:[o.jsx(le,{onClick:P,disabled:q,children:"Cancel"}),o.jsx(le,{variant:"primary",onClick:U,disabled:!z||q,children:q?o.jsxs(o.Fragment,{children:[o.jsx(Ut,{className:"h-4 w-4"}),"Running..."]}):"Run"})]})]})})}const VVt=g.createContext(null);function Bms({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:a,children:i}){const l=Vr(),u=Vgt("/experiments/:experimentId/items/:itemId")?.params.itemId,d=g.useCallback(b=>{l(`/experiments/${e}/items/${encodeURIComponent(b)}`)},[l,e]),f=g.useCallback(()=>{l(`/experiments/${e}`)},[l,e]),p=g.useCallback(b=>{l(pTe(e,b))},[l,e]),h=g.useMemo(()=>u?r.findIndex(b=>b.itemId===u):-1,[r,u]),m=g.useMemo(()=>{if(h<=0)return;const b=r[h-1].itemId;return()=>d(b)},[h,r,d]),v=g.useMemo(()=>{if(h<0||h>=r.length-1)return;const b=r[h+1].itemId;return()=>d(b)},[h,r,d]);FVt({active:!!u,onPrevious:m,onNext:v,onClose:f});const y=g.useMemo(()=>({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:a,currentItemId:u,openItem:d,close:f,openInReview:p,goToPreviousItem:m,goToNextItem:v}),[e,t,n,r,s,a,u,d,f,p,m,v]);return o.jsx(VVt.Provider,{value:y,children:i})}function HVt(){const e=g.useContext(VVt);if(!e)throw new Error("useExperimentItemPanel must be used within an ExperimentItemPanelProvider");return e}function Ums({results:e,isLoading:t,featuredResultId:n,onResultClick:r,columns:s,scoresByItemId:a,scorerIds:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u,selectedIds:d,onToggleSelect:f}){const{Link:p,paths:h}=un(),m=!!(d&&f),v=[m?"auto":"",...s.map(k=>k.size)].filter(Boolean).join(" "),y=s.some(k=>k.name==="input"),{containerRef:b,getRowProps:x}=so({count:e.length}),S=k=>i?.includes(k.name)?o.jsx(he.TopCell,{children:o.jsxs(p,{href:h.scorerLink(k.name),className:"flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[o.jsx(AC,{}),o.jsx("span",{className:"min-w-0 truncate",children:k.label})]})},k.name):o.jsx(he.TopCell,{children:k.label},k.name);return t?o.jsx(Fo,{columns:v}):o.jsxs(he,{columns:v,className:"min-w-0",scrollRef:b,children:[o.jsxs(he.Top,{hasLeadingCell:m,children:[m&&o.jsx(he.TopCell,{children:" "}),m?o.jsx(he.TopCells,{colStart:2,children:s.map(S)}):s.map(S)]}),e.length===0?o.jsx(he.NoMatch,{message:"No results yet"}):o.jsxs(o.Fragment,{children:[e.map((k,_)=>{const C=!!k.error,T=k.id===n,E=o.jsxs(o.Fragment,{children:[o.jsxs(he.Cell,{className:"text-ui-smd text-neutral3 flex items-center gap-1.5 tracking-wide",children:[o.jsx("span",{children:k.itemId?.slice(0,8)??""}),C&&o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx(xO,{role:"img","aria-label":"Error",className:"text-error size-3.5"})}),o.jsx(yn,{children:k.error?.message||"Error"})]})]}),y&&o.jsx(he.TextCell,{font:"mono",children:Vms(qms(k.input),200)}),i?.map(N=>{const A=a?.[k.itemId]?.find(R=>R.scorerId===N);return o.jsx(he.Cell,{className:"text-neutral3 text-ui-smd font-mono",children:A!=null?A.score.toFixed(3):"-"},N)})]});return m?o.jsxs(he.RowWrapper,{children:[o.jsx(he.SelectCell,{checked:d.has(k.id),onToggle:()=>f(k.id),"aria-label":`Select result ${k.itemId}`}),o.jsx(he.RowButton,{colStart:2,featured:T,"data-selected":T||void 0,onClick:()=>r(k.id),...x(_),children:E})]},k.id):o.jsx(he.RowButton,{featured:T,"data-selected":T||void 0,onClick:()=>r(k.id),...x(_),children:E},k.id)}),o.jsx(he.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function qms(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Vms(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}function Hms({scoresByItemId:e,experimentStatus:t}){const{Link:n,paths:r}=un(),{data:s}=uh(),a=g.useMemo(()=>{if(!e)return[];const i={};for(const l of Object.values(e))for(const c of l)i[c.scorerId]||(i[c.scorerId]={sum:0,count:0}),i[c.scorerId].sum+=c.score,i[c.scorerId].count++;return Object.entries(i).map(([l,{sum:c,count:u}])=>({scorerId:l,avg:c/u})).sort((l,c)=>l.scorerId.localeCompare(c.scorerId))},[e]);if(a.length===0){const i=t==="running"||t==="pending",l=e!==void 0;let c,u;return i?(c="Experiment in progress",u="Summary metrics will appear here once the experiment completes."):l?(c="No scorers configured",u="Add scorers when triggering an experiment to evaluate results and see summary metrics here."):(c="Loading scores",u="Fetching scorer results…"),o.jsxs("div",{className:"text-ui-sm text-neutral3 flex items-center gap-2",children:[o.jsx(Gp,{className:"text-neutral3 size-4 shrink-0"}),o.jsx("span",{className:"text-neutral4",children:c}),o.jsx("span",{className:"truncate",children:u})]})}return o.jsx("div",{className:"flex items-stretch gap-2 overflow-x-auto pb-1",children:a.map(({scorerId:i,avg:l})=>{const c=s?.[i]?.scorer?.config?.name??i;return o.jsxs(Xr,{className:"w-52 min-w-0 flex-none p-3",children:[o.jsxs(n,{href:r.scorerLink(i),className:"text-ui-sm text-neutral3 [&>svg]:text-neutral3 flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3 [&>svg]:shrink-0",children:[o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx(AC,{role:"img","aria-label":"Scorer"})}),o.jsx(yn,{children:"Scorer"})]}),o.jsx("span",{className:"truncate",children:c})]}),o.jsxs("strong",{className:"text-ui-lg text-neutral4 font-semibold",children:[l.toFixed(3),o.jsx("span",{className:"text-ui-sm text-neutral3 ml-1.5 font-normal",children:"avg score"})]})]},i)})})}function Wms({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoading:s,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l}){const{currentItemId:c,openItem:u,close:d}=HVt(),[f,p]=g.useState(new Set),[h,m]=g.useState(!1),{updateExperimentResult:v}=bi(),y=g.useCallback(E=>{p(N=>{const I=new Set(N);return I.has(E)?I.delete(E):I.add(E),I})},[]),b=g.useCallback(()=>p(new Set),[]),x=g.useCallback(async E=>{if(h||E.length===0)return;m(!0);let N=0;const I=new Set;try{for(const A of E)try{await v.mutateAsync({datasetId:t,experimentId:e,resultId:A,status:"needs-review"}),N++,I.add(A)}catch{}}finally{m(!1)}I.size>0&&p(A=>{const R=new Set(A);for(const L of I)R.delete(L);return R}),N>0&&ze(`${N} result${N>1?"s":""} flagged for review`)},[t,e,h,v]),S=g.useMemo(()=>c?r.find(E=>E.itemId===c)?.id??null:null,[r,c]),{data:k}=C_(e,n),_=g.useMemo(()=>{if(!k)return[];const E=new Set;for(const N of Object.values(k))for(const I of N)E.add(I.scorerId);return[...E].sort()},[k]),C=g.useCallback(E=>{const N=r.find(I=>I.id===E);N&&(N.itemId===c?d():u(N.itemId))},[r,c,d,u]),T=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"7rem"},{name:"input",label:"Input",size:"minmax(10rem,20rem)"},..._.map(E=>({name:E,label:E,size:"12rem"}))],[_]);return o.jsxs("div",{className:K("grid h-full gap-3 overflow-hidden",f.size>0?"grid-rows-[auto_auto_1fr]":"grid-rows-[auto_1fr]"),children:[o.jsx(Hms,{scoresByItemId:k,experimentStatus:n}),f.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(le,{variant:"outline",size:"sm",disabled:h,onClick:()=>x([...f]),children:[o.jsx(We,{size:"sm",children:o.jsx(Q1,{})}),"Flag ",f.size," to review"]}),o.jsx(le,{variant:"ghost",size:"sm",onClick:b,children:"Clear"})]}),o.jsx("div",{className:"min-h-0 overflow-y-auto",children:o.jsx(Ums,{results:r,isLoading:s,featuredResultId:S,onResultClick:C,columns:T,scoresByItemId:k,scorerIds:_,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l,selectedIds:f,onToggleSelect:y})})]})}const ott={pending:{icon:o.jsx(a1,{className:"text-warning1 size-4"}),label:"Pending"},running:{icon:o.jsx(Ut,{size:"sm"}),label:"Running"},completed:{icon:o.jsx(t3,{className:"text-neutral3 size-4"}),label:"Completed"},failed:{icon:o.jsx(SO,{className:"text-error size-4"}),label:"Failed"}};function Zms({status:e,className:t}){const n=ott[e]??ott.pending;return o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx("span",{tabIndex:0,className:K("flex shrink-0 items-center",t),children:n.icon})}),o.jsx(yn,{children:n.label})]})}const Gms=e=>{const t=Ge();return mt({queryKey:["experiment-trace-light",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return t.getTraceLight(e)},select:AAe,enabled:!!e})};function WVt({children:e,className:t}){return o.jsx("div",{className:K("",t),children:e})}function Qms({date:e,className:t,withTime:n=!1}){const r=e?Axt(new Date(e)):!1,s=e?V3(new Date(e))?"Today":dr(new Date(e),"MMM dd"):"",a=e&&!r?dr(new Date(e),"yyyy"):"",i=e&&n?`${dr(new Date(e),"'at' h:mm aaa")}`:"";return o.jsxs("div",{className:K("truncate text-ui-md text-neutral2",t),children:[s," ",a," ",i]})}function dRe(e){return!e||e.length===0?"":e?.map(t=>t.size).join(" ")}function Yms({columns:e,isSelectionActive:t,children:n}){return o.jsx("div",{className:K("sticky top-0 z-10 mb-4 rounded-lg bg-surface3 px-4"),children:o.jsx("div",{className:K("grid items-center gap-4 text-left text-ui-xs tracking-widest text-neutral3 uppercase",{"pl-12 [&>label]:absolute [&>label]:left-0":t}),style:{gridTemplateColumns:dRe(e)},children:n})})}function Kms({children:e,className:t}){return o.jsx("span",{className:K("py-3",t),children:e})}function Xms({id:e,className:t,isShortened:n=!0}){const r=n?e.slice(0,8):e;return o.jsx("div",{className:K("truncate py-[0.6rem] text-ui-md text-neutral2",t),children:r})}function Jms({children:e}){return o.jsx("ul",{className:"grid content-start",children:e})}function egs({children:e}){const t=g.useRef(null);return o.jsx("div",{ref:t,className:K("overflow-y-auto"),children:e})}function tgs({children:e,className:t}){return o.jsx("label",{className:K("flex h-full w-14 items-center justify-center rounded-lg hover:bg-surface5",t),children:e})}function ngs({children:e,href:t,className:n,LinkComponent:r,tooltip:s}){const a=o.jsx(r,{href:t,className:K("flex w-full items-center justify-center gap-6 rounded-lg px-3 py-[0.6rem] text-left","hover:bg-surface4",Yr.colors,L3.visible,n),children:e});return s==null?a:o.jsxs(xn,{children:[o.jsx(vn,{render:a}),o.jsx(yn,{children:s})]})}function rgs({children:e,message:t,className:n,type:r}){return!e&&!t?null:o.jsx("div",{className:K("grid border-t border-border1",n),children:t?o.jsxs("p",{className:K("grid justify-center justify-items-center gap-2 p-8 text-center text-ui-md text-neutral3","[&>svg]:size-[1.5em] [&>svg]:opacity-75",{"[&>svg]:text-red-500":r==="error"}),children:[r==="error"?o.jsx(uc,{}):o.jsx(Em,{})," ",t]}):e})}function sgs({isLoading:e,hasMore:t,setEndOfListElement:n,loadingText:r="Loading more data...",noMoreDataText:s="No more data to load"}){return n?o.jsxs("div",{ref:n,className:"text-ui-md text-neutral3 mt-8 flex justify-center opacity-50",children:[e&&r,!t&&!e&&s]}):null}function ags({currentPage:e,hasMore:t,onNextPage:n,onPrevPage:r}){const s=typeof e=="number"&&e>0||t;return o.jsxs("div",{className:K("flex items-center justify-center gap-8 pt-6 text-ui-md text-neutral3"),children:[o.jsxs("span",{children:["Page ",o.jsx("b",{children:e?e+1:"1"})]}),s&&o.jsxs("div",{className:K("flex gap-4","[&>button]:flex [&>button]:items-center [&>button]:gap-2 [&>button]:rounded-md [&>button]:border [&>button]:border-border1 [&>button]:p-1 [&>button]:px-2 [&>button]:text-neutral4 [&>button]:transition-colors [&>button:hover]:text-neutral5","[&_svg]:size-[1em] [&_svg]:text-neutral3"),children:[typeof e=="number"&&e>0&&o.jsxs("button",{onClick:r,children:[o.jsx(bl,{}),"Previous"]}),t&&o.jsxs("button",{onClick:n,children:["Next",o.jsx(zd,{})]})]})]})}function igs({children:e,className:t}){return o.jsx("div",{className:K("grid grid-rows-[auto_1fr] overflow-y-auto",t),children:e})}function ogs({isSelected:e,children:t,columns:n}){return o.jsx("li",{className:K("flex overflow-hidden rounded-lg border border-transparent border-t-border1 py-[3px] pb-[2px] text-ui-md text-neutral5 first:border-t-transparent","[&:last-child>button]:rounded-b-lg","[&.selected-row]:border [&.selected-row]:border-dashed [&.selected-row]:border-white/50 [&.selected-row]:pr-[3px] [&.selected-row]:first:border-t","[&:has(+.selected-row)]:rounded-b-none [&:has(+.selected-row)]:border-b-transparent","[.selected-row+&]:rounded-t-none",Yr.colors,{"selected-row":e,"grid px-4 gap-4 ":n}),style:{gridTemplateColumns:dRe(n)},children:t})}function lgs({item:e,isFeatured:t,onClick:n,children:r,columns:s,className:a,disabled:i,tooltip:l,...c}){const u=()=>{n?.(e?.id)},d=o.jsx("button",{...c,onClick:u,className:K("grid w-full items-center gap-4 rounded-lg px-4 text-left",Yr.colors,L3.visible,{"bg-surface4":t,"hover:bg-surface4":e&&!t&&!i},a),style:{gridTemplateColumns:dRe(s)},disabled:i,children:r});return l==null?d:o.jsxs(xn,{children:[o.jsx(vn,{render:d}),o.jsx(yn,{children:l})]})}function cgs(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ugs({status:e}){return e?o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx("div",{className:K("relative flex h-full w-10 items-center justify-center bg-transparent"),children:o.jsx("div",{className:K("size-2 rounded-full",{"bg-green-600":["success","completed"].includes(e),"bg-red-700":["error","failed"].includes(e),"bg-yellow-500":["pending","running"].includes(e)})})})}),o.jsx(yn,{children:cgs(e)})]}):null}function dgs({children:e,isLoading:t,className:n}){return o.jsx("div",{className:K("truncate py-[0.6rem] text-ui-md text-neutral4",n),children:t?o.jsx("div",{className:"bg-surface4 h-4 animate-pulse rounded-md text-transparent select-none"}):e})}const SV={latest:"Latest version",deleted:"Deleted in this version"};function fgs({isLatest:e,isDeleted:t}){const n=[];return e&&n.push(SV.latest),t&&n.push(SV.deleted),n.length>0?n.join(" · "):void 0}function pgs({version:e,date:t,isLatest:n,isDeleted:r}){return o.jsxs(WVt,{className:K("grid grid-cols-[1fr_auto] pl-1"),children:[o.jsxs("div",{className:K("grid gap-1 leading-none text-neutral3",{"text-neutral4":n}),children:[o.jsxs("strong",{className:"font-normal",children:["v. ",e]}),o.jsx("em",{className:K("text-ui-sm","font-normal","text-neutral2"),children:t?dr(new Date(t),"MMM d, yyyy HH:mm"):null})]}),(n||r)&&o.jsxs("div",{className:"flex items-center gap-1",children:[n&&o.jsx("span",{className:"inline-flex",role:"img","aria-label":SV.latest,children:o.jsx(xt,{variant:"blue",size:"sm",icon:o.jsx(a1,{})})}),r&&o.jsx("span",{className:"inline-flex",role:"img","aria-label":SV.deleted,children:o.jsx(xt,{variant:"red",size:"sm",icon:o.jsx(x0e,{})})})]})]})}const pi=Object.assign(igs,{Header:Yms,HeaderCol:Kms,Items:Jms,Scroller:egs,Row:ogs,RowButton:lgs,Message:rgs,NextPageLoading:sgs,Pagination:ags,Cell:WVt,TextCell:dgs,StatusCell:ugs,VersionCell:pgs,IdCell:Xms,DateCell:Qms,LinkCell:ngs,LabelCell:tgs});function hgs({datasetId:e,itemId:t,onVersionSelect:n,onCompareVersionsClick:r,activeVersion:s}){const{data:a,isLoading:i}=lRe(e,t),[l,c]=g.useState(!1),[u,d]=g.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)},v=()=>{c(!0)},y=()=>{u.size===2&&r?.([...u])};return o.jsxs(pa,{className:"min-w-56",children:[l?o.jsx(pa.Toolbar,{className:"grid w-full justify-stretch gap-3",children:o.jsxs(es,{children:[o.jsx(le,{onClick:m,children:"Cancel"}),o.jsx(le,{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(pa.Toolbar,{children:o.jsxs(le,{onClick:v,className:"w-full",children:[o.jsx(Tj,{})," Compare Ver."]})})}),i?o.jsx(mgs,{}):o.jsxs(pi,{children:[o.jsx(pi.Header,{children:o.jsx(pi.HeaderCol,{children:"Item Version History"})}),o.jsx(pi.Scroller,{children:o.jsx(pi.Items,{children:a?.map(b=>{const x=String(b.datasetVersion),S=typeof b.updatedAt=="string"?new Date(b.updatedAt):b.updatedAt;return o.jsxs(pi.Row,{isSelected:l&&u.has(x),children:[l&&o.jsx(pi.LabelCell,{children:o.jsx(Oo,{checked:u.has(x),disabled:b.isDeleted,onCheckedChange:()=>{},onClick:k=>{k.stopPropagation(),b.isDeleted||h(x)},"aria-label":`Select version ${b.datasetVersion}`})}),o.jsx(pi.RowButton,{item:b,columns:[{name:"version",label:"Item Version History",size:"1fr"}],isFeatured:p(b),onClick:()=>f(b),className:"py-2",tooltip:fgs({isLatest:b.isLatest,isDeleted:b.isDeleted}),children:o.jsx(pi.VersionCell,{version:b.datasetVersion,date:S,isLatest:b.isLatest,isDeleted:b.isDeleted})})]},String(b.datasetVersion))})})})]})]})}function mgs(){return o.jsxs(pi,{children:[o.jsx(pi.Header,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(pi.HeaderCol,{children:"Item Version History"})}),o.jsx(pi.Items,{children:Array.from({length:3}).map((e,t)=>o.jsx(pi.Row,{children:o.jsx(pi.RowButton,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(pi.TextCell,{isLoading:!0,children:"Loading..."})})},t))})]})}function ggs(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${dr(n,"MMM dd 'at' H:mm:ss a")}`}return`v${e}`}function vgs({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=xAe(e),a=(s??[]).map(i=>({value:String(i.version),label:`${ggs(i.version,i.createdAt)}${i.isCurrent?" (current)":""}`}));return o.jsxs(pa.Toolbar,{className:"grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4",children:[o.jsx("div",{}),o.jsx(Ld,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:a,value:t??"",onValueChange:i=>r?.(i,n??"")}),o.jsx(Ld,{label:"Version B",labelIsHidden:!0,name:"version-b",options:a,value:n??"",onValueChange:i=>r?.(t??"",i)}),o.jsx("div",{})]})}const ygs=[{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"}],D9={added:{badgeVariant:"blue",borderColor:"border-blue-900",icon:o.jsx(Cr,{}),tooltip:"Added in this version"},changed:{badgeVariant:"yellow",borderColor:"border-yellow-900",icon:o.jsx(uJt,{}),tooltip:"Changed in this version"},same:{badgeVariant:"green",borderColor:"border-green-900",icon:o.jsx(fct,{}),tooltip:"Same in both versions"}};function Hie({red:e=!1,tooltip:t}){return o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx("span",{}),role:"img",tabIndex:0,"aria-label":t,className:"focus-visible:outline-neutral5/55 rounded focus-visible:outline-1 focus-visible:outline-offset-2 focus-visible:outline-solid",children:o.jsx(x0e,{className:K("text-neutral3/40 w-5 h-5 ",{"text-red-900":e})})}),o.jsx(yn,{children:t})]})}function Wie({variant:e,version:t}){if(!e)return o.jsxs("span",{className:"text-ui-md text-neutral4",children:["v. ",t]});const{badgeVariant:n,icon:r,tooltip:s}=D9[e];return o.jsxs("div",{className:"grid grid-cols-[1fr_auto]",children:[t!==void 0&&o.jsxs("span",{className:"text-ui-md text-neutral4 flex min-w-16 justify-end pr-3",children:["v. ",t]}),o.jsx("span",{className:"inline-flex",role:"img","aria-label":s,children:o.jsx(xt,{variant:n,size:"xs",icon:r})})]})}function bgs(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function ltt({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return"added";if(t==="changed"&&n)return"changed"}function xgs({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:a}){const{Link:i}=un(),l=t>n;return o.jsx(pi,{children:o.jsx(pi.Scroller,{children:o.jsx(pi.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=a.get(c),f=bgs(u,d),p=ltt({otherVersionExists:d!==void 0,status:f,isNewer:l}),h=ltt({otherVersionExists:u!==void 0,status:f,isNewer:!l});return o.jsxs(pi.Row,{columns:ygs,children:[o.jsx(pi.IdCell,{id:c,isShortened:!1}),f!=="same"?o.jsxs(o.Fragment,{children:[u?.datasetVersion?o.jsx(pi.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:p?D9[p].tooltip:void 0,children:o.jsx(Wie,{variant:p,version:u.datasetVersion})}):o.jsx(pi.Cell,{className:"flex items-center justify-center",children:o.jsx(Hie,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?o.jsx(pi.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:h?D9[h].tooltip:void 0,children:o.jsx(Wie,{variant:h,version:d.datasetVersion})}):o.jsx(pi.Cell,{className:"flex items-center justify-center",children:o.jsx(Hie,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):o.jsx(pi.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",tooltip:D9.same.tooltip,children:o.jsx(Wie,{variant:"same",version:d?.datasetVersion})}),f==="changed"?o.jsx(pi.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}/versions?ids=${u?.datasetVersion},${d?.datasetVersion}`,children:"Compare"}):o.jsx(pi.Cell,{children:o.jsx(Hie,{tooltip:"Comparing is available only for changed items"})})]},c)})})})})}function wgs(){const e=Vr(),[t,n]=g.useState(""),[r,s]=g.useState("all"),[a,i]=g.useState("all"),[l,c]=g.useState("all"),{data:u=[],isLoading:d,error:f,isFetchingNextPage:p,hasNextPage:h,setEndOfListElement:m}=jRn(),{data:v,isLoading:y,error:b}=UH(),x=g.useMemo(()=>v?.experiments??[],[v?.experiments]),S=g.useMemo(()=>Phs(u),[u]),k=d||y,_=f||b,C=()=>{e("/datasets/new")};if(_&&ps(_))return o.jsx(Zn,{children:o.jsx(Ts,{})});if(_&&hs(_))return o.jsx(Zn,{children:o.jsx(Os,{resource:"datasets"})});if(_)return o.jsx(Zn,{children:o.jsx($a,{title:"Failed to load datasets",message:_.message})});if(u.length===0&&!k)return o.jsx(Zn,{children:o.jsx(Fhs,{onCreateClick:C})});const T=r!=="all"||a!=="all"||l!=="all"||t!=="",E=()=>{n(""),s("all"),i("all"),c("all")};return o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(Uhs,{search:t,onSearchChange:n,targetFilter:r,onTargetFilterChange:s,experimentFilter:a,onExperimentFilterChange:i,tagFilter:l,onTagFilterChange:c,tagOptions:S,onReset:E,hasActiveFilters:T,onCreateClick:C})}),o.jsx(Lhs,{datasets:u,experiments:x,isLoading:k,search:t,targetFilter:r,experimentFilter:a,tagFilter:l,isFetchingNextPage:p,hasNextPage:h,setEndOfListElement:m})]})}function n8({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function Sgs(){const{datasetId:e}=fr(),t=Vr(),[n,r]=Ma(),{activeVersion:s,handleVersionChange:a}=cRe(n,r),[i,l]=g.useState(!1),[c,u]=g.useState(!1),[d,f]=g.useState(!1),[p,h]=g.useState(!1),{data:m,error:v,isLoading:y}=My(e),{data:b=[],isLoading:x}=W1(e,void 0,s),S=!x&&b.length===0;if(y)return null;if(v&&ps(v))return o.jsx(n8,{children:o.jsx(Ts,{})});if(v&&hs(v))return o.jsx(n8,{children:o.jsx(Os,{resource:"datasets"})});if(v&&VEe(v)||!y&&!v&&!m)return o.jsx(n8,{children:o.jsx(br,{iconSlot:o.jsx(hm,{}),titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:o.jsxs(le,{as:Ba,to:"/datasets",children:[o.jsx(bl,{}),"Back to Datasets"]})})});if(v)return o.jsx(n8,{children:o.jsx($a,{title:"Failed to load dataset",message:v instanceof Error?v.message:"An unexpected error occurred. Please try again."})});const k=C=>{t(`/experiments/${C}`)},_=()=>{t("/datasets")};return o.jsxs(Ams,{datasetId:e,items:b,isLoadingItems:x,children:[o.jsxs("div",{className:"relative h-full overflow-hidden",children:[o.jsx(Lt,{height:"full",className:"grid-rows-[1fr] p-0",children:o.jsx(Lt.MainArea,{children:o.jsx(Rms,{datasetId:e,onAddItemClick:()=>u(!0),leftSlot:o.jsx("span",{className:"text-ui-sm text-neutral3 mr-3 whitespace-nowrap",children:m?.createdAt?`Created ${dr(new Date(m.createdAt),"MMM d")}`:""}),rightSlot:o.jsxs(es,{children:[o.jsxs(le,{as:Ba,to:`/experiments?dataset=${e}`,children:[o.jsx(k0e,{}),"View experiments"]}),o.jsx(DVt,{datasetId:e,value:s,onValueChange:a,currentVersion:m?.version,className:"w-36"}),S?o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx("span",{className:"cursor-not-allowed",children:o.jsx("div",{className:"pointer-events-none opacity-50",inert:!0,"aria-disabled":"true",children:o.jsxs(le,{variant:"primary",children:[o.jsx(Mc,{}),"Run Experiment"]})})})}),o.jsx(yn,{children:"Add items to the dataset before running an experiment"})]}):o.jsxs(le,{variant:"primary",onClick:()=>l(!0),children:[o.jsx(Mc,{}),"Run Experiment"]}),o.jsxs(at,{children:[o.jsx(at.Trigger,{asChild:!0,children:o.jsx(le,{size:"lg","aria-label":"Dataset actions menu",children:o.jsx(sI,{})})}),o.jsxs(at.Content,{align:"end",className:"w-48",children:[o.jsxs(at.Item,{onSelect:()=>{t(`/datasets/${e}/edit`)},children:[o.jsx(Qp,{})," Edit Dataset"]}),o.jsxs(at.Item,{onSelect:()=>h(!0),children:[o.jsx(Bd,{})," Duplicate Dataset"]}),o.jsxs(at.Item,{onSelect:()=>f(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(Fl,{})," Delete Dataset"]})]})]})]})})})}),o.jsx(Fg,{})]}),o.jsx(sY,{initialDatasetId:e,initialDatasetVersion:s??void 0,open:i,onOpenChange:l,onSuccess:k},`${e}:${s??"latest"}`),o.jsx($ms,{datasetId:e,open:c,onOpenChange:u}),m&&o.jsx(rms,{open:p,onOpenChange:h,sourceDatasetId:m.id,sourceDatasetName:m.name,sourceDatasetDescription:m.description,sourceDatasetTargetType:m.targetType}),m&&o.jsx(oms,{open:d,onOpenChange:f,datasetId:m.id,datasetName:m.name,onSuccess:_})]})}function Zie({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function kgs(){const{datasetId:e}=fr(),t=Vr(),{data:n,error:r,isLoading:s}=My(e),a=()=>{t(`/datasets/${e}`)};return s?null:r&&ps(r)?o.jsx(Zie,{children:o.jsx(Ts,{})}):r&&hs(r)?o.jsx(Zie,{children:o.jsx(Os,{resource:"datasets"})}):r||!n?o.jsx(Zie,{children:o.jsx($a,{title:"Failed to load dataset",message:r instanceof Error?r.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-6 py-8",children:[o.jsx(Aa,{className:"mb-6 p-0",children:o.jsxs(Aa.Column,{children:[o.jsxs(Aa.Title,{children:[o.jsx(hm,{})," Edit dataset"]}),o.jsx(Aa.Description,{children:n.name})]})}),o.jsx(Yu,{className:"p-6",children:o.jsx(ims,{dataset:{id:n.id,name:n.name,description:n.description||"",targetType:n.targetType,inputSchema:n.inputSchema,groundTruthSchema:n.groundTruthSchema,requestContextSchema:n.requestContextSchema},onSuccess:a,onCancel:a})})]})})]})}function aY({label:e,wide:t=!1,children:n}){return o.jsxs("div",{className:K("pointer-events-none absolute inset-0 z-30","grid transition-[grid-template-columns] duration-300 ease-in-out",t?"grid-cols-[1fr_4fr]":"grid-cols-[1fr_1fr]"),children:[o.jsx("div",{className:"pointer-events-none"}),o.jsx("div",{role:"dialog","data-item-panel":!0,"aria-label":e,className:"pointer-events-auto h-full min-h-0 min-w-0 overflow-y-auto",children:n})]})}const r8=()=>{},Ogs=new Set,_gs=[{name:"id",label:"ID",size:"7rem"},{name:"input",label:"Input",size:"minmax(10rem,1fr)"},{name:"groundTruth",label:"Ground Truth",size:"minmax(10rem,1fr)"},{name:"trajectory",label:"Trajectory",size:"8rem"},{name:"createdAt",label:"Created",size:"10rem"}];function Cgs({datasetId:e,currentItemId:t,open:n,onOpenChange:r}){const{navigate:s,paths:a}=un(),[i,l]=g.useState(""),[c]=YH(i,300),{data:u,isLoading:d,setEndOfListElement:f,isFetchingNextPage:p,hasNextPage:h}=W1(e,c||void 0),m=u.filter(y=>y.id!==t),v=y=>{r(!1),s(a.datasetItemCompareLink(e,t,y))};return o.jsx(hr,{open:n,onOpenChange:r,children:o.jsxs(mr,{className:"sm:max-w-[min(72rem,calc(100%-4rem))]",children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Compare with…"}),o.jsx(Cs,{children:"Pick an item to compare with the current one."})]}),o.jsxs(jr,{className:"grid max-h-[70vh] min-h-[24rem] grid-rows-[auto_1fr] gap-3",children:[o.jsx(y_,{name:"compare-with-dialog-search",label:"Search items to compare",labelIsHidden:!0,value:i,onChange:y=>l(y.target.value),placeholder:"Search items..."}),o.jsx("div",{className:"min-h-0 overflow-y-auto",children:o.jsx(LVt,{items:m,isLoading:d,onItemClick:v,selectOnNavigate:!1,columns:_gs,searchQuery:c||" ",setEndOfListElement:f,isFetchingNextPage:p,hasNextPage:h,isSelectionActive:!1,selectedIds:Ogs,onToggleSelection:r8,onSelectAll:r8,onClearSelection:r8,onAddClick:r8})})]})]})})}function Egs(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 Tgs({datasetId:e,item:t,items:n,onItemChange:r,onClose:s}){const{Link:a}=un(),{updateItem:i,deleteItem:l}=bi(),[c,u]=g.useState(!1),[d,f]=g.useState(""),[p,h]=g.useState(""),[m,v]=g.useState(""),[y,b]=g.useState(""),[x,S]=g.useState(""),[k,_]=g.useState(t.scorerIds!==void 0),[C,T]=g.useState(t.scorerIds??[]),[E,N]=g.useState(""),[I,A]=g.useState(null),[R,L]=g.useState(!1),[M,F]=g.useState(!1);g.useEffect(()=>{t&&(f(JSON.stringify(t.input,null,2)),h(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),v(t.metadata?JSON.stringify(t.metadata,null,2):""),b(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),S(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),_(t.scorerIds!==void 0),T(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),L(!1),A(null))},[t?.id]);const H=n.findIndex(B=>B.id===t.id),z=H>0?()=>r(n[H-1].id):void 0,q=H>=0&&H<n.length-1?()=>r(n[H+1].id):void 0,V=async()=>{let B;try{B=JSON.parse(d)}catch{ze.error("Input must be valid JSON");return}let Z;if(p.trim())try{Z=JSON.parse(p)}catch{ze.error("Ground Truth must be valid JSON");return}let Y;if(m.trim())try{Y=JSON.parse(m)}catch{ze.error("Metadata must be valid JSON");return}let te=null;if(y.trim())try{te=JSON.parse(y)}catch{ze.error("Expected Trajectory must be valid JSON");return}let J;if(x.trim())try{const oe=JSON.parse(x);if(!Array.isArray(oe)){ze.error("Tool Mocks must be a JSON array");return}J=oe}catch{ze.error("Tool Mocks must be valid JSON");return}else J=[];let ee;if(E.trim())try{ee=JSON.parse(E)}catch{ze.error("Request Context must be valid JSON");return}let re;k?re=C:t.scorerIds!==void 0&&(re=null);try{const oe=await i.mutateAsync({datasetId:e,itemId:t.id,input:B,groundTruth:Z,metadata:Y,expectedTrajectory:te,toolMocks:J,scorerIds:re,requestContext:ee});ze.success("Item updated successfully"),_(oe.scorerIds!==void 0),T(oe.scorerIds??[]),u(!1),A(null)}catch(oe){const X=Egs(oe);X?A(X):ze.error(`Failed to update item: ${oe instanceof Error?oe.message:"Unknown error"}`)}},D=()=>{f(JSON.stringify(t.input,null,2)),h(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),v(t.metadata?JSON.stringify(t.metadata,null,2):""),b(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),S(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),_(t.scorerIds!==void 0),T(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),A(null)},G=B=>{f(B),I?.field==="input"&&A(null)},U=B=>{h(B),I?.field==="groundTruth"&&A(null)},P=async()=>{try{await l.mutateAsync({datasetId:e,itemId:t.id}),ze.success("Item deleted successfully"),L(!1),s()}catch(B){ze.error(`Failed to delete item: ${B instanceof Error?B.message:"Unknown error"}`)}};return o.jsxs(o.Fragment,{children:[o.jsxs(on,{children:[o.jsxs(on.Header,{children:[o.jsxs(on.Heading,{children:["Item ",o.jsxs("b",{children:["# ",t.id.length>12?`${t.id.slice(0,12)}…`:t.id]})]}),o.jsxs(es,{className:"ml-auto shrink-0",children:[o.jsx(on.NextPrevNav,{onPrevious:z,onNext:q,previousLabel:"Previous item",nextLabel:"Next item"}),!c&&o.jsxs(o.Fragment,{children:[o.jsx(le,{as:a,href:`/datasets/${e}/items/${t.id}/versions`,size:"md",tooltip:"Go to item versions history","aria-label":"Go to item versions history",children:o.jsx(lI,{})}),o.jsxs(at,{children:[o.jsx(at.Trigger,{asChild:!0,children:o.jsx(le,{size:"md","aria-label":"Actions menu",children:o.jsx(sI,{})})}),o.jsxs(at.Content,{align:"end",className:"w-48",children:[o.jsxs(at.Item,{onSelect:()=>u(!0),children:[o.jsx(Qp,{}),"Edit"]}),o.jsxs(at.Item,{onSelect:()=>F(!0),children:[o.jsx(Tj,{}),"Compare with…"]}),o.jsxs(at.Item,{onSelect:()=>L(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(Fl,{}),"Delete Item"]})]})]})]}),o.jsx(on.CloseButton,{onClick:s,tooltip:"Close detail panel"})]})]}),o.jsx(on.Content,{children:c?o.jsx(Dms,{inputValue:d,setInputValue:G,groundTruthValue:p,setGroundTruthValue:U,metadataValue:m,setMetadataValue:v,trajectoryValue:y,setTrajectoryValue:b,toolMocksValue:x,setToolMocksValue:S,scorerOverrideEnabled:k,setScorerOverrideEnabled:_,selectedScorerIds:C,setSelectedScorerIds:T,requestContextValue:E,setRequestContextValue:N,validationErrors:I,onSave:V,onCancel:D,isSaving:i.isPending}):o.jsxs(o.Fragment,{children:[o.jsxs(Tn,{children:[o.jsx(Tn.Key,{children:"Dataset Id"}),o.jsx(Tn.ValueWithCopyBtn,{copyTooltip:"Copy Dataset Id to clipboard",copyValue:t.datasetId,children:t.datasetId}),o.jsx(Tn.Key,{children:"Version"}),o.jsxs(Tn.Value,{children:["v",t.datasetVersion]}),o.jsx(Tn.Key,{children:"Created"}),o.jsx(Tn.Value,{children:dr(new Date(t.createdAt),"MMM d, yyyy h:mm aaa")}),t.updatedAt&&new Date(t.updatedAt).getTime()!==new Date(t.createdAt).getTime()&&o.jsxs(o.Fragment,{children:[o.jsx(Tn.Key,{children:"Updated"}),o.jsx(Tn.Value,{children:dr(new Date(t.updatedAt),"MMM d, yyyy h:mm aaa")})]})]}),o.jsxs("div",{className:"mt-3 grid gap-3",children:[o.jsx(on.CodeSection,{title:"Input",icon:o.jsx(wx,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(on.CodeSection,{title:"Ground Truth",icon:o.jsx(rm,{}),codeStr:JSON.stringify(t.groundTruth??null,null,2)}),t.expectedTrajectory!=null&&o.jsx(on.CodeSection,{title:"Expected Trajectory",icon:o.jsx(I0e,{}),codeStr:JSON.stringify(t.expectedTrajectory,null,2)}),o.jsx(on.CodeSection,{title:"Tool Mocks",icon:o.jsx(qd,{}),codeStr:JSON.stringify(t.toolMocks??[],null,2)}),o.jsx(on.CodeSection,{title:"Scorers",icon:o.jsx(PV,{}),codeStr:t.scorerIds===void 0?"Inherited from dataset":JSON.stringify(t.scorerIds,null,2)}),t.requestContext!=null&&o.jsx(on.CodeSection,{title:"Request Context",icon:o.jsx(sc,{}),codeStr:JSON.stringify(t.requestContext,null,2)}),o.jsx(on.CodeSection,{title:"Metadata",icon:o.jsx(cI,{}),codeStr:JSON.stringify(t.metadata??null,null,2)})]})]})})]}),o.jsx(Cgs,{datasetId:e,currentItemId:t.id,open:M,onOpenChange:F}),o.jsx(Mt,{open:R,onOpenChange:L,children:o.jsxs(Mt.Content,{children:[o.jsxs(Mt.Header,{children:[o.jsx(Mt.Title,{children:"Delete Item"}),o.jsx(Mt.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),o.jsxs(Mt.Footer,{children:[o.jsx(Mt.Cancel,{children:"Cancel"}),o.jsx(Mt.Action,{onClick:P,children:l.isPending?"Deleting...":"Yes, Delete"})]})]})})]})}function jgs(){const{itemId:e}=fr(),{datasetId:t,items:n,isLoadingItems:r,openItem:s,close:a}=BVt(),i=g.useMemo(()=>n.find(d=>d.id===e)??null,[n,e]),{data:l,isLoading:c}=GD(i?"":t,!i&&e?e:""),u=i??l??null;return e?o.jsx(aY,{label:`Dataset item ${e}`,children:u?o.jsx("div",{className:"[&>section]:bg-surface3 flex min-h-full flex-col p-3 [&>section]:min-h-0 [&>section]:flex-1 [&>section]:rounded-lg [&>section]:shadow-lg",children:o.jsx(Tgs,{datasetId:t,item:u,items:n,onItemChange:s,onClose:a})}):r||c?o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(Ut,{})})}):o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(br,{iconSlot:o.jsx(hm,{}),titleSlot:"Item not found",descriptionSlot:`No loaded item "${e}".`,actionSlot:o.jsx(le,{onClick:a,children:"Close"})})})})}):null}function ctt(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,metadata:e.metadata??null},null,2)}function Ngs(){const{datasetId:e,itemId:t,secondItemId:n}=fr(),r=Vr(),s=[t,n].filter(h=>!!h),{data:a,error:i}=My(e??""),{Link:l,paths:c}=un(),[u,d]=g.useState(!1),{data:f}=GD(e??"",s[0]??""),{data:p}=GD(e??"",s[1]??"");return i&&ps(i)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{})})}):i&&hs(i)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Os,{resource:"datasets"})})}):!e||s.length<2?o.jsx(vs,{children:o.jsx(hy,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Select at least two items to compare."})})})}):o.jsxs(vs,{children:[o.jsx(Dy,{owner:"dataset-items-compare",children:o.jsxs(le,{as:Ba,to:`/datasets/${e}`,variant:"outline",children:[o.jsx(bl,{}),"Back to Dataset"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:K("grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",{"grid-rows-[auto_auto_1fr]":u}),children:[o.jsxs(Aa,{children:[o.jsxs(Aa.Column,{children:[o.jsxs(Aa.Title,{children:[o.jsx(Tj,{}),"Compare Dataset Items"]}),o.jsx(Aa.Description,{children:o.jsxs(Pl,{children:["Comparing ",s.length," items of"," ",o.jsx(Ba,{to:`/datasets/${e}`,className:"text-info1 hover:underline",children:a?.name||e?.slice(0,8)})]})})]}),o.jsx(Aa.Column,{children:o.jsx(es,{children:o.jsx(le,{variant:"primary",onClick:()=>d(h=>!h),children:u?o.jsxs(o.Fragment,{children:[o.jsx(TV,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx($Yt,{})," Diff View"]})})})})]}),o.jsx(r1,{className:"grid-cols-[1fr_3vw_1fr]",children:s.map((h,m)=>o.jsxs(g.Fragment,{children:[o.jsx(Igs,{datasetId:e,itemId:h,Link:l,idx:m,itemIds:s,showContent:!u,onItemChange:v=>{const y=[...s];y[m]=v,r(c.datasetItemCompareLink(e,y[0],y[1]))}}),m==0&&o.jsx("div",{className:K("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},h))}),u&&f&&p&&o.jsx(NAe,{codeA:ctt(f),codeB:ctt(p)})]})})]})}function Igs({datasetId:e,itemId:t,Link:n,idx:r,itemIds:s,onItemChange:a,showContent:i=!0}){const{data:l,isLoading:c}=GD(e,t),{data:u}=W1(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(pa,{children:[o.jsxs(pa.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(xr,{value:p.value,disabled:p.disabled,children:p.label},p.value))})]}),o.jsxs(le,{as:n,to:`/datasets/${e}/items/${t}`,children:[o.jsx(lI,{}),"Versions"]})]}),i&&o.jsx(pa.Content,{children:c?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):l?o.jsxs(o.Fragment,{children:[o.jsx(Mms,{item:l}),o.jsx(uRe,{item:l,Link:n})]}):o.jsxs("div",{className:"text-neutral4 text-sm",children:["Item ",t.slice(0,8)," not found"]})})]})}function utt(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,scorerIds:e.scorerIds??null,metadata:e.metadata??null},null,2)}function Ags(){const{datasetId:e,itemId:t}=fr(),[n,r]=Ma(),[s,a]=g.useState(!1),i=n.get("ids")?.split(",").map(Number).filter(h=>!isNaN(h)&&h>0)??[],{data:l,error:c}=My(e??""),{Link:u}=un(),{data:d}=lRe(e??"",t??""),{data:f}=t0e(e??"",t??"",i[0]??0,l?.version),{data:p}=t0e(e??"",t??"",i[1]??0,l?.version);return c&&ps(c)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{})})}):c&&hs(c)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Os,{resource:"datasets"})})}):!e||!t?o.jsx(vs,{children:o.jsx(hy,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Item not found."})})})}):i.length<2?o.jsx(Rgs,{datasetId:e,itemId:t,Link:u,onCompare:h=>r({ids:h.join(",")})}):o.jsxs(vs,{children:[o.jsx(Dy,{owner:"dataset-item-versions-compare",children:o.jsxs(le,{as:Ba,to:`/datasets/${e}/items/${t}`,variant:"outline",children:[o.jsx(bl,{}),"Back to Item"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:K("grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",{"grid-rows-[auto_auto_1fr]":s}),children:[o.jsxs(Aa,{children:[o.jsxs(Aa.Column,{children:[o.jsxs(Aa.Title,{children:[o.jsx(Tj,{}),"Compare Dataset Item Versions"]}),o.jsx(Aa.Description,{children:o.jsxs(Pl,{children:["Comparing ",i.length," versions of"," ",o.jsx(Ba,{to:`/datasets/${e}/items/${t}`,className:"text-info1 hover:underline",children:t})]})})]}),o.jsx(Aa.Column,{children:o.jsx(es,{children:o.jsx(le,{variant:"primary",onClick:()=>a(h=>!h),children:s?o.jsxs(o.Fragment,{children:[o.jsx(TV,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(NKt,{})," Diff View"]})})})})]}),o.jsx(r1,{className:"grid-cols-[1fr_3vw_1fr]",children:i.map((h,m)=>o.jsxs(g.Fragment,{children:[o.jsx(Pgs,{datasetId:e,itemId:t,datasetVersion:h,latestVersion:l?.version,allVersions:d??[],versionNumbers:i,Link:u,idx:m,showContent:!s,onVersionChange:v=>{const y=[...i];y[m]=v,r({ids:y.join(",")})}}),m===0&&o.jsx("div",{className:K("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},h))}),s&&f&&p&&o.jsx(NAe,{codeA:utt(f),codeB:utt(p)})]})})]})}function Rgs({datasetId:e,itemId:t,Link:n,onCompare:r}){const[s,a]=g.useState(null),{data:i,isLoading:l}=lRe(e,t),c=(s!=null?i?.find(d=>d.datasetVersion===s):void 0)??i?.[0],u=c?{id:c.id,datasetId:e,datasetVersion:c.datasetVersion,input:c.input,groundTruth:c.groundTruth,scorerIds:c.scorerIds,metadata:c.metadata,createdAt:c.createdAt,updatedAt:c.updatedAt}:null;return o.jsxs(vs,{children:[o.jsx(Dy,{owner:"dataset-item-versions-history",children:o.jsxs(le,{as:Ba,to:`/datasets/${e}/items/${t}`,variant:"outline",children:[o.jsx(bl,{}),"Back to Item"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:"mx-auto grid h-full max-w-[140rem] grid-rows-[auto_1fr] gap-6",children:[o.jsx(Aa,{children:o.jsxs(Aa.Column,{children:[o.jsxs(Aa.Title,{children:[o.jsx(lI,{}),"Item Version History"]}),o.jsx(Aa.Description,{children:o.jsxs(Pl,{children:["Versions of ",t]})})]})}),o.jsxs(r1,{className:"grid-cols-[1fr_auto]",children:[o.jsx(pa,{children:o.jsx(pa.Content,{children:l?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):u?o.jsx(uRe,{item:u,Link:n}):o.jsx("div",{className:"text-neutral4 text-sm",children:"Item data not available"})})}),o.jsx(hgs,{datasetId:e,itemId:t,onClose:()=>{},onVersionSelect:d=>a(d.datasetVersion),onCompareVersionsClick:r,activeVersion:s})]})]})})]})}function Pgs({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}=t0e(e,t,n,r),p=new Set(a.filter((v,y)=>y!==l)),h=s.map(v=>{const y=typeof v.updatedAt=="string"?new Date(v.updatedAt):v.updatedAt;return{value:String(v.datasetVersion),label:o.jsxs(o.Fragment,{children:[o.jsxs("b",{children:["v. ",v.datasetVersion]})," - ",dr(y,"MMM d, yyyy h:mm a"),v.isLatest?o.jsx(xt,{variant:"blue",size:"xs",children:"Latest"}):null]}),disabled:p.has(v.datasetVersion)}}),m=d?{id:d.id,datasetId:e,datasetVersion:d.datasetVersion,input:d.input,groundTruth:d.groundTruth,scorerIds:d.scorerIds,metadata:d.metadata,createdAt:d.createdAt,updatedAt:d.updatedAt}:null;return o.jsxs(pa,{children:[o.jsxs(pa.Toolbar,{className:"grid grid-cols-[auto_1fr] gap-4",children:[o.jsx(lI,{className:"h-6 w-6 opacity-50"}),o.jsxs(oa,{name:`compare-version-${l}`,value:String(n),onValueChange:v=>u(Number(v)),children:[o.jsx(ca,{"aria-label":"Version",className:"w-full",children:o.jsx(la,{placeholder:"Select version"})}),o.jsx(ua,{children:h.map(v=>o.jsx(xr,{value:v.value,disabled:v.disabled,children:v.label},v.value))})]})]}),c&&o.jsx(pa.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(uRe,{item:m,Link:i})})]})}function $gs(){const{datasetId:e}=fr(),[t]=Ma(),n=t.get("ids")?.split(",").map(Number).filter(v=>!isNaN(v)&&v>0)??[],r=Vr(),{data:s,error:a}=My(e??""),i=W1(e??"",void 0,n[0]??null),l=W1(e??"",void 0,n[1]??null),c=g.useMemo(()=>i.data??[],[i.data]),u=g.useMemo(()=>l.data??[],[l.data]),d=g.useMemo(()=>{const v=new Map;for(const y of[...c,...u])v.has(y.id)||v.set(y.id,{id:y.id,createdAt:new Date(y.createdAt)});return[...v.values()].sort((y,b)=>b.createdAt.getTime()-y.createdAt.getTime())},[c,u]),f=g.useMemo(()=>new Map(c.map(v=>[v.id,v])),[c]),p=g.useMemo(()=>new Map(u.map(v=>[v.id,v])),[u]);if(a&&ps(a))return o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{})})});if(a&&hs(a))return o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Os,{resource:"datasets"})})});if(!e||n.length<2)return o.jsx(vs,{children:o.jsx(hy,{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=(v,y,b)=>{r(`/datasets/${e}/items/${v}/versions?ids=${y?.datasetVersion??""},${b?.datasetVersion??""}`)},m=(v,y)=>{r(`/datasets/${e}/versions?ids=${v},${y}`,{replace:!0})};return o.jsx(vs,{children:o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:"mx-auto grid h-full max-w-[140rem] grid-rows-[auto_1fr] gap-6",children:[o.jsxs(Aa,{children:[o.jsxs(Aa.Column,{children:[o.jsxs(Aa.Title,{children:[o.jsx(FJt,{})," Compare Dataset Versions"]}),o.jsx(Aa.Description,{children:o.jsxs(Pl,{children:[o.jsx(lI,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),o.jsx(Aa.Column,{children:o.jsxs(le,{as:Ba,to:`/datasets/${e}`,children:[o.jsx(bl,{}),"Back to Dataset"]})})]}),o.jsx(r1,{children:o.jsxs(pa,{children:[o.jsx(vgs,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:m}),o.jsx(xgs,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:p,onItemClick:h})]})})]})})})}function Mgs(){const e=Vr(),[t]=Ma(),n=t.get("targetType"),r=YD(n)?n:void 0,s=t.get("targetIds"),a=r&&s?s.split(",").map(i=>i.trim()).filter(Boolean):void 0;return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-6 py-8",children:[o.jsx(Aa,{className:"mb-6 p-0",children:o.jsxs(Aa.Column,{children:[o.jsxs(Aa.Title,{children:[o.jsx(hm,{})," Create new dataset"]}),o.jsx(Aa.Description,{children:"Datasets group test cases used to evaluate your agents and workflows."})]})}),o.jsx(Yu,{className:"p-6",children:o.jsx(ems,{targetType:r,targetIds:a,onSuccess:i=>{e(`/datasets/${i}`)},onCancel:()=>{e(-1)}})})]})})]})}function s0e({children:e,className:t}){return o.jsx("div",{className:K("flex flex-wrap gap-8",t),children:e})}function Dgs(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 Lgs({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,v=Dgs(n);return o.jsxs(o.Fragment,{children:[o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Total Scorers"}),i?o.jsx(Xr.Loading,{}):f!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(f)}),o.jsx(Xr.NoChange,{message:"Static count"})]}):o.jsx(Xr.NoData,{})]}),o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Total Datasets"}),l?o.jsx(Xr.Loading,{}):p!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(p)}),o.jsx(Xr.NoChange,{message:"Static count"})]}):o.jsx(Xr.NoData,{})]}),o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Avg Score"}),u?o.jsx(Xr.Loading,{}):r!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(r)}),m?o.jsx(Xr.Change,{changePct:m.changePct,prevValue:m.prevValue}):o.jsx(Xr.NoChange,{})]}):o.jsx(Xr.NoData,{})]}),o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Total Experiments"}),c?o.jsx(Xr.Loading,{}):h!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(h)}),v?o.jsx(Xr.Change,{changePct:v.changePct,prevValue:v.prevValue}):o.jsx(Xr.NoChange,{})]}):o.jsx(Xr.NoData,{})]}),o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Needs Review"}),d?o.jsx(Xr.Loading,{}):a!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(a)}),a>0?o.jsx(Xr.NoChange,{message:"items pending review"}):o.jsx(Xr.NoChange,{message:"All caught up"})]}):o.jsx(Xr.NoData,{})]})]})}function ZVt(e){const t=h0(e.id)??e.id;return e.name||`Experiment #${t}`}const Fgs=60;function zgs({experiment:e}){return o.jsx("span",{className:"text-neutral4 block min-w-0 truncate text-left",children:ZVt(e)})}function Bgs({experiment:e}){const t=e.description;if(!t)return o.jsx("span",{className:"text-neutral2",children:"—"});const n=o.jsx("span",{className:"text-neutral3 block min-w-0 truncate text-left",children:t});return t.length<=Fgs?n:o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:n}),o.jsx(yn,{children:t})]})}const iY=()=>{const{requestContext:e}=ys(),t=Ge();return mt({queryKey:["processors"],queryFn:()=>t.listProcessors(e)})},GVt=(e,t)=>{const n=Ge(),{requestContext:r}=ys();return mt({queryKey:["processor",e],queryFn:()=>n.getProcessor(e).details(r),enabled:!!e})},Ugs=()=>{const e=Ge(),{requestContext:t}=ys();return Sn({mutationFn:async({processorId:n,phase:r,messages:s,agentId:a})=>e.getProcessor(n).execute({phase:r,messages:s,agentId:a,requestContext:t})})};function QVt(){const{data:e}=zm(),{data:t}=Gy(),{data:n}=uh(),{data:r}=iY();return{agents:e,workflows:t,scorers:n,processors:r}}const YVt={agent:Ai,workflow:Bc,scorer:AC,processor:ID},KVt={agent:"Agent",workflow:"Workflow",scorer:"Scorer",processor:"Processor"},qgs="External (caller-run)";function XVt(e,{agents:t,workflows:n,scorers:r,processors:s}){const{targetType:a,targetId:i}=e;if(!i)return qgs;switch(a){case"agent":return t?.[i]?.name??i;case"workflow":return n?.[i]?.name??i;case"scorer":return r?.[i]?.scorer?.config?.name??i;case"processor":return s?.[i]?.name??i;default:return i}}function Vgs({experiment:e,datasetName:t,review:n}){const r=e.status??"pending",s=e.succeededCount??0,a=e.failedCount??0,i=e.totalItems??0;return o.jsxs(o.Fragment,{children:[o.jsx(he.Cell,{children:o.jsx(zgs,{experiment:e})}),o.jsx(he.Cell,{children:o.jsx(Bgs,{experiment:e})}),t!==void 0&&o.jsx(he.TextCell,{children:t}),o.jsx(he.Cell,{children:o.jsx(Hgs,{experiment:e})}),o.jsx(he.Cell,{children:o.jsx(xt,{variant:RUt[r]??"neutral",indicator:"dot",children:DT[r]??r})}),o.jsx(he.TextCell,{className:"text-center",children:i}),o.jsx(he.TextCell,{className:"text-center",children:s}),o.jsx(he.TextCell,{className:"text-center",children:o.jsx("span",{className:a>0?"text-accent2":"",children:a})}),o.jsx(he.Cell,{className:"text-center",children:o.jsx(Wgs,{review:n})}),o.jsx(he.TextCell,{children:Los(e.createdAt)})]})}function Hgs({experiment:e}){const t=QVt(),n=XVt(e,t),r=e.targetId?e.targetType:null,s=r?YVt[r]:null;return o.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 [&_svg]:size-3.5 [&_svg]:shrink-0",children:[s&&o.jsx("span",{className:"text-neutral3 flex",role:"img","aria-label":KVt[r],children:o.jsx(s,{})}),o.jsx("span",{className:r?"truncate":"text-neutral2 truncate",children:n})]})}function Wgs({review:e}){if(!e)return o.jsx("span",{className:"text-neutral2",children:"—"});const t=e.needsReview+e.complete;return t===0?o.jsx("span",{className:"text-neutral2",children:"—"}):e.needsReview>0?o.jsxs(xt,{size:"xs",variant:"yellow",children:[e.needsReview," pending"]}):o.jsxs(xt,{size:"xs",variant:"green",children:[e.complete,"/",t," reviewed"]})}const Gie=`${Pos} ${$os} ${Mos} ${Dos}`,Zgs=[{label:kv.experiment},{label:kv.description},{label:kv.dataset},{label:kv.target},{label:kv.status},{label:kv.items,className:"text-center"},{label:kv.succeeded,className:"text-center"},{label:kv.failed,className:"text-center"},{label:kv.review,className:"text-center"},{label:kv.date}];function Ggs({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:a="all",datasetFilter:i="all",selection:l}){const c=l!==void 0,{paths:u,Link:d}=un(),f=g.useMemo(()=>{const x=new Map;return t?.forEach(S=>x.set(S.id,S.name)),x},[t]),p=g.useMemo(()=>[...e].sort((x,S)=>{const k=x.createdAt?new Date(x.createdAt).getTime():0;return(S.createdAt?new Date(S.createdAt).getTime():0)-k}),[e]),h=g.useMemo(()=>{const x=s.toLowerCase();return p.filter(S=>{const k=S.datasetId?f.get(S.datasetId)??"":"",_=!x||S.id.toLowerCase().includes(x)||(S.name??"").toLowerCase().includes(x)||k.toLowerCase().includes(x)||(S.targetId??"").toLowerCase().includes(x),C=a==="all"||S.status===a,T=i==="all"||S.datasetId===i;return _&&C&&T})},[p,s,f,a,i]),{containerRef:m,getRowProps:v}=so({count:h.length});if(r)return o.jsx(Fo,{columns:Gie});const y=c?`auto ${Gie}`:Gie,b=Zgs.map(x=>o.jsx(he.TopCell,{className:x.className,children:x.label},x.label));return o.jsxs(he,{columns:y,scrollRef:m,children:[o.jsx(he.Top,{hasLeadingCell:c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(he.TopCell,{children:" "}),o.jsx(he.TopCells,{colStart:2,children:b})]}):b}),h.map((x,S)=>{const k=x.datasetId?f.get(x.datasetId)??h0(x.datasetId)??x.datasetId:"—",_=o.jsx(Vgs,{experiment:x,datasetName:k,review:n?.get(x.id)});if(!l)return o.jsx(he.RowLink,{to:u.experimentLink(x.id),LinkComponent:d,...v(S),children:_},x.id);const C=l.selectedExperimentIds.includes(x.id),T=()=>l.onToggleSelection(x.id);return o.jsxs(he.RowWrapper,{children:[o.jsx(he.SelectCell,{checked:C,onToggle:T,"aria-label":`Select experiment ${x.id}`}),o.jsx(he.RowButton,{colStart:2,featured:C,onClick:T,...v(S),children:_})]},x.id)})]})}const Qgs=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function Ygs(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const s8={completed:F7.neutral3,running:"#facc15",pending:"#fb923c",failed:"#f87171"},Kgs=[{label:"Completed",color:s8.completed},{label:"Running",color:s8.running},{label:"Pending",color:s8.pending},{label:"Failed",color:s8.failed}];function Xgs({experiments:e,datasets:t,isLoading:n,isError:r}){const{data:s,maxVal:a}=g.useMemo(()=>{if(!e||e.length===0)return{data:[],maxVal:0};const l=new Map;if(t)for(const f of t)l.set(f.id,f.name);const c=new Map;for(const f of e){const 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(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Experiments by Dataset",description:"Experiment status breakdown per dataset."}),i&&o.jsx(Vt.Summary,{value:String(e?.length??0),label:"Total experiments"})]}),n?o.jsx(Vt.Loading,{}):r?o.jsx(Vt.Error,{message:"Failed to load experiments data"}):o.jsx(Vt.Content,{children:i?o.jsx(QN,{data:s,segments:Kgs,maxVal:a,fmt:l=>String(l)}):o.jsx(Vt.NoData,{message:"No experiments have been run yet"})})]})}const Jgs=({onRunExperiment:e})=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx($c,{}),titleSlot:"No Experiments yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Run an experiment from a dataset to evaluate ",o.jsx("br",{}),"your agents and workflows."]}),actionSlot:o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e&&o.jsxs(le,{variant:"primary",onClick:e,children:[o.jsx(Mc,{}),"Run Experiment"]}),o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/evals/experiments",target:"_blank",rel:"noopener noreferrer",children:["Experiments Documentation ",o.jsx(ea,{})]})]})})});function evs({search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:i,onReset:l,hasActiveFilters:c,onRunClick:u,runTooltip:d="Run an experiment",onCompareClick:f,selection:p}){if(p){const{selectedCount:h,onExecuteCompare:m,onCancelSelection:v,compareDisabledReason:y}=p,b=h===2&&!y;return o.jsx("div",{className:"flex w-full items-center justify-end gap-4",children:o.jsxs("div",{className:"flex items-center gap-5",children:[o.jsxs("div",{className:"text-neutral3 flex items-center gap-2 pl-6 text-sm",children:[o.jsx(xt,{size:"md",variant:h<2?"red":"green",children:h}),o.jsx("span",{children:"of 2 experiments selected"}),y&&o.jsxs("span",{className:"text-accent2",children:["— ",y]}),o.jsx(wct,{})]}),o.jsxs(es,{children:[o.jsxs(le,{variant:"primary",disabled:!b,onClick:m,children:[o.jsx(Tj,{className:"h-4 w-4"}),"Compare Experiments"]}),o.jsx(le,{onClick:v,children:"Cancel"})]})]})})}return o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("div",{className:"max-w-120 min-w-64 flex-1",children:o.jsx(od,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t})}),o.jsxs(es,{children:[o.jsx(Ld,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...Qgs],value:n,onValueChange:r,className:"whitespace-nowrap"}),o.jsx(Ld,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:i,value:s,onValueChange:a,className:"whitespace-nowrap"}),l&&c&&o.jsxs(le,{onClick:l,size:"sm",variant:"default",children:[o.jsx(or,{className:"size-3"})," Reset"]})]}),o.jsxs(es,{className:"ml-auto shrink-0",children:[f&&o.jsxs(le,{onClick:f,tooltip:"Select two experiments of the same dataset to compare",children:[o.jsx(Tj,{}),"Compare"]}),u&&o.jsxs(le,{onClick:u,tooltip:d,variant:"primary",children:[o.jsx(Mc,{}),"Run Experiment"]})]})]})}const tvs={present:!1,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},dtt=e=>e?e instanceof Date?e.toISOString():e:null,ftt=e=>{const t=new Map;for(const n of e??[])t.set(n.itemId,n);return t},ptt=(e,t,n)=>{if(!e)return tvs;const r=new Map;for(const s of n??[])r.set(s.scorerId,s.reason??null);return{present:!0,output:e.output,metadata:t?.metadata??null,comment:t?.comment??null,error:t?.error??null,startedAt:dtt(t?.startedAt),completedAt:dtt(t?.completedAt),scores:Object.entries(e.scores).map(([s,a])=>({scorerId:s,value:a,reason:r.get(s)??null})).sort((s,a)=>s.scorerId.localeCompare(a.scorerId))}},nvs=({comparison:e,baselineId:t,contenderId:n,baselineResults:r,contenderResults:s,baselineScores:a,contenderScores:i})=>{if(!e)return[];const l=ftt(r),c=ftt(s);return e.items.map(u=>{const d=ptt(u.results[t],l.get(u.itemId),a?.[u.itemId]),f=ptt(u.results[n],c.get(u.itemId),i?.[u.itemId]),p={};for(const h of new Set([...d.scores,...f.scores].map(m=>m.scorerId))){const m=d.scores.find(y=>y.scorerId===h)?.value??null,v=f.scores.find(y=>y.scorerId===h)?.value??null;p[h]=m!=null&&v!=null?v-m:null}return{itemId:u.itemId,input:u.input,groundTruth:u.groundTruth,baseline:d,contender:f,deltas:p}})};function Rk({title:e,actions:t,tone:n="default",defaultOpen:r=!0,children:s}){return o.jsxs(Lc,{defaultOpen:r,className:"grid gap-2",children:[o.jsxs("div",{className:"flex min-h-6 items-center justify-between gap-2",children:[o.jsxs(fc,{className:K("text-ui-md flex items-center gap-1.5 font-semibold [&>svg]:size-4",n==="negative"?"text-negative1":"text-neutral5"),children:[o.jsx(Br,{}),e]}),t]}),o.jsx(pc,{role:"region","aria-label":e,children:s})]})}function htt({label:e,value:t}){return t==null?null:o.jsx(Rk,{title:e,defaultOpen:!1,children:o.jsx("pre",{className:"text-ui-sm text-neutral4 bg-surface3 max-h-40 overflow-auto rounded-md p-3 whitespace-pre-wrap",children:typeof t=="string"?t:JSON.stringify(t,null,2)})})}function JVt({delta:e}){const t=e>0?"text-positive1":e<0?"text-negative1":"text-neutral3";return o.jsxs("span",{className:K("inline-flex min-w-20 items-center gap-1 font-mono text-sm",t),children:[o.jsx("span",{className:"inline-block w-3",children:e>0?"+":e<0?"-":""}),Math.abs(e).toFixed(2),e>0?o.jsx(pQt,{className:"size-3.5"}):e<0?o.jsx(rQt,{className:"size-3.5"}):null]})}function eHt({scorerId:e,value:t,delta:n,reason:r}){const{Link:s,paths:a}=un();return o.jsxs("div",{className:"bg-surface2 grid gap-1 rounded-lg px-3 py-2",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4",children:[o.jsxs(s,{href:a.scorerLink(e),"aria-label":`Open ${e}`,className:"text-neutral5 flex min-w-0 items-center gap-1.5 text-sm font-medium hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[o.jsx(AC,{}),o.jsx("span",{className:"min-w-0 truncate",children:e})]}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:"text-neutral3 font-mono text-sm",children:t!=null?t.toFixed(2):"-"}),n!=null&&o.jsx(JVt,{delta:n})]})]}),r&&o.jsx("p",{className:"text-neutral3 text-sm",children:r})]})}function mtt(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function rvs(e){if(!e.startedAt||!e.completedAt)return null;const t=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return Number.isFinite(t)?`${(t/1e3).toFixed(2)}s`:null}const svs="border-border1 bg-surface3 text-ui-md text-neutral4 max-h-[30vh] overflow-y-auto rounded-xl border p-4 font-mono break-all whitespace-pre-wrap dark:border-white/10 dark:bg-black/20";function gtt({side:e,row:t,showDeltas:n,isLoading:r}){const s=t[e],a=rvs(s);if(r)return o.jsx("div",{className:"flex h-32 items-center justify-center",children:o.jsx(Ut,{})});if(!s.present)return o.jsx("p",{className:"text-neutral3 py-8 text-center text-sm",children:"Not present in this experiment"});const i=mtt(s.output);return o.jsxs("div",{className:"grid content-start gap-5",children:[a&&o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsxs("p",{className:"text-neutral3 flex items-center justify-end gap-1.5 text-sm [&>svg]:size-3.5",children:[o.jsx(a1,{}),a]})}),o.jsx(yn,{children:"Run duration"})]}),s.error?o.jsx(Rk,{title:"Error",tone:"negative",actions:o.jsx(ka,{content:s.error.message}),children:o.jsx("p",{className:"border-negative1/40 bg-negative1/5 text-ui-md text-neutral4 rounded-xl border p-4 break-words",children:s.error.message})}):o.jsx(Rk,{title:"Output",actions:o.jsx(ka,{content:i}),children:o.jsx("pre",{className:svs,children:i})}),s.scores.length>0&&o.jsx(Rk,{title:"Scores",children:o.jsx("div",{className:"grid gap-2",children:s.scores.map(l=>o.jsx(eHt,{scorerId:l.scorerId,value:l.value,delta:n?t.deltas[l.scorerId]:null,reason:l.reason},l.scorerId))})}),s.comment&&o.jsx(Rk,{title:"Comment",defaultOpen:!1,children:o.jsx("p",{className:"text-neutral3 text-sm",children:s.comment})}),s.metadata&&Object.keys(s.metadata).length>0&&o.jsx(Rk,{title:"Metadata",defaultOpen:!1,children:o.jsx("dl",{className:"grid gap-1",children:Object.entries(s.metadata).map(([l,c])=>o.jsxs("div",{className:"flex items-start justify-between gap-4 text-sm",children:[o.jsx("dt",{className:"text-neutral3",children:l}),o.jsx("dd",{className:"text-neutral5 font-mono break-all",children:mtt(c)})]},l))})})]})}const avs={baseline:"Baseline",contender:"Contender"},ivs={baseline:"purple",contender:"blue"},ovs="flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0";function vtt({side:e,experiment:t,summary:n,showDeltas:r,versionMismatch:s}){const{Link:a,paths:i}=un(),l=avs[e],c=t?h0(t.id)??t.id:null,u=t?.createdAt?new Date(t.createdAt):null,d=n??[];return o.jsxs("div",{className:"grid content-start gap-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(xt,{variant:ivs[e],size:"xs",children:l}),t&&o.jsx(le,{as:a,size:"xs",href:`/experiments/${t.id}`,"aria-label":`Open experiment ${t.name||c}`,children:o.jsx("span",{className:"min-w-0 truncate",children:t.name||c})})]}),t&&o.jsxs("div",{className:"text-ui-sm text-neutral3 flex flex-wrap gap-x-4 gap-y-1",children:[t.name&&o.jsxs(Pl,{children:[o.jsx(AV,{})," ",c]}),t.targetType==="agent"&&t.targetId?o.jsxs(a,{href:i.agentLink(t.targetId),className:ovs,children:[o.jsx(Ai,{}),o.jsx("span",{className:"min-w-0 truncate",children:t.targetId})]}):o.jsxs(Pl,{children:[o.jsx(jct,{})," ",t.targetId]}),o.jsx("span",{className:K(s&&"text-accent6"),children:o.jsxs(Pl,{children:[o.jsx(RV,{})," v",t.datasetVersion??"—",s&&" · different dataset version"]})}),u&&o.jsxs(Pl,{children:[o.jsx(U9,{})," ",dr(u,"MMM d, yyyy HH:mm")]})]}),d.length>0&&o.jsx(Rk,{title:"Overall score",children:o.jsx("div",{className:"grid gap-2",children:d.map(({scorerId:f,average:p,delta:h})=>o.jsx(eHt,{scorerId:f,value:p,delta:r?h:null},f))})})]})}const qE="min-w-0 px-4 py-3";function lvs({datasetId:e,experimentIdA:t,experimentIdB:n}){const{Link:r,paths:s}=un(),{data:a,isLoading:i,error:l}=mhs(e,t,n),{data:c}=WD(e,t),{data:u}=WD(e,n),d=c&&u&&c.datasetVersion!==u.datasetVersion,f=a?.baselineId??t,p=t===f?n:t,h=c?.id===f?c:u,m=c?.id===p?c:u,{data:v,isLoading:y}=ZD({datasetId:e,experimentId:f,experimentStatus:h?.status}),{data:b,isLoading:x}=ZD({datasetId:e,experimentId:p,experimentStatus:m?.status}),{data:S}=C_(f,h?.status),{data:k}=C_(p,m?.status),_=g.useMemo(()=>nvs({comparison:a,baselineId:f,contenderId:p,baselineResults:v,contenderResults:b,baselineScores:S,contenderScores:k}),[a,f,p,v,b,S,k]),C=g.useMemo(()=>[...new Set(_.flatMap(E=>Object.keys(E.deltas)))].sort(),[_]),T=g.useMemo(()=>{const E=(A,R)=>{const L=_.map(M=>M[A].scores.find(F=>F.scorerId===R)?.value).filter(M=>M!=null);return L.length>0?L.reduce((M,F)=>M+F,0)/L.length:null},N=C.map(A=>({scorerId:A,average:E("baseline",A),delta:null})),I=C.map(A=>{const R=E("baseline",A),L=E("contender",A);return{scorerId:A,average:L,delta:R!=null&&L!=null?L-R:null}});return{baseline:N,contender:I}},[_,C]);return i?o.jsx("div",{className:"flex h-64 items-center justify-center",children:o.jsx(Ut,{})}):l?o.jsx(Rn,{variant:"warning",title:"Error loading comparison",children:o.jsx(Rn.Message,{children:l instanceof Error?l.message:"Unknown error"})}):!a||a.items.length===0?o.jsx("div",{className:"text-neutral4 py-8 text-center text-sm",children:"No comparison data"}):o.jsx("div",{className:"grid gap-4",children:o.jsxs("div",{role:"table","aria-label":"Experiments comparison",className:"grid",children:[o.jsxs("div",{role:"row",className:"border-border1 grid border-y xl:grid-cols-[minmax(20rem,24rem)_1fr_1fr] xl:divide-x xl:divide-[var(--border1)]",children:[o.jsx("div",{role:"columnheader","aria-label":"Items",className:`${qE} text-neutral3 text-ui-sm uppercase`,children:"Items"}),o.jsx("div",{role:"columnheader","aria-label":"Baseline",className:qE,children:o.jsx(vtt,{side:"baseline",experiment:h,summary:T.baseline,versionMismatch:d})}),o.jsx("div",{role:"columnheader","aria-label":"Contender",className:qE,children:o.jsx(vtt,{side:"contender",experiment:m,summary:T.contender,versionMismatch:d,showDeltas:!0})})]}),_.map(E=>{const N=Object.entries(E.deltas).filter(([,I])=>I!=null&&I!==0);return o.jsxs("div",{role:"row","aria-label":E.itemId,className:"border-border1 grid border-b xl:grid-cols-[minmax(20rem,24rem)_1fr_1fr] xl:divide-x xl:divide-[var(--border1)]",children:[o.jsxs("div",{role:"cell",className:`${qE} grid content-start gap-1`,children:[o.jsx(r,{href:s.datasetItemLink(e,E.itemId),"aria-label":`Open item ${E.itemId}`,className:K("text-ui-sm flex items-start gap-1.5 font-mono break-all hover:underline [&>svg]:mt-0.5 [&>svg]:size-3.5 [&>svg]:shrink-0",E.baseline.present&&E.contender.present?"text-neutral4":"text-neutral1"),children:o.jsx("span",{className:"min-w-0",children:E.itemId})}),N.length>0&&o.jsx("span",{className:"flex flex-wrap items-center gap-2",children:N.map(([I,A])=>o.jsx(JVt,{delta:A},I))}),o.jsxs("div",{className:"grid pt-3",children:[o.jsx(htt,{label:"Input",value:E.input}),o.jsx(htt,{label:"Ground truth",value:E.groundTruth})]})]}),o.jsx("div",{role:"cell","aria-label":"Baseline",className:qE,children:o.jsx(gtt,{side:"baseline",row:E,isLoading:y})}),o.jsx("div",{role:"cell","aria-label":"Contender",className:qE,children:o.jsx(gtt,{side:"contender",row:E,isLoading:x,showDeltas:!0})})]},E.itemId)})]})})}const cvs=100;function oY(e){const t=Ge(),n={perPage:cvs};return mt({queryKey:e?["dataset-experiments",e,n]:["experiments",n],queryFn:()=>e?t.listDatasetExperiments(e,n):t.listExperiments(n)})}const tHt=(e,t)=>{const n=Ge(),{data:r,isLoading:s}=oY(void 0),a=r?.experiments,i=t?a?.filter(c=>c.id===t):a,l=mt({queryKey:["review-items",e,t??"all",i?.map(c=>c.id)],queryFn:async()=>!i||i.length===0?[]:(await Promise.all(i.map(async u=>{if(!u.datasetId)return[];try{const{results:d}=await n.listDatasetExperimentResults(u.datasetId,u.id);return d.filter(f=>f.status===e).map(f=>({id:f.id,input:f.input,output:f.output,error:f.error,itemId:f.itemId,experimentId:f.experimentId,datasetId:u.datasetId??void 0,traceId:f.traceId??void 0,scores:f.scores?Object.fromEntries(f.scores.map(p=>[p.scorerId,p.score??0])):{},tags:f.tags??[],comment:f.comment??""}))}catch{return[]}}))).flat(),enabled:!!a,refetchOnWindowFocus:!1});return{...l,isLoading:l.isLoading||s}},uvs=({experimentId:e}={})=>tHt("needs-review",e),dvs=({experimentId:e}={})=>tHt("complete",e);function fvs(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 pvs({datasetId:e,experimentId:t,featuredItemId:n,detailPanelVariant:r="inline"}){const s=Ge(),{data:a}=My(e??""),{data:i,isLoading:l}=uvs({experimentId:t}),{data:c,isLoading:u}=dvs({experimentId:t}),{updateExperimentResult:d}=bi(),[f,p]=g.useState(n??null);g.useEffect(()=>{n!==void 0&&p(n)},[n]);const[h,m]=g.useState(null),[v,y]=g.useState(new Set),[b,x]=g.useState(!1),[S,k]=g.useState(!1),[_,C]=g.useState(!1),[T,E]=g.useState(""),[N,I]=g.useState(""),[A,R]=g.useState(""),[L,M]=g.useState([]),[F,H]=g.useState(!1),[z,q]=g.useState({}),V=g.useMemo(()=>(i??[]).map(Ie=>Ie.id in z?{...Ie,rating:z[Ie.id]}:Ie),[i,z]),D=g.useMemo(()=>{const Ie=new Set;if(a?.tags)for(const Xe of a.tags)Ie.add(Xe);for(const Xe of V)for(const Qe of Xe.tags)Ie.add(Qe);return[...Ie].sort()},[a,V]),G=g.useCallback(Ie=>{!a||!e||(a.tags??[]).includes(Ie)},[a,e]),U=g.useMemo(()=>h?h==="__untagged__"?V.filter(Ie=>Ie.tags.length===0):V.filter(Ie=>Ie.tags.includes(h)):V,[V,h]),P=g.useMemo(()=>{const Ie=new Map;for(const Xe of V)for(const Qe of Xe.tags)Ie.set(Qe,(Ie.get(Qe)??0)+1);return[...Ie.entries()].sort((Xe,Qe)=>Qe[1]-Xe[1])},[V]),B=g.useMemo(()=>V.filter(Ie=>Ie.tags.length===0).length,[V]),Z=g.useMemo(()=>{let Ie=0;return h&&Ie++,b&&Ie++,Ie},[h,b]),Y=g.useCallback((Ie,Xe)=>{const Qe=V.find(Se=>Se.id===Ie);Qe?.experimentId&&Qe?.datasetId&&d.mutate({datasetId:Qe.datasetId,experimentId:Qe.experimentId,resultId:Qe.id,tags:Xe})},[V,d]),te=g.useCallback((Ie,Xe)=>{const Qe=V.find(Se=>Se.id===Ie);Qe?.traceId&&Xe!==void 0&&s.createFeedback({feedback:{traceId:Qe.traceId,source:"studio",feedbackSource:"studio",feedbackType:"rating",value:Xe==="positive"?1:-1,reviewStatus:"reviewed",experimentId:Qe.experimentId??void 0,sourceId:Qe.id}}).catch(()=>{}),q(Se=>({...Se,[Ie]:Xe}))},[V,s]),J=g.useCallback((Ie,Xe)=>{const Qe=V.find(Se=>Se.id===Ie);Qe?.experimentId&&Qe?.datasetId&&d.mutate({datasetId:Qe.datasetId,experimentId:Qe.experimentId,resultId:Qe.id,comment:Xe}),Qe?.traceId&&s.createFeedback({feedback:{traceId:Qe.traceId,source:"studio",feedbackSource:"studio",feedbackType:"comment",value:Xe,comment:Xe,reviewStatus:"reviewed",experimentId:Qe.experimentId??void 0,sourceId:Qe.id}}).catch(()=>{})},[V,s,d]),ee=g.useCallback(Ie=>{const Xe=V.find(Qe=>Qe.id===Ie);y(Qe=>{const Se=new Set(Qe);return Se.delete(Ie),Se}),f===Ie&&p(null),Xe?.experimentId&&Xe?.datasetId&&d.mutate({datasetId:Xe.datasetId,experimentId:Xe.experimentId,resultId:Xe.id,status:null})},[V,d,f]),re=g.useCallback(Ie=>{const Xe=V.find(Qe=>Qe.id===Ie);y(Qe=>{const Se=new Set(Qe);return Se.delete(Ie),Se}),f===Ie&&p(null),Xe?.experimentId&&Xe?.datasetId&&d.mutate({datasetId:Xe.datasetId,experimentId:Xe.experimentId,resultId:Xe.id,status:"complete"})},[V,d,f]),oe=g.useMemo(()=>{const Ie=b?c??[]:U;return!b||!h?Ie:h==="__untagged__"?Ie.filter(Xe=>Xe.tags.length===0):Ie.filter(Xe=>Xe.tags.includes(h))},[b,c,U,h]),X=b?u:!1,ne=g.useMemo(()=>new Set(oe.map(Ie=>Ie.id)),[oe]),se=g.useMemo(()=>[...v].filter(Ie=>ne.has(Ie)).length,[v,ne]),fe=oe.length>0&&se===oe.length,ce=se>0&&!fe,xe=g.useCallback(Ie=>{y(Xe=>{const Qe=new Set(Xe);return Qe.has(Ie)?Qe.delete(Ie):Qe.add(Ie),Qe})},[]),pe=g.useCallback(()=>{y(fe?new Set:new Set(oe.map(Ie=>Ie.id)))},[fe,oe]),we=g.useCallback(Ie=>{for(const Xe of v){const Qe=V.find(Se=>Se.id===Xe);Qe&&!Qe.tags.includes(Ie)&&Y(Xe,[...Qe.tags,Ie])}},[V,v,Y]),Ne=g.useCallback(Ie=>{for(const Xe of v){const Qe=V.find(Se=>Se.id===Xe);Qe&&Qe.tags.includes(Ie)&&Y(Xe,Qe.tags.filter(Se=>Se!==Ie))}},[V,v,Y]),Pe=g.useCallback(()=>{for(const Ie of v)re(Ie);y(new Set)},[v,re]),Re=g.useCallback(()=>{for(const Ie of v)ee(Ie);y(new Set)},[v,ee]),Ae=g.useCallback(()=>{E(""),C(!0)},[]),ae=g.useCallback(async()=>{if(!(!N||!A)){k(!0),C(!1);try{const Ie=V.filter(Qe=>v.has(Qe.id));if(Ie.length===0){k(!1);return}const Xe=await s.clusterFailures({modelId:`${N}/${A}`,items:Ie.map(Qe=>({id:Qe.id,input:Qe.input,output:Qe.output??void 0,error:typeof Qe.error=="string"?Qe.error:Qe.error?String(Qe.error):void 0,scores:Qe.scores,existingTags:Qe.tags.length>0?Qe.tags:void 0})),availableTags:D.length>0?D:void 0,prompt:T||void 0});Xe.proposedTags&&Xe.proposedTags.length>0&&(M(Xe.proposedTags.map(Qe=>({...Qe,accepted:!0}))),H(!0))}catch(Ie){console.error("Analysis failed:",Ie)}finally{k(!1)}}},[N,A,V,v,s,D,T]),me=g.useCallback(()=>{for(const Ie of L){if(!Ie.accepted)continue;const Xe=V.find(Qe=>Qe.id===Ie.itemId);if(Xe){const Qe=[...new Set([...Xe.tags,...Ie.tags])];Y(Xe.id,Qe)}}H(!1)},[L,V,Y]),ue=g.useCallback(Ie=>{p(Xe=>Xe===Ie?null:Ie)},[]),be=g.useMemo(()=>f?oe.find(Ie=>Ie.id===f)??null:null,[f,oe]),_e=f?oe.findIndex(Ie=>Ie.id===f):-1,ye=_e>0?()=>p(oe[_e-1].id):void 0,Ce=_e>=0&&_e<oe.length-1?()=>p(oe[_e+1].id):void 0,Be="auto minmax(0,20rem) minmax(0,1fr) minmax(0,8rem) 6rem 6rem",{containerRef:De,getRowProps:He}=so({count:oe.length});if(l)return o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(Ut,{className:"h-6 w-6"})});const et=be?o.jsx(MUt,{className:"h-full",item:be,isCompleted:b,tagVocabulary:D,onRate:Ie=>te(be.id,Ie),onSetTags:Ie=>{Y(be.id,Ie);for(const Xe of Ie)D.includes(Xe)||G(Xe)},onComment:Ie=>J(be.id,Ie),onRemove:()=>ee(be.id),onComplete:b?void 0:()=>re(be.id),onPrevious:ye,onNext:Ce,onClose:()=>p(null)}):null;return o.jsxs("div",{className:K("flex h-full min-h-0 flex-1",r==="overlay"?"overflow-visible":"overflow-hidden"),children:[o.jsx(hr,{open:_,onOpenChange:C,children:o.jsxs(mr,{children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Analyze Items"}),o.jsx(Cs,{children:"Use an LLM to automatically suggest tags for the selected items."})]}),o.jsxs("div",{className:"space-y-4 py-2",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx(Pt,{className:"mb-1 block text-xs",children:"Provider"}),o.jsx(Wy,{value:N,onValueChange:I})]}),o.jsxs("div",{children:[o.jsx(Pt,{className:"mb-1 block text-xs",children:"Model"}),o.jsx(Zy,{llmId:N,value:A,onValueChange:R})]})]}),o.jsxs(ve,{variant:"ui-xs",className:"text-neutral3",children:[v.size," item",v.size!==1?"s":""," will be analyzed"]}),o.jsxs("div",{children:[o.jsx(Pt,{className:"text-xs",children:"Instructions (optional)"}),o.jsx(il,{value:T,onChange:Ie=>E(Ie.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3,className:"mt-1 text-xs"})]})]}),o.jsxs(Ul,{children:[o.jsx(le,{variant:"outline",onClick:()=>C(!1),children:"Cancel"}),o.jsxs(le,{onClick:ae,disabled:!N||!A||S,children:[S?o.jsx(Ut,{className:"mr-1 h-4 w-4"}):null,"Analyze"]})]})]})}),o.jsx(hr,{open:F,onOpenChange:H,children:o.jsxs(mr,{className:"max-h-[80vh] max-w-2xl overflow-y-auto",children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Review Proposed Tags"}),o.jsxs(Cs,{children:[L.filter(Ie=>Ie.accepted).length," of ",L.length," proposals selected"]})]}),o.jsx("div",{className:"space-y-3 py-2",children:L.map((Ie,Xe)=>{const Qe=V.find(Se=>Se.id===Ie.itemId);return o.jsx("div",{className:K("p-3 border rounded-lg",!Ie.accepted&&"opacity-50"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(Oo,{checked:Ie.accepted,onCheckedChange:Se=>M(Te=>Te.map((Le,qe)=>qe===Xe?{...Le,accepted:!!Se}:Le))}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(ve,{variant:"ui-xs",className:"text-neutral4 block truncate",children:Qe?typeof Qe.input=="string"?Qe.input.slice(0,100):JSON.stringify(Qe.input).slice(0,100):Ie.itemId}),o.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:Ie.tags.map((Se,Te)=>o.jsx(LUt,{tag:Se,onRename:Le=>M(qe=>qe.map((tt,It)=>It===Xe?{...tt,tags:tt.tags.map((Ee,Je)=>Je===Te?Le:Ee)}:tt)),onRemove:()=>M(Le=>Le.map((qe,tt)=>tt===Xe?{...qe,tags:qe.tags.filter((It,Ee)=>Ee!==Te)}:qe))},`${Se}-${Te}`))}),Ie.reason&&o.jsx(ve,{variant:"ui-xs",className:"text-neutral3 mt-1 block italic",children:Ie.reason})]})]})},Ie.itemId)})}),o.jsxs(Ul,{children:[o.jsx(le,{variant:"outline",onClick:()=>H(!1),children:"Cancel"}),o.jsxs(le,{onClick:me,disabled:L.filter(Ie=>Ie.accepted).length===0,children:["Accept ",L.filter(Ie=>Ie.accepted).length," proposals"]})]})]})}),o.jsxs("div",{className:K("grid h-full min-h-0 w-full grid-cols-1 gap-4",r==="overlay"?"overflow-visible":"overflow-hidden",be&&r==="inline"&&"grid-cols-[1fr_1fr]"),children:[o.jsxs("div",{className:"grid min-h-0 w-full grid-rows-[auto_1fr] gap-3 overflow-hidden pt-3",children:[(V.length>0||Z>0)&&o.jsxs("div",{className:"flex w-full flex-wrap items-center justify-start gap-3",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs(at,{children:[o.jsx(at.Trigger,{asChild:!0,children:o.jsxs(le,{size:"sm",children:[o.jsx(O0e,{}),"Filter",Z>0&&o.jsx(xt,{size:"xs",children:Z})]})}),o.jsxs(at.Content,{align:"start",className:K("min-w-48"),children:[o.jsxs(at.Sub,{children:[o.jsxs(at.SubTrigger,{children:["Status",b&&o.jsx("span",{className:K("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(at.SubContent,{children:[o.jsx(at.CheckboxItem,{checked:!b,onCheckedChange:()=>{x(!1),p(null)},onSelect:Ie=>Ie.preventDefault(),children:"Review Queue"}),o.jsx(at.CheckboxItem,{checked:b,onCheckedChange:()=>{x(!0),p(null)},onSelect:Ie=>Ie.preventDefault(),children:"Completed"})]})]}),o.jsxs(at.Sub,{children:[o.jsxs(at.SubTrigger,{children:["Tags",h&&o.jsx("span",{className:K("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(at.SubContent,{children:[o.jsx(at.CheckboxItem,{checked:!h,onCheckedChange:()=>m(null),onSelect:Ie=>Ie.preventDefault(),children:"All"}),B>0&&o.jsx(at.CheckboxItem,{checked:h==="__untagged__",onCheckedChange:()=>m(h==="__untagged__"?null:"__untagged__"),onSelect:Ie=>Ie.preventDefault(),children:"Untagged"}),P.length>0&&o.jsx(at.Separator,{}),P.map(([Ie])=>o.jsx(at.CheckboxItem,{checked:h===Ie,onCheckedChange:()=>m(h===Ie?null:Ie),onSelect:Xe=>Xe.preventDefault(),children:Ie},Ie))]})]}),Z>0&&o.jsxs(o.Fragment,{children:[o.jsx(at.Separator,{}),o.jsxs(at.Item,{onSelect:()=>{m(null),x(!1),p(null)},children:[o.jsx(or,{}),"Clear all filters"]})]})]})]}),Z>0&&o.jsxs(le,{size:"sm",onClick:()=>{m(null),x(!1),p(null)},children:[o.jsx(or,{}),"Reset"]})]}),!b&&v.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(DUt,{selectedCount:v.size,vocabulary:D,onApplyTag:we,onRemoveTag:Ne,onNewTag:Ie=>we(Ie)}),o.jsxs(at,{children:[o.jsx(at.Trigger,{asChild:!0,children:o.jsxs(le,{size:"sm",disabled:S,children:[S?o.jsx(Ut,{className:"h-4 w-4"}):o.jsx(We,{size:"sm",children:o.jsx(Xs,{})}),"Actions"]})}),o.jsxs(at.Content,{align:"end",children:[o.jsxs(at.Item,{onSelect:Pe,children:[o.jsx(We,{size:"sm",children:o.jsx(wO,{})}),"Complete"]}),o.jsxs(at.Item,{onSelect:Re,children:[o.jsx(We,{size:"sm",children:o.jsx(Fl,{})}),"Remove"]}),o.jsx(at.Separator,{}),o.jsxs(at.Item,{onSelect:Ae,children:[o.jsx(We,{size:"sm",children:o.jsx($g,{})}),"Analyze"]})]})]})]})]}),X?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(Ut,{className:"h-6 w-6"})}):oe.length===0?o.jsx("div",{className:"flex h-full items-center justify-center py-12",children:o.jsx(br,{iconSlot:o.jsx(Q1,{className:"text-neutral3 h-8 w-8"}),titleSlot:b?"No completed reviews yet":"No items to review",descriptionSlot:b?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here."})}):o.jsxs(he,{columns:Be,fit:"container",className:"min-w-0",scrollRef:De,children:[o.jsxs(he.Top,{hasLeadingCell:!0,children:[b?o.jsx(he.TopCell,{children:" "}):o.jsx(he.TopSelectCell,{checked:fe?!0:ce?"indeterminate":!1,onToggle:()=>pe(),"aria-label":"Select all"}),o.jsxs(he.TopCells,{colStart:2,children:[o.jsx(he.TopCell,{children:"Input"}),o.jsx(he.TopCell,{children:"Comment"}),o.jsx(he.TopCell,{children:"Tags"}),o.jsx(he.TopCell,{children:"Rating"}),o.jsx(he.TopCell,{children:"Scores"})]})]}),oe.map((Ie,Xe)=>{const Qe=Ie.scores?Object.entries(Ie.scores):[],Se=f===Ie.id,Te=o.jsxs(o.Fragment,{children:[o.jsx(he.Cell,{className:"text-neutral4 min-w-0",children:o.jsx("span",{className:"block truncate",children:fvs(Ie.input,200)})}),o.jsx(he.Cell,{className:"min-w-0",children:Ie.comment?o.jsx(ve,{variant:"ui-xs",className:"text-neutral3 truncate",children:Ie.comment}):o.jsx(ve,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsx(he.Cell,{className:"min-w-0",children:Ie.tags.length>0?o.jsx(ve,{variant:"ui-xs",className:"text-neutral4 truncate",children:Ie.tags.join(", ")}):o.jsx(ve,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsxs(he.Cell,{children:[Ie.rating==="positive"&&o.jsx(We,{size:"sm",className:"text-positive1",children:o.jsx(M0e,{})}),Ie.rating==="negative"&&o.jsx(We,{size:"sm",className:"text-negative1",children:o.jsx($0e,{})}),!Ie.rating&&o.jsx(ve,{variant:"ui-xs",className:"text-neutral2",children:"—"})]}),o.jsx(he.Cell,{children:Qe.length>0?o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(We,{size:"sm",className:"text-neutral3",children:o.jsx(Gp,{})}),o.jsx(ve,{variant:"ui-xs",className:"text-neutral4 font-mono",children:Qe[0][1].toFixed(2)}),Qe.length>1&&o.jsxs(xt,{children:["+",Qe.length-1]})]}):o.jsx(ve,{variant:"ui-xs",className:"text-neutral2",children:"—"})})]});return o.jsxs(he.RowWrapper,{children:[b?o.jsx(he.Cell,{className:"justify-items-center px-4",children:o.jsx("div",{role:"img","aria-label":Ie.error?"Error":"Success",title:Ie.error?"Error":"Success",className:K("w-2 h-2 rounded-full",Ie.error?"bg-red-700":"bg-green-600")})}):o.jsx(he.SelectCell,{checked:v.has(Ie.id),onToggle:()=>xe(Ie.id),"aria-label":`Select item ${Ie.id}`}),o.jsx(he.RowButton,{colStart:2,featured:Se,onClick:()=>ue(Ie.id),...He(Xe),children:Te})]},Ie.id)})]})]}),et&&(r==="overlay"?o.jsx(aY,{label:`Review item ${be?.id??""}`,children:et}):et)]})]})}const ytt={needsReview:"#facc15",complete:"#22c55e"},hvs=[{label:"Needs Review",color:ytt.needsReview},{label:"Reviewed",color:ytt.complete}];function mvs({reviewSummary:e,experiments:t,datasets:n,isLoading:r,isError:s}){const{data:a,maxVal:i,totalInPipeline:l}=g.useMemo(()=>{if(!e?.counts||!t)return{data:[],maxVal:0,totalInPipeline:0};const u=new Map;for(const m of t)u.set(m.id,m);const d=new Map;if(n)for(const m of n)d.set(m.id,m.name);let f=0,p=0;const h=[];for(const m of e.counts){const v=m.needsReview+m.complete;if(v===0)continue;p+=v,v>f&&(f=v);const y=u.get(m.experimentId),b=y?.datasetId?d.get(y.datasetId):void 0,x=b?`${b} · ${m.experimentId.slice(0,8)}`:m.experimentId.slice(0,8);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(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Review Pipeline",description:"Items in review across experiments."}),c&&o.jsx(Vt.Summary,{value:String(l),label:"Items in pipeline"})]}),r?o.jsx(Vt.Loading,{}):s?o.jsx(Vt.Error,{message:"Failed to load review data"}):o.jsx(Vt.Content,{children:c?o.jsx(QN,{data:a,segments:hvs,maxVal:i,fmt:u=>String(u)}):o.jsx(Vt.NoData,{message:"No items have been sent to review yet"})})]})}function nHt(){const e=Ge();return mt({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function gvs(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 vvs(e){return e?.counts?e.counts.reduce((t,n)=>({needsReview:t.needsReview+n.needsReview,complete:t.complete+n.complete,inPipeline:t.inPipeline+n.needsReview+n.complete}),{needsReview:0,complete:0,inPipeline:0}):{needsReview:0,complete:0,inPipeline:0}}function yvs(){const[e,t]=g.useState("all"),[n,r]=g.useState({}),{data:s,isLoading:a,error:i}=uh(),{data:l,isLoading:c,error:u}=Qg(),{data:d,isLoading:f,error:p}=UH(),{data:h,isLoading:m,isError:v,error:y}=pUr(n),{data:b,isLoading:x,isError:S,error:k}=nHt(),_=l?.datasets,C=d?.experiments,T=g.useMemo(()=>vvs(b),[b]),E=i||u||p||y||k;return E&&ps(E)?o.jsx(Zn,{children:o.jsx(Ts,{})}):E&&hs(E)?o.jsx(Zn,{children:o.jsx(Os,{resource:"evaluation"})}):E?o.jsx(Zn,{children:o.jsx($a,{title:"Failed to load evaluation data",message:E.message})}):o.jsxs(Lt,{width:"wide",height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(Lt.Row,{children:o.jsx(Lt.Column,{children:o.jsx(W4,{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(s0e,{children:o.jsx(Lgs,{scorers:s,datasets:_,experiments:C,avgScore:h?.avgScore??null,prevAvgScore:h?.prevAvgScore??null,totalNeedsReview:T.needsReview,isLoadingScorers:a,isLoadingDatasets:c,isLoadingExperiments:f,isLoadingScores:m,isLoadingReview:x})}),o.jsx(_Br,{summaryData:h?.summaryData??[],overTimeData:h?.overTimeData??[],scorerNames:h?.scorerNames??[],avgScore:h?.avgScore??null,isLoading:m,isError:v}),o.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:[o.jsx(Bhs,{experiments:C,isLoading:f,isError:!!p}),o.jsx(Xgs,{experiments:C,datasets:_,isLoading:f,isError:!!p})]}),o.jsx(mvs,{reviewSummary:b,experiments:C,datasets:_,isLoading:x,isError:!!S})]})]})}function bvs(){const[e,t]=g.useState(""),[n,r]=g.useState("all"),[s,a]=g.useState(!1),[i,l]=g.useState(!1),[c,u]=g.useState([]),d=Vr(),[f,p]=Ma(),h=f.get("dataset")??"all",m=g.useCallback(G=>{p(U=>{const P=new URLSearchParams(U);return G==="all"?P.delete("dataset"):P.set("dataset",G),P},{replace:!0})},[p]),{data:v,isLoading:y,error:b}=Qg(),{data:x,isLoading:S,error:k}=oY(h==="all"?void 0:h),{data:_}=nHt(),C=g.useMemo(()=>v?.datasets??[],[v?.datasets]),T=g.useMemo(()=>x?.experiments??[],[x?.experiments]),E=g.useMemo(()=>Ygs(C),[C]),N=g.useMemo(()=>gvs(_),[_]),I=y||S,A=k||b,R=G=>{u(U=>U.includes(G)?U.filter(P=>P!==G):U.length>=2?[U[0],G]:[...U,G])},L=()=>{u([]),l(!1)},{selectedIds:M,selectedDatasetIds:F}=g.useMemo(()=>{const G=new Map(T.map(P=>[P.id,P.datasetId])),U=c.filter(P=>G.has(P));return{selectedIds:U,selectedDatasetIds:new Set(U.map(P=>G.get(P)))}},[T,c]),H=M.length===2&&F.size!==1?"experiments must belong to the same dataset":void 0,z=()=>{if(M.length!==2||H)return;const[G,U]=M,[P]=F;if(!P)return;const B=new URLSearchParams({dataset:P,baseline:G,contender:U});d(`/experiments/compare?${B.toString()}`)};if(A&&ps(A))return o.jsx(Zn,{children:o.jsx(Ts,{})});if(k&&hs(k))return o.jsx(Zn,{children:o.jsx(Os,{resource:"experiments"})});if(b&&hs(b))return o.jsx(Zn,{children:o.jsx(Os,{resource:"datasets"})});if(A)return o.jsx(Zn,{children:o.jsx($a,{title:"Failed to load experiments",message:A.message})});const q=o.jsx(sY,{open:s,onOpenChange:a,onSuccess:G=>{d(`/experiments/${G}`)}});if(T.length===0&&!I&&h==="all")return o.jsxs(Zn,{children:[o.jsx(Jgs,{onRunExperiment:()=>a(!0)}),q]});const V=n!=="all"||h!=="all"||e!=="",D=()=>{t(""),r("all"),m("all")};return o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(evs,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:h,onDatasetFilterChange:m,datasetOptions:E,onReset:D,hasActiveFilters:V,onRunClick:()=>a(!0),onCompareClick:()=>l(!0),selection:i?{selectedCount:M.length,onExecuteCompare:z,onCancelSelection:L,compareDisabledReason:H}:void 0})}),o.jsx(Ggs,{experiments:T,datasets:C,reviewByExperiment:N,isLoading:I,search:e,statusFilter:n,datasetFilter:h,selection:i?{selectedExperimentIds:M,onToggleSelection:R}:void 0}),q]})}function a8({experimentId:e}){const{Link:t,paths:n}=un();return o.jsx(le,{as:t,href:n.experimentLink(e),size:"sm","aria-label":`Open experiment ${e}`,children:e.slice(0,8)})}function xvs(){const[e,t]=Ma(),n=e.get("dataset")??"",r=e.get("baseline")??"",s=e.get("contender")??"",a=WD(n,r),i=WD(n,s),l=a.isLoading||i.isLoading,c=a.error??i.error;return c&&ps(c)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{})})}):c&&hs(c)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Os,{resource:"experiments"})})}):!n||!r||!s?o.jsx(vs,{children:o.jsx(hy,{children:o.jsxs("div",{className:"text-neutral4 py-8 text-center",children:[o.jsx("p",{children:"Select two experiments to compare."}),o.jsxs("p",{className:"mt-2 text-sm",children:["Use the URL format: /experiments/compare?dataset=","{datasetId}","&baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})}):l?null:c&&!VEe(c)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx($a,{title:"Failed to load experiments",message:c.message})})}):c||!a.data||!i.data?o.jsx(vs,{children:o.jsx(hy,{children:o.jsxs("div",{className:"text-neutral4 py-8 text-center",children:[o.jsxs("p",{children:["Experiments must belong to the same dataset (",n,") to be compared."]}),o.jsxs("p",{className:"mt-2 flex items-center justify-center gap-2 text-sm",children:["One of",o.jsx(a8,{experimentId:r}),"and",o.jsx(a8,{experimentId:s}),"was not found in it."]})]})})}):o.jsx(vs,{children:o.jsx(hy,{children:o.jsxs("div",{className:"grid w-full content-start",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4 px-6 py-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[o.jsx(ve,{as:"h1",variant:"ui-lg",className:"text-neutral6 font-medium",children:"Experiments comparison"}),o.jsxs("p",{className:"text-ui-sm text-neutral4 flex items-center gap-2",children:[o.jsx(a8,{experimentId:r}),"and",o.jsx(a8,{experimentId:s})]})]}),o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsxs(le,{onClick:()=>t({dataset:n,baseline:s,contender:r}),children:[o.jsx(tct,{}),"Swap sides"]})}),o.jsx(yn,{children:"Switch baseline and contender"})]})]}),o.jsx(lvs,{datasetId:n,experimentIdA:r,experimentIdB:s})]})})})}const rHt=e=>o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 8.64637 9.45103",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:o.jsx("path",{d:"M7.80735 5.87241C7.63209 5.97219 7.43696 6.06166 7.22844 6.13866C6.46456 6.42068 5.43714 6.58649 4.32296 6.58649C3.20873 6.58649 2.18135 6.4207 1.41747 6.13866C1.20889 6.06164 1.01385 5.97223 0.838558 5.87241V7.59003C0.838558 7.62341 0.855765 7.70759 1.00172 7.83512C1.14707 7.96201 1.38219 8.09563 1.70829 8.21605C2.3572 8.45563 3.28149 8.61268 4.32296 8.61269C5.36456 8.61269 6.28937 8.45568 6.9383 8.21605C7.26428 8.09566 7.49888 7.96198 7.64419 7.83512C7.79024 7.70754 7.80735 7.62342 7.80735 7.59003V5.87241ZM7.80735 3.00789C7.63214 3.10763 7.4369 3.19647 7.22844 3.27345C6.46455 3.55549 5.43719 3.72129 4.32296 3.72129C3.20868 3.72128 2.18136 3.55552 1.41747 3.27345C1.20896 3.19645 1.01381 3.10766 0.838558 3.00789V4.72551C0.838558 4.7589 0.855657 4.84301 1.00172 4.97059C1.14707 5.09749 1.38219 5.23111 1.70829 5.35153C2.3572 5.59109 3.28154 5.74747 4.32296 5.74748C5.36456 5.74748 6.28937 5.59116 6.9383 5.35153C7.26432 5.23112 7.49887 5.09747 7.64419 4.97059C7.7536 4.87505 7.79089 4.80404 7.80257 4.76033L7.80735 4.72551V3.00789ZM7.80735 1.86099C7.80735 1.82758 7.79045 1.74291 7.64419 1.61522C7.49887 1.48838 7.26421 1.35534 6.9383 1.23497C6.28937 0.995339 5.36456 0.838331 4.32296 0.838331C3.28149 0.83834 2.3572 0.995383 1.70829 1.23497C1.38219 1.35539 1.14707 1.48832 1.00172 1.61522C0.855475 1.7429 0.838558 1.82758 0.838558 1.86099C0.838673 1.89462 0.855968 1.97882 1.00172 2.10607C1.14707 2.23297 1.38219 2.3659 1.70829 2.48632C2.3572 2.7259 3.28149 2.88295 4.32296 2.88296C5.36456 2.88296 6.28937 2.72595 6.9383 2.48632C7.26421 2.36595 7.49887 2.23291 7.64419 2.10607C7.78996 1.97881 7.80724 1.89462 7.80735 1.86099ZM8.64637 7.59003C8.64637 7.95465 8.44458 8.25006 8.1958 8.46728C7.94608 8.68529 7.60876 8.86274 7.22844 9.00318C6.46455 9.28522 5.43718 9.45102 4.32296 9.45102C3.20869 9.45101 2.18135 9.28525 1.41747 9.00318C1.03715 8.86274 0.699831 8.68529 0.450113 8.46728C0.201377 8.25007 0.000227451 7.9546 0.000227451 7.59003V1.86099C0.000227451 1.49643 0.201388 1.20095 0.450113 0.983742C0.699831 0.765728 1.03715 0.588275 1.41747 0.447838C2.18136 0.165769 3.20868 8.74396e-06 4.32296 0C5.43719 0 6.46455 0.165797 7.22844 0.447838C7.60876 0.588275 7.94608 0.765728 8.1958 0.983742C8.44457 1.20096 8.64637 1.49638 8.64637 1.86099V7.59003Z",fill:"currentColor"})});function sHt(e){const{data:t}=C_(e.id,e.status);return g.useMemo(()=>{if(e.scorerIds?.length)return e.scorerIds;if(!t)return[];const n=new Set;for(const r of Object.values(t))for(const s of r)n.add(s.scorerId);return[...n].sort()},[e.scorerIds,t])}function Qie({icon:e,typeLabel:t,children:n}){return o.jsxs("div",{className:"text-ui-sm text-neutral5 flex flex-none items-center gap-1.5 [&_svg]:size-3.5 [&_svg]:shrink-0",children:[o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx("span",{className:"text-neutral3 flex",role:"img","aria-label":t}),children:e}),o.jsx(yn,{children:t})]}),n]})}function Yie({label:e}){return o.jsxs("div",{className:"text-neutral2 text-ui-xs flex flex-none items-center gap-1.5",children:[o.jsx("span",{className:"whitespace-nowrap",children:e}),o.jsx(zd,{className:"size-3.5 shrink-0","aria-hidden":!0})]})}const btt="text-neutral5 inline-flex items-center gap-1.5 hover:underline";function wvs({experiment:e,className:t}){const{Link:n,paths:r}=un(),s=QVt(),{scorers:a}=s,{data:i,isLoading:l}=My(e.datasetId??""),c=sHt(e),u=c.map(b=>a?.[b]?.scorer?.config?.name??b),d=e.targetType,f=e.targetId,p=()=>XVt(e,s),h=()=>{if(!f)return null;switch(d){case"agent":return r.agentLink(f);case"workflow":return r.workflowLink(f);case"scorer":return r.scorerLink(f);default:return null}},m=d&&YVt[d]||Ai,v=d&&KVt[d]||"Evaluation target",y=h();return o.jsxs("div",{className:K("flex items-center gap-3 overflow-x-auto",t),children:[o.jsx(Qie,{icon:o.jsx(rHt,{}),typeLabel:"Dataset",children:e.datasetId?o.jsxs(n,{href:r.datasetLink(e.datasetId),className:btt,children:[l?o.jsx(Ct,{className:"h-4 w-28"}):i?.name??e.datasetId,e.datasetVersion!=null&&o.jsxs("span",{className:"text-neutral3",children:["(v",e.datasetVersion,")"]})]}):o.jsx("span",{className:"text-neutral3",children:"No dataset"})}),o.jsx(Yie,{label:"each item"}),o.jsx(Qie,{icon:o.jsx(m,{}),typeLabel:v,children:y?o.jsx(n,{href:y,className:btt,children:p()}):o.jsx("span",{className:"text-neutral3",children:p()})}),o.jsx(Yie,{label:"output"}),o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx("div",{tabIndex:0,className:"flex outline-offset-4",children:o.jsx(Qie,{icon:o.jsx(AC,{}),typeLabel:"Scorers",children:c.length===0?"Scorers":`${c.length} scorer${c.length===1?"":"s"}`})})}),o.jsx(yn,{children:u.length>0?u.join(", "):"No scorer has produced a score yet"})]}),o.jsx(Yie,{label:"comparing ground truth"}),o.jsx("div",{className:"text-ui-sm text-neutral5 flex-none whitespace-nowrap",children:"Score"})]})}function i8({label:e,children:t}){return o.jsxs("div",{className:"min-w-0 flex-1 px-6 py-3",children:[o.jsx("div",{className:"text-ui-sm text-neutral2 tracking-widest uppercase",children:e}),o.jsx("div",{className:"text-ui-md text-neutral5 mt-1 flex flex-wrap items-baseline gap-x-1.5",children:t})]})}function Svs(e){if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(1).replace(/\.0$/,"")}s`;const t=Math.floor(e/6e4),n=Math.round(e%6e4/1e3);if(t<60)return n>0?`${t}m ${n}s`:`${t}m`;const r=Math.floor(t/60),s=t%60;return s>0?`${r}h ${s}m`:`${r}h`}function kvs({experiment:e,className:t}){const{data:n}=C_(e.id,e.status),r=g.useMemo(()=>{if(!n)return;const l=Object.values(n).flat();if(l.length!==0)return l.reduce((c,u)=>c+u.score,0)/l.length},[n]),s=e.startedAt??e.createdAt,a=s?new Date(s):null,i=(()=>{if(e.status==="running")return"Running…";if(!e.startedAt||!e.completedAt)return"—";const l=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return l<0?"—":Svs(l)})();return o.jsxs("div",{className:K("flex w-full items-stretch divide-x divide-border1 border-y border-border1",t),children:[o.jsx(i8,{label:"Avg score",children:r===void 0?o.jsx("span",{className:"text-neutral3",children:"—"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{children:r.toFixed(3)}),(e.status==="running"||e.status==="pending")&&o.jsx("span",{className:"text-neutral3",children:"· so far"})]})}),o.jsx(i8,{label:"Items",children:e.status==="running"||e.status==="pending"?o.jsxs("span",{className:"text-neutral3",children:[(e.succeededCount??0)+(e.failedCount??0),"/",e.totalItems," items processed"]}):o.jsxs(o.Fragment,{children:[o.jsxs("span",{children:[e.totalItems," item",e.totalItems===1?"":"s"]}),(e.failedCount??0)>0&&o.jsxs("span",{className:"text-error",children:["· ",e.failedCount," errored"]})]})}),o.jsx(i8,{label:"Started",children:a?o.jsxs(o.Fragment,{children:[o.jsx("span",{children:dr(a,"MMM d, h:mm a")}),o.jsxs("span",{className:"text-neutral3",children:["· ",G2n(a,{addSuffix:!0})]})]}):o.jsx("span",{children:"—"})}),o.jsx(i8,{label:"Duration",children:o.jsx("span",{children:i})})]})}function Ovs({experiment:e,open:t,onOpenChange:n}){const[r,s]=g.useState(e.name??""),[a,i]=g.useState(e.description??""),{updateExperiment:l}=bi(),c=!!r.trim()&&!l.isPending,u=async d=>{if(d.preventDefault(),!(!c||!e.datasetId))try{await l.mutateAsync({datasetId:e.datasetId,experimentId:e.id,name:r.trim(),description:a.trim()}),ze.success("Experiment renamed"),n(!1)}catch(f){ze.error(`Failed to rename experiment: ${f instanceof Error?f.message:"Unknown error"}`)}};return o.jsx(hr,{open:t,onOpenChange:n,children:o.jsxs(mr,{className:"max-w-md",children:[o.jsx(gr,{children:o.jsx(ur,{children:"Rename Experiment"})}),o.jsx(jr,{children:o.jsxs("form",{onSubmit:u,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Pt,{htmlFor:"rename-experiment-name",children:"Name *"}),o.jsx(Cn,{id:"rename-experiment-name",value:r,onChange:d=>s(d.target.value),placeholder:"Enter experiment name",autoFocus:!0})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Pt,{htmlFor:"rename-experiment-description",children:"Description"}),o.jsx(Cn,{id:"rename-experiment-description",value:a,onChange:d=>i(d.target.value),placeholder:"Enter experiment description (optional)"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(le,{type:"button",onClick:()=>n(!1),disabled:l.isPending,children:"Cancel"}),o.jsx(le,{type:"submit",variant:"primary",disabled:!c,children:l.isPending?"Saving...":"Save"})]})]})})]})})}function _vs({experiment:e}){const[t,n]=g.useState(!1);return e.datasetId?o.jsxs(o.Fragment,{children:[o.jsx(le,{onClick:()=>n(!0),tooltip:"Rename this experiment",variant:"ghost",size:"icon-sm",children:o.jsx(Qp,{})}),t&&o.jsx(Ovs,{experiment:e,open:!0,onOpenChange:n})]}):null}const Cvs=["agent","workflow","scorer"];function Evs({experiment:e}){const[t,n]=g.useState(!1),r=Vr(),{paths:s}=un(),a=sHt(e),i=Cvs.find(l=>l===e.targetType);return!e.datasetId||!i||!e.targetId?null:o.jsxs(o.Fragment,{children:[o.jsxs(le,{variant:"primary",onClick:()=>n(!0),tooltip:"Run this experiment again with the same configuration",children:[o.jsx(Mc,{}),"Rerun"]}),t&&o.jsx(sY,{open:!0,onOpenChange:n,initialDatasetId:e.datasetId,initialDatasetVersion:e.datasetVersion??void 0,initialTargetType:i,initialTargetId:e.targetId,initialScorerIds:a,initialName:e.name??void 0,initialDescription:e.description??void 0,onSuccess:l=>{r(s.experimentLink(l))}},a.join(","))]})}function Tvs({experiment:e}){const{Link:t,paths:n}=un(),r=e.agentVersion&&e.targetType==="agent"&&e.targetId?`${n.agentLink(e.targetId)}/editor?version=${encodeURIComponent(e.agentVersion)}`:null;return o.jsxs(Lt.TopArea,{children:[o.jsxs(Lt.Row,{children:[o.jsx(Lt.Column,{className:"justify-items-start gap-3",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx(Zms,{status:e.status,className:"h-7"}),o.jsxs(Dl,{children:[o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Dl.Title,{children:e.name||`Experiment #${e.id.slice(0,8)}`}),o.jsx(_vs,{experiment:e})]}),e.description&&o.jsx(Dl.Description,{children:e.description}),o.jsx(wvs,{experiment:e,className:"mt-2"})]})]})}),o.jsxs(Lt.Column,{className:"justify-items-end gap-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(le,{as:t,to:pTe(e.id),children:[o.jsx(Q1,{}),"View items to review"]}),o.jsx(Evs,{experiment:e})]}),e.agentVersion&&o.jsxs(Tn,{numOfCol:1,children:[o.jsx(Tn.Key,{children:"Version"}),r?o.jsx(Tn.ValueLink,{href:r,as:t,children:e.agentVersion}):o.jsx(Tn.Value,{children:e.agentVersion})]})]})]}),o.jsx(kvs,{experiment:e,className:"-mx-6 w-auto"})]})}function o8({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function jvs(){const{experimentId:e}=fr(),{data:t,isLoading:n}=UH(),s=t?.experiments?.find(h=>h.id===e)?.datasetId??"",{data:a,isLoading:i,error:l}=WD(s,e??""),{data:c,isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p}=ZD({datasetId:s,experimentId:e??"",experimentStatus:a?.status});return!e||n||i?null:l&&ps(l)?o.jsx(o8,{children:o.jsx(Ts,{})}):l&&hs(l)?o.jsx(o8,{children:o.jsx(Os,{resource:"datasets"})}):l&&VEe(l)||!n&&!s||!i&&!l&&!a?o.jsx(o8,{children:o.jsx(br,{iconSlot:o.jsx(w0e,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:o.jsxs(le,{as:Ba,to:"/experiments",children:[o.jsx(bl,{}),"Back to Experiments"]})})}):l?o.jsx(o8,{children:o.jsx($a,{title:"Failed to load experiment",message:l instanceof Error?l.message:"An unexpected error occurred. Please try again."})}):o.jsx(Bms,{experimentId:e,datasetId:s,experimentStatus:a.status,results:c??[],isLoadingResults:u,hasNextPage:p,children:o.jsxs("div",{className:"relative h-full overflow-hidden",children:[o.jsxs(Lt,{height:"full",children:[o.jsx(Tvs,{experiment:a}),o.jsx(Lt.MainArea,{className:"overflow-visible",children:o.jsx(Wms,{experimentId:e,datasetId:s,experimentStatus:a.status,results:c??[],isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p})})]}),o.jsx(Fg,{})]})})}const fRe=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 Kie(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function Nvs({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(on.SectionHeading,{icon:o.jsx(qd,{}),className:"mb-2",children:"Tool Mocks"}),s&&o.jsx(Rn,{variant:"destructive",title:"Mock mismatch",children:o.jsxs(Rn.Message,{children:[o.jsx("span",{className:"block",children:`Tool "${s.toolName}" was called with arguments that did not match an available mock (${s.code}).`}),o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Called with: ",Kie(s.args)]}),n.length>0&&o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Unconsumed mocks: ",n.map(i=>Kie(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:Kie(i.args)})]}),o.jsx("span",{className:`shrink-0 rounded px-2 py-0.5 text-xs ${Ivs(i.outcome)}`,children:i.outcome})]},`${i.outcome}-${i.toolName}-${l}`))})]})}function Ivs(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 Avs({result:e,scores:t,onPrevious:n,onNext:r,onClose:s,onShowTrace:a,onOpenInReview:i,onScoreClick:l,featuredScoreId:c,onFlagForReview:u,collapsed:d=!1,scorePanelSlot:f}){const p=!!e?.error,h=l8(e?.input),m=l8(e?.output),v=l8(e?.groundTruth),y=u&&e.status!=="needs-review"&&e.status!=="complete",b=Array.isArray(e.tags)?e.tags:[];return o.jsxs(on,{collapsed:d,children:[o.jsxs(on.Header,{children:[o.jsxs(on.Heading,{children:["Result ",o.jsxs("b",{children:["# ",e.id.length>12?`${e.id.slice(0,12)}…`:e.id]})]}),o.jsxs(es,{className:"ml-auto shrink-0",children:[o.jsx(on.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Previous result",nextLabel:"Next result"}),e.traceId&&o.jsxs(le,{size:"md",onClick:a,children:[o.jsx(fRe,{}),"Trace"]}),y&&o.jsxs(le,{size:"md",variant:"primary",onClick:()=>u(e.id),children:[o.jsx(Q1,{}),"Flag for Review"]}),e.status==="needs-review"&&i&&o.jsxs(le,{size:"md",variant:"primary",onClick:i,children:[o.jsx(ea,{}),"Review"]}),o.jsx(on.CloseButton,{onClick:s,tooltip:"Close result panel"})]})]}),!d&&o.jsx(Rvs,{scorePanelSlot:f,children:o.jsxs(on.Content,{children:[o.jsxs("div",{className:"mb-6 grid gap-4",children:[o.jsxs(Tn,{children:[o.jsx(Tn.Key,{children:"Item Id"}),o.jsx(Tn.ValueWithCopyBtn,{copyTooltip:"Copy Item Id to clipboard",copyValue:e.itemId,children:e.itemId}),o.jsx(Tn.Key,{children:"Created"}),o.jsx(Tn.Value,{children:dr(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")})]}),p&&o.jsx(Rn,{variant:"destructive",title:"Error",children:o.jsx(Rn.Message,{children:l8(e?.error&&typeof e.error=="object"?e.error.message:e?.error)})}),t&&t.length>0&&o.jsxs(he,{columns:"1fr 1fr",children:[o.jsxs(he.Top,{children:[o.jsx(he.TopCell,{children:"Scorer"}),o.jsx(he.TopCell,{children:"Score"})]}),t.map(x=>o.jsxs(he.RowButton,{featured:c===x.id,onClick:()=>l?.(x.id),children:[o.jsx(he.Cell,{children:x.scorerId}),o.jsx(he.TextCell,{font:"mono",children:x.score.toFixed(3)})]},x.id))]}),e.toolMockReport&&o.jsx(Nvs,{report:e.toolMockReport}),(e.status||b.length>0)&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(on.SectionHeading,{icon:o.jsx(cI,{}),className:"mb-2",children:"Review"}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.status&&o.jsx("span",{className:`rounded-full px-2 py-0.5 text-xs font-medium ${e.status==="needs-review"?"bg-orange-500/10 text-orange-400":e.status==="complete"?"bg-accent1/10 text-accent1":"bg-neutral3/10 text-neutral4"}`,children:e.status}),b.map(x=>o.jsx("span",{className:"bg-surface4 text-neutral4 rounded px-2 py-0.5 text-xs",children:x},x))]})]})]}),o.jsxs("div",{className:"grid gap-3",children:[o.jsx(on.CodeSection,{title:"Input",icon:o.jsx(NV,{}),codeStr:h}),o.jsx(on.CodeSection,{title:"Output",icon:o.jsx(rm,{}),codeStr:m}),o.jsx(on.CodeSection,{title:"Ground Truth",icon:o.jsx(jct,{}),codeStr:v})]})]})})]})}function Rvs({scorePanelSlot:e,children:t}){return e?o.jsxs("div",{className:"grid min-h-0 flex-1 grid-cols-[1fr_1fr]",children:[o.jsx("div",{className:"flex min-h-0 flex-col overflow-hidden",children:t}),o.jsx("div",{className:"animate-in border-border1 fade-in-0 flex min-h-0 flex-col overflow-hidden border-l duration-300",children:e})]}):o.jsx(o.Fragment,{children:t})}function l8(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Pvs(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function $vs({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s,collapsed:a,onCollapsedChange:i,className:l}){const[c,u]=g.useState(!1),d=a??c,f=i??u,p=Pvs(e),h=p?"N/A — code-based scorer":"N/A — step not configured";return o.jsxs(on,{collapsed:d,className:l,children:[o.jsxs(on.Header,{children:[o.jsxs(on.Heading,{children:["Score ",o.jsx("b",{children:e.scorerId})]}),o.jsxs(es,{className:"ml-auto shrink-0",children:[i&&o.jsx(le,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(rI,{}):o.jsx(CV,{})}),(n||t)&&o.jsx(on.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:"Previous score",nextLabel:"Next score"}),s&&e.traceId&&o.jsxs(le,{size:"md",onClick:s,children:[o.jsx(fRe,{}),"Trace"]}),o.jsx(on.CloseButton,{onClick:r,tooltip:"Close score panel"})]})]}),!d&&o.jsx(on.Content,{children:o.jsxs("div",{className:"grid gap-3",children:[o.jsx(on.CodeSection,{title:`Score: ${e.score}`,icon:o.jsx(Gp,{}),codeStr:e.reason||h,simplified:!0}),!p&&o.jsxs(o.Fragment,{children:[o.jsx(on.CodeSection,{title:"Preprocess Prompt",icon:o.jsx($h,{}),codeStr:e.preprocessPrompt||h,simplified:!0}),o.jsx(on.CodeSection,{title:"Analyze Prompt",icon:o.jsx($h,{}),codeStr:e.analyzePrompt||h,simplified:!0}),o.jsx(on.CodeSection,{title:"Generate Score Prompt",icon:o.jsx($h,{}),codeStr:e.generateScorePrompt||h,simplified:!0}),o.jsx(on.CodeSection,{title:"Generate Reason Prompt",icon:o.jsx($h,{}),codeStr:e.generateReasonPrompt||h,simplified:!0})]})]})})]})}function Mvs(){const{itemId:e}=fr();return e?o.jsx(Dvs,{itemId:e},e):null}function Dvs({itemId:e}){const{experimentId:t,datasetId:n,experimentStatus:r,results:s,isLoadingResults:a,hasNextPage:i,close:l,openInReview:c,goToPreviousItem:u,goToNextItem:d}=HVt(),f=g.useMemo(()=>s.find(P=>P.itemId===e)??null,[s,e]),{data:p}=C_(t,r),{updateExperimentResult:h}=bi(),m=g.useCallback(async P=>{try{await h.mutateAsync({datasetId:n,experimentId:t,resultId:P,status:"needs-review"}),ze("Result flagged for review")}catch{ze.error("Failed to flag result for review")}},[n,t,h]),v=f?p?.[f.itemId]:void 0,[y,b]=g.useState(null),[x,S]=g.useState(void 0),[k,_]=g.useState(null),[C,T]=g.useState(!1),[E,N]=g.useState(!1),I=v?.find(P=>P.id===k)??null,A=g.useCallback(P=>{_(B=>P===B?null:P),b(null),S(void 0)},[]),R=()=>{if(!k||!v)return;const P=v.findIndex(B=>B.id===k);if(P>=0&&P<v.length-1)return()=>_(v[P+1].id)},L=()=>{if(!k||!v)return;const P=v.findIndex(B=>B.id===k);if(P>0)return()=>_(v[P-1].id)},{data:M,isLoading:F}=Gms(y),H=M?.spans,z=H?.find(P=>!P.parentSpanId),q=z?.entityType==="agent"?"Agent":z?.entityType==="workflow_run"?"Workflow":void 0,{data:V}=sRe({traceId:y??void 0}),{data:D}=aRe({traceId:y??void 0,spanId:x}),{data:G}=hje({traceId:y??void 0,spanId:z?.spanId,page:0}),U=(()=>{const P=[],B=!!y;return P.push(C?"auto":B?"2fr":"1fr"),B&&P.push(E?"auto":"3fr"),P.join(" ")})();return o.jsx(aY,{label:`Experiment item ${e}`,wide:!!x||!!I&&!C,children:f?o.jsxs("div",{className:"[&>section]:bg-surface3 grid h-full min-h-0 content-start gap-4 p-3 [&>section]:rounded-lg [&>section]:shadow-lg",style:{gridTemplateRows:U},children:[o.jsx(Avs,{result:f,scores:v,onPrevious:u,onNext:d,onClose:l,onScoreClick:A,featuredScoreId:k,onShowTrace:()=>{f.traceId&&(b(f.traceId),S(void 0),_(null),T(!0),N(!1))},onOpenInReview:()=>c(f.id),onFlagForReview:()=>{m(f.id)},collapsed:C,scorePanelSlot:I?o.jsx($vs,{score:I,onNext:R(),onPrevious:L(),onClose:()=>_(null),onShowTrace:()=>{I.traceId&&(b(I.traceId),S(void 0),T(!0),N(!1))},className:"rounded-none border-0 bg-transparent"}):null}),y&&o.jsx(JQ,{traceId:y,spans:H,isLoadingSpans:F,selectedSpanId:x??null,onClose:()=>{b(null),S(void 0),T(!1)},onSpanSelect:S,showUnavailableFeaturesMsg:!1,collapsed:E,onCollapsedChange:N,traceHref:`/traces?traceId=${encodeURIComponent(y)}`,anchorSpanId:z?.spanId,feedbackTabBadge:V?.pagination?.total??void 0,feedbackTabSlot:({traceId:P})=>o.jsx(oRe,{traceId:P}),scoresTabBadge:G?.pagination?.total??void 0,scoresTabSlot:({traceId:P,rootSpanId:B})=>B?o.jsx(RVt,{traceId:P,spanId:B,isTopLevelSpan:!z?.parentSpanId,entityType:q,onScoreSelect:Z=>{v?.some(Y=>Y.id===Z)&&(_(Z),T(!1))}}):null,spanFeedbackTabBadge:D?.pagination?.total??void 0,spanFeedbackTabSlot:({traceId:P,spanId:B})=>P&&B?o.jsx(iRe,{traceId:P,spanId:B},`${P}:${B}`):null,spanPanelClassName:"rounded-none border-0 bg-transparent"})]}):a||i?o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(Ut,{})})}):o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(br,{iconSlot:o.jsx(w0e,{}),titleSlot:"Item not found",descriptionSlot:`No loaded result for item "${e}".`,actionSlot:o.jsx(le,{onClick:l,children:"Close"})})})})})}const pRe=e=>o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 9.83952 9.3295",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.67171 0.838331H6.70163V4.05307L9.68767 8.09999C10.0634 8.6093 9.69869 9.32932 9.06643 9.3295H0.772551C0.140289 9.3293 -0.223777 8.60929 0.151995 8.09999L3.13804 4.05307V0.838331H2.17136V0H7.67171V0.838331ZM3.97705 4.32955L3.89513 4.44015L2.34681 6.53802H7.49285L5.94453 4.44015L5.86261 4.32955V0.860859H3.97705V4.32955Z",fill:"currentColor"})}),kV="all",xtt=60,Lvs=e=>e.length>xtt?`${e.slice(0,xtt)}…`:e;function Fvs({value:e,onValueChange:t,className:n,variant:r,allOption:s}){const{data:a,isLoading:i,isError:l}=oY(void 0),c=(a?.experiments??[]).map(d=>({label:ZVt(d),value:d.id,start:o.jsx(pRe,{className:"text-neutral3 size-4 shrink-0","data-testid":"experiments-icon"}),description:d.description?Lvs(d.description):h0(d.id)??d.id})),u=s?[{label:"All experiments",value:kV},...c]:c;return o.jsx(yl,{options:u,value:e??(s?kV:""),onValueChange:t,placeholder:i?"Loading experiments...":l?"Failed to load experiments":"Select experiment",searchPlaceholder:"Search experiments...",emptyText:"No experiments found.",className:n,disabled:i||l,variant:r})}function zvs(){const[e,t]=Ma(),n=e.get("experiment"),r=e.get("review"),{data:s,error:a}=oY(void 0),i=s?.experiments.find(c=>c.id===n),l=c=>{t(c===kV?{}:{experiment:c},{replace:!0})};return a&&ps(a)?o.jsx(Zn,{children:o.jsx(Ts,{})}):a&&hs(a)?o.jsx(Zn,{children:o.jsx(Os,{resource:"experiments"})}):a?o.jsx(Zn,{children:o.jsx($a,{title:"Failed to load experiments",message:a.message})}):o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(Lt.Row,{children:o.jsx(Lt.Column,{className:"justify-items-start",children:o.jsx(Fvs,{allOption:!0,value:n??void 0,onValueChange:l,className:"w-80"})})})}),o.jsx(Lt.MainArea,{className:"overflow-visible",children:o.jsx(pvs,{datasetId:i?.datasetId??void 0,experimentId:n??void 0,featuredItemId:r,detailPanelVariant:"overlay"},n??kV)})]})}const Bvs=20;function Uvs({reviewStatus:e}){const t=Ge(),n=Py({queryKey:["feedback","list",e],queryFn:({pageParam:r})=>t.listFeedback({filters:{reviewStatus:e},pagination:{page:r,perPage:Bvs},orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:r=>r.pagination?.hasMore?r.pagination.page+1:void 0});return{...n,items:n.data?.pages.flatMap(r=>r.feedback)??[],total:n.data?.pages[0]?.pagination?.total}}function qvs({enabled:e}){const t=Ge();return mt({queryKey:["feedback","inbox-count"],queryFn:()=>t.listFeedback({filters:{reviewStatus:"needs-review"},pagination:{page:0,perPage:1},orderBy:{field:"timestamp",direction:"DESC"}}),enabled:e,refetchInterval:3e3})}function Vvs(){const e=Ge(),t=Ir();return Sn({mutationFn:({feedbackId:n,reviewStatus:r})=>e.updateFeedbackReviewStatus({feedbackId:n,reviewStatus:r}),onSuccess:()=>t.invalidateQueries({queryKey:["feedback"]})})}const wtt="minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) auto";function Hvs({items:e,isLoading:t,error:n}){const r=Vr(),[s,a]=g.useState(""),i=s.trim().toLowerCase(),l=i?e.filter(d=>[d.itemId,d.experimentId,d.datasetId,d.traceId??""].some(f=>f.toLowerCase().includes(i))):e,{containerRef:c,getRowProps:u}=so({count:l.length});return t?o.jsx(Fo,{columns:wtt}):n?o.jsx($a,{title:"Failed to load dataset items",message:n.message}):e.length===0?o.jsx(br,{iconSlot:o.jsx(E0e,{className:"text-neutral3 h-8 w-8"}),titleSlot:"Nothing to review",descriptionSlot:"Experiment results that need review will show up here."}):o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_1fr] gap-4",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(od,{onSearch:a,label:"Filter dataset items",placeholder:"Filter by item, experiment, dataset or trace",shortcutDisabled:!0})}),o.jsx("div",{className:"min-h-0 overflow-hidden",children:o.jsxs(he,{columns:wtt,fit:"container",scrollRef:c,children:[o.jsxs(he.Top,{children:[o.jsx(he.TopCell,{children:"Item"}),o.jsx(he.TopCell,{children:"Experiment"}),o.jsx(he.TopCell,{children:"Dataset"}),o.jsx(he.TopCell,{children:"Trace"}),o.jsx(he.TopCell,{children:" "})]}),l.length===0?o.jsx(he.NoMatch,{message:"No dataset items match your search"}):l.map((d,f)=>{const p=pTe(d.experimentId,d.id);return o.jsxs(he.RowWrapper,{children:[o.jsxs(he.RowButton,{colEnd:-2,onClick:()=>r(p),...u(f),children:[o.jsx(he.TextCell,{font:"mono",children:d.itemId}),o.jsx(he.TextCell,{font:"mono",children:d.experimentId}),o.jsx(he.TextCell,{font:"mono",children:d.datasetId}),o.jsx(he.TextCell,{font:"mono",children:d.traceId??"—"})]}),o.jsx(he.ActionsCell,{className:"pl-2",children:d.traceId?o.jsx(le,{as:Ba,to:`/traces?traceId=${encodeURIComponent(d.traceId)}`,variant:"ghost",size:"sm",children:"Open trace"}):null})]},d.id)})]})})]})}function Wvs(){return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx(E0e,{}),titleSlot:"Your inbox is empty",descriptionSlot:o.jsxs(o.Fragment,{children:["Feedback left on traces and experiment results flagged for review ",o.jsx("br",{}),"will show up here until you mark them reviewed."]}),actionSlot:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(le,{as:Ba,to:"/experiments",variant:"outline",children:"Go to experiments"}),o.jsx(le,{as:Ba,to:"/traces",variant:"outline",children:"Go to traces"})]})})})}function a0e(e){return e.comment?e.comment:typeof e.value=="string"?e.value:e.feedbackType==="thumbs"?e.value===1?"Thumbs up":"Thumbs down":JSON.stringify(e.value)??String(e.value)}const Stt="minmax(0, 2fr) auto minmax(0, 1fr) auto auto";function Zvs({items:e,isLoading:t,error:n,hasNextPage:r,isFetchingNextPage:s,fetchNextPage:a,onMarkReviewed:i,pendingFeedbackId:l,onSelect:c,selectedFeedbackId:u}){const[d,f]=g.useState(""),p=d.trim().toLowerCase(),h=p?e.filter(x=>a0e(x).toLowerCase().includes(p)||(x.traceId??"").toLowerCase().includes(p)||(x.feedbackSource??"").toLowerCase().includes(p)):e,{containerRef:m,getRowProps:v}=so({count:h.length}),{inView:y,setRef:b}=t0({root:m});return g.useEffect(()=>{y&&r&&!s&&a()},[y,r,s,a]),t?o.jsx(Fo,{columns:Stt}):n?o.jsx($a,{title:"Failed to load feedback",message:n.message}):o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_1fr] gap-4",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(od,{onSearch:f,label:"Filter feedback",placeholder:"Filter loaded feedback by text, trace or source"})}),o.jsx("div",{className:"min-h-0 overflow-hidden",children:o.jsxs(he,{columns:Stt,fit:"container",scrollRef:m,children:[o.jsxs(he.Top,{children:[o.jsx(he.TopCell,{children:"Feedback"}),o.jsx(he.TopCell,{children:"Source"}),o.jsx(he.TopCell,{children:"Trace"}),o.jsx(he.TopCell,{children:"Date"}),o.jsx(he.TopCell,{children:" "})]}),h.length===0?o.jsx(he.NoMatch,{message:p?"No feedback matches your search":"No feedback needs review"}):h.map((x,S)=>{const k=x.feedbackId;return o.jsxs(he.RowWrapper,{children:[o.jsxs(he.RowButton,{colEnd:-2,disabled:!x.traceId,featured:k!==void 0&&k===u,onClick:()=>c(x),...v(S),children:[o.jsx(he.TextCell,{className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:a0e(x)})}),o.jsx(he.Cell,{children:o.jsx(xt,{size:"sm",children:x.feedbackSource})}),o.jsx(he.TextCell,{font:"mono",className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:x.traceId??"—"})}),o.jsx(he.TextCell,{children:dr(x.timestamp,"MMM d, h:mm a")})]}),o.jsx(he.ActionsCell,{className:"pl-2",children:k?o.jsx(le,{variant:"ghost",size:"sm",onClick:()=>i(k),disabled:l===k,children:"Mark reviewed"}):null})]},k??`${String(x.timestamp)}-${x.traceId}`)}),o.jsx(he.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:b})]})})]})}function Gvs({feedback:e,traceId:t,initialSpanId:n,onClose:r,onPrevious:s,onNext:a,onMarkReviewed:i,isMarkingReviewed:l}){const[c,u]=g.useState(n),{spans:d,isLoading:f}=PAe({traceId:t,anchorSpanId:null,listMode:"traces"});return o.jsx(aY,{label:`Review feedback for trace ${t}`,wide:!!c,children:o.jsxs("div",{className:"[&>*]:bg-surface3 grid h-full min-h-0 grid-rows-[auto_minmax(0,1fr)] gap-4 p-3 [&>*]:rounded-lg [&>*]:shadow-lg",children:[o.jsxs(on,{className:"max-h-[33vh]",children:[o.jsxs(on.Header,{className:"items-start",children:[o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(on.Heading,{children:"Feedback"}),o.jsx(xt,{variant:"neutral",emphasis:"muted",children:e.feedbackType}),e.feedbackSource&&o.jsx(xt,{variant:"neutral",emphasis:"muted",children:e.feedbackSource})]}),o.jsxs(ve,{as:"p",variant:"ui-sm",className:"text-neutral3",children:[dr(new Date(e.timestamp),"MMM dd, yyyy HH:mm:ss"),e.feedbackUserId?` · ${e.feedbackUserId}`:null]})]}),o.jsx(es,{className:"ml-auto shrink-0",children:o.jsxs(le,{variant:"primary",size:"sm",onClick:i,disabled:l,children:[o.jsx(We,{children:o.jsx(qr,{})}),"Mark as reviewed"]})})]}),o.jsx(on.Content,{children:o.jsx(ve,{as:"p",variant:"ui-md",className:"text-neutral5 whitespace-pre-wrap",children:a0e(e)})})]}),o.jsx("section",{className:"min-h-0 overflow-hidden",children:o.jsx(JQ,{className:"h-full rounded-none border-0 bg-transparent",spanPanelClassName:"rounded-none border-0 bg-transparent",traceId:t,spans:d,isLoadingSpans:f,selectedSpanId:c??null,initialSpanId:n,onSpanSelect:u,onClose:r,onPrevious:s,onNext:a,traceHref:`/traces?traceId=${encodeURIComponent(t)}`,feedbackTabSlot:({traceId:p})=>o.jsx(oRe,{traceId:p}),spanFeedbackTabSlot:({traceId:p,spanId:h})=>p&&h?o.jsx(iRe,{traceId:p,spanId:h},`${p}:${h}`):null})})]})})}const aHt=100;async function Qvs(e){const t=[];let n=0,r=!0;for(;r;){const s=await e.listExperiments({page:n,perPage:aHt});t.push(...s.experiments),r=s.pagination.hasMore,n+=1}return t}async function Yvs(e,t,n){const r=[];let s=0,a=!0;for(;a;){const i=await e.listDatasetExperimentResults(t,n,{page:s,perPage:aHt});r.push(...i.results),a=i.pagination.hasMore,s+=1}return r}function Kvs(){const e=Ge();return mt({queryKey:["inbox-dataset-review-items"],queryFn:async()=>{const t=await Qvs(e);return(await Promise.all(t.map(async r=>{const s=r.datasetId;return s?(await Yvs(e,s,r.id)).filter(i=>i.status==="needs-review").map(i=>({id:i.id,datasetId:s,experimentId:r.id,itemId:i.itemId,traceId:i.traceId??void 0,input:i.input,output:i.output})):[]}))).flat()},refetchInterval:3e3,refetchOnWindowFocus:!1})}function Xvs({enabled:e}){const t=Ge();return mt({queryKey:["inbox-dataset-review-count"],queryFn:async()=>{const{counts:n}=await t.getExperimentReviewSummary();return n.reduce((r,s)=>r+s.needsReview,0)},enabled:e,refetchInterval:3e3})}function Jvs(e){return e==="dataset"||e==="feedback"}function eys(){const[e,t]=Ma(),n=e.get("tab"),r=Jvs(n)?n:"feedback",s=Uvs({reviewStatus:"needs-review"}),a=Vvs(),i=Kvs(),l=i.data??[],c=s.total??0,u=!s.isLoading&&!i.isLoading&&!s.error&&!i.error&&s.items.length===0&&l.length===0,d=e.get("feedbackId")??void 0,f=e.get("traceId")??void 0,p=e.get("spanId")??void 0,h=T=>{t(E=>{const N=new URLSearchParams(E);for(const I of["feedbackId","traceId","spanId"]){const A=T[I];A?N.set(I,A):N.delete(I)}return N},{replace:!0})},m=()=>h({}),v=T=>h({feedbackId:T.feedbackId??void 0,traceId:T.traceId??void 0,spanId:T.spanId??void 0}),y=s.items.findIndex(T=>T.feedbackId===d),b=y>=0?s.items[y]:void 0,x=y>0?s.items[y-1]:void 0,S=y>=0&&y<s.items.length-1?s.items[y+1]:void 0,k=!!f&&!!d,_=T=>{a.mutate({feedbackId:T,reviewStatus:"reviewed"},{onSuccess:()=>T===d&&m()})},C=T=>{t(E=>{const N=new URLSearchParams(E);return N.set("tab",T),N},{replace:!0})};return o.jsxs("div",{className:"relative h-full overflow-hidden",children:[o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs(Dl,{children:[o.jsx(Dl.Title,{children:"Inbox"}),o.jsx(Dl.Description,{children:"Items waiting for review"})]})}),o.jsx(Lt.MainArea,{className:"min-h-0 overflow-hidden",children:u?o.jsx(Wvs,{}):o.jsxs(Wc,{defaultTab:"feedback",value:r,onValueChange:C,className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[o.jsxs(Hc,{variant:"pill-ghost",children:[o.jsxs(Ur,{value:"feedback",className:"px-3 py-2.5",children:[o.jsx(We,{size:"sm",children:o.jsx($V,{})}),o.jsx(ve,{variant:"ui-sm",className:"text-inherit",children:"Feedback"}),c>0&&o.jsx(xt,{variant:"yellow",size:"sm",children:c})]}),o.jsxs(Ur,{value:"dataset",className:"px-3 py-2.5",children:[o.jsx(We,{size:"sm",children:o.jsx(Q1,{})}),o.jsx(ve,{variant:"ui-sm",className:"text-inherit",children:"Dataset items"}),l.length>0&&o.jsx(xt,{variant:"yellow",size:"sm",children:l.length})]})]}),o.jsx(Ss,{value:"feedback",className:"h-full min-h-0 pt-4",children:o.jsx(Zvs,{items:s.items,isLoading:s.isLoading,error:s.error??void 0,hasNextPage:s.hasNextPage,isFetchingNextPage:s.isFetchingNextPage,fetchNextPage:s.fetchNextPage,onMarkReviewed:_,pendingFeedbackId:a.isPending?a.variables?.feedbackId:void 0,onSelect:v,selectedFeedbackId:d})}),o.jsx(Ss,{value:"dataset",className:"h-full min-h-0 pt-4",children:o.jsx(Hvs,{items:l,isLoading:i.isLoading,error:i.error??void 0})})]})})]}),k&&f&&b&&o.jsx(Gvs,{feedback:b,traceId:f,initialSpanId:p,onClose:m,onPrevious:x?()=>v(x):void 0,onNext:S?()=>v(S):void 0,onMarkReviewed:()=>d&&_(d),isMarkingReviewed:a.isPending},`${d}:${f}`)]})}function tys({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 iHt({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("ul",{className:"space-y-1",children:e.map(s=>o.jsx(tys,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function nys({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(iHt,{connections:a,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function rys({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(nys,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):o.jsx(iHt,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?o.jsx("p",{className:"text-red-600",children:String(c)}):null]})}function sys({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:v}){return o.jsxs("div",{className:"space-y-4 border rounded p-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"provider-select",children:"Provider"}),o.jsxs("select",{id:"provider-select",className:"border rounded px-2 py-1 w-full",value:n,onChange:y=>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:v,disabled:!n||!r||u,children:u?"Authorizing…":"Connect"}),d?o.jsx("p",{className:"text-red-600",children:String(d)}):null,f&&o.jsxs("p",{className:"text-green-700",children:["Authorized: ",f.connectionId," (status: ",f.status,")"]})]})}const ktt=e=>e.authorId?.trim()||"shared",ays=(e,t)=>{if(!t||new Set(e.map(ktt)).size<=1)return null;const r=new Map;for(const a of e){const i=ktt(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},iys=["*","tool-providers:*","tool-providers:admin"];function oys(){const{data:e}=Fm();return e?.permissions?.some(t=>iys.includes(t))??!1}function lys(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,a]=g.useState(""),i=eA(),l=lG(e||null),c=T3t(e||null,n||null),u=E3t(),d=O3t(),f=oys(),p=i.data?.providers??[],h=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),v=g.useMemo(()=>ays(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(sys,{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(rys,{providerId:e,toolkit:n,connections:m,groupedByAuthor:v,isAdmin:f,isLoading:c.isLoading,error:c.error,disconnectPending:d.isPending,disconnectError:d.error,onDisconnect:x})]})}function cys({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(Hp,{className:"h-10 w-10"}),o.jsx("h1",{className:"text-neutral6 text-xl font-semibold",children:e})]}),t,n,r]})})}function oHt({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:a}=mc(),{mutate:i,isPending:l,error:c}=rPr(),{mutate:u,isPending:d,error:f}=aPr(),{mutate:p,isPending:h}=jMt(),[m,v]=g.useState(n),[y,b]=g.useState(""),[x,S]=g.useState(""),[k,_]=g.useState("");if(a)return o.jsx("div",{className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"text-neutral3",children:"Loading..."})});if(!s?.enabled||!s?.login)return o.jsx("div",{className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"text-neutral3",children:"Authentication is not configured"})});const{login:C}=s,T=C.type==="sso"||C.type==="both",E=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,M=()=>{t?t():e?window.location.href=e:window.location.href=vG("/")},F=D=>{D.preventDefault(),A?i({email:x,password:k},{onSuccess:M}):u({email:x,password:k,name:y||void 0},{onSuccess:M})},H=()=>{p({redirectUri:e},{onSuccess:D=>{window.location.href=D.url}})},z=()=>{v(A?"signup":"signin")},q=C.description?o.jsxs("div",{className:"border-border1 bg-surface1 flex items-start gap-2.5 rounded-md border p-3",children:[o.jsx(Ud,{className:"text-neutral4 mt-0.5 h-4 w-4 shrink-0"}),o.jsx("p",{className:"text-neutral3 text-sm",children:C.description})]}):null,V=r?o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:r}):null;return o.jsxs(cys,{title:A?"Sign in to Mastra Studio":"Create your account",description:q,errorBanner:V,children:[E&&o.jsxs("form",{onSubmit:F,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:D=>b(D.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:D=>S(D.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:D=>_(D.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(le,{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:z,className:"text-neutral6 hover:underline",children:A?"Sign up":"Sign in"})]})]}),T&&E&&o.jsxs("div",{className:"relative",children:[o.jsx("div",{className:"absolute inset-0 flex items-center",children:o.jsx("div",{className:"border-border1 w-full border-t"})}),o.jsx("div",{className:"relative flex justify-center text-sm",children:o.jsx("span",{className:"bg-surface1 text-neutral3 px-2",children:"or continue with"})})]}),T&&N&&o.jsxs(le,{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 uys(){const[e]=Ma(),t=Vr(),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(oHt,{redirectUri:n,onSuccess:i,initialMode:s,errorMessage:a})}const mp=Na.KeyValueList;function dys(e){return e instanceof Date?e:new Date(e)}function fys({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:a,collapsed:i,onCollapsedChange:l}){const[c,u]=g.useState(!1),d=i??c,f=l??u,p=dys(e.timestamp),h=e.traceId,m=e.spanId;return o.jsxs(Na,{collapsed:d,children:[o.jsxs(Na.Header,{children:[o.jsxs(Na.Heading,{children:["Log ",o.jsx("b",{children:dr(p,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(es,{className:"ml-auto shrink-0",children:[l&&o.jsx(le,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(rI,{}):o.jsx(CV,{})}),o.jsxs(es,{spacing:"close",children:[o.jsx(le,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(G1,{})}),o.jsx(le,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(_V,{})})]}),o.jsx(Na.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(Na.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:K("my-8 grid gap-2","[&>button]:justify-between [&>button]:overflow-hidden"),children:[h&&o.jsxs(es,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(le,{size:"md",className:"min-w-0 flex-1 overflow-hidden",onClick:()=>n?.(h),children:[o.jsx(zd,{}),o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",h]})]}),o.jsx(ka,{content:h,size:"md",tooltip:"Copy Trace ID to clipboard"})]}),m&&o.jsxs(es,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(le,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!h||!r,onClick:()=>h&&r?.(h,m),children:[o.jsx(zd,{}),o.jsx("span",{children:"Span"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",m]})]}),o.jsx(ka,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(mp,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(mp.Key,{children:"Entity Type"}),o.jsx(mp.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(mp.Key,{children:"Entity Name"}),o.jsx(mp.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(mp.Key,{children:"Service"}),o.jsx(mp.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(mp.Key,{children:"Environment"}),o.jsx(mp.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(mp.Key,{children:"Source"}),o.jsx(mp.Value,{children:e.source})]}),e.metadata&&Object.keys(e.metadata).length>0&&o.jsx(o.Fragment,{children:Object.entries(e.metadata).map(([v,y])=>o.jsxs(g.Fragment,{children:[o.jsx(mp.Key,{children:v}),o.jsx(mp.Value,{children:String(y)})]},v))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(Na.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function pys({error:e,resource:t,errorTitle:n}){if(ps(e))return o.jsx(Ts,{});if(hs(e))return o.jsx(Os,{resource:t});if(V4(e))return o.jsx(br,{iconSlot:o.jsx($c,{}),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(q4(e,"logs"))return o.jsx(br,{iconSlot:o.jsx($c,{}),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($a,{title:n,message:r??"Unknown error"})}function hys({listSlot:e,logPanelSlot:t,tracePanelSlot:n,spanPanelSlot:r,logCollapsed:s}){const a=!!t;return o.jsxs("div",{className:K("grid h-full min-h-0 items-start gap-4",a?"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[e,a&&o.jsxs("div",{className:K("grid h-full gap-4 overflow-auto",n&&r?s?"grid-rows-[auto_1fr_1fr]":"grid-rows-[1fr_1fr_1fr]":n?s?"grid-rows-[auto_1fr]":"grid-rows-[1fr_1fr]":s?"grid-rows-[auto]":"grid-rows-[1fr]"),children:[t,n,r]})]})}const mys={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 gys({level:e}){const t=mys[e];return o.jsx(fo,{children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function vys({entityType:e,className:t}){const n=K("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case"agent":return o.jsx(Ai,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return o.jsx(Bc,{className:n,"aria-hidden":!0});case"tool":return o.jsx(zf,{className:n,"aria-hidden":!0});default:return null}}function yys({entityType:e,entityName:t}){const n=e??"";return o.jsxs(fo,{className:"flex min-w-0 items-center gap-2",children:[o.jsx(vys,{entityType:n}),t?o.jsx("span",{className:"text-ui-smd min-w-0 truncate",children:t}):"-"]})}function bys({message:e}){return o.jsx(fo,{className:"text-ui-smd text-neutral4 min-w-0 truncate font-mono",children:e})}function xys({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(fo,{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(LEe,{font:"mono",children:t})}const ec=Object.assign(z4,{Top:U4,TopCell:pS,TopCellWithTooltip:GZ,TopCellSmart:$Pt,RowWrapper:BEe,RowButton:B4,RowLink:PPt,Spacer:UEe,NoMatch:ZZ,DateCell:IPt,TimeCell:APt,LevelCell:gys,EntityCell:yys,MessageCell:bys,DataCell:xys,NextPageLoading:WZ}),Ott="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",wys=36,Sys=8;function kys({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=g.useRef(null),u=gqt({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>wys,overscan:Sys}),{getRowProps:d}=so({count:e.length,containerRef:c,onNavigate:y=>u.scrollToIndex(y)}),f=g.useRef(t);if(g.useEffect(()=>{f.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),f.current=t},[t]),t)return o.jsx(Fo,{columns:Ott});const p=u.getVirtualItems(),h=u.getTotalSize(),m=p[0]?.start??0,v=p.length>0?Math.max(0,h-(p[p.length-1]?.end??0)):0;return o.jsxs(ec,{columns:Ott,scrollRef:c,className:"min-w-0",children:[o.jsxs(ec.Top,{children:[o.jsx(ec.TopCell,{children:"Date"}),o.jsx(ec.TopCell,{children:"Time"}),o.jsx(ec.TopCell,{children:"Level"}),o.jsx(ec.TopCell,{children:"Entity"}),o.jsx(ec.TopCell,{children:"Message"}),o.jsx(ec.TopCell,{children:"Data"})]}),e.length===0?o.jsx(ec.NoMatch,{message:"No logs match your search"}):o.jsxs(o.Fragment,{children:[o.jsx(ec.Spacer,{height:m}),p.map(y=>{const b=e[y.index];if(!b)return null;const x=a.get(b);if(!x)return null;const S=x===i;return o.jsxs(ec.RowButton,{ref:u.measureElement,"data-index":y.index,...d(y.index),onClick:()=>l(b),featured:S,variant:b.level==="error"||b.level==="fatal"?"error":"default",children:[o.jsx(ec.DateCell,{timestamp:b.timestamp}),o.jsx(ec.TimeCell,{timestamp:b.timestamp}),o.jsx(ec.LevelCell,{level:b.level}),o.jsx(ec.EntityCell,{entityType:b.entityType,entityName:b.entityName}),o.jsx(ec.MessageCell,{message:b.message}),o.jsx(ec.DataCell,{data:b.data})]},x)}),o.jsx(ec.Spacer,{height:v})]}),o.jsx(ec.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function Oys({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=>_ys(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(YAe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(GAe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function _ys(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 Cys={"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"},Xie="MMM d, yyyy HH:mm",Jie="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function Eys({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${Cys[e]}`,description:Jie}:t&&n?{title:`No logs between ${dr(t,Xie)} and ${dr(n,Xie)}`,description:Jie}:t?{title:`No logs since ${dr(t,Xie)}`,description:Jie}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const Tys=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=Eys({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx($c,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",children:["Logging Documentation ",o.jsx(ea,{})]})})})},jys=20,Nys=1e4;function Iys(e,t,n){if(e?.pagination?.hasMore)return n+1}function Ays(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 Rys(e){return q4(e.state.error,"logs")||V4(e.state.error)?!1:Nys}const Pys=({filters:e}={})=>{const t=Ge(),{inView:n,setRef:r}=t0(),s=Py({queryKey:["logs",e],queryFn:({pageParam:p})=>t.listLogsVNext({pagination:{page:p,perPage:jys},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:Iys,select:Ays,retry:!1,refetchInterval:Rys}),{hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,data:c,isLoading:u,isError:d,error:f}=s;return g.useEffect(()=>{n&&a&&!i&&l()},[n,a,i,l]),{data:c,hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,isLoading:u,isError:d,error:f,setEndOfListElement:r}},c8={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},lHt=[{label:"Agent",entityType:c8.AGENT},{label:"Workflow",entityType:c8.WORKFLOW},{label:"Scorer",entityType:c8.SCORER},{label:"Ingest",entityType:c8.INGEST}],$ys=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],Gx="rootEntityType",tx="datePreset",nx="dateFrom",rx="dateTo",Mys=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),jl={level:"filterLevel",tags:"filterTags",entityName:"filterEntityName",traceId:"filterTraceId",spanId:"filterSpanId",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId"},XL=Object.keys(jl),hRe=new Set(["tags"]),mRe="mastra:logs:saved-filters";function Dys(e,t=mRe){const n=Uys(e),r=e.get(tx);r&&n.set(tx,r);const s=e.get(nx);s&&n.set(nx,s);const a=e.get(rx);a&&n.set(rx,a);try{localStorage.setItem(t,n.toString())}catch{}}function Lys(e=mRe){try{localStorage.removeItem(e)}catch{}}function _tt(e=mRe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function Fys(e){if(e.has(tx)||e.has(nx)||e.has(rx)||e.has(Gx))return!0;for(const t of XL)if(e.has(jl[t]))return!0;return!1}function zys({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:lHt.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:$ys.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 Bys(e){const t=[],n=new Map([[Gx,"rootEntityType"]]);for(const s of XL)n.set(jl[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),hRe.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 Uys(e){const t=new URLSearchParams,n=e.get(Gx);n&&t.set(Gx,n);for(const r of XL){const s=jl[r];if(hRe.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 qys(e,t){e.delete(Gx);for(const n of XL)e.delete(jl[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(Gx,n.value);continue}const r=jl[n.fieldId];if(r){if(hRe.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 Vys({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 Hys(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 Wys="Filters setting for Logs saved",Zys="Filters setting for Logs cleared up";function Gys(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=g.useState(()=>_tt(r)!==null),c=g.useCallback(()=>{Dys(e,r),l(!0);const f=s?.saved??Wys;f!==!1&&ze.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{Lys(r),l(!1);const f=s?.cleared??Zys;f!==!1&&ze.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(a||d.current||(d.current=!0,Fys(e)))return;const f=_tt(r);f&&t(p=>{const h=new URLSearchParams(p);for(const[m,v]of f)h.append(m,v);return h},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function Qys(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 Yys(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,Qys(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function Kys(e,t,n,r){const s=g.useMemo(()=>Yys(e),[e]),a=g.useMemo(()=>{const h=new Map;for(const[m,v]of e.entries()){const y=s.get(v);y&&h.set(y,{log:v,idx:m})}return h},[e,s]),l=(t?a.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=g.useCallback(h=>s.get(h),[s]),d=g.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 i0e="logId",o0e="traceId",l0e="spanId",TP=1440*60*1e3,Xys={"last-24h":TP,"last-3d":3*TP,"last-7d":7*TP,"last-14d":14*TP,"last-30d":30*TP};function u8(e){e.delete(i0e),e.delete(o0e),e.delete(l0e)}function Jys(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const _=e.get(tx);return _&&Mys.has(_)?_:"last-24h"},[e]),a=e.get(nx),i=e.get(rx),l=g.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 _=Xys[s];return _?new Date(Date.now()-_):void 0},[s,a]),c=g.useMemo(()=>{if(s!=="custom"||!i)return;const _=new Date(i);return Number.isNaN(_.getTime())?void 0:_},[s,i]),u=g.useRef(s);u.current=s;const d=e.get(i0e),f=e.get(o0e),p=e.get(l0e),h=g.useMemo(()=>lHt.find(_=>_.entityType===e.get(Gx)),[e]),m=g.useMemo(()=>Bys(e),[e]),v=g.useCallback(_=>{t(C=>{const T=new URLSearchParams(C);for(const[E,N]of Object.entries(_)){const I=E==="logId"?i0e:E==="traceId"?o0e:l0e;N?T.set(I,N):T.delete(I)}return T},{replace:!0})},[t]),y=g.useCallback(_=>{t(C=>{const T=new URLSearchParams(C);return qys(T,_),u8(T),T},{replace:!0})},[t]),b=y,x=g.useCallback((_,C)=>{if(u.current!=="custom")return;const T=C==="from"?nx:rx;t(E=>{const N=new URLSearchParams(E);return _?N.set(T,_.toISOString()):N.delete(T),u8(N),N},{replace:!0})},[t]),S=g.useCallback(_=>{u.current=_,t(C=>{const T=new URLSearchParams(C);return _==="last-24h"?(T.delete(tx),T.delete(nx),T.delete(rx)):_==="custom"?T.set(tx,"custom"):(T.set(tx,_),T.delete(nx),T.delete(rx)),u8(T),T},{replace:!0})},[t]),k=g.useCallback(()=>{t(_=>{const C=new URLSearchParams(_);C.delete(Gx);for(const T of XL)C.delete(jl[T]);return C.delete(tx),C.delete(nx),C.delete(rx),u8(C),C},{replace:!0}),r?.()},[t,r]);return g.useMemo(()=>({searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,featuredLogId:d,featuredTraceId:f,featuredSpanId:p,selectedEntityOption:h,filterTokens:m,handleFeaturedChange:v,handleFilterTokensChange:b,handleDateChange:x,handleDatePresetChange:S,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,p,h,m,v,b,x,S,k,y])}const jb=Na.KeyValueList;function ebs({spanId:e,span:t,isLoading:n,onClose:r}){const s=DQ(t?.startedAt,t?.endedAt),a=vV(t?.startedAt),i=vV(t?.endedAt);return o.jsxs(Na,{children:[o.jsxs(Na.Header,{children:[o.jsxs(Na.Heading,{children:["Span ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Na.CloseButton,{onClick:r})]}),n?o.jsx(Na.LoadingData,{children:"Loading span..."}):t?o.jsxs(Na.Content,{children:[o.jsxs(jb,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(jb.Key,{children:"Type"}),o.jsx(jb.Value,{children:t.spanType})]}),a&&o.jsxs(o.Fragment,{children:[o.jsx(jb.Key,{children:"Started"}),o.jsx(jb.Value,{children:a})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(jb.Key,{children:"Ended"}),o.jsx(jb.Value,{children:i})]}),s&&o.jsxs(o.Fragment,{children:[o.jsx(jb.Key,{children:"Duration"}),o.jsx(jb.Value,{children:s})]})]}),o.jsx("br",{}),o.jsx(Na.CodeSection,{title:"Input",icon:o.jsx(wx,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(Na.CodeSection,{title:"Output",icon:o.jsx(rm,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(Na.CodeSection,{title:"Metadata",icon:o.jsx(sc,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(Na.CodeSection,{title:"Attributes",icon:o.jsx(sc,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(Na.NoData,{children:"Span not found."})]})}function tbs({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:a}){const i=g.useMemo(()=>XQ(t??[]),[t]),[l,c]=g.useState([]);g.useEffect(()=>{i.length>0&&c(WAe(i))},[i]);const u=d=>{s?.(a===d?void 0:d)};return o.jsxs(Na,{children:[o.jsxs(Na.Header,{children:[o.jsxs(Na.Heading,{children:["Trace ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Na.CloseButton,{onClick:r})]}),n?o.jsx(Na.LoadingData,{children:"Loading trace..."}):i.length===0?o.jsx(Na.NoData,{children:"No spans found for this trace."}):o.jsx(Na.Content,{children:o.jsx(dVt,{hierarchicalSpans:i,onSpanClick:u,selectedSpanId:a??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}function nbs(){const[e,t]=Ma(),n=Jys(e,t),r=Gys(e,t),[s,a]=g.useState(),[i,l]=g.useState(!1),{data:c=[],isPending:u}=rRe(),{data:d=[],isPending:f}=eRe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:p=[],isPending:h}=tRe(),{data:m=[],isPending:v}=nRe(),y=g.useMemo(()=>zys({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:p,loading:{tags:u,entityNames:f,serviceNames:v,environments:h}}),[c,d,m,p,u,f,v,h]),b=g.useMemo(()=>Vys({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:T}=Pys({filters:b}),{logIdMap:E,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:R}=Kys(x,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:L,isLoading:M}=RAe(n.featuredTraceId??null),{data:F,isLoading:H}=HAe(n.featuredTraceId??"",n.featuredSpanId??""),z=g.useCallback(()=>n.applyFilterTokens(Hys(y,n.filterTokens)),[y,n]),q=g.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),V=g.useCallback(Y=>n.handleFeaturedChange({traceId:Y,spanId:null}),[n]),D=g.useCallback((Y,te)=>n.handleFeaturedChange({traceId:Y,spanId:te}),[n]),G=g.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),U=g.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),P=g.useCallback(Y=>n.handleFeaturedChange({spanId:Y??null}),[n]),B=o.jsxs(Lt.TopArea,{children:[o.jsx(Lt.Row,{children:o.jsxs(Lt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(W4,{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(KAe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:S,onStartTextFilter:a})]})}),o.jsx(Oys,{isLoading:S,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:z,onRemoveAll:n.handleRemoveAll,onSave:r.handleSave,onRemoveSaved:r.hasSavedFilters?r.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(k)return o.jsxs(Lt,{width:"wide",height:"full",children:[B,o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(pys,{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(Lt,{width:"wide",height:"full",children:[B,o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(Tys,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Lt,{width:"wide",height:"full",children:[B,o.jsx(hys,{logCollapsed:i,listSlot:o.jsx(kys,{logs:x,isLoading:S,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:T,logIdMap:E,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(fys,{log:N,onClose:q,onTraceClick:V,onSpanClick:D,onPrevious:A,onNext:R,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(tbs,{traceId:n.featuredTraceId,spans:L?.spans,isLoading:M,onClose:G,onSpanSelect:P,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(ebs,{spanId:n.featuredSpanId,span:F?.span,isLoading:H,onClose:U}):null})]})}function rbs({server:e,rowProps:t}){const{paths:n,Link:r}=un(),a=Ge().options.baseUrl,i=a?`${a}/api/mcp/${e.id}/sse`:"",{data:l}=jBt(e),c=Object.values(l||{}),u=c.length,d=c.filter(h=>h.toolType==="agent").length,f=c.filter(h=>h.toolType==="workflow").length,p=tm(e.name,50);return o.jsxs(he.RowLink,{to:n.mcpServerLink(e.id),LinkComponent:r,...t,children:[o.jsx(he.NameCell,{children:p}),o.jsx(he.DescriptionCell,{children:i}),o.jsx(he.TextCell,{className:"text-center",children:d||""}),o.jsx(he.TextCell,{className:"text-center",children:u||""}),o.jsx(he.TextCell,{className:"text-center",children:f||""})]})}function sbs({mcpServers:e,isLoading:t,search:n=""}){const r=g.useMemo(()=>{const i=n.toLowerCase();return e.filter(l=>l.name?.toLowerCase().includes(i)||l.id?.toLowerCase().includes(i))},[e,n]),{containerRef:s,getRowProps:a}=so({count:r.length});return t?o.jsx(Fo,{columns:"auto 1fr auto auto auto"}):o.jsxs(he,{columns:"auto 1fr auto auto auto",scrollRef:s,children:[o.jsxs(he.Top,{children:[o.jsx(he.TopCell,{children:"Name"}),o.jsx(he.TopCell,{children:"URL"}),o.jsx(he.TopCellSmart,{long:"Agents",short:o.jsx(Ai,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(he.TopCellSmart,{long:"Tools",short:o.jsx(zf,{}),tooltip:"Tools",className:"text-center"}),o.jsx(he.TopCellSmart,{long:"Workflows",short:o.jsx(Bc,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(he.NoMatch,{message:"No MCP Servers match your search"}):null,r.map((i,l)=>o.jsx(rbs,{server:i,rowProps:a(l)},i.id))]})}const abs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx($c,{}),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(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(ea,{})]})})}),ibs=()=>{const{data:e=[],isLoading:t,error:n}=TQ(),[r,s]=g.useState("");return n&&ps(n)?o.jsx(Zn,{children:o.jsx(Ts,{})}):n&&hs(n)?o.jsx(Zn,{children:o.jsx(Os,{resource:"MCP servers"})}):n?o.jsx(Zn,{children:o.jsx($a,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(Zn,{children:o.jsx(abs,{})}):o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx(od,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(sbs,{mcpServers:e,isLoading:t,search:r})]})},obs=(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 lbs({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=un(),i=g.useMemo(()=>obs(e,t),[e,t]),l=g.useMemo(()=>i.filter(d=>d.id.toLowerCase().includes(r.toLowerCase())),[i,r]),{containerRef:c,getRowProps:u}=so({count:l.length});return n?o.jsx(Fo,{columns:"auto 1fr auto"}):o.jsxs(he,{columns:"auto 1fr auto",scrollRef:c,children:[o.jsxs(he.Top,{children:[o.jsx(he.TopCell,{children:"Name"}),o.jsx(he.TopCell,{children:"Description"}),o.jsx(he.TopCellSmart,{long:"Agents",short:o.jsx(Ai,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(he.NoMatch,{message:"No Tools match your search"}):null,l.map((d,f)=>{const p=tm(d.id,50),h=tm(d.description??"",200),m=d.agents.length;return o.jsxs(he.RowLink,{to:s.toolLink(d.id),LinkComponent:a,...u(f),children:[o.jsx(he.NameCell,{children:p}),o.jsx(he.DescriptionCell,{children:h}),o.jsx(he.TextCell,{className:"text-center",children:m||""})]},d.id)})]})}const cbs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx($c,{}),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(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(ea,{})]})})}),ubs=()=>{const e=Ge();return Sn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new D_;Object.entries(r??{}).forEach(([a,i])=>{s.set(a,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(a){throw ze.error("Error executing dev tool"),console.error("Error executing dev tool:",a),a}}})},dbs=({toolId:e})=>{const{canExecute:t}=Eo(),n=t("tools"),{data:r={}}=zm(),s=g.useMemo(()=>{for(const v of Object.values(r))if(v.tools){const y=Object.values(v.tools).find(b=>b.id===e);if(y)return y}return null},[r,e]),{data:a,isLoading:i,error:l}=vRr(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=ubs(),{requestContext:p}=ys();g.useEffect(()=>{if(l){const v=l instanceof Error?l.message:"Failed to load tool";ze.error(`Error loading tool: ${v}`)}},[l]);const h=async(v,y)=>{if(!c)return;const b={...p??{},...y??{}};return u({toolId:c.id,input:v,requestContext:b})},m=c?.inputSchema?wm(Tx(c?.inputSchema)):ws({});return i?o.jsxs("div",{className:"p-6",children:[o.jsx(Ct,{className:"mb-4 h-8 w-48"}),o.jsx(Ct,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(lAe,{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(ve,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ve,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function fbs({value:e,onValueChange:t,placeholder:n="Select a tool...",searchPlaceholder:r="Search tools...",emptyText:s="No tools found.",className:a,disabled:i=!1,variant:l,size:c}){const{data:u={},isLoading:d,isError:f,error:p}=XI(),{data:h={},isLoading:m,isError:v,error:y}=zm(),{navigate:b,paths:x}=un();g.useEffect(()=>{if(f){const C=p instanceof Error?p.message:"Failed to load tools";ze.error(`Error loading tools: ${C}`)}},[f,p]),g.useEffect(()=>{if(v){const C=y instanceof Error?y.message:"Failed to load agents";ze.error(`Error loading agents: ${C}`)}},[v,y]);const S=new Map;Object.values(h).forEach(C=>{C.tools&&Object.values(C.tools).forEach(T=>{S.has(T.id)||S.set(T.id,T)})}),Object.values(u).forEach(C=>{S.has(C.id)||S.set(C.id,C)});const k=Array.from(S.values()).map(C=>({label:C.id,value:C.id})),_=C=>{t?t(C):C&&C!==e&&b(x.toolLink(C))};return o.jsx(yl,{options:k,value:e,onValueChange:_,placeholder:d||m?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||d||m||f||v,variant:l,size:c})}const pbs=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=g.useState({sseUrl:"",httpStreamUrl:""});if(g.useEffect(()=>{if(!t)return;const i=window.MASTRA_SERVER_HOST,l=window.MASTRA_SERVER_PORT;let c=null;i&&l&&(c=`http://${i}:${l}`);const u=c||"http://localhost:4111",d=`${u}/api/mcp/${t.id}/sse`,f=`${u}/api/mcp/${t.id}/mcp`;s({sseUrl:d,httpStreamUrl:f})},[t]),e)return null;if(!t)return o.jsx(hy,{children:o.jsx(ve,{as:"h1",variant:"header-md",className:"text-neutral3 py-20 text-center font-medium",children:"Server not found"})});const a=`npx -y mcp-remote ${n}`;return o.jsxs(hy,{isDivided:!0,children:[o.jsxs("div",{className:"mx-auto w-full max-w-2xl px-8 py-12",children:[o.jsx(ve,{as:"h1",variant:"header-md",className:"text-neutral6 pb-4 font-medium",children:t.name}),o.jsxs("div",{className:"flex items-center gap-1 pb-6",children:[o.jsx(xt,{icon:o.jsx(lVt,{}),size:"sm",children:"Version"}),o.jsx(xt,{size:"sm",children:t.version_detail.version})]}),o.jsx(ve,{className:"text-neutral3 pb-4",children:"This MCP server can be accessed through multiple transport methods. Choose the one that best fits your use case."}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(xt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"HTTP"}),children:"Regular HTTP Endpoint"}),o.jsx(ve,{className:"text-neutral3 pt-1 pb-2",children:"Use for stateless HTTP transport with streamable responses."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ve,{className:"bg-surface4 rounded-lg px-2 py-1",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx(ka,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(xt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"SSE"}),children:"Server-Sent Events"}),o.jsx(ve,{className:"text-neutral3 pt-1 pb-2",children:"Use for real-time communication via SSE."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ve,{className:"bg-surface4 rounded-lg px-2 py-1",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx(ka,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(xt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"CLI"}),children:"Command Line"}),o.jsx(ve,{className:"text-neutral3 pt-1 pb-2",children:"Use for local command-line access via npx and mcp-remote."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ve,{className:"bg-surface4 rounded-lg px-2 py-1",children:a}),o.jsx("div",{className:"pt-1",children:o.jsx(ka,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"border-border1 h-full overflow-y-scroll border-l",children:o.jsx(hbs,{server:t})})]})},hbs=({server:e})=>{const{data:t={},isLoading:n}=jBt(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(We,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(TC,{})}),o.jsx(ve,{variant:"header-md",as:"h2",className:"font-medium",children:"Available Tools"})]}),o.jsx("div",{className:"flex flex-col gap-2 pt-6",children:r.map(s=>{const a=t[s];return o.jsx(gbs,{tool:a,serverId:e.id},s)})})]})};function mbs(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 gbs=({tool:e,serverId:t})=>{const n=g.useRef(null),{Link:r,paths:s}=un(),a=MBt[e.toolType||"tool"],i=mbs(e._meta);return o.jsxs(Hf,{onClick:()=>n.current?.click(),children:[o.jsx(C3t,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Zf,{children:[o.jsx(Wf,{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(xt,{size:"xs",children:"App"})]})}),o.jsx(ch,{children:e.description})]})]})},vbs=()=>{const{serverId:e}=fr(),{data:t=[],isLoading:n}=TQ(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(pbs,{isLoading:n,server:r})})};function ybs(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 bbs=({toolId:e,serverId:t})=>{const{canExecute:n}=Eo(),r=n("tools"),s=Ge(),{data:a,isLoading:i,error:l}=aAe(t,e),{mutateAsync:c,isPending:u,data:d}=Prs(t,e),f=a?ybs(a._meta):void 0,{data:p}=mt({queryKey:["mcp-app-resource",t,f],queryFn:async()=>f?(await s.readMcpServerResource(t,f)).contents[0]?.text??null:null,enabled:!!f}),h=g.useCallback(async(y,b)=>await c(b),[c]);g.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";ze.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(Ct,{className:"mb-4 h-8 w-48"}),o.jsx(Ct,{className:"h-32 w-full"})]});if(l)return null;if(!a)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ve,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ve,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let v;try{v=wm(a.inputSchema)}catch(y){console.error("Error processing input schema:",y),ze.error("Failed to process tool input schema."),v=ws({})}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(TBt,{html:p,toolName:a.name??a.id,onToolCall:h})}),o.jsx(lAe,{executionResult:d,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},xbs=()=>{const{serverId:e,toolId:t}=fr(),{data:n,isLoading:r}=aAe(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(bbs,{toolId:t,serverId:e})})},cHt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],YN="rootEntityType",KN={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"},lY=Object.keys(KN),gRe="mastra:metrics:saved-filters";function wbs(e){const t=Cbs(e);try{localStorage.setItem(gRe,t.toString())}catch{}}function Sbs(){try{localStorage.removeItem(gRe)}catch{}}function uHt(){try{const e=localStorage.getItem(gRe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function kbs(e){if(e.has(YN))return!0;for(const t of lY)if(e.has(KN[t]))return!0;return!1}function Obs({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:cHt.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 _bs(e){const t=[],n=new Map([[YN,"rootEntityType"]]);for(const s of lY)n.set(KN[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 Cbs(e){const t=new URLSearchParams,n=e.getAll(YN);for(const r of n)t.append(YN,r);for(const r of lY){const s=KN[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function Ebs(e,t){e.delete(YN);for(const n of lY)e.delete(KN[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?YN:KN[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 Tbs="Any";function Ctt(e){const t=e.trim();return t===""||t===Tbs}const jbs=new Set(cHt.map(e=>e.entityType));function Ett(e){const t=e.trim();return jbs.has(t)?t:void 0}function Nbs(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=>!Ctt(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?Ett(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(Ctt(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=Ett(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const dHt=[{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"}],Ibs=new Set(dHt.map(e=>e.value));function Abs(e){return typeof e=="string"&&(Ibs.has(e)||e==="custom")}const fHt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function cY(){return g.useContext(fHt)}function Rbs(e,t){return e!=="custom"?dHt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${dr(t.from,"MMM d, yyyy")} – ${dr(t.to,"MMM d, yyyy")}`:dr(t.from,"MMM d, yyyy"):"Custom range"}function Pbs({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:a,onCustomRangeChange:i,tracesBasePath:l,logsBasePath:c}){const u=g.useMemo(()=>JSON.stringify(n),[n]),d=g.useMemo(()=>n,[u]),f=g.useMemo(()=>Nbs(d),[d]),p=g.useMemo(()=>JSON.stringify(f),[f]),h=Rbs(t,a),m=g.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(fHt.Provider,{value:m,children:e})}const $bs=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function Mbs(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 Dbs(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 Lbs(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=cY(),s=g.useRef(e);s.current=e;const a=g.useRef(n);return a.current=n,o.jsx(W4,{preset:Mbs(e),onPresetChange:i=>{const l=Dbs(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:$bs})}const c0e=1440*60*1e3,Fbs={"24h":c0e,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function zbs(e,t,n){if(e!=="custom"){const r=Fbs[e]??c0e;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-c0e),end:t?.to??new Date(n)}}function Vm(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=cY(),s=g.useRef(null),a=e==="custom"?`custom:${t?.from?.getTime()??""}:${t?.to?.getTime()??""}`:`preset:${e}`;(!s.current||s.current.key!==a)&&(s.current={key:a,anchor:Date.now()});const i=s.current.anchor,l=g.useMemo(()=>zbs(e,t,i),[e,t,i]),c=g.useMemo(()=>({timestamp:l,...n}),[l,r]),u=g.useMemo(()=>`${a}|${r}`,[a,r]);return{datePreset:e,customRange:t,timestamp:l,filters:c,dimensionalFilter:n,filterKey:u}}function pHt(){const e=Ge(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function JL({href:e,LinkComponent:t="a"}){return o.jsx(le,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(ac,{})})}function Bbs({href:e,LinkComponent:t="a"}){return o.jsx(le,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(wXt,{})})}function Ubs(e){return e==="agents"||e==="workflows"||e==="tools"}function Ttt(e,t){if(e.length===0)return"0";const n=e.reduce((r,s)=>{const a=s[t];return r+(typeof a=="number"&&Number.isFinite(a)?a:0)},0);return`${Math.round(n/e.length)}`}function qbs(e){const t=e;return typeof t?.tsMs=="number"&&Number.isFinite(t.tsMs)}const Vbs=[{dataKey:"p50",label:"p50",color:Zp.blue,aggregate:e=>({value:Ttt(e,"p50"),suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:Zp.yellow,aggregate:e=>({value:Ttt(e,"p95"),suffix:"avg ms"})}];function eoe({data:e,onPointClick:t}){return e.length===0?o.jsx(Vt.NoData,{message:"No latency data yet"}):o.jsx(RD,{data:e,series:Vbs,onPointClick:t?n=>qbs(n)?t(n):void 0:void 0})}function Hbs({data:e,isLoading:t,isError:n,onPointClick:r,actions:s}){const a=(e?.agentData.length??0)>0,i=(e?.workflowData.length??0)>0,l=(e?.toolData.length??0)>0,c={agents:a,workflows:i,tools:l},u=a?"agents":i?"workflows":l?"tools":"agents",[d,f]=g.useState("agents"),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),v=e?Object.values(e).filter(Array.isArray).flat().map(b=>b.p50).filter(b=>typeof b=="number"):[],y=v.length>0?`${Math.round(v.reduce((b,x)=>b+x,0)/v.length)}ms`:"—";return o.jsxs(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(Vt.Summary,{value:y,label:"Avg p50"}),h?o.jsx(Vt.Actions,{children:h}):null]}),t?o.jsx(Vt.Loading,{}):n?o.jsx(Vt.Error,{message:"Failed to load latency data"}):o.jsx(Vt.Content,{children:m?o.jsxs(Wc,{value:p,onValueChange:b=>{Ubs(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(Hc,{children:[o.jsx(Ur,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(Ur,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(Ur,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(Ss,{value:"agents",children:o.jsx(eoe,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(Ss,{value:"workflows",children:o.jsx(eoe,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(Ss,{value:"tools",children:o.jsx(eoe,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Vt.NoData,{message:"No latency data yet"})})]})}function Wbs(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 Zbs(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 hHt(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=Wbs(s);l&&e.set(t,l)}function $o(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function mHt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function jtt({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const a=new URLSearchParams;a.set(Mw,"branches"),hHt(a,Dw,Lw,Fw,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Wx,i),r.status&&a.set(Zx,r.status),$o(a,Tl.entityName,r.entityName??n.entityName),$o(a,Tl.threadId,r.threadId??n.threadId),$o(a,Tl.resourceId,r.resourceId??n.resourceId),$o(a,Tl.entityId,n.entityId),$o(a,Tl.runId,n.runId),$o(a,Tl.sessionId,n.sessionId),$o(a,Tl.requestId,n.requestId),$o(a,Tl.userId,n.userId),$o(a,Tl.organizationId,n.organizationId),$o(a,Tl.experimentId,n.experimentId),$o(a,Tl.serviceName,n.serviceName),$o(a,Tl.environment,n.environment),mHt(a,Tl.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function Gbs({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;hHt(a,tx,nx,rx,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Gx,i),$o(a,jl.entityName,r.entityName??n.entityName),$o(a,jl.threadId,r.threadId??n.threadId),$o(a,jl.resourceId,r.resourceId??n.resourceId),$o(a,jl.runId,n.runId),$o(a,jl.sessionId,n.sessionId),$o(a,jl.requestId,n.requestId),$o(a,jl.userId,n.userId),$o(a,jl.organizationId,n.organizationId),$o(a,jl.experimentId,n.experimentId),$o(a,jl.serviceName,n.serviceName),$o(a,jl.environment,n.environment),mHt(a,jl.tags,n.tags),r.status==="error"&&a.append(jl.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function gA(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=cY(),a=g.useCallback((c={})=>jtt({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=g.useCallback((c={})=>Gbs({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=Zbs(u,d);return jtt({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const gHt="1h";async function toe(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:gHt,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 Qbs(){const e=Ge(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([toe(e,"mastra_agent_duration_ms",t),toe(e,"mastra_workflow_duration_ms",t),toe(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:gHt}}})}const Ntt={agents:Ku.AGENT,workflows:Ku.WORKFLOW_RUN,tools:Ku.TOOL};function Ybs(){const{data:e,isLoading:t,isError:n}=Qbs(),{getTracesHref:r,getBucketTracesHref:s}=gA(),{Link:a}=un(),i=Vr();return o.jsx(Hbs,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:Ntt[l]},c.tsMs,"1h"))},actions:l=>o.jsx(JL,{href:r({rootEntityType:Ntt[l]}),LinkComponent:a})})}function Kbs(e){return e==="threads"||e==="resources"}function noe(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function Xbs({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("threads"),c=e.data?.map(y=>({...y,key:y.threadId}))??[],u=t.data?.map(y=>({...y,key:y.resourceId}))??[],d=c.length>0,f=u.length>0,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,v=typeof s=="function"?s(i):s;return o.jsxs(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&o.jsx(Vt.Summary,{value:p.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&o.jsx(Vt.Summary,{value:h.toLocaleString(),label:"Total threads"}),v?o.jsx(Vt.Actions,{children:v}):null]}),m.isLoading?o.jsx(Vt.Loading,{}):m.isError?o.jsx(Vt.Error,{message:"Failed to load memory data"}):o.jsx(Vt.Content,{children:o.jsxs(Wc,{defaultTab:"threads",value:i,onValueChange:y=>{Kbs(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Hc,{children:[o.jsx(Ur,{value:"threads",children:"Threads"}),o.jsx(Ur,{value:"resources",children:"Resources"})]}),o.jsx(Ss,{value:"threads",children:d?o.jsxs(he,{columns:"auto auto auto auto auto",...Xxe,children:[o.jsxs(he.Top,{children:[o.jsx(he.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(he.RowHeaderCell,{className:"text-ui-sm",children:noe(y.threadId)}),o.jsx(he.NumberCell,{children:y.resourceId?noe(y.resourceId):"—"}),o.jsx(he.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(he.NumberCell,{children:y.tokens>0?al(y.tokens):"—"}),o.jsx(he.NumberCell,{children:y.cost!=null?Wp(y.cost,y.costUnit):"—"})]});return b?o.jsx(he.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(he.RowStatic,{children:x},y.key)})]}):o.jsx(Vt.NoData,{message:"No thread activity yet"})}),o.jsx(Ss,{value:"resources",children:f?o.jsxs(he,{columns:"auto auto auto auto",...Xxe,children:[o.jsxs(he.Top,{children:[o.jsx(he.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(he.RowHeaderCell,{className:"text-ui-sm",children:noe(y.resourceId)}),o.jsx(he.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(he.NumberCell,{children:y.tokens>0?al(y.tokens):"—"}),o.jsx(he.NumberCell,{children:y.cost!=null?Wp(y.cost,y.costUnit):"—"})]});return b?o.jsx(he.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(he.RowStatic,{children:x},y.key)})]}):o.jsx(Vt.NoData,{message:"No resource activity yet"})})]})})]})}const roe=20;function Jbs(){const e=Ge(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","top-active-threads",n],queryFn:async()=>{const r={groupBy:["threadId","resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count",limit:roe}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:roe}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:roe})]),l=new Map,c=d=>mA(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 soe=20;function exs(){const e=Ge(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","top-resources-by-threads",n],queryFn:async()=>{const r={groupBy:["resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",limit:soe}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:soe}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:soe})]),l=new Map,c=d=>mA(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 txs(){const e=Jbs(),t=exs(),{getTracesHref:n}=gA(),{Link:r}=un();return o.jsx(Xbs,{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 e5({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:a}){const i=t!=null;return o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:e}),o.jsx(Xr.Value,{className:i?void 0:"invisible",children:i?t:"—"}),a?o.jsx(Xr.Error,{}):s?o.jsx(Xr.Loading,{}):i?r!=null?o.jsx(Xr.Change,{changePct:r,prevValue:n}):o.jsx(Xr.NoChange,{}):o.jsx(Xr.NoData,{})]})}function nxs(){const e=Ge(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","active-resources-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"resourceId",filters:t,comparePeriod:"previous_period"})})}function rxs(){const e=Ge(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","active-threads-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",filters:t,comparePeriod:"previous_period"})})}function sxs(){const e=Ge(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","model-cost-kpi",n],queryFn:async()=>{const r=await e.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"});return{cost:r.estimatedCost??null,costUnit:r.costUnit??null,previousCost:r.previousEstimatedCost??null,costChangePercent:r.costChangePercent??null}}})}function axs(){const e=Ge(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","total-tokens-kpi",n],queryFn:async()=>{const[r,s]=await Promise.all([e.getMetricAggregate({name:["mastra_model_total_input_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"}),e.getMetricAggregate({name:["mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"})]),a=r.value!=null||s.value!=null,i=r.previousValue!=null||s.previousValue!=null,l=(r.value??0)+(s.value??0),c=(r.previousValue??0)+(s.previousValue??0),u=i&&c>0?(l-c)/c*100:null;return{value:a?l:null,previousValue:i?c:null,changePercent:u}}})}function ixs(){const{data:e,isLoading:t,isError:n}=pHt();return o.jsx(e5,{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 oxs(){const{data:e,isLoading:t,isError:n}=sxs();return o.jsx(e5,{label:"Total Model Cost",value:e?.cost!=null?Wp(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?Wp(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function lxs(){const{data:e,isLoading:t,isError:n}=axs();return o.jsx(e5,{label:"Total Tokens",value:e?.value!=null?al(e.value):null,prevValue:e?.previousValue!=null?al(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function cxs(){const{data:e,isLoading:t,isError:n}=rxs();return o.jsx(e5,{label:"Total Threads",value:e?.value!=null?al(e.value):null,prevValue:e?.previousValue!=null?al(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function uxs(){const{data:e,isLoading:t,isError:n}=nxs();return o.jsx(e5,{label:"Total Resources",value:e?.value!=null?al(e.value):null,prevValue:e?.previousValue!=null?al(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function dxs({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=>fxs(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(YAe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(GAe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function fxs(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 pxs({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const i=!!e&&e.length>0;return o.jsxs(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Model Usage & Cost",description:"Token consumption by model."}),i&&(()=>{const l=e.reduce((d,f)=>d+(f.cost??0),0),c=new Set;for(const d of e)d.cost!=null&&d.costUnit&&c.add(d.costUnit);let u;return c.size===0?u=l>0?Wp(l):"—":c.size===1?u=l>0?Wp(l,[...c][0]):"—":u="Mixed",o.jsx(Vt.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(Vt.Actions,{children:s}):null]}),t?o.jsx(Vt.Loading,{}):n?o.jsx(Vt.Error,{message:"Failed to load model usage data"}):o.jsx(Vt.Content,{children:i?o.jsxs(he,{columns:"auto auto auto auto auto auto",...Xxe,children:[o.jsxs(he.Top,{children:[o.jsx(he.TopCell,{sticky:"start",children:"Model"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(he.RowHeaderCell,{className:"text-ui-sm",children:l.model}),o.jsx(he.NumberCell,{children:l.input}),o.jsx(he.NumberCell,{children:l.output}),o.jsx(he.NumberCell,{children:l.cacheRead}),o.jsx(he.NumberCell,{children:l.cacheWrite}),o.jsx(he.NumberCell,{highlight:!0,children:l.cost!=null?Wp(l.cost,l.costUnit):"—"})]});return c?o.jsx(he.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(he.RowStatic,{children:u},l.model)})]}):o.jsx(Vt.NoData,{message:"No model usage data yet"})})]})}function hxs(){const e=Ge(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","model-usage-cost",n],queryFn:async()=>{const[r,s,a,i]=await Promise.all(["mastra_model_total_input_tokens","mastra_model_total_output_tokens","mastra_model_input_cache_read_tokens","mastra_model_input_cache_write_tokens"].map(d=>e.getMetricBreakdown({name:[d],groupBy:["model"],aggregation:"sum",orderDirection:"DESC",filters:t})));if(!r||!s||!a||!i)return[];const l=new Map,c=d=>mA(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:al(f.input),output:al(f.output),cacheRead:al(f.cacheRead),cacheWrite:al(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function mxs(){const{data:e,isLoading:t,isError:n}=hxs(),{getTracesHref:r}=gA(),{Link:s}=un();return o.jsx(pxs,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:Ku.AGENT}),actions:o.jsx(JL,{href:r({rootEntityType:Ku.AGENT}),LinkComponent:s})})}function gxs(e){return e==="tokens"||e==="cost"}function vxs({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("tokens"),c=e??[],u=c.length>0,d=c.reduce((b,x)=>b+x.total,0),f=c.filter(b=>b.cost!=null&&b.cost>0),p=new Set(f.map(b=>b.costUnit??"usd")),h=p.size<=1,m=h?[...p][0]??"usd":null,v=h?f.reduce((b,x)=>b+(x.cost??0),0):0,y=h&&v>0;return o.jsxs(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&y?o.jsx(Vt.Summary,{value:Wp(v,m),label:"Total cost"}):o.jsx(Vt.Summary,{value:al(d),label:"Total tokens"})),u&&s?o.jsx(Vt.Actions,{children:s}):null]}),t?o.jsx(Vt.Loading,{}):n?o.jsx(Vt.Error,{message:"Failed to load token usage data"}):o.jsx(Vt.Content,{children:u?o.jsxs(Wc,{defaultTab:"tokens",value:i,onValueChange:b=>{gxs(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Hc,{children:[o.jsx(Ur,{value:"tokens",children:"Tokens"}),o.jsx(Ur,{value:"cost",children:"Cost"})]}),o.jsx(Ss,{value:"tokens",children:o.jsx(QN,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:Zp.blueDark},{label:"Output",color:Zp.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:al})}),o.jsx(Ss,{value:"cost",children:y?o.jsx(QN,{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:Zp.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>Wp(b,m)}):o.jsx(Vt.NoData,{message:"No cost data yet"})})]}):o.jsx(Vt.NoData,{message:"No token usage data yet"})})]})}function yxs(){const e=Ge(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","token-usage-by-agent",n],queryFn:async()=>{const r={groupBy:["entityName"],aggregation:"sum",orderDirection:"DESC",filters:t},[s,a]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"]}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"]})]),i=new Map,l=u=>mA(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 bxs(){const{data:e,isLoading:t,isError:n}=yxs(),{getTracesHref:r}=gA(),{Link:s}=un();return o.jsx(vxs,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:Ku.AGENT,entityName:a.name}),actions:o.jsx(JL,{href:r({rootEntityType:Ku.AGENT}),LinkComponent:s})})}function u0e(e,t=al){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const xxs=[{dataKey:"input",label:"Input tokens",color:Zp.blue,aggregate:u0e("input")},{dataKey:"output",label:"Output tokens",color:Zp.yellow,aggregate:u0e("output")}];function wxs(e){return e==="tokens"||e==="cost"}function Sxs({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[a,i]=g.useState("tokens"),l=e??[],c=l.map(k=>({...k})),u=l.length>0,d=l.reduce((k,_)=>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),v=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:Zp.purple,aggregate:u0e("cost",k=>Wp(k,v))}];return o.jsxs(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Token usage over time",description:x}),u&&(a==="cost"&&b?o.jsx(Vt.Summary,{value:Wp(y,v),label:"Total cost"}):o.jsx(Vt.Summary,{value:al(d),label:"Total tokens"})),u&&s?o.jsx(Vt.Actions,{children:s}):null]}),n?o.jsx(Vt.Loading,{}):r?o.jsx(Vt.Error,{message:"Failed to load token usage timeline"}):o.jsx(Vt.Content,{children:u?o.jsxs(Wc,{defaultTab:"tokens",value:a,onValueChange:k=>{wxs(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(Hc,{children:[o.jsx(Ur,{value:"tokens",children:"Tokens"}),o.jsx(Ur,{value:"cost",children:"Cost"})]}),o.jsx(Ss,{value:"tokens",children:o.jsx(RD,{data:c,series:xxs})}),o.jsx(Ss,{value:"cost",children:b?o.jsx(RD,{data:p,series:S}):o.jsx(Vt.NoData,{message:"No cost data yet"})})]}):o.jsx(Vt.NoData,{message:"No token usage data yet"})})]})}function kxs(e){return e==="24h"?"1h":"1d"}function Oxs(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 Itt(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 _xs(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function Cxs(){const e=Ge(),{datePreset:t,filters:n,filterKey:r}=Vm(),s=kxs(t);return mt({queryKey:["metrics","token-usage-timeseries",r,s],queryFn:async()=>{const[a,i]=await Promise.all([e.getMetricTimeSeries({name:["mastra_model_total_input_tokens"],interval:s,aggregation:"sum",filters:n}),e.getMetricTimeSeries({name:["mastra_model_total_output_tokens"],interval:s,aggregation:"sum",filters:n})]),l=new Map;return Itt(l,a.series[0],"input"),Itt(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:Oxs(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:_xs(u)}}),interval:s}}})}function Exs(){const{data:e,isLoading:t,isError:n}=Cxs(),{getTracesHref:r}=gA(),{Link:s}=un();return o.jsx(Sxs,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(JL,{href:r(),LinkComponent:s})})}function aoe({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(QN,{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:Zp.blueDark},{label:"Errors",color:Zp.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:al})}function Txs({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:a,LinkComponent:i}){const[l,c]=g.useState("agents"),u=typeof a=="function"?a(l):a,d=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),f=e?[...e.agentData,...e.workflowData,...e.toolData].reduce((m,v)=>m+v.completed+v.errors,0):0,p=m=>r?v=>r(m,v):void 0,h=m=>s?v=>s(m,v):void 0;return o.jsxs(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(Vt.Summary,{value:al(f),label:"Total runs"}),u?o.jsx(Vt.Actions,{children:u}):null]}),t?o.jsx(Vt.Loading,{}):n?o.jsx(Vt.Error,{message:"Failed to load trace volume data"}):o.jsx(Vt.Content,{children:d?o.jsxs(Wc,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Hc,{children:[o.jsx(Ur,{value:"agents",children:"Agents"}),o.jsx(Ur,{value:"workflows",children:"Workflows"}),o.jsx(Ur,{value:"tools",children:"Tools"})]}),o.jsx(Ss,{value:"agents",children:e.agentData.length>0?o.jsx(aoe,{data:e.agentData,rowHrefs:p("agents"),errorHrefs:h("agents"),LinkComponent:i}):o.jsx(Vt.NoData,{message:"No agent data yet"})}),o.jsx(Ss,{value:"workflows",children:e.workflowData.length>0?o.jsx(aoe,{data:e.workflowData,rowHrefs:p("workflows"),errorHrefs:h("workflows"),LinkComponent:i}):o.jsx(Vt.NoData,{message:"No workflow data yet"})}),o.jsx(Ss,{value:"tools",children:e.toolData.length>0?o.jsx(aoe,{data:e.toolData,rowHrefs:p("tools"),errorHrefs:h("tools"),LinkComponent:i}):o.jsx(Vt.NoData,{message:"No tool data yet"})})]}):o.jsx(Vt.NoData,{message:"No trace volume data yet"})})]})}async function ioe(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=mA(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 jxs(){const e=Ge(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([ioe(e,"mastra_agent_duration_ms",t),ioe(e,"mastra_workflow_duration_ms",t),ioe(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const d8={agents:Ku.AGENT,workflows:Ku.WORKFLOW_RUN,tools:Ku.TOOL};function Nxs(){const{data:e,isLoading:t,isError:n}=jxs(),{getTracesHref:r,getLogsHref:s}=gA(),{Link:a}=un();return o.jsx(Txs,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:d8[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:d8[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(JL,{href:r({rootEntityType:d8[i]}),LinkComponent:a}),o.jsx(Bbs,{href:s({rootEntityType:d8[i],status:"error"}),LinkComponent:a})]})})}const ooe="period",f8="dateFrom",p8="dateTo";function Ixs(){const[e,t]=Ma(),n=e.get(ooe),r=Abs(n)?n:"24h",s=g.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(f8)),p=d(e.get(p8));if(!(!f&&!p))return{from:f,to:p}},[r,e.toString()]),a=g.useMemo(()=>_bs(e),[e.toString()]),i=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d==="24h"?p.delete(ooe):p.set(ooe,d),d!=="custom"&&(p.delete(f8),p.delete(p8)),p},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d?.from?p.set(f8,d.from.toISOString()):p.delete(f8),d?.to?p.set(p8,d.to.toISOString()):p.delete(p8),p},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return Ebs(p,d),p},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,kbs(e)))return;const d=uHt();d&&t(f=>{const p=new URLSearchParams(f);for(const[h,m]of d)p.append(h,m);return p},{replace:!0})},[]),o.jsx(Pbs,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(Axs,{})})}function Axs(){const[e]=Ma(),{error:t,isLoading:n}=pHt(),{filterTokens:r,setFilterTokens:s}=cY(),[a,i]=g.useState(),{supportsMetrics:l,isInMemory:c,isLoading:u}=vVt(),{data:d,isLoading:f}=rRe(),{data:p,isLoading:h}=eRe(),{data:m,isLoading:v}=nRe(),{data:y,isLoading:b}=tRe(),x=g.useMemo(()=>Obs({availableTags:d??[],availableEntityNames:p??[],availableServiceNames:m??[],availableEnvironments:y??[],loading:{tags:f,entityNames:h,serviceNames:v,environments:b}}),[d,p,m,y,f,h,v,b]),[S,k]=g.useState(()=>uHt()!==null),_=g.useCallback(()=>{wbs(e),k(!0),ze.success("Filters setting for Metrics saved")},[e]),C=g.useCallback(()=>{Sbs(),k(!1),ze.success("Filters setting for Metrics cleared up")},[]),T=g.useCallback(()=>{s([])},[s]),E=g.useCallback(()=>{const N=r.map(I=>{const A=x.find(R=>R.id===I.fieldId);return A?A.kind==="text"?{fieldId:I.fieldId,value:""}:A.kind==="pick-multi"?A.multi?{fieldId:I.fieldId,value:[]}:{fieldId:I.fieldId,value:"Any"}:A.kind==="multi-select"?{fieldId:I.fieldId,value:[]}:I:I});s(N)},[x,r,s]);return t&&ps(t)?o.jsx(Zn,{children:o.jsx(Ts,{})}):t&&hs(t)?o.jsx(Zn,{children:o.jsx(Os,{resource:"metrics"})}):t?o.jsx(Zn,{children:o.jsx($a,{title:"Failed to load metrics",message:t.message})}):o.jsxs(Lt,{width:"wide",height:"full",children:[o.jsxs(Lt.TopArea,{children:[o.jsx(Lt.Row,{children:o.jsxs(Lt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(Lbs,{}),o.jsx(KAe,{fields:x,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(dxs,{isLoading:n,filterFields:x,filterTokens:r,onFilterTokensChange:s,onClear:E,onRemoveAll:T,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(Rn,{variant:"info",title:"Metrics are not persisted",children:o.jsx(Rn.Message,{children:"This project uses in-memory storage for observability. Metrics will be lost on every server restart. For persistent metrics, switch the observability storage to ClickHouse, DuckDB, Postgres v-next, or Spanner."})}),o.jsxs(s0e,{children:[o.jsx(ixs,{}),o.jsx(oxs,{}),o.jsx(lxs,{}),o.jsx(cxs,{}),o.jsx(uxs,{})]}),o.jsxs(s0e,{children:[o.jsx(mxs,{}),o.jsx(bxs,{}),o.jsx(Exs,{}),o.jsx(txs,{}),o.jsx(Nxs,{}),o.jsx(Ybs,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx($c,{}),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(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(ea,{})]})})})]})}const Rxs=50;function Pxs(){const{paths:e}=un(),{isCmsAvailable:t}=bS(),[n,r]=g.useState(""),[s,a]=g.useState(0),{data:i,isLoading:l,error:c,isPlaceholderData:u}=zBt({page:s,perPage:Rxs}),d=i?.promptBlocks??[],f=i?.hasMore??!1,p=g.useCallback(()=>{u||a(v=>v+1)},[u]),h=g.useCallback(()=>{u||a(v=>Math.max(0,v-1))},[u]),m=g.useCallback(v=>{r(v),a(0)},[]);return c&&ps(c)?o.jsx(Zn,{children:o.jsx(Ts,{})}):c&&hs(c)?o.jsx(Zn,{children:o.jsx(Os,{resource:"prompt blocks"})}):c?o.jsx(Zn,{children:o.jsx($a,{title:"Failed to load prompt blocks",message:c.message})}):d.length===0&&!l&&s===0?o.jsx(Zn,{children:o.jsx(Fas,{})}):o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(od,{onSearch:m,label:"Filter prompts",placeholder:"Filter by name or description"})}),t&&o.jsxs(le,{as:Ba,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(Cr,{}),"Create Prompt"]})]})}),o.jsx(Las,{promptBlocks:d,isLoading:l,search:n,currentPage:s,hasMore:f,onNextPage:p,onPrevPage:h})]})}function $xs(){return o.jsx(Lt,{width:"narrow",children:o.jsx(Lt.MainArea,{children:o.jsx(Oss,{children:o.jsx(Mxe,{})})})})}const Mxs=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:zYt,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:rct,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:ea,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:$V,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:cct,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:sct,href:"https://mastra.ai/contact?ref=studio",external:!0}];function Dxs(){return o.jsx(Lt,{width:"narrow",children:o.jsx(Lt.MainArea,{children:o.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:Mxs.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(ea,{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 Lxs(){const{data:e={},isLoading:t,error:n}=uh(),[r,s]=g.useState(""),[a,i]=g.useState("all");if(n&&ps(n))return o.jsx(Zn,{children:o.jsx(Ts,{})});if(n&&hs(n))return o.jsx(Zn,{children:o.jsx(Os,{resource:"scorers"})});if(n)return o.jsx(Zn,{children:o.jsx($a,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(Zn,{children:o.jsx(EBr,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(jBr,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(CBr,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}function Fxs(){const{scorerId:e}=fr(),[t,n]=Ma(),r=t.get("scoreId")??void 0,[s,a]=g.useState(r),[i,l]=g.useState(!1),c=Vr(),[u,d]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:f,error:p}=iBr(e),{data:h={},isLoading:m,error:v}=zm(),{isLoading:y,error:b}=Gy(),{data:x=[],isLoading:S,error:k,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:T}=aBr({scorerId:e,entityId:u?.value==="all"?void 0:u?.value,entityType:u?.type==="ALL"?void 0:u?.type}),E=g.useMemo(()=>f?.agentIds?.filter(P=>h[P]).map(P=>({value:P,label:h[P].name,type:"AGENT"}))||[],[f?.agentIds,h]),N=g.useMemo(()=>f?.workflowIds?.map(P=>({value:P,label:P,type:"WORKFLOW"}))||[],[f?.workflowIds]),I=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...E,...N],[E,N]),A=t.get("entity")??"all",R=I.find(P=>P.value===A);R&&R.value!==u?.value&&d(R),g.useEffect(()=>{if(p){const P=p instanceof Error?p.message:"Failed to load scorer";ze.error(`Error loading scorer: ${P}`)}},[p]),g.useEffect(()=>{if(v){const P=v instanceof Error?v.message:"Failed to load agents";ze.error(`Error loading agents: ${P}`)}},[v]),g.useEffect(()=>{if(b){const P=b instanceof Error?b.message:"Failed to load workflows";ze.error(`Error loading workflows: ${P}`)}},[b]);const L=P=>{P?.value&&n(B=>{const Z=new URLSearchParams(B);return Z.set("entity",P.value),Z})};g.useEffect(()=>{const P=t.get("scoreId")??void 0;if(P===s)return;if(!P){a(void 0);return}x.find(Z=>Z.id===P)&&a(P)},[t,x]);const M=g.useCallback(P=>{a(P||void 0),n(B=>{const Z=new URLSearchParams(B);return P?Z.set("scoreId",P):Z.delete("scoreId"),Z})},[n]);if(!f)return null;const F=ps(p)||ps(v)||ps(b),H=p&&hs(p),z=!F&&!H&&(p||v||b),q=!S&&x.length===0,V=u?.value!=="all",D=f?.scorer?.source==="stored"?o.jsx(Dy,{owner:"scorer-detail",children:o.jsxs(le,{variant:"default",as:Ba,to:`/cms/scorers/${e}/edit`,size:"sm",children:[o.jsx(Qp,{})," Edit"]})}):null,G=e?o.jsx(sY,{open:i,onOpenChange:l,initialScorerIds:[e],onSuccess:P=>{c(`/experiments/${P}`)}}):null;if(F||H||z||q&&!V){const P=(p instanceof Error?p.message:void 0)??(v instanceof Error?v.message:void 0)??(b instanceof Error?b.message:void 0)??"An unexpected error occurred";return o.jsxs(Lt,{width:"wide",height:"full",className:"grid-rows-[1fr]",children:[D,o.jsx(Lt.MainArea,{isCentered:!0,children:F?o.jsx(Ts,{}):H?o.jsx(Os,{resource:"scorers"}):z?o.jsx($a,{title:"Failed to load scorer",message:P}):o.jsx(K7r,{onRunExperiment:()=>l(!0)})}),G]})}return o.jsxs(Lt,{width:"wide",height:"full",children:[D,o.jsx(Lt.TopArea,{children:o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx(J7r,{selectedEntity:u,entityOptions:I,onEntityChange:L,onReset:()=>{n(P=>{const B=new URLSearchParams(P);return B.set("entity","all"),B})},isLoading:S||m||y}),o.jsxs(le,{variant:"primary",onClick:()=>l(!0),children:[o.jsx(Mc,{}),"Run Experiment"]})]})}),o.jsx(Y7r,{scores:x,isLoading:S,selectedScoreId:s,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:T,onScoreClick:M,errorMsg:k?.message}),G]})}const zxs=co("flex min-w-0 flex-col",{variants:{variant:{default:"gap-3 sm:flex-row sm:items-center sm:justify-between",factory:"gap-2 px-4 py-3 lg:flex-row lg:items-center lg:justify-between lg:gap-4"}},defaultVariants:{variant:"default"}}),Bxs=co("flex min-w-0 flex-col",{variants:{variant:{default:"",factory:"gap-0.5"}},defaultVariants:{variant:"default"}}),Att=co("",{variants:{variant:{default:"text-sm font-medium",factory:"text-ui-md leading-ui-md text-neutral5"}},defaultVariants:{variant:"default"}}),Uxs=co("flex flex-col gap-0.5",{variants:{variant:{default:"text-sm text-neutral3",factory:"text-ui-sm text-neutral3"}},defaultVariants:{variant:"default"}});function qxs({label:e,description:t,htmlFor:n,variant:r,className:s,children:a}){return o.jsxs("div",{className:K(zxs({variant:r}),s),"data-slot":"settings-row",children:[o.jsxs("div",{className:Bxs({variant:r}),children:[n?o.jsx(Pt,{htmlFor:n,className:Att({variant:r}),children:e}):o.jsx("span",{className:Att({variant:r}),children:e}),t&&o.jsx("div",{className:Uxs({variant:r}),children:t})]}),a]})}const vHt=[{value:"dark",label:"Dark",Icon:zXt},{value:"light",label:"Light",Icon:uen},{value:"system",label:"System",Icon:xct}],Vxs=e=>vHt.some(t=>t.value===e);function Hxs({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 Wxs=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=$H(),{theme:r,setTheme:s}=rC();return o.jsx(Lt,{width:"narrow",children:o.jsxs(Lt.MainArea,{className:"mt-6 flex flex-col gap-5",children:[o.jsx(cxe,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(qxs,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(oa,{value:r,onValueChange:a=>{Vxs(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:vHt.map(a=>o.jsx(xr,{value:a.value,children:o.jsx(Hxs,{option:a})},a.value))})]})})}),o.jsx(cxe,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(g4t,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function Zxs(){const[e]=Ma(),t=Vr(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(oHt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}function Gxs(e){return e.replace(/\/$/,"").split("/").pop()}function uY({children:e,className:t}){return o.jsx("div",{className:K("border border-border1 rounded-lg mt-12 py-8 lg:min-h-[25rem] transition-height px-4 lg:px-12",t),children:e})}function Qxs({templates:e,linkComponent:t,className:n,isLoading:r}){const s=t||"a";return r?o.jsx("div",{className:K("grid gap-y-4",n),children:Array.from({length:5}).map((a,i)=>o.jsx("div",{className:"bg-surface3 h-16 animate-pulse rounded-lg"},i))}):o.jsx("div",{className:K("grid gap-y-4",n),children:e.map(a=>{const i=a?.agents||a?.tools||a?.networks||a?.workflows||a?.mcp;return o.jsxs("article",{className:K("border border-border1 rounded-lg overflow-hidden w-full grid grid-cols-[1fr_auto] bg-surface3 transition-colors hover:bg-surface4"),children:[o.jsxs(s,{to:`/templates/${a.slug}`,className:K("grid [&:hover_p]:text-neutral5",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":a.imageURL}),children:[a.imageURL&&o.jsx("div",{className:K("overflow-hidden"),children:o.jsx("div",{className:"thumb transition-scale h-full w-full bg-cover duration-150",style:{backgroundImage:`url(${a.imageURL})`}})}),o.jsxs("div",{className:K("grid py-3 px-6 w-full gap-0.5","[&_svg]:w-[1em] [&_svg]:h-[1em] [&_svg]:text-neutral3"),children:[o.jsx("h2",{className:"text-ui-lg text-neutral5",children:a.title}),o.jsx("p",{className:"text-ui-md text-neutral4 transition-colors duration-500",children:a.description}),o.jsxs("div",{className:"text-neutral3 text-ui-md mt-3 hidden flex-wrap items-center gap-4 2xl:flex",children:[i&&o.jsxs("ul",{className:K("flex gap-4 text-ui-md text-neutral3 m-0 p-0 list-none","[&>li]:flex [&>li]:items-center [&>li]:gap-0.5 text-neutral4"),children:[a?.agents&&a.agents.length>0&&o.jsxs("li",{children:[o.jsx(Ai,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(zf,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(Sct,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(uI,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(TC,{})," ",a.mcp.length]})]}),i&&a.supportedProviders&&o.jsx("small",{children:"|"}),o.jsx("div",{className:"text-neutral3 flex items-center gap-4",children:a.supportedProviders.map(l=>o.jsx("span",{className:"",children:l},l))})]})]})]}),o.jsx("a",{href:a.githubUrl,className:K("group items-center gap-2 text-ui-md ml-auto pr-4 hidden","lg:flex"),target:"_blank",rel:"noopener noreferrer",children:o.jsxs("span",{className:"bg-surface1 group-hover:bg-surface2 text-neutral3 group-hover:text-neutral5 flex items-center gap-2 rounded px-2 py-1 transition-colors",children:[o.jsx(dG,{})," ",Gxs(a.githubUrl)]})})]},a.slug)})})}function Yxs({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:s,onProviderChange:a,searchTerm:i,onSearchChange:l,onReset:c,className:u,isLoading:d}){return d?o.jsxs("div",{className:K("h-[6.5rem] flex items-center gap-8","[&>div]:bg-surface3 [&>div]:w-48 [&>div]:h-8 [&>div]:animate-pulse",u),children:[o.jsx("div",{})," ",o.jsx("div",{})," ",o.jsx("div",{})]}):o.jsxs("div",{className:K("flex flex-wrap mx-auto sticky top-0 gap-4 bg-surface2 py-8",u),children:[o.jsx(y_,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(Ld,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(Ld,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(le,{onClick:c,children:["Reset ",o.jsx(or,{})]})]})}function Kxs(){const{data:e,isLoading:t}=Qnr(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[a,i]=g.useState("all"),[l,c]=g.useState("all"),[u,d]=g.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(x=>{f.push({value:x,label:x})});const 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)},v=()=>{i("all"),c("all"),d("")},y=n.filter(x=>!(u&&!x.title.toLowerCase().includes(u)&&!x.description.toLowerCase().includes(u)||a!=="all"&&!x.tags.includes(a)||l!=="all"&&!x.supportedProviders.includes(l))),b=u||a!=="all"||l!=="all";return o.jsxs(vs,{children:[o.jsx(OSe,{children:o.jsxs(jbt,{children:[o.jsx(We,{children:o.jsx(oy,{})}),"Templates"]})}),o.jsxs("div",{className:K("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(Yxs,{selectedTag:a,onTagChange:x=>h(x,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:x=>h(x,"provider"),providerOptions:p,searchTerm:u,onSearchChange:m,onReset:b?v:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(Qxs,{templates:y,linkComponent:Ba,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const Xxs="1.65.0-alpha.1";function Jxs({errorMsg:e,validationErrors:t}){const n=typeof e=="string"?e:e!=null?String(e):void 0,r=n?.includes("Invalid schema for function"),s=n?.includes("validation issue")||t&&t.length>0,a=()=>s?"Template installation completed but some validation issues remain. The template may still be functional, but you should review and fix these issues.":r?"There was an issue with the AI model configuration. This may be related to the selected model or AI SDK version compatibility.":"An unexpected error occurred during template installation.",i=()=>s?{icon:o.jsx(uc,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(eKt,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(uY,{className:"text-neutral3 mb-8 content-center space-y-4",children:[o.jsxs("div",{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[l,o.jsxs("div",{className:"space-y-2 text-center",children:[o.jsx("p",{className:"text-ui-md text-neutral5 font-medium",children:c}),o.jsx("p",{className:"text-ui-md text-neutral3",children:a()})]})]}),t&&t.length>0&&o.jsxs("details",{className:"text-xs",children:[o.jsxs("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:["Show Validation Issues (",t.length,")"]}),o.jsx("div",{className:"mt-4 max-h-60 space-y-2 overflow-auto rounded bg-gray-100 p-3 text-left text-xs dark:bg-gray-800",children:t.map((u,d)=>o.jsxs("div",{className:"border-l-2 border-red-400 pl-2",children:[o.jsx("div",{className:"font-medium text-red-600 dark:text-red-400",children:u.type==="typescript"?"🔴 TypeScript Error":"⚠️ Lint Error"}),o.jsx("div",{className:"mt-1 font-mono text-xs wrap-break-word whitespace-pre-wrap text-gray-700 dark:text-gray-300",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-xs",children:[o.jsx("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:"Show Details"}),o.jsx("div",{className:"mt-4 max-h-60 overflow-auto rounded bg-gray-100 p-3 text-left font-mono text-xs dark:bg-gray-800",children:o.jsx("div",{className:"wrap-break-word whitespace-pre-wrap",children:n})})]})]})}function e0s({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(uY,{children:o.jsxs("div",{className:"mx-auto my-4 grid max-w-[40rem] gap-8 p-4 lg:p-8",children:[o.jsxs("h2",{className:K("text-neutral4 text-header-sm font-semibold flex items-center gap-2","[&>svg]:w-[1.2em] [&_svg]:h-[1.2em] [&_svg]:opacity-70"),children:["Install Template ",o.jsx(kct,{})]}),o.jsx(Ld,{name:"template-provider",options:e,label:"Template AI Model Provider",onValueChange:n,value:t,placeholder:"Select",layout:"horizontal"}),t&&Object.entries(r||{}).length>0&&o.jsxs(o.Fragment,{children:[o.jsx("h3",{className:"text-neutral3 text-ui-md",children:"Set required Environmental Variables"}),o.jsx("div",{className:"grid grid-cols-[1fr_1fr] items-start gap-4",children:l?o.jsxs("div",{className:K("flex items-center justify-center col-span-2 text-neutral3 text-ui-sm gap-4","[&_svg]:opacity-50 [&_svg]:w-[1.1em] [&_svg]:h-[1.1em]","animate-in fade-in duration-300"),children:[o.jsx(Ut,{})," Loading variables..."]}):Object.entries(r).map(([p,h])=>o.jsxs(g.Fragment,{children:[o.jsx(Jp,{name:`env-${p}`,labelIsHidden:!0,label:"Key",value:p,disabled:!0,className:"w-full"}),o.jsx(Jp,{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(m4t,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(le,{className:K("flex items-center gap-2 mt-4 justify-center text-ui-md w-full bg-surface5 min-h-10 rounded-lg text-neutral5 hover:bg-surface6 transition-colors","[&>svg]:w-[1.1em] [&_svg]:h-[1.1em] [&_svg]:text-neutral5"),onClick:a,disabled:!t||!u||!d||s.length>0||c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(Ut,{className:"h-4 w-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(zd,{})]})})]})})}function t0s({title:e,description:t,githubUrl:n,isLoading:r,infoData:s,templateSlug:a}){const i=a?`feat/install-template-${a}`:"feat/install-template-[slug]";return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:K("grid mt-8 items-center"),children:o.jsxs("div",{className:K("text-header-lg flex items-center gap-3","[&>svg]:w-[1.2em] [&>svg]:h-[1.2em] [&>svg]:opacity-50",{"[&>svg]:opacity-20":r}),children:[o.jsx(oy,{}),o.jsx("h2",{className:K({"bg-surface4 flex rounded-lg min-w-[50%]":r}),children:r?o.jsx(o.Fragment,{children:" "}):e})]})}),o.jsxs("div",{className:"grid gap-x-24 lg:grid-cols-[1fr_1fr]",children:[o.jsxs("div",{className:"grid",children:[o.jsx("p",{className:K("mb-4 text-ui-md text-neutral4 mt-2 leading-7",{"bg-surface4 rounded-lg ":r}),children:r?o.jsx(o.Fragment,{children:" "}):t}),!r&&a&&o.jsxs("div",{className:K("bg-surface2 border border-surface4 rounded-lg p-4 mb-4","flex items-start gap-3"),children:[o.jsx("div",{className:"mt-0.5 shrink-0",children:o.jsx(Em,{className:"h-[1.1em] w-[1.1em] text-blue-500"})}),o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(_0e,{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(dG,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(dje,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function Rtt(e){switch(e){case"running":return o.jsx(Ut,{size:"sm","aria-hidden":!0});case"success":return o.jsx(qr,{"aria-hidden":!0});case"failed":return o.jsx(or,{"aria-hidden":!0});default:return null}}function n0s(){return o.jsx("svg",{viewBox:"0 0 24 24",className:"text-neutral2","aria-hidden":!0,children:o.jsx("circle",{cx:"12",cy:"12",r:"8.5",pathLength:"48",fill:"none",stroke:"currentcolor",strokeWidth:"2.8",strokeLinecap:"round",strokeDasharray:"3 3"})})}function r0s({status:e,variant:t}){return t==="plain"?o.jsx("span",{className:K("flex size-4 items-center justify-center self-center [&>svg]:size-4",Yr.colors,{"[&>svg]:text-positive1":e==="success","[&>svg]:text-negative1":e==="failed"}),children:e==="pending"?o.jsx(n0s,{}):Rtt(e)}):o.jsx("span",{className:K("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",Yr.colors,Yr.transform,Yr.shadow,{"[&>svg]:text-notice-success-fg":e==="success","[&>svg]:text-notice-destructive-fg":e==="failed","border border-dashed border-neutral2":e==="pending","[&>svg]:size-4":e!=="running","bg-accent1Dark shadow-glow-accent1":e==="success","bg-accent2Dark shadow-glow-accent2":e==="failed","scale-110":e==="success"||e==="failed"}),children:Rtt(e)})}function s0s({step:e,isActive:t,position:n,variant:r="default"}){return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none",Yr.colors,{"border border-transparent":r==="default","border-dashed border-neutral2 bg-surface3":t&&r==="default"}),children:[o.jsxs("div",{className:"grid min-w-0 grid-cols-[auto_1fr] gap-2",children:[o.jsxs("span",{className:K("flex min-w-6 justify-end text-ui-md",Yr.colors,{"text-neutral5":t||e.status==="success","text-neutral3":!t&&e.status!=="success"}),children:[n,"."]}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("h4",{className:K("text-ui-md",Yr.colors,{"text-neutral5":t||e.status==="success","text-neutral3":!t&&e.status!=="success"}),children:e.title}),e.description&&o.jsx("p",{className:K("-mt-0.5 text-ui-md text-neutral2",{truncate:r==="plain"}),children:e.description})]})]}),o.jsx(r0s,{status:e.status,variant:r})]})}function a0s({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:K(n),children:t.map((r,s)=>o.jsx(s0s,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function i0s({steps:e}){const t=e.length,n=e.filter(r=>r.status==="success").length;return o.jsxs("div",{className:"flex w-full flex-col content-center justify-center gap-4",children:[o.jsx("div",{className:"grid w-full grid-cols-[0_repeat(9,1fr)]",children:e.map((r,s)=>o.jsx("div",{className:K("relative flex h-8 items-center justify-end",Yr.colors,{"bg-accent1Dark":r.status==="success"&&e?.[s-1]?.status==="success"}),children:o.jsx("div",{className:K("absolute right-0 z-10 flex size-8 translate-x-1/2 items-center justify-center self-center rounded-full bg-surface3 text-ui-sm font-bold text-neutral3 motion-reduce:transition-none",Yr.colors,Yr.transform,Yr.shadow,{"border border-dashed border-neutral2":r.status==="pending","bg-accent1Dark text-notice-success-fg shadow-glow-accent1 scale-110":r.status==="success","bg-accent2Dark text-notice-destructive-fg shadow-glow-accent2 scale-110":r.status==="failed"}),children:r.status==="running"?o.jsx(Ut,{}):s+1})},r.id))}),o.jsxs("div",{className:K("text-center text-xs text-neutral3",Yr.colors),children:[n," of ",t," steps completed"]})]})}function o0s({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",a=t?.payload?.workflowState,i=t?.payload?.currentStep,l=t?.error,c=a?.steps||{},u=Object.keys(c).length>0,d=v=>v==="input"||v.endsWith(".input")||v.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(v)||/[0-9a-f]{8,}/.test(v)?!1:r?.allSteps?v in r.allSteps:!0,f=Object.entries(c).filter(([v,y])=>d(v)),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(([v,y])=>({id:v,status:y?.status,description:y?.description,title:v.charAt(0).toUpperCase()+v.slice(1).replace(/-/g," "),isActive:i?.id===v}));return o.jsxs(uY,{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(i0s,{steps:m})}),l&&s==="error"&&o.jsxs("div",{className:K("rounded-lg text-neutral5 p-6 flex items-center gap-3 text-ui-md bg-red-500/10","[&>svg]:w-6 [&>svg]:h-6 [&>svg]:opacity-70 [&>svg]:text-red-500"),children:[o.jsx(XXt,{}),l||"Something went wrong"]}),u&&o.jsx(a0s,{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(Ut,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function l0s({name:e,installedEntities:t}){return o.jsxs(uY,{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(kct,{}),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(dje,{data:t})]})}function c0s(){const{templateSlug:e}=fr(),[t,n]=Ma(),[r,s]=g.useState(""),[a,i]=g.useState(""),[l,c]=g.useState(""),[u,d]=g.useState({}),[f,p]=g.useState([]),[h,m]=g.useState(null),[v,y]=g.useState(!1),[b,x]=g.useState(""),[S,k]=g.useState(!1),[_,C]=g.useState(!1),[T,E]=g.useState([]),{data:N,isLoading:I}=Ynr({repoOrSlug:e,owner:"mastra-ai"}),R=Xxs?.includes("beta")??!1?"beta":"main",{data:L,isLoading:M}=Knr({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:R}),{data:F,isLoading:H}=Xnr(),{mutateAsync:z,isPending:q}=Jnr(),{mutateAsync:V}=err(),{streamInstall:D,streamResult:G,isStreaming:U}=nrr(F),{observeInstall:P,streamResult:B,isStreaming:Z}=rrr(F);g.useEffect(()=>{const ne=t.get("runId");ne&&!v&&!h&&!U&&!Z&&(console.info("🔄 Checking completed run after hot reload:",{runId:ne}),x(ne),V({runId:ne}).then(se=>{const fe=se.snapshot;if(fe?.status==="success"&&fe?.result?.success)y(!0);else if(fe?.result?.success===!1)if(fe?.result?.validationResults&&!fe?.result?.validationResults?.valid&&fe?.result?.validationResults?.remainingErrors>0){const{remainingErrors:xe,errors:pe}=fe.result.validationResults,we=`Template installation completed but ${xe} validation issue${xe>1?"s":""} remain unresolved.`;m(we),E(pe||[])}else{const xe=fe?.result?.message||fe?.result?.error||"Template installation failed";m(typeof xe=="string"?xe:String(xe))}}).catch(se=>{console.error("❌ Failed to fetch run details:",se),m("Failed to retrieve installation status after reload")}))},[t,v,h,U,Z,V]),g.useEffect(()=>{const ne=t.get("runId"),se=t.get("resume"),fe=t.get("provider");if(ne&&se==="true"&&fe&&!U&&!Z&&!S&&!_&&F){x(ne),k(!0);try{V({runId:ne}).then(ce=>{if(ce.snapshot?.status==="running")return P.mutateAsync({runId:ne})}).then(()=>{n(ce=>{const xe=new URLSearchParams(ce);return xe.delete("resume"),xe})}).catch(ce=>{console.error("❌ Failed to resume template installation:",ce),ce.message?.includes("404")||ce.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(ce){console.error("❌ Auto-resume failed with error:",ce),m("Failed to resume template installation. Please refresh and try again.")}}},[t,e,U,Z,S,_,F,V,P,n]);const Y=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],te=[{key:"tools",label:"Tools",value:N?.tools?.length?N.tools.map(ne=>ne).join(", "):"n/a",icon:o.jsx(zf,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(ne=>ne).join(", "):"n/a",icon:o.jsx(Ai,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(ne=>ne).join(", "):"n/a",icon:o.jsx(uI,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(_g,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(cI,{})}],J=[{...te[0]},{...te[1]},{...te[2]}].filter(ne=>ne.value!=="n/a");g.useEffect(()=>{L&&d(L)},[L]),g.useEffect(()=>{const ne=G||B;ne?.phase==="error"&&ne?.error&&m(typeof ne.error=="string"?ne.error:String(ne.error))},[G?.phase,G?.error,B?.phase,B?.error]);const ee=ne=>{s(ne)},re=async ne=>(i(ne.provider),c(ne.modelId),{message:"Model updated successfully"}),oe=async()=>{const ne=Object.entries(u).reduce((se,[fe,ce])=>(ce===""&&se.push(fe),se),[]);if(ne.length>0){p(ne);return}if(N){m(null),y(!1),x(""),C(!0);try{const fe={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:R,slug:N.slug,variables:u},{runId:ce}=await z({});x(ce),n(xe=>{const pe=new URLSearchParams(xe);return pe.set("runId",ce),pe.set("resume","true"),pe.set("provider",r||"openai"),pe}),await D.mutateAsync({inputData:fe,selectedModel:{provider:a,modelId:l},runId:ce})}catch(se){C(!1),m(se?.message||"Template installation failed"),console.error("Template installation failed",se)}}},X=ne=>{const{name:se,value:fe}=ne.target;fe.trim()===""?p(ce=>[...ce,se]):p(ce=>ce.filter(xe=>xe!==se)),d(ce=>({...ce,[se]:fe}))};return o.jsx(vs,{children:o.jsx("div",{className:K("w-full lg:px-12 h-full overflow-y-scroll"),children:o.jsxs("div",{className:"mx-auto grid w-full max-w-[80rem] gap-y-4 p-6",children:[o.jsx(t0s,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:te,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(U||Z)&&o.jsx(o0s,{name:N.title,streamResult:Z?B:G,runId:b,workflowInfo:F}),v&&o.jsx(l0s,{name:N.title,installedEntities:J,linkComponent:Ba}),h&&o.jsx(Jxs,{errorMsg:h,validationErrors:T.length>0?T:G?.validationResults?.errors||B?.validationResults?.errors}),!U&&!Z&&!v&&!h&&o.jsx(e0s,{providerOptions:Y,selectedProvider:r,onProviderChange:ee,variables:u,setVariables:d,errors:f,setErrors:p,handleInstallTemplate:oe,handleVariableChange:X,isLoadingEnvVars:M||H,isInstalling:q,defaultModelProvider:a,defaultModelId:l,onModelUpdate:re})]})]})})})}const u0s=()=>{const{toolId:e,agentId:t}=fr();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(Bss,{toolId:e,agentId:t})})},d0s=()=>{const{toolId:e}=fr();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(dbs,{toolId:e})})};function f0s(){const{data:e,isLoading:t,error:n}=Gy(),[r,s]=g.useState("");return n&&ps(n)?o.jsx(Zn,{children:o.jsx(Ts,{})}):n&&hs(n)?o.jsx(Zn,{children:o.jsx(Os,{resource:"workflows"})}):n?o.jsx(Zn,{children:o.jsx($a,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(Zn,{children:o.jsx(jZr,{})}):o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(od,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsxs(le,{as:Ba,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(nI,{}),"Schedules"]})]})}),o.jsx(TZr,{workflows:e||{},isLoading:t,search:r})]})}const p0s={active:"bg-accent1",paused:"bg-accent3"},h0s={active:"text-accent1",paused:"text-accent3"},yHt=({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 ${p0s[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${h0s[e]}`,children:e})]}),_j=e=>!e||e<=0?"—":new Date(e).toLocaleString(),d2=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 bHt({status:e}){const{icon:t,color:n}=m0s(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 m0s(e){switch(e){case"success":return{icon:o.jsx(qr,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(or,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(Ut,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(EV,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx($c,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(a1,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const Ptt="auto auto auto auto 1fr";function g0s(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 v0s(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 y0s=3e4,b0s=5*6e4;function x0s({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=un(),c=h=>!!(n&&h.runId&&h.outcome!=="failed"),u=e.filter(c).length,{containerRef:d,getRowProps:f}=so({count:u});let p=-1;return t?o.jsx(Fo,{columns:Ptt}):e.length===0?o.jsx(ve,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(he,{columns:Ptt,className:"min-w-0",scrollRef:d,children:[o.jsxs(he.Top,{children:[o.jsx(he.TopCell,{children:"Run"}),o.jsx(he.TopCell,{children:"Status"}),o.jsx(he.TopCell,{children:"Started"}),o.jsx(he.TopCell,{children:"Duration"}),o.jsx(he.TopCell,{children:" "})]}),e.map(h=>{const m=h.actualFireAt-h.scheduledFireAt,v=v0s(m),y=`Scheduled ${_j(h.scheduledFireAt)} — published ${_j(h.actualFireAt)} (drift ${v})`,b=h.outcome==="failed",x=b?h.error:h.run?.error,S=Math.abs(m),k=!b&&S>y0s&&S<=b0s,_=`${h.scheduleId}-${h.runId}-${h.actualFireAt}`,C=c(h);C&&(p+=1);const T=o.jsx("span",{className:C?"text-accent1 text-ui-sm font-mono whitespace-nowrap":"text-neutral3 text-ui-sm font-mono whitespace-nowrap",children:h.runId}),E=o.jsxs(o.Fragment,{children:[o.jsx(he.Cell,{children:T}),o.jsx(he.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[b?o.jsxs("span",{className:"text-ui-sm text-accent2 inline-flex items-center gap-1.5 whitespace-nowrap",children:[o.jsx(uc,{size:14}),"publish failed"]}):h.run?o.jsx(bHt,{status:h.run.status}):o.jsx("span",{className:"text-ui-sm text-neutral3 inline-flex items-center gap-1.5 whitespace-nowrap",children:"pending"}),x?o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(uc,{size:14})})}),o.jsx(yn,{children:x})]}):null]})}),o.jsx(he.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:y,children:d2(h.actualFireAt)}),k?o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(uc,{size:14})})}),o.jsxs(yn,{children:["Published ",v," after the scheduled fire time"]})]}):null]})}),o.jsx(he.Cell,{children:h.run?o.jsx("span",{children:g0s(h.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(he.Cell,{children:" "})]});return C?o.jsx(he.RowLink,{to:l.workflowRunLink(n,h.runId),LinkComponent:i,...f(p),children:E},_):o.jsx(he.RowStatic,{children:E},_)}),o.jsx(he.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const w0s=e=>{const t=Ge();return mt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},$tt=25,S0s=e=>{const t=Ge(),{inView:n,setRef:r}=t0(),s=Py({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:$tt,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<$tt))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 g.useEffect(()=>{n&&i&&!l&&c()},[n,i,l,c]),{...s,data:a,setEndOfListElement:r}},k0s=e=>{const t=Ge(),n=Ir();return Sn({mutationFn:async r=>{if(!e)throw new Error("scheduleId is required");return r==="pause"?t.pauseSchedule(e):t.resumeSchedule(e)},onSuccess:(r,s)=>{n.invalidateQueries({queryKey:["schedule",e]}),n.invalidateQueries({queryKey:["schedules"]}),ze.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{ze.error(r.message)}})};function h8({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ve,{variant:"ui-xs",className:"text-neutral4 tracking-wide uppercase",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function O0s(){const{scheduleId:e}=fr(),{paths:t}=un(),{data:n,error:r}=w0s(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=S0s(e),d=k0s(e);if(r&&ps(r))return o.jsx(Zn,{children:o.jsx(Ts,{})});if(r&&hs(r))return o.jsx(Zn,{children:o.jsx(Os,{resource:"schedules"})});if(r)return o.jsx(Zn,{children:o.jsx($a,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,p=n?.agentId;return o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx(Lt.Row,{className:"justify-end",children:o.jsxs(Lt.Column,{className:"flex justify-end gap-2",children:[o.jsxs(le,{as:Ba,to:t.schedulesLink(),variant:"ghost",children:[o.jsx(bl,{}),"Back to schedules"]}),f?o.jsx(le,{as:Ba,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(le,{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(MV,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(Mc,{}),"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(h8,{label:p?"Agent":"Workflow",children:f?o.jsx(Ba,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):p?o.jsx(Ba,{to:t.agentLink(p),className:"text-accent1 hover:underline",children:p}):"—"}),o.jsxs(h8,{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(h8,{label:"Status",children:o.jsx(yHt,{status:n.status})}),o.jsx(h8,{label:"Next fire",children:o.jsx("span",{title:_j(n.nextFireAt),children:d2(n.nextFireAt)})})]}),o.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[o.jsx(ve,{variant:"ui-md",className:"mb-3",children:"Trigger history"}),i?o.jsx($a,{title:"Failed to load trigger history",message:i.message}):o.jsx(x0s,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const Mtt="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function _0s({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=un(),a=g.useMemo(()=>{const c=n.toLowerCase();return c?e.filter(u=>u.id.toLowerCase().includes(c)||(u.workflowId??u.agentId??"").toLowerCase().includes(c)):e},[e,n]),{containerRef:i,getRowProps:l}=so({count:a.length});return t?o.jsx(Fo,{columns:Mtt}):o.jsxs(he,{columns:Mtt,className:"min-w-0",scrollRef:i,children:[o.jsxs(he.Top,{children:[o.jsx(he.TopCell,{children:"Target"}),o.jsx(he.TopCell,{children:"Schedule ID"}),o.jsx(he.TopCell,{children:"Cron"}),o.jsx(he.TopCell,{children:"Status"}),o.jsx(he.TopCell,{children:"Next fire"}),o.jsx(he.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(he.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(he.NoMatch,{message:"No schedules configured"}):null,a.map((c,u)=>o.jsxs(he.RowLink,{to:r.scheduleLink(c.id),LinkComponent:s,...l(u),children:[o.jsx(he.NameCell,{children:c.workflowId??c.agentId}),o.jsx(he.Cell,{className:"min-w-0",children:o.jsx("span",{className:"text-ui-smd text-neutral3 block truncate font-mono",title:c.id,children:c.id})}),o.jsx(he.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("code",{className:"text-ui-sm font-mono",children:c.cron}),c.timezone?o.jsx("span",{className:"text-neutral4 text-ui-xs",children:c.timezone}):null]})}),o.jsx(he.Cell,{children:o.jsx(yHt,{status:c.status})}),o.jsx(he.Cell,{children:o.jsx("span",{className:"whitespace-nowrap",title:_j(c.nextFireAt),children:d2(c.nextFireAt)})}),o.jsx(he.Cell,{children:c.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(bHt,{status:c.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:_j(c.lastFireAt),children:c.lastFireAt?d2(c.lastFireAt):""})]}):c.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:_j(c.lastFireAt),children:d2(c.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},c.id))]})}function C0s({workflowId:e}={}){const{data:t,isLoading:n,error:r}=SSe(e?{workflowId:e}:{}),[s,a]=g.useState("");return r?o.jsx($a,{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(od,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(_0s,{schedules:t??[],isLoading:n,search:s})})]})}function E0s(){const[e]=Ma(),t=e.get("workflowId")??void 0,{error:n}=SSe(t?{workflowId:t}:{});return n&&ps(n)?o.jsx(Zn,{children:o.jsx(Ts,{})}):n&&hs(n)?o.jsx(Zn,{children:o.jsx(Os,{resource:"schedules"})}):o.jsx(Lt,{children:o.jsx("div",{className:"h-full",children:o.jsx(C0s,{workflowId:t})})})}function T0s({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=ZOe({stepGraph:e}),[a,i]=g.useState(!1),[l,c,u]=tCt(r),[d]=nCt(s),{edgeTypes:f,nodeTypes:p,styledEdges:h}=d5t({edges:d,workflowName:n,stepGraph:e});return g.useEffect(()=>{if(t){const m=setTimeout(()=>{i(!0)},500);return()=>clearTimeout(m)}},[t]),o.jsx("div",{className:"bg-surface1 relative h-full w-full",children:a?o.jsxs(eCt,{nodes:l,edges:h,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:p,onNodesChange:u,children:[o.jsx($je,{position:"bottom-left"}),o.jsx(sCt,{variant:dy.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:o.jsx(Ut,{})})})}function j0s(){const{stepDetail:e,closeStepDetail:t}=MW();return e?o.jsxs("div",{className:"flex h-full flex-col","data-testid":"workflow-step-detail-panel",children:[o.jsxs("div",{className:"border-border1 bg-surface1 flex items-center justify-between border-b px-4 py-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[e.type==="map-config"&&o.jsx(i1,{className:"h-4 w-4",style:{color:zu.map}}),e.type==="nested-graph"&&o.jsx(Bc,{className:"h-4 w-4",style:{color:zu.workflow}}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx(ve,{variant:"ui-md",className:"text-neutral6 font-medium",children:e.type==="map-config"?`${e.stepName} Config`:`${e.stepName} Workflow`}),e.type==="map-config"&&e.stepId&&e.stepId!==e.stepName&&o.jsx(ve,{variant:"ui-xs",className:"text-neutral3",children:e.stepId})]})]}),o.jsx("button",{onClick:t,className:"hover:bg-surface3 rounded p-1 transition-colors","aria-label":"Close",children:o.jsx(or,{className:"text-neutral3 h-4 w-4"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(o2,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(WOe,{children:o.jsx(T0s,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function N0s(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function I0s(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 A0s({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:o.jsxs("div",{className:"border-border1 bg-surface4 space-y-5 rounded-lg border p-5","data-testid":"workflow-suspended-steps",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs(ve,{as:"p",variant:"ui-md",className:"text-neutral6 flex items-center gap-2 font-semibold",children:[o.jsx(We,{children:o.jsx(EV,{})}),"Step suspended"]}),o.jsx(xt,{variant:"yellow",children:"Needs input"})]}),e.map((s,a)=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const l=i?.resumeSchema?wm(Tx(i.resumeSchema)):mf(cr(),_f());return o.jsx(R0s,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function R0s({step:e,stepSchema:t,description:n,isStreaming:r,onResume:s}){const[a,i]=g.useState(!1);return o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(ve,{as:"p",variant:"ui-md",className:"text-neutral6 truncate font-medium",children:e.stepId}),n&&o.jsx(ve,{as:"p",variant:"ui-sm",className:"text-neutral3",children:n})]}),e.suspendPayload&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs(ve,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(We,{children:o.jsx(UXt,{})}),"The step is asking"]}),o.jsxs(Lc,{open:a,onOpenChange:i,children:[o.jsxs(fc,{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(We,{children:o.jsx(Br,{className:K("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(ve,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:I0s(e.suspendPayload,e.stepId)})]}),o.jsx(ve,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:N0s(e.suspendPayload)})]}),o.jsx(pc,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Qr,{data:e.suspendPayload,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs(ve,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(We,{children:o.jsx(HXt,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(hU,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(Mc,{}),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 P0s(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext(Zl),{runId:a}=fr(),i=dCt(e,r??""),l=cer(),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(A0s,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const $0s=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"})]}),M0s=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"})]}),D0s=e=>e.includes("."),L0s=e=>e==="input"||e.endsWith(".input"),F0s=1;function z0s(e){return`${Number((e/1e3).toPrecision(3))}s`}function B0s(e,t){const n=Object.entries(e).filter(([i])=>!L0s(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,F0s);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:p,durationMs:d,isRunning:c,isNestedEntry:D0s(i)}})}const U0s=({status:e})=>o.jsxs(We,{children:[e==="success"&&o.jsx($0s,{className:"text-accent1"}),e==="failed"&&o.jsx(M0s,{className:"text-accent2"}),e==="suspended"&&o.jsx(EV,{className:"text-accent3"}),e==="waiting"&&o.jsx(Ype,{className:"text-accent5"}),e==="skipped"&&o.jsx(Ype,{className:"text-icon3"}),e==="running"&&o.jsx(Vs,{className:"text-accent6 animate-spin"})]}),q0s={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function xHt(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const Dtt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},V0s=e=>{const t=e;return n5t({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},H0s=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=V0s(e.step),u=e.status==="running",d=!e.isNestedEntry;return o.jsxs("div",{role:"button",tabIndex:0,"data-testid":"workflow-timeline-row","data-workflow-step-key":e.stepId,"data-workflow-step-active":n?"true":void 0,"data-workflow-step-hovered":r?"true":void 0,"data-workflow-step-nested":e.isNestedEntry?"true":void 0,"aria-pressed":n,"aria-disabled":!d,onMouseEnter:()=>{d&&a(e.stepId)},onMouseLeave:()=>{d&&a(null)},onClick:()=>{d&&s(e.stepId)},onKeyDown:f=>{!d||f.key!=="Enter"&&f.key!==" "||(f.preventDefault(),s(e.stepId))},className:K("grid grid-cols-[auto_auto_auto_minmax(0,10rem)_minmax(0,1fr)_auto_5rem] items-center gap-2 rounded-md border border-transparent px-2 py-1 text-left transition-colors focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-accent1",d&&"cursor-pointer",d&&"hover:bg-surface4",d&&r&&!n&&"border-neutral6 bg-surface4",d&&n&&"border-accent1",e.isNestedEntry&&"cursor-default opacity-55"),children:[o.jsx("div",{className:"flex justify-center",children:o.jsx(U0s,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(le,{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(sen,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(Jq,{indicators:c,className:"shrink-0"})}),o.jsx(ve,{as:"span",variant:"ui-sm",className:"text-neutral6 block max-w-full min-w-0 justify-self-stretch overflow-hidden text-left text-ellipsis whitespace-nowrap",children:xHt(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 ${q0s[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(le,{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(nen,{})})}),o.jsx(ve,{as:"span",variant:"ui-sm",className:"text-neutral3 w-20 justify-self-end text-right tabular-nums",children:z0s(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function W0s(){const{steps:e}=lL(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=WH(),[a,i]=g.useState(()=>Date.now()),[l,c]=g.useState(!1),[u,d]=g.useState(null),f=g.useRef(null);Ubt(f,{enabled:!l});const p=B0s(e,a),h=p.some(m=>m.isRunning);return g.useEffect(()=>{if(!h)return;const m=setInterval(()=>i(Date.now()),100);return()=>clearInterval(m)},[h]),g.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(ve,{as:"p",variant:"ui-md",className:"text-neutral3",children:"Timeline"}),o.jsx("button",{type:"button","aria-label":l?"Expand timeline":"Collapse timeline","aria-expanded":!l,onClick:()=>c(m=>!m),className:"text-neutral3 hover:bg-surface4 hover:text-neutral6 rounded-md p-1 transition-colors",children:o.jsx(Xs,{className:K("h-4 w-4 transition-transform",l&&"-rotate-90")})})]}),!l&&o.jsx("div",{ref:f,"data-testid":"workflow-timeline-list",className:"flex min-h-0 flex-col gap-2 overflow-y-auto",children:p.map((m,v)=>o.jsx(H0s,{row:m,index:v,isSelected:t===m.stepId,isHovered:n===m.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:y=>d({type:"input",stepId:y.stepId,data:Dtt(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:Dtt(y.step.output)})},`timeline-item-${m.stepId}-${v}`))})]})}),o.jsx(hr,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(pCt,{data:u.data,title:`${xHt(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const Z0s=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=MW();return o.jsxs("div",{className:"flex h-full min-h-0",children:[o.jsx("div",{className:"flex h-full min-h-0 flex-1 flex-col",children:o.jsxs("div",{className:"relative min-h-0 flex-1 p-2 pb-0",children:[o.jsx(y5t,{workflowId:e,workflow:t,isLoading:n}),o.jsx(P0s,{}),o.jsx(W0s,{})]})}),r&&o.jsx("div",{className:"border-border1 min-h-0 w-[420px] overflow-hidden border-l",children:o.jsx(j0s,{})})]})},Ltt=()=>{const{workflowId:e}=fr(),{data:t,isLoading:n,error:r}=h4(e);return r&&ps(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{})}):r&&hs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Os,{resource:"workflows"})}):o.jsx(d_e,{children:o.jsx(Z0s,{workflowId:e,workflow:t??void 0,isLoading:n})})};function G0s(e,t){if(e==null)return{};var n,r,s=vkt(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 d0e(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 Q0s(e){if(Array.isArray(e))return d0e(e)}function Y0s(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function K0s(e,t){if(e){if(typeof e=="string")return d0e(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)?d0e(e,t):void 0}}function X0s(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
645
|
+
]`})]})]})}function jms({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(We,{children:o.jsx(uc,{className:"h-4 w-4"})}),o.jsxs("span",{className:"text-sm font-medium",children:[e.length," validation error",e.length!==1?"s":""]})]}),o.jsx("ul",{className:"text-accent2/80 space-y-1 text-sm",children:n.map((s,a)=>o.jsxs("li",{className:"flex gap-2",children:[o.jsx("span",{className:"shrink-0",children:"•"}),o.jsx("span",{children:s.message})]},a))}),r>0&&o.jsxs("div",{className:"text-accent2/60 mt-2 text-xs",children:["+",r," more error",r!==1?"s":""]})]})}function Nms({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=g.useState("upload"),[i,l]=g.useState(null),[c,u]=g.useState({current:0,total:0}),[d,f]=g.useState(null),[p,h]=g.useState(!1),{parseFile:m,isParsing:v,error:y}=_hs(),{batchInsertItems:b}=bi(),x=g.useCallback(async I=>{try{const A=await m(I);l(A),a("preview")}catch{}},[m]),S=g.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=g.useCallback(()=>{n(!1),r?.(),d&&d.success>0&&ze.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]),_=g.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,T=()=>{switch(s){case"upload":return o.jsx(Tms,{onFileSelect:x,isParsing:v,error:y?.message});case"preview":return i?o.jsx("div",{className:"flex flex-col gap-4",children:i.errors.length>0?o.jsxs(o.Fragment,{children:[o.jsx(jms,{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(Ems,{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(Ut,{}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-neutral1 text-lg font-medium",children:"Importing items..."}),o.jsxs("div",{className:"text-neutral4 mt-1 text-sm",children:[c.current," of ",c.total]})]})]});case"complete":return o.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[o.jsx("div",{className:"text-4xl",children:d&&d.errors===0?"✓":"⚠"}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-neutral1 text-lg font-medium",children:"Import Complete"}),o.jsxs("div",{className:"text-neutral4 mt-1 text-sm",children:[d?.success??0," item",d?.success!==1?"s":""," imported",d&&d.errors>0&&o.jsxs("span",{className:"text-accent2",children:[" ","(",d.errors," error",d.errors!==1?"s":"",")"]})]})]})]})}},E=()=>{switch(s){case"upload":return o.jsx(le,{onClick:_,children:"Cancel"});case"preview":return o.jsxs(o.Fragment,{children:[o.jsx(le,{onClick:()=>a("upload"),children:"Back"}),o.jsxs(le,{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(le,{variant:"primary",onClick:k,children:"Done"})}},N={upload:"Import JSON",preview:"Preview Data",importing:"Importing",complete:"Import Complete"};return o.jsx(hr,{open:t,onOpenChange:_,children:o.jsxs(mr,{className:"max-h-[90vh] max-w-2xl",children:[o.jsxs(gr,{children:[o.jsx(ur,{children:N[s]}),o.jsx(Cs,{children:"Import dataset items from a JSON file."})]}),o.jsx(jr,{className:"max-h-[50vh] min-h-[200px] overflow-y-auto",children:T()}),o.jsx(Ul,{className:"flex justify-end gap-2 px-6 pt-4",children:E()})]})})}function Ims(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"?!0:!!e.closest('[role="dialog"]:not([data-item-panel])')}function FVt({active:e,onPrevious:t,onNext:n,onClose:r}){g.useEffect(()=>{if(!e)return;const s=a=>{a.defaultPrevented||Ims(a.target)||(a.key==="PageUp"?(a.preventDefault(),t?.()):a.key==="PageDown"?(a.preventDefault(),n?.()):a.key==="Escape"&&(a.preventDefault(),r()))};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,t,n,r])}const zVt=g.createContext(null);function Ams({datasetId:e,items:t,isLoadingItems:n,children:r}){const s=Vr(),i=Vgt("/datasets/:datasetId/items/:itemId")?.params.itemId,l=g.useCallback(h=>{s(`/datasets/${e}/items/${encodeURIComponent(h)}`)},[s,e]),c=g.useCallback(()=>{s(`/datasets/${e}`)},[s,e]),u=g.useMemo(()=>i?t.findIndex(h=>h.id===i):-1,[t,i]),d=g.useMemo(()=>{if(u<=0)return;const h=t[u-1].id;return()=>l(h)},[u,t,l]),f=g.useMemo(()=>{if(u<0||u>=t.length-1)return;const h=t[u+1].id;return()=>l(h)},[u,t,l]);FVt({active:!!i,onPrevious:d,onNext:f,onClose:c});const p=g.useMemo(()=>({datasetId:e,items:t,isLoadingItems:n,currentItemId:i,openItem:l,close:c,goToPreviousItem:d,goToNextItem:f}),[e,t,n,i,l,c,d,f]);return o.jsx(zVt.Provider,{value:p,children:r})}function BVt(){const e=g.useContext(zVt);if(!e)throw new Error("useDatasetItemPanel must be used within a DatasetItemPanelProvider");return e}function Rms({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,leftSlot:r,rightSlot:s}){const[a,i]=Ma(),{activeVersion:l}=cRe(a,i),[c,u]=g.useState(!1),[d,f]=g.useState(!1),[p,h]=g.useState(!1),[m,v]=g.useState([]),[y,b]=g.useState(!1),[x,S]=g.useState([]),[k,_]=g.useState(!1),[C,T]=g.useState([]),[E,N]=g.useState(0),[I,A]=g.useState(""),[R]=YH(I,300),{data:L}=My(e),{data:M=[],isLoading:F,setEndOfListElement:H,isFetchingNextPage:z,hasNextPage:q}=W1(e,R||void 0,l),{deleteItems:V}=bi(),{currentItemId:D,openItem:G,close:U}=BVt(),P=oe=>{D===oe?U():G(oe)},B=oe=>{v(oe),h(!0)},Z=oe=>{S(oe),b(!0)},Y=oe=>{b(oe),oe||(S([]),N(X=>X+1))},te=oe=>{T(oe),_(!0)},J=async()=>{await V.mutateAsync({datasetId:e,itemIds:C}),ze.success(`Deleted ${C.length} items`),_(!1),T([]),N(oe=>oe+1)},ee=oe=>{h(!1),v([]),N(X=>X+1),n?.(oe)},re=oe=>{h(oe),oe||(v([]),N(X=>X+1))};return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"grid h-full overflow-auto",children:o.jsx(Cms,{items:M,leftSlot:r,rightSlot:s,isLoading:F,onItemClick:P,featuredItemId:D,onAddClick:t??(()=>{}),onImportClick:()=>u(!0),onImportJsonClick:()=>f(!0),onBulkDeleteClick:te,onCreateDatasetClick:B,onAddToDatasetClick:Z,datasetName:L?.name,clearSelectionTrigger:E,setEndOfListElement:H,isFetchingNextPage:z,hasNextPage:q,searchQuery:I,activeSearchQuery:R,onSearchChange:A,currentDatasetVersion:L?.version})}),o.jsx(wms,{datasetId:e,open:c,onOpenChange:u}),o.jsx(Nms,{datasetId:e,open:d,onOpenChange:f}),o.jsx(tms,{open:p,onOpenChange:re,items:m,onSuccess:ee}),o.jsx(nms,{open:y,onOpenChange:Y,items:x,currentDatasetId:e}),o.jsx(Mt,{open:k,onOpenChange:_,children:o.jsxs(Mt.Content,{children:[o.jsxs(Mt.Header,{children:[o.jsx(Mt.Title,{children:"Delete Items"}),o.jsxs(Mt.Description,{children:["Are you sure you want to delete ",C.length," item",C.length!==1?"s":"","? This action cannot be undone."]})]}),o.jsxs(Mt.Footer,{children:[o.jsx(Mt.Cancel,{children:"Cancel"}),o.jsx(Mt.Action,{onClick:J,children:V.isPending?"Deleting...":"Delete"})]})]})})]})}function UVt({selectedScorers:e,setSelectedScorers:t,disabled:n=!1,container:r,label:s="Scorers (Optional)",helperText:a}){const{data:i,isLoading:l}=uh(),c=Object.entries(i??{}).filter(([,u])=>u.isRegistered).map(([u,d])=>({value:u,label:d.scorer?.config?.name||u,description:d.scorer?.config?.description||""}));return o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Pt,{children:s}),a?o.jsx("p",{className:"text-muted-foreground text-xs",children:a}):null,o.jsx(yl,{multiple:!0,options:c,value:e,onValueChange:t,placeholder:"Select scorers...",searchPlaceholder:"Search scorers...",emptyText:"No scorers available",disabled:n||l,container:r})]})}function qVt({overrideEnabled:e,onOverrideEnabledChange:t,selectedScorerIds:n,onSelectedScorerIdsChange:r,disabled:s=!1}){return o.jsxs("div",{className:"grid gap-3",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(Bl,{id:"override-dataset-scorers",checked:e,onCheckedChange:t,disabled:s}),o.jsx(Pt,{htmlFor:"override-dataset-scorers",children:"Override dataset scorers"})]}),o.jsx("p",{className:"text-muted-foreground text-xs",children:e?"Only selected scorers run for this item. Leave empty to run no scorers.":"Use scorers attached to the dataset."}),e?o.jsx(UVt,{selectedScorers:n,setSelectedScorers:r,disabled:s,label:"Item scorers",helperText:"Choose from scorers that can be resolved by this Mastra instance."}):null]})}function Pms(e){if(!(e instanceof Error))return null;const t=e.message.match(/- ({.*})$/);if(!t)return null;try{const n=JSON.parse(t[1]);if(n.field&&Array.isArray(n.errors))return{field:n.field,errors:n.errors}}catch{}return null}function qie({field:e,errors:t}){return t.length?o.jsx("div",{className:"mt-2 space-y-1",children:t.map((n,r)=>o.jsxs("p",{className:"text-destructive text-xs",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function $ms({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=g.useState("{}"),[i,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState(""),[p,h]=g.useState(!1),[m,v]=g.useState([]),[y,b]=g.useState(""),[x,S]=g.useState(null),{addItem:k}=bi(),_=()=>{a("{}"),l(""),u(""),f(""),h(!1),v([]),b(""),S(null)},C=R=>{_(),n(R)},T=async R=>{R.preventDefault();let L;try{L=JSON.parse(s)}catch{ze.error("Input must be valid JSON");return}let M;if(i.trim())try{M=JSON.parse(i)}catch{ze.error("Ground Truth must be valid JSON");return}let F;if(c.trim())try{F=JSON.parse(c)}catch{ze.error("Expected Trajectory must be valid JSON");return}let H;if(d.trim())try{const q=JSON.parse(d);if(!Array.isArray(q)){ze.error("Tool Mocks must be a JSON array");return}H=q}catch{ze.error("Tool Mocks must be valid JSON");return}let z;if(y.trim())try{z=JSON.parse(y)}catch{ze.error("Request Context must be valid JSON");return}try{await k.mutateAsync({datasetId:e,input:L,groundTruth:M,expectedTrajectory:F,toolMocks:H,scorerIds:p?m:void 0,requestContext:z}),ze.success("Item added successfully"),C(!1),r?.()}catch(q){const V=Pms(q);V?S(V):ze.error(`Failed to add item: ${q instanceof Error?q.message:"Unknown error"}`)}},E=R=>{a(R),x?.field==="input"&&S(null)},N=R=>{l(R),x?.field==="groundTruth"&&S(null)},I=R=>{f(R),x?.field==="toolMocks"&&S(null)},A=()=>{C(!1)};return o.jsxs(Sa,{dialogTitle:"Add Item",dialogDescription:"Create a new dataset item",isOpen:t,onClose:A,level:1,children:[o.jsx(Sa.Top,{children:"Add Item"}),o.jsxs(Sa.Content,{children:[o.jsx(Sa.Header,{children:o.jsx(Sa.Heading,{children:"Add Item"})}),o.jsxs("form",{onSubmit:T,className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Pt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Qr,{value:s,onChange:E,showCopyButton:!1,className:"min-h-[240px]"}),x?.field==="input"&&o.jsx(qie,{field:"input",errors:x.errors})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Pt,{htmlFor:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),o.jsx(Qr,{value:i,onChange:N,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="groundTruth"&&o.jsx(qie,{field:"groundTruth",errors:x.errors})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Pt,{htmlFor:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),o.jsx(Qr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[200px]"})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Pt,{htmlFor:"item-tool-mocks",children:"Tool Mocks (JSON array, optional)"}),o.jsx(Qr,{value:d,onChange:I,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="toolMocks"&&o.jsx(qie,{field:"toolMocks",errors:x.errors})]}),o.jsx(qVt,{overrideEnabled:p,onOverrideEnabledChange:h,selectedScorerIds:m,onSelectedScorerIdsChange:v,disabled:k.isPending}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Pt,{htmlFor:"item-request-context",children:"Request Context (JSON, optional)"}),o.jsx(Qr,{value:y,onChange:b,showCopyButton:!1,className:"min-h-[200px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(le,{type:"button",onClick:A,children:"Cancel"}),o.jsx(le,{type:"submit",variant:"primary",disabled:k.isPending,children:k.isPending?"Adding...":"Add Item"})]})]})]})]})}function Mms({item:e}){return o.jsx(Aa,{withMargins:!1,children:o.jsxs(Aa.Column,{children:[o.jsxs(Aa.Title,{size:"smaller",children:[o.jsx(NV,{}),o.jsx("span",{className:"truncate",children:e.id}),o.jsx(ka,{content:e.id,tooltip:`Copy item ID: ${e.id}`})]}),o.jsxs(Aa.Description,{children:[o.jsxs(Pl,{children:[o.jsx(MQt,{})," Created ",dr(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")]}),e.datasetVersion!=null&&o.jsxs(Pl,{children:[o.jsx(lI,{})," Version v",e.datasetVersion]})]})]})})}function uRe({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(X7r,{children:[o.jsx(Sa.CodeSection,{title:"Input",icon:o.jsx(wx,{}),codeStr:t}),o.jsx(Sa.CodeSection,{title:"Ground Truth",icon:o.jsx(rm,{}),codeStr:n}),s&&o.jsx(Sa.CodeSection,{title:"Expected Trajectory",icon:o.jsx(I0e,{}),codeStr:s}),o.jsx(Sa.CodeSection,{title:"Scorers",icon:o.jsx(PV,{}),codeStr:e.scorerIds===void 0?"Inherited from dataset":JSON.stringify(e.scorerIds,null,2)}),o.jsx(Sa.CodeSection,{title:"Metadata",icon:o.jsx(cI,{}),codeStr:r})]})}function Vie({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 Dms({inputValue:e,setInputValue:t,groundTruthValue:n,setGroundTruthValue:r,metadataValue:s,setMetadataValue:a,trajectoryValue:i,setTrajectoryValue:l,toolMocksValue:c,setToolMocksValue:u,scorerOverrideEnabled:d,setScorerOverrideEnabled:f,selectedScorerIds:p,setSelectedScorerIds:h,requestContextValue:m,setRequestContextValue:v,validationErrors:y,onSave:b,onCancel:x,isSaving:S}){return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"mb-4",children:o.jsxs("h3",{className:"flex items-center gap-2 text-lg font-medium",children:[o.jsx(Qp,{className:"h-5 w-5"})," Edit Item"]})}),o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Pt,{children:"Input (JSON) *"}),o.jsx(Qr,{value:e,onChange:t,showCopyButton:!1,className:"min-h-[120px]"}),y?.field==="input"&&o.jsx(Vie,{field:"input",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Pt,{children:"Ground Truth (JSON, optional)"}),o.jsx(Qr,{value:n,onChange:r,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="groundTruth"&&o.jsx(Vie,{field:"groundTruth",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Pt,{children:"Expected Trajectory (JSON, optional)"}),o.jsx(Qr,{value:i,onChange:l,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Pt,{children:"Tool Mocks (JSON array, optional)"}),o.jsxs("p",{className:"text-muted-foreground text-xs",children:["Ordered static mocks served in place of executing the tool. Each entry is"," ",o.jsx("code",{children:'{ "toolName", "args", "output" }'}),". Calling a mocked tool with non-matching args fails the item; unmocked tools run live."]}),o.jsx(Qr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="toolMocks"&&o.jsx(Vie,{field:"toolMocks",errors:y.errors})]}),o.jsx(qVt,{overrideEnabled:d,onOverrideEnabledChange:f,selectedScorerIds:p,onSelectedScorerIdsChange:h,disabled:S}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Pt,{children:"Request Context (JSON, optional)"}),o.jsx(Qr,{value:m,onChange:v,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Pt,{children:"Metadata (JSON, optional)"}),o.jsx(Qr,{value:s,onChange:a,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex gap-2 pt-4",children:[o.jsx(le,{variant:"primary",onClick:b,disabled:S,children:S?"Saving...":"Save Changes"}),o.jsx(le,{onClick:x,disabled:S,children:"Cancel"})]})]})]})}const Lms=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function Fms({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:a,isLoading:i}=zm(),{data:l,isLoading:c}=Gy(),{data:u,isLoading:d}=uh(),f=e==="agent"?Object.entries(a??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="workflow"?Object.entries(l??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="scorer"?Object.entries(u??{}).map(([v,y])=>({value:v,label:y.scorer?.config?.name??v})):[],p=e==="agent"&&i||e==="workflow"&&c||e==="scorer"&&d,h=v=>{t(v),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(Pt,{children:"Target Type"}),o.jsx(yl,{options:Lms,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(Pt,{children:m}),o.jsx(yl,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:p,container:s})]})]})}function zms({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return wm(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(Pt,{children:"Request Context"}),o.jsx(K3,{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 sY({initialDatasetId:e,initialDatasetVersion:t,initialScorerIds:n,initialTargetType:r,initialTargetId:s,initialName:a,initialDescription:i,open:l,onOpenChange:c,onSuccess:u}){const d=g.useRef(null),[f,p]=g.useState(a??""),[h,m]=g.useState(i??""),[v,y]=g.useState(e??""),[b,x]=g.useState(t??null),[S,k]=g.useState(r??""),[_,C]=g.useState(s??""),[T,E]=g.useState(n??[]),[N,I]=g.useState({}),[A,R]=g.useState(""),{triggerExperiment:L}=bi(),{data:M}=My(v),F=M?.requestContextSchema,H=!!(F&&Object.keys(F).length>0),z=!!(v&&S&&_&&f.trim()),q=L.isPending,V=B=>{y(B),x(null),I({})},D=()=>{p(a??""),m(i??""),y(e??""),x(t??null),k(r??""),C(s??""),E(n??[]),I({}),R("")},G=()=>{if(H){const B=Object.entries(N).filter(([,Z])=>Z!==void 0&&Z!=="");return B.length>0?Object.fromEntries(B):void 0}if(A.trim()){let B;try{B=JSON.parse(A)}catch{throw new Error("Request Context must be valid JSON")}if(!B||typeof B!="object"||Array.isArray(B))throw new Error("Request Context must be a JSON object");return B}},U=async()=>{if(!v||!S||!_||!f.trim())return;let B;try{B=G()}catch(Z){const Y=Z instanceof Error?Z.message:"Request Context must be valid JSON";gu.error(Y);return}try{const Z=await L.mutateAsync({datasetId:v,name:f.trim(),description:h.trim()||void 0,targetType:S,targetId:_,scorerIds:T.length>0?T:void 0,version:b??void 0,requestContext:B});gu.success("Experiment triggered successfully"),c(!1),u?.(Z.experimentId),D()}catch(Z){const Y=Z instanceof Error?Z.message:"Failed to trigger experiment";gu.error(Y)}},P=()=>{q||(c(!1),D())};return o.jsx(hr,{open:l,onOpenChange:P,children:o.jsxs(mr,{ref:d,children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Run Experiment"}),o.jsx(Cs,{children:b!=null?`Execute items from version v${b} of the dataset against a target.`:"Execute dataset items against a target."})]}),o.jsxs(jr,{className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Pt,{htmlFor:"experiment-name",children:"Name *"}),o.jsx(Cn,{id:"experiment-name",value:f,onChange:B=>p(B.target.value),placeholder:"Enter experiment name",autoFocus:!0,disabled:q})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Pt,{htmlFor:"experiment-description",children:"Description"}),o.jsx(Cn,{id:"experiment-description",value:h,onChange:B=>m(B.target.value),placeholder:"Enter experiment description (optional)",disabled:q})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Pt,{children:"Dataset"}),o.jsx(lms,{value:v,onValueChange:V,container:d})]}),v&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Pt,{children:"Version"}),o.jsx(DVt,{datasetId:v,value:b,onValueChange:x,container:d})]})]}),o.jsx(Fms,{targetType:S,setTargetType:k,targetId:_,setTargetId:C,container:d}),o.jsx(UVt,{selectedScorers:T,setSelectedScorers:E,disabled:q,container:d}),H?o.jsx(zms,{requestContextSchema:F,onChange:I}):o.jsxs("div",{className:"space-y-2",children:[o.jsx(Pt,{children:"Request Context (JSON, optional)"}),o.jsx(Qr,{value:A,onChange:R,showCopyButton:!1,className:"min-h-[80px]"})]})]}),o.jsxs(Ul,{className:"px-6 pt-4",children:[o.jsx(le,{onClick:P,disabled:q,children:"Cancel"}),o.jsx(le,{variant:"primary",onClick:U,disabled:!z||q,children:q?o.jsxs(o.Fragment,{children:[o.jsx(Ut,{className:"h-4 w-4"}),"Running..."]}):"Run"})]})]})})}const VVt=g.createContext(null);function Bms({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:a,children:i}){const l=Vr(),u=Vgt("/experiments/:experimentId/items/:itemId")?.params.itemId,d=g.useCallback(b=>{l(`/experiments/${e}/items/${encodeURIComponent(b)}`)},[l,e]),f=g.useCallback(()=>{l(`/experiments/${e}`)},[l,e]),p=g.useCallback(b=>{l(pTe(e,b))},[l,e]),h=g.useMemo(()=>u?r.findIndex(b=>b.itemId===u):-1,[r,u]),m=g.useMemo(()=>{if(h<=0)return;const b=r[h-1].itemId;return()=>d(b)},[h,r,d]),v=g.useMemo(()=>{if(h<0||h>=r.length-1)return;const b=r[h+1].itemId;return()=>d(b)},[h,r,d]);FVt({active:!!u,onPrevious:m,onNext:v,onClose:f});const y=g.useMemo(()=>({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:a,currentItemId:u,openItem:d,close:f,openInReview:p,goToPreviousItem:m,goToNextItem:v}),[e,t,n,r,s,a,u,d,f,p,m,v]);return o.jsx(VVt.Provider,{value:y,children:i})}function HVt(){const e=g.useContext(VVt);if(!e)throw new Error("useExperimentItemPanel must be used within an ExperimentItemPanelProvider");return e}function Ums({results:e,isLoading:t,featuredResultId:n,onResultClick:r,columns:s,scoresByItemId:a,scorerIds:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u,selectedIds:d,onToggleSelect:f}){const{Link:p,paths:h}=un(),m=!!(d&&f),v=[m?"auto":"",...s.map(k=>k.size)].filter(Boolean).join(" "),y=s.some(k=>k.name==="input"),{containerRef:b,getRowProps:x}=so({count:e.length}),S=k=>i?.includes(k.name)?o.jsx(he.TopCell,{children:o.jsxs(p,{href:h.scorerLink(k.name),className:"flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[o.jsx(AC,{}),o.jsx("span",{className:"min-w-0 truncate",children:k.label})]})},k.name):o.jsx(he.TopCell,{children:k.label},k.name);return t?o.jsx(Fo,{columns:v}):o.jsxs(he,{columns:v,className:"min-w-0",scrollRef:b,children:[o.jsxs(he.Top,{hasLeadingCell:m,children:[m&&o.jsx(he.TopCell,{children:" "}),m?o.jsx(he.TopCells,{colStart:2,children:s.map(S)}):s.map(S)]}),e.length===0?o.jsx(he.NoMatch,{message:"No results yet"}):o.jsxs(o.Fragment,{children:[e.map((k,_)=>{const C=!!k.error,T=k.id===n,E=o.jsxs(o.Fragment,{children:[o.jsxs(he.Cell,{className:"text-ui-smd text-neutral3 flex items-center gap-1.5 tracking-wide",children:[o.jsx("span",{children:k.itemId?.slice(0,8)??""}),C&&o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx(xO,{role:"img","aria-label":"Error",className:"text-error size-3.5"})}),o.jsx(yn,{children:k.error?.message||"Error"})]})]}),y&&o.jsx(he.TextCell,{font:"mono",children:Vms(qms(k.input),200)}),i?.map(N=>{const A=a?.[k.itemId]?.find(R=>R.scorerId===N);return o.jsx(he.Cell,{className:"text-neutral3 text-ui-smd font-mono",children:A!=null?A.score.toFixed(3):"-"},N)})]});return m?o.jsxs(he.RowWrapper,{children:[o.jsx(he.SelectCell,{checked:d.has(k.id),onToggle:()=>f(k.id),"aria-label":`Select result ${k.itemId}`}),o.jsx(he.RowButton,{colStart:2,featured:T,"data-selected":T||void 0,onClick:()=>r(k.id),...x(_),children:E})]},k.id):o.jsx(he.RowButton,{featured:T,"data-selected":T||void 0,onClick:()=>r(k.id),...x(_),children:E},k.id)}),o.jsx(he.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function qms(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Vms(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}function Hms({scoresByItemId:e,experimentStatus:t}){const{Link:n,paths:r}=un(),{data:s}=uh(),a=g.useMemo(()=>{if(!e)return[];const i={};for(const l of Object.values(e))for(const c of l)i[c.scorerId]||(i[c.scorerId]={sum:0,count:0}),i[c.scorerId].sum+=c.score,i[c.scorerId].count++;return Object.entries(i).map(([l,{sum:c,count:u}])=>({scorerId:l,avg:c/u})).sort((l,c)=>l.scorerId.localeCompare(c.scorerId))},[e]);if(a.length===0){const i=t==="running"||t==="pending",l=e!==void 0;let c,u;return i?(c="Experiment in progress",u="Summary metrics will appear here once the experiment completes."):l?(c="No scorers configured",u="Add scorers when triggering an experiment to evaluate results and see summary metrics here."):(c="Loading scores",u="Fetching scorer results…"),o.jsxs("div",{className:"text-ui-sm text-neutral3 flex items-center gap-2",children:[o.jsx(Gp,{className:"text-neutral3 size-4 shrink-0"}),o.jsx("span",{className:"text-neutral4",children:c}),o.jsx("span",{className:"truncate",children:u})]})}return o.jsx("div",{className:"flex items-stretch gap-2 overflow-x-auto pb-1",children:a.map(({scorerId:i,avg:l})=>{const c=s?.[i]?.scorer?.config?.name??i;return o.jsxs(Xr,{className:"w-52 min-w-0 flex-none p-3",children:[o.jsxs(n,{href:r.scorerLink(i),className:"text-ui-sm text-neutral3 [&>svg]:text-neutral3 flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3 [&>svg]:shrink-0",children:[o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx(AC,{role:"img","aria-label":"Scorer"})}),o.jsx(yn,{children:"Scorer"})]}),o.jsx("span",{className:"truncate",children:c})]}),o.jsxs("strong",{className:"text-ui-lg text-neutral4 font-semibold",children:[l.toFixed(3),o.jsx("span",{className:"text-ui-sm text-neutral3 ml-1.5 font-normal",children:"avg score"})]})]},i)})})}function Wms({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoading:s,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l}){const{currentItemId:c,openItem:u,close:d}=HVt(),[f,p]=g.useState(new Set),[h,m]=g.useState(!1),{updateExperimentResult:v}=bi(),y=g.useCallback(E=>{p(N=>{const I=new Set(N);return I.has(E)?I.delete(E):I.add(E),I})},[]),b=g.useCallback(()=>p(new Set),[]),x=g.useCallback(async E=>{if(h||E.length===0)return;m(!0);let N=0;const I=new Set;try{for(const A of E)try{await v.mutateAsync({datasetId:t,experimentId:e,resultId:A,status:"needs-review"}),N++,I.add(A)}catch{}}finally{m(!1)}I.size>0&&p(A=>{const R=new Set(A);for(const L of I)R.delete(L);return R}),N>0&&ze(`${N} result${N>1?"s":""} flagged for review`)},[t,e,h,v]),S=g.useMemo(()=>c?r.find(E=>E.itemId===c)?.id??null:null,[r,c]),{data:k}=C_(e,n),_=g.useMemo(()=>{if(!k)return[];const E=new Set;for(const N of Object.values(k))for(const I of N)E.add(I.scorerId);return[...E].sort()},[k]),C=g.useCallback(E=>{const N=r.find(I=>I.id===E);N&&(N.itemId===c?d():u(N.itemId))},[r,c,d,u]),T=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"7rem"},{name:"input",label:"Input",size:"minmax(10rem,20rem)"},..._.map(E=>({name:E,label:E,size:"12rem"}))],[_]);return o.jsxs("div",{className:K("grid h-full gap-3 overflow-hidden",f.size>0?"grid-rows-[auto_auto_1fr]":"grid-rows-[auto_1fr]"),children:[o.jsx(Hms,{scoresByItemId:k,experimentStatus:n}),f.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(le,{variant:"outline",size:"sm",disabled:h,onClick:()=>x([...f]),children:[o.jsx(We,{size:"sm",children:o.jsx(Q1,{})}),"Flag ",f.size," to review"]}),o.jsx(le,{variant:"ghost",size:"sm",onClick:b,children:"Clear"})]}),o.jsx("div",{className:"min-h-0 overflow-y-auto",children:o.jsx(Ums,{results:r,isLoading:s,featuredResultId:S,onResultClick:C,columns:T,scoresByItemId:k,scorerIds:_,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l,selectedIds:f,onToggleSelect:y})})]})}const ott={pending:{icon:o.jsx(a1,{className:"text-warning1 size-4"}),label:"Pending"},running:{icon:o.jsx(Ut,{size:"sm"}),label:"Running"},completed:{icon:o.jsx(t3,{className:"text-neutral3 size-4"}),label:"Completed"},failed:{icon:o.jsx(SO,{className:"text-error size-4"}),label:"Failed"}};function Zms({status:e,className:t}){const n=ott[e]??ott.pending;return o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx("span",{tabIndex:0,className:K("flex shrink-0 items-center",t),children:n.icon})}),o.jsx(yn,{children:n.label})]})}const Gms=e=>{const t=Ge();return mt({queryKey:["experiment-trace-light",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return t.getTraceLight(e)},select:AAe,enabled:!!e})};function WVt({children:e,className:t}){return o.jsx("div",{className:K("",t),children:e})}function Qms({date:e,className:t,withTime:n=!1}){const r=e?Axt(new Date(e)):!1,s=e?V3(new Date(e))?"Today":dr(new Date(e),"MMM dd"):"",a=e&&!r?dr(new Date(e),"yyyy"):"",i=e&&n?`${dr(new Date(e),"'at' h:mm aaa")}`:"";return o.jsxs("div",{className:K("truncate text-ui-md text-neutral2",t),children:[s," ",a," ",i]})}function dRe(e){return!e||e.length===0?"":e?.map(t=>t.size).join(" ")}function Yms({columns:e,isSelectionActive:t,children:n}){return o.jsx("div",{className:K("sticky top-0 z-10 mb-4 rounded-lg bg-surface3 px-4"),children:o.jsx("div",{className:K("grid items-center gap-4 text-left text-ui-xs tracking-widest text-neutral3 uppercase",{"pl-12 [&>label]:absolute [&>label]:left-0":t}),style:{gridTemplateColumns:dRe(e)},children:n})})}function Kms({children:e,className:t}){return o.jsx("span",{className:K("py-3",t),children:e})}function Xms({id:e,className:t,isShortened:n=!0}){const r=n?e.slice(0,8):e;return o.jsx("div",{className:K("truncate py-[0.6rem] text-ui-md text-neutral2",t),children:r})}function Jms({children:e}){return o.jsx("ul",{className:"grid content-start",children:e})}function egs({children:e}){const t=g.useRef(null);return o.jsx("div",{ref:t,className:K("overflow-y-auto"),children:e})}function tgs({children:e,className:t}){return o.jsx("label",{className:K("flex h-full w-14 items-center justify-center rounded-lg hover:bg-surface5",t),children:e})}function ngs({children:e,href:t,className:n,LinkComponent:r,tooltip:s}){const a=o.jsx(r,{href:t,className:K("flex w-full items-center justify-center gap-6 rounded-lg px-3 py-[0.6rem] text-left","hover:bg-surface4",Yr.colors,L3.visible,n),children:e});return s==null?a:o.jsxs(xn,{children:[o.jsx(vn,{render:a}),o.jsx(yn,{children:s})]})}function rgs({children:e,message:t,className:n,type:r}){return!e&&!t?null:o.jsx("div",{className:K("grid border-t border-border1",n),children:t?o.jsxs("p",{className:K("grid justify-center justify-items-center gap-2 p-8 text-center text-ui-md text-neutral3","[&>svg]:size-[1.5em] [&>svg]:opacity-75",{"[&>svg]:text-red-500":r==="error"}),children:[r==="error"?o.jsx(uc,{}):o.jsx(Em,{})," ",t]}):e})}function sgs({isLoading:e,hasMore:t,setEndOfListElement:n,loadingText:r="Loading more data...",noMoreDataText:s="No more data to load"}){return n?o.jsxs("div",{ref:n,className:"text-ui-md text-neutral3 mt-8 flex justify-center opacity-50",children:[e&&r,!t&&!e&&s]}):null}function ags({currentPage:e,hasMore:t,onNextPage:n,onPrevPage:r}){const s=typeof e=="number"&&e>0||t;return o.jsxs("div",{className:K("flex items-center justify-center gap-8 pt-6 text-ui-md text-neutral3"),children:[o.jsxs("span",{children:["Page ",o.jsx("b",{children:e?e+1:"1"})]}),s&&o.jsxs("div",{className:K("flex gap-4","[&>button]:flex [&>button]:items-center [&>button]:gap-2 [&>button]:rounded-md [&>button]:border [&>button]:border-border1 [&>button]:p-1 [&>button]:px-2 [&>button]:text-neutral4 [&>button]:transition-colors [&>button:hover]:text-neutral5","[&_svg]:size-[1em] [&_svg]:text-neutral3"),children:[typeof e=="number"&&e>0&&o.jsxs("button",{onClick:r,children:[o.jsx(bl,{}),"Previous"]}),t&&o.jsxs("button",{onClick:n,children:["Next",o.jsx(zd,{})]})]})]})}function igs({children:e,className:t}){return o.jsx("div",{className:K("grid grid-rows-[auto_1fr] overflow-y-auto",t),children:e})}function ogs({isSelected:e,children:t,columns:n}){return o.jsx("li",{className:K("flex overflow-hidden rounded-lg border border-transparent border-t-border1 py-[3px] pb-[2px] text-ui-md text-neutral5 first:border-t-transparent","[&:last-child>button]:rounded-b-lg","[&.selected-row]:border [&.selected-row]:border-dashed [&.selected-row]:border-white/50 [&.selected-row]:pr-[3px] [&.selected-row]:first:border-t","[&:has(+.selected-row)]:rounded-b-none [&:has(+.selected-row)]:border-b-transparent","[.selected-row+&]:rounded-t-none",Yr.colors,{"selected-row":e,"grid px-4 gap-4 ":n}),style:{gridTemplateColumns:dRe(n)},children:t})}function lgs({item:e,isFeatured:t,onClick:n,children:r,columns:s,className:a,disabled:i,tooltip:l,...c}){const u=()=>{n?.(e?.id)},d=o.jsx("button",{...c,onClick:u,className:K("grid w-full items-center gap-4 rounded-lg px-4 text-left",Yr.colors,L3.visible,{"bg-surface4":t,"hover:bg-surface4":e&&!t&&!i},a),style:{gridTemplateColumns:dRe(s)},disabled:i,children:r});return l==null?d:o.jsxs(xn,{children:[o.jsx(vn,{render:d}),o.jsx(yn,{children:l})]})}function cgs(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ugs({status:e}){return e?o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx("div",{className:K("relative flex h-full w-10 items-center justify-center bg-transparent"),children:o.jsx("div",{className:K("size-2 rounded-full",{"bg-green-600":["success","completed"].includes(e),"bg-red-700":["error","failed"].includes(e),"bg-yellow-500":["pending","running"].includes(e)})})})}),o.jsx(yn,{children:cgs(e)})]}):null}function dgs({children:e,isLoading:t,className:n}){return o.jsx("div",{className:K("truncate py-[0.6rem] text-ui-md text-neutral4",n),children:t?o.jsx("div",{className:"bg-surface4 h-4 animate-pulse rounded-md text-transparent select-none"}):e})}const SV={latest:"Latest version",deleted:"Deleted in this version"};function fgs({isLatest:e,isDeleted:t}){const n=[];return e&&n.push(SV.latest),t&&n.push(SV.deleted),n.length>0?n.join(" · "):void 0}function pgs({version:e,date:t,isLatest:n,isDeleted:r}){return o.jsxs(WVt,{className:K("grid grid-cols-[1fr_auto] pl-1"),children:[o.jsxs("div",{className:K("grid gap-1 leading-none text-neutral3",{"text-neutral4":n}),children:[o.jsxs("strong",{className:"font-normal",children:["v. ",e]}),o.jsx("em",{className:K("text-ui-sm","font-normal","text-neutral2"),children:t?dr(new Date(t),"MMM d, yyyy HH:mm"):null})]}),(n||r)&&o.jsxs("div",{className:"flex items-center gap-1",children:[n&&o.jsx("span",{className:"inline-flex",role:"img","aria-label":SV.latest,children:o.jsx(xt,{variant:"blue",size:"sm",icon:o.jsx(a1,{})})}),r&&o.jsx("span",{className:"inline-flex",role:"img","aria-label":SV.deleted,children:o.jsx(xt,{variant:"red",size:"sm",icon:o.jsx(x0e,{})})})]})]})}const pi=Object.assign(igs,{Header:Yms,HeaderCol:Kms,Items:Jms,Scroller:egs,Row:ogs,RowButton:lgs,Message:rgs,NextPageLoading:sgs,Pagination:ags,Cell:WVt,TextCell:dgs,StatusCell:ugs,VersionCell:pgs,IdCell:Xms,DateCell:Qms,LinkCell:ngs,LabelCell:tgs});function hgs({datasetId:e,itemId:t,onVersionSelect:n,onCompareVersionsClick:r,activeVersion:s}){const{data:a,isLoading:i}=lRe(e,t),[l,c]=g.useState(!1),[u,d]=g.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)},v=()=>{c(!0)},y=()=>{u.size===2&&r?.([...u])};return o.jsxs(pa,{className:"min-w-56",children:[l?o.jsx(pa.Toolbar,{className:"grid w-full justify-stretch gap-3",children:o.jsxs(es,{children:[o.jsx(le,{onClick:m,children:"Cancel"}),o.jsx(le,{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(pa.Toolbar,{children:o.jsxs(le,{onClick:v,className:"w-full",children:[o.jsx(Tj,{})," Compare Ver."]})})}),i?o.jsx(mgs,{}):o.jsxs(pi,{children:[o.jsx(pi.Header,{children:o.jsx(pi.HeaderCol,{children:"Item Version History"})}),o.jsx(pi.Scroller,{children:o.jsx(pi.Items,{children:a?.map(b=>{const x=String(b.datasetVersion),S=typeof b.updatedAt=="string"?new Date(b.updatedAt):b.updatedAt;return o.jsxs(pi.Row,{isSelected:l&&u.has(x),children:[l&&o.jsx(pi.LabelCell,{children:o.jsx(Oo,{checked:u.has(x),disabled:b.isDeleted,onCheckedChange:()=>{},onClick:k=>{k.stopPropagation(),b.isDeleted||h(x)},"aria-label":`Select version ${b.datasetVersion}`})}),o.jsx(pi.RowButton,{item:b,columns:[{name:"version",label:"Item Version History",size:"1fr"}],isFeatured:p(b),onClick:()=>f(b),className:"py-2",tooltip:fgs({isLatest:b.isLatest,isDeleted:b.isDeleted}),children:o.jsx(pi.VersionCell,{version:b.datasetVersion,date:S,isLatest:b.isLatest,isDeleted:b.isDeleted})})]},String(b.datasetVersion))})})})]})]})}function mgs(){return o.jsxs(pi,{children:[o.jsx(pi.Header,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(pi.HeaderCol,{children:"Item Version History"})}),o.jsx(pi.Items,{children:Array.from({length:3}).map((e,t)=>o.jsx(pi.Row,{children:o.jsx(pi.RowButton,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(pi.TextCell,{isLoading:!0,children:"Loading..."})})},t))})]})}function ggs(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${dr(n,"MMM dd 'at' H:mm:ss a")}`}return`v${e}`}function vgs({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=xAe(e),a=(s??[]).map(i=>({value:String(i.version),label:`${ggs(i.version,i.createdAt)}${i.isCurrent?" (current)":""}`}));return o.jsxs(pa.Toolbar,{className:"grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4",children:[o.jsx("div",{}),o.jsx(Ld,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:a,value:t??"",onValueChange:i=>r?.(i,n??"")}),o.jsx(Ld,{label:"Version B",labelIsHidden:!0,name:"version-b",options:a,value:n??"",onValueChange:i=>r?.(t??"",i)}),o.jsx("div",{})]})}const ygs=[{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"}],D9={added:{badgeVariant:"blue",borderColor:"border-blue-900",icon:o.jsx(Cr,{}),tooltip:"Added in this version"},changed:{badgeVariant:"yellow",borderColor:"border-yellow-900",icon:o.jsx(uJt,{}),tooltip:"Changed in this version"},same:{badgeVariant:"green",borderColor:"border-green-900",icon:o.jsx(fct,{}),tooltip:"Same in both versions"}};function Hie({red:e=!1,tooltip:t}){return o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx("span",{}),role:"img",tabIndex:0,"aria-label":t,className:"focus-visible:outline-neutral5/55 rounded focus-visible:outline-1 focus-visible:outline-offset-2 focus-visible:outline-solid",children:o.jsx(x0e,{className:K("text-neutral3/40 w-5 h-5 ",{"text-red-900":e})})}),o.jsx(yn,{children:t})]})}function Wie({variant:e,version:t}){if(!e)return o.jsxs("span",{className:"text-ui-md text-neutral4",children:["v. ",t]});const{badgeVariant:n,icon:r,tooltip:s}=D9[e];return o.jsxs("div",{className:"grid grid-cols-[1fr_auto]",children:[t!==void 0&&o.jsxs("span",{className:"text-ui-md text-neutral4 flex min-w-16 justify-end pr-3",children:["v. ",t]}),o.jsx("span",{className:"inline-flex",role:"img","aria-label":s,children:o.jsx(xt,{variant:n,size:"xs",icon:r})})]})}function bgs(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function ltt({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return"added";if(t==="changed"&&n)return"changed"}function xgs({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:a}){const{Link:i}=un(),l=t>n;return o.jsx(pi,{children:o.jsx(pi.Scroller,{children:o.jsx(pi.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=a.get(c),f=bgs(u,d),p=ltt({otherVersionExists:d!==void 0,status:f,isNewer:l}),h=ltt({otherVersionExists:u!==void 0,status:f,isNewer:!l});return o.jsxs(pi.Row,{columns:ygs,children:[o.jsx(pi.IdCell,{id:c,isShortened:!1}),f!=="same"?o.jsxs(o.Fragment,{children:[u?.datasetVersion?o.jsx(pi.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:p?D9[p].tooltip:void 0,children:o.jsx(Wie,{variant:p,version:u.datasetVersion})}):o.jsx(pi.Cell,{className:"flex items-center justify-center",children:o.jsx(Hie,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?o.jsx(pi.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:h?D9[h].tooltip:void 0,children:o.jsx(Wie,{variant:h,version:d.datasetVersion})}):o.jsx(pi.Cell,{className:"flex items-center justify-center",children:o.jsx(Hie,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):o.jsx(pi.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",tooltip:D9.same.tooltip,children:o.jsx(Wie,{variant:"same",version:d?.datasetVersion})}),f==="changed"?o.jsx(pi.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}/versions?ids=${u?.datasetVersion},${d?.datasetVersion}`,children:"Compare"}):o.jsx(pi.Cell,{children:o.jsx(Hie,{tooltip:"Comparing is available only for changed items"})})]},c)})})})})}function wgs(){const e=Vr(),[t,n]=g.useState(""),[r,s]=g.useState("all"),[a,i]=g.useState("all"),[l,c]=g.useState("all"),{data:u=[],isLoading:d,error:f,isFetchingNextPage:p,hasNextPage:h,setEndOfListElement:m}=jRn(),{data:v,isLoading:y,error:b}=UH(),x=g.useMemo(()=>v?.experiments??[],[v?.experiments]),S=g.useMemo(()=>Phs(u),[u]),k=d||y,_=f||b,C=()=>{e("/datasets/new")};if(_&&ps(_))return o.jsx(Zn,{children:o.jsx(Ts,{})});if(_&&hs(_))return o.jsx(Zn,{children:o.jsx(Os,{resource:"datasets"})});if(_)return o.jsx(Zn,{children:o.jsx($a,{title:"Failed to load datasets",message:_.message})});if(u.length===0&&!k)return o.jsx(Zn,{children:o.jsx(Fhs,{onCreateClick:C})});const T=r!=="all"||a!=="all"||l!=="all"||t!=="",E=()=>{n(""),s("all"),i("all"),c("all")};return o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(Uhs,{search:t,onSearchChange:n,targetFilter:r,onTargetFilterChange:s,experimentFilter:a,onExperimentFilterChange:i,tagFilter:l,onTagFilterChange:c,tagOptions:S,onReset:E,hasActiveFilters:T,onCreateClick:C})}),o.jsx(Lhs,{datasets:u,experiments:x,isLoading:k,search:t,targetFilter:r,experimentFilter:a,tagFilter:l,isFetchingNextPage:p,hasNextPage:h,setEndOfListElement:m})]})}function n8({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function Sgs(){const{datasetId:e}=fr(),t=Vr(),[n,r]=Ma(),{activeVersion:s,handleVersionChange:a}=cRe(n,r),[i,l]=g.useState(!1),[c,u]=g.useState(!1),[d,f]=g.useState(!1),[p,h]=g.useState(!1),{data:m,error:v,isLoading:y}=My(e),{data:b=[],isLoading:x}=W1(e,void 0,s),S=!x&&b.length===0;if(y)return null;if(v&&ps(v))return o.jsx(n8,{children:o.jsx(Ts,{})});if(v&&hs(v))return o.jsx(n8,{children:o.jsx(Os,{resource:"datasets"})});if(v&&VEe(v)||!y&&!v&&!m)return o.jsx(n8,{children:o.jsx(br,{iconSlot:o.jsx(hm,{}),titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:o.jsxs(le,{as:Ba,to:"/datasets",children:[o.jsx(bl,{}),"Back to Datasets"]})})});if(v)return o.jsx(n8,{children:o.jsx($a,{title:"Failed to load dataset",message:v instanceof Error?v.message:"An unexpected error occurred. Please try again."})});const k=C=>{t(`/experiments/${C}`)},_=()=>{t("/datasets")};return o.jsxs(Ams,{datasetId:e,items:b,isLoadingItems:x,children:[o.jsxs("div",{className:"relative h-full overflow-hidden",children:[o.jsx(Lt,{height:"full",className:"grid-rows-[1fr] p-0",children:o.jsx(Lt.MainArea,{children:o.jsx(Rms,{datasetId:e,onAddItemClick:()=>u(!0),leftSlot:o.jsx("span",{className:"text-ui-sm text-neutral3 mr-3 whitespace-nowrap",children:m?.createdAt?`Created ${dr(new Date(m.createdAt),"MMM d")}`:""}),rightSlot:o.jsxs(es,{children:[o.jsxs(le,{as:Ba,to:`/experiments?dataset=${e}`,children:[o.jsx(k0e,{}),"View experiments"]}),o.jsx(DVt,{datasetId:e,value:s,onValueChange:a,currentVersion:m?.version,className:"w-36"}),S?o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx("span",{className:"cursor-not-allowed",children:o.jsx("div",{className:"pointer-events-none opacity-50",inert:!0,"aria-disabled":"true",children:o.jsxs(le,{variant:"primary",children:[o.jsx(Mc,{}),"Run Experiment"]})})})}),o.jsx(yn,{children:"Add items to the dataset before running an experiment"})]}):o.jsxs(le,{variant:"primary",onClick:()=>l(!0),children:[o.jsx(Mc,{}),"Run Experiment"]}),o.jsxs(at,{children:[o.jsx(at.Trigger,{asChild:!0,children:o.jsx(le,{size:"lg","aria-label":"Dataset actions menu",children:o.jsx(sI,{})})}),o.jsxs(at.Content,{align:"end",className:"w-48",children:[o.jsxs(at.Item,{onSelect:()=>{t(`/datasets/${e}/edit`)},children:[o.jsx(Qp,{})," Edit Dataset"]}),o.jsxs(at.Item,{onSelect:()=>h(!0),children:[o.jsx(Bd,{})," Duplicate Dataset"]}),o.jsxs(at.Item,{onSelect:()=>f(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(Fl,{})," Delete Dataset"]})]})]})]})})})}),o.jsx(Fg,{})]}),o.jsx(sY,{initialDatasetId:e,initialDatasetVersion:s??void 0,open:i,onOpenChange:l,onSuccess:k},`${e}:${s??"latest"}`),o.jsx($ms,{datasetId:e,open:c,onOpenChange:u}),m&&o.jsx(rms,{open:p,onOpenChange:h,sourceDatasetId:m.id,sourceDatasetName:m.name,sourceDatasetDescription:m.description,sourceDatasetTargetType:m.targetType}),m&&o.jsx(oms,{open:d,onOpenChange:f,datasetId:m.id,datasetName:m.name,onSuccess:_})]})}function Zie({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function kgs(){const{datasetId:e}=fr(),t=Vr(),{data:n,error:r,isLoading:s}=My(e),a=()=>{t(`/datasets/${e}`)};return s?null:r&&ps(r)?o.jsx(Zie,{children:o.jsx(Ts,{})}):r&&hs(r)?o.jsx(Zie,{children:o.jsx(Os,{resource:"datasets"})}):r||!n?o.jsx(Zie,{children:o.jsx($a,{title:"Failed to load dataset",message:r instanceof Error?r.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-6 py-8",children:[o.jsx(Aa,{className:"mb-6 p-0",children:o.jsxs(Aa.Column,{children:[o.jsxs(Aa.Title,{children:[o.jsx(hm,{})," Edit dataset"]}),o.jsx(Aa.Description,{children:n.name})]})}),o.jsx(Yu,{className:"p-6",children:o.jsx(ims,{dataset:{id:n.id,name:n.name,description:n.description||"",targetType:n.targetType,inputSchema:n.inputSchema,groundTruthSchema:n.groundTruthSchema,requestContextSchema:n.requestContextSchema},onSuccess:a,onCancel:a})})]})})]})}function aY({label:e,wide:t=!1,children:n}){return o.jsxs("div",{className:K("pointer-events-none absolute inset-0 z-30","grid transition-[grid-template-columns] duration-300 ease-in-out",t?"grid-cols-[1fr_4fr]":"grid-cols-[1fr_1fr]"),children:[o.jsx("div",{className:"pointer-events-none"}),o.jsx("div",{role:"dialog","data-item-panel":!0,"aria-label":e,className:"pointer-events-auto h-full min-h-0 min-w-0 overflow-y-auto",children:n})]})}const r8=()=>{},Ogs=new Set,_gs=[{name:"id",label:"ID",size:"7rem"},{name:"input",label:"Input",size:"minmax(10rem,1fr)"},{name:"groundTruth",label:"Ground Truth",size:"minmax(10rem,1fr)"},{name:"trajectory",label:"Trajectory",size:"8rem"},{name:"createdAt",label:"Created",size:"10rem"}];function Cgs({datasetId:e,currentItemId:t,open:n,onOpenChange:r}){const{navigate:s,paths:a}=un(),[i,l]=g.useState(""),[c]=YH(i,300),{data:u,isLoading:d,setEndOfListElement:f,isFetchingNextPage:p,hasNextPage:h}=W1(e,c||void 0),m=u.filter(y=>y.id!==t),v=y=>{r(!1),s(a.datasetItemCompareLink(e,t,y))};return o.jsx(hr,{open:n,onOpenChange:r,children:o.jsxs(mr,{className:"sm:max-w-[min(72rem,calc(100%-4rem))]",children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Compare with…"}),o.jsx(Cs,{children:"Pick an item to compare with the current one."})]}),o.jsxs(jr,{className:"grid max-h-[70vh] min-h-[24rem] grid-rows-[auto_1fr] gap-3",children:[o.jsx(y_,{name:"compare-with-dialog-search",label:"Search items to compare",labelIsHidden:!0,value:i,onChange:y=>l(y.target.value),placeholder:"Search items..."}),o.jsx("div",{className:"min-h-0 overflow-y-auto",children:o.jsx(LVt,{items:m,isLoading:d,onItemClick:v,selectOnNavigate:!1,columns:_gs,searchQuery:c||" ",setEndOfListElement:f,isFetchingNextPage:p,hasNextPage:h,isSelectionActive:!1,selectedIds:Ogs,onToggleSelection:r8,onSelectAll:r8,onClearSelection:r8,onAddClick:r8})})]})]})})}function Egs(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 Tgs({datasetId:e,item:t,items:n,onItemChange:r,onClose:s}){const{Link:a}=un(),{updateItem:i,deleteItem:l}=bi(),[c,u]=g.useState(!1),[d,f]=g.useState(""),[p,h]=g.useState(""),[m,v]=g.useState(""),[y,b]=g.useState(""),[x,S]=g.useState(""),[k,_]=g.useState(t.scorerIds!==void 0),[C,T]=g.useState(t.scorerIds??[]),[E,N]=g.useState(""),[I,A]=g.useState(null),[R,L]=g.useState(!1),[M,F]=g.useState(!1);g.useEffect(()=>{t&&(f(JSON.stringify(t.input,null,2)),h(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),v(t.metadata?JSON.stringify(t.metadata,null,2):""),b(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),S(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),_(t.scorerIds!==void 0),T(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),L(!1),A(null))},[t?.id]);const H=n.findIndex(B=>B.id===t.id),z=H>0?()=>r(n[H-1].id):void 0,q=H>=0&&H<n.length-1?()=>r(n[H+1].id):void 0,V=async()=>{let B;try{B=JSON.parse(d)}catch{ze.error("Input must be valid JSON");return}let Z;if(p.trim())try{Z=JSON.parse(p)}catch{ze.error("Ground Truth must be valid JSON");return}let Y;if(m.trim())try{Y=JSON.parse(m)}catch{ze.error("Metadata must be valid JSON");return}let te=null;if(y.trim())try{te=JSON.parse(y)}catch{ze.error("Expected Trajectory must be valid JSON");return}let J;if(x.trim())try{const oe=JSON.parse(x);if(!Array.isArray(oe)){ze.error("Tool Mocks must be a JSON array");return}J=oe}catch{ze.error("Tool Mocks must be valid JSON");return}else J=[];let ee;if(E.trim())try{ee=JSON.parse(E)}catch{ze.error("Request Context must be valid JSON");return}let re;k?re=C:t.scorerIds!==void 0&&(re=null);try{const oe=await i.mutateAsync({datasetId:e,itemId:t.id,input:B,groundTruth:Z,metadata:Y,expectedTrajectory:te,toolMocks:J,scorerIds:re,requestContext:ee});ze.success("Item updated successfully"),_(oe.scorerIds!==void 0),T(oe.scorerIds??[]),u(!1),A(null)}catch(oe){const X=Egs(oe);X?A(X):ze.error(`Failed to update item: ${oe instanceof Error?oe.message:"Unknown error"}`)}},D=()=>{f(JSON.stringify(t.input,null,2)),h(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),v(t.metadata?JSON.stringify(t.metadata,null,2):""),b(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),S(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),_(t.scorerIds!==void 0),T(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),A(null)},G=B=>{f(B),I?.field==="input"&&A(null)},U=B=>{h(B),I?.field==="groundTruth"&&A(null)},P=async()=>{try{await l.mutateAsync({datasetId:e,itemId:t.id}),ze.success("Item deleted successfully"),L(!1),s()}catch(B){ze.error(`Failed to delete item: ${B instanceof Error?B.message:"Unknown error"}`)}};return o.jsxs(o.Fragment,{children:[o.jsxs(on,{children:[o.jsxs(on.Header,{children:[o.jsxs(on.Heading,{children:["Item ",o.jsxs("b",{children:["# ",t.id.length>12?`${t.id.slice(0,12)}…`:t.id]})]}),o.jsxs(es,{className:"ml-auto shrink-0",children:[o.jsx(on.NextPrevNav,{onPrevious:z,onNext:q,previousLabel:"Previous item",nextLabel:"Next item"}),!c&&o.jsxs(o.Fragment,{children:[o.jsx(le,{as:a,href:`/datasets/${e}/items/${t.id}/versions`,size:"md",tooltip:"Go to item versions history","aria-label":"Go to item versions history",children:o.jsx(lI,{})}),o.jsxs(at,{children:[o.jsx(at.Trigger,{asChild:!0,children:o.jsx(le,{size:"md","aria-label":"Actions menu",children:o.jsx(sI,{})})}),o.jsxs(at.Content,{align:"end",className:"w-48",children:[o.jsxs(at.Item,{onSelect:()=>u(!0),children:[o.jsx(Qp,{}),"Edit"]}),o.jsxs(at.Item,{onSelect:()=>F(!0),children:[o.jsx(Tj,{}),"Compare with…"]}),o.jsxs(at.Item,{onSelect:()=>L(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(Fl,{}),"Delete Item"]})]})]})]}),o.jsx(on.CloseButton,{onClick:s,tooltip:"Close detail panel"})]})]}),o.jsx(on.Content,{children:c?o.jsx(Dms,{inputValue:d,setInputValue:G,groundTruthValue:p,setGroundTruthValue:U,metadataValue:m,setMetadataValue:v,trajectoryValue:y,setTrajectoryValue:b,toolMocksValue:x,setToolMocksValue:S,scorerOverrideEnabled:k,setScorerOverrideEnabled:_,selectedScorerIds:C,setSelectedScorerIds:T,requestContextValue:E,setRequestContextValue:N,validationErrors:I,onSave:V,onCancel:D,isSaving:i.isPending}):o.jsxs(o.Fragment,{children:[o.jsxs(Tn,{children:[o.jsx(Tn.Key,{children:"Dataset Id"}),o.jsx(Tn.ValueWithCopyBtn,{copyTooltip:"Copy Dataset Id to clipboard",copyValue:t.datasetId,children:t.datasetId}),o.jsx(Tn.Key,{children:"Version"}),o.jsxs(Tn.Value,{children:["v",t.datasetVersion]}),o.jsx(Tn.Key,{children:"Created"}),o.jsx(Tn.Value,{children:dr(new Date(t.createdAt),"MMM d, yyyy h:mm aaa")}),t.updatedAt&&new Date(t.updatedAt).getTime()!==new Date(t.createdAt).getTime()&&o.jsxs(o.Fragment,{children:[o.jsx(Tn.Key,{children:"Updated"}),o.jsx(Tn.Value,{children:dr(new Date(t.updatedAt),"MMM d, yyyy h:mm aaa")})]})]}),o.jsxs("div",{className:"mt-3 grid gap-3",children:[o.jsx(on.CodeSection,{title:"Input",icon:o.jsx(wx,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(on.CodeSection,{title:"Ground Truth",icon:o.jsx(rm,{}),codeStr:JSON.stringify(t.groundTruth??null,null,2)}),t.expectedTrajectory!=null&&o.jsx(on.CodeSection,{title:"Expected Trajectory",icon:o.jsx(I0e,{}),codeStr:JSON.stringify(t.expectedTrajectory,null,2)}),o.jsx(on.CodeSection,{title:"Tool Mocks",icon:o.jsx(qd,{}),codeStr:JSON.stringify(t.toolMocks??[],null,2)}),o.jsx(on.CodeSection,{title:"Scorers",icon:o.jsx(PV,{}),codeStr:t.scorerIds===void 0?"Inherited from dataset":JSON.stringify(t.scorerIds,null,2)}),t.requestContext!=null&&o.jsx(on.CodeSection,{title:"Request Context",icon:o.jsx(sc,{}),codeStr:JSON.stringify(t.requestContext,null,2)}),o.jsx(on.CodeSection,{title:"Metadata",icon:o.jsx(cI,{}),codeStr:JSON.stringify(t.metadata??null,null,2)})]})]})})]}),o.jsx(Cgs,{datasetId:e,currentItemId:t.id,open:M,onOpenChange:F}),o.jsx(Mt,{open:R,onOpenChange:L,children:o.jsxs(Mt.Content,{children:[o.jsxs(Mt.Header,{children:[o.jsx(Mt.Title,{children:"Delete Item"}),o.jsx(Mt.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),o.jsxs(Mt.Footer,{children:[o.jsx(Mt.Cancel,{children:"Cancel"}),o.jsx(Mt.Action,{onClick:P,children:l.isPending?"Deleting...":"Yes, Delete"})]})]})})]})}function jgs(){const{itemId:e}=fr(),{datasetId:t,items:n,isLoadingItems:r,openItem:s,close:a}=BVt(),i=g.useMemo(()=>n.find(d=>d.id===e)??null,[n,e]),{data:l,isLoading:c}=GD(i?"":t,!i&&e?e:""),u=i??l??null;return e?o.jsx(aY,{label:`Dataset item ${e}`,children:u?o.jsx("div",{className:"[&>section]:bg-surface3 flex min-h-full flex-col p-3 [&>section]:min-h-0 [&>section]:flex-1 [&>section]:rounded-lg [&>section]:shadow-lg",children:o.jsx(Tgs,{datasetId:t,item:u,items:n,onItemChange:s,onClose:a})}):r||c?o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(Ut,{})})}):o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(br,{iconSlot:o.jsx(hm,{}),titleSlot:"Item not found",descriptionSlot:`No loaded item "${e}".`,actionSlot:o.jsx(le,{onClick:a,children:"Close"})})})})}):null}function ctt(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,metadata:e.metadata??null},null,2)}function Ngs(){const{datasetId:e,itemId:t,secondItemId:n}=fr(),r=Vr(),s=[t,n].filter(h=>!!h),{data:a,error:i}=My(e??""),{Link:l,paths:c}=un(),[u,d]=g.useState(!1),{data:f}=GD(e??"",s[0]??""),{data:p}=GD(e??"",s[1]??"");return i&&ps(i)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{})})}):i&&hs(i)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Os,{resource:"datasets"})})}):!e||s.length<2?o.jsx(vs,{children:o.jsx(hy,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Select at least two items to compare."})})})}):o.jsxs(vs,{children:[o.jsx(Dy,{owner:"dataset-items-compare",children:o.jsxs(le,{as:Ba,to:`/datasets/${e}`,variant:"outline",children:[o.jsx(bl,{}),"Back to Dataset"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:K("grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",{"grid-rows-[auto_auto_1fr]":u}),children:[o.jsxs(Aa,{children:[o.jsxs(Aa.Column,{children:[o.jsxs(Aa.Title,{children:[o.jsx(Tj,{}),"Compare Dataset Items"]}),o.jsx(Aa.Description,{children:o.jsxs(Pl,{children:["Comparing ",s.length," items of"," ",o.jsx(Ba,{to:`/datasets/${e}`,className:"text-info1 hover:underline",children:a?.name||e?.slice(0,8)})]})})]}),o.jsx(Aa.Column,{children:o.jsx(es,{children:o.jsx(le,{variant:"primary",onClick:()=>d(h=>!h),children:u?o.jsxs(o.Fragment,{children:[o.jsx(TV,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx($Yt,{})," Diff View"]})})})})]}),o.jsx(r1,{className:"grid-cols-[1fr_3vw_1fr]",children:s.map((h,m)=>o.jsxs(g.Fragment,{children:[o.jsx(Igs,{datasetId:e,itemId:h,Link:l,idx:m,itemIds:s,showContent:!u,onItemChange:v=>{const y=[...s];y[m]=v,r(c.datasetItemCompareLink(e,y[0],y[1]))}}),m==0&&o.jsx("div",{className:K("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},h))}),u&&f&&p&&o.jsx(NAe,{codeA:ctt(f),codeB:ctt(p)})]})})]})}function Igs({datasetId:e,itemId:t,Link:n,idx:r,itemIds:s,onItemChange:a,showContent:i=!0}){const{data:l,isLoading:c}=GD(e,t),{data:u}=W1(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(pa,{children:[o.jsxs(pa.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(xr,{value:p.value,disabled:p.disabled,children:p.label},p.value))})]}),o.jsxs(le,{as:n,to:`/datasets/${e}/items/${t}`,children:[o.jsx(lI,{}),"Versions"]})]}),i&&o.jsx(pa.Content,{children:c?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):l?o.jsxs(o.Fragment,{children:[o.jsx(Mms,{item:l}),o.jsx(uRe,{item:l,Link:n})]}):o.jsxs("div",{className:"text-neutral4 text-sm",children:["Item ",t.slice(0,8)," not found"]})})]})}function utt(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,scorerIds:e.scorerIds??null,metadata:e.metadata??null},null,2)}function Ags(){const{datasetId:e,itemId:t}=fr(),[n,r]=Ma(),[s,a]=g.useState(!1),i=n.get("ids")?.split(",").map(Number).filter(h=>!isNaN(h)&&h>0)??[],{data:l,error:c}=My(e??""),{Link:u}=un(),{data:d}=lRe(e??"",t??""),{data:f}=t0e(e??"",t??"",i[0]??0,l?.version),{data:p}=t0e(e??"",t??"",i[1]??0,l?.version);return c&&ps(c)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{})})}):c&&hs(c)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Os,{resource:"datasets"})})}):!e||!t?o.jsx(vs,{children:o.jsx(hy,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Item not found."})})})}):i.length<2?o.jsx(Rgs,{datasetId:e,itemId:t,Link:u,onCompare:h=>r({ids:h.join(",")})}):o.jsxs(vs,{children:[o.jsx(Dy,{owner:"dataset-item-versions-compare",children:o.jsxs(le,{as:Ba,to:`/datasets/${e}/items/${t}`,variant:"outline",children:[o.jsx(bl,{}),"Back to Item"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:K("grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",{"grid-rows-[auto_auto_1fr]":s}),children:[o.jsxs(Aa,{children:[o.jsxs(Aa.Column,{children:[o.jsxs(Aa.Title,{children:[o.jsx(Tj,{}),"Compare Dataset Item Versions"]}),o.jsx(Aa.Description,{children:o.jsxs(Pl,{children:["Comparing ",i.length," versions of"," ",o.jsx(Ba,{to:`/datasets/${e}/items/${t}`,className:"text-info1 hover:underline",children:t})]})})]}),o.jsx(Aa.Column,{children:o.jsx(es,{children:o.jsx(le,{variant:"primary",onClick:()=>a(h=>!h),children:s?o.jsxs(o.Fragment,{children:[o.jsx(TV,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(NKt,{})," Diff View"]})})})})]}),o.jsx(r1,{className:"grid-cols-[1fr_3vw_1fr]",children:i.map((h,m)=>o.jsxs(g.Fragment,{children:[o.jsx(Pgs,{datasetId:e,itemId:t,datasetVersion:h,latestVersion:l?.version,allVersions:d??[],versionNumbers:i,Link:u,idx:m,showContent:!s,onVersionChange:v=>{const y=[...i];y[m]=v,r({ids:y.join(",")})}}),m===0&&o.jsx("div",{className:K("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},h))}),s&&f&&p&&o.jsx(NAe,{codeA:utt(f),codeB:utt(p)})]})})]})}function Rgs({datasetId:e,itemId:t,Link:n,onCompare:r}){const[s,a]=g.useState(null),{data:i,isLoading:l}=lRe(e,t),c=(s!=null?i?.find(d=>d.datasetVersion===s):void 0)??i?.[0],u=c?{id:c.id,datasetId:e,datasetVersion:c.datasetVersion,input:c.input,groundTruth:c.groundTruth,scorerIds:c.scorerIds,metadata:c.metadata,createdAt:c.createdAt,updatedAt:c.updatedAt}:null;return o.jsxs(vs,{children:[o.jsx(Dy,{owner:"dataset-item-versions-history",children:o.jsxs(le,{as:Ba,to:`/datasets/${e}/items/${t}`,variant:"outline",children:[o.jsx(bl,{}),"Back to Item"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:"mx-auto grid h-full max-w-[140rem] grid-rows-[auto_1fr] gap-6",children:[o.jsx(Aa,{children:o.jsxs(Aa.Column,{children:[o.jsxs(Aa.Title,{children:[o.jsx(lI,{}),"Item Version History"]}),o.jsx(Aa.Description,{children:o.jsxs(Pl,{children:["Versions of ",t]})})]})}),o.jsxs(r1,{className:"grid-cols-[1fr_auto]",children:[o.jsx(pa,{children:o.jsx(pa.Content,{children:l?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):u?o.jsx(uRe,{item:u,Link:n}):o.jsx("div",{className:"text-neutral4 text-sm",children:"Item data not available"})})}),o.jsx(hgs,{datasetId:e,itemId:t,onClose:()=>{},onVersionSelect:d=>a(d.datasetVersion),onCompareVersionsClick:r,activeVersion:s})]})]})})]})}function Pgs({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}=t0e(e,t,n,r),p=new Set(a.filter((v,y)=>y!==l)),h=s.map(v=>{const y=typeof v.updatedAt=="string"?new Date(v.updatedAt):v.updatedAt;return{value:String(v.datasetVersion),label:o.jsxs(o.Fragment,{children:[o.jsxs("b",{children:["v. ",v.datasetVersion]})," - ",dr(y,"MMM d, yyyy h:mm a"),v.isLatest?o.jsx(xt,{variant:"blue",size:"xs",children:"Latest"}):null]}),disabled:p.has(v.datasetVersion)}}),m=d?{id:d.id,datasetId:e,datasetVersion:d.datasetVersion,input:d.input,groundTruth:d.groundTruth,scorerIds:d.scorerIds,metadata:d.metadata,createdAt:d.createdAt,updatedAt:d.updatedAt}:null;return o.jsxs(pa,{children:[o.jsxs(pa.Toolbar,{className:"grid grid-cols-[auto_1fr] gap-4",children:[o.jsx(lI,{className:"h-6 w-6 opacity-50"}),o.jsxs(oa,{name:`compare-version-${l}`,value:String(n),onValueChange:v=>u(Number(v)),children:[o.jsx(ca,{"aria-label":"Version",className:"w-full",children:o.jsx(la,{placeholder:"Select version"})}),o.jsx(ua,{children:h.map(v=>o.jsx(xr,{value:v.value,disabled:v.disabled,children:v.label},v.value))})]})]}),c&&o.jsx(pa.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(uRe,{item:m,Link:i})})]})}function $gs(){const{datasetId:e}=fr(),[t]=Ma(),n=t.get("ids")?.split(",").map(Number).filter(v=>!isNaN(v)&&v>0)??[],r=Vr(),{data:s,error:a}=My(e??""),i=W1(e??"",void 0,n[0]??null),l=W1(e??"",void 0,n[1]??null),c=g.useMemo(()=>i.data??[],[i.data]),u=g.useMemo(()=>l.data??[],[l.data]),d=g.useMemo(()=>{const v=new Map;for(const y of[...c,...u])v.has(y.id)||v.set(y.id,{id:y.id,createdAt:new Date(y.createdAt)});return[...v.values()].sort((y,b)=>b.createdAt.getTime()-y.createdAt.getTime())},[c,u]),f=g.useMemo(()=>new Map(c.map(v=>[v.id,v])),[c]),p=g.useMemo(()=>new Map(u.map(v=>[v.id,v])),[u]);if(a&&ps(a))return o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{})})});if(a&&hs(a))return o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Os,{resource:"datasets"})})});if(!e||n.length<2)return o.jsx(vs,{children:o.jsx(hy,{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=(v,y,b)=>{r(`/datasets/${e}/items/${v}/versions?ids=${y?.datasetVersion??""},${b?.datasetVersion??""}`)},m=(v,y)=>{r(`/datasets/${e}/versions?ids=${v},${y}`,{replace:!0})};return o.jsx(vs,{children:o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:"mx-auto grid h-full max-w-[140rem] grid-rows-[auto_1fr] gap-6",children:[o.jsxs(Aa,{children:[o.jsxs(Aa.Column,{children:[o.jsxs(Aa.Title,{children:[o.jsx(FJt,{})," Compare Dataset Versions"]}),o.jsx(Aa.Description,{children:o.jsxs(Pl,{children:[o.jsx(lI,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),o.jsx(Aa.Column,{children:o.jsxs(le,{as:Ba,to:`/datasets/${e}`,children:[o.jsx(bl,{}),"Back to Dataset"]})})]}),o.jsx(r1,{children:o.jsxs(pa,{children:[o.jsx(vgs,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:m}),o.jsx(xgs,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:p,onItemClick:h})]})})]})})})}function Mgs(){const e=Vr(),[t]=Ma(),n=t.get("targetType"),r=YD(n)?n:void 0,s=t.get("targetIds"),a=r&&s?s.split(",").map(i=>i.trim()).filter(Boolean):void 0;return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-6 py-8",children:[o.jsx(Aa,{className:"mb-6 p-0",children:o.jsxs(Aa.Column,{children:[o.jsxs(Aa.Title,{children:[o.jsx(hm,{})," Create new dataset"]}),o.jsx(Aa.Description,{children:"Datasets group test cases used to evaluate your agents and workflows."})]})}),o.jsx(Yu,{className:"p-6",children:o.jsx(ems,{targetType:r,targetIds:a,onSuccess:i=>{e(`/datasets/${i}`)},onCancel:()=>{e(-1)}})})]})})]})}function s0e({children:e,className:t}){return o.jsx("div",{className:K("flex flex-wrap gap-8",t),children:e})}function Dgs(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 Lgs({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,v=Dgs(n);return o.jsxs(o.Fragment,{children:[o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Total Scorers"}),i?o.jsx(Xr.Loading,{}):f!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(f)}),o.jsx(Xr.NoChange,{message:"Static count"})]}):o.jsx(Xr.NoData,{})]}),o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Total Datasets"}),l?o.jsx(Xr.Loading,{}):p!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(p)}),o.jsx(Xr.NoChange,{message:"Static count"})]}):o.jsx(Xr.NoData,{})]}),o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Avg Score"}),u?o.jsx(Xr.Loading,{}):r!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(r)}),m?o.jsx(Xr.Change,{changePct:m.changePct,prevValue:m.prevValue}):o.jsx(Xr.NoChange,{})]}):o.jsx(Xr.NoData,{})]}),o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Total Experiments"}),c?o.jsx(Xr.Loading,{}):h!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(h)}),v?o.jsx(Xr.Change,{changePct:v.changePct,prevValue:v.prevValue}):o.jsx(Xr.NoChange,{})]}):o.jsx(Xr.NoData,{})]}),o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Needs Review"}),d?o.jsx(Xr.Loading,{}):a!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(a)}),a>0?o.jsx(Xr.NoChange,{message:"items pending review"}):o.jsx(Xr.NoChange,{message:"All caught up"})]}):o.jsx(Xr.NoData,{})]})]})}function ZVt(e){const t=h0(e.id)??e.id;return e.name||`Experiment #${t}`}const Fgs=60;function zgs({experiment:e}){return o.jsx("span",{className:"text-neutral4 block min-w-0 truncate text-left",children:ZVt(e)})}function Bgs({experiment:e}){const t=e.description;if(!t)return o.jsx("span",{className:"text-neutral2",children:"—"});const n=o.jsx("span",{className:"text-neutral3 block min-w-0 truncate text-left",children:t});return t.length<=Fgs?n:o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:n}),o.jsx(yn,{children:t})]})}const iY=()=>{const{requestContext:e}=ys(),t=Ge();return mt({queryKey:["processors"],queryFn:()=>t.listProcessors(e)})},GVt=(e,t)=>{const n=Ge(),{requestContext:r}=ys();return mt({queryKey:["processor",e],queryFn:()=>n.getProcessor(e).details(r),enabled:!!e})},Ugs=()=>{const e=Ge(),{requestContext:t}=ys();return Sn({mutationFn:async({processorId:n,phase:r,messages:s,agentId:a})=>e.getProcessor(n).execute({phase:r,messages:s,agentId:a,requestContext:t})})};function QVt(){const{data:e}=zm(),{data:t}=Gy(),{data:n}=uh(),{data:r}=iY();return{agents:e,workflows:t,scorers:n,processors:r}}const YVt={agent:Ai,workflow:Bc,scorer:AC,processor:ID},KVt={agent:"Agent",workflow:"Workflow",scorer:"Scorer",processor:"Processor"},qgs="External (caller-run)";function XVt(e,{agents:t,workflows:n,scorers:r,processors:s}){const{targetType:a,targetId:i}=e;if(!i)return qgs;switch(a){case"agent":return t?.[i]?.name??i;case"workflow":return n?.[i]?.name??i;case"scorer":return r?.[i]?.scorer?.config?.name??i;case"processor":return s?.[i]?.name??i;default:return i}}function Vgs({experiment:e,datasetName:t,review:n}){const r=e.status??"pending",s=e.succeededCount??0,a=e.failedCount??0,i=e.totalItems??0;return o.jsxs(o.Fragment,{children:[o.jsx(he.Cell,{children:o.jsx(zgs,{experiment:e})}),o.jsx(he.Cell,{children:o.jsx(Bgs,{experiment:e})}),t!==void 0&&o.jsx(he.TextCell,{children:t}),o.jsx(he.Cell,{children:o.jsx(Hgs,{experiment:e})}),o.jsx(he.Cell,{children:o.jsx(xt,{variant:RUt[r]??"neutral",indicator:"dot",children:DT[r]??r})}),o.jsx(he.TextCell,{className:"text-center",children:i}),o.jsx(he.TextCell,{className:"text-center",children:s}),o.jsx(he.TextCell,{className:"text-center",children:o.jsx("span",{className:a>0?"text-accent2":"",children:a})}),o.jsx(he.Cell,{className:"text-center",children:o.jsx(Wgs,{review:n})}),o.jsx(he.TextCell,{children:Los(e.createdAt)})]})}function Hgs({experiment:e}){const t=QVt(),n=XVt(e,t),r=e.targetId?e.targetType:null,s=r?YVt[r]:null;return o.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 [&_svg]:size-3.5 [&_svg]:shrink-0",children:[s&&o.jsx("span",{className:"text-neutral3 flex",role:"img","aria-label":KVt[r],children:o.jsx(s,{})}),o.jsx("span",{className:r?"truncate":"text-neutral2 truncate",children:n})]})}function Wgs({review:e}){if(!e)return o.jsx("span",{className:"text-neutral2",children:"—"});const t=e.needsReview+e.complete;return t===0?o.jsx("span",{className:"text-neutral2",children:"—"}):e.needsReview>0?o.jsxs(xt,{size:"xs",variant:"yellow",children:[e.needsReview," pending"]}):o.jsxs(xt,{size:"xs",variant:"green",children:[e.complete,"/",t," reviewed"]})}const Gie=`${Pos} ${$os} ${Mos} ${Dos}`,Zgs=[{label:kv.experiment},{label:kv.description},{label:kv.dataset},{label:kv.target},{label:kv.status},{label:kv.items,className:"text-center"},{label:kv.succeeded,className:"text-center"},{label:kv.failed,className:"text-center"},{label:kv.review,className:"text-center"},{label:kv.date}];function Ggs({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:a="all",datasetFilter:i="all",selection:l}){const c=l!==void 0,{paths:u,Link:d}=un(),f=g.useMemo(()=>{const x=new Map;return t?.forEach(S=>x.set(S.id,S.name)),x},[t]),p=g.useMemo(()=>[...e].sort((x,S)=>{const k=x.createdAt?new Date(x.createdAt).getTime():0;return(S.createdAt?new Date(S.createdAt).getTime():0)-k}),[e]),h=g.useMemo(()=>{const x=s.toLowerCase();return p.filter(S=>{const k=S.datasetId?f.get(S.datasetId)??"":"",_=!x||S.id.toLowerCase().includes(x)||(S.name??"").toLowerCase().includes(x)||k.toLowerCase().includes(x)||(S.targetId??"").toLowerCase().includes(x),C=a==="all"||S.status===a,T=i==="all"||S.datasetId===i;return _&&C&&T})},[p,s,f,a,i]),{containerRef:m,getRowProps:v}=so({count:h.length});if(r)return o.jsx(Fo,{columns:Gie});const y=c?`auto ${Gie}`:Gie,b=Zgs.map(x=>o.jsx(he.TopCell,{className:x.className,children:x.label},x.label));return o.jsxs(he,{columns:y,scrollRef:m,children:[o.jsx(he.Top,{hasLeadingCell:c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(he.TopCell,{children:" "}),o.jsx(he.TopCells,{colStart:2,children:b})]}):b}),h.map((x,S)=>{const k=x.datasetId?f.get(x.datasetId)??h0(x.datasetId)??x.datasetId:"—",_=o.jsx(Vgs,{experiment:x,datasetName:k,review:n?.get(x.id)});if(!l)return o.jsx(he.RowLink,{to:u.experimentLink(x.id),LinkComponent:d,...v(S),children:_},x.id);const C=l.selectedExperimentIds.includes(x.id),T=()=>l.onToggleSelection(x.id);return o.jsxs(he.RowWrapper,{children:[o.jsx(he.SelectCell,{checked:C,onToggle:T,"aria-label":`Select experiment ${x.id}`}),o.jsx(he.RowButton,{colStart:2,featured:C,onClick:T,...v(S),children:_})]},x.id)})]})}const Qgs=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function Ygs(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const s8={completed:F7.neutral3,running:"#facc15",pending:"#fb923c",failed:"#f87171"},Kgs=[{label:"Completed",color:s8.completed},{label:"Running",color:s8.running},{label:"Pending",color:s8.pending},{label:"Failed",color:s8.failed}];function Xgs({experiments:e,datasets:t,isLoading:n,isError:r}){const{data:s,maxVal:a}=g.useMemo(()=>{if(!e||e.length===0)return{data:[],maxVal:0};const l=new Map;if(t)for(const f of t)l.set(f.id,f.name);const c=new Map;for(const f of e){const 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(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Experiments by Dataset",description:"Experiment status breakdown per dataset."}),i&&o.jsx(Vt.Summary,{value:String(e?.length??0),label:"Total experiments"})]}),n?o.jsx(Vt.Loading,{}):r?o.jsx(Vt.Error,{message:"Failed to load experiments data"}):o.jsx(Vt.Content,{children:i?o.jsx(QN,{data:s,segments:Kgs,maxVal:a,fmt:l=>String(l)}):o.jsx(Vt.NoData,{message:"No experiments have been run yet"})})]})}const Jgs=({onRunExperiment:e})=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx($c,{}),titleSlot:"No Experiments yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Run an experiment from a dataset to evaluate ",o.jsx("br",{}),"your agents and workflows."]}),actionSlot:o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e&&o.jsxs(le,{variant:"primary",onClick:e,children:[o.jsx(Mc,{}),"Run Experiment"]}),o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/evals/experiments",target:"_blank",rel:"noopener noreferrer",children:["Experiments Documentation ",o.jsx(ea,{})]})]})})});function evs({search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:i,onReset:l,hasActiveFilters:c,onRunClick:u,runTooltip:d="Run an experiment",onCompareClick:f,selection:p}){if(p){const{selectedCount:h,onExecuteCompare:m,onCancelSelection:v,compareDisabledReason:y}=p,b=h===2&&!y;return o.jsx("div",{className:"flex w-full items-center justify-end gap-4",children:o.jsxs("div",{className:"flex items-center gap-5",children:[o.jsxs("div",{className:"text-neutral3 flex items-center gap-2 pl-6 text-sm",children:[o.jsx(xt,{size:"md",variant:h<2?"red":"green",children:h}),o.jsx("span",{children:"of 2 experiments selected"}),y&&o.jsxs("span",{className:"text-accent2",children:["— ",y]}),o.jsx(wct,{})]}),o.jsxs(es,{children:[o.jsxs(le,{variant:"primary",disabled:!b,onClick:m,children:[o.jsx(Tj,{className:"h-4 w-4"}),"Compare Experiments"]}),o.jsx(le,{onClick:v,children:"Cancel"})]})]})})}return o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("div",{className:"max-w-120 min-w-64 flex-1",children:o.jsx(od,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t})}),o.jsxs(es,{children:[o.jsx(Ld,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...Qgs],value:n,onValueChange:r,className:"whitespace-nowrap"}),o.jsx(Ld,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:i,value:s,onValueChange:a,className:"whitespace-nowrap"}),l&&c&&o.jsxs(le,{onClick:l,size:"sm",variant:"default",children:[o.jsx(or,{className:"size-3"})," Reset"]})]}),o.jsxs(es,{className:"ml-auto shrink-0",children:[f&&o.jsxs(le,{onClick:f,tooltip:"Select two experiments of the same dataset to compare",children:[o.jsx(Tj,{}),"Compare"]}),u&&o.jsxs(le,{onClick:u,tooltip:d,variant:"primary",children:[o.jsx(Mc,{}),"Run Experiment"]})]})]})}const tvs={present:!1,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},dtt=e=>e?e instanceof Date?e.toISOString():e:null,ftt=e=>{const t=new Map;for(const n of e??[])t.set(n.itemId,n);return t},ptt=(e,t,n)=>{if(!e)return tvs;const r=new Map;for(const s of n??[])r.set(s.scorerId,s.reason??null);return{present:!0,output:e.output,metadata:t?.metadata??null,comment:t?.comment??null,error:t?.error??null,startedAt:dtt(t?.startedAt),completedAt:dtt(t?.completedAt),scores:Object.entries(e.scores).map(([s,a])=>({scorerId:s,value:a,reason:r.get(s)??null})).sort((s,a)=>s.scorerId.localeCompare(a.scorerId))}},nvs=({comparison:e,baselineId:t,contenderId:n,baselineResults:r,contenderResults:s,baselineScores:a,contenderScores:i})=>{if(!e)return[];const l=ftt(r),c=ftt(s);return e.items.map(u=>{const d=ptt(u.results[t],l.get(u.itemId),a?.[u.itemId]),f=ptt(u.results[n],c.get(u.itemId),i?.[u.itemId]),p={};for(const h of new Set([...d.scores,...f.scores].map(m=>m.scorerId))){const m=d.scores.find(y=>y.scorerId===h)?.value??null,v=f.scores.find(y=>y.scorerId===h)?.value??null;p[h]=m!=null&&v!=null?v-m:null}return{itemId:u.itemId,input:u.input,groundTruth:u.groundTruth,baseline:d,contender:f,deltas:p}})};function Rk({title:e,actions:t,tone:n="default",defaultOpen:r=!0,children:s}){return o.jsxs(Lc,{defaultOpen:r,className:"grid gap-2",children:[o.jsxs("div",{className:"flex min-h-6 items-center justify-between gap-2",children:[o.jsxs(fc,{className:K("text-ui-md flex items-center gap-1.5 font-semibold [&>svg]:size-4",n==="negative"?"text-negative1":"text-neutral5"),children:[o.jsx(Br,{}),e]}),t]}),o.jsx(pc,{role:"region","aria-label":e,children:s})]})}function htt({label:e,value:t}){return t==null?null:o.jsx(Rk,{title:e,defaultOpen:!1,children:o.jsx("pre",{className:"text-ui-sm text-neutral4 bg-surface3 max-h-40 overflow-auto rounded-md p-3 whitespace-pre-wrap",children:typeof t=="string"?t:JSON.stringify(t,null,2)})})}function JVt({delta:e}){const t=e>0?"text-positive1":e<0?"text-negative1":"text-neutral3";return o.jsxs("span",{className:K("inline-flex min-w-20 items-center gap-1 font-mono text-sm",t),children:[o.jsx("span",{className:"inline-block w-3",children:e>0?"+":e<0?"-":""}),Math.abs(e).toFixed(2),e>0?o.jsx(pQt,{className:"size-3.5"}):e<0?o.jsx(rQt,{className:"size-3.5"}):null]})}function eHt({scorerId:e,value:t,delta:n,reason:r}){const{Link:s,paths:a}=un();return o.jsxs("div",{className:"bg-surface2 grid gap-1 rounded-lg px-3 py-2",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4",children:[o.jsxs(s,{href:a.scorerLink(e),"aria-label":`Open ${e}`,className:"text-neutral5 flex min-w-0 items-center gap-1.5 text-sm font-medium hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[o.jsx(AC,{}),o.jsx("span",{className:"min-w-0 truncate",children:e})]}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:"text-neutral3 font-mono text-sm",children:t!=null?t.toFixed(2):"-"}),n!=null&&o.jsx(JVt,{delta:n})]})]}),r&&o.jsx("p",{className:"text-neutral3 text-sm",children:r})]})}function mtt(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function rvs(e){if(!e.startedAt||!e.completedAt)return null;const t=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return Number.isFinite(t)?`${(t/1e3).toFixed(2)}s`:null}const svs="border-border1 bg-surface3 text-ui-md text-neutral4 max-h-[30vh] overflow-y-auto rounded-xl border p-4 font-mono break-all whitespace-pre-wrap dark:border-white/10 dark:bg-black/20";function gtt({side:e,row:t,showDeltas:n,isLoading:r}){const s=t[e],a=rvs(s);if(r)return o.jsx("div",{className:"flex h-32 items-center justify-center",children:o.jsx(Ut,{})});if(!s.present)return o.jsx("p",{className:"text-neutral3 py-8 text-center text-sm",children:"Not present in this experiment"});const i=mtt(s.output);return o.jsxs("div",{className:"grid content-start gap-5",children:[a&&o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsxs("p",{className:"text-neutral3 flex items-center justify-end gap-1.5 text-sm [&>svg]:size-3.5",children:[o.jsx(a1,{}),a]})}),o.jsx(yn,{children:"Run duration"})]}),s.error?o.jsx(Rk,{title:"Error",tone:"negative",actions:o.jsx(ka,{content:s.error.message}),children:o.jsx("p",{className:"border-negative1/40 bg-negative1/5 text-ui-md text-neutral4 rounded-xl border p-4 break-words",children:s.error.message})}):o.jsx(Rk,{title:"Output",actions:o.jsx(ka,{content:i}),children:o.jsx("pre",{className:svs,children:i})}),s.scores.length>0&&o.jsx(Rk,{title:"Scores",children:o.jsx("div",{className:"grid gap-2",children:s.scores.map(l=>o.jsx(eHt,{scorerId:l.scorerId,value:l.value,delta:n?t.deltas[l.scorerId]:null,reason:l.reason},l.scorerId))})}),s.comment&&o.jsx(Rk,{title:"Comment",defaultOpen:!1,children:o.jsx("p",{className:"text-neutral3 text-sm",children:s.comment})}),s.metadata&&Object.keys(s.metadata).length>0&&o.jsx(Rk,{title:"Metadata",defaultOpen:!1,children:o.jsx("dl",{className:"grid gap-1",children:Object.entries(s.metadata).map(([l,c])=>o.jsxs("div",{className:"flex items-start justify-between gap-4 text-sm",children:[o.jsx("dt",{className:"text-neutral3",children:l}),o.jsx("dd",{className:"text-neutral5 font-mono break-all",children:mtt(c)})]},l))})})]})}const avs={baseline:"Baseline",contender:"Contender"},ivs={baseline:"purple",contender:"blue"},ovs="flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0";function vtt({side:e,experiment:t,summary:n,showDeltas:r,versionMismatch:s}){const{Link:a,paths:i}=un(),l=avs[e],c=t?h0(t.id)??t.id:null,u=t?.createdAt?new Date(t.createdAt):null,d=n??[];return o.jsxs("div",{className:"grid content-start gap-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(xt,{variant:ivs[e],size:"xs",children:l}),t&&o.jsx(le,{as:a,size:"xs",href:`/experiments/${t.id}`,"aria-label":`Open experiment ${t.name||c}`,children:o.jsx("span",{className:"min-w-0 truncate",children:t.name||c})})]}),t&&o.jsxs("div",{className:"text-ui-sm text-neutral3 flex flex-wrap gap-x-4 gap-y-1",children:[t.name&&o.jsxs(Pl,{children:[o.jsx(AV,{})," ",c]}),t.targetType==="agent"&&t.targetId?o.jsxs(a,{href:i.agentLink(t.targetId),className:ovs,children:[o.jsx(Ai,{}),o.jsx("span",{className:"min-w-0 truncate",children:t.targetId})]}):o.jsxs(Pl,{children:[o.jsx(jct,{})," ",t.targetId]}),o.jsx("span",{className:K(s&&"text-accent6"),children:o.jsxs(Pl,{children:[o.jsx(RV,{})," v",t.datasetVersion??"—",s&&" · different dataset version"]})}),u&&o.jsxs(Pl,{children:[o.jsx(U9,{})," ",dr(u,"MMM d, yyyy HH:mm")]})]}),d.length>0&&o.jsx(Rk,{title:"Overall score",children:o.jsx("div",{className:"grid gap-2",children:d.map(({scorerId:f,average:p,delta:h})=>o.jsx(eHt,{scorerId:f,value:p,delta:r?h:null},f))})})]})}const qE="min-w-0 px-4 py-3";function lvs({datasetId:e,experimentIdA:t,experimentIdB:n}){const{Link:r,paths:s}=un(),{data:a,isLoading:i,error:l}=mhs(e,t,n),{data:c}=WD(e,t),{data:u}=WD(e,n),d=c&&u&&c.datasetVersion!==u.datasetVersion,f=a?.baselineId??t,p=t===f?n:t,h=c?.id===f?c:u,m=c?.id===p?c:u,{data:v,isLoading:y}=ZD({datasetId:e,experimentId:f,experimentStatus:h?.status}),{data:b,isLoading:x}=ZD({datasetId:e,experimentId:p,experimentStatus:m?.status}),{data:S}=C_(f,h?.status),{data:k}=C_(p,m?.status),_=g.useMemo(()=>nvs({comparison:a,baselineId:f,contenderId:p,baselineResults:v,contenderResults:b,baselineScores:S,contenderScores:k}),[a,f,p,v,b,S,k]),C=g.useMemo(()=>[...new Set(_.flatMap(E=>Object.keys(E.deltas)))].sort(),[_]),T=g.useMemo(()=>{const E=(A,R)=>{const L=_.map(M=>M[A].scores.find(F=>F.scorerId===R)?.value).filter(M=>M!=null);return L.length>0?L.reduce((M,F)=>M+F,0)/L.length:null},N=C.map(A=>({scorerId:A,average:E("baseline",A),delta:null})),I=C.map(A=>{const R=E("baseline",A),L=E("contender",A);return{scorerId:A,average:L,delta:R!=null&&L!=null?L-R:null}});return{baseline:N,contender:I}},[_,C]);return i?o.jsx("div",{className:"flex h-64 items-center justify-center",children:o.jsx(Ut,{})}):l?o.jsx(Rn,{variant:"warning",title:"Error loading comparison",children:o.jsx(Rn.Message,{children:l instanceof Error?l.message:"Unknown error"})}):!a||a.items.length===0?o.jsx("div",{className:"text-neutral4 py-8 text-center text-sm",children:"No comparison data"}):o.jsx("div",{className:"grid gap-4",children:o.jsxs("div",{role:"table","aria-label":"Experiments comparison",className:"grid",children:[o.jsxs("div",{role:"row",className:"border-border1 grid border-y xl:grid-cols-[minmax(20rem,24rem)_1fr_1fr] xl:divide-x xl:divide-[var(--border1)]",children:[o.jsx("div",{role:"columnheader","aria-label":"Items",className:`${qE} text-neutral3 text-ui-sm uppercase`,children:"Items"}),o.jsx("div",{role:"columnheader","aria-label":"Baseline",className:qE,children:o.jsx(vtt,{side:"baseline",experiment:h,summary:T.baseline,versionMismatch:d})}),o.jsx("div",{role:"columnheader","aria-label":"Contender",className:qE,children:o.jsx(vtt,{side:"contender",experiment:m,summary:T.contender,versionMismatch:d,showDeltas:!0})})]}),_.map(E=>{const N=Object.entries(E.deltas).filter(([,I])=>I!=null&&I!==0);return o.jsxs("div",{role:"row","aria-label":E.itemId,className:"border-border1 grid border-b xl:grid-cols-[minmax(20rem,24rem)_1fr_1fr] xl:divide-x xl:divide-[var(--border1)]",children:[o.jsxs("div",{role:"cell",className:`${qE} grid content-start gap-1`,children:[o.jsx(r,{href:s.datasetItemLink(e,E.itemId),"aria-label":`Open item ${E.itemId}`,className:K("text-ui-sm flex items-start gap-1.5 font-mono break-all hover:underline [&>svg]:mt-0.5 [&>svg]:size-3.5 [&>svg]:shrink-0",E.baseline.present&&E.contender.present?"text-neutral4":"text-neutral1"),children:o.jsx("span",{className:"min-w-0",children:E.itemId})}),N.length>0&&o.jsx("span",{className:"flex flex-wrap items-center gap-2",children:N.map(([I,A])=>o.jsx(JVt,{delta:A},I))}),o.jsxs("div",{className:"grid pt-3",children:[o.jsx(htt,{label:"Input",value:E.input}),o.jsx(htt,{label:"Ground truth",value:E.groundTruth})]})]}),o.jsx("div",{role:"cell","aria-label":"Baseline",className:qE,children:o.jsx(gtt,{side:"baseline",row:E,isLoading:y})}),o.jsx("div",{role:"cell","aria-label":"Contender",className:qE,children:o.jsx(gtt,{side:"contender",row:E,isLoading:x,showDeltas:!0})})]},E.itemId)})]})})}const cvs=100;function oY(e){const t=Ge(),n={perPage:cvs};return mt({queryKey:e?["dataset-experiments",e,n]:["experiments",n],queryFn:()=>e?t.listDatasetExperiments(e,n):t.listExperiments(n)})}const tHt=(e,t)=>{const n=Ge(),{data:r,isLoading:s}=oY(void 0),a=r?.experiments,i=t?a?.filter(c=>c.id===t):a,l=mt({queryKey:["review-items",e,t??"all",i?.map(c=>c.id)],queryFn:async()=>!i||i.length===0?[]:(await Promise.all(i.map(async u=>{if(!u.datasetId)return[];try{const{results:d}=await n.listDatasetExperimentResults(u.datasetId,u.id);return d.filter(f=>f.status===e).map(f=>({id:f.id,input:f.input,output:f.output,error:f.error,itemId:f.itemId,experimentId:f.experimentId,datasetId:u.datasetId??void 0,traceId:f.traceId??void 0,scores:f.scores?Object.fromEntries(f.scores.map(p=>[p.scorerId,p.score??0])):{},tags:f.tags??[],comment:f.comment??""}))}catch{return[]}}))).flat(),enabled:!!a,refetchOnWindowFocus:!1});return{...l,isLoading:l.isLoading||s}},uvs=({experimentId:e}={})=>tHt("needs-review",e),dvs=({experimentId:e}={})=>tHt("complete",e);function fvs(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 pvs({datasetId:e,experimentId:t,featuredItemId:n,detailPanelVariant:r="inline"}){const s=Ge(),{data:a}=My(e??""),{data:i,isLoading:l}=uvs({experimentId:t}),{data:c,isLoading:u}=dvs({experimentId:t}),{updateExperimentResult:d}=bi(),[f,p]=g.useState(n??null);g.useEffect(()=>{n!==void 0&&p(n)},[n]);const[h,m]=g.useState(null),[v,y]=g.useState(new Set),[b,x]=g.useState(!1),[S,k]=g.useState(!1),[_,C]=g.useState(!1),[T,E]=g.useState(""),[N,I]=g.useState(""),[A,R]=g.useState(""),[L,M]=g.useState([]),[F,H]=g.useState(!1),[z,q]=g.useState({}),V=g.useMemo(()=>(i??[]).map(Ie=>Ie.id in z?{...Ie,rating:z[Ie.id]}:Ie),[i,z]),D=g.useMemo(()=>{const Ie=new Set;if(a?.tags)for(const Xe of a.tags)Ie.add(Xe);for(const Xe of V)for(const Qe of Xe.tags)Ie.add(Qe);return[...Ie].sort()},[a,V]),G=g.useCallback(Ie=>{!a||!e||(a.tags??[]).includes(Ie)},[a,e]),U=g.useMemo(()=>h?h==="__untagged__"?V.filter(Ie=>Ie.tags.length===0):V.filter(Ie=>Ie.tags.includes(h)):V,[V,h]),P=g.useMemo(()=>{const Ie=new Map;for(const Xe of V)for(const Qe of Xe.tags)Ie.set(Qe,(Ie.get(Qe)??0)+1);return[...Ie.entries()].sort((Xe,Qe)=>Qe[1]-Xe[1])},[V]),B=g.useMemo(()=>V.filter(Ie=>Ie.tags.length===0).length,[V]),Z=g.useMemo(()=>{let Ie=0;return h&&Ie++,b&&Ie++,Ie},[h,b]),Y=g.useCallback((Ie,Xe)=>{const Qe=V.find(Se=>Se.id===Ie);Qe?.experimentId&&Qe?.datasetId&&d.mutate({datasetId:Qe.datasetId,experimentId:Qe.experimentId,resultId:Qe.id,tags:Xe})},[V,d]),te=g.useCallback((Ie,Xe)=>{const Qe=V.find(Se=>Se.id===Ie);Qe?.traceId&&Xe!==void 0&&s.createFeedback({feedback:{traceId:Qe.traceId,source:"studio",feedbackSource:"studio",feedbackType:"rating",value:Xe==="positive"?1:-1,reviewStatus:"reviewed",experimentId:Qe.experimentId??void 0,sourceId:Qe.id}}).catch(()=>{}),q(Se=>({...Se,[Ie]:Xe}))},[V,s]),J=g.useCallback((Ie,Xe)=>{const Qe=V.find(Se=>Se.id===Ie);Qe?.experimentId&&Qe?.datasetId&&d.mutate({datasetId:Qe.datasetId,experimentId:Qe.experimentId,resultId:Qe.id,comment:Xe}),Qe?.traceId&&s.createFeedback({feedback:{traceId:Qe.traceId,source:"studio",feedbackSource:"studio",feedbackType:"comment",value:Xe,comment:Xe,reviewStatus:"reviewed",experimentId:Qe.experimentId??void 0,sourceId:Qe.id}}).catch(()=>{})},[V,s,d]),ee=g.useCallback(Ie=>{const Xe=V.find(Qe=>Qe.id===Ie);y(Qe=>{const Se=new Set(Qe);return Se.delete(Ie),Se}),f===Ie&&p(null),Xe?.experimentId&&Xe?.datasetId&&d.mutate({datasetId:Xe.datasetId,experimentId:Xe.experimentId,resultId:Xe.id,status:null})},[V,d,f]),re=g.useCallback(Ie=>{const Xe=V.find(Qe=>Qe.id===Ie);y(Qe=>{const Se=new Set(Qe);return Se.delete(Ie),Se}),f===Ie&&p(null),Xe?.experimentId&&Xe?.datasetId&&d.mutate({datasetId:Xe.datasetId,experimentId:Xe.experimentId,resultId:Xe.id,status:"complete"})},[V,d,f]),oe=g.useMemo(()=>{const Ie=b?c??[]:U;return!b||!h?Ie:h==="__untagged__"?Ie.filter(Xe=>Xe.tags.length===0):Ie.filter(Xe=>Xe.tags.includes(h))},[b,c,U,h]),X=b?u:!1,ne=g.useMemo(()=>new Set(oe.map(Ie=>Ie.id)),[oe]),se=g.useMemo(()=>[...v].filter(Ie=>ne.has(Ie)).length,[v,ne]),fe=oe.length>0&&se===oe.length,ce=se>0&&!fe,xe=g.useCallback(Ie=>{y(Xe=>{const Qe=new Set(Xe);return Qe.has(Ie)?Qe.delete(Ie):Qe.add(Ie),Qe})},[]),pe=g.useCallback(()=>{y(fe?new Set:new Set(oe.map(Ie=>Ie.id)))},[fe,oe]),we=g.useCallback(Ie=>{for(const Xe of v){const Qe=V.find(Se=>Se.id===Xe);Qe&&!Qe.tags.includes(Ie)&&Y(Xe,[...Qe.tags,Ie])}},[V,v,Y]),Ne=g.useCallback(Ie=>{for(const Xe of v){const Qe=V.find(Se=>Se.id===Xe);Qe&&Qe.tags.includes(Ie)&&Y(Xe,Qe.tags.filter(Se=>Se!==Ie))}},[V,v,Y]),Pe=g.useCallback(()=>{for(const Ie of v)re(Ie);y(new Set)},[v,re]),Re=g.useCallback(()=>{for(const Ie of v)ee(Ie);y(new Set)},[v,ee]),Ae=g.useCallback(()=>{E(""),C(!0)},[]),ae=g.useCallback(async()=>{if(!(!N||!A)){k(!0),C(!1);try{const Ie=V.filter(Qe=>v.has(Qe.id));if(Ie.length===0){k(!1);return}const Xe=await s.clusterFailures({modelId:`${N}/${A}`,items:Ie.map(Qe=>({id:Qe.id,input:Qe.input,output:Qe.output??void 0,error:typeof Qe.error=="string"?Qe.error:Qe.error?String(Qe.error):void 0,scores:Qe.scores,existingTags:Qe.tags.length>0?Qe.tags:void 0})),availableTags:D.length>0?D:void 0,prompt:T||void 0});Xe.proposedTags&&Xe.proposedTags.length>0&&(M(Xe.proposedTags.map(Qe=>({...Qe,accepted:!0}))),H(!0))}catch(Ie){console.error("Analysis failed:",Ie)}finally{k(!1)}}},[N,A,V,v,s,D,T]),me=g.useCallback(()=>{for(const Ie of L){if(!Ie.accepted)continue;const Xe=V.find(Qe=>Qe.id===Ie.itemId);if(Xe){const Qe=[...new Set([...Xe.tags,...Ie.tags])];Y(Xe.id,Qe)}}H(!1)},[L,V,Y]),ue=g.useCallback(Ie=>{p(Xe=>Xe===Ie?null:Ie)},[]),be=g.useMemo(()=>f?oe.find(Ie=>Ie.id===f)??null:null,[f,oe]),_e=f?oe.findIndex(Ie=>Ie.id===f):-1,ye=_e>0?()=>p(oe[_e-1].id):void 0,Ce=_e>=0&&_e<oe.length-1?()=>p(oe[_e+1].id):void 0,Be="auto minmax(0,20rem) minmax(0,1fr) minmax(0,8rem) 6rem 6rem",{containerRef:De,getRowProps:He}=so({count:oe.length});if(l)return o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(Ut,{className:"h-6 w-6"})});const et=be?o.jsx(MUt,{className:"h-full",item:be,isCompleted:b,tagVocabulary:D,onRate:Ie=>te(be.id,Ie),onSetTags:Ie=>{Y(be.id,Ie);for(const Xe of Ie)D.includes(Xe)||G(Xe)},onComment:Ie=>J(be.id,Ie),onRemove:()=>ee(be.id),onComplete:b?void 0:()=>re(be.id),onPrevious:ye,onNext:Ce,onClose:()=>p(null)}):null;return o.jsxs("div",{className:K("flex h-full min-h-0 flex-1",r==="overlay"?"overflow-visible":"overflow-hidden"),children:[o.jsx(hr,{open:_,onOpenChange:C,children:o.jsxs(mr,{children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Analyze Items"}),o.jsx(Cs,{children:"Use an LLM to automatically suggest tags for the selected items."})]}),o.jsxs("div",{className:"space-y-4 py-2",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx(Pt,{className:"mb-1 block text-xs",children:"Provider"}),o.jsx(Wy,{value:N,onValueChange:I})]}),o.jsxs("div",{children:[o.jsx(Pt,{className:"mb-1 block text-xs",children:"Model"}),o.jsx(Zy,{llmId:N,value:A,onValueChange:R})]})]}),o.jsxs(ve,{variant:"ui-xs",className:"text-neutral3",children:[v.size," item",v.size!==1?"s":""," will be analyzed"]}),o.jsxs("div",{children:[o.jsx(Pt,{className:"text-xs",children:"Instructions (optional)"}),o.jsx(il,{value:T,onChange:Ie=>E(Ie.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3,className:"mt-1 text-xs"})]})]}),o.jsxs(Ul,{children:[o.jsx(le,{variant:"outline",onClick:()=>C(!1),children:"Cancel"}),o.jsxs(le,{onClick:ae,disabled:!N||!A||S,children:[S?o.jsx(Ut,{className:"mr-1 h-4 w-4"}):null,"Analyze"]})]})]})}),o.jsx(hr,{open:F,onOpenChange:H,children:o.jsxs(mr,{className:"max-h-[80vh] max-w-2xl overflow-y-auto",children:[o.jsxs(gr,{children:[o.jsx(ur,{children:"Review Proposed Tags"}),o.jsxs(Cs,{children:[L.filter(Ie=>Ie.accepted).length," of ",L.length," proposals selected"]})]}),o.jsx("div",{className:"space-y-3 py-2",children:L.map((Ie,Xe)=>{const Qe=V.find(Se=>Se.id===Ie.itemId);return o.jsx("div",{className:K("p-3 border rounded-lg",!Ie.accepted&&"opacity-50"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(Oo,{checked:Ie.accepted,onCheckedChange:Se=>M(Te=>Te.map((Le,qe)=>qe===Xe?{...Le,accepted:!!Se}:Le))}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(ve,{variant:"ui-xs",className:"text-neutral4 block truncate",children:Qe?typeof Qe.input=="string"?Qe.input.slice(0,100):JSON.stringify(Qe.input).slice(0,100):Ie.itemId}),o.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:Ie.tags.map((Se,Te)=>o.jsx(LUt,{tag:Se,onRename:Le=>M(qe=>qe.map((tt,It)=>It===Xe?{...tt,tags:tt.tags.map((Ee,Je)=>Je===Te?Le:Ee)}:tt)),onRemove:()=>M(Le=>Le.map((qe,tt)=>tt===Xe?{...qe,tags:qe.tags.filter((It,Ee)=>Ee!==Te)}:qe))},`${Se}-${Te}`))}),Ie.reason&&o.jsx(ve,{variant:"ui-xs",className:"text-neutral3 mt-1 block italic",children:Ie.reason})]})]})},Ie.itemId)})}),o.jsxs(Ul,{children:[o.jsx(le,{variant:"outline",onClick:()=>H(!1),children:"Cancel"}),o.jsxs(le,{onClick:me,disabled:L.filter(Ie=>Ie.accepted).length===0,children:["Accept ",L.filter(Ie=>Ie.accepted).length," proposals"]})]})]})}),o.jsxs("div",{className:K("grid h-full min-h-0 w-full grid-cols-1 gap-4",r==="overlay"?"overflow-visible":"overflow-hidden",be&&r==="inline"&&"grid-cols-[1fr_1fr]"),children:[o.jsxs("div",{className:"grid min-h-0 w-full grid-rows-[auto_1fr] gap-3 overflow-hidden pt-3",children:[(V.length>0||Z>0)&&o.jsxs("div",{className:"flex w-full flex-wrap items-center justify-start gap-3",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs(at,{children:[o.jsx(at.Trigger,{asChild:!0,children:o.jsxs(le,{size:"sm",children:[o.jsx(O0e,{}),"Filter",Z>0&&o.jsx(xt,{size:"xs",children:Z})]})}),o.jsxs(at.Content,{align:"start",className:K("min-w-48"),children:[o.jsxs(at.Sub,{children:[o.jsxs(at.SubTrigger,{children:["Status",b&&o.jsx("span",{className:K("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(at.SubContent,{children:[o.jsx(at.CheckboxItem,{checked:!b,onCheckedChange:()=>{x(!1),p(null)},onSelect:Ie=>Ie.preventDefault(),children:"Review Queue"}),o.jsx(at.CheckboxItem,{checked:b,onCheckedChange:()=>{x(!0),p(null)},onSelect:Ie=>Ie.preventDefault(),children:"Completed"})]})]}),o.jsxs(at.Sub,{children:[o.jsxs(at.SubTrigger,{children:["Tags",h&&o.jsx("span",{className:K("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(at.SubContent,{children:[o.jsx(at.CheckboxItem,{checked:!h,onCheckedChange:()=>m(null),onSelect:Ie=>Ie.preventDefault(),children:"All"}),B>0&&o.jsx(at.CheckboxItem,{checked:h==="__untagged__",onCheckedChange:()=>m(h==="__untagged__"?null:"__untagged__"),onSelect:Ie=>Ie.preventDefault(),children:"Untagged"}),P.length>0&&o.jsx(at.Separator,{}),P.map(([Ie])=>o.jsx(at.CheckboxItem,{checked:h===Ie,onCheckedChange:()=>m(h===Ie?null:Ie),onSelect:Xe=>Xe.preventDefault(),children:Ie},Ie))]})]}),Z>0&&o.jsxs(o.Fragment,{children:[o.jsx(at.Separator,{}),o.jsxs(at.Item,{onSelect:()=>{m(null),x(!1),p(null)},children:[o.jsx(or,{}),"Clear all filters"]})]})]})]}),Z>0&&o.jsxs(le,{size:"sm",onClick:()=>{m(null),x(!1),p(null)},children:[o.jsx(or,{}),"Reset"]})]}),!b&&v.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(DUt,{selectedCount:v.size,vocabulary:D,onApplyTag:we,onRemoveTag:Ne,onNewTag:Ie=>we(Ie)}),o.jsxs(at,{children:[o.jsx(at.Trigger,{asChild:!0,children:o.jsxs(le,{size:"sm",disabled:S,children:[S?o.jsx(Ut,{className:"h-4 w-4"}):o.jsx(We,{size:"sm",children:o.jsx(Xs,{})}),"Actions"]})}),o.jsxs(at.Content,{align:"end",children:[o.jsxs(at.Item,{onSelect:Pe,children:[o.jsx(We,{size:"sm",children:o.jsx(wO,{})}),"Complete"]}),o.jsxs(at.Item,{onSelect:Re,children:[o.jsx(We,{size:"sm",children:o.jsx(Fl,{})}),"Remove"]}),o.jsx(at.Separator,{}),o.jsxs(at.Item,{onSelect:Ae,children:[o.jsx(We,{size:"sm",children:o.jsx($g,{})}),"Analyze"]})]})]})]})]}),X?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(Ut,{className:"h-6 w-6"})}):oe.length===0?o.jsx("div",{className:"flex h-full items-center justify-center py-12",children:o.jsx(br,{iconSlot:o.jsx(Q1,{className:"text-neutral3 h-8 w-8"}),titleSlot:b?"No completed reviews yet":"No items to review",descriptionSlot:b?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here."})}):o.jsxs(he,{columns:Be,fit:"container",className:"min-w-0",scrollRef:De,children:[o.jsxs(he.Top,{hasLeadingCell:!0,children:[b?o.jsx(he.TopCell,{children:" "}):o.jsx(he.TopSelectCell,{checked:fe?!0:ce?"indeterminate":!1,onToggle:()=>pe(),"aria-label":"Select all"}),o.jsxs(he.TopCells,{colStart:2,children:[o.jsx(he.TopCell,{children:"Input"}),o.jsx(he.TopCell,{children:"Comment"}),o.jsx(he.TopCell,{children:"Tags"}),o.jsx(he.TopCell,{children:"Rating"}),o.jsx(he.TopCell,{children:"Scores"})]})]}),oe.map((Ie,Xe)=>{const Qe=Ie.scores?Object.entries(Ie.scores):[],Se=f===Ie.id,Te=o.jsxs(o.Fragment,{children:[o.jsx(he.Cell,{className:"text-neutral4 min-w-0",children:o.jsx("span",{className:"block truncate",children:fvs(Ie.input,200)})}),o.jsx(he.Cell,{className:"min-w-0",children:Ie.comment?o.jsx(ve,{variant:"ui-xs",className:"text-neutral3 truncate",children:Ie.comment}):o.jsx(ve,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsx(he.Cell,{className:"min-w-0",children:Ie.tags.length>0?o.jsx(ve,{variant:"ui-xs",className:"text-neutral4 truncate",children:Ie.tags.join(", ")}):o.jsx(ve,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsxs(he.Cell,{children:[Ie.rating==="positive"&&o.jsx(We,{size:"sm",className:"text-positive1",children:o.jsx(M0e,{})}),Ie.rating==="negative"&&o.jsx(We,{size:"sm",className:"text-negative1",children:o.jsx($0e,{})}),!Ie.rating&&o.jsx(ve,{variant:"ui-xs",className:"text-neutral2",children:"—"})]}),o.jsx(he.Cell,{children:Qe.length>0?o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(We,{size:"sm",className:"text-neutral3",children:o.jsx(Gp,{})}),o.jsx(ve,{variant:"ui-xs",className:"text-neutral4 font-mono",children:Qe[0][1].toFixed(2)}),Qe.length>1&&o.jsxs(xt,{children:["+",Qe.length-1]})]}):o.jsx(ve,{variant:"ui-xs",className:"text-neutral2",children:"—"})})]});return o.jsxs(he.RowWrapper,{children:[b?o.jsx(he.Cell,{className:"justify-items-center px-4",children:o.jsx("div",{role:"img","aria-label":Ie.error?"Error":"Success",title:Ie.error?"Error":"Success",className:K("w-2 h-2 rounded-full",Ie.error?"bg-red-700":"bg-green-600")})}):o.jsx(he.SelectCell,{checked:v.has(Ie.id),onToggle:()=>xe(Ie.id),"aria-label":`Select item ${Ie.id}`}),o.jsx(he.RowButton,{colStart:2,featured:Se,onClick:()=>ue(Ie.id),...He(Xe),children:Te})]},Ie.id)})]})]}),et&&(r==="overlay"?o.jsx(aY,{label:`Review item ${be?.id??""}`,children:et}):et)]})]})}const ytt={needsReview:"#facc15",complete:"#22c55e"},hvs=[{label:"Needs Review",color:ytt.needsReview},{label:"Reviewed",color:ytt.complete}];function mvs({reviewSummary:e,experiments:t,datasets:n,isLoading:r,isError:s}){const{data:a,maxVal:i,totalInPipeline:l}=g.useMemo(()=>{if(!e?.counts||!t)return{data:[],maxVal:0,totalInPipeline:0};const u=new Map;for(const m of t)u.set(m.id,m);const d=new Map;if(n)for(const m of n)d.set(m.id,m.name);let f=0,p=0;const h=[];for(const m of e.counts){const v=m.needsReview+m.complete;if(v===0)continue;p+=v,v>f&&(f=v);const y=u.get(m.experimentId),b=y?.datasetId?d.get(y.datasetId):void 0,x=b?`${b} · ${m.experimentId.slice(0,8)}`:m.experimentId.slice(0,8);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(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Review Pipeline",description:"Items in review across experiments."}),c&&o.jsx(Vt.Summary,{value:String(l),label:"Items in pipeline"})]}),r?o.jsx(Vt.Loading,{}):s?o.jsx(Vt.Error,{message:"Failed to load review data"}):o.jsx(Vt.Content,{children:c?o.jsx(QN,{data:a,segments:hvs,maxVal:i,fmt:u=>String(u)}):o.jsx(Vt.NoData,{message:"No items have been sent to review yet"})})]})}function nHt(){const e=Ge();return mt({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function gvs(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 vvs(e){return e?.counts?e.counts.reduce((t,n)=>({needsReview:t.needsReview+n.needsReview,complete:t.complete+n.complete,inPipeline:t.inPipeline+n.needsReview+n.complete}),{needsReview:0,complete:0,inPipeline:0}):{needsReview:0,complete:0,inPipeline:0}}function yvs(){const[e,t]=g.useState("all"),[n,r]=g.useState({}),{data:s,isLoading:a,error:i}=uh(),{data:l,isLoading:c,error:u}=Qg(),{data:d,isLoading:f,error:p}=UH(),{data:h,isLoading:m,isError:v,error:y}=pUr(n),{data:b,isLoading:x,isError:S,error:k}=nHt(),_=l?.datasets,C=d?.experiments,T=g.useMemo(()=>vvs(b),[b]),E=i||u||p||y||k;return E&&ps(E)?o.jsx(Zn,{children:o.jsx(Ts,{})}):E&&hs(E)?o.jsx(Zn,{children:o.jsx(Os,{resource:"evaluation"})}):E?o.jsx(Zn,{children:o.jsx($a,{title:"Failed to load evaluation data",message:E.message})}):o.jsxs(Lt,{width:"wide",height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(Lt.Row,{children:o.jsx(Lt.Column,{children:o.jsx(W4,{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(s0e,{children:o.jsx(Lgs,{scorers:s,datasets:_,experiments:C,avgScore:h?.avgScore??null,prevAvgScore:h?.prevAvgScore??null,totalNeedsReview:T.needsReview,isLoadingScorers:a,isLoadingDatasets:c,isLoadingExperiments:f,isLoadingScores:m,isLoadingReview:x})}),o.jsx(_Br,{summaryData:h?.summaryData??[],overTimeData:h?.overTimeData??[],scorerNames:h?.scorerNames??[],avgScore:h?.avgScore??null,isLoading:m,isError:v}),o.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:[o.jsx(Bhs,{experiments:C,isLoading:f,isError:!!p}),o.jsx(Xgs,{experiments:C,datasets:_,isLoading:f,isError:!!p})]}),o.jsx(mvs,{reviewSummary:b,experiments:C,datasets:_,isLoading:x,isError:!!S})]})]})}function bvs(){const[e,t]=g.useState(""),[n,r]=g.useState("all"),[s,a]=g.useState(!1),[i,l]=g.useState(!1),[c,u]=g.useState([]),d=Vr(),[f,p]=Ma(),h=f.get("dataset")??"all",m=g.useCallback(G=>{p(U=>{const P=new URLSearchParams(U);return G==="all"?P.delete("dataset"):P.set("dataset",G),P},{replace:!0})},[p]),{data:v,isLoading:y,error:b}=Qg(),{data:x,isLoading:S,error:k}=oY(h==="all"?void 0:h),{data:_}=nHt(),C=g.useMemo(()=>v?.datasets??[],[v?.datasets]),T=g.useMemo(()=>x?.experiments??[],[x?.experiments]),E=g.useMemo(()=>Ygs(C),[C]),N=g.useMemo(()=>gvs(_),[_]),I=y||S,A=k||b,R=G=>{u(U=>U.includes(G)?U.filter(P=>P!==G):U.length>=2?[U[0],G]:[...U,G])},L=()=>{u([]),l(!1)},{selectedIds:M,selectedDatasetIds:F}=g.useMemo(()=>{const G=new Map(T.map(P=>[P.id,P.datasetId])),U=c.filter(P=>G.has(P));return{selectedIds:U,selectedDatasetIds:new Set(U.map(P=>G.get(P)))}},[T,c]),H=M.length===2&&F.size!==1?"experiments must belong to the same dataset":void 0,z=()=>{if(M.length!==2||H)return;const[G,U]=M,[P]=F;if(!P)return;const B=new URLSearchParams({dataset:P,baseline:G,contender:U});d(`/experiments/compare?${B.toString()}`)};if(A&&ps(A))return o.jsx(Zn,{children:o.jsx(Ts,{})});if(k&&hs(k))return o.jsx(Zn,{children:o.jsx(Os,{resource:"experiments"})});if(b&&hs(b))return o.jsx(Zn,{children:o.jsx(Os,{resource:"datasets"})});if(A)return o.jsx(Zn,{children:o.jsx($a,{title:"Failed to load experiments",message:A.message})});const q=o.jsx(sY,{open:s,onOpenChange:a,onSuccess:G=>{d(`/experiments/${G}`)}});if(T.length===0&&!I&&h==="all")return o.jsxs(Zn,{children:[o.jsx(Jgs,{onRunExperiment:()=>a(!0)}),q]});const V=n!=="all"||h!=="all"||e!=="",D=()=>{t(""),r("all"),m("all")};return o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(evs,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:h,onDatasetFilterChange:m,datasetOptions:E,onReset:D,hasActiveFilters:V,onRunClick:()=>a(!0),onCompareClick:()=>l(!0),selection:i?{selectedCount:M.length,onExecuteCompare:z,onCancelSelection:L,compareDisabledReason:H}:void 0})}),o.jsx(Ggs,{experiments:T,datasets:C,reviewByExperiment:N,isLoading:I,search:e,statusFilter:n,datasetFilter:h,selection:i?{selectedExperimentIds:M,onToggleSelection:R}:void 0}),q]})}function a8({experimentId:e}){const{Link:t,paths:n}=un();return o.jsx(le,{as:t,href:n.experimentLink(e),size:"sm","aria-label":`Open experiment ${e}`,children:e.slice(0,8)})}function xvs(){const[e,t]=Ma(),n=e.get("dataset")??"",r=e.get("baseline")??"",s=e.get("contender")??"",a=WD(n,r),i=WD(n,s),l=a.isLoading||i.isLoading,c=a.error??i.error;return c&&ps(c)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{})})}):c&&hs(c)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Os,{resource:"experiments"})})}):!n||!r||!s?o.jsx(vs,{children:o.jsx(hy,{children:o.jsxs("div",{className:"text-neutral4 py-8 text-center",children:[o.jsx("p",{children:"Select two experiments to compare."}),o.jsxs("p",{className:"mt-2 text-sm",children:["Use the URL format: /experiments/compare?dataset=","{datasetId}","&baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})}):l?null:c&&!VEe(c)?o.jsx(vs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx($a,{title:"Failed to load experiments",message:c.message})})}):c||!a.data||!i.data?o.jsx(vs,{children:o.jsx(hy,{children:o.jsxs("div",{className:"text-neutral4 py-8 text-center",children:[o.jsxs("p",{children:["Experiments must belong to the same dataset (",n,") to be compared."]}),o.jsxs("p",{className:"mt-2 flex items-center justify-center gap-2 text-sm",children:["One of",o.jsx(a8,{experimentId:r}),"and",o.jsx(a8,{experimentId:s}),"was not found in it."]})]})})}):o.jsx(vs,{children:o.jsx(hy,{children:o.jsxs("div",{className:"grid w-full content-start",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4 px-6 py-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[o.jsx(ve,{as:"h1",variant:"ui-lg",className:"text-neutral6 font-medium",children:"Experiments comparison"}),o.jsxs("p",{className:"text-ui-sm text-neutral4 flex items-center gap-2",children:[o.jsx(a8,{experimentId:r}),"and",o.jsx(a8,{experimentId:s})]})]}),o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsxs(le,{onClick:()=>t({dataset:n,baseline:s,contender:r}),children:[o.jsx(tct,{}),"Swap sides"]})}),o.jsx(yn,{children:"Switch baseline and contender"})]})]}),o.jsx(lvs,{datasetId:n,experimentIdA:r,experimentIdB:s})]})})})}const rHt=e=>o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 8.64637 9.45103",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:o.jsx("path",{d:"M7.80735 5.87241C7.63209 5.97219 7.43696 6.06166 7.22844 6.13866C6.46456 6.42068 5.43714 6.58649 4.32296 6.58649C3.20873 6.58649 2.18135 6.4207 1.41747 6.13866C1.20889 6.06164 1.01385 5.97223 0.838558 5.87241V7.59003C0.838558 7.62341 0.855765 7.70759 1.00172 7.83512C1.14707 7.96201 1.38219 8.09563 1.70829 8.21605C2.3572 8.45563 3.28149 8.61268 4.32296 8.61269C5.36456 8.61269 6.28937 8.45568 6.9383 8.21605C7.26428 8.09566 7.49888 7.96198 7.64419 7.83512C7.79024 7.70754 7.80735 7.62342 7.80735 7.59003V5.87241ZM7.80735 3.00789C7.63214 3.10763 7.4369 3.19647 7.22844 3.27345C6.46455 3.55549 5.43719 3.72129 4.32296 3.72129C3.20868 3.72128 2.18136 3.55552 1.41747 3.27345C1.20896 3.19645 1.01381 3.10766 0.838558 3.00789V4.72551C0.838558 4.7589 0.855657 4.84301 1.00172 4.97059C1.14707 5.09749 1.38219 5.23111 1.70829 5.35153C2.3572 5.59109 3.28154 5.74747 4.32296 5.74748C5.36456 5.74748 6.28937 5.59116 6.9383 5.35153C7.26432 5.23112 7.49887 5.09747 7.64419 4.97059C7.7536 4.87505 7.79089 4.80404 7.80257 4.76033L7.80735 4.72551V3.00789ZM7.80735 1.86099C7.80735 1.82758 7.79045 1.74291 7.64419 1.61522C7.49887 1.48838 7.26421 1.35534 6.9383 1.23497C6.28937 0.995339 5.36456 0.838331 4.32296 0.838331C3.28149 0.83834 2.3572 0.995383 1.70829 1.23497C1.38219 1.35539 1.14707 1.48832 1.00172 1.61522C0.855475 1.7429 0.838558 1.82758 0.838558 1.86099C0.838673 1.89462 0.855968 1.97882 1.00172 2.10607C1.14707 2.23297 1.38219 2.3659 1.70829 2.48632C2.3572 2.7259 3.28149 2.88295 4.32296 2.88296C5.36456 2.88296 6.28937 2.72595 6.9383 2.48632C7.26421 2.36595 7.49887 2.23291 7.64419 2.10607C7.78996 1.97881 7.80724 1.89462 7.80735 1.86099ZM8.64637 7.59003C8.64637 7.95465 8.44458 8.25006 8.1958 8.46728C7.94608 8.68529 7.60876 8.86274 7.22844 9.00318C6.46455 9.28522 5.43718 9.45102 4.32296 9.45102C3.20869 9.45101 2.18135 9.28525 1.41747 9.00318C1.03715 8.86274 0.699831 8.68529 0.450113 8.46728C0.201377 8.25007 0.000227451 7.9546 0.000227451 7.59003V1.86099C0.000227451 1.49643 0.201388 1.20095 0.450113 0.983742C0.699831 0.765728 1.03715 0.588275 1.41747 0.447838C2.18136 0.165769 3.20868 8.74396e-06 4.32296 0C5.43719 0 6.46455 0.165797 7.22844 0.447838C7.60876 0.588275 7.94608 0.765728 8.1958 0.983742C8.44457 1.20096 8.64637 1.49638 8.64637 1.86099V7.59003Z",fill:"currentColor"})});function sHt(e){const{data:t}=C_(e.id,e.status);return g.useMemo(()=>{if(e.scorerIds?.length)return e.scorerIds;if(!t)return[];const n=new Set;for(const r of Object.values(t))for(const s of r)n.add(s.scorerId);return[...n].sort()},[e.scorerIds,t])}function Qie({icon:e,typeLabel:t,children:n}){return o.jsxs("div",{className:"text-ui-sm text-neutral5 flex flex-none items-center gap-1.5 [&_svg]:size-3.5 [&_svg]:shrink-0",children:[o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx("span",{className:"text-neutral3 flex",role:"img","aria-label":t}),children:e}),o.jsx(yn,{children:t})]}),n]})}function Yie({label:e}){return o.jsxs("div",{className:"text-neutral2 text-ui-xs flex flex-none items-center gap-1.5",children:[o.jsx("span",{className:"whitespace-nowrap",children:e}),o.jsx(zd,{className:"size-3.5 shrink-0","aria-hidden":!0})]})}const btt="text-neutral5 inline-flex items-center gap-1.5 hover:underline";function wvs({experiment:e,className:t}){const{Link:n,paths:r}=un(),s=QVt(),{scorers:a}=s,{data:i,isLoading:l}=My(e.datasetId??""),c=sHt(e),u=c.map(b=>a?.[b]?.scorer?.config?.name??b),d=e.targetType,f=e.targetId,p=()=>XVt(e,s),h=()=>{if(!f)return null;switch(d){case"agent":return r.agentLink(f);case"workflow":return r.workflowLink(f);case"scorer":return r.scorerLink(f);default:return null}},m=d&&YVt[d]||Ai,v=d&&KVt[d]||"Evaluation target",y=h();return o.jsxs("div",{className:K("flex items-center gap-3 overflow-x-auto",t),children:[o.jsx(Qie,{icon:o.jsx(rHt,{}),typeLabel:"Dataset",children:e.datasetId?o.jsxs(n,{href:r.datasetLink(e.datasetId),className:btt,children:[l?o.jsx(Ct,{className:"h-4 w-28"}):i?.name??e.datasetId,e.datasetVersion!=null&&o.jsxs("span",{className:"text-neutral3",children:["(v",e.datasetVersion,")"]})]}):o.jsx("span",{className:"text-neutral3",children:"No dataset"})}),o.jsx(Yie,{label:"each item"}),o.jsx(Qie,{icon:o.jsx(m,{}),typeLabel:v,children:y?o.jsx(n,{href:y,className:btt,children:p()}):o.jsx("span",{className:"text-neutral3",children:p()})}),o.jsx(Yie,{label:"output"}),o.jsxs(xn,{children:[o.jsx(vn,{render:o.jsx("div",{tabIndex:0,className:"flex outline-offset-4",children:o.jsx(Qie,{icon:o.jsx(AC,{}),typeLabel:"Scorers",children:c.length===0?"Scorers":`${c.length} scorer${c.length===1?"":"s"}`})})}),o.jsx(yn,{children:u.length>0?u.join(", "):"No scorer has produced a score yet"})]}),o.jsx(Yie,{label:"comparing ground truth"}),o.jsx("div",{className:"text-ui-sm text-neutral5 flex-none whitespace-nowrap",children:"Score"})]})}function i8({label:e,children:t}){return o.jsxs("div",{className:"min-w-0 flex-1 px-6 py-3",children:[o.jsx("div",{className:"text-ui-sm text-neutral2 tracking-widest uppercase",children:e}),o.jsx("div",{className:"text-ui-md text-neutral5 mt-1 flex flex-wrap items-baseline gap-x-1.5",children:t})]})}function Svs(e){if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(1).replace(/\.0$/,"")}s`;const t=Math.floor(e/6e4),n=Math.round(e%6e4/1e3);if(t<60)return n>0?`${t}m ${n}s`:`${t}m`;const r=Math.floor(t/60),s=t%60;return s>0?`${r}h ${s}m`:`${r}h`}function kvs({experiment:e,className:t}){const{data:n}=C_(e.id,e.status),r=g.useMemo(()=>{if(!n)return;const l=Object.values(n).flat();if(l.length!==0)return l.reduce((c,u)=>c+u.score,0)/l.length},[n]),s=e.startedAt??e.createdAt,a=s?new Date(s):null,i=(()=>{if(e.status==="running")return"Running…";if(!e.startedAt||!e.completedAt)return"—";const l=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return l<0?"—":Svs(l)})();return o.jsxs("div",{className:K("flex w-full items-stretch divide-x divide-border1 border-y border-border1",t),children:[o.jsx(i8,{label:"Avg score",children:r===void 0?o.jsx("span",{className:"text-neutral3",children:"—"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{children:r.toFixed(3)}),(e.status==="running"||e.status==="pending")&&o.jsx("span",{className:"text-neutral3",children:"· so far"})]})}),o.jsx(i8,{label:"Items",children:e.status==="running"||e.status==="pending"?o.jsxs("span",{className:"text-neutral3",children:[(e.succeededCount??0)+(e.failedCount??0),"/",e.totalItems," items processed"]}):o.jsxs(o.Fragment,{children:[o.jsxs("span",{children:[e.totalItems," item",e.totalItems===1?"":"s"]}),(e.failedCount??0)>0&&o.jsxs("span",{className:"text-error",children:["· ",e.failedCount," errored"]})]})}),o.jsx(i8,{label:"Started",children:a?o.jsxs(o.Fragment,{children:[o.jsx("span",{children:dr(a,"MMM d, h:mm a")}),o.jsxs("span",{className:"text-neutral3",children:["· ",G2n(a,{addSuffix:!0})]})]}):o.jsx("span",{children:"—"})}),o.jsx(i8,{label:"Duration",children:o.jsx("span",{children:i})})]})}function Ovs({experiment:e,open:t,onOpenChange:n}){const[r,s]=g.useState(e.name??""),[a,i]=g.useState(e.description??""),{updateExperiment:l}=bi(),c=!!r.trim()&&!l.isPending,u=async d=>{if(d.preventDefault(),!(!c||!e.datasetId))try{await l.mutateAsync({datasetId:e.datasetId,experimentId:e.id,name:r.trim(),description:a.trim()}),ze.success("Experiment renamed"),n(!1)}catch(f){ze.error(`Failed to rename experiment: ${f instanceof Error?f.message:"Unknown error"}`)}};return o.jsx(hr,{open:t,onOpenChange:n,children:o.jsxs(mr,{className:"max-w-md",children:[o.jsx(gr,{children:o.jsx(ur,{children:"Rename Experiment"})}),o.jsx(jr,{children:o.jsxs("form",{onSubmit:u,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Pt,{htmlFor:"rename-experiment-name",children:"Name *"}),o.jsx(Cn,{id:"rename-experiment-name",value:r,onChange:d=>s(d.target.value),placeholder:"Enter experiment name",autoFocus:!0})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Pt,{htmlFor:"rename-experiment-description",children:"Description"}),o.jsx(Cn,{id:"rename-experiment-description",value:a,onChange:d=>i(d.target.value),placeholder:"Enter experiment description (optional)"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(le,{type:"button",onClick:()=>n(!1),disabled:l.isPending,children:"Cancel"}),o.jsx(le,{type:"submit",variant:"primary",disabled:!c,children:l.isPending?"Saving...":"Save"})]})]})})]})})}function _vs({experiment:e}){const[t,n]=g.useState(!1);return e.datasetId?o.jsxs(o.Fragment,{children:[o.jsx(le,{onClick:()=>n(!0),tooltip:"Rename this experiment",variant:"ghost",size:"icon-sm",children:o.jsx(Qp,{})}),t&&o.jsx(Ovs,{experiment:e,open:!0,onOpenChange:n})]}):null}const Cvs=["agent","workflow","scorer"];function Evs({experiment:e}){const[t,n]=g.useState(!1),r=Vr(),{paths:s}=un(),a=sHt(e),i=Cvs.find(l=>l===e.targetType);return!e.datasetId||!i||!e.targetId?null:o.jsxs(o.Fragment,{children:[o.jsxs(le,{variant:"primary",onClick:()=>n(!0),tooltip:"Run this experiment again with the same configuration",children:[o.jsx(Mc,{}),"Rerun"]}),t&&o.jsx(sY,{open:!0,onOpenChange:n,initialDatasetId:e.datasetId,initialDatasetVersion:e.datasetVersion??void 0,initialTargetType:i,initialTargetId:e.targetId,initialScorerIds:a,initialName:e.name??void 0,initialDescription:e.description??void 0,onSuccess:l=>{r(s.experimentLink(l))}},a.join(","))]})}function Tvs({experiment:e}){const{Link:t,paths:n}=un(),r=e.agentVersion&&e.targetType==="agent"&&e.targetId?`${n.agentLink(e.targetId)}/editor?version=${encodeURIComponent(e.agentVersion)}`:null;return o.jsxs(Lt.TopArea,{children:[o.jsxs(Lt.Row,{children:[o.jsx(Lt.Column,{className:"justify-items-start gap-3",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx(Zms,{status:e.status,className:"h-7"}),o.jsxs(Dl,{children:[o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Dl.Title,{children:e.name||`Experiment #${e.id.slice(0,8)}`}),o.jsx(_vs,{experiment:e})]}),e.description&&o.jsx(Dl.Description,{children:e.description}),o.jsx(wvs,{experiment:e,className:"mt-2"})]})]})}),o.jsxs(Lt.Column,{className:"justify-items-end gap-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(le,{as:t,to:pTe(e.id),children:[o.jsx(Q1,{}),"View items to review"]}),o.jsx(Evs,{experiment:e})]}),e.agentVersion&&o.jsxs(Tn,{numOfCol:1,children:[o.jsx(Tn.Key,{children:"Version"}),r?o.jsx(Tn.ValueLink,{href:r,as:t,children:e.agentVersion}):o.jsx(Tn.Value,{children:e.agentVersion})]})]})]}),o.jsx(kvs,{experiment:e,className:"-mx-6 w-auto"})]})}function o8({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function jvs(){const{experimentId:e}=fr(),{data:t,isLoading:n}=UH(),s=t?.experiments?.find(h=>h.id===e)?.datasetId??"",{data:a,isLoading:i,error:l}=WD(s,e??""),{data:c,isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p}=ZD({datasetId:s,experimentId:e??"",experimentStatus:a?.status});return!e||n||i?null:l&&ps(l)?o.jsx(o8,{children:o.jsx(Ts,{})}):l&&hs(l)?o.jsx(o8,{children:o.jsx(Os,{resource:"datasets"})}):l&&VEe(l)||!n&&!s||!i&&!l&&!a?o.jsx(o8,{children:o.jsx(br,{iconSlot:o.jsx(w0e,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:o.jsxs(le,{as:Ba,to:"/experiments",children:[o.jsx(bl,{}),"Back to Experiments"]})})}):l?o.jsx(o8,{children:o.jsx($a,{title:"Failed to load experiment",message:l instanceof Error?l.message:"An unexpected error occurred. Please try again."})}):o.jsx(Bms,{experimentId:e,datasetId:s,experimentStatus:a.status,results:c??[],isLoadingResults:u,hasNextPage:p,children:o.jsxs("div",{className:"relative h-full overflow-hidden",children:[o.jsxs(Lt,{height:"full",children:[o.jsx(Tvs,{experiment:a}),o.jsx(Lt.MainArea,{className:"overflow-visible",children:o.jsx(Wms,{experimentId:e,datasetId:s,experimentStatus:a.status,results:c??[],isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p})})]}),o.jsx(Fg,{})]})})}const fRe=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 Kie(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function Nvs({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(on.SectionHeading,{icon:o.jsx(qd,{}),className:"mb-2",children:"Tool Mocks"}),s&&o.jsx(Rn,{variant:"destructive",title:"Mock mismatch",children:o.jsxs(Rn.Message,{children:[o.jsx("span",{className:"block",children:`Tool "${s.toolName}" was called with arguments that did not match an available mock (${s.code}).`}),o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Called with: ",Kie(s.args)]}),n.length>0&&o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Unconsumed mocks: ",n.map(i=>Kie(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:Kie(i.args)})]}),o.jsx("span",{className:`shrink-0 rounded px-2 py-0.5 text-xs ${Ivs(i.outcome)}`,children:i.outcome})]},`${i.outcome}-${i.toolName}-${l}`))})]})}function Ivs(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 Avs({result:e,scores:t,onPrevious:n,onNext:r,onClose:s,onShowTrace:a,onOpenInReview:i,onScoreClick:l,featuredScoreId:c,onFlagForReview:u,collapsed:d=!1,scorePanelSlot:f}){const p=!!e?.error,h=l8(e?.input),m=l8(e?.output),v=l8(e?.groundTruth),y=u&&e.status!=="needs-review"&&e.status!=="complete",b=Array.isArray(e.tags)?e.tags:[];return o.jsxs(on,{collapsed:d,children:[o.jsxs(on.Header,{children:[o.jsxs(on.Heading,{children:["Result ",o.jsxs("b",{children:["# ",e.id.length>12?`${e.id.slice(0,12)}…`:e.id]})]}),o.jsxs(es,{className:"ml-auto shrink-0",children:[o.jsx(on.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Previous result",nextLabel:"Next result"}),e.traceId&&o.jsxs(le,{size:"md",onClick:a,children:[o.jsx(fRe,{}),"Trace"]}),y&&o.jsxs(le,{size:"md",variant:"primary",onClick:()=>u(e.id),children:[o.jsx(Q1,{}),"Flag for Review"]}),e.status==="needs-review"&&i&&o.jsxs(le,{size:"md",variant:"primary",onClick:i,children:[o.jsx(ea,{}),"Review"]}),o.jsx(on.CloseButton,{onClick:s,tooltip:"Close result panel"})]})]}),!d&&o.jsx(Rvs,{scorePanelSlot:f,children:o.jsxs(on.Content,{children:[o.jsxs("div",{className:"mb-6 grid gap-4",children:[o.jsxs(Tn,{children:[o.jsx(Tn.Key,{children:"Item Id"}),o.jsx(Tn.ValueWithCopyBtn,{copyTooltip:"Copy Item Id to clipboard",copyValue:e.itemId,children:e.itemId}),o.jsx(Tn.Key,{children:"Created"}),o.jsx(Tn.Value,{children:dr(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")})]}),p&&o.jsx(Rn,{variant:"destructive",title:"Error",children:o.jsx(Rn.Message,{children:l8(e?.error&&typeof e.error=="object"?e.error.message:e?.error)})}),t&&t.length>0&&o.jsxs(he,{columns:"1fr 1fr",children:[o.jsxs(he.Top,{children:[o.jsx(he.TopCell,{children:"Scorer"}),o.jsx(he.TopCell,{children:"Score"})]}),t.map(x=>o.jsxs(he.RowButton,{featured:c===x.id,onClick:()=>l?.(x.id),children:[o.jsx(he.Cell,{children:x.scorerId}),o.jsx(he.TextCell,{font:"mono",children:x.score.toFixed(3)})]},x.id))]}),e.toolMockReport&&o.jsx(Nvs,{report:e.toolMockReport}),(e.status||b.length>0)&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(on.SectionHeading,{icon:o.jsx(cI,{}),className:"mb-2",children:"Review"}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.status&&o.jsx("span",{className:`rounded-full px-2 py-0.5 text-xs font-medium ${e.status==="needs-review"?"bg-orange-500/10 text-orange-400":e.status==="complete"?"bg-accent1/10 text-accent1":"bg-neutral3/10 text-neutral4"}`,children:e.status}),b.map(x=>o.jsx("span",{className:"bg-surface4 text-neutral4 rounded px-2 py-0.5 text-xs",children:x},x))]})]})]}),o.jsxs("div",{className:"grid gap-3",children:[o.jsx(on.CodeSection,{title:"Input",icon:o.jsx(NV,{}),codeStr:h}),o.jsx(on.CodeSection,{title:"Output",icon:o.jsx(rm,{}),codeStr:m}),o.jsx(on.CodeSection,{title:"Ground Truth",icon:o.jsx(jct,{}),codeStr:v})]})]})})]})}function Rvs({scorePanelSlot:e,children:t}){return e?o.jsxs("div",{className:"grid min-h-0 flex-1 grid-cols-[1fr_1fr]",children:[o.jsx("div",{className:"flex min-h-0 flex-col overflow-hidden",children:t}),o.jsx("div",{className:"animate-in border-border1 fade-in-0 flex min-h-0 flex-col overflow-hidden border-l duration-300",children:e})]}):o.jsx(o.Fragment,{children:t})}function l8(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Pvs(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function $vs({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s,collapsed:a,onCollapsedChange:i,className:l}){const[c,u]=g.useState(!1),d=a??c,f=i??u,p=Pvs(e),h=p?"N/A — code-based scorer":"N/A — step not configured";return o.jsxs(on,{collapsed:d,className:l,children:[o.jsxs(on.Header,{children:[o.jsxs(on.Heading,{children:["Score ",o.jsx("b",{children:e.scorerId})]}),o.jsxs(es,{className:"ml-auto shrink-0",children:[i&&o.jsx(le,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(rI,{}):o.jsx(CV,{})}),(n||t)&&o.jsx(on.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:"Previous score",nextLabel:"Next score"}),s&&e.traceId&&o.jsxs(le,{size:"md",onClick:s,children:[o.jsx(fRe,{}),"Trace"]}),o.jsx(on.CloseButton,{onClick:r,tooltip:"Close score panel"})]})]}),!d&&o.jsx(on.Content,{children:o.jsxs("div",{className:"grid gap-3",children:[o.jsx(on.CodeSection,{title:`Score: ${e.score}`,icon:o.jsx(Gp,{}),codeStr:e.reason||h,simplified:!0}),!p&&o.jsxs(o.Fragment,{children:[o.jsx(on.CodeSection,{title:"Preprocess Prompt",icon:o.jsx($h,{}),codeStr:e.preprocessPrompt||h,simplified:!0}),o.jsx(on.CodeSection,{title:"Analyze Prompt",icon:o.jsx($h,{}),codeStr:e.analyzePrompt||h,simplified:!0}),o.jsx(on.CodeSection,{title:"Generate Score Prompt",icon:o.jsx($h,{}),codeStr:e.generateScorePrompt||h,simplified:!0}),o.jsx(on.CodeSection,{title:"Generate Reason Prompt",icon:o.jsx($h,{}),codeStr:e.generateReasonPrompt||h,simplified:!0})]})]})})]})}function Mvs(){const{itemId:e}=fr();return e?o.jsx(Dvs,{itemId:e},e):null}function Dvs({itemId:e}){const{experimentId:t,datasetId:n,experimentStatus:r,results:s,isLoadingResults:a,hasNextPage:i,close:l,openInReview:c,goToPreviousItem:u,goToNextItem:d}=HVt(),f=g.useMemo(()=>s.find(P=>P.itemId===e)??null,[s,e]),{data:p}=C_(t,r),{updateExperimentResult:h}=bi(),m=g.useCallback(async P=>{try{await h.mutateAsync({datasetId:n,experimentId:t,resultId:P,status:"needs-review"}),ze("Result flagged for review")}catch{ze.error("Failed to flag result for review")}},[n,t,h]),v=f?p?.[f.itemId]:void 0,[y,b]=g.useState(null),[x,S]=g.useState(void 0),[k,_]=g.useState(null),[C,T]=g.useState(!1),[E,N]=g.useState(!1),I=v?.find(P=>P.id===k)??null,A=g.useCallback(P=>{_(B=>P===B?null:P),b(null),S(void 0)},[]),R=()=>{if(!k||!v)return;const P=v.findIndex(B=>B.id===k);if(P>=0&&P<v.length-1)return()=>_(v[P+1].id)},L=()=>{if(!k||!v)return;const P=v.findIndex(B=>B.id===k);if(P>0)return()=>_(v[P-1].id)},{data:M,isLoading:F}=Gms(y),H=M?.spans,z=H?.find(P=>!P.parentSpanId),q=z?.entityType==="agent"?"Agent":z?.entityType==="workflow_run"?"Workflow":void 0,{data:V}=sRe({traceId:y??void 0}),{data:D}=aRe({traceId:y??void 0,spanId:x}),{data:G}=hje({traceId:y??void 0,spanId:z?.spanId,page:0}),U=(()=>{const P=[],B=!!y;return P.push(C?"auto":B?"2fr":"1fr"),B&&P.push(E?"auto":"3fr"),P.join(" ")})();return o.jsx(aY,{label:`Experiment item ${e}`,wide:!!x||!!I&&!C,children:f?o.jsxs("div",{className:"[&>section]:bg-surface3 grid h-full min-h-0 content-start gap-4 p-3 [&>section]:rounded-lg [&>section]:shadow-lg",style:{gridTemplateRows:U},children:[o.jsx(Avs,{result:f,scores:v,onPrevious:u,onNext:d,onClose:l,onScoreClick:A,featuredScoreId:k,onShowTrace:()=>{f.traceId&&(b(f.traceId),S(void 0),_(null),T(!0),N(!1))},onOpenInReview:()=>c(f.id),onFlagForReview:()=>{m(f.id)},collapsed:C,scorePanelSlot:I?o.jsx($vs,{score:I,onNext:R(),onPrevious:L(),onClose:()=>_(null),onShowTrace:()=>{I.traceId&&(b(I.traceId),S(void 0),T(!0),N(!1))},className:"rounded-none border-0 bg-transparent"}):null}),y&&o.jsx(JQ,{traceId:y,spans:H,isLoadingSpans:F,selectedSpanId:x??null,onClose:()=>{b(null),S(void 0),T(!1)},onSpanSelect:S,showUnavailableFeaturesMsg:!1,collapsed:E,onCollapsedChange:N,traceHref:`/traces?traceId=${encodeURIComponent(y)}`,anchorSpanId:z?.spanId,feedbackTabBadge:V?.pagination?.total??void 0,feedbackTabSlot:({traceId:P})=>o.jsx(oRe,{traceId:P}),scoresTabBadge:G?.pagination?.total??void 0,scoresTabSlot:({traceId:P,rootSpanId:B})=>B?o.jsx(RVt,{traceId:P,spanId:B,isTopLevelSpan:!z?.parentSpanId,entityType:q,onScoreSelect:Z=>{v?.some(Y=>Y.id===Z)&&(_(Z),T(!1))}}):null,spanFeedbackTabBadge:D?.pagination?.total??void 0,spanFeedbackTabSlot:({traceId:P,spanId:B})=>P&&B?o.jsx(iRe,{traceId:P,spanId:B},`${P}:${B}`):null,spanPanelClassName:"rounded-none border-0 bg-transparent"})]}):a||i?o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(Ut,{})})}):o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(br,{iconSlot:o.jsx(w0e,{}),titleSlot:"Item not found",descriptionSlot:`No loaded result for item "${e}".`,actionSlot:o.jsx(le,{onClick:l,children:"Close"})})})})})}const pRe=e=>o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 9.83952 9.3295",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.67171 0.838331H6.70163V4.05307L9.68767 8.09999C10.0634 8.6093 9.69869 9.32932 9.06643 9.3295H0.772551C0.140289 9.3293 -0.223777 8.60929 0.151995 8.09999L3.13804 4.05307V0.838331H2.17136V0H7.67171V0.838331ZM3.97705 4.32955L3.89513 4.44015L2.34681 6.53802H7.49285L5.94453 4.44015L5.86261 4.32955V0.860859H3.97705V4.32955Z",fill:"currentColor"})}),kV="all",xtt=60,Lvs=e=>e.length>xtt?`${e.slice(0,xtt)}…`:e;function Fvs({value:e,onValueChange:t,className:n,variant:r,allOption:s}){const{data:a,isLoading:i,isError:l}=oY(void 0),c=(a?.experiments??[]).map(d=>({label:ZVt(d),value:d.id,start:o.jsx(pRe,{className:"text-neutral3 size-4 shrink-0","data-testid":"experiments-icon"}),description:d.description?Lvs(d.description):h0(d.id)??d.id})),u=s?[{label:"All experiments",value:kV},...c]:c;return o.jsx(yl,{options:u,value:e??(s?kV:""),onValueChange:t,placeholder:i?"Loading experiments...":l?"Failed to load experiments":"Select experiment",searchPlaceholder:"Search experiments...",emptyText:"No experiments found.",className:n,disabled:i||l,variant:r})}function zvs(){const[e,t]=Ma(),n=e.get("experiment"),r=e.get("review"),{data:s,error:a}=oY(void 0),i=s?.experiments.find(c=>c.id===n),l=c=>{t(c===kV?{}:{experiment:c},{replace:!0})};return a&&ps(a)?o.jsx(Zn,{children:o.jsx(Ts,{})}):a&&hs(a)?o.jsx(Zn,{children:o.jsx(Os,{resource:"experiments"})}):a?o.jsx(Zn,{children:o.jsx($a,{title:"Failed to load experiments",message:a.message})}):o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(Lt.Row,{children:o.jsx(Lt.Column,{className:"justify-items-start",children:o.jsx(Fvs,{allOption:!0,value:n??void 0,onValueChange:l,className:"w-80"})})})}),o.jsx(Lt.MainArea,{className:"overflow-visible",children:o.jsx(pvs,{datasetId:i?.datasetId??void 0,experimentId:n??void 0,featuredItemId:r,detailPanelVariant:"overlay"},n??kV)})]})}const Bvs=20;function Uvs({reviewStatus:e}){const t=Ge(),n=Py({queryKey:["feedback","list",e],queryFn:({pageParam:r})=>t.listFeedback({filters:{reviewStatus:e},pagination:{page:r,perPage:Bvs},orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:r=>r.pagination?.hasMore?r.pagination.page+1:void 0});return{...n,items:n.data?.pages.flatMap(r=>r.feedback)??[],total:n.data?.pages[0]?.pagination?.total}}function qvs({enabled:e}){const t=Ge();return mt({queryKey:["feedback","inbox-count"],queryFn:()=>t.listFeedback({filters:{reviewStatus:"needs-review"},pagination:{page:0,perPage:1},orderBy:{field:"timestamp",direction:"DESC"}}),enabled:e,refetchInterval:3e3})}function Vvs(){const e=Ge(),t=Ir();return Sn({mutationFn:({feedbackId:n,reviewStatus:r})=>e.updateFeedbackReviewStatus({feedbackId:n,reviewStatus:r}),onSuccess:()=>t.invalidateQueries({queryKey:["feedback"]})})}const wtt="minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) auto";function Hvs({items:e,isLoading:t,error:n}){const r=Vr(),[s,a]=g.useState(""),i=s.trim().toLowerCase(),l=i?e.filter(d=>[d.itemId,d.experimentId,d.datasetId,d.traceId??""].some(f=>f.toLowerCase().includes(i))):e,{containerRef:c,getRowProps:u}=so({count:l.length});return t?o.jsx(Fo,{columns:wtt}):n?o.jsx($a,{title:"Failed to load dataset items",message:n.message}):e.length===0?o.jsx(br,{iconSlot:o.jsx(E0e,{className:"text-neutral3 h-8 w-8"}),titleSlot:"Nothing to review",descriptionSlot:"Experiment results that need review will show up here."}):o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_1fr] gap-4",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(od,{onSearch:a,label:"Filter dataset items",placeholder:"Filter by item, experiment, dataset or trace",shortcutDisabled:!0})}),o.jsx("div",{className:"min-h-0 overflow-hidden",children:o.jsxs(he,{columns:wtt,fit:"container",scrollRef:c,children:[o.jsxs(he.Top,{children:[o.jsx(he.TopCell,{children:"Item"}),o.jsx(he.TopCell,{children:"Experiment"}),o.jsx(he.TopCell,{children:"Dataset"}),o.jsx(he.TopCell,{children:"Trace"}),o.jsx(he.TopCell,{children:" "})]}),l.length===0?o.jsx(he.NoMatch,{message:"No dataset items match your search"}):l.map((d,f)=>{const p=pTe(d.experimentId,d.id);return o.jsxs(he.RowWrapper,{children:[o.jsxs(he.RowButton,{colEnd:-2,onClick:()=>r(p),...u(f),children:[o.jsx(he.TextCell,{font:"mono",children:d.itemId}),o.jsx(he.TextCell,{font:"mono",children:d.experimentId}),o.jsx(he.TextCell,{font:"mono",children:d.datasetId}),o.jsx(he.TextCell,{font:"mono",children:d.traceId??"—"})]}),o.jsx(he.ActionsCell,{className:"pl-2",children:d.traceId?o.jsx(le,{as:Ba,to:`/traces?traceId=${encodeURIComponent(d.traceId)}`,variant:"ghost",size:"sm",children:"Open trace"}):null})]},d.id)})]})})]})}function Wvs(){return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx(E0e,{}),titleSlot:"Your inbox is empty",descriptionSlot:o.jsxs(o.Fragment,{children:["Feedback left on traces and experiment results flagged for review ",o.jsx("br",{}),"will show up here until you mark them reviewed."]}),actionSlot:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(le,{as:Ba,to:"/experiments",variant:"outline",children:"Go to experiments"}),o.jsx(le,{as:Ba,to:"/traces",variant:"outline",children:"Go to traces"})]})})})}function a0e(e){return e.comment?e.comment:typeof e.value=="string"?e.value:e.feedbackType==="thumbs"?e.value===1?"Thumbs up":"Thumbs down":JSON.stringify(e.value)??String(e.value)}const Stt="minmax(0, 2fr) auto minmax(0, 1fr) auto auto";function Zvs({items:e,isLoading:t,error:n,hasNextPage:r,isFetchingNextPage:s,fetchNextPage:a,onMarkReviewed:i,pendingFeedbackId:l,onSelect:c,selectedFeedbackId:u}){const[d,f]=g.useState(""),p=d.trim().toLowerCase(),h=p?e.filter(x=>a0e(x).toLowerCase().includes(p)||(x.traceId??"").toLowerCase().includes(p)||(x.feedbackSource??"").toLowerCase().includes(p)):e,{containerRef:m,getRowProps:v}=so({count:h.length}),{inView:y,setRef:b}=t0({root:m});return g.useEffect(()=>{y&&r&&!s&&a()},[y,r,s,a]),t?o.jsx(Fo,{columns:Stt}):n?o.jsx($a,{title:"Failed to load feedback",message:n.message}):o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_1fr] gap-4",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(od,{onSearch:f,label:"Filter feedback",placeholder:"Filter loaded feedback by text, trace or source"})}),o.jsx("div",{className:"min-h-0 overflow-hidden",children:o.jsxs(he,{columns:Stt,fit:"container",scrollRef:m,children:[o.jsxs(he.Top,{children:[o.jsx(he.TopCell,{children:"Feedback"}),o.jsx(he.TopCell,{children:"Source"}),o.jsx(he.TopCell,{children:"Trace"}),o.jsx(he.TopCell,{children:"Date"}),o.jsx(he.TopCell,{children:" "})]}),h.length===0?o.jsx(he.NoMatch,{message:p?"No feedback matches your search":"No feedback needs review"}):h.map((x,S)=>{const k=x.feedbackId;return o.jsxs(he.RowWrapper,{children:[o.jsxs(he.RowButton,{colEnd:-2,disabled:!x.traceId,featured:k!==void 0&&k===u,onClick:()=>c(x),...v(S),children:[o.jsx(he.TextCell,{className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:a0e(x)})}),o.jsx(he.Cell,{children:o.jsx(xt,{size:"sm",children:x.feedbackSource})}),o.jsx(he.TextCell,{font:"mono",className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:x.traceId??"—"})}),o.jsx(he.TextCell,{children:dr(x.timestamp,"MMM d, h:mm a")})]}),o.jsx(he.ActionsCell,{className:"pl-2",children:k?o.jsx(le,{variant:"ghost",size:"sm",onClick:()=>i(k),disabled:l===k,children:"Mark reviewed"}):null})]},k??`${String(x.timestamp)}-${x.traceId}`)}),o.jsx(he.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:b})]})})]})}function Gvs({feedback:e,traceId:t,initialSpanId:n,onClose:r,onPrevious:s,onNext:a,onMarkReviewed:i,isMarkingReviewed:l}){const[c,u]=g.useState(n),{spans:d,isLoading:f}=PAe({traceId:t,anchorSpanId:null,listMode:"traces"});return o.jsx(aY,{label:`Review feedback for trace ${t}`,wide:!!c,children:o.jsxs("div",{className:"[&>*]:bg-surface3 grid h-full min-h-0 grid-rows-[auto_minmax(0,1fr)] gap-4 p-3 [&>*]:rounded-lg [&>*]:shadow-lg",children:[o.jsxs(on,{className:"max-h-[33vh]",children:[o.jsxs(on.Header,{className:"items-start",children:[o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(on.Heading,{children:"Feedback"}),o.jsx(xt,{variant:"neutral",emphasis:"muted",children:e.feedbackType}),e.feedbackSource&&o.jsx(xt,{variant:"neutral",emphasis:"muted",children:e.feedbackSource})]}),o.jsxs(ve,{as:"p",variant:"ui-sm",className:"text-neutral3",children:[dr(new Date(e.timestamp),"MMM dd, yyyy HH:mm:ss"),e.feedbackUserId?` · ${e.feedbackUserId}`:null]})]}),o.jsx(es,{className:"ml-auto shrink-0",children:o.jsxs(le,{variant:"primary",size:"sm",onClick:i,disabled:l,children:[o.jsx(We,{children:o.jsx(qr,{})}),"Mark as reviewed"]})})]}),o.jsx(on.Content,{children:o.jsx(ve,{as:"p",variant:"ui-md",className:"text-neutral5 whitespace-pre-wrap",children:a0e(e)})})]}),o.jsx("section",{className:"min-h-0 overflow-hidden",children:o.jsx(JQ,{className:"h-full rounded-none border-0 bg-transparent",spanPanelClassName:"rounded-none border-0 bg-transparent",traceId:t,spans:d,isLoadingSpans:f,selectedSpanId:c??null,initialSpanId:n,onSpanSelect:u,onClose:r,onPrevious:s,onNext:a,traceHref:`/traces?traceId=${encodeURIComponent(t)}`,feedbackTabSlot:({traceId:p})=>o.jsx(oRe,{traceId:p}),spanFeedbackTabSlot:({traceId:p,spanId:h})=>p&&h?o.jsx(iRe,{traceId:p,spanId:h},`${p}:${h}`):null})})]})})}const aHt=100;async function Qvs(e){const t=[];let n=0,r=!0;for(;r;){const s=await e.listExperiments({page:n,perPage:aHt});t.push(...s.experiments),r=s.pagination.hasMore,n+=1}return t}async function Yvs(e,t,n){const r=[];let s=0,a=!0;for(;a;){const i=await e.listDatasetExperimentResults(t,n,{page:s,perPage:aHt});r.push(...i.results),a=i.pagination.hasMore,s+=1}return r}function Kvs(){const e=Ge();return mt({queryKey:["inbox-dataset-review-items"],queryFn:async()=>{const t=await Qvs(e);return(await Promise.all(t.map(async r=>{const s=r.datasetId;return s?(await Yvs(e,s,r.id)).filter(i=>i.status==="needs-review").map(i=>({id:i.id,datasetId:s,experimentId:r.id,itemId:i.itemId,traceId:i.traceId??void 0,input:i.input,output:i.output})):[]}))).flat()},refetchInterval:3e3,refetchOnWindowFocus:!1})}function Xvs({enabled:e}){const t=Ge();return mt({queryKey:["inbox-dataset-review-count"],queryFn:async()=>{const{counts:n}=await t.getExperimentReviewSummary();return n.reduce((r,s)=>r+s.needsReview,0)},enabled:e,refetchInterval:3e3})}function Jvs(e){return e==="dataset"||e==="feedback"}function eys(){const[e,t]=Ma(),n=e.get("tab"),r=Jvs(n)?n:"feedback",s=Uvs({reviewStatus:"needs-review"}),a=Vvs(),i=Kvs(),l=i.data??[],c=s.total??0,u=!s.isLoading&&!i.isLoading&&!s.error&&!i.error&&s.items.length===0&&l.length===0,d=e.get("feedbackId")??void 0,f=e.get("traceId")??void 0,p=e.get("spanId")??void 0,h=T=>{t(E=>{const N=new URLSearchParams(E);for(const I of["feedbackId","traceId","spanId"]){const A=T[I];A?N.set(I,A):N.delete(I)}return N},{replace:!0})},m=()=>h({}),v=T=>h({feedbackId:T.feedbackId??void 0,traceId:T.traceId??void 0,spanId:T.spanId??void 0}),y=s.items.findIndex(T=>T.feedbackId===d),b=y>=0?s.items[y]:void 0,x=y>0?s.items[y-1]:void 0,S=y>=0&&y<s.items.length-1?s.items[y+1]:void 0,k=!!f&&!!d,_=T=>{a.mutate({feedbackId:T,reviewStatus:"reviewed"},{onSuccess:()=>T===d&&m()})},C=T=>{t(E=>{const N=new URLSearchParams(E);return N.set("tab",T),N},{replace:!0})};return o.jsxs("div",{className:"relative h-full overflow-hidden",children:[o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs(Dl,{children:[o.jsx(Dl.Title,{children:"Inbox"}),o.jsx(Dl.Description,{children:"Items waiting for review"})]})}),o.jsx(Lt.MainArea,{className:"min-h-0 overflow-hidden",children:u?o.jsx(Wvs,{}):o.jsxs(Wc,{defaultTab:"feedback",value:r,onValueChange:C,className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[o.jsxs(Hc,{variant:"pill-ghost",children:[o.jsxs(Ur,{value:"feedback",className:"px-3 py-2.5",children:[o.jsx(We,{size:"sm",children:o.jsx($V,{})}),o.jsx(ve,{variant:"ui-sm",className:"text-inherit",children:"Feedback"}),c>0&&o.jsx(xt,{variant:"yellow",size:"sm",children:c})]}),o.jsxs(Ur,{value:"dataset",className:"px-3 py-2.5",children:[o.jsx(We,{size:"sm",children:o.jsx(Q1,{})}),o.jsx(ve,{variant:"ui-sm",className:"text-inherit",children:"Dataset items"}),l.length>0&&o.jsx(xt,{variant:"yellow",size:"sm",children:l.length})]})]}),o.jsx(Ss,{value:"feedback",className:"h-full min-h-0 pt-4",children:o.jsx(Zvs,{items:s.items,isLoading:s.isLoading,error:s.error??void 0,hasNextPage:s.hasNextPage,isFetchingNextPage:s.isFetchingNextPage,fetchNextPage:s.fetchNextPage,onMarkReviewed:_,pendingFeedbackId:a.isPending?a.variables?.feedbackId:void 0,onSelect:v,selectedFeedbackId:d})}),o.jsx(Ss,{value:"dataset",className:"h-full min-h-0 pt-4",children:o.jsx(Hvs,{items:l,isLoading:i.isLoading,error:i.error??void 0})})]})})]}),k&&f&&b&&o.jsx(Gvs,{feedback:b,traceId:f,initialSpanId:p,onClose:m,onPrevious:x?()=>v(x):void 0,onNext:S?()=>v(S):void 0,onMarkReviewed:()=>d&&_(d),isMarkingReviewed:a.isPending},`${d}:${f}`)]})}function tys({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 iHt({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("ul",{className:"space-y-1",children:e.map(s=>o.jsx(tys,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function nys({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(iHt,{connections:a,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function rys({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(nys,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):o.jsx(iHt,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?o.jsx("p",{className:"text-red-600",children:String(c)}):null]})}function sys({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:v}){return o.jsxs("div",{className:"space-y-4 border rounded p-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"provider-select",children:"Provider"}),o.jsxs("select",{id:"provider-select",className:"border rounded px-2 py-1 w-full",value:n,onChange:y=>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:v,disabled:!n||!r||u,children:u?"Authorizing…":"Connect"}),d?o.jsx("p",{className:"text-red-600",children:String(d)}):null,f&&o.jsxs("p",{className:"text-green-700",children:["Authorized: ",f.connectionId," (status: ",f.status,")"]})]})}const ktt=e=>e.authorId?.trim()||"shared",ays=(e,t)=>{if(!t||new Set(e.map(ktt)).size<=1)return null;const r=new Map;for(const a of e){const i=ktt(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},iys=["*","tool-providers:*","tool-providers:admin"];function oys(){const{data:e}=Fm();return e?.permissions?.some(t=>iys.includes(t))??!1}function lys(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,a]=g.useState(""),i=eA(),l=lG(e||null),c=T3t(e||null,n||null),u=E3t(),d=O3t(),f=oys(),p=i.data?.providers??[],h=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),v=g.useMemo(()=>ays(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(sys,{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(rys,{providerId:e,toolkit:n,connections:m,groupedByAuthor:v,isAdmin:f,isLoading:c.isLoading,error:c.error,disconnectPending:d.isPending,disconnectError:d.error,onDisconnect:x})]})}function cys({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(Hp,{className:"h-10 w-10"}),o.jsx("h1",{className:"text-neutral6 text-xl font-semibold",children:e})]}),t,n,r]})})}function oHt({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:a}=mc(),{mutate:i,isPending:l,error:c}=rPr(),{mutate:u,isPending:d,error:f}=aPr(),{mutate:p,isPending:h}=jMt(),[m,v]=g.useState(n),[y,b]=g.useState(""),[x,S]=g.useState(""),[k,_]=g.useState("");if(a)return o.jsx("div",{className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"text-neutral3",children:"Loading..."})});if(!s?.enabled||!s?.login)return o.jsx("div",{className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"text-neutral3",children:"Authentication is not configured"})});const{login:C}=s,T=C.type==="sso"||C.type==="both",E=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,M=()=>{t?t():e?window.location.href=e:window.location.href=vG("/")},F=D=>{D.preventDefault(),A?i({email:x,password:k},{onSuccess:M}):u({email:x,password:k,name:y||void 0},{onSuccess:M})},H=()=>{p({redirectUri:e},{onSuccess:D=>{window.location.href=D.url}})},z=()=>{v(A?"signup":"signin")},q=C.description?o.jsxs("div",{className:"border-border1 bg-surface1 flex items-start gap-2.5 rounded-md border p-3",children:[o.jsx(Ud,{className:"text-neutral4 mt-0.5 h-4 w-4 shrink-0"}),o.jsx("p",{className:"text-neutral3 text-sm",children:C.description})]}):null,V=r?o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:r}):null;return o.jsxs(cys,{title:A?"Sign in to Mastra Studio":"Create your account",description:q,errorBanner:V,children:[E&&o.jsxs("form",{onSubmit:F,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:D=>b(D.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:D=>S(D.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:D=>_(D.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(le,{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:z,className:"text-neutral6 hover:underline",children:A?"Sign up":"Sign in"})]})]}),T&&E&&o.jsxs("div",{className:"relative",children:[o.jsx("div",{className:"absolute inset-0 flex items-center",children:o.jsx("div",{className:"border-border1 w-full border-t"})}),o.jsx("div",{className:"relative flex justify-center text-sm",children:o.jsx("span",{className:"bg-surface1 text-neutral3 px-2",children:"or continue with"})})]}),T&&N&&o.jsxs(le,{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 uys(){const[e]=Ma(),t=Vr(),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(oHt,{redirectUri:n,onSuccess:i,initialMode:s,errorMessage:a})}const mp=Na.KeyValueList;function dys(e){return e instanceof Date?e:new Date(e)}function fys({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:a,collapsed:i,onCollapsedChange:l}){const[c,u]=g.useState(!1),d=i??c,f=l??u,p=dys(e.timestamp),h=e.traceId,m=e.spanId;return o.jsxs(Na,{collapsed:d,children:[o.jsxs(Na.Header,{children:[o.jsxs(Na.Heading,{children:["Log ",o.jsx("b",{children:dr(p,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(es,{className:"ml-auto shrink-0",children:[l&&o.jsx(le,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(rI,{}):o.jsx(CV,{})}),o.jsxs(es,{spacing:"close",children:[o.jsx(le,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(G1,{})}),o.jsx(le,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(_V,{})})]}),o.jsx(Na.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(Na.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:K("my-8 grid gap-2","[&>button]:justify-between [&>button]:overflow-hidden"),children:[h&&o.jsxs(es,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(le,{size:"md",className:"min-w-0 flex-1 overflow-hidden",onClick:()=>n?.(h),children:[o.jsx(zd,{}),o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",h]})]}),o.jsx(ka,{content:h,size:"md",tooltip:"Copy Trace ID to clipboard"})]}),m&&o.jsxs(es,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(le,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!h||!r,onClick:()=>h&&r?.(h,m),children:[o.jsx(zd,{}),o.jsx("span",{children:"Span"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",m]})]}),o.jsx(ka,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(mp,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(mp.Key,{children:"Entity Type"}),o.jsx(mp.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(mp.Key,{children:"Entity Name"}),o.jsx(mp.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(mp.Key,{children:"Service"}),o.jsx(mp.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(mp.Key,{children:"Environment"}),o.jsx(mp.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(mp.Key,{children:"Source"}),o.jsx(mp.Value,{children:e.source})]}),e.metadata&&Object.keys(e.metadata).length>0&&o.jsx(o.Fragment,{children:Object.entries(e.metadata).map(([v,y])=>o.jsxs(g.Fragment,{children:[o.jsx(mp.Key,{children:v}),o.jsx(mp.Value,{children:String(y)})]},v))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(Na.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function pys({error:e,resource:t,errorTitle:n}){if(ps(e))return o.jsx(Ts,{});if(hs(e))return o.jsx(Os,{resource:t});if(V4(e))return o.jsx(br,{iconSlot:o.jsx($c,{}),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(q4(e,"logs"))return o.jsx(br,{iconSlot:o.jsx($c,{}),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($a,{title:n,message:r??"Unknown error"})}function hys({listSlot:e,logPanelSlot:t,tracePanelSlot:n,spanPanelSlot:r,logCollapsed:s}){const a=!!t;return o.jsxs("div",{className:K("grid h-full min-h-0 items-start gap-4",a?"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[e,a&&o.jsxs("div",{className:K("grid h-full gap-4 overflow-auto",n&&r?s?"grid-rows-[auto_1fr_1fr]":"grid-rows-[1fr_1fr_1fr]":n?s?"grid-rows-[auto_1fr]":"grid-rows-[1fr_1fr]":s?"grid-rows-[auto]":"grid-rows-[1fr]"),children:[t,n,r]})]})}const mys={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 gys({level:e}){const t=mys[e];return o.jsx(fo,{children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function vys({entityType:e,className:t}){const n=K("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case"agent":return o.jsx(Ai,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return o.jsx(Bc,{className:n,"aria-hidden":!0});case"tool":return o.jsx(zf,{className:n,"aria-hidden":!0});default:return null}}function yys({entityType:e,entityName:t}){const n=e??"";return o.jsxs(fo,{className:"flex min-w-0 items-center gap-2",children:[o.jsx(vys,{entityType:n}),t?o.jsx("span",{className:"text-ui-smd min-w-0 truncate",children:t}):"-"]})}function bys({message:e}){return o.jsx(fo,{className:"text-ui-smd text-neutral4 min-w-0 truncate font-mono",children:e})}function xys({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(fo,{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(LEe,{font:"mono",children:t})}const ec=Object.assign(z4,{Top:U4,TopCell:pS,TopCellWithTooltip:GZ,TopCellSmart:$Pt,RowWrapper:BEe,RowButton:B4,RowLink:PPt,Spacer:UEe,NoMatch:ZZ,DateCell:IPt,TimeCell:APt,LevelCell:gys,EntityCell:yys,MessageCell:bys,DataCell:xys,NextPageLoading:WZ}),Ott="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",wys=36,Sys=8;function kys({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=g.useRef(null),u=gqt({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>wys,overscan:Sys}),{getRowProps:d}=so({count:e.length,containerRef:c,onNavigate:y=>u.scrollToIndex(y)}),f=g.useRef(t);if(g.useEffect(()=>{f.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),f.current=t},[t]),t)return o.jsx(Fo,{columns:Ott});const p=u.getVirtualItems(),h=u.getTotalSize(),m=p[0]?.start??0,v=p.length>0?Math.max(0,h-(p[p.length-1]?.end??0)):0;return o.jsxs(ec,{columns:Ott,scrollRef:c,className:"min-w-0",children:[o.jsxs(ec.Top,{children:[o.jsx(ec.TopCell,{children:"Date"}),o.jsx(ec.TopCell,{children:"Time"}),o.jsx(ec.TopCell,{children:"Level"}),o.jsx(ec.TopCell,{children:"Entity"}),o.jsx(ec.TopCell,{children:"Message"}),o.jsx(ec.TopCell,{children:"Data"})]}),e.length===0?o.jsx(ec.NoMatch,{message:"No logs match your search"}):o.jsxs(o.Fragment,{children:[o.jsx(ec.Spacer,{height:m}),p.map(y=>{const b=e[y.index];if(!b)return null;const x=a.get(b);if(!x)return null;const S=x===i;return o.jsxs(ec.RowButton,{ref:u.measureElement,"data-index":y.index,...d(y.index),onClick:()=>l(b),featured:S,variant:b.level==="error"||b.level==="fatal"?"error":"default",children:[o.jsx(ec.DateCell,{timestamp:b.timestamp}),o.jsx(ec.TimeCell,{timestamp:b.timestamp}),o.jsx(ec.LevelCell,{level:b.level}),o.jsx(ec.EntityCell,{entityType:b.entityType,entityName:b.entityName}),o.jsx(ec.MessageCell,{message:b.message}),o.jsx(ec.DataCell,{data:b.data})]},x)}),o.jsx(ec.Spacer,{height:v})]}),o.jsx(ec.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function Oys({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=>_ys(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(YAe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(GAe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function _ys(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 Cys={"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"},Xie="MMM d, yyyy HH:mm",Jie="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function Eys({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${Cys[e]}`,description:Jie}:t&&n?{title:`No logs between ${dr(t,Xie)} and ${dr(n,Xie)}`,description:Jie}:t?{title:`No logs since ${dr(t,Xie)}`,description:Jie}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const Tys=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=Eys({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx($c,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(le,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",children:["Logging Documentation ",o.jsx(ea,{})]})})})},jys=20,Nys=1e4;function Iys(e,t,n){if(e?.pagination?.hasMore)return n+1}function Ays(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 Rys(e){return q4(e.state.error,"logs")||V4(e.state.error)?!1:Nys}const Pys=({filters:e}={})=>{const t=Ge(),{inView:n,setRef:r}=t0(),s=Py({queryKey:["logs",e],queryFn:({pageParam:p})=>t.listLogsVNext({pagination:{page:p,perPage:jys},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:Iys,select:Ays,retry:!1,refetchInterval:Rys}),{hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,data:c,isLoading:u,isError:d,error:f}=s;return g.useEffect(()=>{n&&a&&!i&&l()},[n,a,i,l]),{data:c,hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,isLoading:u,isError:d,error:f,setEndOfListElement:r}},c8={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},lHt=[{label:"Agent",entityType:c8.AGENT},{label:"Workflow",entityType:c8.WORKFLOW},{label:"Scorer",entityType:c8.SCORER},{label:"Ingest",entityType:c8.INGEST}],$ys=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],Gx="rootEntityType",tx="datePreset",nx="dateFrom",rx="dateTo",Mys=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),jl={level:"filterLevel",tags:"filterTags",entityName:"filterEntityName",traceId:"filterTraceId",spanId:"filterSpanId",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId"},XL=Object.keys(jl),hRe=new Set(["tags"]),mRe="mastra:logs:saved-filters";function Dys(e,t=mRe){const n=Uys(e),r=e.get(tx);r&&n.set(tx,r);const s=e.get(nx);s&&n.set(nx,s);const a=e.get(rx);a&&n.set(rx,a);try{localStorage.setItem(t,n.toString())}catch{}}function Lys(e=mRe){try{localStorage.removeItem(e)}catch{}}function _tt(e=mRe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function Fys(e){if(e.has(tx)||e.has(nx)||e.has(rx)||e.has(Gx))return!0;for(const t of XL)if(e.has(jl[t]))return!0;return!1}function zys({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:lHt.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:$ys.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 Bys(e){const t=[],n=new Map([[Gx,"rootEntityType"]]);for(const s of XL)n.set(jl[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),hRe.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 Uys(e){const t=new URLSearchParams,n=e.get(Gx);n&&t.set(Gx,n);for(const r of XL){const s=jl[r];if(hRe.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 qys(e,t){e.delete(Gx);for(const n of XL)e.delete(jl[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(Gx,n.value);continue}const r=jl[n.fieldId];if(r){if(hRe.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 Vys({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 Hys(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 Wys="Filters setting for Logs saved",Zys="Filters setting for Logs cleared up";function Gys(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=g.useState(()=>_tt(r)!==null),c=g.useCallback(()=>{Dys(e,r),l(!0);const f=s?.saved??Wys;f!==!1&&ze.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{Lys(r),l(!1);const f=s?.cleared??Zys;f!==!1&&ze.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(a||d.current||(d.current=!0,Fys(e)))return;const f=_tt(r);f&&t(p=>{const h=new URLSearchParams(p);for(const[m,v]of f)h.append(m,v);return h},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function Qys(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 Yys(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,Qys(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function Kys(e,t,n,r){const s=g.useMemo(()=>Yys(e),[e]),a=g.useMemo(()=>{const h=new Map;for(const[m,v]of e.entries()){const y=s.get(v);y&&h.set(y,{log:v,idx:m})}return h},[e,s]),l=(t?a.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=g.useCallback(h=>s.get(h),[s]),d=g.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 i0e="logId",o0e="traceId",l0e="spanId",TP=1440*60*1e3,Xys={"last-24h":TP,"last-3d":3*TP,"last-7d":7*TP,"last-14d":14*TP,"last-30d":30*TP};function u8(e){e.delete(i0e),e.delete(o0e),e.delete(l0e)}function Jys(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const _=e.get(tx);return _&&Mys.has(_)?_:"last-24h"},[e]),a=e.get(nx),i=e.get(rx),l=g.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 _=Xys[s];return _?new Date(Date.now()-_):void 0},[s,a]),c=g.useMemo(()=>{if(s!=="custom"||!i)return;const _=new Date(i);return Number.isNaN(_.getTime())?void 0:_},[s,i]),u=g.useRef(s);u.current=s;const d=e.get(i0e),f=e.get(o0e),p=e.get(l0e),h=g.useMemo(()=>lHt.find(_=>_.entityType===e.get(Gx)),[e]),m=g.useMemo(()=>Bys(e),[e]),v=g.useCallback(_=>{t(C=>{const T=new URLSearchParams(C);for(const[E,N]of Object.entries(_)){const I=E==="logId"?i0e:E==="traceId"?o0e:l0e;N?T.set(I,N):T.delete(I)}return T},{replace:!0})},[t]),y=g.useCallback(_=>{t(C=>{const T=new URLSearchParams(C);return qys(T,_),u8(T),T},{replace:!0})},[t]),b=y,x=g.useCallback((_,C)=>{if(u.current!=="custom")return;const T=C==="from"?nx:rx;t(E=>{const N=new URLSearchParams(E);return _?N.set(T,_.toISOString()):N.delete(T),u8(N),N},{replace:!0})},[t]),S=g.useCallback(_=>{u.current=_,t(C=>{const T=new URLSearchParams(C);return _==="last-24h"?(T.delete(tx),T.delete(nx),T.delete(rx)):_==="custom"?T.set(tx,"custom"):(T.set(tx,_),T.delete(nx),T.delete(rx)),u8(T),T},{replace:!0})},[t]),k=g.useCallback(()=>{t(_=>{const C=new URLSearchParams(_);C.delete(Gx);for(const T of XL)C.delete(jl[T]);return C.delete(tx),C.delete(nx),C.delete(rx),u8(C),C},{replace:!0}),r?.()},[t,r]);return g.useMemo(()=>({searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,featuredLogId:d,featuredTraceId:f,featuredSpanId:p,selectedEntityOption:h,filterTokens:m,handleFeaturedChange:v,handleFilterTokensChange:b,handleDateChange:x,handleDatePresetChange:S,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,p,h,m,v,b,x,S,k,y])}const jb=Na.KeyValueList;function ebs({spanId:e,span:t,isLoading:n,onClose:r}){const s=DQ(t?.startedAt,t?.endedAt),a=vV(t?.startedAt),i=vV(t?.endedAt);return o.jsxs(Na,{children:[o.jsxs(Na.Header,{children:[o.jsxs(Na.Heading,{children:["Span ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Na.CloseButton,{onClick:r})]}),n?o.jsx(Na.LoadingData,{children:"Loading span..."}):t?o.jsxs(Na.Content,{children:[o.jsxs(jb,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(jb.Key,{children:"Type"}),o.jsx(jb.Value,{children:t.spanType})]}),a&&o.jsxs(o.Fragment,{children:[o.jsx(jb.Key,{children:"Started"}),o.jsx(jb.Value,{children:a})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(jb.Key,{children:"Ended"}),o.jsx(jb.Value,{children:i})]}),s&&o.jsxs(o.Fragment,{children:[o.jsx(jb.Key,{children:"Duration"}),o.jsx(jb.Value,{children:s})]})]}),o.jsx("br",{}),o.jsx(Na.CodeSection,{title:"Input",icon:o.jsx(wx,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(Na.CodeSection,{title:"Output",icon:o.jsx(rm,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(Na.CodeSection,{title:"Metadata",icon:o.jsx(sc,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(Na.CodeSection,{title:"Attributes",icon:o.jsx(sc,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(Na.NoData,{children:"Span not found."})]})}function tbs({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:a}){const i=g.useMemo(()=>XQ(t??[]),[t]),[l,c]=g.useState([]);g.useEffect(()=>{i.length>0&&c(WAe(i))},[i]);const u=d=>{s?.(a===d?void 0:d)};return o.jsxs(Na,{children:[o.jsxs(Na.Header,{children:[o.jsxs(Na.Heading,{children:["Trace ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Na.CloseButton,{onClick:r})]}),n?o.jsx(Na.LoadingData,{children:"Loading trace..."}):i.length===0?o.jsx(Na.NoData,{children:"No spans found for this trace."}):o.jsx(Na.Content,{children:o.jsx(dVt,{hierarchicalSpans:i,onSpanClick:u,selectedSpanId:a??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}function nbs(){const[e,t]=Ma(),n=Jys(e,t),r=Gys(e,t),[s,a]=g.useState(),[i,l]=g.useState(!1),{data:c=[],isPending:u}=rRe(),{data:d=[],isPending:f}=eRe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:p=[],isPending:h}=tRe(),{data:m=[],isPending:v}=nRe(),y=g.useMemo(()=>zys({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:p,loading:{tags:u,entityNames:f,serviceNames:v,environments:h}}),[c,d,m,p,u,f,v,h]),b=g.useMemo(()=>Vys({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:T}=Pys({filters:b}),{logIdMap:E,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:R}=Kys(x,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:L,isLoading:M}=RAe(n.featuredTraceId??null),{data:F,isLoading:H}=HAe(n.featuredTraceId??"",n.featuredSpanId??""),z=g.useCallback(()=>n.applyFilterTokens(Hys(y,n.filterTokens)),[y,n]),q=g.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),V=g.useCallback(Y=>n.handleFeaturedChange({traceId:Y,spanId:null}),[n]),D=g.useCallback((Y,te)=>n.handleFeaturedChange({traceId:Y,spanId:te}),[n]),G=g.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),U=g.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),P=g.useCallback(Y=>n.handleFeaturedChange({spanId:Y??null}),[n]),B=o.jsxs(Lt.TopArea,{children:[o.jsx(Lt.Row,{children:o.jsxs(Lt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(W4,{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(KAe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:S,onStartTextFilter:a})]})}),o.jsx(Oys,{isLoading:S,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:z,onRemoveAll:n.handleRemoveAll,onSave:r.handleSave,onRemoveSaved:r.hasSavedFilters?r.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(k)return o.jsxs(Lt,{width:"wide",height:"full",children:[B,o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(pys,{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(Lt,{width:"wide",height:"full",children:[B,o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(Tys,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Lt,{width:"wide",height:"full",children:[B,o.jsx(hys,{logCollapsed:i,listSlot:o.jsx(kys,{logs:x,isLoading:S,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:T,logIdMap:E,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(fys,{log:N,onClose:q,onTraceClick:V,onSpanClick:D,onPrevious:A,onNext:R,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(tbs,{traceId:n.featuredTraceId,spans:L?.spans,isLoading:M,onClose:G,onSpanSelect:P,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(ebs,{spanId:n.featuredSpanId,span:F?.span,isLoading:H,onClose:U}):null})]})}function rbs({server:e,rowProps:t}){const{paths:n,Link:r}=un(),a=Ge().options.baseUrl,i=a?`${a}/api/mcp/${e.id}/sse`:"",{data:l}=jBt(e),c=Object.values(l||{}),u=c.length,d=c.filter(h=>h.toolType==="agent").length,f=c.filter(h=>h.toolType==="workflow").length,p=tm(e.name,50);return o.jsxs(he.RowLink,{to:n.mcpServerLink(e.id),LinkComponent:r,...t,children:[o.jsx(he.NameCell,{children:p}),o.jsx(he.DescriptionCell,{children:i}),o.jsx(he.TextCell,{className:"text-center",children:d||""}),o.jsx(he.TextCell,{className:"text-center",children:u||""}),o.jsx(he.TextCell,{className:"text-center",children:f||""})]})}function sbs({mcpServers:e,isLoading:t,search:n=""}){const r=g.useMemo(()=>{const i=n.toLowerCase();return e.filter(l=>l.name?.toLowerCase().includes(i)||l.id?.toLowerCase().includes(i))},[e,n]),{containerRef:s,getRowProps:a}=so({count:r.length});return t?o.jsx(Fo,{columns:"auto 1fr auto auto auto"}):o.jsxs(he,{columns:"auto 1fr auto auto auto",scrollRef:s,children:[o.jsxs(he.Top,{children:[o.jsx(he.TopCell,{children:"Name"}),o.jsx(he.TopCell,{children:"URL"}),o.jsx(he.TopCellSmart,{long:"Agents",short:o.jsx(Ai,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(he.TopCellSmart,{long:"Tools",short:o.jsx(zf,{}),tooltip:"Tools",className:"text-center"}),o.jsx(he.TopCellSmart,{long:"Workflows",short:o.jsx(Bc,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(he.NoMatch,{message:"No MCP Servers match your search"}):null,r.map((i,l)=>o.jsx(rbs,{server:i,rowProps:a(l)},i.id))]})}const abs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx($c,{}),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(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(ea,{})]})})}),ibs=()=>{const{data:e=[],isLoading:t,error:n}=TQ(),[r,s]=g.useState("");return n&&ps(n)?o.jsx(Zn,{children:o.jsx(Ts,{})}):n&&hs(n)?o.jsx(Zn,{children:o.jsx(Os,{resource:"MCP servers"})}):n?o.jsx(Zn,{children:o.jsx($a,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(Zn,{children:o.jsx(abs,{})}):o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx(od,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(sbs,{mcpServers:e,isLoading:t,search:r})]})},obs=(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 lbs({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=un(),i=g.useMemo(()=>obs(e,t),[e,t]),l=g.useMemo(()=>i.filter(d=>d.id.toLowerCase().includes(r.toLowerCase())),[i,r]),{containerRef:c,getRowProps:u}=so({count:l.length});return n?o.jsx(Fo,{columns:"auto 1fr auto"}):o.jsxs(he,{columns:"auto 1fr auto",scrollRef:c,children:[o.jsxs(he.Top,{children:[o.jsx(he.TopCell,{children:"Name"}),o.jsx(he.TopCell,{children:"Description"}),o.jsx(he.TopCellSmart,{long:"Agents",short:o.jsx(Ai,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(he.NoMatch,{message:"No Tools match your search"}):null,l.map((d,f)=>{const p=tm(d.id,50),h=tm(d.description??"",200),m=d.agents.length;return o.jsxs(he.RowLink,{to:s.toolLink(d.id),LinkComponent:a,...u(f),children:[o.jsx(he.NameCell,{children:p}),o.jsx(he.DescriptionCell,{children:h}),o.jsx(he.TextCell,{className:"text-center",children:m||""})]},d.id)})]})}const cbs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx($c,{}),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(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(ea,{})]})})}),ubs=()=>{const e=Ge();return Sn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new D_;Object.entries(r??{}).forEach(([a,i])=>{s.set(a,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(a){throw ze.error("Error executing dev tool"),console.error("Error executing dev tool:",a),a}}})},dbs=({toolId:e})=>{const{canExecute:t}=Eo(),n=t("tools"),{data:r={}}=zm(),s=g.useMemo(()=>{for(const v of Object.values(r))if(v.tools){const y=Object.values(v.tools).find(b=>b.id===e);if(y)return y}return null},[r,e]),{data:a,isLoading:i,error:l}=vRr(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=ubs(),{requestContext:p}=ys();g.useEffect(()=>{if(l){const v=l instanceof Error?l.message:"Failed to load tool";ze.error(`Error loading tool: ${v}`)}},[l]);const h=async(v,y)=>{if(!c)return;const b={...p??{},...y??{}};return u({toolId:c.id,input:v,requestContext:b})},m=c?.inputSchema?wm(Tx(c?.inputSchema)):ws({});return i?o.jsxs("div",{className:"p-6",children:[o.jsx(Ct,{className:"mb-4 h-8 w-48"}),o.jsx(Ct,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(lAe,{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(ve,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ve,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function fbs({value:e,onValueChange:t,placeholder:n="Select a tool...",searchPlaceholder:r="Search tools...",emptyText:s="No tools found.",className:a,disabled:i=!1,variant:l,size:c}){const{data:u={},isLoading:d,isError:f,error:p}=XI(),{data:h={},isLoading:m,isError:v,error:y}=zm(),{navigate:b,paths:x}=un();g.useEffect(()=>{if(f){const C=p instanceof Error?p.message:"Failed to load tools";ze.error(`Error loading tools: ${C}`)}},[f,p]),g.useEffect(()=>{if(v){const C=y instanceof Error?y.message:"Failed to load agents";ze.error(`Error loading agents: ${C}`)}},[v,y]);const S=new Map;Object.values(h).forEach(C=>{C.tools&&Object.values(C.tools).forEach(T=>{S.has(T.id)||S.set(T.id,T)})}),Object.values(u).forEach(C=>{S.has(C.id)||S.set(C.id,C)});const k=Array.from(S.values()).map(C=>({label:C.id,value:C.id})),_=C=>{t?t(C):C&&C!==e&&b(x.toolLink(C))};return o.jsx(yl,{options:k,value:e,onValueChange:_,placeholder:d||m?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||d||m||f||v,variant:l,size:c})}const pbs=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=g.useState({sseUrl:"",httpStreamUrl:""});if(g.useEffect(()=>{if(!t)return;const i=window.MASTRA_SERVER_HOST,l=window.MASTRA_SERVER_PORT;let c=null;i&&l&&(c=`http://${i}:${l}`);const u=c||"http://localhost:4111",d=`${u}/api/mcp/${t.id}/sse`,f=`${u}/api/mcp/${t.id}/mcp`;s({sseUrl:d,httpStreamUrl:f})},[t]),e)return null;if(!t)return o.jsx(hy,{children:o.jsx(ve,{as:"h1",variant:"header-md",className:"text-neutral3 py-20 text-center font-medium",children:"Server not found"})});const a=`npx -y mcp-remote ${n}`;return o.jsxs(hy,{isDivided:!0,children:[o.jsxs("div",{className:"mx-auto w-full max-w-2xl px-8 py-12",children:[o.jsx(ve,{as:"h1",variant:"header-md",className:"text-neutral6 pb-4 font-medium",children:t.name}),o.jsxs("div",{className:"flex items-center gap-1 pb-6",children:[o.jsx(xt,{icon:o.jsx(lVt,{}),size:"sm",children:"Version"}),o.jsx(xt,{size:"sm",children:t.version_detail.version})]}),o.jsx(ve,{className:"text-neutral3 pb-4",children:"This MCP server can be accessed through multiple transport methods. Choose the one that best fits your use case."}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(xt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"HTTP"}),children:"Regular HTTP Endpoint"}),o.jsx(ve,{className:"text-neutral3 pt-1 pb-2",children:"Use for stateless HTTP transport with streamable responses."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ve,{className:"bg-surface4 rounded-lg px-2 py-1",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx(ka,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(xt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"SSE"}),children:"Server-Sent Events"}),o.jsx(ve,{className:"text-neutral3 pt-1 pb-2",children:"Use for real-time communication via SSE."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ve,{className:"bg-surface4 rounded-lg px-2 py-1",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx(ka,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(xt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"CLI"}),children:"Command Line"}),o.jsx(ve,{className:"text-neutral3 pt-1 pb-2",children:"Use for local command-line access via npx and mcp-remote."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ve,{className:"bg-surface4 rounded-lg px-2 py-1",children:a}),o.jsx("div",{className:"pt-1",children:o.jsx(ka,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"border-border1 h-full overflow-y-scroll border-l",children:o.jsx(hbs,{server:t})})]})},hbs=({server:e})=>{const{data:t={},isLoading:n}=jBt(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(We,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(TC,{})}),o.jsx(ve,{variant:"header-md",as:"h2",className:"font-medium",children:"Available Tools"})]}),o.jsx("div",{className:"flex flex-col gap-2 pt-6",children:r.map(s=>{const a=t[s];return o.jsx(gbs,{tool:a,serverId:e.id},s)})})]})};function mbs(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 gbs=({tool:e,serverId:t})=>{const n=g.useRef(null),{Link:r,paths:s}=un(),a=MBt[e.toolType||"tool"],i=mbs(e._meta);return o.jsxs(Hf,{onClick:()=>n.current?.click(),children:[o.jsx(C3t,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Zf,{children:[o.jsx(Wf,{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(xt,{size:"xs",children:"App"})]})}),o.jsx(ch,{children:e.description})]})]})},vbs=()=>{const{serverId:e}=fr(),{data:t=[],isLoading:n}=TQ(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(pbs,{isLoading:n,server:r})})};function ybs(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 bbs=({toolId:e,serverId:t})=>{const{canExecute:n}=Eo(),r=n("tools"),s=Ge(),{data:a,isLoading:i,error:l}=aAe(t,e),{mutateAsync:c,isPending:u,data:d}=Prs(t,e),f=a?ybs(a._meta):void 0,{data:p}=mt({queryKey:["mcp-app-resource",t,f],queryFn:async()=>f?(await s.readMcpServerResource(t,f)).contents[0]?.text??null:null,enabled:!!f}),h=g.useCallback(async(y,b)=>await c(b),[c]);g.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";ze.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(Ct,{className:"mb-4 h-8 w-48"}),o.jsx(Ct,{className:"h-32 w-full"})]});if(l)return null;if(!a)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ve,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ve,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let v;try{v=wm(a.inputSchema)}catch(y){console.error("Error processing input schema:",y),ze.error("Failed to process tool input schema."),v=ws({})}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(TBt,{html:p,toolName:a.name??a.id,onToolCall:h})}),o.jsx(lAe,{executionResult:d,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},xbs=()=>{const{serverId:e,toolId:t}=fr(),{data:n,isLoading:r}=aAe(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(bbs,{toolId:t,serverId:e})})},cHt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],YN="rootEntityType",KN={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"},lY=Object.keys(KN),gRe="mastra:metrics:saved-filters";function wbs(e){const t=Cbs(e);try{localStorage.setItem(gRe,t.toString())}catch{}}function Sbs(){try{localStorage.removeItem(gRe)}catch{}}function uHt(){try{const e=localStorage.getItem(gRe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function kbs(e){if(e.has(YN))return!0;for(const t of lY)if(e.has(KN[t]))return!0;return!1}function Obs({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:cHt.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 _bs(e){const t=[],n=new Map([[YN,"rootEntityType"]]);for(const s of lY)n.set(KN[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 Cbs(e){const t=new URLSearchParams,n=e.getAll(YN);for(const r of n)t.append(YN,r);for(const r of lY){const s=KN[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function Ebs(e,t){e.delete(YN);for(const n of lY)e.delete(KN[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?YN:KN[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 Tbs="Any";function Ctt(e){const t=e.trim();return t===""||t===Tbs}const jbs=new Set(cHt.map(e=>e.entityType));function Ett(e){const t=e.trim();return jbs.has(t)?t:void 0}function Nbs(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=>!Ctt(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?Ett(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(Ctt(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=Ett(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const dHt=[{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"}],Ibs=new Set(dHt.map(e=>e.value));function Abs(e){return typeof e=="string"&&(Ibs.has(e)||e==="custom")}const fHt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function cY(){return g.useContext(fHt)}function Rbs(e,t){return e!=="custom"?dHt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${dr(t.from,"MMM d, yyyy")} – ${dr(t.to,"MMM d, yyyy")}`:dr(t.from,"MMM d, yyyy"):"Custom range"}function Pbs({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:a,onCustomRangeChange:i,tracesBasePath:l,logsBasePath:c}){const u=g.useMemo(()=>JSON.stringify(n),[n]),d=g.useMemo(()=>n,[u]),f=g.useMemo(()=>Nbs(d),[d]),p=g.useMemo(()=>JSON.stringify(f),[f]),h=Rbs(t,a),m=g.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(fHt.Provider,{value:m,children:e})}const $bs=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function Mbs(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 Dbs(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 Lbs(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=cY(),s=g.useRef(e);s.current=e;const a=g.useRef(n);return a.current=n,o.jsx(W4,{preset:Mbs(e),onPresetChange:i=>{const l=Dbs(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:$bs})}const c0e=1440*60*1e3,Fbs={"24h":c0e,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function zbs(e,t,n){if(e!=="custom"){const r=Fbs[e]??c0e;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-c0e),end:t?.to??new Date(n)}}function Vm(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=cY(),s=g.useRef(null),a=e==="custom"?`custom:${t?.from?.getTime()??""}:${t?.to?.getTime()??""}`:`preset:${e}`;(!s.current||s.current.key!==a)&&(s.current={key:a,anchor:Date.now()});const i=s.current.anchor,l=g.useMemo(()=>zbs(e,t,i),[e,t,i]),c=g.useMemo(()=>({timestamp:l,...n}),[l,r]),u=g.useMemo(()=>`${a}|${r}`,[a,r]);return{datePreset:e,customRange:t,timestamp:l,filters:c,dimensionalFilter:n,filterKey:u}}function pHt(){const e=Ge(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function JL({href:e,LinkComponent:t="a"}){return o.jsx(le,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(ac,{})})}function Bbs({href:e,LinkComponent:t="a"}){return o.jsx(le,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(wXt,{})})}function Ubs(e){return e==="agents"||e==="workflows"||e==="tools"}function Ttt(e,t){if(e.length===0)return"0";const n=e.reduce((r,s)=>{const a=s[t];return r+(typeof a=="number"&&Number.isFinite(a)?a:0)},0);return`${Math.round(n/e.length)}`}function qbs(e){const t=e;return typeof t?.tsMs=="number"&&Number.isFinite(t.tsMs)}const Vbs=[{dataKey:"p50",label:"p50",color:Zp.blue,aggregate:e=>({value:Ttt(e,"p50"),suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:Zp.yellow,aggregate:e=>({value:Ttt(e,"p95"),suffix:"avg ms"})}];function eoe({data:e,onPointClick:t}){return e.length===0?o.jsx(Vt.NoData,{message:"No latency data yet"}):o.jsx(RD,{data:e,series:Vbs,onPointClick:t?n=>qbs(n)?t(n):void 0:void 0})}function Hbs({data:e,isLoading:t,isError:n,onPointClick:r,actions:s}){const a=(e?.agentData.length??0)>0,i=(e?.workflowData.length??0)>0,l=(e?.toolData.length??0)>0,c={agents:a,workflows:i,tools:l},u=a?"agents":i?"workflows":l?"tools":"agents",[d,f]=g.useState("agents"),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),v=e?Object.values(e).filter(Array.isArray).flat().map(b=>b.p50).filter(b=>typeof b=="number"):[],y=v.length>0?`${Math.round(v.reduce((b,x)=>b+x,0)/v.length)}ms`:"—";return o.jsxs(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(Vt.Summary,{value:y,label:"Avg p50"}),h?o.jsx(Vt.Actions,{children:h}):null]}),t?o.jsx(Vt.Loading,{}):n?o.jsx(Vt.Error,{message:"Failed to load latency data"}):o.jsx(Vt.Content,{children:m?o.jsxs(Wc,{value:p,onValueChange:b=>{Ubs(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(Hc,{children:[o.jsx(Ur,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(Ur,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(Ur,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(Ss,{value:"agents",children:o.jsx(eoe,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(Ss,{value:"workflows",children:o.jsx(eoe,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(Ss,{value:"tools",children:o.jsx(eoe,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Vt.NoData,{message:"No latency data yet"})})]})}function Wbs(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 Zbs(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 hHt(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=Wbs(s);l&&e.set(t,l)}function $o(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function mHt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function jtt({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const a=new URLSearchParams;a.set(Mw,"branches"),hHt(a,Dw,Lw,Fw,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Wx,i),r.status&&a.set(Zx,r.status),$o(a,Tl.entityName,r.entityName??n.entityName),$o(a,Tl.threadId,r.threadId??n.threadId),$o(a,Tl.resourceId,r.resourceId??n.resourceId),$o(a,Tl.entityId,n.entityId),$o(a,Tl.runId,n.runId),$o(a,Tl.sessionId,n.sessionId),$o(a,Tl.requestId,n.requestId),$o(a,Tl.userId,n.userId),$o(a,Tl.organizationId,n.organizationId),$o(a,Tl.experimentId,n.experimentId),$o(a,Tl.serviceName,n.serviceName),$o(a,Tl.environment,n.environment),mHt(a,Tl.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function Gbs({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;hHt(a,tx,nx,rx,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Gx,i),$o(a,jl.entityName,r.entityName??n.entityName),$o(a,jl.threadId,r.threadId??n.threadId),$o(a,jl.resourceId,r.resourceId??n.resourceId),$o(a,jl.runId,n.runId),$o(a,jl.sessionId,n.sessionId),$o(a,jl.requestId,n.requestId),$o(a,jl.userId,n.userId),$o(a,jl.organizationId,n.organizationId),$o(a,jl.experimentId,n.experimentId),$o(a,jl.serviceName,n.serviceName),$o(a,jl.environment,n.environment),mHt(a,jl.tags,n.tags),r.status==="error"&&a.append(jl.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function gA(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=cY(),a=g.useCallback((c={})=>jtt({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=g.useCallback((c={})=>Gbs({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=Zbs(u,d);return jtt({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const gHt="1h";async function toe(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:gHt,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 Qbs(){const e=Ge(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([toe(e,"mastra_agent_duration_ms",t),toe(e,"mastra_workflow_duration_ms",t),toe(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:gHt}}})}const Ntt={agents:Ku.AGENT,workflows:Ku.WORKFLOW_RUN,tools:Ku.TOOL};function Ybs(){const{data:e,isLoading:t,isError:n}=Qbs(),{getTracesHref:r,getBucketTracesHref:s}=gA(),{Link:a}=un(),i=Vr();return o.jsx(Hbs,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:Ntt[l]},c.tsMs,"1h"))},actions:l=>o.jsx(JL,{href:r({rootEntityType:Ntt[l]}),LinkComponent:a})})}function Kbs(e){return e==="threads"||e==="resources"}function noe(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function Xbs({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("threads"),c=e.data?.map(y=>({...y,key:y.threadId}))??[],u=t.data?.map(y=>({...y,key:y.resourceId}))??[],d=c.length>0,f=u.length>0,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,v=typeof s=="function"?s(i):s;return o.jsxs(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&o.jsx(Vt.Summary,{value:p.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&o.jsx(Vt.Summary,{value:h.toLocaleString(),label:"Total threads"}),v?o.jsx(Vt.Actions,{children:v}):null]}),m.isLoading?o.jsx(Vt.Loading,{}):m.isError?o.jsx(Vt.Error,{message:"Failed to load memory data"}):o.jsx(Vt.Content,{children:o.jsxs(Wc,{defaultTab:"threads",value:i,onValueChange:y=>{Kbs(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Hc,{children:[o.jsx(Ur,{value:"threads",children:"Threads"}),o.jsx(Ur,{value:"resources",children:"Resources"})]}),o.jsx(Ss,{value:"threads",children:d?o.jsxs(he,{columns:"auto auto auto auto auto",...Xxe,children:[o.jsxs(he.Top,{children:[o.jsx(he.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(he.RowHeaderCell,{className:"text-ui-sm",children:noe(y.threadId)}),o.jsx(he.NumberCell,{children:y.resourceId?noe(y.resourceId):"—"}),o.jsx(he.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(he.NumberCell,{children:y.tokens>0?al(y.tokens):"—"}),o.jsx(he.NumberCell,{children:y.cost!=null?Wp(y.cost,y.costUnit):"—"})]});return b?o.jsx(he.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(he.RowStatic,{children:x},y.key)})]}):o.jsx(Vt.NoData,{message:"No thread activity yet"})}),o.jsx(Ss,{value:"resources",children:f?o.jsxs(he,{columns:"auto auto auto auto",...Xxe,children:[o.jsxs(he.Top,{children:[o.jsx(he.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(he.RowHeaderCell,{className:"text-ui-sm",children:noe(y.resourceId)}),o.jsx(he.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(he.NumberCell,{children:y.tokens>0?al(y.tokens):"—"}),o.jsx(he.NumberCell,{children:y.cost!=null?Wp(y.cost,y.costUnit):"—"})]});return b?o.jsx(he.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(he.RowStatic,{children:x},y.key)})]}):o.jsx(Vt.NoData,{message:"No resource activity yet"})})]})})]})}const roe=20;function Jbs(){const e=Ge(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","top-active-threads",n],queryFn:async()=>{const r={groupBy:["threadId","resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count",limit:roe}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:roe}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:roe})]),l=new Map,c=d=>mA(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 soe=20;function exs(){const e=Ge(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","top-resources-by-threads",n],queryFn:async()=>{const r={groupBy:["resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",limit:soe}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:soe}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:soe})]),l=new Map,c=d=>mA(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 txs(){const e=Jbs(),t=exs(),{getTracesHref:n}=gA(),{Link:r}=un();return o.jsx(Xbs,{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 e5({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:a}){const i=t!=null;return o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:e}),o.jsx(Xr.Value,{className:i?void 0:"invisible",children:i?t:"—"}),a?o.jsx(Xr.Error,{}):s?o.jsx(Xr.Loading,{}):i?r!=null?o.jsx(Xr.Change,{changePct:r,prevValue:n}):o.jsx(Xr.NoChange,{}):o.jsx(Xr.NoData,{})]})}function nxs(){const e=Ge(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","active-resources-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"resourceId",filters:t,comparePeriod:"previous_period"})})}function rxs(){const e=Ge(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","active-threads-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",filters:t,comparePeriod:"previous_period"})})}function sxs(){const e=Ge(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","model-cost-kpi",n],queryFn:async()=>{const r=await e.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"});return{cost:r.estimatedCost??null,costUnit:r.costUnit??null,previousCost:r.previousEstimatedCost??null,costChangePercent:r.costChangePercent??null}}})}function axs(){const e=Ge(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","total-tokens-kpi",n],queryFn:async()=>{const[r,s]=await Promise.all([e.getMetricAggregate({name:["mastra_model_total_input_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"}),e.getMetricAggregate({name:["mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"})]),a=r.value!=null||s.value!=null,i=r.previousValue!=null||s.previousValue!=null,l=(r.value??0)+(s.value??0),c=(r.previousValue??0)+(s.previousValue??0),u=i&&c>0?(l-c)/c*100:null;return{value:a?l:null,previousValue:i?c:null,changePercent:u}}})}function ixs(){const{data:e,isLoading:t,isError:n}=pHt();return o.jsx(e5,{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 oxs(){const{data:e,isLoading:t,isError:n}=sxs();return o.jsx(e5,{label:"Total Model Cost",value:e?.cost!=null?Wp(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?Wp(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function lxs(){const{data:e,isLoading:t,isError:n}=axs();return o.jsx(e5,{label:"Total Tokens",value:e?.value!=null?al(e.value):null,prevValue:e?.previousValue!=null?al(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function cxs(){const{data:e,isLoading:t,isError:n}=rxs();return o.jsx(e5,{label:"Total Threads",value:e?.value!=null?al(e.value):null,prevValue:e?.previousValue!=null?al(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function uxs(){const{data:e,isLoading:t,isError:n}=nxs();return o.jsx(e5,{label:"Total Resources",value:e?.value!=null?al(e.value):null,prevValue:e?.previousValue!=null?al(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function dxs({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=>fxs(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(YAe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(GAe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function fxs(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 pxs({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const i=!!e&&e.length>0;return o.jsxs(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Model Usage & Cost",description:"Token consumption by model."}),i&&(()=>{const l=e.reduce((d,f)=>d+(f.cost??0),0),c=new Set;for(const d of e)d.cost!=null&&d.costUnit&&c.add(d.costUnit);let u;return c.size===0?u=l>0?Wp(l):"—":c.size===1?u=l>0?Wp(l,[...c][0]):"—":u="Mixed",o.jsx(Vt.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(Vt.Actions,{children:s}):null]}),t?o.jsx(Vt.Loading,{}):n?o.jsx(Vt.Error,{message:"Failed to load model usage data"}):o.jsx(Vt.Content,{children:i?o.jsxs(he,{columns:"auto auto auto auto auto auto",...Xxe,children:[o.jsxs(he.Top,{children:[o.jsx(he.TopCell,{sticky:"start",children:"Model"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(he.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(he.RowHeaderCell,{className:"text-ui-sm",children:l.model}),o.jsx(he.NumberCell,{children:l.input}),o.jsx(he.NumberCell,{children:l.output}),o.jsx(he.NumberCell,{children:l.cacheRead}),o.jsx(he.NumberCell,{children:l.cacheWrite}),o.jsx(he.NumberCell,{highlight:!0,children:l.cost!=null?Wp(l.cost,l.costUnit):"—"})]});return c?o.jsx(he.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(he.RowStatic,{children:u},l.model)})]}):o.jsx(Vt.NoData,{message:"No model usage data yet"})})]})}function hxs(){const e=Ge(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","model-usage-cost",n],queryFn:async()=>{const[r,s,a,i]=await Promise.all(["mastra_model_total_input_tokens","mastra_model_total_output_tokens","mastra_model_input_cache_read_tokens","mastra_model_input_cache_write_tokens"].map(d=>e.getMetricBreakdown({name:[d],groupBy:["model"],aggregation:"sum",orderDirection:"DESC",filters:t})));if(!r||!s||!a||!i)return[];const l=new Map,c=d=>mA(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:al(f.input),output:al(f.output),cacheRead:al(f.cacheRead),cacheWrite:al(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function mxs(){const{data:e,isLoading:t,isError:n}=hxs(),{getTracesHref:r}=gA(),{Link:s}=un();return o.jsx(pxs,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:Ku.AGENT}),actions:o.jsx(JL,{href:r({rootEntityType:Ku.AGENT}),LinkComponent:s})})}function gxs(e){return e==="tokens"||e==="cost"}function vxs({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("tokens"),c=e??[],u=c.length>0,d=c.reduce((b,x)=>b+x.total,0),f=c.filter(b=>b.cost!=null&&b.cost>0),p=new Set(f.map(b=>b.costUnit??"usd")),h=p.size<=1,m=h?[...p][0]??"usd":null,v=h?f.reduce((b,x)=>b+(x.cost??0),0):0,y=h&&v>0;return o.jsxs(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&y?o.jsx(Vt.Summary,{value:Wp(v,m),label:"Total cost"}):o.jsx(Vt.Summary,{value:al(d),label:"Total tokens"})),u&&s?o.jsx(Vt.Actions,{children:s}):null]}),t?o.jsx(Vt.Loading,{}):n?o.jsx(Vt.Error,{message:"Failed to load token usage data"}):o.jsx(Vt.Content,{children:u?o.jsxs(Wc,{defaultTab:"tokens",value:i,onValueChange:b=>{gxs(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Hc,{children:[o.jsx(Ur,{value:"tokens",children:"Tokens"}),o.jsx(Ur,{value:"cost",children:"Cost"})]}),o.jsx(Ss,{value:"tokens",children:o.jsx(QN,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:Zp.blueDark},{label:"Output",color:Zp.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:al})}),o.jsx(Ss,{value:"cost",children:y?o.jsx(QN,{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:Zp.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>Wp(b,m)}):o.jsx(Vt.NoData,{message:"No cost data yet"})})]}):o.jsx(Vt.NoData,{message:"No token usage data yet"})})]})}function yxs(){const e=Ge(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","token-usage-by-agent",n],queryFn:async()=>{const r={groupBy:["entityName"],aggregation:"sum",orderDirection:"DESC",filters:t},[s,a]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"]}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"]})]),i=new Map,l=u=>mA(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 bxs(){const{data:e,isLoading:t,isError:n}=yxs(),{getTracesHref:r}=gA(),{Link:s}=un();return o.jsx(vxs,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:Ku.AGENT,entityName:a.name}),actions:o.jsx(JL,{href:r({rootEntityType:Ku.AGENT}),LinkComponent:s})})}function u0e(e,t=al){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const xxs=[{dataKey:"input",label:"Input tokens",color:Zp.blue,aggregate:u0e("input")},{dataKey:"output",label:"Output tokens",color:Zp.yellow,aggregate:u0e("output")}];function wxs(e){return e==="tokens"||e==="cost"}function Sxs({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[a,i]=g.useState("tokens"),l=e??[],c=l.map(k=>({...k})),u=l.length>0,d=l.reduce((k,_)=>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),v=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:Zp.purple,aggregate:u0e("cost",k=>Wp(k,v))}];return o.jsxs(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Token usage over time",description:x}),u&&(a==="cost"&&b?o.jsx(Vt.Summary,{value:Wp(y,v),label:"Total cost"}):o.jsx(Vt.Summary,{value:al(d),label:"Total tokens"})),u&&s?o.jsx(Vt.Actions,{children:s}):null]}),n?o.jsx(Vt.Loading,{}):r?o.jsx(Vt.Error,{message:"Failed to load token usage timeline"}):o.jsx(Vt.Content,{children:u?o.jsxs(Wc,{defaultTab:"tokens",value:a,onValueChange:k=>{wxs(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(Hc,{children:[o.jsx(Ur,{value:"tokens",children:"Tokens"}),o.jsx(Ur,{value:"cost",children:"Cost"})]}),o.jsx(Ss,{value:"tokens",children:o.jsx(RD,{data:c,series:xxs})}),o.jsx(Ss,{value:"cost",children:b?o.jsx(RD,{data:p,series:S}):o.jsx(Vt.NoData,{message:"No cost data yet"})})]}):o.jsx(Vt.NoData,{message:"No token usage data yet"})})]})}function kxs(e){return e==="24h"?"1h":"1d"}function Oxs(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 Itt(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 _xs(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function Cxs(){const e=Ge(),{datePreset:t,filters:n,filterKey:r}=Vm(),s=kxs(t);return mt({queryKey:["metrics","token-usage-timeseries",r,s],queryFn:async()=>{const[a,i]=await Promise.all([e.getMetricTimeSeries({name:["mastra_model_total_input_tokens"],interval:s,aggregation:"sum",filters:n}),e.getMetricTimeSeries({name:["mastra_model_total_output_tokens"],interval:s,aggregation:"sum",filters:n})]),l=new Map;return Itt(l,a.series[0],"input"),Itt(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:Oxs(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:_xs(u)}}),interval:s}}})}function Exs(){const{data:e,isLoading:t,isError:n}=Cxs(),{getTracesHref:r}=gA(),{Link:s}=un();return o.jsx(Sxs,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(JL,{href:r(),LinkComponent:s})})}function aoe({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(QN,{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:Zp.blueDark},{label:"Errors",color:Zp.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:al})}function Txs({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:a,LinkComponent:i}){const[l,c]=g.useState("agents"),u=typeof a=="function"?a(l):a,d=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),f=e?[...e.agentData,...e.workflowData,...e.toolData].reduce((m,v)=>m+v.completed+v.errors,0):0,p=m=>r?v=>r(m,v):void 0,h=m=>s?v=>s(m,v):void 0;return o.jsxs(Vt,{children:[o.jsxs(Vt.TopBar,{children:[o.jsx(Vt.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(Vt.Summary,{value:al(f),label:"Total runs"}),u?o.jsx(Vt.Actions,{children:u}):null]}),t?o.jsx(Vt.Loading,{}):n?o.jsx(Vt.Error,{message:"Failed to load trace volume data"}):o.jsx(Vt.Content,{children:d?o.jsxs(Wc,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Hc,{children:[o.jsx(Ur,{value:"agents",children:"Agents"}),o.jsx(Ur,{value:"workflows",children:"Workflows"}),o.jsx(Ur,{value:"tools",children:"Tools"})]}),o.jsx(Ss,{value:"agents",children:e.agentData.length>0?o.jsx(aoe,{data:e.agentData,rowHrefs:p("agents"),errorHrefs:h("agents"),LinkComponent:i}):o.jsx(Vt.NoData,{message:"No agent data yet"})}),o.jsx(Ss,{value:"workflows",children:e.workflowData.length>0?o.jsx(aoe,{data:e.workflowData,rowHrefs:p("workflows"),errorHrefs:h("workflows"),LinkComponent:i}):o.jsx(Vt.NoData,{message:"No workflow data yet"})}),o.jsx(Ss,{value:"tools",children:e.toolData.length>0?o.jsx(aoe,{data:e.toolData,rowHrefs:p("tools"),errorHrefs:h("tools"),LinkComponent:i}):o.jsx(Vt.NoData,{message:"No tool data yet"})})]}):o.jsx(Vt.NoData,{message:"No trace volume data yet"})})]})}async function ioe(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=mA(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 jxs(){const e=Ge(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([ioe(e,"mastra_agent_duration_ms",t),ioe(e,"mastra_workflow_duration_ms",t),ioe(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const d8={agents:Ku.AGENT,workflows:Ku.WORKFLOW_RUN,tools:Ku.TOOL};function Nxs(){const{data:e,isLoading:t,isError:n}=jxs(),{getTracesHref:r,getLogsHref:s}=gA(),{Link:a}=un();return o.jsx(Txs,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:d8[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:d8[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(JL,{href:r({rootEntityType:d8[i]}),LinkComponent:a}),o.jsx(Bbs,{href:s({rootEntityType:d8[i],status:"error"}),LinkComponent:a})]})})}const ooe="period",f8="dateFrom",p8="dateTo";function Ixs(){const[e,t]=Ma(),n=e.get(ooe),r=Abs(n)?n:"24h",s=g.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(f8)),p=d(e.get(p8));if(!(!f&&!p))return{from:f,to:p}},[r,e.toString()]),a=g.useMemo(()=>_bs(e),[e.toString()]),i=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d==="24h"?p.delete(ooe):p.set(ooe,d),d!=="custom"&&(p.delete(f8),p.delete(p8)),p},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d?.from?p.set(f8,d.from.toISOString()):p.delete(f8),d?.to?p.set(p8,d.to.toISOString()):p.delete(p8),p},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return Ebs(p,d),p},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,kbs(e)))return;const d=uHt();d&&t(f=>{const p=new URLSearchParams(f);for(const[h,m]of d)p.append(h,m);return p},{replace:!0})},[]),o.jsx(Pbs,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(Axs,{})})}function Axs(){const[e]=Ma(),{error:t,isLoading:n}=pHt(),{filterTokens:r,setFilterTokens:s}=cY(),[a,i]=g.useState(),{supportsMetrics:l,isInMemory:c,isLoading:u}=vVt(),{data:d,isLoading:f}=rRe(),{data:p,isLoading:h}=eRe(),{data:m,isLoading:v}=nRe(),{data:y,isLoading:b}=tRe(),x=g.useMemo(()=>Obs({availableTags:d??[],availableEntityNames:p??[],availableServiceNames:m??[],availableEnvironments:y??[],loading:{tags:f,entityNames:h,serviceNames:v,environments:b}}),[d,p,m,y,f,h,v,b]),[S,k]=g.useState(()=>uHt()!==null),_=g.useCallback(()=>{wbs(e),k(!0),ze.success("Filters setting for Metrics saved")},[e]),C=g.useCallback(()=>{Sbs(),k(!1),ze.success("Filters setting for Metrics cleared up")},[]),T=g.useCallback(()=>{s([])},[s]),E=g.useCallback(()=>{const N=r.map(I=>{const A=x.find(R=>R.id===I.fieldId);return A?A.kind==="text"?{fieldId:I.fieldId,value:""}:A.kind==="pick-multi"?A.multi?{fieldId:I.fieldId,value:[]}:{fieldId:I.fieldId,value:"Any"}:A.kind==="multi-select"?{fieldId:I.fieldId,value:[]}:I:I});s(N)},[x,r,s]);return t&&ps(t)?o.jsx(Zn,{children:o.jsx(Ts,{})}):t&&hs(t)?o.jsx(Zn,{children:o.jsx(Os,{resource:"metrics"})}):t?o.jsx(Zn,{children:o.jsx($a,{title:"Failed to load metrics",message:t.message})}):o.jsxs(Lt,{width:"wide",height:"full",children:[o.jsxs(Lt.TopArea,{children:[o.jsx(Lt.Row,{children:o.jsxs(Lt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(Lbs,{}),o.jsx(KAe,{fields:x,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(dxs,{isLoading:n,filterFields:x,filterTokens:r,onFilterTokensChange:s,onClear:E,onRemoveAll:T,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(Rn,{variant:"info",title:"Metrics are not persisted",children:o.jsx(Rn.Message,{children:"This project uses in-memory storage for observability. Metrics will be lost on every server restart. For persistent metrics, switch the observability storage to ClickHouse, DuckDB, Postgres v-next, or Spanner."})}),o.jsxs(s0e,{children:[o.jsx(ixs,{}),o.jsx(oxs,{}),o.jsx(lxs,{}),o.jsx(cxs,{}),o.jsx(uxs,{})]}),o.jsxs(s0e,{children:[o.jsx(mxs,{}),o.jsx(bxs,{}),o.jsx(Exs,{}),o.jsx(txs,{}),o.jsx(Nxs,{}),o.jsx(Ybs,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(br,{iconSlot:o.jsx($c,{}),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(le,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(ea,{})]})})})]})}const Rxs=50;function Pxs(){const{paths:e}=un(),{isCmsAvailable:t}=bS(),[n,r]=g.useState(""),[s,a]=g.useState(0),{data:i,isLoading:l,error:c,isPlaceholderData:u}=zBt({page:s,perPage:Rxs}),d=i?.promptBlocks??[],f=i?.hasMore??!1,p=g.useCallback(()=>{u||a(v=>v+1)},[u]),h=g.useCallback(()=>{u||a(v=>Math.max(0,v-1))},[u]),m=g.useCallback(v=>{r(v),a(0)},[]);return c&&ps(c)?o.jsx(Zn,{children:o.jsx(Ts,{})}):c&&hs(c)?o.jsx(Zn,{children:o.jsx(Os,{resource:"prompt blocks"})}):c?o.jsx(Zn,{children:o.jsx($a,{title:"Failed to load prompt blocks",message:c.message})}):d.length===0&&!l&&s===0?o.jsx(Zn,{children:o.jsx(Fas,{})}):o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(od,{onSearch:m,label:"Filter prompts",placeholder:"Filter by name or description"})}),t&&o.jsxs(le,{as:Ba,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(Cr,{}),"Create Prompt"]})]})}),o.jsx(Las,{promptBlocks:d,isLoading:l,search:n,currentPage:s,hasMore:f,onNextPage:p,onPrevPage:h})]})}function $xs(){return o.jsx(Lt,{width:"narrow",children:o.jsx(Lt.MainArea,{children:o.jsx(Oss,{children:o.jsx(Mxe,{})})})})}const Mxs=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:zYt,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:rct,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:ea,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:$V,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:cct,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:sct,href:"https://mastra.ai/contact?ref=studio",external:!0}];function Dxs(){return o.jsx(Lt,{width:"narrow",children:o.jsx(Lt.MainArea,{children:o.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:Mxs.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(ea,{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 Lxs(){const{data:e={},isLoading:t,error:n}=uh(),[r,s]=g.useState(""),[a,i]=g.useState("all");if(n&&ps(n))return o.jsx(Zn,{children:o.jsx(Ts,{})});if(n&&hs(n))return o.jsx(Zn,{children:o.jsx(Os,{resource:"scorers"})});if(n)return o.jsx(Zn,{children:o.jsx($a,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(Zn,{children:o.jsx(EBr,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(jBr,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(CBr,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}function Fxs(){const{scorerId:e}=fr(),[t,n]=Ma(),r=t.get("scoreId")??void 0,[s,a]=g.useState(r),[i,l]=g.useState(!1),c=Vr(),[u,d]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:f,error:p}=iBr(e),{data:h={},isLoading:m,error:v}=zm(),{isLoading:y,error:b}=Gy(),{data:x=[],isLoading:S,error:k,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:T}=aBr({scorerId:e,entityId:u?.value==="all"?void 0:u?.value,entityType:u?.type==="ALL"?void 0:u?.type}),E=g.useMemo(()=>f?.agentIds?.filter(P=>h[P]).map(P=>({value:P,label:h[P].name,type:"AGENT"}))||[],[f?.agentIds,h]),N=g.useMemo(()=>f?.workflowIds?.map(P=>({value:P,label:P,type:"WORKFLOW"}))||[],[f?.workflowIds]),I=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...E,...N],[E,N]),A=t.get("entity")??"all",R=I.find(P=>P.value===A);R&&R.value!==u?.value&&d(R),g.useEffect(()=>{if(p){const P=p instanceof Error?p.message:"Failed to load scorer";ze.error(`Error loading scorer: ${P}`)}},[p]),g.useEffect(()=>{if(v){const P=v instanceof Error?v.message:"Failed to load agents";ze.error(`Error loading agents: ${P}`)}},[v]),g.useEffect(()=>{if(b){const P=b instanceof Error?b.message:"Failed to load workflows";ze.error(`Error loading workflows: ${P}`)}},[b]);const L=P=>{P?.value&&n(B=>{const Z=new URLSearchParams(B);return Z.set("entity",P.value),Z})};g.useEffect(()=>{const P=t.get("scoreId")??void 0;if(P===s)return;if(!P){a(void 0);return}x.find(Z=>Z.id===P)&&a(P)},[t,x]);const M=g.useCallback(P=>{a(P||void 0),n(B=>{const Z=new URLSearchParams(B);return P?Z.set("scoreId",P):Z.delete("scoreId"),Z})},[n]);if(!f)return null;const F=ps(p)||ps(v)||ps(b),H=p&&hs(p),z=!F&&!H&&(p||v||b),q=!S&&x.length===0,V=u?.value!=="all",D=f?.scorer?.source==="stored"?o.jsx(Dy,{owner:"scorer-detail",children:o.jsxs(le,{variant:"default",as:Ba,to:`/cms/scorers/${e}/edit`,size:"sm",children:[o.jsx(Qp,{})," Edit"]})}):null,G=e?o.jsx(sY,{open:i,onOpenChange:l,initialScorerIds:[e],onSuccess:P=>{c(`/experiments/${P}`)}}):null;if(F||H||z||q&&!V){const P=(p instanceof Error?p.message:void 0)??(v instanceof Error?v.message:void 0)??(b instanceof Error?b.message:void 0)??"An unexpected error occurred";return o.jsxs(Lt,{width:"wide",height:"full",className:"grid-rows-[1fr]",children:[D,o.jsx(Lt.MainArea,{isCentered:!0,children:F?o.jsx(Ts,{}):H?o.jsx(Os,{resource:"scorers"}):z?o.jsx($a,{title:"Failed to load scorer",message:P}):o.jsx(K7r,{onRunExperiment:()=>l(!0)})}),G]})}return o.jsxs(Lt,{width:"wide",height:"full",children:[D,o.jsx(Lt.TopArea,{children:o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx(J7r,{selectedEntity:u,entityOptions:I,onEntityChange:L,onReset:()=>{n(P=>{const B=new URLSearchParams(P);return B.set("entity","all"),B})},isLoading:S||m||y}),o.jsxs(le,{variant:"primary",onClick:()=>l(!0),children:[o.jsx(Mc,{}),"Run Experiment"]})]})}),o.jsx(Y7r,{scores:x,isLoading:S,selectedScoreId:s,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:T,onScoreClick:M,errorMsg:k?.message}),G]})}const zxs=co("flex min-w-0 flex-col",{variants:{variant:{default:"gap-3 sm:flex-row sm:items-center sm:justify-between",factory:"gap-2 px-4 py-3 lg:flex-row lg:items-center lg:justify-between lg:gap-4"}},defaultVariants:{variant:"default"}}),Bxs=co("flex min-w-0 flex-col",{variants:{variant:{default:"",factory:"gap-0.5"}},defaultVariants:{variant:"default"}}),Att=co("",{variants:{variant:{default:"text-sm font-medium",factory:"text-ui-md leading-ui-md text-neutral5"}},defaultVariants:{variant:"default"}}),Uxs=co("flex flex-col gap-0.5",{variants:{variant:{default:"text-sm text-neutral3",factory:"text-ui-sm text-neutral3"}},defaultVariants:{variant:"default"}});function qxs({label:e,description:t,htmlFor:n,variant:r,className:s,children:a}){return o.jsxs("div",{className:K(zxs({variant:r}),s),"data-slot":"settings-row",children:[o.jsxs("div",{className:Bxs({variant:r}),children:[n?o.jsx(Pt,{htmlFor:n,className:Att({variant:r}),children:e}):o.jsx("span",{className:Att({variant:r}),children:e}),t&&o.jsx("div",{className:Uxs({variant:r}),children:t})]}),a]})}const vHt=[{value:"dark",label:"Dark",Icon:zXt},{value:"light",label:"Light",Icon:uen},{value:"system",label:"System",Icon:xct}],Vxs=e=>vHt.some(t=>t.value===e);function Hxs({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 Wxs=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=$H(),{theme:r,setTheme:s}=rC();return o.jsx(Lt,{width:"narrow",children:o.jsxs(Lt.MainArea,{className:"mt-6 flex flex-col gap-5",children:[o.jsx(cxe,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(qxs,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(oa,{value:r,onValueChange:a=>{Vxs(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:vHt.map(a=>o.jsx(xr,{value:a.value,children:o.jsx(Hxs,{option:a})},a.value))})]})})}),o.jsx(cxe,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(g4t,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function Zxs(){const[e]=Ma(),t=Vr(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(oHt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}function Gxs(e){return e.replace(/\/$/,"").split("/").pop()}function uY({children:e,className:t}){return o.jsx("div",{className:K("border border-border1 rounded-lg mt-12 py-8 lg:min-h-[25rem] transition-height px-4 lg:px-12",t),children:e})}function Qxs({templates:e,linkComponent:t,className:n,isLoading:r}){const s=t||"a";return r?o.jsx("div",{className:K("grid gap-y-4",n),children:Array.from({length:5}).map((a,i)=>o.jsx("div",{className:"bg-surface3 h-16 animate-pulse rounded-lg"},i))}):o.jsx("div",{className:K("grid gap-y-4",n),children:e.map(a=>{const i=a?.agents||a?.tools||a?.networks||a?.workflows||a?.mcp;return o.jsxs("article",{className:K("border border-border1 rounded-lg overflow-hidden w-full grid grid-cols-[1fr_auto] bg-surface3 transition-colors hover:bg-surface4"),children:[o.jsxs(s,{to:`/templates/${a.slug}`,className:K("grid [&:hover_p]:text-neutral5",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":a.imageURL}),children:[a.imageURL&&o.jsx("div",{className:K("overflow-hidden"),children:o.jsx("div",{className:"thumb transition-scale h-full w-full bg-cover duration-150",style:{backgroundImage:`url(${a.imageURL})`}})}),o.jsxs("div",{className:K("grid py-3 px-6 w-full gap-0.5","[&_svg]:w-[1em] [&_svg]:h-[1em] [&_svg]:text-neutral3"),children:[o.jsx("h2",{className:"text-ui-lg text-neutral5",children:a.title}),o.jsx("p",{className:"text-ui-md text-neutral4 transition-colors duration-500",children:a.description}),o.jsxs("div",{className:"text-neutral3 text-ui-md mt-3 hidden flex-wrap items-center gap-4 2xl:flex",children:[i&&o.jsxs("ul",{className:K("flex gap-4 text-ui-md text-neutral3 m-0 p-0 list-none","[&>li]:flex [&>li]:items-center [&>li]:gap-0.5 text-neutral4"),children:[a?.agents&&a.agents.length>0&&o.jsxs("li",{children:[o.jsx(Ai,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(zf,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(Sct,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(uI,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(TC,{})," ",a.mcp.length]})]}),i&&a.supportedProviders&&o.jsx("small",{children:"|"}),o.jsx("div",{className:"text-neutral3 flex items-center gap-4",children:a.supportedProviders.map(l=>o.jsx("span",{className:"",children:l},l))})]})]})]}),o.jsx("a",{href:a.githubUrl,className:K("group items-center gap-2 text-ui-md ml-auto pr-4 hidden","lg:flex"),target:"_blank",rel:"noopener noreferrer",children:o.jsxs("span",{className:"bg-surface1 group-hover:bg-surface2 text-neutral3 group-hover:text-neutral5 flex items-center gap-2 rounded px-2 py-1 transition-colors",children:[o.jsx(dG,{})," ",Gxs(a.githubUrl)]})})]},a.slug)})})}function Yxs({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:s,onProviderChange:a,searchTerm:i,onSearchChange:l,onReset:c,className:u,isLoading:d}){return d?o.jsxs("div",{className:K("h-[6.5rem] flex items-center gap-8","[&>div]:bg-surface3 [&>div]:w-48 [&>div]:h-8 [&>div]:animate-pulse",u),children:[o.jsx("div",{})," ",o.jsx("div",{})," ",o.jsx("div",{})]}):o.jsxs("div",{className:K("flex flex-wrap mx-auto sticky top-0 gap-4 bg-surface2 py-8",u),children:[o.jsx(y_,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(Ld,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(Ld,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(le,{onClick:c,children:["Reset ",o.jsx(or,{})]})]})}function Kxs(){const{data:e,isLoading:t}=Qnr(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[a,i]=g.useState("all"),[l,c]=g.useState("all"),[u,d]=g.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(x=>{f.push({value:x,label:x})});const 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)},v=()=>{i("all"),c("all"),d("")},y=n.filter(x=>!(u&&!x.title.toLowerCase().includes(u)&&!x.description.toLowerCase().includes(u)||a!=="all"&&!x.tags.includes(a)||l!=="all"&&!x.supportedProviders.includes(l))),b=u||a!=="all"||l!=="all";return o.jsxs(vs,{children:[o.jsx(OSe,{children:o.jsxs(jbt,{children:[o.jsx(We,{children:o.jsx(oy,{})}),"Templates"]})}),o.jsxs("div",{className:K("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(Yxs,{selectedTag:a,onTagChange:x=>h(x,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:x=>h(x,"provider"),providerOptions:p,searchTerm:u,onSearchChange:m,onReset:b?v:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(Qxs,{templates:y,linkComponent:Ba,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const Xxs="1.65.0-alpha.2";function Jxs({errorMsg:e,validationErrors:t}){const n=typeof e=="string"?e:e!=null?String(e):void 0,r=n?.includes("Invalid schema for function"),s=n?.includes("validation issue")||t&&t.length>0,a=()=>s?"Template installation completed but some validation issues remain. The template may still be functional, but you should review and fix these issues.":r?"There was an issue with the AI model configuration. This may be related to the selected model or AI SDK version compatibility.":"An unexpected error occurred during template installation.",i=()=>s?{icon:o.jsx(uc,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(eKt,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(uY,{className:"text-neutral3 mb-8 content-center space-y-4",children:[o.jsxs("div",{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[l,o.jsxs("div",{className:"space-y-2 text-center",children:[o.jsx("p",{className:"text-ui-md text-neutral5 font-medium",children:c}),o.jsx("p",{className:"text-ui-md text-neutral3",children:a()})]})]}),t&&t.length>0&&o.jsxs("details",{className:"text-xs",children:[o.jsxs("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:["Show Validation Issues (",t.length,")"]}),o.jsx("div",{className:"mt-4 max-h-60 space-y-2 overflow-auto rounded bg-gray-100 p-3 text-left text-xs dark:bg-gray-800",children:t.map((u,d)=>o.jsxs("div",{className:"border-l-2 border-red-400 pl-2",children:[o.jsx("div",{className:"font-medium text-red-600 dark:text-red-400",children:u.type==="typescript"?"🔴 TypeScript Error":"⚠️ Lint Error"}),o.jsx("div",{className:"mt-1 font-mono text-xs wrap-break-word whitespace-pre-wrap text-gray-700 dark:text-gray-300",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-xs",children:[o.jsx("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:"Show Details"}),o.jsx("div",{className:"mt-4 max-h-60 overflow-auto rounded bg-gray-100 p-3 text-left font-mono text-xs dark:bg-gray-800",children:o.jsx("div",{className:"wrap-break-word whitespace-pre-wrap",children:n})})]})]})}function e0s({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(uY,{children:o.jsxs("div",{className:"mx-auto my-4 grid max-w-[40rem] gap-8 p-4 lg:p-8",children:[o.jsxs("h2",{className:K("text-neutral4 text-header-sm font-semibold flex items-center gap-2","[&>svg]:w-[1.2em] [&_svg]:h-[1.2em] [&_svg]:opacity-70"),children:["Install Template ",o.jsx(kct,{})]}),o.jsx(Ld,{name:"template-provider",options:e,label:"Template AI Model Provider",onValueChange:n,value:t,placeholder:"Select",layout:"horizontal"}),t&&Object.entries(r||{}).length>0&&o.jsxs(o.Fragment,{children:[o.jsx("h3",{className:"text-neutral3 text-ui-md",children:"Set required Environmental Variables"}),o.jsx("div",{className:"grid grid-cols-[1fr_1fr] items-start gap-4",children:l?o.jsxs("div",{className:K("flex items-center justify-center col-span-2 text-neutral3 text-ui-sm gap-4","[&_svg]:opacity-50 [&_svg]:w-[1.1em] [&_svg]:h-[1.1em]","animate-in fade-in duration-300"),children:[o.jsx(Ut,{})," Loading variables..."]}):Object.entries(r).map(([p,h])=>o.jsxs(g.Fragment,{children:[o.jsx(Jp,{name:`env-${p}`,labelIsHidden:!0,label:"Key",value:p,disabled:!0,className:"w-full"}),o.jsx(Jp,{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(m4t,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(le,{className:K("flex items-center gap-2 mt-4 justify-center text-ui-md w-full bg-surface5 min-h-10 rounded-lg text-neutral5 hover:bg-surface6 transition-colors","[&>svg]:w-[1.1em] [&_svg]:h-[1.1em] [&_svg]:text-neutral5"),onClick:a,disabled:!t||!u||!d||s.length>0||c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(Ut,{className:"h-4 w-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(zd,{})]})})]})})}function t0s({title:e,description:t,githubUrl:n,isLoading:r,infoData:s,templateSlug:a}){const i=a?`feat/install-template-${a}`:"feat/install-template-[slug]";return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:K("grid mt-8 items-center"),children:o.jsxs("div",{className:K("text-header-lg flex items-center gap-3","[&>svg]:w-[1.2em] [&>svg]:h-[1.2em] [&>svg]:opacity-50",{"[&>svg]:opacity-20":r}),children:[o.jsx(oy,{}),o.jsx("h2",{className:K({"bg-surface4 flex rounded-lg min-w-[50%]":r}),children:r?o.jsx(o.Fragment,{children:" "}):e})]})}),o.jsxs("div",{className:"grid gap-x-24 lg:grid-cols-[1fr_1fr]",children:[o.jsxs("div",{className:"grid",children:[o.jsx("p",{className:K("mb-4 text-ui-md text-neutral4 mt-2 leading-7",{"bg-surface4 rounded-lg ":r}),children:r?o.jsx(o.Fragment,{children:" "}):t}),!r&&a&&o.jsxs("div",{className:K("bg-surface2 border border-surface4 rounded-lg p-4 mb-4","flex items-start gap-3"),children:[o.jsx("div",{className:"mt-0.5 shrink-0",children:o.jsx(Em,{className:"h-[1.1em] w-[1.1em] text-blue-500"})}),o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(_0e,{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(dG,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(dje,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function Rtt(e){switch(e){case"running":return o.jsx(Ut,{size:"sm","aria-hidden":!0});case"success":return o.jsx(qr,{"aria-hidden":!0});case"failed":return o.jsx(or,{"aria-hidden":!0});default:return null}}function n0s(){return o.jsx("svg",{viewBox:"0 0 24 24",className:"text-neutral2","aria-hidden":!0,children:o.jsx("circle",{cx:"12",cy:"12",r:"8.5",pathLength:"48",fill:"none",stroke:"currentcolor",strokeWidth:"2.8",strokeLinecap:"round",strokeDasharray:"3 3"})})}function r0s({status:e,variant:t}){return t==="plain"?o.jsx("span",{className:K("flex size-4 items-center justify-center self-center [&>svg]:size-4",Yr.colors,{"[&>svg]:text-positive1":e==="success","[&>svg]:text-negative1":e==="failed"}),children:e==="pending"?o.jsx(n0s,{}):Rtt(e)}):o.jsx("span",{className:K("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",Yr.colors,Yr.transform,Yr.shadow,{"[&>svg]:text-notice-success-fg":e==="success","[&>svg]:text-notice-destructive-fg":e==="failed","border border-dashed border-neutral2":e==="pending","[&>svg]:size-4":e!=="running","bg-accent1Dark shadow-glow-accent1":e==="success","bg-accent2Dark shadow-glow-accent2":e==="failed","scale-110":e==="success"||e==="failed"}),children:Rtt(e)})}function s0s({step:e,isActive:t,position:n,variant:r="default"}){return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none",Yr.colors,{"border border-transparent":r==="default","border-dashed border-neutral2 bg-surface3":t&&r==="default"}),children:[o.jsxs("div",{className:"grid min-w-0 grid-cols-[auto_1fr] gap-2",children:[o.jsxs("span",{className:K("flex min-w-6 justify-end text-ui-md",Yr.colors,{"text-neutral5":t||e.status==="success","text-neutral3":!t&&e.status!=="success"}),children:[n,"."]}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("h4",{className:K("text-ui-md",Yr.colors,{"text-neutral5":t||e.status==="success","text-neutral3":!t&&e.status!=="success"}),children:e.title}),e.description&&o.jsx("p",{className:K("-mt-0.5 text-ui-md text-neutral2",{truncate:r==="plain"}),children:e.description})]})]}),o.jsx(r0s,{status:e.status,variant:r})]})}function a0s({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:K(n),children:t.map((r,s)=>o.jsx(s0s,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function i0s({steps:e}){const t=e.length,n=e.filter(r=>r.status==="success").length;return o.jsxs("div",{className:"flex w-full flex-col content-center justify-center gap-4",children:[o.jsx("div",{className:"grid w-full grid-cols-[0_repeat(9,1fr)]",children:e.map((r,s)=>o.jsx("div",{className:K("relative flex h-8 items-center justify-end",Yr.colors,{"bg-accent1Dark":r.status==="success"&&e?.[s-1]?.status==="success"}),children:o.jsx("div",{className:K("absolute right-0 z-10 flex size-8 translate-x-1/2 items-center justify-center self-center rounded-full bg-surface3 text-ui-sm font-bold text-neutral3 motion-reduce:transition-none",Yr.colors,Yr.transform,Yr.shadow,{"border border-dashed border-neutral2":r.status==="pending","bg-accent1Dark text-notice-success-fg shadow-glow-accent1 scale-110":r.status==="success","bg-accent2Dark text-notice-destructive-fg shadow-glow-accent2 scale-110":r.status==="failed"}),children:r.status==="running"?o.jsx(Ut,{}):s+1})},r.id))}),o.jsxs("div",{className:K("text-center text-xs text-neutral3",Yr.colors),children:[n," of ",t," steps completed"]})]})}function o0s({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",a=t?.payload?.workflowState,i=t?.payload?.currentStep,l=t?.error,c=a?.steps||{},u=Object.keys(c).length>0,d=v=>v==="input"||v.endsWith(".input")||v.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(v)||/[0-9a-f]{8,}/.test(v)?!1:r?.allSteps?v in r.allSteps:!0,f=Object.entries(c).filter(([v,y])=>d(v)),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(([v,y])=>({id:v,status:y?.status,description:y?.description,title:v.charAt(0).toUpperCase()+v.slice(1).replace(/-/g," "),isActive:i?.id===v}));return o.jsxs(uY,{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(i0s,{steps:m})}),l&&s==="error"&&o.jsxs("div",{className:K("rounded-lg text-neutral5 p-6 flex items-center gap-3 text-ui-md bg-red-500/10","[&>svg]:w-6 [&>svg]:h-6 [&>svg]:opacity-70 [&>svg]:text-red-500"),children:[o.jsx(XXt,{}),l||"Something went wrong"]}),u&&o.jsx(a0s,{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(Ut,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function l0s({name:e,installedEntities:t}){return o.jsxs(uY,{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(kct,{}),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(dje,{data:t})]})}function c0s(){const{templateSlug:e}=fr(),[t,n]=Ma(),[r,s]=g.useState(""),[a,i]=g.useState(""),[l,c]=g.useState(""),[u,d]=g.useState({}),[f,p]=g.useState([]),[h,m]=g.useState(null),[v,y]=g.useState(!1),[b,x]=g.useState(""),[S,k]=g.useState(!1),[_,C]=g.useState(!1),[T,E]=g.useState([]),{data:N,isLoading:I}=Ynr({repoOrSlug:e,owner:"mastra-ai"}),R=Xxs?.includes("beta")??!1?"beta":"main",{data:L,isLoading:M}=Knr({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:R}),{data:F,isLoading:H}=Xnr(),{mutateAsync:z,isPending:q}=Jnr(),{mutateAsync:V}=err(),{streamInstall:D,streamResult:G,isStreaming:U}=nrr(F),{observeInstall:P,streamResult:B,isStreaming:Z}=rrr(F);g.useEffect(()=>{const ne=t.get("runId");ne&&!v&&!h&&!U&&!Z&&(console.info("🔄 Checking completed run after hot reload:",{runId:ne}),x(ne),V({runId:ne}).then(se=>{const fe=se.snapshot;if(fe?.status==="success"&&fe?.result?.success)y(!0);else if(fe?.result?.success===!1)if(fe?.result?.validationResults&&!fe?.result?.validationResults?.valid&&fe?.result?.validationResults?.remainingErrors>0){const{remainingErrors:xe,errors:pe}=fe.result.validationResults,we=`Template installation completed but ${xe} validation issue${xe>1?"s":""} remain unresolved.`;m(we),E(pe||[])}else{const xe=fe?.result?.message||fe?.result?.error||"Template installation failed";m(typeof xe=="string"?xe:String(xe))}}).catch(se=>{console.error("❌ Failed to fetch run details:",se),m("Failed to retrieve installation status after reload")}))},[t,v,h,U,Z,V]),g.useEffect(()=>{const ne=t.get("runId"),se=t.get("resume"),fe=t.get("provider");if(ne&&se==="true"&&fe&&!U&&!Z&&!S&&!_&&F){x(ne),k(!0);try{V({runId:ne}).then(ce=>{if(ce.snapshot?.status==="running")return P.mutateAsync({runId:ne})}).then(()=>{n(ce=>{const xe=new URLSearchParams(ce);return xe.delete("resume"),xe})}).catch(ce=>{console.error("❌ Failed to resume template installation:",ce),ce.message?.includes("404")||ce.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(ce){console.error("❌ Auto-resume failed with error:",ce),m("Failed to resume template installation. Please refresh and try again.")}}},[t,e,U,Z,S,_,F,V,P,n]);const Y=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],te=[{key:"tools",label:"Tools",value:N?.tools?.length?N.tools.map(ne=>ne).join(", "):"n/a",icon:o.jsx(zf,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(ne=>ne).join(", "):"n/a",icon:o.jsx(Ai,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(ne=>ne).join(", "):"n/a",icon:o.jsx(uI,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(_g,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(cI,{})}],J=[{...te[0]},{...te[1]},{...te[2]}].filter(ne=>ne.value!=="n/a");g.useEffect(()=>{L&&d(L)},[L]),g.useEffect(()=>{const ne=G||B;ne?.phase==="error"&&ne?.error&&m(typeof ne.error=="string"?ne.error:String(ne.error))},[G?.phase,G?.error,B?.phase,B?.error]);const ee=ne=>{s(ne)},re=async ne=>(i(ne.provider),c(ne.modelId),{message:"Model updated successfully"}),oe=async()=>{const ne=Object.entries(u).reduce((se,[fe,ce])=>(ce===""&&se.push(fe),se),[]);if(ne.length>0){p(ne);return}if(N){m(null),y(!1),x(""),C(!0);try{const fe={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:R,slug:N.slug,variables:u},{runId:ce}=await z({});x(ce),n(xe=>{const pe=new URLSearchParams(xe);return pe.set("runId",ce),pe.set("resume","true"),pe.set("provider",r||"openai"),pe}),await D.mutateAsync({inputData:fe,selectedModel:{provider:a,modelId:l},runId:ce})}catch(se){C(!1),m(se?.message||"Template installation failed"),console.error("Template installation failed",se)}}},X=ne=>{const{name:se,value:fe}=ne.target;fe.trim()===""?p(ce=>[...ce,se]):p(ce=>ce.filter(xe=>xe!==se)),d(ce=>({...ce,[se]:fe}))};return o.jsx(vs,{children:o.jsx("div",{className:K("w-full lg:px-12 h-full overflow-y-scroll"),children:o.jsxs("div",{className:"mx-auto grid w-full max-w-[80rem] gap-y-4 p-6",children:[o.jsx(t0s,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:te,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(U||Z)&&o.jsx(o0s,{name:N.title,streamResult:Z?B:G,runId:b,workflowInfo:F}),v&&o.jsx(l0s,{name:N.title,installedEntities:J,linkComponent:Ba}),h&&o.jsx(Jxs,{errorMsg:h,validationErrors:T.length>0?T:G?.validationResults?.errors||B?.validationResults?.errors}),!U&&!Z&&!v&&!h&&o.jsx(e0s,{providerOptions:Y,selectedProvider:r,onProviderChange:ee,variables:u,setVariables:d,errors:f,setErrors:p,handleInstallTemplate:oe,handleVariableChange:X,isLoadingEnvVars:M||H,isInstalling:q,defaultModelProvider:a,defaultModelId:l,onModelUpdate:re})]})]})})})}const u0s=()=>{const{toolId:e,agentId:t}=fr();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(Bss,{toolId:e,agentId:t})})},d0s=()=>{const{toolId:e}=fr();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(dbs,{toolId:e})})};function f0s(){const{data:e,isLoading:t,error:n}=Gy(),[r,s]=g.useState("");return n&&ps(n)?o.jsx(Zn,{children:o.jsx(Ts,{})}):n&&hs(n)?o.jsx(Zn,{children:o.jsx(Os,{resource:"workflows"})}):n?o.jsx(Zn,{children:o.jsx($a,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(Zn,{children:o.jsx(jZr,{})}):o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(od,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsxs(le,{as:Ba,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(nI,{}),"Schedules"]})]})}),o.jsx(TZr,{workflows:e||{},isLoading:t,search:r})]})}const p0s={active:"bg-accent1",paused:"bg-accent3"},h0s={active:"text-accent1",paused:"text-accent3"},yHt=({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 ${p0s[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${h0s[e]}`,children:e})]}),_j=e=>!e||e<=0?"—":new Date(e).toLocaleString(),d2=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 bHt({status:e}){const{icon:t,color:n}=m0s(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 m0s(e){switch(e){case"success":return{icon:o.jsx(qr,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(or,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(Ut,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(EV,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx($c,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(a1,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const Ptt="auto auto auto auto 1fr";function g0s(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 v0s(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 y0s=3e4,b0s=5*6e4;function x0s({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=un(),c=h=>!!(n&&h.runId&&h.outcome!=="failed"),u=e.filter(c).length,{containerRef:d,getRowProps:f}=so({count:u});let p=-1;return t?o.jsx(Fo,{columns:Ptt}):e.length===0?o.jsx(ve,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(he,{columns:Ptt,className:"min-w-0",scrollRef:d,children:[o.jsxs(he.Top,{children:[o.jsx(he.TopCell,{children:"Run"}),o.jsx(he.TopCell,{children:"Status"}),o.jsx(he.TopCell,{children:"Started"}),o.jsx(he.TopCell,{children:"Duration"}),o.jsx(he.TopCell,{children:" "})]}),e.map(h=>{const m=h.actualFireAt-h.scheduledFireAt,v=v0s(m),y=`Scheduled ${_j(h.scheduledFireAt)} — published ${_j(h.actualFireAt)} (drift ${v})`,b=h.outcome==="failed",x=b?h.error:h.run?.error,S=Math.abs(m),k=!b&&S>y0s&&S<=b0s,_=`${h.scheduleId}-${h.runId}-${h.actualFireAt}`,C=c(h);C&&(p+=1);const T=o.jsx("span",{className:C?"text-accent1 text-ui-sm font-mono whitespace-nowrap":"text-neutral3 text-ui-sm font-mono whitespace-nowrap",children:h.runId}),E=o.jsxs(o.Fragment,{children:[o.jsx(he.Cell,{children:T}),o.jsx(he.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[b?o.jsxs("span",{className:"text-ui-sm text-accent2 inline-flex items-center gap-1.5 whitespace-nowrap",children:[o.jsx(uc,{size:14}),"publish failed"]}):h.run?o.jsx(bHt,{status:h.run.status}):o.jsx("span",{className:"text-ui-sm text-neutral3 inline-flex items-center gap-1.5 whitespace-nowrap",children:"pending"}),x?o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(uc,{size:14})})}),o.jsx(yn,{children:x})]}):null]})}),o.jsx(he.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:y,children:d2(h.actualFireAt)}),k?o.jsxs(xn,{children:[o.jsx(vn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(uc,{size:14})})}),o.jsxs(yn,{children:["Published ",v," after the scheduled fire time"]})]}):null]})}),o.jsx(he.Cell,{children:h.run?o.jsx("span",{children:g0s(h.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(he.Cell,{children:" "})]});return C?o.jsx(he.RowLink,{to:l.workflowRunLink(n,h.runId),LinkComponent:i,...f(p),children:E},_):o.jsx(he.RowStatic,{children:E},_)}),o.jsx(he.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const w0s=e=>{const t=Ge();return mt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},$tt=25,S0s=e=>{const t=Ge(),{inView:n,setRef:r}=t0(),s=Py({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:$tt,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<$tt))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 g.useEffect(()=>{n&&i&&!l&&c()},[n,i,l,c]),{...s,data:a,setEndOfListElement:r}},k0s=e=>{const t=Ge(),n=Ir();return Sn({mutationFn:async r=>{if(!e)throw new Error("scheduleId is required");return r==="pause"?t.pauseSchedule(e):t.resumeSchedule(e)},onSuccess:(r,s)=>{n.invalidateQueries({queryKey:["schedule",e]}),n.invalidateQueries({queryKey:["schedules"]}),ze.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{ze.error(r.message)}})};function h8({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ve,{variant:"ui-xs",className:"text-neutral4 tracking-wide uppercase",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function O0s(){const{scheduleId:e}=fr(),{paths:t}=un(),{data:n,error:r}=w0s(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=S0s(e),d=k0s(e);if(r&&ps(r))return o.jsx(Zn,{children:o.jsx(Ts,{})});if(r&&hs(r))return o.jsx(Zn,{children:o.jsx(Os,{resource:"schedules"})});if(r)return o.jsx(Zn,{children:o.jsx($a,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,p=n?.agentId;return o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx(Lt.Row,{className:"justify-end",children:o.jsxs(Lt.Column,{className:"flex justify-end gap-2",children:[o.jsxs(le,{as:Ba,to:t.schedulesLink(),variant:"ghost",children:[o.jsx(bl,{}),"Back to schedules"]}),f?o.jsx(le,{as:Ba,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(le,{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(MV,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(Mc,{}),"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(h8,{label:p?"Agent":"Workflow",children:f?o.jsx(Ba,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):p?o.jsx(Ba,{to:t.agentLink(p),className:"text-accent1 hover:underline",children:p}):"—"}),o.jsxs(h8,{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(h8,{label:"Status",children:o.jsx(yHt,{status:n.status})}),o.jsx(h8,{label:"Next fire",children:o.jsx("span",{title:_j(n.nextFireAt),children:d2(n.nextFireAt)})})]}),o.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[o.jsx(ve,{variant:"ui-md",className:"mb-3",children:"Trigger history"}),i?o.jsx($a,{title:"Failed to load trigger history",message:i.message}):o.jsx(x0s,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const Mtt="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function _0s({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=un(),a=g.useMemo(()=>{const c=n.toLowerCase();return c?e.filter(u=>u.id.toLowerCase().includes(c)||(u.workflowId??u.agentId??"").toLowerCase().includes(c)):e},[e,n]),{containerRef:i,getRowProps:l}=so({count:a.length});return t?o.jsx(Fo,{columns:Mtt}):o.jsxs(he,{columns:Mtt,className:"min-w-0",scrollRef:i,children:[o.jsxs(he.Top,{children:[o.jsx(he.TopCell,{children:"Target"}),o.jsx(he.TopCell,{children:"Schedule ID"}),o.jsx(he.TopCell,{children:"Cron"}),o.jsx(he.TopCell,{children:"Status"}),o.jsx(he.TopCell,{children:"Next fire"}),o.jsx(he.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(he.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(he.NoMatch,{message:"No schedules configured"}):null,a.map((c,u)=>o.jsxs(he.RowLink,{to:r.scheduleLink(c.id),LinkComponent:s,...l(u),children:[o.jsx(he.NameCell,{children:c.workflowId??c.agentId}),o.jsx(he.Cell,{className:"min-w-0",children:o.jsx("span",{className:"text-ui-smd text-neutral3 block truncate font-mono",title:c.id,children:c.id})}),o.jsx(he.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("code",{className:"text-ui-sm font-mono",children:c.cron}),c.timezone?o.jsx("span",{className:"text-neutral4 text-ui-xs",children:c.timezone}):null]})}),o.jsx(he.Cell,{children:o.jsx(yHt,{status:c.status})}),o.jsx(he.Cell,{children:o.jsx("span",{className:"whitespace-nowrap",title:_j(c.nextFireAt),children:d2(c.nextFireAt)})}),o.jsx(he.Cell,{children:c.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(bHt,{status:c.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:_j(c.lastFireAt),children:c.lastFireAt?d2(c.lastFireAt):""})]}):c.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:_j(c.lastFireAt),children:d2(c.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},c.id))]})}function C0s({workflowId:e}={}){const{data:t,isLoading:n,error:r}=SSe(e?{workflowId:e}:{}),[s,a]=g.useState("");return r?o.jsx($a,{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(od,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(_0s,{schedules:t??[],isLoading:n,search:s})})]})}function E0s(){const[e]=Ma(),t=e.get("workflowId")??void 0,{error:n}=SSe(t?{workflowId:t}:{});return n&&ps(n)?o.jsx(Zn,{children:o.jsx(Ts,{})}):n&&hs(n)?o.jsx(Zn,{children:o.jsx(Os,{resource:"schedules"})}):o.jsx(Lt,{children:o.jsx("div",{className:"h-full",children:o.jsx(C0s,{workflowId:t})})})}function T0s({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=ZOe({stepGraph:e}),[a,i]=g.useState(!1),[l,c,u]=tCt(r),[d]=nCt(s),{edgeTypes:f,nodeTypes:p,styledEdges:h}=d5t({edges:d,workflowName:n,stepGraph:e});return g.useEffect(()=>{if(t){const m=setTimeout(()=>{i(!0)},500);return()=>clearTimeout(m)}},[t]),o.jsx("div",{className:"bg-surface1 relative h-full w-full",children:a?o.jsxs(eCt,{nodes:l,edges:h,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:p,onNodesChange:u,children:[o.jsx($je,{position:"bottom-left"}),o.jsx(sCt,{variant:dy.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:o.jsx(Ut,{})})})}function j0s(){const{stepDetail:e,closeStepDetail:t}=MW();return e?o.jsxs("div",{className:"flex h-full flex-col","data-testid":"workflow-step-detail-panel",children:[o.jsxs("div",{className:"border-border1 bg-surface1 flex items-center justify-between border-b px-4 py-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[e.type==="map-config"&&o.jsx(i1,{className:"h-4 w-4",style:{color:zu.map}}),e.type==="nested-graph"&&o.jsx(Bc,{className:"h-4 w-4",style:{color:zu.workflow}}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx(ve,{variant:"ui-md",className:"text-neutral6 font-medium",children:e.type==="map-config"?`${e.stepName} Config`:`${e.stepName} Workflow`}),e.type==="map-config"&&e.stepId&&e.stepId!==e.stepName&&o.jsx(ve,{variant:"ui-xs",className:"text-neutral3",children:e.stepId})]})]}),o.jsx("button",{onClick:t,className:"hover:bg-surface3 rounded p-1 transition-colors","aria-label":"Close",children:o.jsx(or,{className:"text-neutral3 h-4 w-4"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(o2,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(WOe,{children:o.jsx(T0s,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function N0s(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function I0s(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 A0s({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:o.jsxs("div",{className:"border-border1 bg-surface4 space-y-5 rounded-lg border p-5","data-testid":"workflow-suspended-steps",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs(ve,{as:"p",variant:"ui-md",className:"text-neutral6 flex items-center gap-2 font-semibold",children:[o.jsx(We,{children:o.jsx(EV,{})}),"Step suspended"]}),o.jsx(xt,{variant:"yellow",children:"Needs input"})]}),e.map((s,a)=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const l=i?.resumeSchema?wm(Tx(i.resumeSchema)):mf(cr(),_f());return o.jsx(R0s,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function R0s({step:e,stepSchema:t,description:n,isStreaming:r,onResume:s}){const[a,i]=g.useState(!1);return o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(ve,{as:"p",variant:"ui-md",className:"text-neutral6 truncate font-medium",children:e.stepId}),n&&o.jsx(ve,{as:"p",variant:"ui-sm",className:"text-neutral3",children:n})]}),e.suspendPayload&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs(ve,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(We,{children:o.jsx(UXt,{})}),"The step is asking"]}),o.jsxs(Lc,{open:a,onOpenChange:i,children:[o.jsxs(fc,{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(We,{children:o.jsx(Br,{className:K("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(ve,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:I0s(e.suspendPayload,e.stepId)})]}),o.jsx(ve,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:N0s(e.suspendPayload)})]}),o.jsx(pc,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Qr,{data:e.suspendPayload,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs(ve,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(We,{children:o.jsx(HXt,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(hU,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(Mc,{}),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 P0s(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext(Zl),{runId:a}=fr(),i=dCt(e,r??""),l=cer(),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(A0s,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const $0s=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"})]}),M0s=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"})]}),D0s=e=>e.includes("."),L0s=e=>e==="input"||e.endsWith(".input"),F0s=1;function z0s(e){return`${Number((e/1e3).toPrecision(3))}s`}function B0s(e,t){const n=Object.entries(e).filter(([i])=>!L0s(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,F0s);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:p,durationMs:d,isRunning:c,isNestedEntry:D0s(i)}})}const U0s=({status:e})=>o.jsxs(We,{children:[e==="success"&&o.jsx($0s,{className:"text-accent1"}),e==="failed"&&o.jsx(M0s,{className:"text-accent2"}),e==="suspended"&&o.jsx(EV,{className:"text-accent3"}),e==="waiting"&&o.jsx(Ype,{className:"text-accent5"}),e==="skipped"&&o.jsx(Ype,{className:"text-icon3"}),e==="running"&&o.jsx(Vs,{className:"text-accent6 animate-spin"})]}),q0s={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function xHt(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const Dtt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},V0s=e=>{const t=e;return n5t({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},H0s=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=V0s(e.step),u=e.status==="running",d=!e.isNestedEntry;return o.jsxs("div",{role:"button",tabIndex:0,"data-testid":"workflow-timeline-row","data-workflow-step-key":e.stepId,"data-workflow-step-active":n?"true":void 0,"data-workflow-step-hovered":r?"true":void 0,"data-workflow-step-nested":e.isNestedEntry?"true":void 0,"aria-pressed":n,"aria-disabled":!d,onMouseEnter:()=>{d&&a(e.stepId)},onMouseLeave:()=>{d&&a(null)},onClick:()=>{d&&s(e.stepId)},onKeyDown:f=>{!d||f.key!=="Enter"&&f.key!==" "||(f.preventDefault(),s(e.stepId))},className:K("grid grid-cols-[auto_auto_auto_minmax(0,10rem)_minmax(0,1fr)_auto_5rem] items-center gap-2 rounded-md border border-transparent px-2 py-1 text-left transition-colors focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-accent1",d&&"cursor-pointer",d&&"hover:bg-surface4",d&&r&&!n&&"border-neutral6 bg-surface4",d&&n&&"border-accent1",e.isNestedEntry&&"cursor-default opacity-55"),children:[o.jsx("div",{className:"flex justify-center",children:o.jsx(U0s,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(le,{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(sen,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(Jq,{indicators:c,className:"shrink-0"})}),o.jsx(ve,{as:"span",variant:"ui-sm",className:"text-neutral6 block max-w-full min-w-0 justify-self-stretch overflow-hidden text-left text-ellipsis whitespace-nowrap",children:xHt(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 ${q0s[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(le,{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(nen,{})})}),o.jsx(ve,{as:"span",variant:"ui-sm",className:"text-neutral3 w-20 justify-self-end text-right tabular-nums",children:z0s(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function W0s(){const{steps:e}=lL(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=WH(),[a,i]=g.useState(()=>Date.now()),[l,c]=g.useState(!1),[u,d]=g.useState(null),f=g.useRef(null);Ubt(f,{enabled:!l});const p=B0s(e,a),h=p.some(m=>m.isRunning);return g.useEffect(()=>{if(!h)return;const m=setInterval(()=>i(Date.now()),100);return()=>clearInterval(m)},[h]),g.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(ve,{as:"p",variant:"ui-md",className:"text-neutral3",children:"Timeline"}),o.jsx("button",{type:"button","aria-label":l?"Expand timeline":"Collapse timeline","aria-expanded":!l,onClick:()=>c(m=>!m),className:"text-neutral3 hover:bg-surface4 hover:text-neutral6 rounded-md p-1 transition-colors",children:o.jsx(Xs,{className:K("h-4 w-4 transition-transform",l&&"-rotate-90")})})]}),!l&&o.jsx("div",{ref:f,"data-testid":"workflow-timeline-list",className:"flex min-h-0 flex-col gap-2 overflow-y-auto",children:p.map((m,v)=>o.jsx(H0s,{row:m,index:v,isSelected:t===m.stepId,isHovered:n===m.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:y=>d({type:"input",stepId:y.stepId,data:Dtt(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:Dtt(y.step.output)})},`timeline-item-${m.stepId}-${v}`))})]})}),o.jsx(hr,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(pCt,{data:u.data,title:`${xHt(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const Z0s=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=MW();return o.jsxs("div",{className:"flex h-full min-h-0",children:[o.jsx("div",{className:"flex h-full min-h-0 flex-1 flex-col",children:o.jsxs("div",{className:"relative min-h-0 flex-1 p-2 pb-0",children:[o.jsx(y5t,{workflowId:e,workflow:t,isLoading:n}),o.jsx(P0s,{}),o.jsx(W0s,{})]})}),r&&o.jsx("div",{className:"border-border1 min-h-0 w-[420px] overflow-hidden border-l",children:o.jsx(j0s,{})})]})},Ltt=()=>{const{workflowId:e}=fr(),{data:t,isLoading:n,error:r}=h4(e);return r&&ps(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{})}):r&&hs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Os,{resource:"workflows"})}):o.jsx(d_e,{children:o.jsx(Z0s,{workflowId:e,workflow:t??void 0,isLoading:n})})};function G0s(e,t){if(e==null)return{};var n,r,s=vkt(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 d0e(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 Q0s(e){if(Array.isArray(e))return d0e(e)}function Y0s(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function K0s(e,t){if(e){if(typeof e=="string")return d0e(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)?d0e(e,t):void 0}}function X0s(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
646
646
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function f0e(e){return Q0s(e)||Y0s(e)||K0s(e)||X0s()}function KD(e){"@babel/helpers - typeof";return KD=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},KD(e)}function J0s(e,t){if(KD(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(KD(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function ews(e){var t=J0s(e,"string");return KD(t)=="symbol"?t:t+""}function wHt(e,t,n){return(t=ews(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ftt(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 LT(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Ftt(Object(n),!0).forEach(function(r){wHt(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Ftt(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function tws(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 loe={};function nws(e){if(e.length===0||e.length===1)return e;var t=e.join(".");return loe[t]||(loe[t]=tws(e)),loe[t]}function rws(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=nws(r);return s.reduce(function(a,i){return LT(LT({},a),n[i])},t)}function ztt(e){return e.join(" ")}function sws(e,t){var n=0;return function(r){return n+=1,r.map(function(s,a){return SHt({node:s,stylesheet:e,useInlineStyles:t,key:"code-segment-".concat(n,"-").concat(a)})})}}function SHt(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=sws(n,a),p;if(!a)p=LT(LT({},l),{},{className:ztt(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"]:[],v=l.className&&m.concat(l.className.filter(function(b){return!h.includes(b)}));p=LT(LT({},l),{},{className:ztt(v)||void 0,style:rws(l.className,Object.assign({},l.style,s),n)})}var y=f(t.children);return Fe.createElement(u,JO({key:i},p),y)}}const aws=(function(e,t){var n=e.listLanguages();return n.indexOf(t)!==-1});var iws=["language","children","style","customStyle","codeTagProps","useInlineStyles","showLineNumbers","showInlineLineNumbers","startingLineNumber","lineNumberContainerStyle","lineNumberStyle","wrapLines","wrapLongLines","lineProps","renderer","PreTag","CodeTag","code","astGenerator"];function Btt(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 zw(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Btt(Object(n),!0).forEach(function(r){wHt(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Btt(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var ows=/\n/g;function lws(e){return e.match(ows)}function cws(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,`
|
|
647
647
|
`))})}function uws(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)},cws({lines:t.replace(/\n$/,"").split(`
|
|
648
648
|
`),style:i,startingLineNumber:l}))}function dws(e){return"".concat(e.toString().length,".25em")}function kHt(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 OHt(e,t,n){var r={display:"inline-block",minWidth:dws(n),paddingRight:"1em",textAlign:"right",userSelect:"none"},s=typeof e=="function"?e(t):e,a=zw(zw({},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?zw({},typeof l=="function"?l(n):l):{};if(m.className=m.className?[].concat(f0e(m.className.trim().split(/\s+/)),f0e(u)):u,n&&a){var v=OHt(r,n,s);t.unshift(kHt(n,v))}return f&d&&(m.style=zw({display:"flex"},m.style)),{type:"element",tagName:"span",properties:m,children:t}}function _Ht(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:f0e(new Set(t))}));else if(s.children){var a=t.concat(s.properties.className);_Ht(s.children,a).forEach(function(i){return n.push(i)})}}return n}function fws(e,t,n,r,s,a,i,l,c){var u,d=_Ht(e.value),f=[],p=-1,h=0;function m(_,C){var T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return L9({children:_,lineNumber:C,lineNumberStyle:l,largestLineNumber:i,showInlineLineNumbers:s,lineProps:n,className:T,showLineNumbers:r,wrapLongLines:c,wrapLines:t})}function v(_,C){if(r&&C&&s){var T=OHt(l,C,i);_.unshift(kHt(C,T))}return _}function y(_,C){var T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return t||T.length>0?m(_,C,T):v(_,C)}for(var b=function(){var C=d[h],T=C.children[0].value,E=lws(T);if(E){var N=T.split(`
|