@mastra/deployer-cloud 1.68.0-alpha.8 → 1.68.0-alpha.9

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-CB1TmVRp.js","./engine-compile-BkERmzkH.js","./preload-helper-PPVm8Dsz.js","./engine-javascript-CSIo_1eZ.js","./html-C2L_23MC.js","./javascript-ySlJ1b_l.js","./css-BPhBrDlE.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./core-DJ3oKHtP.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 Bi}from"./preload-helper-PPVm8Dsz.js";function _on(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 i=Object.getOwnPropertyDescriptor(r,s);i&&Object.defineProperty(e,s,i.get?i:{enumerable:!0,get:()=>r[s]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}var UN=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ql(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ite={exports:{}},ZP={};var a6e;function Eon(){if(a6e)return ZP;a6e=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,s,i){var a=null;if(i!==void 0&&(a=""+i),s.key!==void 0&&(a=""+s.key),"key"in s){i={};for(var l in s)l!=="key"&&(i[l]=s[l])}else i=s;return s=i.ref,{$$typeof:e,type:r,key:a,ref:s!==void 0?s:null,props:i}}return ZP.Fragment=t,ZP.jsx=n,ZP.jsxs=n,ZP}var o6e;function Ton(){return o6e||(o6e=1,Ite.exports=Eon()),Ite.exports}var o=Ton(),Ate={exports:{}},Wr={},l6e;function jon(){if(l6e)return Wr;l6e=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"),i=Symbol.for("react.profiler"),a=Symbol.for("react.consumer"),l=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),h=Symbol.for("react.activity"),p=Symbol.iterator;function m(F){return F===null||typeof F!="object"?null:(F=p&&F[p]||F["@@iterator"],typeof F=="function"?F:null)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y=Object.assign,b={};function x(F,R,D){this.props=F,this.context=R,this.refs=b,this.updater=D||v}x.prototype.isReactComponent={},x.prototype.setState=function(F,R){if(typeof F!="object"&&typeof F!="function"&&F!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,F,R,"setState")},x.prototype.forceUpdate=function(F){this.updater.enqueueForceUpdate(this,F,"forceUpdate")};function w(){}w.prototype=x.prototype;function k(F,R,D){this.props=F,this.context=R,this.refs=b,this.updater=D||v}var _=k.prototype=new w;_.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(F,R,D){var U=D.ref;return{$$typeof:t,type:F,key:R,ref:U!==void 0?U:null,props:D}}function A(F,R){return I(F.type,R,F.props)}function P(F){return typeof F=="object"&&F!==null&&F.$$typeof===t}function L(F){var R={"=":"=0",":":"=2"};return"$"+F.replace(/[=:]/g,function(D){return R[D]})}var M=/\/+/g;function V(F,R){return typeof F=="object"&&F!==null&&F.key!=null?L(""+F.key):R.toString(36)}function q(F){switch(F.status){case"fulfilled":return F.value;case"rejected":throw F.reason;default:switch(typeof F.status=="string"?F.then(T,T):(F.status="pending",F.then(function(R){F.status==="pending"&&(F.status="fulfilled",F.value=R)},function(R){F.status==="pending"&&(F.status="rejected",F.reason=R)})),F.status){case"fulfilled":return F.value;case"rejected":throw F.reason}}throw F}function H(F,R,D,U,Q){var ee=typeof F;(ee==="undefined"||ee==="boolean")&&(F=null);var J=!1;if(F===null)J=!0;else switch(ee){case"bigint":case"string":case"number":J=!0;break;case"object":switch(F.$$typeof){case t:case n:J=!0;break;case f:return J=F._init,H(J(F._payload),R,D,U,Q)}}if(J)return Q=Q(F),J=U===""?"."+V(F,0):U,C(Q)?(D="",J!=null&&(D=J.replace(M,"$&/")+"/"),H(Q,R,D,"",function(ce){return ce})):Q!=null&&(P(Q)&&(Q=A(Q,D+(Q.key==null||F&&F.key===Q.key?"":(""+Q.key).replace(M,"$&/")+"/")+J)),R.push(Q)),1;J=0;var te=U===""?".":U+":";if(C(F))for(var re=0;re<F.length;re++)U=F[re],ee=te+V(U,re),J+=H(U,R,D,ee,Q);else if(re=m(F),typeof re=="function")for(F=re.call(F),re=0;!(U=F.next()).done;)U=U.value,ee=te+V(U,re++),J+=H(U,R,D,ee,Q);else if(ee==="object"){if(typeof F.then=="function")return H(q(F),R,D,U,Q);throw R=String(F),Error("Objects are not valid as a React child (found: "+(R==="[object Object]"?"object with keys {"+Object.keys(F).join(", ")+"}":R)+"). If you meant to render a collection of children, use an array instead.")}return J}function B(F,R,D){if(F==null)return F;var U=[],Q=0;return H(F,U,"","",function(ee){return R.call(D,ee,Q++)}),U}function W(F){if(F._status===-1){var R=F._result;R=R(),R.then(function(D){(F._status===0||F._status===-1)&&(F._status=1,F._result=D)},function(D){(F._status===0||F._status===-1)&&(F._status=2,F._result=D)}),F._status===-1&&(F._status=0,F._result=R)}if(F._status===1)return F._result.default;throw F._result}var z=typeof reportError=="function"?reportError:function(F){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var R=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof F=="object"&&F!==null&&typeof F.message=="string"?String(F.message):String(F),error:F});if(!window.dispatchEvent(R))return}else if(typeof e=="object"&&typeof e.emit=="function"){e.emit("uncaughtException",F);return}console.error(F)},G={map:B,forEach:function(F,R,D){B(F,function(){R.apply(this,arguments)},D)},count:function(F){var R=0;return B(F,function(){R++}),R},toArray:function(F){return B(F,function(R){return R})||[]},only:function(F){if(!P(F))throw Error("React.Children.only expected to receive a single React element child.");return F}};return Wr.Activity=h,Wr.Children=G,Wr.Component=x,Wr.Fragment=r,Wr.Profiler=i,Wr.PureComponent=k,Wr.StrictMode=s,Wr.Suspense=u,Wr.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=E,Wr.__COMPILER_RUNTIME={__proto__:null,c:function(F){return E.H.useMemoCache(F)}},Wr.cache=function(F){return function(){return F.apply(null,arguments)}},Wr.cacheSignal=function(){return null},Wr.cloneElement=function(F,R,D){if(F==null)throw Error("The argument must be a React element, but you passed "+F+".");var U=y({},F.props),Q=F.key;if(R!=null)for(ee in R.key!==void 0&&(Q=""+R.key),R)!N.call(R,ee)||ee==="key"||ee==="__self"||ee==="__source"||ee==="ref"&&R.ref===void 0||(U[ee]=R[ee]);var ee=arguments.length-2;if(ee===1)U.children=D;else if(1<ee){for(var J=Array(ee),te=0;te<ee;te++)J[te]=arguments[te+2];U.children=J}return I(F.type,Q,U)},Wr.createContext=function(F){return F={$$typeof:l,_currentValue:F,_currentValue2:F,_threadCount:0,Provider:null,Consumer:null},F.Provider=F,F.Consumer={$$typeof:a,_context:F},F},Wr.createElement=function(F,R,D){var U,Q={},ee=null;if(R!=null)for(U in R.key!==void 0&&(ee=""+R.key),R)N.call(R,U)&&U!=="key"&&U!=="__self"&&U!=="__source"&&(Q[U]=R[U]);var J=arguments.length-2;if(J===1)Q.children=D;else if(1<J){for(var te=Array(J),re=0;re<J;re++)te[re]=arguments[re+2];Q.children=te}if(F&&F.defaultProps)for(U in J=F.defaultProps,J)Q[U]===void 0&&(Q[U]=J[U]);return I(F,ee,Q)},Wr.createRef=function(){return{current:null}},Wr.forwardRef=function(F){return{$$typeof:c,render:F}},Wr.isValidElement=P,Wr.lazy=function(F){return{$$typeof:f,_payload:{_status:-1,_result:F},_init:W}},Wr.memo=function(F,R){return{$$typeof:d,type:F,compare:R===void 0?null:R}},Wr.startTransition=function(F){var R=E.T,D={};E.T=D;try{var U=F(),Q=E.S;Q!==null&&Q(D,U),typeof U=="object"&&U!==null&&typeof U.then=="function"&&U.then(T,z)}catch(ee){z(ee)}finally{R!==null&&D.types!==null&&(R.types=D.types),E.T=R}},Wr.unstable_useCacheRefresh=function(){return E.H.useCacheRefresh()},Wr.use=function(F){return E.H.use(F)},Wr.useActionState=function(F,R,D){return E.H.useActionState(F,R,D)},Wr.useCallback=function(F,R){return E.H.useCallback(F,R)},Wr.useContext=function(F){return E.H.useContext(F)},Wr.useDebugValue=function(){},Wr.useDeferredValue=function(F,R){return E.H.useDeferredValue(F,R)},Wr.useEffect=function(F,R){return E.H.useEffect(F,R)},Wr.useEffectEvent=function(F){return E.H.useEffectEvent(F)},Wr.useId=function(){return E.H.useId()},Wr.useImperativeHandle=function(F,R,D){return E.H.useImperativeHandle(F,R,D)},Wr.useInsertionEffect=function(F,R){return E.H.useInsertionEffect(F,R)},Wr.useLayoutEffect=function(F,R){return E.H.useLayoutEffect(F,R)},Wr.useMemo=function(F,R){return E.H.useMemo(F,R)},Wr.useOptimistic=function(F,R){return E.H.useOptimistic(F,R)},Wr.useReducer=function(F,R,D){return E.H.useReducer(F,R,D)},Wr.useRef=function(F){return E.H.useRef(F)},Wr.useState=function(F){return E.H.useState(F)},Wr.useSyncExternalStore=function(F,R,D){return E.H.useSyncExternalStore(F,R,D)},Wr.useTransition=function(){return E.H.useTransition()},Wr.version="19.2.7",Wr}var c6e;function SA(){return c6e||(c6e=1,Ate.exports=jon()),Ate.exports}var g=SA();const Me=ql(g),kA=_on({__proto__:null,default:Me},[g]);var Rte={exports:{}},GP={},Pte={exports:{}},$te={};var u6e;function Non(){return u6e||(u6e=1,(function(e){function t(q,H){var B=q.length;q.push(H);e:for(;0<B;){var W=B-1>>>1,z=q[W];if(0<s(z,H))q[W]=H,q[B]=z,B=W;else break e}}function n(q){return q.length===0?null:q[0]}function r(q){if(q.length===0)return null;var H=q[0],B=q.pop();if(B!==H){q[0]=B;e:for(var W=0,z=q.length,G=z>>>1;W<G;){var F=2*(W+1)-1,R=q[F],D=F+1,U=q[D];if(0>s(R,B))D<z&&0>s(U,R)?(q[W]=U,q[D]=B,W=D):(q[W]=R,q[F]=B,W=F);else if(D<z&&0>s(U,B))q[W]=U,q[D]=B,W=D;else break e}}return H}function s(q,H){var B=q.sortIndex-H.sortIndex;return B!==0?B:q.id-H.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var a=Date,l=a.now();e.unstable_now=function(){return a.now()-l}}var c=[],u=[],d=1,f=null,h=3,p=!1,m=!1,v=!1,y=!1,b=typeof setTimeout=="function"?setTimeout:null,x=typeof clearTimeout=="function"?clearTimeout:null,w=typeof setImmediate<"u"?setImmediate:null;function k(q){for(var H=n(u);H!==null;){if(H.callback===null)r(u);else if(H.startTime<=q)r(u),H.sortIndex=H.expirationTime,t(c,H);else break;H=n(u)}}function _(q){if(v=!1,k(q),!m)if(n(c)!==null)m=!0,C||(C=!0,P());else{var H=n(u);H!==null&&V(_,H.startTime-q)}}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 q=e.unstable_now();N=q;var H=!0;try{e:{m=!1,v&&(v=!1,x(T),T=-1),p=!0;var B=h;try{t:{for(k(q),f=n(c);f!==null&&!(f.expirationTime>q&&I());){var W=f.callback;if(typeof W=="function"){f.callback=null,h=f.priorityLevel;var z=W(f.expirationTime<=q);if(q=e.unstable_now(),typeof z=="function"){f.callback=z,k(q),H=!0;break t}f===n(c)&&r(c),k(q)}else r(c);f=n(c)}if(f!==null)H=!0;else{var G=n(u);G!==null&&V(_,G.startTime-q),H=!1}}break e}finally{f=null,h=B,p=!1}H=void 0}}finally{H?P():C=!1}}}var P;if(typeof w=="function")P=function(){w(A)};else if(typeof MessageChannel<"u"){var L=new MessageChannel,M=L.port2;L.port1.onmessage=A,P=function(){M.postMessage(null)}}else P=function(){b(A,0)};function V(q,H){T=b(function(){q(e.unstable_now())},H)}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(q){q.callback=null},e.unstable_forceFrameRate=function(q){0>q||125<q?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):E=0<q?Math.floor(1e3/q):5},e.unstable_getCurrentPriorityLevel=function(){return h},e.unstable_next=function(q){switch(h){case 1:case 2:case 3:var H=3;break;default:H=h}var B=h;h=H;try{return q()}finally{h=B}},e.unstable_requestPaint=function(){y=!0},e.unstable_runWithPriority=function(q,H){switch(q){case 1:case 2:case 3:case 4:case 5:break;default:q=3}var B=h;h=q;try{return H()}finally{h=B}},e.unstable_scheduleCallback=function(q,H,B){var W=e.unstable_now();switch(typeof B=="object"&&B!==null?(B=B.delay,B=typeof B=="number"&&0<B?W+B:W):B=W,q){case 1:var z=-1;break;case 2:z=250;break;case 5:z=1073741823;break;case 4:z=1e4;break;default:z=5e3}return z=B+z,q={id:d++,callback:H,priorityLevel:q,startTime:B,expirationTime:z,sortIndex:-1},B>W?(q.sortIndex=B,t(u,q),n(c)===null&&q===n(u)&&(v?(x(T),T=-1):v=!0,V(_,B-W))):(q.sortIndex=z,t(c,q),m||p||(m=!0,C||(C=!0,P()))),q},e.unstable_shouldYield=I,e.unstable_wrapCallback=function(q){var H=h;return function(){var B=h;h=H;try{return q.apply(this,arguments)}finally{h=B}}}})($te)),$te}var d6e;function Ion(){return d6e||(d6e=1,Pte.exports=Non()),Pte.exports}var Mte={exports:{}},Au={};var f6e;function Aon(){if(f6e)return Au;f6e=1;var e=SA();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 i(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 a=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function l(c,u){if(c==="font")return"";if(typeof u=="string")return u==="use-credentials"?u:""}return Au.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,Au.createPortal=function(c,u){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!u||u.nodeType!==1&&u.nodeType!==9&&u.nodeType!==11)throw Error(t(299));return i(c,u,null,d)},Au.flushSync=function(c){var u=a.T,d=r.p;try{if(a.T=null,r.p=2,c)return c()}finally{a.T=u,r.p=d,r.d.f()}},Au.preconnect=function(c,u){typeof c=="string"&&(u?(u=u.crossOrigin,u=typeof u=="string"?u==="use-credentials"?u:"":void 0):u=null,r.d.C(c,u))},Au.prefetchDNS=function(c){typeof c=="string"&&r.d.D(c)},Au.preinit=function(c,u){if(typeof c=="string"&&u&&typeof u.as=="string"){var d=u.as,f=l(d,u.crossOrigin),h=typeof u.integrity=="string"?u.integrity:void 0,p=typeof u.fetchPriority=="string"?u.fetchPriority:void 0;d==="style"?r.d.S(c,typeof u.precedence=="string"?u.precedence:void 0,{crossOrigin:f,integrity:h,fetchPriority:p}):d==="script"&&r.d.X(c,{crossOrigin:f,integrity:h,fetchPriority:p,nonce:typeof u.nonce=="string"?u.nonce:void 0})}},Au.preinitModule=function(c,u){if(typeof c=="string")if(typeof u=="object"&&u!==null){if(u.as==null||u.as==="script"){var d=l(u.as,u.crossOrigin);r.d.M(c,{crossOrigin:d,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0})}}else u==null&&r.d.M(c)},Au.preload=function(c,u){if(typeof c=="string"&&typeof u=="object"&&u!==null&&typeof u.as=="string"){var d=u.as,f=l(d,u.crossOrigin);r.d.L(c,d,{crossOrigin:f,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0,type:typeof u.type=="string"?u.type:void 0,fetchPriority:typeof u.fetchPriority=="string"?u.fetchPriority:void 0,referrerPolicy:typeof u.referrerPolicy=="string"?u.referrerPolicy:void 0,imageSrcSet:typeof u.imageSrcSet=="string"?u.imageSrcSet:void 0,imageSizes:typeof u.imageSizes=="string"?u.imageSizes:void 0,media:typeof u.media=="string"?u.media:void 0})}},Au.preloadModule=function(c,u){if(typeof c=="string")if(u){var d=l(u.as,u.crossOrigin);r.d.m(c,{as:typeof u.as=="string"&&u.as!=="script"?u.as:void 0,crossOrigin:d,integrity:typeof u.integrity=="string"?u.integrity:void 0})}else r.d.m(c)},Au.requestFormReset=function(c){r.d.r(c)},Au.unstable_batchedUpdates=function(c,u){return c(u)},Au.useFormState=function(c,u,d){return a.H.useFormState(c,u,d)},Au.useFormStatus=function(){return a.H.useHostTransitionStatus()},Au.version="19.2.7",Au}var h6e;function Lvt(){if(h6e)return Mte.exports;h6e=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(),Mte.exports=Aon(),Mte.exports}var p6e;function Ron(){if(p6e)return GP;p6e=1;var e={env:{}};var t=Ion(),n=SA(),r=Lvt();function s(S){var O="https://react.dev/errors/"+S;if(1<arguments.length){O+="?args[]="+encodeURIComponent(arguments[1]);for(var j=2;j<arguments.length;j++)O+="&args[]="+encodeURIComponent(arguments[j])}return"Minified React error #"+S+"; visit "+O+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function i(S){return!(!S||S.nodeType!==1&&S.nodeType!==9&&S.nodeType!==11)}function a(S){var O=S,j=S;if(S.alternate)for(;O.return;)O=O.return;else{S=O;do O=S,(O.flags&4098)!==0&&(j=O.return),S=O.return;while(S)}return O.tag===3?j:null}function l(S){if(S.tag===13){var O=S.memoizedState;if(O===null&&(S=S.alternate,S!==null&&(O=S.memoizedState)),O!==null)return O.dehydrated}return null}function c(S){if(S.tag===31){var O=S.memoizedState;if(O===null&&(S=S.alternate,S!==null&&(O=S.memoizedState)),O!==null)return O.dehydrated}return null}function u(S){if(a(S)!==S)throw Error(s(188))}function d(S){var O=S.alternate;if(!O){if(O=a(S),O===null)throw Error(s(188));return O!==S?null:S}for(var j=S,$=O;;){var Z=j.return;if(Z===null)break;var Y=Z.alternate;if(Y===null){if($=Z.return,$!==null){j=$;continue}break}if(Z.child===Y.child){for(Y=Z.child;Y;){if(Y===j)return u(Z),S;if(Y===$)return u(Z),O;Y=Y.sibling}throw Error(s(188))}if(j.return!==$.return)j=Z,$=Y;else{for(var ie=!1,ye=Z.child;ye;){if(ye===j){ie=!0,j=Z,$=Y;break}if(ye===$){ie=!0,$=Z,j=Y;break}ye=ye.sibling}if(!ie){for(ye=Y.child;ye;){if(ye===j){ie=!0,j=Y,$=Z;break}if(ye===$){ie=!0,$=Y,j=Z;break}ye=ye.sibling}if(!ie)throw Error(s(189))}}if(j.alternate!==$)throw Error(s(190))}if(j.tag!==3)throw Error(s(188));return j.stateNode.current===j?S:O}function f(S){var O=S.tag;if(O===5||O===26||O===27||O===6)return S;for(S=S.child;S!==null;){if(O=f(S),O!==null)return O;S=S.sibling}return null}var h=Object.assign,p=Symbol.for("react.element"),m=Symbol.for("react.transitional.element"),v=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),b=Symbol.for("react.strict_mode"),x=Symbol.for("react.profiler"),w=Symbol.for("react.consumer"),k=Symbol.for("react.context"),_=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"),P=Symbol.iterator;function L(S){return S===null||typeof S!="object"?null:(S=P&&S[P]||S["@@iterator"],typeof S=="function"?S:null)}var M=Symbol.for("react.client.reference");function V(S){if(S==null)return null;if(typeof S=="function")return S.$$typeof===M?null:S.displayName||S.name||null;if(typeof S=="string")return S;switch(S){case y:return"Fragment";case x:return"Profiler";case b:return"StrictMode";case C:return"Suspense";case T:return"SuspenseList";case I:return"Activity"}if(typeof S=="object")switch(S.$$typeof){case v:return"Portal";case k:return S.displayName||"Context";case w:return(S._context.displayName||"Context")+".Consumer";case _:var O=S.render;return S=S.displayName,S||(S=O.displayName||O.name||"",S=S!==""?"ForwardRef("+S+")":"ForwardRef"),S;case E:return O=S.displayName||null,O!==null?O:V(S.type)||"Memo";case N:O=S._payload,S=S._init;try{return V(S(O))}catch{}}return null}var q=Array.isArray,H=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,B=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,W={pending:!1,data:null,method:null,action:null},z=[],G=-1;function F(S){return{current:S}}function R(S){0>G||(S.current=z[G],z[G]=null,G--)}function D(S,O){G++,z[G]=S.current,S.current=O}var U=F(null),Q=F(null),ee=F(null),J=F(null);function te(S,O){switch(D(ee,O),D(Q,S),D(U,null),O.nodeType){case 9:case 11:S=(S=O.documentElement)&&(S=S.namespaceURI)?j5e(S):0;break;default:if(S=O.tagName,O=O.namespaceURI)O=j5e(O),S=N5e(O,S);else switch(S){case"svg":S=1;break;case"math":S=2;break;default:S=0}}R(U),D(U,S)}function re(){R(U),R(Q),R(ee)}function ce(S){S.memoizedState!==null&&D(J,S);var O=U.current,j=N5e(O,S.type);O!==j&&(D(Q,S),D(U,j))}function X(S){Q.current===S&&(R(U),R(Q)),J.current===S&&(R(J),VP._currentValue=W)}var ne,se;function le(S){if(ne===void 0)try{throw Error()}catch(j){var O=j.stack.trim().match(/\n( *(at )?)/);ne=O&&O[1]||"",se=-1<j.stack.indexOf(`
3
3
  at`)?" (<anonymous>)":-1<j.stack.indexOf("@")?"@unknown:0:0":""}return`
4
4
  `+ne+S+se}var he=!1;function pe(S,O){if(!S||he)return"";he=!0;var j=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var $={DetermineComponentFrameRoot:function(){try{if(O){var Pt=function(){throw Error()};if(Object.defineProperty(Pt.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Pt,[])}catch(gt){var lt=gt}Reflect.construct(S,[],Pt)}else{try{Pt.call()}catch(gt){lt=gt}S.call(Pt.prototype)}}else{try{throw Error()}catch(gt){lt=gt}(Pt=S())&&typeof Pt.catch=="function"&&Pt.catch(function(){})}}catch(gt){if(gt&&lt&&typeof gt.stack=="string")return[gt.stack,lt.stack]}return[null,null]}};$.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var Z=Object.getOwnPropertyDescriptor($.DetermineComponentFrameRoot,"name");Z&&Z.configurable&&Object.defineProperty($.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var Y=$.DetermineComponentFrameRoot(),ie=Y[0],ye=Y[1];if(ie&&ye){var Ve=ie.split(`
@@ -228,7 +228,7 @@ attempted value: ${a}
228
228
  \${}
229
229
  }
230
230
  }`,{label:"class",detail:"definition",type:"keyword"}),wf('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),wf('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],ZAt=Fje.concat([wf("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),wf("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),wf("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),FWe=new Kjt,GAt=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function x$(e){return(t,n)=>{let r=t.node.getChild("VariableDefinition");return r&&n(r,e),!0}}const Oar=["FunctionDeclaration"],Car={FunctionDeclaration:x$("function"),ClassDeclaration:x$("class"),ClassExpression:()=>!0,EnumDeclaration:x$("constant"),TypeAliasDeclaration:x$("type"),NamespaceDeclaration:x$("namespace"),VariableDefinition(e,t){e.matchContext(Oar)||t(e,"variable")},TypeDefinition(e,t){t(e,"type")},__proto__:null};function QAt(e,t){let n=FWe.get(t);if(n)return n;let r=[],s=!0;function i(a,l){let c=e.sliceString(a.from,a.to);r.push({label:c,type:l})}return t.cursor(Ui.IncludeAnonymous).iterate(a=>{if(s)s=!1;else if(a.name){let l=Car[a.name];if(l&&l(a,i)||GAt.has(a.name))return!1}else if(a.to-a.from>8192){for(let l of QAt(e,a.node))r.push(l);return!1}}),FWe.set(t,r),r}const Kq=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,zje=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function KAt(e){let t=ba(e.state).resolveInner(e.pos,-1);if(zje.indexOf(t.name)>-1)return null;let n=t.name=="VariableName"||t.to-t.from<20&&Kq.test(e.state.sliceDoc(t.from,t.to));if(!n&&!e.explicit)return null;let r=[];for(let s=t;s;s=s.parent)GAt.has(s.name)&&(r=r.concat(QAt(e.state.doc,s)));return{options:r,from:n?t.from:e.pos,validFor:Kq}}function Vse(e,t,n){var r;let s=[];for(;;){let i=t.firstChild,a;if(i?.name=="VariableName")return s.push(e(i)),{path:s.reverse(),name:n};if(i?.name=="MemberExpression"&&((r=a=i.lastChild)===null||r===void 0?void 0:r.name)=="PropertyName")s.push(e(a)),t=i;else return null}}function YAt(e){let t=r=>e.state.doc.sliceString(r.from,r.to),n=ba(e.state).resolveInner(e.pos,-1);return n.name=="PropertyName"?Vse(t,n.parent,t(n)):(n.name=="."||n.name=="?.")&&n.parent.name=="MemberExpression"?Vse(t,n.parent,""):zje.indexOf(n.name)>-1?null:n.name=="VariableName"||n.to-n.from<20&&Kq.test(t(n))?{path:[],name:t(n)}:n.name=="MemberExpression"?Vse(t,n,""):e.explicit?{path:[],name:""}:null}function _ar(e,t){let n=e,r=[],s=new Set;for(let i=0;;i++){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:-i})}let a=Object.getPrototypeOf(e);if(!a)return r;e=a}}function Ear(e){let t=new Map;return n=>{let r=YAt(n);if(!r)return null;let s=e;for(let a of r.path)if(s=s[a],!s)return null;let i=t.get(s);return i||t.set(s,i=_ar(s,!r.path.length)),{from:n.pos-r.name.length,options:i,validFor:Kq}}}const wm=t_.define({name:"javascript",parser:kar.configure({props:[lE.add({IfStatement:yN({except:/^\s*({|else\b)/}),TryStatement:yN({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:xnr,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:bnr({closing:"}"}),ArrowFunction:e=>e.baseIndent+e.unit,"TemplateString BlockComment":()=>null,"Statement Property":yN({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}}),cE.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":bje,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:"$"}}),XAt={test:e=>/^JSX/.test(e.name),facet:bQ({commentTokens:{block:{open:"{/*",close:"*/}"}}})},Bje=wm.configure({dialect:"ts"},"typescript"),Uje=wm.configure({dialect:"jsx",props:[gje.add(e=>e.isTop?[XAt]:void 0)]}),Vje=wm.configure({dialect:"jsx ts",props:[gje.add(e=>e.isTop?[XAt]:void 0)]},"typescript");let JAt=e=>({label:e,type:"keyword"});const eRt="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(JAt),Tar=eRt.concat(["declare","implements","private","protected","public"].map(JAt));function Yq(e={}){let t=e.jsx?e.typescript?Vje:Uje:e.typescript?Bje:wm,n=e.typescript?ZAt.concat(Tar):Fje.concat(eRt);return new r_(t,[wm.data.of({autocomplete:irr(zje,XIt(n))}),wm.data.of({autocomplete:KAt}),e.jsx?tRt:[]])}function jar(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 zWe(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 Nar=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),tRt=Rt.inputHandler.of((e,t,n,r,s)=>{if((Nar?e.composing:e.compositionStarted)||e.state.readOnly||t!=n||r!=">"&&r!="/"||!wm.isActiveAt(e.state,t,-1))return!1;let i=s(),{state:a}=i,l=a.changeByRange(c=>{var u;let{head:d}=c,f=ba(a).resolveInner(d-1,-1),h;if(f.name=="JSXStartTag"&&(f=f.parent),!(a.doc.sliceString(d-1,d)!=r||f.name=="JSXAttributeValue"&&f.to>d)){if(r==">"&&f.name=="JSXFragmentTag")return{range:c,changes:{from:d,insert:"</>"}};if(r=="/"&&f.name=="JSXStartCloseTag"){let p=f.parent,m=p.parent;if(m&&p.from==d-2&&((h=zWe(a.doc,m.firstChild,d))||((u=m.firstChild)===null||u===void 0?void 0:u.name)=="JSXFragmentTag")){let v=`${h}>`;return{range:wt.cursor(d+v.length,-1),changes:{from:d,insert:v}}}}else if(r==">"){let p=jar(f);if(p&&p.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(a.doc.sliceString(d,d+2))&&(h=zWe(a.doc,p,d)))return{range:c,changes:{from:d,insert:`</${h}>`}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([i,a.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)});function Iar(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:i,to:a}of wm.findRegions(r)){let l=r.doc.lineAt(i),c={line:l.number-1,col:i-l.from,pos:i};for(let u of e.verify(r.sliceDoc(i,a),t))s.push(Aar(u,r.doc,c))}return s}}function BWe(e,t,n,r){return n.line(e+r.line).from+t+(e==1?r.col-1:-1)}function Aar(e,t,n){let r=BWe(e.line,e.column,t,n),s={from:r,to:e.endLine!=null&&e.endColumn!=1?BWe(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:i,text:a}=e.fix,l=i[0]+n.pos-r,c=i[1]+n.pos-r;s.actions=[{name:"fix",apply(u,d){u.dispatch({changes:{from:d+l,to:d+c,insert:a},scrollIntoView:!0})}}]}return s}const F9=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:tRt,completionPath:YAt,esLint:Iar,javascript:Yq,javascriptLanguage:wm,jsxLanguage:Uje,localCompletionSource:KAt,scopeCompletionSource:Ear,snippets:Fje,tsxLanguage:Vje,typescriptLanguage:Bje,typescriptSnippets:ZAt},Symbol.toStringTag,{value:"Module"})),w$=["_blank","_self","_top","_parent"],qse=["ascii","utf-8","utf-16","latin1","latin1"],Hse=["get","post","put","delete"],Wse=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],kh=["true","false"],nr={},Rar={a:{attrs:{href:null,ping:null,type:null,media:null,target:w$,hreflang:null}},abbr:nr,address:nr,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:nr,aside:nr,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:nr,base:{attrs:{href:null,target:w$}},bdi:nr,bdo:nr,blockquote:{attrs:{cite:null}},body:nr,br:nr,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:Wse,formmethod:Hse,formnovalidate:["novalidate"],formtarget:w$,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:nr,center:nr,cite:nr,code:nr,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:nr,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:nr,div:nr,dl:nr,dt:nr,em:nr,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:nr,figure:nr,footer:nr,form:{attrs:{action:null,name:null,"accept-charset":qse,autocomplete:["on","off"],enctype:Wse,method:Hse,novalidate:["novalidate"],target:w$}},h1:nr,h2:nr,h3:nr,h4:nr,h5:nr,h6:nr,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:nr,hgroup:nr,hr:nr,html:{attrs:{manifest:null}},i:nr,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:Wse,formmethod:Hse,formnovalidate:["novalidate"],formtarget:w$,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:nr,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:nr,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:nr,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:qse,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:nr,noscript:nr,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:nr,param:{attrs:{name:null,value:null}},pre:nr,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:nr,rt:nr,ruby:nr,samp:nr,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:qse}},section:nr,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:nr,source:{attrs:{src:null,type:null,media:null}},span:nr,strong:nr,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:nr,summary:nr,sup:nr,table:nr,tbody:nr,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:nr,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:nr,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:nr,time:{attrs:{datetime:null}},title:nr,tr:nr,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:nr,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:nr},nRt={accesskey:null,class:null,contenteditable:kh,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:kh,autocorrect:kh,autocapitalize:kh,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":kh,"aria-autocomplete":["inline","list","both","none"],"aria-busy":kh,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":kh,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":kh,"aria-hidden":kh,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":kh,"aria-multiselectable":kh,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":kh,"aria-relevant":null,"aria-required":kh,"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},rRt="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 rRt)nRt[e]=null;let LL=class{constructor(t,n){this.tags={...Rar,...t},this.globalAttrs={...nRt,...n},this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}};LL.default=new LL;function SI(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 kI(e,t=!1){for(;e;e=e.parent)if(e.name=="Element")if(t)t=!1;else return e;return null}function sRt(e,t,n){let r=n.tags[SI(e,kI(t))];return r?.children||n.allTags}function qje(e,t){let n=[];for(let r=kI(t);r&&!r.type.isTop;r=kI(r.parent)){let s=SI(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 iRt=/^[:\-\.\w\u00b7-\uffff]*$/;function UWe(e,t,n,r,s){let i=/\s*>/.test(e.sliceDoc(s,s+5))?"":">",a=kI(n,n.name=="StartTag"||n.name=="TagName");return{from:r,to:s,options:sRt(e.doc,a,t).map(l=>({label:l,type:"type"})).concat(qje(e.doc,n).map((l,c)=>({label:"/"+l,apply:"/"+l+i,type:"type",boost:99-c}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function VWe(e,t,n,r){let s=/\s*>/.test(e.sliceDoc(r,r+5))?"":">";return{from:n,to:r,options:qje(e.doc,t).map((i,a)=>({label:i,apply:i+s,type:"type",boost:99-a})),validFor:iRt}}function Par(e,t,n,r){let s=[],i=0;for(let a of sRt(e.doc,n,t))s.push({label:"<"+a,type:"type"});for(let a of qje(e.doc,n))s.push({label:"</"+a+">",type:"type",boost:99-i++});return{from:r,to:r,options:s,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function $ar(e,t,n,r,s){let i=kI(n),a=i?t.tags[SI(e.doc,i)]:null,l=a&&a.attrs?Object.keys(a.attrs):[],c=a&&a.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:iRt}}function Mar(e,t,n,r,s){var i;let a=(i=n.parent)===null||i===void 0?void 0:i.getChild("AttributeName"),l=[],c;if(a){let u=e.sliceDoc(a.from,a.to),d=t.globalAttrs[u];if(!d){let f=kI(n),h=f?t.tags[SI(e.doc,f)]:null;d=h?.attrs&&h.attrs[u]}if(d){let f=e.sliceDoc(r,s).toLowerCase(),h='"',p='"';/^['"]/.test(f)?(c=f[0]=='"'?/^[^"]*$/:/^[^']*$/,h="",p=e.sliceDoc(s,s+1)==f[0]?"":f[0],f=f.slice(1),r++):c=/^[^\s<>='"]*$/;for(let m of d)l.push({label:m,apply:h+m+p,type:"constant"})}}return{from:r,to:s,options:l,validFor:c}}function aRt(e,t){let{state:n,pos:r}=t,s=ba(n).resolveInner(r,-1),i=s.resolve(r);for(let a=r,l;i==s&&(l=s.childBefore(a));){let c=l.lastChild;if(!c||!c.type.isError||c.from<c.to)break;i=s=l,a=c.from}return s.name=="TagName"?s.parent&&/CloseTag$/.test(s.parent.name)?VWe(n,s,s.from,r):UWe(n,e,s,s.from,r):s.name=="StartTag"||s.name=="IncompleteTag"?UWe(n,e,s,r,r):s.name=="StartCloseTag"||s.name=="IncompleteCloseTag"?VWe(n,s,r,r):s.name=="OpenTag"||s.name=="SelfClosingTag"||s.name=="AttributeName"?$ar(n,e,s,s.name=="AttributeName"?s.from:r,r):s.name=="Is"||s.name=="AttributeValue"||s.name=="UnquotedAttributeValue"?Mar(n,e,s,s.name=="Is"?r:s.from,r):t.explicit&&(i.name=="Element"||i.name=="Text"||i.name=="Document")?Par(n,e,s,r):null}function Dar(e){return aRt(LL.default,e)}function Lar(e){let{extraTags:t,extraGlobalAttributes:n}=e,r=n||t?new LL(t,n):LL.default;return s=>aRt(r,s)}const Far=wm.parser.configure({top:"SingleExpression"}),oRt=[{tag:"script",attrs:e=>e.type=="text/typescript"||e.lang=="ts",parser:Bje.parser},{tag:"script",attrs:e=>e.type=="text/babel"||e.type=="text/jsx",parser:Uje.parser},{tag:"script",attrs:e=>e.type=="text/typescript-jsx",parser:Vje.parser},{tag:"script",attrs(e){return/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(e.type)},parser:Far},{tag:"script",attrs(e){return!e.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(e.type)},parser:wm.parser},{tag:"style",attrs(e){return(!e.lang||e.lang=="css")&&(!e.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(e.type))},parser:Qq.parser}],lRt=[{name:"style",parser:Qq.parser.configure({top:"Styles"})}].concat(rRt.map(e=>({name:e,parser:wm.parser}))),cRt=t_.define({name:"html",parser:cir.configure({props:[lE.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}}),cE.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}}}),HIt.add({"OpenTag CloseTag":e=>e.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:"<!--",close:"-->"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-_"}}),j7=cRt.configure({wrap:zAt(oRt,lRt)});function zar(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=zAt((e.nestedLanguages||[]).concat(oRt),(e.nestedAttributes||[]).concat(lRt)));let r=n?cRt.configure({wrap:n,dialect:t}):t?j7.configure({dialect:t}):j7;return new r_(r,[j7.data.of({autocomplete:Lar(e)}),e.autoCloseTags!==!1?Bar:[],Yq().support,Hir().support])}const qWe=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" ")),Bar=Rt.inputHandler.of((e,t,n,r,s)=>{if(e.composing||e.state.readOnly||t!=n||r!=">"&&r!="/"||!j7.isActiveAt(e.state,t,-1))return!1;let i=s(),{state:a}=i,l=a.changeByRange(c=>{var u,d,f;let h=a.doc.sliceString(c.from-1,c.to)==r,{head:p}=c,m=ba(a).resolveInner(p,-1),v;if(h&&r==">"&&m.name=="EndTag"){let y=m.parent;if(((d=(u=y.parent)===null||u===void 0?void 0:u.lastChild)===null||d===void 0?void 0:d.name)!="CloseTag"&&(v=SI(a.doc,y.parent,p))&&!qWe.has(v)){let b=p+(a.doc.sliceString(p,p+1)===">"?1:0),x=`</${v}>`;return{range:c,changes:{from:p,to:b,insert:x}}}}else if(h&&r=="/"&&m.name=="IncompleteCloseTag"){let y=m.parent;if(m.from==p-2&&((f=y.lastChild)===null||f===void 0?void 0:f.name)!="CloseTag"&&(v=SI(a.doc,y,p))&&!qWe.has(v)){let b=p+(a.doc.sliceString(p,p+1)===">"?1:0),x=`${v}>`;return{range:wt.cursor(p+x.length,-1),changes:{from:p,to:b,insert:x}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([i,a.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),uRt=bQ({commentTokens:{block:{open:"<!--",close:"-->"}}}),dRt=new Rr,fRt=dsr.configure({props:[cE.add(e=>!e.is("Block")||e.is("Document")||z0e(e)!=null||Uar(e)?void 0:(t,n)=>({from:n.doc.lineAt(t.from).to,to:t.to})),dRt.add(z0e),lE.add({Document:()=>null}),CS.add({Document:uRt})]});function z0e(e){let t=/^(?:ATX|Setext)Heading(\d)$/.exec(e.name);return t?+t[1]:void 0}function Uar(e){return e.name=="OrderedList"||e.name=="BulletList"}function Var(e,t){let n=e;for(;;){let r=n.nextSibling,s;if(!r||(s=z0e(r.type))!=null&&s<=t)break;n=r}return n.to}const qar=RIt.of((e,t,n)=>{for(let r=ba(e).resolveInner(n,-1);r&&!(r.from<t);r=r.parent){let s=r.type.prop(dRt);if(s==null)continue;let i=Var(r,s);if(i>n)return{from:n,to:i}}return null});function Hje(e){return new Gh(uRt,e,[],"markdown")}const hRt=Hje(fRt),Har=fRt.configure([Ssr,Osr,ksr,Csr,{props:[cE.add({Table:(e,t)=>({from:t.doc.lineAt(e.from).to,to:e.to})})]}]),OI=Hje(Har);function War(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:n_.getSkippingParser(r.load());if(r)return r.parser}return t?t.parser:null}}class Zse{constructor(t,n,r,s,i,a,l){this.node=t,this.from=n,this.to=r,this.spaceBefore=s,this.spaceAfter=i,this.type=a,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(+mRt(this.item,t)[2]+n):"";return this.spaceBefore+r+this.type+this.spaceAfter}}function pRt(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 i=n[s],a,l=t.lineAt(i.from),c=i.from-l.from;if(i.name=="Blockquote"&&(a=/^ *>( ?)/.exec(l.text.slice(c))))r.push(new Zse(i,c,c+a[0].length,"",a[1],">",null));else if(i.name=="ListItem"&&i.parent.name=="OrderedList"&&(a=/^( *)\d+([.)])( *)/.exec(l.text.slice(c)))){let u=a[3],d=a[0].length;u.length>=4&&(u=u.slice(0,u.length-4),d-=4),r.push(new Zse(i.parent,c,c+d,a[1],u,a[2],i))}else if(i.name=="ListItem"&&i.parent.name=="BulletList"&&(a=/^( *)([-+*])( {1,4}\[[ xX]\])?( +)/.exec(l.text.slice(c)))){let u=a[4],d=a[0].length;u.length>4&&(u=u.slice(0,u.length-4),d-=4);let f=a[2];a[3]&&(f+=a[3].replace(/[xX]/," ")),r.push(new Zse(i.parent,c,c+d,a[1],u,f,i))}}return r}function mRt(e,t){return/^(\s*)(\d+)(?=[.)])/.exec(t.sliceString(e.from,e.from+10))}function Gse(e,t,n,r=0){for(let s=-1,i=e;;){if(i.name=="ListItem"){let l=mRt(i,t),c=+l[2];if(s>=0){if(c!=s+1)return;n.push({from:i.from+l[1].length,to:i.from+l[0].length,insert:String(s+2+r)})}s=c}let a=i.nextSibling;if(!a)break;i=a}}function Wje(e,t){let n=/^[ \t]*/.exec(e)[0].length;if(!n||t.facet(KA)!=" ")return e;let r=cv(e,4,n),s="";for(let i=r;i>0;)i>=4?(s+=" ",i-=4):(s+=" ",i--);return s+e.slice(n)}const gRt=(e={})=>({state:t,dispatch:n})=>{let r=ba(t),{doc:s}=t,i=null,a=t.changeByRange(l=>{if(!l.empty||!OI.isActiveAt(t,l.from,-1)&&!OI.isActiveAt(t,l.from,1))return i={range:l};let c=l.from,u=s.lineAt(c),d=pRt(r.resolveInner(c,-1),s);for(;d.length&&d[d.length-1].from>c-u.from;)d.pop();if(!d.length)return i={range:l};let f=d[d.length-1];if(f.to-f.spaceAfter.length>c-u.from)return i={range:l};let h=c>=f.to-f.spaceAfter.length&&!/\S/.test(u.text.slice(f.to));if(f.item&&h){let b=f.node.firstChild,x=f.node.getChild("ListItem","ListItem");if(b.to>=c||x&&x.to<c||u.from>0&&!/[^\s>]/.test(s.lineAt(u.from-1).text)||e.nonTightLists===!1){let w=d.length>1?d[d.length-2]:null,k,_="";w&&w.item?(k=u.from+w.from,_=w.marker(s,1)):k=u.from+(w?w.to:0);let C=[{from:k,to:c,insert:_}];return f.node.name=="OrderedList"&&Gse(f.item,s,C,-2),w&&w.node.name=="OrderedList"&&Gse(w.item,s,C),{range:wt.cursor(k+_.length),changes:C}}else{let w=WWe(d,t,u);return{range:wt.cursor(c+w.length+1),changes:{from:u.from,insert:w+t.lineBreak}}}}if(f.node.name=="Blockquote"&&h&&u.from){let b=s.lineAt(u.from-1),x=/>\s*$/.exec(b.text);if(x&&x.index==f.from){let w=t.changes([{from:b.from+x.index,to:b.to},{from:u.from+f.from,to:u.to}]);return{range:l.map(w),changes:w}}}let p=[];f.node.name=="OrderedList"&&Gse(f.item,s,p);let m=f.item&&f.item.from<u.from,v="";if(!m||/^[\s\d.)\-+*>]*/.exec(u.text)[0].length>=f.to)for(let b=0,x=d.length-1;b<=x;b++)v+=b==x&&!m?d[b].marker(s,1):d[b].blank(b<x?cv(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=Wje(v,t),Zar(f.node,t.doc)&&(v=WWe(d,t,u)+t.lineBreak+v),p.push({from:y,to:c,insert:t.lineBreak+v}),{range:wt.cursor(y+v.length+1),changes:p}});return i?!1:(n(t.update(a,{scrollIntoView:!0,userEvent:"input"})),!0)},vRt=gRt();function HWe(e){return e.name=="QuoteMark"||e.name=="ListMark"}function Zar(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),i=t.lineAt(r.from),a=/^[\s>]*$/.test(s.text);return s.number+(a?0:1)<i.number}function WWe(e,t,n){let r="";for(let s=0,i=e.length-2;s<=i;s++)r+=e[s].blank(s<i?cv(n.text,4,e[s+1].from)-r.length:null,s<i);return Wje(r,t)}function Gar(e,t){let n=e.resolveInner(t,-1),r=t;HWe(n)&&(r=n.from,n=n.parent);for(let s;s=n.childBefore(r);)if(HWe(s))r=s.from;else if(s.name=="OrderedList"||s.name=="BulletList")n=s.lastChild,r=n.to;else break;return n}const yRt=({state:e,dispatch:t})=>{let n=ba(e),r=null,s=e.changeByRange(i=>{let a=i.from,{doc:l}=e;if(i.empty&&OI.isActiveAt(e,i.from)){let c=l.lineAt(a),u=pRt(Gar(n,a),l);if(u.length){let d=u[u.length-1],f=d.to-d.spaceAfter.length+(d.spaceAfter?1:0);if(a-c.from>f&&!/\S/.test(c.text.slice(f,a-c.from)))return{range:wt.cursor(c.from+f),changes:{from:c.from+f,to:a}};if(a-c.from==f&&(!d.item||c.from<=d.item.from||!/\S/.test(c.text.slice(0,d.to)))){let h=c.from+d.from;if(d.item&&d.node.from<d.item.from&&/\S/.test(c.text.slice(d.from,d.to))){let p=d.blank(cv(c.text,4,d.to)-cv(c.text,4,d.from));return h==c.from&&(p=Wje(p,e)),{range:wt.cursor(h+p.length),changes:{from:h,to:c.from+d.to,insert:p}}}if(h<a)return{range:wt.cursor(h),changes:{from:h,to:a}}}}}return r={range:i}});return r?!1:(t(e.update(s,{scrollIntoView:!0,userEvent:"delete"})),!0)},bRt=[{key:"Enter",run:vRt},{key:"Backspace",run:yRt}],xRt=zar({matchClosingTags:!1});function wRt(e={}){let{codeLanguages:t,defaultCodeLanguage:n,addKeymap:r=!0,base:{parser:s}=hRt,completeHTMLTags:i=!0,pasteURLAsLink:a=!0,htmlTagLanguage:l=xRt}=e;if(!(s instanceof kQ))throw new RangeError("Base parser provided to `markdown` should be a Markdown parser");let c=e.extensions?[e.extensions]:[],u=[l.support,qar],d;a&&u.push(SRt),n instanceof r_?(u.push(n.support),d=n.language):n&&(d=n);let f=t||d?War(t,d):void 0;c.push(hsr({codeParser:f,htmlParser:l.language.parser})),r&&u.push(bp.high(QA.of(bRt)));let h=Hje(s.configure(c));return i&&u.push(h.data.of({autocomplete:Qar})),new r_(h,u)}function Qar(e){let{state:t,pos:n}=e,r=/<[:\-\.\w\u00b7-\uffff]*$/.exec(t.sliceDoc(n-25,n));if(!r)return null;let s=ba(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:Kar(),validFor:/^<[:\-\.\w\u00b7-\uffff]*$/}}let Qse=null;function Kar(){if(Qse)return Qse;let e=Dar(new kje(gs.create({extensions:xRt}),0,!0));return Qse=e?e.options:[]}const Yar=/code|horizontalrule|html|link|comment|processing|escape|entity|image|mark|url/i,SRt=Rt.domEventHandlers({paste:(e,t)=>{var n;let{main:r}=t.state.selection;if(r.empty)return!1;let s=(n=e.clipboardData)===null||n===void 0?void 0:n.getData("text/plain");if(!s||!/^(https?:\/\/|mailto:|xmpp:|www\.)/.test(s)||(/^www\./.test(s)&&(s="https://"+s),!OI.isActiveAt(t.state,r.from,1)))return!1;let i=ba(t.state),a=!1;return i.iterate({from:r.from,to:r.to,enter:l=>{(l.from>r.from||Yar.test(l.name))&&(a=!0)},leave:l=>{l.to<r.to&&(a=!0)}}),a?!1:(t.dispatch({changes:[{from:r.from,insert:"["},{from:r.to,insert:`](${s})`}],userEvent:"input.paste",scrollIntoView:!0}),!0)}}),Xar=Object.freeze(Object.defineProperty({__proto__:null,commonmarkLanguage:hRt,deleteMarkupBackward:yRt,insertNewlineContinueMarkup:vRt,insertNewlineContinueMarkupCommand:gRt,markdown:wRt,markdownKeymap:bRt,markdownLanguage:OI,pasteURLAsLink:SRt},Symbol.toStringTag,{value:"Module"}));function a_(){return a_=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},a_.apply(null,arguments)}var Jar=e=>{var t=e.theme,n=e.settings,r=n===void 0?{}:n,s=e.styles,i=s===void 0?[]:s,a={".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)&&(a["&"]=l),r.fontFamily&&(a["&.cm-editor .cm-scroller"]={fontFamily:r.fontFamily}),r.gutterBackground&&(a[".cm-gutters"].backgroundColor=r.gutterBackground),r.gutterForeground&&(a[".cm-gutters"].color=r.gutterForeground),r.gutterBorder&&(a[".cm-gutters"].borderRightColor=r.gutterBorder),r.caret&&(a[".cm-content"]={caretColor:r.caret},a[".cm-cursor, .cm-dropCursor"]={borderLeftColor:r.caret});var c={};r.gutterActiveForeground&&(c.color=r.gutterActiveForeground),r.lineHighlight&&(a[".cm-activeLine"]={backgroundColor:r.lineHighlight},c.backgroundColor=r.lineHighlight),a[".cm-activeLineGutter"]=c,r.selection&&(a["&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection"]={background:r.selection+" !important"}),r.selectionMatch&&(a["& .cm-selectionMatch"]={backgroundColor:r.selectionMatch});var u=Rt.theme(a,{dark:t==="dark"}),d=wv.define(i),f=[u,J1(d)];return f},eor={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)"},tor=[{tag:oe.comment,color:"#6272a4"},{tag:oe.string,color:"#f1fa8c"},{tag:oe.atom,color:"#bd93f9"},{tag:oe.meta,color:"#f8f8f2"},{tag:[oe.keyword,oe.operator,oe.tagName],color:"#ff79c6"},{tag:[oe.function(oe.propertyName),oe.propertyName],color:"#66d9ef"},{tag:[oe.definition(oe.variableName),oe.function(oe.variableName),oe.className,oe.attributeName],color:"#50fa7b"},{tag:oe.atom,color:"#bd93f9"}],XA=e=>{var t=e||{},n=t.theme,r=n===void 0?"dark":n,s=t.settings,i=s===void 0?{}:s,a=t.styles,l=a===void 0?[]:a;return Jar({theme:r,settings:a_({},eor,i),styles:[...tor,...l]})};XA();function kRt(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 nor=e=>{let{state:t}=e,n=t.doc.lineAt(t.selection.main.from),r=Gje(e.state,n.from);return r.line?ror(e):r.block?ior(e):!1};function Zje(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 ror=Zje(lor,0),sor=Zje(ORt,0),ior=Zje((e,t)=>ORt(e,t,oor(t)),0);function Gje(e,t){let n=e.languageDataAt("commentTokens",t,1);return n.length?n[0]:{}}const S$=50;function aor(e,{open:t,close:n},r,s){let i=e.sliceDoc(r-S$,r),a=e.sliceDoc(s,s+S$),l=/\s*$/.exec(i)[0].length,c=/^\s*/.exec(a)[0].length,u=i.length-l;if(i.slice(u-t.length,u)==t&&a.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*S$?d=f=e.sliceDoc(r,s):(d=e.sliceDoc(r,r+S$),f=e.sliceDoc(s-S$,s));let h=/^\s*/.exec(d)[0].length,p=/\s*$/.exec(f)[0].length,m=f.length-p-n.length;return d.slice(h,h+t.length)==t&&f.slice(m,m+n.length)==n?{open:{pos:r+h+t.length,margin:/\s/.test(d.charAt(h+t.length))?1:0},close:{pos:s-p-n.length,margin:/\s/.test(f.charAt(m-1))?1:0}}:null}function oor(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 i=t.length-1;i>=0&&t[i].to>r.from?t[i].to=s.to:t.push({from:r.from+/^\s*/.exec(r.text)[0].length,to:s.to})}return t}function ORt(e,t,n=t.selection.ranges){let r=n.map(i=>Gje(t,i.from).block);if(!r.every(i=>i))return null;let s=n.map((i,a)=>aor(t,r[a],i.from,i.to));if(e!=2&&!s.every(i=>i))return{changes:t.changes(n.map((i,a)=>s[a]?[]:[{from:i.from,insert:r[a].open+" "},{from:i.to,insert:" "+r[a].close}]))};if(e!=1&&s.some(i=>i)){let i=[];for(let a=0,l;a<s.length;a++)if(l=s[a]){let c=r[a],{open:u,close:d}=l;i.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:i}}return null}function lor(e,t,n=t.selection.ranges){let r=[],s=-1;e:for(let{from:i,to:a}of n){let l=r.length,c=1e9,u;for(let d=i;d<=a;){let f=t.doc.lineAt(d);if(u==null&&(u=Gje(t,f.from).line,!u))continue e;if(f.from>s&&(i==a||a>f.from)){s=f.from;let h=/^\s*/.exec(f.text)[0].length,p=h==f.length,m=f.text.slice(h,h+u.length)==u?h:-1;h<f.text.length&&h<c&&(c=h),r.push({line:f,comment:m,token:u,indent:h,empty:p,single:!1})}d=f.to+1}if(c<1e9)for(let d=l;d<r.length;d++)r[d].indent<r[d].line.text.length&&(r[d].indent=c);r.length==l+1&&(r[l].single=!0)}if(e!=2&&r.some(i=>i.comment<0&&(!i.empty||i.single))){let i=[];for(let{line:l,token:c,indent:u,empty:d,single:f}of r)(f||!d)&&i.push({from:l.from+u,insert:c+" "});let a=t.changes(i);return{changes:a,selection:t.selection.map(a,1)}}else if(e!=1&&r.some(i=>i.comment>=0)){let i=[];for(let{line:a,comment:l,token:c}of r)if(l>=0){let u=a.from+l,d=u+c.length;a.text[d-a.from]==" "&&d++,i.push({from:u,to:d})}return{changes:i}}return null}const B0e=Cb.define(),cor=Cb.define(),uor=wn.define(),CRt=wn.define({combine(e){return _b(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)})}}),_Rt=Ol.define({create(){return Iy.empty},update(e,t){let n=t.state.facet(CRt),r=t.annotation(B0e);if(r){let c=Df.fromTransaction(t,r.selection),u=r.side,d=u==0?e.undone:e.done;return c?d=Xq(d,d.length,n.minDepth,c):d=jRt(d,t.startState.selection),new Iy(u==0?r.rest:d,u==0?d:r.rest)}let s=t.annotation(cor);if((s=="full"||s=="before")&&(e=e.isolate()),t.annotation(Ll.addToHistory)===!1)return t.changes.empty?e:e.addMapping(t.changes.desc);let i=Df.fromTransaction(t),a=t.annotation(Ll.time),l=t.annotation(Ll.userEvent);return i?e=e.addChanges(i,a,l,n,t):t.selection&&(e=e.addSelection(t.startState.selection,a,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 Iy(e.done.map(Df.fromJSON),e.undone.map(Df.fromJSON))}});function dor(e={}){return[_Rt,CRt.of(e),Rt.domEventHandlers({beforeinput(t,n){let r=t.inputType=="historyUndo"?ERt:t.inputType=="historyRedo"?U0e:null;return r?(t.preventDefault(),r(n)):!1}})]}function OQ(e,t){return function({state:n,dispatch:r}){if(!t&&n.readOnly)return!1;let s=n.field(_Rt,!1);if(!s)return!1;let i=s.pop(e,n,t);return i?(r(i),!0):!1}}const ERt=OQ(0,!1),U0e=OQ(1,!1),hor=OQ(0,!0),por=OQ(1,!0);class Df{constructor(t,n,r,s,i){this.changes=t,this.effects=n,this.mapped=r,this.startSelection=s,this.selectionsAfter=i}setSelAfter(t){return new Df(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 Df(t.changes&&Ml.fromJSON(t.changes),[],t.mapped&&qy.fromJSON(t.mapped),t.startSelection&&wt.fromJSON(t.startSelection),t.selectionsAfter.map(wt.fromJSON))}static fromTransaction(t,n){let r=um;for(let s of t.startState.facet(uor)){let i=s(t);i.length&&(r=r.concat(i))}return!r.length&&t.changes.empty?null:new Df(t.changes.invert(t.startState.doc),r,void 0,n||t.startState.selection,um)}static selection(t){return new Df(void 0,um,void 0,void 0,t)}}function Xq(e,t,n,r){let s=t+1>n+20?t-n-1:0,i=e.slice(s,t);return i.push(r),i}function mor(e,t){let n=[],r=!1;return e.iterChangedRanges((s,i)=>n.push(s,i)),t.iterChangedRanges((s,i,a,l)=>{for(let c=0;c<n.length;){let u=n[c++],d=n[c++];l>=u&&a<=d&&(r=!0)}}),r}function gor(e,t){return e.ranges.length==t.ranges.length&&e.ranges.filter((n,r)=>n.empty!=t.ranges[r].empty).length===0}function TRt(e,t){return e.length?t.length?e.concat(t):e:t}const um=[],vor=200;function jRt(e,t){if(e.length){let n=e[e.length-1],r=n.selectionsAfter.slice(Math.max(0,n.selectionsAfter.length-vor));return r.length&&r[r.length-1].eq(t)?e:(r.push(t),Xq(e,e.length-1,1e9,n.setSelAfter(r)))}else return[Df.selection([t])]}function yor(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 Kse(e,t){if(!e.length)return e;let n=e.length,r=um;for(;n;){let s=bor(e[n-1],t,r);if(s.changes&&!s.changes.empty||s.effects.length){let i=e.slice(0,n);return i[n-1]=s,i}else t=s.mapped,n--,r=s.selectionsAfter}return r.length?[Df.selection(r)]:um}function bor(e,t,n){let r=TRt(e.selectionsAfter.length?e.selectionsAfter.map(l=>l.map(t)):um,n);if(!e.changes)return Df.selection(r);let s=e.changes.map(t),i=t.mapDesc(e.changes,!0),a=e.mapped?e.mapped.composeDesc(i):i;return new Df(s,hr.mapEffects(e.effects,t),a,e.startSelection.map(i),r)}const xor=/^(input\.type|delete)($|\.)/;class Iy{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 Iy(this.done,this.undone):this}addChanges(t,n,r,s,i){let a=this.done,l=a[a.length-1];return l&&l.changes&&!l.changes.empty&&t.changes&&(!r||xor.test(r))&&(!l.selectionsAfter.length&&n-this.prevTime<s.newGroupDelay&&s.joinToEvent(i,mor(l.changes,t.changes))||r=="input.type.compose")?a=Xq(a,a.length-1,s.minDepth,new Df(t.changes.compose(l.changes),TRt(hr.mapEffects(t.effects,l.changes),l.effects),l.mapped,l.startSelection,um)):a=Xq(a,a.length,s.minDepth,t),new Iy(a,um,n,r)}addSelection(t,n,r,s){let i=this.done.length?this.done[this.done.length-1].selectionsAfter:um;return i.length>0&&n-this.prevTime<s&&r==this.prevUserEvent&&r&&/^select($|\.)/.test(r)&&gor(i[i.length-1],t)?this:new Iy(jRt(this.done,t),this.undone,n,r)}addMapping(t){return new Iy(Kse(this.done,t),Kse(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 i=s[s.length-1],a=i.selectionsAfter[0]||(i.startSelection?i.startSelection.map(i.changes.invertedDesc,1):n.selection);if(r&&i.selectionsAfter.length)return n.update({selection:i.selectionsAfter[i.selectionsAfter.length-1],annotations:B0e.of({side:t,rest:yor(s),selection:a}),userEvent:t==0?"select.undo":"select.redo",scrollIntoView:!0});if(i.changes){let l=s.length==1?um:s.slice(0,s.length-1);return i.mapped&&(l=Kse(l,i.mapped)),n.update({changes:i.changes,selection:i.startSelection,effects:i.effects,annotations:B0e.of({side:t,rest:l,selection:a}),filter:!1,userEvent:t==0?"undo":"redo",scrollIntoView:!0})}else return null}}Iy.empty=new Iy(um,um);const wor=[{key:"Mod-z",run:ERt,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:U0e,preventDefault:!0},{linux:"Ctrl-Shift-z",run:U0e,preventDefault:!0},{key:"Mod-u",run:hor,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:por,preventDefault:!0}];function JA(e,t){return wt.create(e.ranges.map(t),e.mainIndex)}function Sv(e,t){return e.update({selection:t,scrollIntoView:!0,userEvent:"select"})}function kv({state:e,dispatch:t},n){let r=JA(e.selection,n);return r.eq(e.selection,!0)?!1:(t(Sv(e,r)),!0)}function CQ(e,t){return wt.cursor(t?e.to:e.from)}function NRt(e,t){return kv(e,n=>n.empty?e.moveByChar(n,t):CQ(n,t))}function ld(e){return e.textDirectionAt(e.state.selection.main.head)==Ta.LTR}const IRt=e=>NRt(e,!ld(e)),ARt=e=>NRt(e,ld(e));function RRt(e,t){return kv(e,n=>n.empty?e.moveByGroup(n,t):CQ(n,t))}const Sor=e=>RRt(e,!ld(e)),kor=e=>RRt(e,ld(e));function Oor(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 _Q(e,t,n){let r=ba(e).resolveInner(t.head),s=n?Rr.closedBy:Rr.openedBy;for(let c=t.head;;){let u=n?r.childAfter(c):r.childBefore(c);if(!u)break;Oor(e,u,s)?r=u:c=n?u.to:u.from}let i=r.type.prop(s),a,l;return i&&(a=n?Ny(e,r.from,1):Ny(e,r.to,-1))&&a.matched?l=n?a.end.to:a.end.from:l=n?r.to:r.from,wt.cursor(l,n?-1:1)}const Cor=e=>kv(e,t=>_Q(e.state,t,!ld(e))),_or=e=>kv(e,t=>_Q(e.state,t,ld(e)));function PRt(e,t){return kv(e,n=>{if(!n.empty)return CQ(n,t);let r=e.moveVertically(n,t);return r.head!=n.head?r:e.moveToLineBoundary(n,t)})}const $Rt=e=>PRt(e,!1),MRt=e=>PRt(e,!0);function DRt(e){let t=e.scrollDOM.clientHeight<e.scrollDOM.scrollHeight-2,n=0,r=0,s;if(t){for(let i of e.state.facet(Rt.scrollMargins)){let a=i(e);a?.top&&(n=Math.max(a?.top,n)),a?.bottom&&(r=Math.max(a?.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 LRt(e,t){let n=DRt(e),{state:r}=e,s=JA(r.selection,a=>a.empty?e.moveVertically(a,t,n.height):CQ(a,t));if(s.eq(r.selection))return!1;let i;if(n.selfScroll){let a=e.coordsAtPos(r.selection.main.head),l=e.scrollDOM.getBoundingClientRect(),c=l.top+n.marginTop,u=l.bottom-n.marginBottom;a&&a.top>c&&a.bottom<u&&(i=Rt.scrollIntoView(s.main.head,{y:"start",yMargin:a.top-c}))}return e.dispatch(Sv(r,s),{effects:i}),!0}const ZWe=e=>LRt(e,!1),V0e=e=>LRt(e,!0);function ek(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 i=/^\s*/.exec(e.state.sliceDoc(r.from,Math.min(r.from+100,r.to)))[0].length;i&&t.head!=r.from+i&&(s=wt.cursor(r.from+i))}return s}const Eor=e=>kv(e,t=>ek(e,t,!0)),Tor=e=>kv(e,t=>ek(e,t,!1)),jor=e=>kv(e,t=>ek(e,t,!ld(e))),Nor=e=>kv(e,t=>ek(e,t,ld(e))),Ior=e=>kv(e,t=>wt.cursor(e.lineBlockAt(t.head).from,1)),Aor=e=>kv(e,t=>wt.cursor(e.lineBlockAt(t.head).to,-1));function Ror(e,t,n){let r=!1,s=JA(e.selection,i=>{let a=Ny(e,i.head,-1)||Ny(e,i.head,1)||i.head>0&&Ny(e,i.head-1,1)||i.head<e.doc.length&&Ny(e,i.head+1,-1);if(!a||!a.end)return i;r=!0;let l=a.start.from==i.head?a.end.to:a.end.from;return wt.cursor(l)});return r?(t(Sv(e,s)),!0):!1}const Por=({state:e,dispatch:t})=>Ror(e,t);function Km(e,t,n){let r=JA(e.state.selection,s=>{s.undirectional&&s.head>=s.anchor!=t&&(s=wt.range(s.head,s.anchor));let i=n(s);return wt.range(s.anchor,i.head,i.goalColumn,i.bidiLevel||void 0,i.assoc)});return r.eq(e.state.selection)?!1:(e.dispatch(Sv(e.state,r)),!0)}function FRt(e,t){return Km(e,t,n=>e.moveByChar(n,t))}const zRt=e=>FRt(e,!ld(e)),BRt=e=>FRt(e,ld(e));function URt(e,t){return Km(e,t,n=>e.moveByGroup(n,t))}const $or=e=>URt(e,!ld(e)),Mor=e=>URt(e,ld(e)),Dor=e=>{let t=!ld(e);return Km(e,t,n=>_Q(e.state,n,t))},Lor=e=>{let t=ld(e);return Km(e,t,n=>_Q(e.state,n,t))};function VRt(e,t){return Km(e,t,n=>e.moveVertically(n,t))}const qRt=e=>VRt(e,!1),HRt=e=>VRt(e,!0);function WRt(e,t){return Km(e,t,n=>e.moveVertically(n,t,DRt(e).height))}const GWe=e=>WRt(e,!1),QWe=e=>WRt(e,!0),For=e=>Km(e,!0,t=>ek(e,t,!0)),zor=e=>Km(e,!1,t=>ek(e,t,!1)),Bor=e=>{let t=!ld(e);return Km(e,t,n=>ek(e,n,t))},Uor=e=>{let t=ld(e);return Km(e,t,n=>ek(e,n,t))},Vor=e=>Km(e,!1,t=>wt.cursor(e.lineBlockAt(t.head).from)),qor=e=>Km(e,!0,t=>wt.cursor(e.lineBlockAt(t.head).to)),KWe=({state:e,dispatch:t})=>(t(Sv(e,{anchor:0})),!0),YWe=({state:e,dispatch:t})=>(t(Sv(e,{anchor:e.doc.length})),!0),XWe=({state:e,dispatch:t})=>(t(Sv(e,{anchor:e.selection.main.anchor,head:0})),!0),JWe=({state:e,dispatch:t})=>(t(Sv(e,{anchor:e.selection.main.anchor,head:e.doc.length})),!0),Hor=({state:e,dispatch:t})=>(t(e.update({selection:{anchor:0,head:e.doc.length},userEvent:"select"})),!0),Wor=({state:e,dispatch:t})=>{let n=EQ(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},Zor=({state:e,dispatch:t})=>{let n=JA(e.selection,r=>{let s=ba(e),i=s.resolveStack(r.from,1);if(r.empty){let a=s.resolveStack(r.from,-1);a.node.from>=i.node.from&&a.node.to<=i.node.to&&(i=a)}for(let a=i;a;a=a.next){let{node:l}=a;if((l.from<r.from&&l.to>=r.to||l.to>r.to&&l.from<=r.from)&&a.next)return wt.range(l.to,l.from)}return r});return n.eq(e.selection)?!1:(t(Sv(e,n)),!0)};function ZRt(e,t){let{state:n}=e,r=n.selection,s=n.selection.ranges.slice();for(let i of n.selection.ranges){let a=n.doc.lineAt(i.head);if(t?a.to<e.state.doc.length:a.from>0)for(let l=i;;){let c=e.moveVertically(l,t);if(c.head<a.from||c.head>a.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(Sv(n,wt.create(s,s.length-1))),!0)}const Gor=e=>ZRt(e,!1),Qor=e=>ZRt(e,!0),Kor=({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(Sv(e,r)),!0):!1};function d5(e,t){if(e.state.readOnly)return!1;let n="delete.selection",{state:r}=e,s=r.changeByRange(i=>{let{from:a,to:l}=i;if(a==l){let c=t(i);c<a?(n="delete.backward",c=z9(e,c,!1)):c>a&&(n="delete.forward",c=z9(e,c,!0)),a=Math.min(a,c),l=Math.max(l,c)}else a=z9(e,a,!1),l=z9(e,l,!0);return a==l?{range:i}:{changes:{from:a,to:l},range:wt.cursor(a,a<i.head?-1:1)}});return s.changes.empty?!1:(e.dispatch(r.update(s,{scrollIntoView:!0,userEvent:n,effects:n=="delete.selection"?Rt.announce.of(r.phrase("Selection deleted")):void 0})),!0)}function z9(e,t,n){if(e instanceof Rt)for(let r of e.state.facet(Rt.atomicRanges).map(s=>s(e)))r.between(t,t,(s,i)=>{s<t&&i>t&&(t=n?i:s)});return t}const GRt=(e,t,n)=>d5(e,r=>{let s=r.from,{state:i}=e,a=i.doc.lineAt(s),l,c;if(n&&!t&&s>a.from&&s<a.from+200&&!/[^ \t]/.test(l=a.text.slice(0,s-a.from))){if(l[l.length-1]==" ")return s-1;let u=cv(l,i.tabSize),d=u%s_(i)||s_(i);for(let f=0;f<d&&l[l.length-1-f]==" ";f++)s--;c=s}else c=Rc(a.text,s-a.from,t,t)+a.from,c==s&&a.number!=(t?i.doc.lines:1)?c+=t?1:-1:!t&&/[\ufe00-\ufe0f]/.test(a.text.slice(c-a.from,s-a.from))&&(c=Rc(a.text,c-a.from,!1,!1)+a.from);return c}),q0e=e=>GRt(e,!1,!0),QRt=e=>GRt(e,!0,!1),KRt=(e,t)=>d5(e,n=>{let r=n.head,{state:s}=e,i=s.doc.lineAt(r),a=s.charCategorizer(r);for(let l=null;;){if(r==(t?i.to:i.from)){r==n.head&&i.number!=(t?s.doc.lines:1)&&(r+=t?1:-1);break}let c=Rc(i.text,r-i.from,t)+i.from,u=i.text.slice(Math.min(r,c)-i.from,Math.max(r,c)-i.from),d=a(u);if(l!=null&&d!=l)break;(u!=" "||r!=n.head)&&(l=d),r=c}return r}),YRt=e=>KRt(e,!1),Yor=e=>KRt(e,!0),Xor=e=>d5(e,t=>{let n=e.lineBlockAt(t.head).to;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),Jor=e=>d5(e,t=>{let n=e.moveToLineBoundary(t,!1).head;return t.head>n?n:Math.max(0,t.head-1)}),elr=e=>d5(e,t=>{let n=e.moveToLineBoundary(t,!0).head;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),tlr=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(r=>({changes:{from:r.from,to:r.to,insert:Js.of(["",""])},range:wt.cursor(r.from)}));return t(e.update(n,{scrollIntoView:!0,userEvent:"input"})),!0},nlr=({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,i=e.doc.lineAt(s),a=s==i.from?s-1:Rc(i.text,s-i.from,!1)+i.from,l=s==i.to?s+1:Rc(i.text,s-i.from,!0)+i.from;return{changes:{from:a,to:l,insert:e.doc.slice(s,l).append(e.doc.slice(a,s))},range:wt.cursor(l)}});return n.changes.empty?!1:(t(e.update(n,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function EQ(e){let t=[],n=-1;for(let r of e.selection.ranges){let s=e.doc.lineAt(r.from),i=e.doc.lineAt(r.to);if(!r.empty&&r.to==i.from&&(i=e.doc.lineAt(r.to-1)),n>=s.number){let a=t[t.length-1];a.to=i.to,a.ranges.push(r)}else t.push({from:s.from,to:i.to,ranges:[r]});n=i.number+1}return t}function XRt(e,t,n){if(e.readOnly)return!1;let r=[],s=[];for(let i of EQ(e)){if(n?i.to==e.doc.length:i.from==0)continue;let a=e.doc.lineAt(n?i.to+1:i.from-1),l=a.length+1;if(n){r.push({from:i.to,to:a.to},{from:i.from,insert:a.text+e.lineBreak});for(let c of i.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:a.from,to:i.from},{from:i.to,insert:e.lineBreak+a.text});for(let c of i.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 rlr=({state:e,dispatch:t})=>XRt(e,t,!1),slr=({state:e,dispatch:t})=>XRt(e,t,!0);function JRt(e,t,n){if(e.readOnly)return!1;let r=[];for(let i of EQ(e))n?r.push({from:i.from,insert:e.doc.slice(i.from,i.to)+e.lineBreak}):r.push({from:i.to,insert:e.lineBreak+e.doc.slice(i.from,i.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 ilr=({state:e,dispatch:t})=>JRt(e,t,!1),alr=({state:e,dispatch:t})=>JRt(e,t,!0),olr=e=>{if(e.state.readOnly)return!1;let{state:t}=e,n=t.changes(EQ(t).map(({from:s,to:i})=>(s>0?s--:i<t.doc.length&&i++,{from:s,to:i}))),r=JA(t.selection,s=>{let i;if(e.lineWrapping){let a=e.lineBlockAt(s.head),l=e.coordsAtPos(s.head,s.assoc||1);l&&(i=a.bottom+e.documentTop-l.bottom+e.defaultLineHeight/2)}return e.moveVertically(s,!0,i)}).map(n);return e.dispatch({changes:n,selection:r,scrollIntoView:!0,userEvent:"delete.line"}),!0};function llr(e,t){if(/\(\)|\[\]|\{\}/.test(e.sliceDoc(t-1,t+1)))return{from:t,to:t};let n=ba(e).resolveInner(t),r=n.childBefore(t),s=n.childAfter(t),i;return r&&s&&r.to<=t&&s.from>=t&&(i=r.type.prop(Rr.closedBy))&&i.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 eZe=ePt(!1),clr=ePt(!0);function ePt(e){return({state:t,dispatch:n})=>{if(t.readOnly)return!1;let r=t.changeByRange(s=>{let{from:i,to:a}=s,l=t.doc.lineAt(i),c=!e&&i==a&&llr(t,i);e&&(i=a=(a<=l.to?l:t.doc.lineAt(a)).to);let u=new xQ(t,{simulateBreak:i,simulateDoubleBreak:!!c}),d=vje(u,i);for(d==null&&(d=cv(/^\s*/.exec(t.doc.lineAt(i).text)[0],t.tabSize));a<l.to&&/\s/.test(l.text[a-l.from]);)a++;c?{from:i,to:a}=c:i>l.from&&i<l.from+100&&!/\S/.test(l.text.slice(0,i))&&(i=l.from);let f=["",NL(t,d)];return c&&f.push(NL(t,u.lineIndent(l.from,-1))),{changes:{from:i,to:a,insert:Js.of(f)},range:wt.cursor(i+1+f[1].length)}});return n(t.update(r,{scrollIntoView:!0,userEvent:"input"})),!0}}function Qje(e,t){let n=-1;return e.changeByRange(r=>{let s=[];for(let a=r.from;a<=r.to;){let l=e.doc.lineAt(a);l.number>n&&(r.empty||r.to>l.from)&&(t(l,s,r),n=l.number),a=l.to+1}let i=e.changes(s);return{changes:s,range:wt.range(i.mapPos(r.anchor,1),i.mapPos(r.head,1))}})}const ulr=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=Object.create(null),r=new xQ(e,{overrideIndentation:i=>{let a=n[i];return a??-1}}),s=Qje(e,(i,a,l)=>{let c=vje(r,i.from);if(c==null)return;/\S/.test(i.text)||(c=0);let u=/^\s*/.exec(i.text)[0],d=NL(e,c);(u!=d||l.from<i.from+u.length)&&(n[i.from]=c,a.push({from:i.from,to:i.from+u.length,insert:d}))});return s.changes.empty||t(e.update(s,{userEvent:"indent"})),!0},tPt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(Qje(e,(n,r)=>{r.push({from:n.from,insert:e.facet(KA)})}),{userEvent:"input.indent"})),!0),nPt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(Qje(e,(n,r)=>{let s=/^\s*/.exec(n.text)[0];if(!s)return;let i=cv(s,e.tabSize),a=0,l=NL(e,Math.max(0,i-s_(e)));for(;a<s.length&&a<l.length&&s.charCodeAt(a)==l.charCodeAt(a);)a++;r.push({from:n.from+a,to:n.from+s.length,insert:l.slice(a)})}),{userEvent:"delete.dedent"})),!0),dlr=e=>(e.setTabFocusMode(),!0),flr=[{key:"Ctrl-b",run:IRt,shift:zRt,preventDefault:!0},{key:"Ctrl-f",run:ARt,shift:BRt},{key:"Ctrl-p",run:$Rt,shift:qRt},{key:"Ctrl-n",run:MRt,shift:HRt},{key:"Ctrl-a",run:Ior,shift:Vor},{key:"Ctrl-e",run:Aor,shift:qor},{key:"Ctrl-d",run:QRt},{key:"Ctrl-h",run:q0e},{key:"Ctrl-k",run:Xor},{key:"Ctrl-Alt-h",run:YRt},{key:"Ctrl-o",run:tlr},{key:"Ctrl-t",run:nlr},{key:"Ctrl-v",run:V0e}],hlr=[{key:"ArrowLeft",run:IRt,shift:zRt,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:Sor,shift:$or,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:jor,shift:Bor,preventDefault:!0},{key:"ArrowRight",run:ARt,shift:BRt,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:kor,shift:Mor,preventDefault:!0},{mac:"Cmd-ArrowRight",run:Nor,shift:Uor,preventDefault:!0},{key:"ArrowUp",run:$Rt,shift:qRt,preventDefault:!0},{mac:"Cmd-ArrowUp",run:KWe,shift:XWe},{mac:"Ctrl-ArrowUp",run:ZWe,shift:GWe},{key:"ArrowDown",run:MRt,shift:HRt,preventDefault:!0},{mac:"Cmd-ArrowDown",run:YWe,shift:JWe},{mac:"Ctrl-ArrowDown",run:V0e,shift:QWe},{key:"PageUp",run:ZWe,shift:GWe},{key:"PageDown",run:V0e,shift:QWe},{key:"Home",run:Tor,shift:zor,preventDefault:!0},{key:"Mod-Home",run:KWe,shift:XWe},{key:"End",run:Eor,shift:For,preventDefault:!0},{key:"Mod-End",run:YWe,shift:JWe},{key:"Enter",run:eZe,shift:eZe},{key:"Mod-a",run:Hor},{key:"Backspace",run:q0e,shift:q0e,preventDefault:!0},{key:"Delete",run:QRt,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:YRt,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:Yor,preventDefault:!0},{mac:"Mod-Backspace",run:Jor,preventDefault:!0},{mac:"Mod-Delete",run:elr,preventDefault:!0}].concat(flr.map(e=>({mac:e.key,run:e.run,shift:e.shift}))),plr=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:Cor,shift:Dor},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:_or,shift:Lor},{key:"Alt-ArrowUp",run:rlr},{key:"Shift-Alt-ArrowUp",run:ilr},{key:"Alt-ArrowDown",run:slr},{key:"Shift-Alt-ArrowDown",run:alr},{key:"Mod-Alt-ArrowUp",run:Gor},{key:"Mod-Alt-ArrowDown",run:Qor},{key:"Escape",run:Kor},{key:"Mod-Enter",run:clr},{key:"Alt-l",mac:"Ctrl-l",run:Wor},{key:"Mod-i",run:Zor,preventDefault:!0},{key:"Mod-[",run:nPt},{key:"Mod-]",run:tPt},{key:"Mod-Alt-\\",run:ulr},{key:"Shift-Mod-k",run:olr},{key:"Shift-Mod-\\",run:Por},{key:"Mod-/",run:nor},{key:"Alt-A",run:sor},{key:"Ctrl-m",mac:"Shift-Alt-m",run:dlr}].concat(hlr),mlr={key:"Tab",run:tPt,shift:nPt},tZe=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class S0{constructor(t,n,r=0,s=t.length,i,a){this.test=a,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=i?l=>i(tZe(l)):tZe,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 Tf(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=XTe(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=by(t);let s=this.normalize(n);if(s.length)for(let i=0,a=r,l=!0;;i++){let c=s.charCodeAt(i),u=this.match(c,a,l,this.bufferPos+this.bufferStart,i==s.length-1);if(u)return this.value=u,this;if(i==s.length-1)break;l&&i<n.length&&n.charCodeAt(i)==c?a++:l=!1}}}match(t,n,r,s,i){let a=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?a={from:c.from,to:s,precise:i&&c.precise}:(c.index++,u=!0)),u?l++:this.matches.splice(l,1)}return this.query.charCodeAt(0)==t&&(this.query.length==1?a={from:n,to:s,precise:r&&i}:this.matches.push({from:n,index:1,precise:r})),a&&this.test&&!this.test(a.from,a.to,this.buffer,this.bufferStart)&&(a=null),a}}typeof Symbol<"u"&&(S0.prototype[Symbol.iterator]=function(){return this});const rPt={from:-1,to:-1,match:/.*/.exec(""),precise:!0},Kje="gm"+(/x/.unicode==null?"":"u");class sPt{constructor(t,n,r,s=0,i=t.length){if(this.text=t,this.to=i,this.curLine="",this.done=!1,this.value=rPt,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new iPt(t,n,r,s,i);this.re=new RegExp(n,Kje+(r?.ignoreCase?"i":"")),this.test=r?.test,this.iter=t.iter();let a=t.lineAt(s);this.curLineStart=a.from,this.matchPos=Jq(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=Jq(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 Yse=new WeakMap;class xN{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let s=Yse.get(t);if(!s||s.from>=r||s.to<=n){let l=new xN(n,t.sliceString(n,r));return Yse.set(t,l),l}if(s.from==n&&s.to==r)return s;let{text:i,from:a}=s;return a>n&&(i=t.sliceString(n,a)+i,a=n),s.to<r&&(i+=t.sliceString(s.to,r)),Yse.set(t,new xN(a,i)),new xN(n,i.slice(n-a,r-a))}}class iPt{constructor(t,n,r,s,i){this.text=t,this.to=i,this.done=!1,this.value=rPt,this.matchPos=Jq(t,s),this.re=new RegExp(n,Kje+(r?.ignoreCase?"i":"")),this.test=r?.test,this.flat=xN.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=Jq(this.text,s+(r==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=xN.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(sPt.prototype[Symbol.iterator]=iPt.prototype[Symbol.iterator]=function(){return this});function glr(e){try{return new RegExp(e,Kje),!0}catch{return!1}}function Jq(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 vlr=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:s}=Ytr(e,{label:t.phrase("Go to line"),input:{type:"text",name:"line",value:n},focus:!0,submitLabel:t.phrase("go")});return s.then(i=>{let a=i&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(i.elements.line.value);if(!a){e.dispatch({effects:r});return}let l=t.doc.lineAt(t.selection.main.head),[,c,u,d,f]=a,h=d?+d.slice(1):0,p=u?+u:l.number;if(u&&f){let y=p/100;c&&(y=y*(c=="-"?-1:1)+l.number/t.doc.lines),p=Math.round(t.doc.lines*y)}else u&&c&&(p=p*(c=="-"?-1:1)+l.number);let m=t.doc.line(Math.max(1,Math.min(t.doc.lines,p))),v=wt.cursor(m.from+Math.max(0,Math.min(h,m.length)));e.dispatch({effects:[r,Rt.scrollIntoView(v.from,{y:"center"})],selection:v})}),!0},ylr={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},blr=wn.define({combine(e){return _b(e,ylr,{highlightWordAroundCursor:(t,n)=>t||n,minSelectionLength:Math.min,maxMatches:Math.min})}});function xlr(e){return[Clr,Olr]}const wlr=Nn.mark({class:"cm-selectionMatch"}),Slr=Nn.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function nZe(e,t,n,r){return(n==0||e(t.sliceDoc(n-1,n))!=Oo.Word)&&(r==t.doc.length||e(t.sliceDoc(r,r+1))!=Oo.Word)}function klr(e,t,n,r){return e(t.sliceDoc(n,n+1))==Oo.Word&&e(t.sliceDoc(r-1,r))==Oo.Word}const Olr=To.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(blr),{state:n}=e,r=n.selection;if(r.ranges.length>1)return Nn.none;let s=r.main,i,a=null;if(s.empty){if(!t.highlightWordAroundCursor)return Nn.none;let c=n.wordAt(s.head);if(!c)return Nn.none;a=n.charCategorizer(s.head),i=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(i=n.sliceDoc(s.from,s.to),a=n.charCategorizer(s.head),!(nZe(a,n,s.from,s.to)&&klr(a,n,s.from,s.to)))return Nn.none}else if(i=n.sliceDoc(s.from,s.to),!i)return Nn.none}let l=[];for(let c of e.visibleRanges){let u=new S0(n.doc,i,c.from,c.to);for(;!u.next().done;){let{from:d,to:f}=u.value;if((!a||nZe(a,n,d,f))&&(s.empty&&d<=s.from&&f>=s.to?l.push(Slr.range(d,f)):(d>=s.to||f<=s.from)&&l.push(wlr.range(d,f)),l.length>t.maxMatches))return Nn.none}}return Nn.set(l)}},{decorations:e=>e.decorations}),Clr=Rt.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),_lr=({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 Elr(e,t){let{main:n,ranges:r}=e.selection,s=e.wordAt(n.head),i=s&&s.from==n.from&&s.to==n.to;for(let a=!1,l=new S0(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(a)return null;l=new S0(e.doc,t,0,Math.max(0,r[r.length-1].from-1)),a=!0}else{if(a&&r.some(c=>c.from==l.value.from))continue;if(i){let c=e.wordAt(l.value.from);if(!c||c.from!=l.value.from||c.to!=l.value.to)continue}return l.value}}const Tlr=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(i=>i.from===i.to))return _lr({state:e,dispatch:t});let r=e.sliceDoc(n[0].from,n[0].to);if(e.selection.ranges.some(i=>e.sliceDoc(i.from,i.to)!=r))return!1;let s=Elr(e,r);return s?(t(e.update({selection:e.selection.addRange(wt.range(s.from,s.to),!1),effects:Rt.scrollIntoView(s.to)})),!0):!1},eR=wn.define({combine(e){return _b(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new Ulr(t),scrollToMatch:t=>Rt.scrollIntoView(t)})}});class aPt{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||glr(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"?`
231
- `: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 Plr(this):new Ilr(this)}getCursor(t,n=0,r){let s=t.doc?t:gs.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?pj(this,s,n,r):hj(this,s,n,r)}}class oPt{constructor(t){this.spec=t}}function jlr(e,t,n){return(r,s,i,a)=>{if(n&&!n(r,s,i,a))return!1;let l=r>=a&&s<=a+i.length?i.slice(r-a,s-a):t.doc.sliceString(r,s);return e(l,t,r,s)}}function hj(e,t,n,r){let s;return e.wholeWord&&(s=Nlr(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=jlr(e.test,t,s)),new S0(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:i=>i.toLowerCase(),s)}function Nlr(e,t){return(n,r,s,i)=>((i>n||i+s.length<r)&&(i=Math.max(0,n-2),s=e.sliceString(i,Math.min(e.length,r+2))),(t(eH(s,n-i))!=Oo.Word||t(tH(s,n-i))!=Oo.Word)&&(t(tH(s,r-i))!=Oo.Word||t(eH(s,r-i))!=Oo.Word))}class Ilr extends oPt{constructor(t){super(t)}nextMatch(t,n,r){let s=hj(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let i=Math.min(t.doc.length,n+this.spec.unquoted.length);s=hj(this.spec,t,0,i).nextOverlapping()}return s.done||s.value.from==n&&s.value.to==r?null:s.value}prevMatchInRange(t,n,r){for(let s=r;;){let i=Math.max(n,s-1e4-this.spec.unquoted.length),a=hj(this.spec,t,i,s),l=null;for(;!a.nextOverlapping().done;)l=a.value;if(l)return l;if(i==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=hj(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 i=hj(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!i.next().done;)s(i.value.from,i.value.to)}}function Alr(e,t,n){return(r,s,i)=>(!n||n(r,s,i))&&e(i[0],t,r,s)}function pj(e,t,n,r){let s;return e.wholeWord&&(s=Rlr(t.charCategorizer(t.selection.main.head))),e.test&&(s=Alr(e.test,t,s)),new sPt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function eH(e,t){return e.slice(Rc(e,t,!1),t)}function tH(e,t){return e.slice(t,Rc(e,t))}function Rlr(e){return(t,n,r)=>!r[0].length||(e(eH(r.input,r.index))!=Oo.Word||e(tH(r.input,r.index))!=Oo.Word)&&(e(tH(r.input,r.index+r[0].length))!=Oo.Word||e(eH(r.input,r.index+r[0].length))!=Oo.Word)}class Plr extends oPt{nextMatch(t,n,r){let s=pj(this.spec,t,r,t.doc.length).next();return s.done&&(s=pj(this.spec,t,0,n).next()),s.done?null:s.value}prevMatchInRange(t,n,r){for(let s=1;;s++){let i=Math.max(n,r-s*1e4),a=pj(this.spec,t,i,r),l=null;for(;!a.next().done;)l=a.value;if(l&&(i==n||l.from>i+10))return l;if(i==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 i=+r.slice(0,s);if(i>0&&i<t.match.length)return t.match[i]+r.slice(s)}return n})}matchAll(t,n){let r=pj(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 i=pj(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!i.next().done;)s(i.value.from,i.value.to)}}const FL=hr.define(),Yje=hr.define(),zS=Ol.define({create(e){return new Xse(H0e(e).create(),null)},update(e,t){for(let n of t.effects)n.is(FL)?e=new Xse(n.value.create(),e.panel):n.is(Yje)&&(e=new Xse(e.query,n.value?Xje:null));return e},provide:e=>jL.from(e,t=>t.panel)});class Xse{constructor(t,n){this.query=t,this.panel=n}}const $lr=Nn.mark({class:"cm-searchMatch"}),Mlr=Nn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),Dlr=To.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(zS))}update(e){let t=e.state.field(zS);(t!=e.startState.field(zS)||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 rd;for(let s=0,i=n.visibleRanges,a=i.length;s<a;s++){let{from:l,to:c}=i[s];for(;s<a-1&&c>i[s+1].from-500;)c=i[++s].to;e.highlight(n.state,l,c,(u,d)=>{let f=n.state.selection.ranges.some(h=>h.from==u&&h.to==d);r.add(u,d,f?Mlr:$lr)})}return r.finish()}},{decorations:e=>e.decorations});function f5(e){return t=>{let n=t.state.field(zS,!1);return n&&n.query.spec.valid?e(t,n):uPt(t)}}const nH=f5((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),i=e.state.facet(eR);return e.dispatch({selection:s,effects:[Jje(e,r),i.scrollToMatch(s.main,e)],userEvent:"select.search"}),cPt(e),!0}),rH=f5((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let i=wt.single(s.from,s.to),a=e.state.facet(eR);return e.dispatch({selection:i,effects:[Jje(e,s),a.scrollToMatch(i.main,e)],userEvent:"select.search"}),cPt(e),!0}),Llr=f5((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)}),Flr=({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,i=[],a=0;for(let l=new S0(e.doc,e.sliceDoc(r,s));!l.next().done;){if(i.length>1e3)return!1;l.value.from==r&&(a=i.length),i.push(wt.range(l.value.from,l.value.to))}return t(e.update({selection:wt.create(i,a),userEvent:"select.search.matches"})),!0},rZe=f5((e,{query:t})=>{let{state:n}=e,{from:r,to:s}=n.selection.main;if(n.readOnly)return!1;let i=t.nextMatch(n,r,r);if(!i)return!1;let a=i,l=[],c,u,d=[];a.precise?a.from==r&&a.to==s&&(u=n.toText(t.getReplacement(a)),l.push({from:a.from,to:a.to,insert:u}),a=t.nextMatch(n,a.from,a.to),d.push(Rt.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+"."))):a=t.nextMatch(n,a.from,a.to);let f=e.state.changes(l);return a&&(c=wt.single(a.from,a.to).map(f),d.push(Jje(e,a)),d.push(n.facet(eR).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),zlr=f5((e,{query:t})=>{if(e.state.readOnly)return!1;let n=[];for(let s of t.matchAll(e.state,1e9)){let{from:i,to:a,precise:l}=s;l&&n.push({from:i,to:a,insert:t.getReplacement(s)})}if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:Rt.announce.of(r),userEvent:"input.replace.all"}),!0});function Xje(e){return e.state.facet(eR).createPanel(e)}function H0e(e,t){var n,r,s,i,a;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(eR);return new aPt({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:(i=t?.regexp)!==null&&i!==void 0?i:u.regexp,wholeWord:(a=t?.wholeWord)!==null&&a!==void 0?a:u.wholeWord})}function lPt(e){let t=mje(e,Xje);return t&&t.dom.querySelector("[main-field]")}function cPt(e){let t=lPt(e);t&&t==e.root.activeElement&&t.select()}const uPt=e=>{let t=e.state.field(zS,!1);if(t&&t.panel){let n=lPt(e);if(n&&n!=e.root.activeElement){let r=H0e(e.state,t.query.spec);r.valid&&e.dispatch({effects:FL.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[Yje.of(!0),t?FL.of(H0e(e.state,t.query.spec)):hr.appendConfig.of(qlr)]});return!0},dPt=e=>{let t=e.state.field(zS,!1);if(!t||!t.panel)return!1;let n=mje(e,Xje);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:Yje.of(!1)}),!0},Blr=[{key:"Mod-f",run:uPt,scope:"editor search-panel"},{key:"F3",run:nH,shift:rH,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:nH,shift:rH,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:dPt,scope:"editor search-panel"},{key:"Mod-Shift-l",run:Flr},{key:"Mod-Alt-g",run:vlr},{key:"Mod-d",run:Tlr,preventDefault:!0}];class Ulr{constructor(t){this.view=t;let n=this.query=t.state.field(zS).query.spec;this.commit=this.commit.bind(this),this.searchField=pa("input",{value:n.search,placeholder:Oh(t,"Find"),"aria-label":Oh(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=pa("input",{value:n.replace,placeholder:Oh(t,"Replace"),"aria-label":Oh(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=pa("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=pa("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=pa("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,i,a){return pa("button",{class:"cm-button",name:s,onclick:i,type:"button"},a)}this.dom=pa("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>nH(t),[Oh(t,"next")]),r("prev",()=>rH(t),[Oh(t,"previous")]),r("select",()=>Llr(t),[Oh(t,"all")]),pa("label",null,[this.caseField,Oh(t,"match case")]),pa("label",null,[this.reField,Oh(t,"regexp")]),pa("label",null,[this.wordField,Oh(t,"by word")]),...t.state.readOnly?[]:[pa("br"),this.replaceField,r("replace",()=>rZe(t),[Oh(t,"replace")]),r("replaceAll",()=>zlr(t),[Oh(t,"replace all")])],pa("button",{name:"close",onclick:()=>dPt(t),"aria-label":Oh(t,"close"),type:"button"},["×"])])}commit(){let t=new aPt({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:FL.of(t)}))}keydown(t){otr(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?rH:nH)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),rZe(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(FL)&&!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(eR).top}}function Oh(e,t){return e.state.phrase(t)}const B9=30,U9=/[\s\.,:;?!]/;function Jje(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),s=e.state.doc.lineAt(n).to,i=Math.max(r.from,t-B9),a=Math.min(s,n+B9),l=e.state.sliceDoc(i,a);if(i!=r.from){for(let c=0;c<B9;c++)if(!U9.test(l[c+1])&&U9.test(l[c])){l=l.slice(c);break}}if(a!=s){for(let c=l.length-1;c>l.length-B9;c--)if(!U9.test(l[c-1])&&U9.test(l[c])){l=l.slice(0,c);break}}return Rt.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const Vlr=Rt.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),qlr=[zS,bp.low(Dlr),Vlr];class sZe{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class TO{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(zL).markerFilter;s&&(t=s(t,r));let i=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),a=new rd,l=[],c=0;for(let d=0;;){let f=d==i.length?null:i[d];if(!f&&!l.length)break;let h,p;for(l.length?(h=c,p=l.reduce((v,y)=>Math.min(v,y.to),f&&f.from>h?f.from:1e8)):(h=f.from,p=f.to,l.push(f),d++);d<i.length;){let v=i[d];if(v.from==h&&(v.to>v.from||v.to==h))l.push(v),d++,p=Math.min(v.to,p);else{p=Math.min(v.from,p);break}}let m=rcr(l);if(l.some(v=>v.from==v.to||v.from==v.to-1&&r.doc.lineAt(v.from).to==v.from))a.add(h,h,Nn.widget({widget:new Jlr(m),diagnostics:l.slice()}));else{let v=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");a.add(h,p,Nn.mark({class:"cm-lintRange cm-lintRange-"+m+v,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>p)}))}c=p;for(let v=0;v<l.length;v++)l[v].to<=c&&l.splice(v--,1)}let u=a.finish();return new TO(u,n,CI(u))}}function CI(e,t=null,n=0){let r=null;return e.between(n,1e9,(s,i,{spec:a})=>{if(!(t&&a.diagnostics.indexOf(t)<0))if(!r)r=new sZe(s,i,t||a.diagnostics[0]);else{if(a.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new sZe(r.from,i,r.diagnostic)}}),r}function Hlr(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(zL).hideOn(e,n,r);if(s!=null)return s;let i=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(a=>a.is(fPt))||e.changes.touchesRange(i.from,Math.max(i.to,r)))}function Wlr(e,t){return e.field(Qh,!1)?t:t.concat(hr.appendConfig.of(scr))}const fPt=hr.define(),eNe=hr.define(),hPt=hr.define(),Qh=Ol.define({create(){return new TO(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 i=t.changes.mapPos(e.selected.from,1);r=CI(n,e.selected.diagnostic,i)||CI(n,null,i)}!n.size&&s&&t.state.facet(zL).autoPanel&&(s=null),e=new TO(n,s,r)}for(let n of t.effects)if(n.is(fPt)){let r=t.state.facet(zL).autoPanel?n.value.length?BL.open:null:e.panel;e=TO.init(n.value,r,t.state)}else n.is(eNe)?e=new TO(e.diagnostics,n.value?BL.open:null,e.selected):n.is(hPt)&&(e=new TO(e.diagnostics,e.panel,n.value));return e},provide:e=>[jL.from(e,t=>t.panel),Rt.decorations.from(e,t=>t.diagnostics)]}),Zlr=Nn.mark({class:"cm-lintRange cm-lintRange-active"});function Glr(e,t,n){let{diagnostics:r}=e.state.field(Qh),s,i=-1,a=-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,i=c,a=u,!1});let l=e.state.facet(zL).tooltipFilter;return s&&l&&(s=l(s,e.state)),s?{pos:i,end:a,above:e.state.doc.lineAt(i).to<a,create(){return{dom:Qlr(e,s)}}}:null}function Qlr(e,t){return pa("ul",{class:"cm-tooltip-lint"},t.map(n=>mPt(e,n,!1)))}const Klr=e=>{let t=e.state.field(Qh,!1);(!t||!t.panel)&&e.dispatch({effects:Wlr(e.state,[eNe.of(!0)])});let n=mje(e,BL.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},iZe=e=>{let t=e.state.field(Qh,!1);return!t||!t.panel?!1:(e.dispatch({effects:eNe.of(!1)}),!0)},Ylr=e=>{let t=e.state.field(Qh,!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)},Xlr=[{key:"Mod-Shift-m",run:Klr,preventDefault:!0},{key:"F8",run:Ylr}],zL=wn.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),..._b(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:aZe,tooltipFilter:aZe,needsRefresh:(t,n)=>t?n?r=>t(r)||n(r):t:n,hideOn:(t,n)=>t?n?(r,s,i)=>t(r,s,i)||n(r,s,i):t:n,autoPanel:(t,n)=>t||n})}}});function aZe(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function pPt(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(i=>i.toLowerCase()==s.toLowerCase())){t.push(s);continue e}}t.push("")}return t}function mPt(e,t,n){var r;let s=n?pPt(t.actions):[];return pa("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},pa("span",{class:"cm-diagnosticText"},t.renderMessage?t.renderMessage(e):t.message),(r=t.actions)===null||r===void 0?void 0:r.map((i,a)=>{let l=!1,c=p=>{if(p.preventDefault(),l)return;l=!0;let m=CI(e.state.field(Qh).diagnostics,t);m&&i.apply(e,m.from,m.to)},{name:u}=i,d=s[a]?u.indexOf(s[a]):-1,f=d<0?u:[u.slice(0,d),pa("u",u.slice(d,d+1)),u.slice(d+1)],h=i.markClass?" "+i.markClass:"";return pa("button",{type:"button",class:"cm-diagnosticAction"+h,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[a]})"`}.`},f)}),t.source&&pa("div",{class:"cm-diagnosticSource"},t.source))}class Jlr extends xp{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return pa("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class oZe{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=mPt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class BL{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)iZe(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:i}=this.items[this.selectedIndex],a=pPt(i.actions);for(let l=0;l<a.length;l++)if(a[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=CI(this.view.state.field(Qh).diagnostics,i);c&&i.actions[l].apply(t,c.from,c.to)}}else return;s.preventDefault()},r=s=>{for(let i=0;i<this.items.length;i++)this.items[i].dom.contains(s.target)&&this.moveSelection(i)};this.list=pa("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=pa("div",{class:"cm-panel-lint"},this.list,pa("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>iZe(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Qh).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(Qh),r=0,s=!1,i=null,a=new Set;for(t.between(0,this.view.state.doc.length,(l,c,{spec:u})=>{for(let d of u.diagnostics){if(a.has(d))continue;a.add(d);let f=-1,h;for(let p=r;p<this.items.length;p++)if(this.items[p].diagnostic==d){f=p;break}f<0?(h=new oZe(this.view,d),this.items.splice(r,0,h),s=!0):(h=this.items[f],f>r&&(this.items.splice(r,f-r),s=!0)),n&&h.diagnostic==n.diagnostic?h.dom.hasAttribute("aria-selected")||(h.dom.setAttribute("aria-selected","true"),i=h):h.dom.hasAttribute("aria-selected")&&h.dom.removeAttribute("aria-selected"),r++}});r<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0);)s=!0,this.items.pop();this.items.length==0&&(this.items.push(new oZe(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),s=!0),i?(this.list.setAttribute("aria-activedescendant",i.id),this.view.requestMeasure({key:this,read:()=>({sel:i.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(Qh),r=CI(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:hPt.of(r)})}static open(t){return new BL(t)}}function ecr(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 V9(e){return ecr(`<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 tcr=Rt.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:V9("#d11")},".cm-lintRange-warning":{backgroundImage:V9("orange")},".cm-lintRange-info":{backgroundImage:V9("#999")},".cm-lintRange-hint":{backgroundImage:V9("#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 ncr(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function rcr(e){let t="hint",n=1;for(let r of e){let s=ncr(r.severity);s>n&&(n=s,t=r.severity)}return t}const scr=[Qh,Rt.decorations.compute([Qh],e=>{let{selected:t,panel:n}=e.field(Qh);return!t||!n||t.from==t.to?Nn.none:Nn.set([Zlr.range(t.from,t.to)])}),Qtr(Glr,{hideOn:Hlr}),tcr];var lZe=function(t){t===void 0&&(t={});var n=t,r=n.crosshairCursor,s=r===void 0?!1:r,i=[];t.closeBracketsKeymap!==!1&&(i=i.concat(Hrr)),t.defaultKeymap!==!1&&(i=i.concat(plr)),t.searchKeymap!==!1&&(i=i.concat(Blr)),t.historyKeymap!==!1&&(i=i.concat(wor)),t.foldKeymap!==!1&&(i=i.concat(Nnr)),t.completionKeymap!==!1&&(i=i.concat(lAt)),t.lintKeymap!==!1&&(i=i.concat(Xlr));var a=[];return t.lineNumbers!==!1&&a.push(jIt()),t.highlightActiveLineGutter!==!1&&a.push(cnr()),t.highlightSpecialChars!==!1&&a.push(ktr()),t.history!==!1&&a.push(dor()),t.foldGutter!==!1&&a.push(Pnr()),t.drawSelection!==!1&&a.push(htr()),t.dropCursor!==!1&&a.push(ytr()),t.allowMultipleSelections!==!1&&a.push(gs.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&a.push(Snr()),t.syntaxHighlighting!==!1&&a.push(J1(Lnr,{fallback:!0})),t.bracketMatching!==!1&&a.push(Hnr()),t.closeBrackets!==!1&&a.push(Brr()),t.autocompletion!==!1&&a.push(oAt()),t.rectangularSelection!==!1&&a.push(Dtr()),s!==!1&&a.push(ztr()),t.highlightActiveLine!==!1&&a.push(jtr()),t.highlightSelectionMatches!==!1&&a.push(xlr()),t.tabSize&&typeof t.tabSize=="number"&&a.push(KA.of(" ".repeat(t.tabSize))),a.concat([QA.of(i.flat())]).filter(Boolean)};const icr="#e5c07b",cZe="#e06c75",acr="#56b6c2",ocr="#ffffff",N7="#abb2bf",W0e="#7d8799",lcr="#61afef",ccr="#98c379",uZe="#d19a66",ucr="#c678dd",dcr="#21252b",dZe="#2c313a",fZe="#282c34",Jse="#353a42",fcr="#3E4451",hZe="#528bff",hcr=Rt.theme({"&":{color:N7,backgroundColor:fZe},".cm-content":{caretColor:hZe},".cm-cursor, .cm-dropCursor":{borderLeftColor:hZe},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:fcr},".cm-panels":{backgroundColor:dcr,color:N7},".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:fZe,color:W0e,border:"none"},".cm-activeLineGutter":{backgroundColor:dZe},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:Jse},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:Jse,borderBottomColor:Jse},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:dZe,color:N7}}},{dark:!0}),pcr=wv.define([{tag:oe.keyword,color:ucr},{tag:[oe.name,oe.deleted,oe.character,oe.propertyName,oe.macroName],color:cZe},{tag:[oe.function(oe.variableName),oe.labelName],color:lcr},{tag:[oe.color,oe.constant(oe.name),oe.standard(oe.name)],color:uZe},{tag:[oe.definition(oe.name),oe.separator],color:N7},{tag:[oe.typeName,oe.className,oe.number,oe.changed,oe.annotation,oe.modifier,oe.self,oe.namespace],color:icr},{tag:[oe.operator,oe.operatorKeyword,oe.url,oe.escape,oe.regexp,oe.link,oe.special(oe.string)],color:acr},{tag:[oe.meta,oe.comment],color:W0e},{tag:oe.strong,fontWeight:"bold"},{tag:oe.emphasis,fontStyle:"italic"},{tag:oe.strikethrough,textDecoration:"line-through"},{tag:oe.link,color:W0e,textDecoration:"underline"},{tag:oe.heading,fontWeight:"bold",color:cZe},{tag:[oe.atom,oe.bool,oe.special(oe.variableName)],color:uZe},{tag:[oe.processingInstruction,oe.string,oe.inserted],color:ccr},{tag:oe.invalid,color:ocr}]),mcr=[hcr,J1(pcr)];var gcr=Rt.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),vcr=function(t){t===void 0&&(t={});var n=t,r=n.indentWithTab,s=r===void 0?!0:r,i=n.editable,a=i===void 0?!0:i,l=n.readOnly,c=l===void 0?!1:l,u=n.theme,d=u===void 0?"light":u,f=n.placeholder,h=f===void 0?"":f,p=n.basicSetup,m=p===void 0?!0:p,v=[];switch(s&&v.unshift(QA.of([mlr])),m&&(typeof m=="boolean"?v.unshift(lZe()):v.unshift(lZe(m))),h&&v.unshift(Rtr(h)),d){case"light":v.push(gcr);break;case"dark":v.push(mcr);break;case"none":break;default:v.push(d);break}return a===!1&&v.push(Rt.editable.of(!1)),c&&v.push(gs.readOnly.of(!0)),[...v]},ycr=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 bcr{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 pZe{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 eie=null,xcr=()=>typeof window>"u"?new pZe:(eie||(eie=new pZe),eie),wcr=Rt.theme({"& .cm-scroller":{height:"100% !important"}}),mZe=null,tie=null;function Scr(e,t,n,r,s,i){if(!e&&!t&&!n&&!r&&!s&&!i)return null;var a=JSON.stringify({height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:i});return a===mZe||(mZe=a,tie=Rt.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:i}})),tie}var gZe=Cb.define(),kcr=200,Ocr=[];function Ccr(e){var t=e.value,n=e.selection,r=e.onChange,s=e.onStatistics,i=e.onCreateEditor,a=e.onUpdate,l=e.extensions,c=l===void 0?Ocr:l,u=e.autoFocus,d=e.theme,f=d===void 0?"light":d,h=e.height,p=h===void 0?null:h,m=e.minHeight,v=m===void 0?null:m,y=e.maxHeight,b=y===void 0?null:y,x=e.width,w=x===void 0?null:x,k=e.minWidth,_=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,P=e.readOnly,L=P===void 0?!1:P,M=e.indentWithTab,V=M===void 0?!0:M,q=e.basicSetup,H=q===void 0?!0:q,B=e.root,W=e.initialState,z=g.useState(),G=z[0],F=z[1],R=g.useState(),D=R[0],U=R[1],Q=g.useState(),ee=Q[0],J=Q[1],te=g.useState(()=>({current:null}))[0],re=g.useState(()=>({current:null}))[0],ce=Scr(p,v,b,w,_,T),X=Rt.updateListener.of(le=>{if(le.docChanged&&typeof r=="function"&&!le.transactions.some(Se=>Se.annotation(gZe))){te.current?te.current.reset():(te.current=new bcr(()=>{if(re.current){var Se=re.current;re.current=null,Se()}te.current=null},kcr),xcr().add(te.current));var he=le.state.doc,pe=he.toString();r(pe,le)}s&&s(ycr(le))}),ne=vcr({theme:f,editable:A,readOnly:L,placeholder:N,indentWithTab:V,basicSetup:H}),se=[X,...ce?[ce]:[],wcr,...ne];return a&&typeof a=="function"&&se.push(Rt.updateListener.of(a)),se=se.concat(c),g.useLayoutEffect(()=>{if(G&&!ee){var le={doc:t,selection:n,extensions:se},he=W?gs.fromJSON(W.json,le,W.fields):gs.create(le);if(J(he),!D){var pe=new Rt({state:he,parent:G,root:B});U(pe),i&&i(pe,he)}}return()=>{D&&(J(void 0),U(void 0))}},[G,ee]),g.useEffect(()=>{e.container&&F(e.container)},[e.container]),g.useEffect(()=>()=>{D&&(D.destroy(),U(void 0)),te.current&&(te.current.cancel(),te.current=null)},[D]),g.useEffect(()=>{u&&D&&D.focus()},[u,D]),g.useEffect(()=>{D&&D.dispatch({effects:hr.reconfigure.of(se)})},[f,c,p,v,b,w,_,T,N,A,L,V,H,r,a]),g.useEffect(()=>{if(t!==void 0){var le=D?D.state.doc.toString():"";if(D&&t!==le){var he=te.current&&!te.current.isDone,pe=()=>{D&&t!==D.state.doc.toString()&&D.dispatch({changes:{from:0,to:D.state.doc.toString().length,insert:t||""},annotations:[gZe.of(!0)]})};he?re.current=pe:pe()}}},[t,D]),{state:ee,setState:J,view:D,setView:U,container:G,setContainer:F}}var _cr=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],ef=g.forwardRef((e,t)=>{var n=e.className,r=e.value,s=r===void 0?"":r,i=e.selection,a=e.extensions,l=a===void 0?[]:a,c=e.onChange,u=e.onStatistics,d=e.onCreateEditor,f=e.onUpdate,h=e.autoFocus,p=e.theme,m=p===void 0?"light":p,v=e.height,y=e.minHeight,b=e.maxHeight,x=e.width,w=e.minWidth,k=e.maxWidth,_=e.basicSetup,C=e.placeholder,T=e.indentWithTab,E=e.editable,N=e.readOnly,I=e.root,A=e.initialState,P=kRt(e,_cr),L=g.useRef(null),M=Ccr({root:I,value:s,autoFocus:h,theme:m,height:v,minHeight:y,maxHeight:b,width:x,minWidth:w,maxWidth:k,basicSetup:_,placeholder:C,indentWithTab:T,editable:E,readOnly:N,selection:i,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),V=M.state,q=M.view,H=M.container,B=M.setContainer;g.useImperativeHandle(t,()=>({editor:L.current,state:V,view:q}),[L,H,V,q]);var W=g.useCallback(G=>{L.current=G,B(G)},[B]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var z=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",a_({ref:W,className:""+z+(n?" "+n:"")},P))});ef.displayName="CodeMirror";function Ecr(e){return new r_(xje.define(e))}const Tcr=[Pg.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return Bi(()=>Promise.resolve().then(()=>F9),[],import.meta.url).then(e=>e.javascript())}}),Pg.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return Bi(()=>Promise.resolve().then(()=>rrr),void 0,import.meta.url).then(e=>e.json())}}),Pg.of({name:"JSX",extensions:["jsx"],load(){return Bi(()=>Promise.resolve().then(()=>F9),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),Pg.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return Bi(()=>Promise.resolve().then(()=>Xar),void 0,import.meta.url).then(e=>e.markdown())}}),Pg.of({name:"TSX",extensions:["tsx"],load(){return Bi(()=>Promise.resolve().then(()=>F9),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 Bi(()=>Promise.resolve().then(()=>F9),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 Bi(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>Ecr(e.shell))}})];function jcr(e,t=5){if(!e?.properties)return[];const n=[];function r(s,i,a){if(a>t)return;const l=Array.isArray(s.type)?s.type.join(" | "):s.type;if(n.push({path:i,label:i,description:s.description??s.title,type:l}),s.properties)for(const[c,u]of Object.entries(s.properties))r(u,`${i}.${c}`,a+1);if(s.items?.properties)for(const[c,u]of Object.entries(s.items.properties))r(u,`${i}[].${c}`,a+1)}for(const[s,i]of Object.entries(e.properties))r(i,s,1);return n}function Ncr(e){const t=jcr(e);return oAt({override:[Icr(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function Icr(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]??"",i=t.pos-s.length,a=s?e.filter(c=>c.path.toLowerCase().startsWith(s.toLowerCase())):e;if(a.length===0)return null;const l=a.map(c=>({label:c.path,displayLabel:c.path,detail:c.type,info:c.description,apply:(u,d,f,h)=>{const v=u.state.sliceDoc(h,h+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:h,insert:v},selection:{anchor:f+v.length}})}}));return{from:i,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const Acr=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,Rcr=Nn.mark({class:"cm-variable-highlight"}),vZe=new xIt({regexp:Acr,decoration:()=>Rcr}),Pcr=To.fromClass(class{decorations;constructor(e){this.decorations=vZe.createDeco(e)}update(e){this.decorations=vZe.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),$cr=Pcr;function Mcr(){const e=XA({settings:{fontFamily:"var(--font-mono)",fontSize:"var(--text-ui-smd)",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"var(--neutral2)",background:"transparent",foreground:"var(--neutral6)",caret:"var(--neutral6)"},styles:[{tag:[oe.className,oe.propertyName],color:"var(--neutral6)"},{tag:oe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[oe.heading1,oe.heading2,oe.heading3,oe.heading4,oe.heading5,oe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:oe.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:oe.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:oe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:oe.url,color:"var(--accent3)"},{tag:oe.monospace,color:"var(--neutral6)"},{tag:oe.strikethrough,textDecoration:"line-through"},{tag:oe.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=Rt.theme({".cm-editor":{backgroundColor:"transparent"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{color:"var(--neutral3)"},".cm-cursor":{borderLeftColor:"var(--neutral6)"},".cm-selectionBackground, .cm-content ::selection":{backgroundColor:"color-mix(in srgb, var(--accent3) 22%, transparent)"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"var(--text-ui-sm)",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 Dcr(){const e=Rt.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"var(--text-ui-smd)"},"&.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:"var(--text-ui-sm)",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=wv.define([{tag:[oe.comment,oe.bracket],color:"var(--neutral2)"},{tag:[oe.string,oe.meta,oe.regexp],color:"var(--accent1)"},{tag:[oe.atom,oe.bool,oe.special(oe.variableName)],color:"var(--accent6)"},{tag:[oe.keyword,oe.operator,oe.tagName],color:"var(--accent2)"},{tag:[oe.function(oe.propertyName),oe.propertyName],color:"var(--accent5)"},{tag:[oe.definition(oe.variableName),oe.function(oe.variableName),oe.className,oe.attributeName],color:"var(--accent3)"},{tag:[oe.variableName,oe.number],color:"var(--accent5)"},{tag:[oe.name,oe.quote],color:"var(--accent1)"},{tag:oe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[oe.heading1,oe.heading2,oe.heading3,oe.heading4,oe.heading5,oe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[oe.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[oe.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:oe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:oe.url,color:"var(--accent3)"},{tag:oe.monospace,color:"var(--neutral6)"},{tag:oe.strikethrough,textDecoration:"line-through"},{tag:[oe.deleted],color:"var(--accent2)"},{tag:oe.invalid,color:"var(--error)"},{tag:[oe.standard(oe.tagName)],color:"var(--accent1)"}]);return[e,J1(t)]}const tk=()=>{const e=aE().resolvedTheme==="dark";return g.useMemo(()=>e?Mcr():Dcr(),[e])},Lcr=kl(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"}}),Fcr=bp.highest(Rt.editorAttributes.of({style:"outline: none"})),zcr=bp.highest(Rt.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),Bcr=[Fcr,zcr],Lr=g.forwardRef(({data:e,value:t,onChange:n,showCopyButton:r=!0,className:s,language:i="json",highlightVariables:a=!1,placeholder:l,schema:c,autoFocus:u,lineNumbers:d=!0,lineWrapping:f=!0,editable:h,variant:p,...m},v)=>{const y=tk(),b=e?JSON.stringify(e,null,2):t??"",x=g.useMemo(()=>{const w=[...Bcr];return f&&w.push(Rt.lineWrapping),i==="json"?w.push(rp):i==="markdown"&&w.push(wRt({base:OI,codeLanguages:Tcr})),a&&i==="markdown"&&w.push($cr),c&&i==="markdown"&&w.push(Ncr(c)),h===!1&&w.push(gs.readOnly.of(!0)),w},[i,a,c,h,f]);return o.jsxs("div",{className:K(Lcr({variant:p}),s),...m,children:[r&&o.jsx(ci,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(ef,{ref:v,value:b,theme:y,extensions:x,onChange:n,editable:h,"aria-label":"Code editor",placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),gPt={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 nie=null;function Ucr(){return nie||(nie=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Bi(()=>import("./core-CB1TmVRp.js"),__vite__mapDeps([0,1,2]),import.meta.url),Bi(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[Bi(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Bi(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Bi(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Bi(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Bi(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Bi(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Bi(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Bi(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Bi(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Bi(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Bi(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Bi(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Bi(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Bi(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([4,5,6]),import.meta.url),Bi(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Bi(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),nie}async function Vcr(e,t){const n=gPt[t?.toLowerCase()];if(!n)return null;const r=await Ucr(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function qcr(e){const t=e?.split(".").pop()?.toLowerCase();return t?gPt[t]:void 0}const Hcr=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},Wcr=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=tk(),{settings:r,setSettings:s}=YG(),i=r?.tracingOptions,a=g.useMemo(()=>Hcr(i),[i]),[l,c]=g.useState(()=>a),u=g.useRef(!1);g.useEffect(()=>{u.current||c(a)},[a]);const d=h=>{u.current=!0,c(h)},f=()=>{if(!l){s({...r,tracingOptions:void 0}),t?.();return}try{const h=JSON.parse(l);typeof h=="object"&&h!==null&&s({...r,tracingOptions:h})}catch{return}t?.()};return o.jsxs("div",{className:"space-y-2 px-5 py-2",children:[o.jsx(Te,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),o.jsx(ef,{value:l,onChange:d,theme:n,extensions:[rp],className:K("overflow-y-scroll bg-surface3 rounded-lg overflow-hidden p-3",e)}),o.jsx("div",{className:"flex items-center justify-end",children:o.jsx(ae,{icon:o.jsx(Mn,{}),type:"button",onClick:f,children:"Save"})})]})},Zcr=()=>{const[e,t]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(In,{children:[o.jsx(On,{asChild:!0,children:o.jsx(ae,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(St,{children:o.jsx(RCe,{})})})}),o.jsx(Cn,{children:"Run Options"})]}),o.jsx(hs,{open:e,onOpenChange:t,children:o.jsxs(Jr,{children:[o.jsxs(es,{children:[o.jsx(Kr,{children:"Run Options"}),o.jsx(Ps,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx(vs,{children:o.jsx(Wcr,{onSaved:()=>t(!1)})})]})})]})};function Hl(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=Hl(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var Gcr={value:()=>{}};function TQ(){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 I7(n)}function I7(e){this._=e}function Qcr(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}})}I7.prototype=TQ.prototype={constructor:I7,on:function(e,t){var n=this._,r=Qcr(e+"",n),s,i=-1,a=r.length;if(arguments.length<2){for(;++i<a;)if((s=(e=r[i]).type)&&(s=Kcr(n[s],e.name)))return s;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++i<a;)if(s=(e=r[i]).type)n[s]=yZe(n[s],e.name,t);else if(t==null)for(s in n)n[s]=yZe(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 I7(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),r=0,s,i;r<s;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(i=this._[e],r=0,s=i.length;r<s;++r)i[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,i=r.length;s<i;++s)r[s].value.apply(t,n)}};function Kcr(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function yZe(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=Gcr,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Z0e="http://www.w3.org/1999/xhtml";const bZe={svg:"http://www.w3.org/2000/svg",xhtml:Z0e,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function jQ(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),bZe.hasOwnProperty(t)?{space:bZe[t],local:e}:e}function Ycr(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Z0e&&t.documentElement.namespaceURI===Z0e?t.createElement(e):t.createElementNS(n,e)}}function Xcr(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function vPt(e){var t=jQ(e);return(t.local?Xcr:Ycr)(t)}function Jcr(){}function tNe(e){return e==null?Jcr:function(){return this.querySelector(e)}}function eur(e){typeof e!="function"&&(e=tNe(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var i=t[s],a=i.length,l=r[s]=new Array(a),c,u,d=0;d<a;++d)(c=i[d])&&(u=e.call(c,c.__data__,d,i))&&("__data__"in c&&(u.__data__=c.__data__),l[d]=u);return new hp(r,this._parents)}function tur(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function nur(){return[]}function yPt(e){return e==null?nur:function(){return this.querySelectorAll(e)}}function rur(e){return function(){return tur(e.apply(this,arguments))}}function sur(e){typeof e=="function"?e=rur(e):e=yPt(e);for(var t=this._groups,n=t.length,r=[],s=[],i=0;i<n;++i)for(var a=t[i],l=a.length,c,u=0;u<l;++u)(c=a[u])&&(r.push(e.call(c,c.__data__,u,a)),s.push(c));return new hp(r,s)}function bPt(e){return function(){return this.matches(e)}}function xPt(e){return function(t){return t.matches(e)}}var iur=Array.prototype.find;function aur(e){return function(){return iur.call(this.children,e)}}function our(){return this.firstElementChild}function lur(e){return this.select(e==null?our:aur(typeof e=="function"?e:xPt(e)))}var cur=Array.prototype.filter;function uur(){return Array.from(this.children)}function dur(e){return function(){return cur.call(this.children,e)}}function fur(e){return this.selectAll(e==null?uur:dur(typeof e=="function"?e:xPt(e)))}function hur(e){typeof e!="function"&&(e=bPt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var i=t[s],a=i.length,l=r[s]=[],c,u=0;u<a;++u)(c=i[u])&&e.call(c,c.__data__,u,i)&&l.push(c);return new hp(r,this._parents)}function wPt(e){return new Array(e.length)}function pur(){return new hp(this._enter||this._groups.map(wPt),this._parents)}function sH(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}sH.prototype={constructor:sH,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 mur(e){return function(){return e}}function gur(e,t,n,r,s,i){for(var a=0,l,c=t.length,u=i.length;a<u;++a)(l=t[a])?(l.__data__=i[a],r[a]=l):n[a]=new sH(e,i[a]);for(;a<c;++a)(l=t[a])&&(s[a]=l)}function vur(e,t,n,r,s,i,a){var l,c,u=new Map,d=t.length,f=i.length,h=new Array(d),p;for(l=0;l<d;++l)(c=t[l])&&(h[l]=p=a.call(c,c.__data__,l,t)+"",u.has(p)?s[l]=c:u.set(p,c));for(l=0;l<f;++l)p=a.call(e,i[l],l,i)+"",(c=u.get(p))?(r[l]=c,c.__data__=i[l],u.delete(p)):n[l]=new sH(e,i[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(h[l])===c&&(s[l]=c)}function yur(e){return e.__data__}function bur(e,t){if(!arguments.length)return Array.from(this,yur);var n=t?vur:gur,r=this._parents,s=this._groups;typeof e!="function"&&(e=mur(e));for(var i=s.length,a=new Array(i),l=new Array(i),c=new Array(i),u=0;u<i;++u){var d=r[u],f=s[u],h=f.length,p=xur(e.call(d,d&&d.__data__,u,r)),m=p.length,v=l[u]=new Array(m),y=a[u]=new Array(m),b=c[u]=new Array(h);n(d,f,v,y,b,p,t);for(var x=0,w=0,k,_;x<m;++x)if(k=v[x]){for(x>=w&&(w=x+1);!(_=y[w])&&++w<m;);k._next=_||null}}return a=new hp(a,r),a._enter=l,a._exit=c,a}function xur(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function wur(){return new hp(this._exit||this._groups.map(wPt),this._parents)}function Sur(e,t,n){var r=this.enter(),s=this,i=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?i.remove():n(i),r&&s?r.merge(s).order():s}function kur(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,s=n.length,i=r.length,a=Math.min(s,i),l=new Array(s),c=0;c<a;++c)for(var u=n[c],d=r[c],f=u.length,h=l[c]=new Array(f),p,m=0;m<f;++m)(p=u[m]||d[m])&&(h[m]=p);for(;c<s;++c)l[c]=n[c];return new hp(l,this._parents)}function Our(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],s=r.length-1,i=r[s],a;--s>=0;)(a=r[s])&&(i&&a.compareDocumentPosition(i)^4&&i.parentNode.insertBefore(a,i),i=a);return this}function Cur(e){e||(e=_ur);function t(f,h){return f&&h?e(f.__data__,h.__data__):!f-!h}for(var n=this._groups,r=n.length,s=new Array(r),i=0;i<r;++i){for(var a=n[i],l=a.length,c=s[i]=new Array(l),u,d=0;d<l;++d)(u=a[d])&&(c[d]=u);c.sort(t)}return new hp(s,this._parents).order()}function _ur(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function Eur(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function Tur(){return Array.from(this)}function jur(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,i=r.length;s<i;++s){var a=r[s];if(a)return a}return null}function Nur(){let e=0;for(const t of this)++e;return e}function Iur(){return!this.node()}function Aur(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var s=t[n],i=0,a=s.length,l;i<a;++i)(l=s[i])&&e.call(l,l.__data__,i,s);return this}function Rur(e){return function(){this.removeAttribute(e)}}function Pur(e){return function(){this.removeAttributeNS(e.space,e.local)}}function $ur(e,t){return function(){this.setAttribute(e,t)}}function Mur(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function Dur(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function Lur(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 Fur(e,t){var n=jQ(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?Pur:Rur:typeof t=="function"?n.local?Lur:Dur:n.local?Mur:$ur)(n,t))}function SPt(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function zur(e){return function(){this.style.removeProperty(e)}}function Bur(e,t,n){return function(){this.style.setProperty(e,t,n)}}function Uur(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function Vur(e,t,n){return arguments.length>1?this.each((t==null?zur:typeof t=="function"?Uur:Bur)(e,t,n??"")):_I(this.node(),e)}function _I(e,t){return e.style.getPropertyValue(t)||SPt(e).getComputedStyle(e,null).getPropertyValue(t)}function qur(e){return function(){delete this[e]}}function Hur(e,t){return function(){this[e]=t}}function Wur(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function Zur(e,t){return arguments.length>1?this.each((t==null?qur:typeof t=="function"?Wur:Hur)(e,t)):this.node()[e]}function kPt(e){return e.trim().split(/^|\s+/)}function nNe(e){return e.classList||new OPt(e)}function OPt(e){this._node=e,this._names=kPt(e.getAttribute("class")||"")}OPt.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 CPt(e,t){for(var n=nNe(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function _Pt(e,t){for(var n=nNe(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function Gur(e){return function(){CPt(this,e)}}function Qur(e){return function(){_Pt(this,e)}}function Kur(e,t){return function(){(t.apply(this,arguments)?CPt:_Pt)(this,e)}}function Yur(e,t){var n=kPt(e+"");if(arguments.length<2){for(var r=nNe(this.node()),s=-1,i=n.length;++s<i;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?Kur:t?Gur:Qur)(n,t))}function Xur(){this.textContent=""}function Jur(e){return function(){this.textContent=e}}function edr(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function tdr(e){return arguments.length?this.each(e==null?Xur:(typeof e=="function"?edr:Jur)(e)):this.node().textContent}function ndr(){this.innerHTML=""}function rdr(e){return function(){this.innerHTML=e}}function sdr(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function idr(e){return arguments.length?this.each(e==null?ndr:(typeof e=="function"?sdr:rdr)(e)):this.node().innerHTML}function adr(){this.nextSibling&&this.parentNode.appendChild(this)}function odr(){return this.each(adr)}function ldr(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function cdr(){return this.each(ldr)}function udr(e){var t=typeof e=="function"?e:vPt(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function ddr(){return null}function fdr(e,t){var n=typeof e=="function"?e:vPt(e),r=t==null?ddr:typeof t=="function"?t:tNe(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function hdr(){var e=this.parentNode;e&&e.removeChild(this)}function pdr(){return this.each(hdr)}function mdr(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function gdr(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function vdr(e){return this.select(e?gdr:mdr)}function ydr(e){return arguments.length?this.property("__data__",e):this.node().__data__}function bdr(e){return function(t){e.call(this,t,this.__data__)}}function xdr(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 wdr(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,s=t.length,i;n<s;++n)i=t[n],(!e.type||i.type===e.type)&&i.name===e.name?this.removeEventListener(i.type,i.listener,i.options):t[++r]=i;++r?t.length=r:delete this.__on}}}function Sdr(e,t,n){return function(){var r=this.__on,s,i=bdr(t);if(r){for(var a=0,l=r.length;a<l;++a)if((s=r[a]).type===e.type&&s.name===e.name){this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=i,s.options=n),s.value=t;return}}this.addEventListener(e.type,i,n),s={type:e.type,name:e.name,value:t,listener:i,options:n},r?r.push(s):this.__on=[s]}}function kdr(e,t,n){var r=xdr(e+""),s,i=r.length,a;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<i;++s)if((a=r[s]).type===d.type&&a.name===d.name)return d.value}return}for(l=t?Sdr:wdr,s=0;s<i;++s)this.each(l(r[s],t,n));return this}function EPt(e,t,n){var r=SPt(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 Odr(e,t){return function(){return EPt(this,e,t)}}function Cdr(e,t){return function(){return EPt(this,e,t.apply(this,arguments))}}function _dr(e,t){return this.each((typeof t=="function"?Cdr:Odr)(e,t))}function*Edr(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,i=r.length,a;s<i;++s)(a=r[s])&&(yield a)}var TPt=[null];function hp(e,t){this._groups=e,this._parents=t}function h5(){return new hp([[document.documentElement]],TPt)}function Tdr(){return this}hp.prototype=h5.prototype={constructor:hp,select:eur,selectAll:sur,selectChild:lur,selectChildren:fur,filter:hur,data:bur,enter:pur,exit:wur,join:Sur,merge:kur,selection:Tdr,order:Our,sort:Cur,call:Eur,nodes:Tur,node:jur,size:Nur,empty:Iur,each:Aur,attr:Fur,style:Vur,property:Zur,classed:Yur,text:tdr,html:idr,raise:odr,lower:cdr,append:udr,insert:fdr,remove:pdr,clone:vdr,datum:ydr,on:kdr,dispatch:_dr,[Symbol.iterator]:Edr};function Uh(e){return typeof e=="string"?new hp([[document.querySelector(e)]],[document.documentElement]):new hp([[e]],TPt)}function jdr(e){let t;for(;t=e.sourceEvent;)e=t;return e}function $g(e,t){if(e=jdr(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 Ndr={passive:!1},UL={capture:!0,passive:!1};function rie(e){e.stopImmediatePropagation()}function wN(e){e.preventDefault(),e.stopImmediatePropagation()}function jPt(e){var t=e.document.documentElement,n=Uh(e).on("dragstart.drag",wN,UL);"onselectstart"in t?n.on("selectstart.drag",wN,UL):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function NPt(e,t){var n=e.document.documentElement,r=Uh(e).on("dragstart.drag",null);t&&(r.on("click.drag",wN,UL),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 q9=e=>()=>e;function G0e(e,{sourceEvent:t,subject:n,target:r,identifier:s,active:i,x:a,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:i,enumerable:!0,configurable:!0},x:{value:a,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}})}G0e.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function Idr(e){return!e.ctrlKey&&!e.button}function Adr(){return this.parentNode}function Rdr(e,t){return t??{x:e.x,y:e.y}}function Pdr(){return navigator.maxTouchPoints||"ontouchstart"in this}function IPt(){var e=Idr,t=Adr,n=Rdr,r=Pdr,s={},i=TQ("start","drag","end"),a=0,l,c,u,d,f=0;function h(k){k.on("mousedown.drag",p).filter(r).on("touchstart.drag",y).on("touchmove.drag",b,Ndr).on("touchend.drag touchcancel.drag",x).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function p(k,_){if(!(d||!e.call(this,k,_))){var C=w(this,t.call(this,k,_),k,_,"mouse");C&&(Uh(k.view).on("mousemove.drag",m,UL).on("mouseup.drag",v,UL),jPt(k.view),rie(k),u=!1,l=k.clientX,c=k.clientY,C("start",k))}}function m(k){if(wN(k),!u){var _=k.clientX-l,C=k.clientY-c;u=_*_+C*C>f}s.mouse("drag",k)}function v(k){Uh(k.view).on("mousemove.drag mouseup.drag",null),NPt(k.view,u),wN(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=w(this,T,k,_,C[N].identifier,C[N]))&&(rie(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])&&(wN(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])&&(rie(k),E("end",k,_[T]))}function w(k,_,C,T,E,N){var I=i.copy(),A=$g(N||C,_),P,L,M;if((M=n.call(k,new G0e("beforestart",{sourceEvent:C,target:h,identifier:E,active:a,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),T))!=null)return P=M.x-A[0]||0,L=M.y-A[1]||0,function V(q,H,B){var W=A,z;switch(q){case"start":s[E]=V,z=a++;break;case"end":delete s[E],--a;case"drag":A=$g(B||H,_),z=a;break}I.call(q,k,new G0e(q,{sourceEvent:H,subject:M,target:h,identifier:E,active:z,x:A[0]+P,y:A[1]+L,dx:A[0]-W[0],dy:A[1]-W[1],dispatch:I}),T)}}return h.filter=function(k){return arguments.length?(e=typeof k=="function"?k:q9(!!k),h):e},h.container=function(k){return arguments.length?(t=typeof k=="function"?k:q9(k),h):t},h.subject=function(k){return arguments.length?(n=typeof k=="function"?k:q9(k),h):n},h.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:q9(!!k),h):r},h.on=function(){var k=i.on.apply(i,arguments);return k===i?h:k},h.clickDistance=function(k){return arguments.length?(f=(k=+k)*k,h):Math.sqrt(f)},h}function rNe(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function APt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function p5(){}var VL=.7,iH=1/VL,SN="\\s*([+-]?\\d+)\\s*",qL="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Hy="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",$dr=/^#([0-9a-f]{3,8})$/,Mdr=new RegExp(`^rgb\\(${SN},${SN},${SN}\\)$`),Ddr=new RegExp(`^rgb\\(${Hy},${Hy},${Hy}\\)$`),Ldr=new RegExp(`^rgba\\(${SN},${SN},${SN},${qL}\\)$`),Fdr=new RegExp(`^rgba\\(${Hy},${Hy},${Hy},${qL}\\)$`),zdr=new RegExp(`^hsl\\(${qL},${Hy},${Hy}\\)$`),Bdr=new RegExp(`^hsla\\(${qL},${Hy},${Hy},${qL}\\)$`),xZe={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};rNe(p5,o_,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:wZe,formatHex:wZe,formatHex8:Udr,formatHsl:Vdr,formatRgb:SZe,toString:SZe});function wZe(){return this.rgb().formatHex()}function Udr(){return this.rgb().formatHex8()}function Vdr(){return RPt(this).formatHsl()}function SZe(){return this.rgb().formatRgb()}function o_(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=$dr.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?kZe(t):n===3?new Lf(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?H9(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?H9(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=Mdr.exec(e))?new Lf(t[1],t[2],t[3],1):(t=Ddr.exec(e))?new Lf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Ldr.exec(e))?H9(t[1],t[2],t[3],t[4]):(t=Fdr.exec(e))?H9(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=zdr.exec(e))?_Ze(t[1],t[2]/100,t[3]/100,1):(t=Bdr.exec(e))?_Ze(t[1],t[2]/100,t[3]/100,t[4]):xZe.hasOwnProperty(e)?kZe(xZe[e]):e==="transparent"?new Lf(NaN,NaN,NaN,0):null}function kZe(e){return new Lf(e>>16&255,e>>8&255,e&255,1)}function H9(e,t,n,r){return r<=0&&(e=t=n=NaN),new Lf(e,t,n,r)}function qdr(e){return e instanceof p5||(e=o_(e)),e?(e=e.rgb(),new Lf(e.r,e.g,e.b,e.opacity)):new Lf}function Q0e(e,t,n,r){return arguments.length===1?qdr(e):new Lf(e,t,n,r??1)}function Lf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}rNe(Lf,Q0e,APt(p5,{brighter(e){return e=e==null?iH:Math.pow(iH,e),new Lf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?VL:Math.pow(VL,e),new Lf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Lf(hC(this.r),hC(this.g),hC(this.b),aH(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:OZe,formatHex:OZe,formatHex8:Hdr,formatRgb:CZe,toString:CZe}));function OZe(){return`#${UO(this.r)}${UO(this.g)}${UO(this.b)}`}function Hdr(){return`#${UO(this.r)}${UO(this.g)}${UO(this.b)}${UO((isNaN(this.opacity)?1:this.opacity)*255)}`}function CZe(){const e=aH(this.opacity);return`${e===1?"rgb(":"rgba("}${hC(this.r)}, ${hC(this.g)}, ${hC(this.b)}${e===1?")":`, ${e})`}`}function aH(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function hC(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function UO(e){return e=hC(e),(e<16?"0":"")+e.toString(16)}function _Ze(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Bg(e,t,n,r)}function RPt(e){if(e instanceof Bg)return new Bg(e.h,e.s,e.l,e.opacity);if(e instanceof p5||(e=o_(e)),!e)return new Bg;if(e instanceof Bg)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,s=Math.min(t,n,r),i=Math.max(t,n,r),a=NaN,l=i-s,c=(i+s)/2;return l?(t===i?a=(n-r)/l+(n<r)*6:n===i?a=(r-t)/l+2:a=(t-n)/l+4,l/=c<.5?i+s:2-i-s,a*=60):l=c>0&&c<1?0:a,new Bg(a,l,c,e.opacity)}function Wdr(e,t,n,r){return arguments.length===1?RPt(e):new Bg(e,t,n,r??1)}function Bg(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}rNe(Bg,Wdr,APt(p5,{brighter(e){return e=e==null?iH:Math.pow(iH,e),new Bg(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?VL:Math.pow(VL,e),new Bg(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 Lf(sie(e>=240?e-240:e+120,s,r),sie(e,s,r),sie(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new Bg(EZe(this.h),W9(this.s),W9(this.l),aH(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=aH(this.opacity);return`${e===1?"hsl(":"hsla("}${EZe(this.h)}, ${W9(this.s)*100}%, ${W9(this.l)*100}%${e===1?")":`, ${e})`}`}}));function EZe(e){return e=(e||0)%360,e<0?e+360:e}function W9(e){return Math.max(0,Math.min(1,e||0))}function sie(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 sNe=e=>()=>e;function Zdr(e,t){return function(n){return e+n*t}}function Gdr(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 Qdr(e){return(e=+e)==1?PPt:function(t,n){return n-t?Gdr(t,n,e):sNe(isNaN(t)?n:t)}}function PPt(e,t){var n=t-e;return n?Zdr(e,n):sNe(isNaN(e)?t:e)}const oH=(function e(t){var n=Qdr(t);function r(s,i){var a=n((s=Q0e(s)).r,(i=Q0e(i)).r),l=n(s.g,i.g),c=n(s.b,i.b),u=PPt(s.opacity,i.opacity);return function(d){return s.r=a(d),s.g=l(d),s.b=c(d),s.opacity=u(d),s+""}}return r.gamma=e,r})(1);function Kdr(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),s;return function(i){for(s=0;s<n;++s)r[s]=e[s]*(1-i)+t[s]*i;return r}}function Ydr(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Xdr(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,s=new Array(r),i=new Array(n),a;for(a=0;a<r;++a)s[a]=t0(e[a],t[a]);for(;a<n;++a)i[a]=t[a];return function(l){for(a=0;a<r;++a)i[a]=s[a](l);return i}}function Jdr(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function Dg(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function efr(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]=t0(e[s],t[s]):r[s]=t[s];return function(i){for(s in n)r[s]=n[s](i);return r}}var K0e=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,iie=new RegExp(K0e.source,"g");function tfr(e){return function(){return e}}function nfr(e){return function(t){return e(t)+""}}function $Pt(e,t){var n=K0e.lastIndex=iie.lastIndex=0,r,s,i,a=-1,l=[],c=[];for(e=e+"",t=t+"";(r=K0e.exec(e))&&(s=iie.exec(t));)(i=s.index)>n&&(i=t.slice(n,i),l[a]?l[a]+=i:l[++a]=i),(r=r[0])===(s=s[0])?l[a]?l[a]+=s:l[++a]=s:(l[++a]=null,c.push({i:a,x:Dg(r,s)})),n=iie.lastIndex;return n<t.length&&(i=t.slice(n),l[a]?l[a]+=i:l[++a]=i),l.length<2?c[0]?nfr(c[0].x):tfr(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 t0(e,t){var n=typeof t,r;return t==null||n==="boolean"?sNe(t):(n==="number"?Dg:n==="string"?(r=o_(t))?(t=r,oH):$Pt:t instanceof o_?oH:t instanceof Date?Jdr:Ydr(t)?Kdr:Array.isArray(t)?Xdr:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?efr:Dg)(e,t)}function iNe(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var TZe=180/Math.PI,Y0e={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function MPt(e,t,n,r,s,i){var a,l,c;return(a=Math.sqrt(e*e+t*t))&&(e/=a,t/=a),(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,a=-a),{translateX:s,translateY:i,rotate:Math.atan2(t,e)*TZe,skewX:Math.atan(c)*TZe,scaleX:a,scaleY:l}}var Z9;function rfr(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Y0e:MPt(t.a,t.b,t.c,t.d,t.e,t.f)}function sfr(e){return e==null||(Z9||(Z9=document.createElementNS("http://www.w3.org/2000/svg","g")),Z9.setAttribute("transform",e),!(e=Z9.transform.baseVal.consolidate()))?Y0e:(e=e.matrix,MPt(e.a,e.b,e.c,e.d,e.e,e.f))}function DPt(e,t,n,r){function s(u){return u.length?u.pop()+" ":""}function i(u,d,f,h,p,m){if(u!==f||d!==h){var v=p.push("translate(",null,t,null,n);m.push({i:v-4,x:Dg(u,f)},{i:v-2,x:Dg(d,h)})}else(f||h)&&p.push("translate("+f+t+h+n)}function a(u,d,f,h){u!==d?(u-d>180?d+=360:d-u>180&&(u+=360),h.push({i:f.push(s(f)+"rotate(",null,r)-2,x:Dg(u,d)})):d&&f.push(s(f)+"rotate("+d+r)}function l(u,d,f,h){u!==d?h.push({i:f.push(s(f)+"skewX(",null,r)-2,x:Dg(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,h,p,m){if(u!==f||d!==h){var v=p.push(s(p)+"scale(",null,",",null,")");m.push({i:v-4,x:Dg(u,f)},{i:v-2,x:Dg(d,h)})}else(f!==1||h!==1)&&p.push(s(p)+"scale("+f+","+h+")")}return function(u,d){var f=[],h=[];return u=e(u),d=e(d),i(u.translateX,u.translateY,d.translateX,d.translateY,f,h),a(u.rotate,d.rotate,f,h),l(u.skewX,d.skewX,f,h),c(u.scaleX,u.scaleY,d.scaleX,d.scaleY,f,h),u=d=null,function(p){for(var m=-1,v=h.length,y;++m<v;)f[(y=h[m]).i]=y.x(p);return f.join("")}}}var ifr=DPt(rfr,"px, ","px)","deg)"),afr=DPt(sfr,", ",")",")"),ofr=1e-12;function jZe(e){return((e=Math.exp(e))+1/e)/2}function lfr(e){return((e=Math.exp(e))-1/e)/2}function cfr(e){return((e=Math.exp(2*e))-1)/(e+1)}const A7=(function e(t,n,r){function s(i,a){var l=i[0],c=i[1],u=i[2],d=a[0],f=a[1],h=a[2],p=d-l,m=f-c,v=p*p+m*m,y,b;if(v<ofr)b=Math.log(h/u)/t,y=function(T){return[l+T*p,c+T*m,u*Math.exp(t*T*b)]};else{var x=Math.sqrt(v),w=(h*h-u*u+r*v)/(2*u*n*x),k=(h*h-u*u-r*v)/(2*h*n*x),_=Math.log(Math.sqrt(w*w+1)-w),C=Math.log(Math.sqrt(k*k+1)-k);b=(C-_)/t,y=function(T){var E=T*b,N=jZe(_),I=u/(n*x)*(N*cfr(t*E+_)-lfr(_));return[l+I*p,c+I*m,u*N/jZe(t*E+_)]}}return y.duration=b*1e3*t/Math.SQRT2,y}return s.rho=function(i){var a=Math.max(.001,+i),l=a*a,c=l*l;return e(a,l,c)},s})(Math.SQRT2,2,4);function ufr(e,t){t===void 0&&(t=e,e=t0);for(var n=0,r=t.length-1,s=t[0],i=new Array(r<0?0:r);n<r;)i[n]=e(s,s=t[++n]);return function(a){var l=Math.max(0,Math.min(r-1,Math.floor(a*=r)));return i[l](a-l)}}var EI=0,UM=0,k$=0,LPt=1e3,lH,VM,cH=0,l_=0,NQ=0,HL=typeof performance=="object"&&performance.now?performance:Date,FPt=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function aNe(){return l_||(FPt(dfr),l_=HL.now()+NQ)}function dfr(){l_=0}function uH(){this._call=this._time=this._next=null}uH.prototype=zPt.prototype={constructor:uH,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?aNe():+n)+(t==null?0:+t),!this._next&&VM!==this&&(VM?VM._next=this:lH=this,VM=this),this._call=e,this._time=n,X0e()},stop:function(){this._call&&(this._call=null,this._time=1/0,X0e())}};function zPt(e,t,n){var r=new uH;return r.restart(e,t,n),r}function ffr(){aNe(),++EI;for(var e=lH,t;e;)(t=l_-e._time)>=0&&e._call.call(void 0,t),e=e._next;--EI}function NZe(){l_=(cH=HL.now())+NQ,EI=UM=0;try{ffr()}finally{EI=0,pfr(),l_=0}}function hfr(){var e=HL.now(),t=e-cH;t>LPt&&(NQ-=t,cH=e)}function pfr(){for(var e,t=lH,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:lH=n);VM=e,X0e(r)}function X0e(e){if(!EI){UM&&(UM=clearTimeout(UM));var t=e-l_;t>24?(e<1/0&&(UM=setTimeout(NZe,e-HL.now()-NQ)),k$&&(k$=clearInterval(k$))):(k$||(cH=HL.now(),k$=setInterval(hfr,LPt)),EI=1,FPt(NZe))}}function IZe(e,t,n){var r=new uH;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var mfr=TQ("start","end","cancel","interrupt"),gfr=[],BPt=0,AZe=1,J0e=2,R7=3,RZe=4,ewe=5,P7=6;function IQ(e,t,n,r,s,i){var a=e.__transition;if(!a)e.__transition={};else if(n in a)return;vfr(e,n,{name:t,index:r,group:s,on:mfr,tween:gfr,time:i.time,delay:i.delay,duration:i.duration,ease:i.ease,timer:null,state:BPt})}function oNe(e,t){var n=Ov(e,t);if(n.state>BPt)throw new Error("too late; already scheduled");return n}function Eb(e,t){var n=Ov(e,t);if(n.state>R7)throw new Error("too late; already running");return n}function Ov(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function vfr(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=zPt(i,0,n.time);function i(u){n.state=AZe,n.timer.restart(a,n.delay,n.time),n.delay<=u&&a(u-n.delay)}function a(u){var d,f,h,p;if(n.state!==AZe)return c();for(d in r)if(p=r[d],p.name===n.name){if(p.state===R7)return IZe(a);p.state===RZe?(p.state=P7,p.timer.stop(),p.on.call("interrupt",e,e.__data__,p.index,p.group),delete r[d]):+d<t&&(p.state=P7,p.timer.stop(),p.on.call("cancel",e,e.__data__,p.index,p.group),delete r[d])}if(IZe(function(){n.state===R7&&(n.state=RZe,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=J0e,n.on.call("start",e,e.__data__,n.index,n.group),n.state===J0e){for(n.state=R7,s=new Array(h=n.tween.length),d=0,f=-1;d<h;++d)(p=n.tween[d].value.call(e,e.__data__,n.index,n.group))&&(s[++f]=p);s.length=f+1}}function l(u){for(var d=u<n.duration?n.ease.call(null,u/n.duration):(n.timer.restart(c),n.state=ewe,1),f=-1,h=s.length;++f<h;)s[f].call(e,d);n.state===ewe&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=P7,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function $7(e,t){var n=e.__transition,r,s,i=!0,a;if(n){t=t==null?null:t+"";for(a in n){if((r=n[a]).name!==t){i=!1;continue}s=r.state>J0e&&r.state<ewe,r.state=P7,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[a]}i&&delete e.__transition}}function yfr(e){return this.each(function(){$7(this,e)})}function bfr(e,t){var n,r;return function(){var s=Eb(this,e),i=s.tween;if(i!==n){r=n=i;for(var a=0,l=r.length;a<l;++a)if(r[a].name===t){r=r.slice(),r.splice(a,1);break}}s.tween=r}}function xfr(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var i=Eb(this,e),a=i.tween;if(a!==r){s=(r=a).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)}i.tween=s}}function wfr(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Ov(this.node(),n).tween,s=0,i=r.length,a;s<i;++s)if((a=r[s]).name===e)return a.value;return null}return this.each((t==null?bfr:xfr)(n,e,t))}function lNe(e,t,n){var r=e._id;return e.each(function(){var s=Eb(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return Ov(s,r).value[t]}}function UPt(e,t){var n;return(typeof t=="number"?Dg:t instanceof o_?oH:(n=o_(t))?(t=n,oH):$Pt)(e,t)}function Sfr(e){return function(){this.removeAttribute(e)}}function kfr(e){return function(){this.removeAttributeNS(e.space,e.local)}}function Ofr(e,t,n){var r,s=n+"",i;return function(){var a=this.getAttribute(e);return a===s?null:a===r?i:i=t(r=a,n)}}function Cfr(e,t,n){var r,s=n+"",i;return function(){var a=this.getAttributeNS(e.space,e.local);return a===s?null:a===r?i:i=t(r=a,n)}}function _fr(e,t,n){var r,s,i;return function(){var a,l=n(this),c;return l==null?void this.removeAttribute(e):(a=this.getAttribute(e),c=l+"",a===c?null:a===r&&c===s?i:(s=c,i=t(r=a,l)))}}function Efr(e,t,n){var r,s,i;return function(){var a,l=n(this),c;return l==null?void this.removeAttributeNS(e.space,e.local):(a=this.getAttributeNS(e.space,e.local),c=l+"",a===c?null:a===r&&c===s?i:(s=c,i=t(r=a,l)))}}function Tfr(e,t){var n=jQ(e),r=n==="transform"?afr:UPt;return this.attrTween(e,typeof t=="function"?(n.local?Efr:_fr)(n,r,lNe(this,"attr."+e,t)):t==null?(n.local?kfr:Sfr)(n):(n.local?Cfr:Ofr)(n,r,t))}function jfr(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function Nfr(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function Ifr(e,t){var n,r;function s(){var i=t.apply(this,arguments);return i!==r&&(n=(r=i)&&Nfr(e,i)),n}return s._value=t,s}function Afr(e,t){var n,r;function s(){var i=t.apply(this,arguments);return i!==r&&(n=(r=i)&&jfr(e,i)),n}return s._value=t,s}function Rfr(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=jQ(e);return this.tween(n,(r.local?Ifr:Afr)(r,t))}function Pfr(e,t){return function(){oNe(this,e).delay=+t.apply(this,arguments)}}function $fr(e,t){return t=+t,function(){oNe(this,e).delay=t}}function Mfr(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?Pfr:$fr)(t,e)):Ov(this.node(),t).delay}function Dfr(e,t){return function(){Eb(this,e).duration=+t.apply(this,arguments)}}function Lfr(e,t){return t=+t,function(){Eb(this,e).duration=t}}function Ffr(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?Dfr:Lfr)(t,e)):Ov(this.node(),t).duration}function zfr(e,t){if(typeof t!="function")throw new Error;return function(){Eb(this,e).ease=t}}function Bfr(e){var t=this._id;return arguments.length?this.each(zfr(t,e)):Ov(this.node(),t).ease}function Ufr(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Eb(this,e).ease=n}}function Vfr(e){if(typeof e!="function")throw new Error;return this.each(Ufr(this._id,e))}function qfr(e){typeof e!="function"&&(e=bPt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var i=t[s],a=i.length,l=r[s]=[],c,u=0;u<a;++u)(c=i[u])&&e.call(c,c.__data__,u,i)&&l.push(c);return new k0(r,this._parents,this._name,this._id)}function Hfr(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,s=n.length,i=Math.min(r,s),a=new Array(r),l=0;l<i;++l)for(var c=t[l],u=n[l],d=c.length,f=a[l]=new Array(d),h,p=0;p<d;++p)(h=c[p]||u[p])&&(f[p]=h);for(;l<r;++l)a[l]=t[l];return new k0(a,this._parents,this._name,this._id)}function Wfr(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 Zfr(e,t,n){var r,s,i=Wfr(t)?oNe:Eb;return function(){var a=i(this,e),l=a.on;l!==r&&(s=(r=l).copy()).on(t,n),a.on=s}}function Gfr(e,t){var n=this._id;return arguments.length<2?Ov(this.node(),n).on.on(e):this.each(Zfr(n,e,t))}function Qfr(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function Kfr(){return this.on("end.remove",Qfr(this._id))}function Yfr(e){var t=this._name,n=this._id;typeof e!="function"&&(e=tNe(e));for(var r=this._groups,s=r.length,i=new Array(s),a=0;a<s;++a)for(var l=r[a],c=l.length,u=i[a]=new Array(c),d,f,h=0;h<c;++h)(d=l[h])&&(f=e.call(d,d.__data__,h,l))&&("__data__"in d&&(f.__data__=d.__data__),u[h]=f,IQ(u[h],t,n,h,u,Ov(d,n)));return new k0(i,this._parents,t,n)}function Xfr(e){var t=this._name,n=this._id;typeof e!="function"&&(e=yPt(e));for(var r=this._groups,s=r.length,i=[],a=[],l=0;l<s;++l)for(var c=r[l],u=c.length,d,f=0;f<u;++f)if(d=c[f]){for(var h=e.call(d,d.__data__,f,c),p,m=Ov(d,n),v=0,y=h.length;v<y;++v)(p=h[v])&&IQ(p,t,n,v,h,m);i.push(h),a.push(d)}return new k0(i,a,t,n)}var Jfr=h5.prototype.constructor;function ehr(){return new Jfr(this._groups,this._parents)}function thr(e,t){var n,r,s;return function(){var i=_I(this,e),a=(this.style.removeProperty(e),_I(this,e));return i===a?null:i===n&&a===r?s:s=t(n=i,r=a)}}function VPt(e){return function(){this.style.removeProperty(e)}}function nhr(e,t,n){var r,s=n+"",i;return function(){var a=_I(this,e);return a===s?null:a===r?i:i=t(r=a,n)}}function rhr(e,t,n){var r,s,i;return function(){var a=_I(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),_I(this,e))),a===c?null:a===r&&c===s?i:(s=c,i=t(r=a,l))}}function shr(e,t){var n,r,s,i="style."+t,a="end."+i,l;return function(){var c=Eb(this,e),u=c.on,d=c.value[i]==null?l||(l=VPt(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(a,s=d),c.on=r}}function ihr(e,t,n){var r=(e+="")=="transform"?ifr:UPt;return t==null?this.styleTween(e,thr(e,r)).on("end.style."+e,VPt(e)):typeof t=="function"?this.styleTween(e,rhr(e,r,lNe(this,"style."+e,t))).each(shr(this._id,e)):this.styleTween(e,nhr(e,r,t),n).on("end.style."+e,null)}function ahr(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function ohr(e,t,n){var r,s;function i(){var a=t.apply(this,arguments);return a!==s&&(r=(s=a)&&ahr(e,a,n)),r}return i._value=t,i}function lhr(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,ohr(e,t,n??""))}function chr(e){return function(){this.textContent=e}}function uhr(e){return function(){var t=e(this);this.textContent=t??""}}function dhr(e){return this.tween("text",typeof e=="function"?uhr(lNe(this,"text",e)):chr(e==null?"":e+""))}function fhr(e){return function(t){this.textContent=e.call(this,t)}}function hhr(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&fhr(s)),t}return r._value=e,r}function phr(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,hhr(e))}function mhr(){for(var e=this._name,t=this._id,n=qPt(),r=this._groups,s=r.length,i=0;i<s;++i)for(var a=r[i],l=a.length,c,u=0;u<l;++u)if(c=a[u]){var d=Ov(c,t);IQ(c,e,n,u,a,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new k0(r,this._parents,e,n)}function ghr(){var e,t,n=this,r=n._id,s=n.size();return new Promise(function(i,a){var l={value:a},c={value:function(){--s===0&&i()}};n.each(function(){var u=Eb(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&&i()})}var vhr=0;function k0(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function qPt(){return++vhr}var ax=h5.prototype;k0.prototype={constructor:k0,select:Yfr,selectAll:Xfr,selectChild:ax.selectChild,selectChildren:ax.selectChildren,filter:qfr,merge:Hfr,selection:ehr,transition:mhr,call:ax.call,nodes:ax.nodes,node:ax.node,size:ax.size,empty:ax.empty,each:ax.each,on:Gfr,attr:Tfr,attrTween:Rfr,style:ihr,styleTween:lhr,text:dhr,textTween:phr,remove:Kfr,tween:wfr,delay:Mfr,duration:Ffr,ease:Bfr,easeVarying:Vfr,end:ghr,[Symbol.iterator]:ax[Symbol.iterator]};function yhr(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var bhr={time:null,delay:0,duration:250,ease:yhr};function xhr(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 whr(e){var t,n;e instanceof k0?(t=e._id,e=e._name):(t=qPt(),(n=bhr).time=aNe(),e=e==null?null:e+"");for(var r=this._groups,s=r.length,i=0;i<s;++i)for(var a=r[i],l=a.length,c,u=0;u<l;++u)(c=a[u])&&IQ(c,e,t,u,a,n||xhr(c,t));return new k0(r,this._parents,e,t)}h5.prototype.interrupt=yfr;h5.prototype.transition=whr;const G9=e=>()=>e;function Shr(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 Lx(e,t,n){this.k=e,this.x=t,this.y=n}Lx.prototype={constructor:Lx,scale:function(e){return e===1?this:new Lx(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new Lx(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 AQ=new Lx(1,0,0);HPt.prototype=Lx.prototype;function HPt(e){for(;!e.__zoom;)if(!(e=e.parentNode))return AQ;return e.__zoom}function aie(e){e.stopImmediatePropagation()}function O$(e){e.preventDefault(),e.stopImmediatePropagation()}function khr(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function Ohr(){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 PZe(){return this.__zoom||AQ}function Chr(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function _hr(){return navigator.maxTouchPoints||"ontouchstart"in this}function Ehr(e,t,n){var r=e.invertX(t[0][0])-n[0][0],s=e.invertX(t[1][0])-n[1][0],i=e.invertY(t[0][1])-n[0][1],a=e.invertY(t[1][1])-n[1][1];return e.translate(s>r?(r+s)/2:Math.min(0,r)||Math.max(0,s),a>i?(i+a)/2:Math.min(0,i)||Math.max(0,a))}function WPt(){var e=khr,t=Ohr,n=Ehr,r=Chr,s=_hr,i=[0,1/0],a=[[-1/0,-1/0],[1/0,1/0]],l=250,c=A7,u=TQ("start","zoom","end"),d,f,h,p=500,m=150,v=0,y=10;function b(M){M.property("__zoom",PZe).on("wheel.zoom",E,{passive:!1}).on("mousedown.zoom",N).on("dblclick.zoom",I).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",P).on("touchend.zoom touchcancel.zoom",L).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(M,V,q,H){var B=M.selection?M.selection():M;B.property("__zoom",PZe),M!==B?_(M,V,q,H):B.interrupt().each(function(){C(this,arguments).event(H).start().zoom(null,typeof V=="function"?V.apply(this,arguments):V).end()})},b.scaleBy=function(M,V,q,H){b.scaleTo(M,function(){var B=this.__zoom.k,W=typeof V=="function"?V.apply(this,arguments):V;return B*W},q,H)},b.scaleTo=function(M,V,q,H){b.transform(M,function(){var B=t.apply(this,arguments),W=this.__zoom,z=q==null?k(B):typeof q=="function"?q.apply(this,arguments):q,G=W.invert(z),F=typeof V=="function"?V.apply(this,arguments):V;return n(w(x(W,F),z,G),B,a)},q,H)},b.translateBy=function(M,V,q,H){b.transform(M,function(){return n(this.__zoom.translate(typeof V=="function"?V.apply(this,arguments):V,typeof q=="function"?q.apply(this,arguments):q),t.apply(this,arguments),a)},null,H)},b.translateTo=function(M,V,q,H,B){b.transform(M,function(){var W=t.apply(this,arguments),z=this.__zoom,G=H==null?k(W):typeof H=="function"?H.apply(this,arguments):H;return n(AQ.translate(G[0],G[1]).scale(z.k).translate(typeof V=="function"?-V.apply(this,arguments):-V,typeof q=="function"?-q.apply(this,arguments):-q),W,a)},H,B)};function x(M,V){return V=Math.max(i[0],Math.min(i[1],V)),V===M.k?M:new Lx(V,M.x,M.y)}function w(M,V,q){var H=V[0]-q[0]*M.k,B=V[1]-q[1]*M.k;return H===M.x&&B===M.y?M:new Lx(M.k,H,B)}function k(M){return[(+M[0][0]+ +M[1][0])/2,(+M[0][1]+ +M[1][1])/2]}function _(M,V,q,H){M.on("start.zoom",function(){C(this,arguments).event(H).start()}).on("interrupt.zoom end.zoom",function(){C(this,arguments).event(H).end()}).tween("zoom",function(){var B=this,W=arguments,z=C(B,W).event(H),G=t.apply(B,W),F=q==null?k(G):typeof q=="function"?q.apply(B,W):q,R=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),D=B.__zoom,U=typeof V=="function"?V.apply(B,W):V,Q=c(D.invert(F).concat(R/D.k),U.invert(F).concat(R/U.k));return function(ee){if(ee===1)ee=U;else{var J=Q(ee),te=R/J[2];ee=new Lx(te,F[0]-J[0]*te,F[1]-J[1]*te)}z.zoom(null,ee)}})}function C(M,V,q){return!q&&M.__zooming||new T(M,V)}function T(M,V){this.that=M,this.args=V,this.active=0,this.sourceEvent=null,this.extent=t.apply(M,V),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,V){return this.mouse&&M!=="mouse"&&(this.mouse[1]=V.invert(this.mouse[0])),this.touch0&&M!=="touch"&&(this.touch0[1]=V.invert(this.touch0[0])),this.touch1&&M!=="touch"&&(this.touch1[1]=V.invert(this.touch1[0])),this.that.__zoom=V,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(M){var V=Uh(this.that).datum();u.call(M,this.that,new Shr(M,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),V)}};function E(M,...V){if(!e.apply(this,arguments))return;var q=C(this,V).event(M),H=this.__zoom,B=Math.max(i[0],Math.min(i[1],H.k*Math.pow(2,r.apply(this,arguments)))),W=$g(M);if(q.wheel)(q.mouse[0][0]!==W[0]||q.mouse[0][1]!==W[1])&&(q.mouse[1]=H.invert(q.mouse[0]=W)),clearTimeout(q.wheel);else{if(H.k===B)return;q.mouse=[W,H.invert(W)],$7(this),q.start()}O$(M),q.wheel=setTimeout(z,m),q.zoom("mouse",n(w(x(H,B),q.mouse[0],q.mouse[1]),q.extent,a));function z(){q.wheel=null,q.end()}}function N(M,...V){if(h||!e.apply(this,arguments))return;var q=M.currentTarget,H=C(this,V,!0).event(M),B=Uh(M.view).on("mousemove.zoom",F,!0).on("mouseup.zoom",R,!0),W=$g(M,q),z=M.clientX,G=M.clientY;jPt(M.view),aie(M),H.mouse=[W,this.__zoom.invert(W)],$7(this),H.start();function F(D){if(O$(D),!H.moved){var U=D.clientX-z,Q=D.clientY-G;H.moved=U*U+Q*Q>v}H.event(D).zoom("mouse",n(w(H.that.__zoom,H.mouse[0]=$g(D,q),H.mouse[1]),H.extent,a))}function R(D){B.on("mousemove.zoom mouseup.zoom",null),NPt(D.view,H.moved),O$(D),H.event(D).end()}}function I(M,...V){if(e.apply(this,arguments)){var q=this.__zoom,H=$g(M.changedTouches?M.changedTouches[0]:M,this),B=q.invert(H),W=q.k*(M.shiftKey?.5:2),z=n(w(x(q,W),H,B),t.apply(this,V),a);O$(M),l>0?Uh(this).transition().duration(l).call(_,z,H,M):Uh(this).call(b.transform,z,H,M)}}function A(M,...V){if(e.apply(this,arguments)){var q=M.touches,H=q.length,B=C(this,V,M.changedTouches.length===H).event(M),W,z,G,F;for(aie(M),z=0;z<H;++z)G=q[z],F=$g(G,this),F=[F,this.__zoom.invert(F),G.identifier],B.touch0?!B.touch1&&B.touch0[2]!==F[2]&&(B.touch1=F,B.taps=0):(B.touch0=F,W=!0,B.taps=1+!!d);d&&(d=clearTimeout(d)),W&&(B.taps<2&&(f=F[0],d=setTimeout(function(){d=null},p)),$7(this),B.start())}}function P(M,...V){if(this.__zooming){var q=C(this,V).event(M),H=M.changedTouches,B=H.length,W,z,G,F;for(O$(M),W=0;W<B;++W)z=H[W],G=$g(z,this),q.touch0&&q.touch0[2]===z.identifier?q.touch0[0]=G:q.touch1&&q.touch1[2]===z.identifier&&(q.touch1[0]=G);if(z=q.that.__zoom,q.touch1){var R=q.touch0[0],D=q.touch0[1],U=q.touch1[0],Q=q.touch1[1],ee=(ee=U[0]-R[0])*ee+(ee=U[1]-R[1])*ee,J=(J=Q[0]-D[0])*J+(J=Q[1]-D[1])*J;z=x(z,Math.sqrt(ee/J)),G=[(R[0]+U[0])/2,(R[1]+U[1])/2],F=[(D[0]+Q[0])/2,(D[1]+Q[1])/2]}else if(q.touch0)G=q.touch0[0],F=q.touch0[1];else return;q.zoom("touch",n(w(z,G,F),q.extent,a))}}function L(M,...V){if(this.__zooming){var q=C(this,V).event(M),H=M.changedTouches,B=H.length,W,z;for(aie(M),h&&clearTimeout(h),h=setTimeout(function(){h=null},p),W=0;W<B;++W)z=H[W],q.touch0&&q.touch0[2]===z.identifier?delete q.touch0:q.touch1&&q.touch1[2]===z.identifier&&delete q.touch1;if(q.touch1&&!q.touch0&&(q.touch0=q.touch1,delete q.touch1),q.touch0)q.touch0[1]=this.__zoom.invert(q.touch0[0]);else if(q.end(),q.taps===2&&(z=$g(z,this),Math.hypot(f[0]-z[0],f[1]-z[1])<y)){var G=Uh(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(M){return arguments.length?(r=typeof M=="function"?M:G9(+M),b):r},b.filter=function(M){return arguments.length?(e=typeof M=="function"?M:G9(!!M),b):e},b.touchable=function(M){return arguments.length?(s=typeof M=="function"?M:G9(!!M),b):s},b.extent=function(M){return arguments.length?(t=typeof M=="function"?M:G9([[+M[0][0],+M[0][1]],[+M[1][0],+M[1][1]]]),b):t},b.scaleExtent=function(M){return arguments.length?(i[0]=+M[0],i[1]=+M[1],b):[i[0],i[1]]},b.translateExtent=function(M){return arguments.length?(a[0][0]=+M[0][0],a[1][0]=+M[1][0],a[0][1]=+M[0][1],a[1][1]=+M[1][1],b):[[a[0][0],a[0][1]],[a[1][0],a[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 ab={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."},WL=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],ZPt=["Enter"," ","Escape"],GPt={"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 TI;(function(e){e.Strict="strict",e.Loose="loose"})(TI||(TI={}));var pC;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(pC||(pC={}));var ZL;(function(e){e.Partial="partial",e.Full="full"})(ZL||(ZL={}));const QPt={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var vS;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(vS||(vS={}));var GL;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(GL||(GL={}));var tr;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(tr||(tr={}));const $Ze={[tr.Left]:tr.Right,[tr.Right]:tr.Left,[tr.Top]:tr.Bottom,[tr.Bottom]:tr.Top};function KPt(e){return e===null?null:e?"valid":"invalid"}const YPt=e=>"id"in e&&"source"in e&&"target"in e,Thr=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),cNe=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),m5=(e,t=[0,0])=>{const{width:n,height:r}=Q0(e),s=e.origin??t,i=n*s[0],a=r*s[1];return{x:e.position.x-i,y:e.position.y-a}},jhr=(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 i=typeof s=="string";let a=!t.nodeLookup&&!i?s:void 0;t.nodeLookup&&(a=i?t.nodeLookup.get(s):cNe(s)?s:t.nodeLookup.get(s.id));const l=a?dH(a,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return RQ(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return PQ(n)},g5=(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=RQ(n,dH(s)),r=!0)}),r?PQ(n):{x:0,y:0,width:0,height:0}},uNe=(e,t,[n,r,s]=[0,0,1],i=!1,a=!1)=>{const l={...y5(t,[n,r,s]),width:t.width/s,height:t.height/s},c=[];for(const u of e.values()){const{measured:d,selectable:f=!0,hidden:h=!1}=u;if(a&&!f||h)continue;const p=d.width??u.width??u.initialWidth??null,m=d.height??u.height??u.initialHeight??null,v=QL(l,NI(u)),y=(p??0)*(m??0),b=i&&v>0;(!u.internals.handleBounds||b||v>=y||u.dragging)&&c.push(u)}return c},Nhr=(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 Ihr(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 Ahr({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:i},a){if(e.size===0)return Promise.resolve(!0);const l=Ihr(e,a),c=g5(l),u=dNe(c,t,n,a?.minZoom??s,a?.maxZoom??i,a?.padding??.1);return await r.setViewport(u,{duration:a?.duration,ease:a?.ease,interpolate:a?.interpolate}),Promise.resolve(!0)}function XPt({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:s,onError:i}){const a=n.get(e),l=a.parentId?n.get(a.parentId):void 0,{x:c,y:u}=l?l.internals.positionAbsolute:{x:0,y:0},d=a.origin??r;let f=a.extent||s;if(a.extent==="parent"&&!a.expandParent)if(!l)i?.("005",ab.error005());else{const p=l.measured.width,m=l.measured.height;p&&m&&(f=[[c,u],[c+p,u+m]])}else l&&II(a.extent)&&(f=[[a.extent[0][0]+c,a.extent[0][1]+u],[a.extent[1][0]+c,a.extent[1][1]+u]]);const h=II(f)?c_(t,f,a.measured):t;return(a.measured.width===void 0||a.measured.height===void 0)&&i?.("015",ab.error015()),{position:{x:h.x-c+(a.measured.width??0)*d[0],y:h.y-u+(a.measured.height??0)*d[1]},positionAbsolute:h}}async function Rhr({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const i=new Set(e.map(h=>h.id)),a=[];for(const h of n){if(h.deletable===!1)continue;const p=i.has(h.id),m=!p&&h.parentId&&a.find(v=>v.id===h.parentId);(p||m)&&a.push(h)}const l=new Set(t.map(h=>h.id)),c=r.filter(h=>h.deletable!==!1),d=Nhr(a,c);for(const h of c)l.has(h.id)&&!d.find(m=>m.id===h.id)&&d.push(h);if(!s)return{edges:d,nodes:a};const f=await s({nodes:a,edges:d});return typeof f=="boolean"?f?{edges:d,nodes:a}:{edges:[],nodes:[]}:f}const jI=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),c_=(e={x:0,y:0},t,n)=>({x:jI(e.x,t[0][0],t[1][0]-(n?.width??0)),y:jI(e.y,t[0][1],t[1][1]-(n?.height??0))});function JPt(e,t,n){const{width:r,height:s}=Q0(n),{x:i,y:a}=n.internals.positionAbsolute;return c_(e,[[i,a],[i+r,a+s]],t)}const MZe=(e,t,n)=>e<t?jI(Math.abs(e-t),1,t)/t:e>n?-jI(Math.abs(e-n),1,t)/t:0,e$t=(e,t,n=15,r=40)=>{const s=MZe(e.x,r,t.width-r)*n,i=MZe(e.y,r,t.height-r)*n;return[s,i]},RQ=(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)}),twe=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),PQ=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),NI=(e,t=[0,0])=>{const{x:n,y:r}=cNe(e)?e.internals.positionAbsolute:m5(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}},dH=(e,t=[0,0])=>{const{x:n,y:r}=cNe(e)?e.internals.positionAbsolute:m5(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)}},t$t=(e,t)=>PQ(RQ(twe(e),twe(t))),QL=(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)},DZe=e=>Wg(e.width)&&Wg(e.height)&&Wg(e.x)&&Wg(e.y),Wg=e=>!isNaN(e)&&isFinite(e),Phr=(e,t)=>{},v5=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),y5=({x:e,y:t},[n,r,s],i=!1,a=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return i?v5(l,a):l},fH=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function IT(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 $hr(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=IT(e,n),s=IT(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=IT(e.top??e.y??0,n),s=IT(e.bottom??e.y??0,n),i=IT(e.left??e.x??0,t),a=IT(e.right??e.x??0,t);return{top:r,right:a,bottom:s,left:i,x:i+a,y:r+s}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function Mhr(e,t,n,r,s,i){const{x:a,y:l}=fH(e,[t,n,r]),{x:c,y:u}=fH({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=s-c,f=i-u;return{left:Math.floor(a),top:Math.floor(l),right:Math.floor(d),bottom:Math.floor(f)}}const dNe=(e,t,n,r,s,i)=>{const a=$hr(i,t,n),l=(t-a.x)/e.width,c=(n-a.y)/e.height,u=Math.min(l,c),d=jI(u,r,s),f=e.x+e.width/2,h=e.y+e.height/2,p=t/2-f*d,m=n/2-h*d,v=Mhr(e,p,m,d,t,n),y={left:Math.min(v.left-a.left,0),top:Math.min(v.top-a.top,0),right:Math.min(v.right-a.right,0),bottom:Math.min(v.bottom-a.bottom,0)};return{x:p-y.left+y.right,y:m-y.top+y.bottom,zoom:d}},KL=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function II(e){return e!=null&&e!=="parent"}function Q0(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function fNe(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function n$t(e,t={width:0,height:0},n,r,s){const i={...e},a=r.get(n);if(a){const l=a.origin||s;i.x+=a.internals.positionAbsolute.x-(t.width??0)*l[0],i.y+=a.internals.positionAbsolute.y-(t.height??0)*l[1]}return i}function LZe(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function Dhr(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function Lhr(e){return{...GPt,...e||{}}}function L2(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:i,y:a}=Zg(e),l=y5({x:i-(s?.left??0),y:a-(s?.top??0)},r),{x:c,y:u}=n?v5(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const hNe=e=>({width:e.offsetWidth,height:e.offsetHeight}),r$t=e=>e?.getRootNode?.()||window?.document,Fhr=["INPUT","SELECT","TEXTAREA"];function s$t(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:Fhr.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const i$t=e=>"clientX"in e,Zg=(e,t)=>{const n=i$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)}},FZe=(e,t,n,r,s)=>{const i=t.querySelectorAll(`.${e}`);return!i||!i.length?null:Array.from(i).map(a=>{const l=a.getBoundingClientRect();return{id:a.getAttribute("data-handleid"),type:e,nodeId:s,position:a.getAttribute("data-handlepos"),x:(l.left-n.left)/r,y:(l.top-n.top)/r,...hNe(a)}})};function a$t({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:s,sourceControlY:i,targetControlX:a,targetControlY:l}){const c=e*.125+s*.375+a*.375+n*.125,u=t*.125+i*.375+l*.375+r*.125,d=Math.abs(c-e),f=Math.abs(u-t);return[c,u,d,f]}function Q9(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function zZe({pos:e,x1:t,y1:n,x2:r,y2:s,c:i}){switch(e){case tr.Left:return[t-Q9(t-r,i),n];case tr.Right:return[t+Q9(r-t,i),n];case tr.Top:return[t,n-Q9(n-s,i)];case tr.Bottom:return[t,n+Q9(s-n,i)]}}function pNe({sourceX:e,sourceY:t,sourcePosition:n=tr.Bottom,targetX:r,targetY:s,targetPosition:i=tr.Top,curvature:a=.25}){const[l,c]=zZe({pos:n,x1:e,y1:t,x2:r,y2:s,c:a}),[u,d]=zZe({pos:i,x1:r,y1:s,x2:e,y2:t,c:a}),[f,h,p,m]=a$t({sourceX:e,sourceY:t,targetX:r,targetY:s,sourceControlX:l,sourceControlY:c,targetControlX:u,targetControlY:d});return[`M${e},${t} C${l},${c} ${u},${d} ${r},${s}`,f,h,p,m]}function o$t({sourceX:e,sourceY:t,targetX:n,targetY:r}){const s=Math.abs(n-e)/2,i=n<e?n+s:n-s,a=Math.abs(r-t)/2,l=r<t?r+a:r-a;return[i,l,s,a]}function zhr({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:s=!1,zIndexMode:i="basic"}){if(i==="manual")return r;const a=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 a+l}function Bhr({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const i=RQ(dH(e),dH(t));i.x===i.x2&&(i.x2+=1),i.y===i.y2&&(i.y2+=1);const a={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:r/s[2]};return QL(a,PQ(i))>0}const Uhr=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,Vhr=(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)),qhr=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||Uhr;let s;return YPt(e)?s={...e}:s={...e,id:r(e)},Vhr(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function l$t({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,i,a,l]=o$t({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,i,a,l]}const BZe={[tr.Left]:{x:-1,y:0},[tr.Right]:{x:1,y:0},[tr.Top]:{x:0,y:-1},[tr.Bottom]:{x:0,y:1}},Hhr=({source:e,sourcePosition:t=tr.Bottom,target:n})=>t===tr.Left||t===tr.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},UZe=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function Whr({source:e,sourcePosition:t=tr.Bottom,target:n,targetPosition:r=tr.Top,center:s,offset:i,stepPosition:a}){const l=BZe[t],c=BZe[r],u={x:e.x+l.x*i,y:e.y+l.y*i},d={x:n.x+c.x*i,y:n.y+c.y*i},f=Hhr({source:u,sourcePosition:t,target:d}),h=f.x!==0?"x":"y",p=f[h];let m=[],v,y;const b={x:0,y:0},x={x:0,y:0},[,,w,k]=o$t({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[h]*c[h]===-1){h==="x"?(v=s.x??u.x+(d.x-u.x)*a,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)*a);const E=[{x:v,y:u.y},{x:v,y:d.y}],N=[{x:u.x,y},{x:d.x,y}];l[h]===p?m=h==="x"?E:N:m=h==="x"?N:E}else{const E=[{x:u.x,y:d.y}],N=[{x:d.x,y:u.y}];if(h==="x"?m=l.x===p?N:E:m=l.y===p?E:N,t===r){const M=Math.abs(e[h]-n[h]);if(M<=i){const V=Math.min(i-1,i-M);l[h]===p?b[h]=(u[h]>e[h]?-1:1)*V:x[h]=(d[h]>n[h]?-1:1)*V}}if(t!==r){const M=h==="x"?"y":"x",V=l[h]===c[M],q=u[M]>d[M],H=u[M]<d[M];(l[h]===1&&(!V&&q||V&&H)||l[h]!==1&&(!V&&H||V&&q))&&(m=h==="x"?E:N)}const I={x:u.x+b.x,y:u.y+b.y},A={x:d.x+x.x,y:d.y+x.y},P=Math.max(Math.abs(I.x-m[0].x),Math.abs(A.x-m[0].x)),L=Math.max(Math.abs(I.y-m[0].y),Math.abs(A.y-m[0].y));P>=L?(v=(I.x+A.x)/2,y=m[0].y):(v=m[0].x,y=(I.y+A.y)/2)}const _={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,w,k]}function Zhr(e,t,n,r){const s=Math.min(UZe(e,t)/2,UZe(t,n)/2,r),{x:i,y:a}=t;if(e.x===i&&i===n.x||e.y===a&&a===n.y)return`L${i} ${a}`;if(e.y===a){const u=e.x<n.x?-1:1,d=e.y<n.y?1:-1;return`L ${i+s*u},${a}Q ${i},${a} ${i},${a+s*d}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${i},${a+s*c}Q ${i},${a} ${i+s*l},${a}`}function nwe({sourceX:e,sourceY:t,sourcePosition:n=tr.Bottom,targetX:r,targetY:s,targetPosition:i=tr.Top,borderRadius:a=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,h,p,m,v]=Whr({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:s},targetPosition:i,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+=Zhr(f[b-1],f[b],f[b+1],a);return y+=`L${f[f.length-1].x} ${f[f.length-1].y}`,[y,h,p,m,v]}function VZe(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function Ghr(e){const{sourceNode:t,targetNode:n}=e;if(!VZe(t)||!VZe(n))return null;const r=t.internals.handleBounds||qZe(t.handles),s=n.internals.handleBounds||qZe(n.handles),i=HZe(r?.source??[],e.sourceHandle),a=HZe(e.connectionMode===TI.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!i||!a)return e.onError?.("008",ab.error008(i?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=i?.position||tr.Bottom,c=a?.position||tr.Top,u=u_(t,i,l),d=u_(n,a,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function qZe(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 u_(e,t,n=tr.Left,r=!1){const s=(t?.x??0)+e.internals.positionAbsolute.x,i=(t?.y??0)+e.internals.positionAbsolute.y,{width:a,height:l}=t??Q0(e);if(r)return{x:s+a/2,y:i+l/2};switch(t?.position??n){case tr.Top:return{x:s+a/2,y:i};case tr.Right:return{x:s+a,y:i+l/2};case tr.Bottom:return{x:s+a/2,y:i+l};case tr.Left:return{x:s,y:i+l/2}}}function HZe(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function rwe(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function Qhr(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:s}){const i=new Set;return e.reduce((a,l)=>([l.markerStart||r,l.markerEnd||s].forEach(c=>{if(c&&typeof c=="object"){const u=rwe(c,t);i.has(u)||(a.push({id:u,color:c.color||n,...c}),i.add(u))}}),a),[]).sort((a,l)=>a.id.localeCompare(l.id))}const c$t=1e3,Khr=10,mNe={nodeOrigin:[0,0],nodeExtent:WL,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},Yhr={...mNe,checkEquality:!0};function gNe(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function Xhr(e,t,n){const r=gNe(mNe,n);for(const s of e.values())if(s.parentId)yNe(s,e,t,r);else{const i=m5(s,r.nodeOrigin),a=II(s.extent)?s.extent:r.nodeExtent,l=c_(i,a,Q0(s));s.internals.positionAbsolute=l}}function Jhr(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;const n=[],r=[];for(const s of e.handles){const i={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(i):s.type==="target"&&r.push(i)}return{source:n,target:r}}function vNe(e){return e==="manual"}function swe(e,t,n,r={}){const s=gNe(Yhr,r),i={i:0},a=new Map(t),l=s?.elevateNodesOnSelect&&!vNe(s.zIndexMode)?c$t:0;let c=e.length>0,u=!1;t.clear(),n.clear();for(const d of e){let f=a.get(d.id);if(s.checkEquality&&d===f?.internals.userNode)t.set(d.id,f);else{const h=m5(d,s.nodeOrigin),p=II(d.extent)?d.extent:s.nodeExtent,m=c_(h,p,Q0(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:Jhr(d,f),z:u$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&&yNe(f,t,n,r,i),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function epr(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 yNe(e,t,n,r,s){const{elevateNodesOnSelect:i,nodeOrigin:a,nodeExtent:l,zIndexMode:c}=gNe(mNe,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}epr(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*Khr),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=i&&!vNe(c)?c$t:0,{x:h,y:p,z:m}=tpr(e,d,a,l,f,c),{positionAbsolute:v}=e.internals,y=h!==v.x||p!==v.y;(y||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:h,y:p}:v,z:m}})}function u$t(e,t,n){const r=Wg(e.zIndex)?e.zIndex:0;return vNe(n)?r:r+(e.selected?t:0)}function tpr(e,t,n,r,s,i){const{x:a,y:l}=t.internals.positionAbsolute,c=Q0(e),u=m5(e,n),d=II(e.extent)?c_(u,e.extent,c):u;let f=c_({x:a+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=JPt(f,c,t));const h=u$t(e,s,i),p=t.internals.z??0;return{x:f.x,y:f.y,z:p>=h?p+1:h}}function bNe(e,t,n,r=[0,0]){const s=[],i=new Map;for(const a of e){const l=t.get(a.parentId);if(!l)continue;const c=i.get(a.parentId)?.expandedRect??NI(l),u=t$t(c,a.rect);i.set(a.parentId,{expandedRect:u,parent:l})}return i.size>0&&i.forEach(({expandedRect:a,parent:l},c)=>{const u=l.internals.positionAbsolute,d=Q0(l),f=l.origin??r,h=a.x<u.x?Math.round(Math.abs(u.x-a.x)):0,p=a.y<u.y?Math.round(Math.abs(u.y-a.y)):0,m=Math.max(d.width,Math.round(a.width)),v=Math.max(d.height,Math.round(a.height)),y=(m-d.width)*f[0],b=(v-d.height)*f[1];(h>0||p>0||y||b)&&(s.push({id:c,type:"position",position:{x:l.position.x-h+y,y:l.position.y-p+b}}),n.get(c)?.forEach(x=>{e.some(w=>w.id===x.id)||s.push({id:x.id,type:"position",position:{x:x.position.x+h,y:x.position.y+p}})})),(d.width<a.width||d.height<a.height||h||p)&&s.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:m+(h?f[0]*h-y:0),height:v+(p?f[1]*p-b:0)}})}),s}function npr(e,t,n,r,s,i,a){const l=r?.querySelector(".xyflow__viewport");let c=!1;if(!l)return{changes:[],updatedInternals:c};const u=[],d=window.getComputedStyle(l),{m22:f}=new window.DOMMatrixReadOnly(d.transform),h=[];for(const p of e.values()){const m=t.get(p.id);if(!m)continue;if(m.hidden){t.set(m.id,{...m,internals:{...m.internals,handleBounds:void 0}}),c=!0;continue}const v=hNe(p.nodeElement),y=m.measured.width!==v.width||m.measured.height!==v.height;if(!!(v.width&&v.height&&(y||!m.internals.handleBounds||p.force))){const x=p.nodeElement.getBoundingClientRect(),w=II(m.extent)?m.extent:i;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=JPt(k,v,t.get(m.parentId)):w&&(k=c_(k,w,v));const _={...m,measured:v,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:FZe("source",p.nodeElement,x,f,m.id),target:FZe("target",p.nodeElement,x,f,m.id)}}};t.set(m.id,_),m.parentId&&yNe(_,t,n,{nodeOrigin:s,zIndexMode:a}),c=!0,y&&(u.push({id:m.id,type:"dimensions",dimensions:v}),m.expandParent&&m.parentId&&h.push({id:m.id,parentId:m.parentId,rect:NI(_,s)}))}}if(h.length>0){const p=bNe(h,t,n,s);u.push(...p)}return{changes:u,updatedInternals:c}}async function rpr({delta:e,panZoom:t,transform:n,translateExtent:r,width:s,height:i}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const a=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[s,i]],r),l=!!a&&(a.x!==n[0]||a.y!==n[1]||a.k!==n[2]);return Promise.resolve(l)}function WZe(e,t,n,r,s,i){let a=s;const l=r.get(a)||new Map;r.set(a,l.set(n,t)),a=`${s}-${e}`;const c=r.get(a)||new Map;if(r.set(a,c.set(n,t)),i){a=`${s}-${e}-${i}`;const u=r.get(a)||new Map;r.set(a,u.set(n,t))}}function d$t(e,t,n){e.clear(),t.clear();for(const r of n){const{source:s,target:i,sourceHandle:a=null,targetHandle:l=null}=r,c={edgeId:r.id,source:s,target:i,sourceHandle:a,targetHandle:l},u=`${s}-${a}--${i}-${l}`,d=`${i}-${l}--${s}-${a}`;WZe("source",c,d,e,s,a),WZe("target",c,u,e,i,l),t.set(r.id,r)}}function f$t(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:f$t(n,t):!1}function ZZe(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 spr(e,t,n,r){const s=new Map;for(const[i,a]of e)if((a.selected||a.id===r)&&(!a.parentId||!f$t(a,e))&&(a.draggable||t&&typeof a.draggable>"u")){const l=e.get(i);l&&s.set(i,{id:i,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 oie({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){const s=[];for(const[a,l]of t){const c=n.get(a)?.internals.userNode;c&&s.push({...c,position:l.position,dragging:r})}if(!e)return[s[0],s];const i=n.get(e)?.internals.userNode;return[i?{...i,position:t.get(e)?.position||i.position,dragging:r}:s[0],s]}function ipr({dragItems:e,snapGrid:t,x:n,y:r}){const s=e.values().next().value;if(!s)return null;const i={x:n-s.distance.x,y:r-s.distance.y},a=v5(i,t);return{x:a.x-i.x,y:a.y-i.y}}function apr({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:s}){let i={x:null,y:null},a=0,l=new Map,c=!1,u={x:0,y:0},d=null,f=!1,h=null,p=!1,m=!1,v=null;function y({noDragClassName:x,handleSelector:w,domNode:k,isSelectable:_,nodeId:C,nodeClickDistance:T=0}){h=Uh(k);function E({x:P,y:L}){const{nodeLookup:M,nodeExtent:V,snapGrid:q,snapToGrid:H,nodeOrigin:B,onNodeDrag:W,onSelectionDrag:z,onError:G,updateNodePositions:F}=t();i={x:P,y:L};let R=!1;const D=l.size>1,U=D&&V?twe(g5(l)):null,Q=D&&H?ipr({dragItems:l,snapGrid:q,x:P,y:L}):null;for(const[ee,J]of l){if(!M.has(ee))continue;let te={x:P-J.distance.x,y:L-J.distance.y};H&&(te=Q?{x:Math.round(te.x+Q.x),y:Math.round(te.y+Q.y)}:v5(te,q));let re=null;if(D&&V&&!J.extent&&U){const{positionAbsolute:ne}=J.internals,se=ne.x-U.x+V[0][0],le=ne.x+J.measured.width-U.x2+V[1][0],he=ne.y-U.y+V[0][1],pe=ne.y+J.measured.height-U.y2+V[1][1];re=[[se,he],[le,pe]]}const{position:ce,positionAbsolute:X}=XPt({nodeId:ee,nextPosition:te,nodeLookup:M,nodeExtent:re||V,nodeOrigin:B,onError:G});R=R||J.position.x!==ce.x||J.position.y!==ce.y,J.position=ce,J.internals.positionAbsolute=X}if(m=m||R,!!R&&(F(l,!0),v&&(r||W||!C&&z))){const[ee,J]=oie({nodeId:C,dragItems:l,nodeLookup:M});r?.(v,l,ee,J),W?.(v,ee,J),C||z?.(v,J)}}async function N(){if(!d)return;const{transform:P,panBy:L,autoPanSpeed:M,autoPanOnNodeDrag:V}=t();if(!V){c=!1,cancelAnimationFrame(a);return}const[q,H]=e$t(u,d,M);(q!==0||H!==0)&&(i.x=(i.x??0)-q/P[2],i.y=(i.y??0)-H/P[2],await L({x:q,y:H})&&E(i)),a=requestAnimationFrame(N)}function I(P){const{nodeLookup:L,multiSelectionActive:M,nodesDraggable:V,transform:q,snapGrid:H,snapToGrid:B,selectNodesOnDrag:W,onNodeDragStart:z,onSelectionDragStart:G,unselectNodesAndEdges:F}=t();f=!0,(!W||!_)&&!M&&C&&(L.get(C)?.selected||F()),_&&W&&C&&e?.(C);const R=L2(P.sourceEvent,{transform:q,snapGrid:H,snapToGrid:B,containerBounds:d});if(i=R,l=spr(L,V,R,C),l.size>0&&(n||z||!C&&G)){const[D,U]=oie({nodeId:C,dragItems:l,nodeLookup:L});n?.(P.sourceEvent,l,D,U),z?.(P.sourceEvent,D,U),C||G?.(P.sourceEvent,U)}}const A=IPt().clickDistance(T).on("start",P=>{const{domNode:L,nodeDragThreshold:M,transform:V,snapGrid:q,snapToGrid:H}=t();d=L?.getBoundingClientRect()||null,p=!1,m=!1,v=P.sourceEvent,M===0&&I(P),i=L2(P.sourceEvent,{transform:V,snapGrid:q,snapToGrid:H,containerBounds:d}),u=Zg(P.sourceEvent,d)}).on("drag",P=>{const{autoPanOnNodeDrag:L,transform:M,snapGrid:V,snapToGrid:q,nodeDragThreshold:H,nodeLookup:B}=t(),W=L2(P.sourceEvent,{transform:M,snapGrid:V,snapToGrid:q,containerBounds:d});if(v=P.sourceEvent,(P.sourceEvent.type==="touchmove"&&P.sourceEvent.touches.length>1||C&&!B.has(C))&&(p=!0),!p){if(!c&&L&&f&&(c=!0,N()),!f){const z=Zg(P.sourceEvent,d),G=z.x-u.x,F=z.y-u.y;Math.sqrt(G*G+F*F)>H&&I(P)}(i.x!==W.xSnapped||i.y!==W.ySnapped)&&l&&f&&(u=Zg(P.sourceEvent,d),E(W))}}).on("end",P=>{if(!(!f||p)&&(c=!1,f=!1,cancelAnimationFrame(a),l.size>0)){const{nodeLookup:L,updateNodePositions:M,onNodeDragStop:V,onSelectionDragStop:q}=t();if(m&&(M(l,!1),m=!1),s||V||!C&&q){const[H,B]=oie({nodeId:C,dragItems:l,nodeLookup:L,dragging:!1});s?.(P.sourceEvent,l,H,B),V?.(P.sourceEvent,H,B),C||q?.(P.sourceEvent,B)}}}).filter(P=>{const L=P.target;return!P.button&&(!x||!ZZe(L,`.${x}`,k))&&(!w||ZZe(L,w,k))});h.call(A)}function b(){h?.on(".drag",null)}return{update:y,destroy:b}}function opr(e,t,n){const r=[],s={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const i of t.values())QL(s,NI(i))>0&&r.push(i);return r}const lpr=250;function cpr(e,t,n,r){let s=[],i=1/0;const a=opr(e,n,t+lpr);for(const l of a){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}=u_(l,u,u.position,!0),h=Math.sqrt(Math.pow(d-e.x,2)+Math.pow(f-e.y,2));h>t||(h<i?(s=[{...u,x:d,y:f}],i=h):h===i&&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 h$t(e,t,n,r,s,i=!1){const a=r.get(e);if(!a)return null;const l=s==="strict"?a.internals.handleBounds?.[t]:[...a.internals.handleBounds?.source??[],...a.internals.handleBounds?.target??[]],c=(n?l?.find(u=>u.id===n):l?.[0])??null;return c&&i?{...c,...u_(a,c,c.position,!0)}:c}function p$t(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function upr(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const m$t=()=>!0;function dpr(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:i,isTarget:a,domNode:l,nodeLookup:c,lib:u,autoPanOnConnect:d,flowId:f,panBy:h,cancelConnection:p,onConnectStart:m,onConnect:v,onConnectEnd:y,isValidConnection:b=m$t,onReconnectEnd:x,updateConnection:w,getTransform:k,getFromHandle:_,autoPanSpeed:C,dragThreshold:T=1,handleDomNode:E}){const N=r$t(e.target);let I=0,A;const{x:P,y:L}=Zg(e),M=p$t(i,E),V=l?.getBoundingClientRect();let q=!1;if(!V||!M)return;const H=h$t(s,M,r,c,t);if(!H)return;let B=Zg(e,V),W=!1,z=null,G=!1,F=null;function R(){if(!d||!V)return;const[ce,X]=e$t(B,V,C);h({x:ce,y:X}),I=requestAnimationFrame(R)}const D={...H,nodeId:s,type:M,position:H.position},U=c.get(s);let ee={inProgress:!0,isValid:null,from:u_(U,D,tr.Left,!0),fromHandle:D,fromPosition:D.position,fromNode:U,to:B,toHandle:null,toPosition:$Ze[D.position],toNode:null,pointer:B};function J(){q=!0,w(ee),m?.(e,{nodeId:s,handleId:r,handleType:M})}T===0&&J();function te(ce){if(!q){const{x:pe,y:Se}=Zg(ce),Ee=pe-P,Re=Se-L;if(!(Ee*Ee+Re*Re>T*T))return;J()}if(!_()||!D){re(ce);return}const X=k();B=Zg(ce,V),A=cpr(y5(B,X,!1,[1,1]),n,c,D),W||(R(),W=!0);const ne=g$t(ce,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:a?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});F=ne.handleDomNode,z=ne.connection,G=upr(!!A,ne.isValid);const se=c.get(s),le=se?u_(se,D,tr.Left,!0):ee.from,he={...ee,from:le,isValid:G,to:ne.toHandle&&G?fH({x:ne.toHandle.x,y:ne.toHandle.y},X):B,toHandle:ne.toHandle,toPosition:G&&ne.toHandle?ne.toHandle.position:$Ze[D.position],toNode:ne.toHandle?c.get(ne.toHandle.nodeId):null,pointer:B};w(he),ee=he}function re(ce){if(!("touches"in ce&&ce.touches.length>0)){if(q){(A||F)&&z&&G&&v?.(z);const{inProgress:X,...ne}=ee,se={...ne,toPosition:ee.toHandle?ee.toPosition:null};y?.(ce,se),i&&x?.(ce,se)}p(),cancelAnimationFrame(I),W=!1,G=!1,z=null,F=null,N.removeEventListener("mousemove",te),N.removeEventListener("mouseup",re),N.removeEventListener("touchmove",te),N.removeEventListener("touchend",re)}}N.addEventListener("mousemove",te),N.addEventListener("mouseup",re),N.addEventListener("touchmove",te),N.addEventListener("touchend",re)}function g$t(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:i,doc:a,lib:l,flowId:c,isValidConnection:u=m$t,nodeLookup:d}){const f=i==="target",h=t?a.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:p,y:m}=Zg(e),v=a.elementFromPoint(p,m),y=v?.classList.contains(`${l}-flow__handle`)?v:h,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){const x=p$t(void 0,y),w=y.getAttribute("data-nodeid"),k=y.getAttribute("data-handleid"),_=y.classList.contains("connectable"),C=y.classList.contains("connectableend");if(!w||!x)return b;const T={source:f?w:r,sourceHandle:f?k:s,target:f?r:w,targetHandle:f?s:k};b.connection=T;const N=_&&C&&(n===TI.Strict?f&&x==="source"||!f&&x==="target":w!==r||k!==s);b.isValid=N&&u(T),b.toHandle=h$t(w,x,k,d,n,!0)}return b}const iwe={onPointerDown:dpr,isValid:g$t};function fpr({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Uh(e);function i({translateExtent:l,width:c,height:u,zoomStep:d=1,pannable:f=!0,zoomable:h=!0,inversePan:p=!1}){const m=w=>{if(w.sourceEvent.type!=="wheel"||!t)return;const k=n(),_=w.sourceEvent.ctrlKey&&KL()?10:1,C=-w.sourceEvent.deltaY*(w.sourceEvent.deltaMode===1?.05:w.sourceEvent.deltaMode?1:.002)*d,T=k[2]*Math.pow(2,C*_);t.scaleTo(T)};let v=[0,0];const y=w=>{(w.sourceEvent.type==="mousedown"||w.sourceEvent.type==="touchstart")&&(v=[w.sourceEvent.clientX??w.sourceEvent.touches[0].clientX,w.sourceEvent.clientY??w.sourceEvent.touches[0].clientY])},b=w=>{const k=n();if(w.sourceEvent.type!=="mousemove"&&w.sourceEvent.type!=="touchmove"||!t)return;const _=[w.sourceEvent.clientX??w.sourceEvent.touches[0].clientX,w.sourceEvent.clientY??w.sourceEvent.touches[0].clientY],C=[_[0]-v[0],_[1]-v[1]];v=_;const T=r()*Math.max(k[2],Math.log(k[2]))*(p?-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=WPt().on("start",y).on("zoom",f?b:null).on("zoom.wheel",h?m:null);s.call(x,{})}function a(){s.on("zoom",null)}return{update:i,destroy:a,pointer:$g}}const $Q=e=>({x:e.x,y:e.y,zoom:e.k}),lie=({x:e,y:t,zoom:n})=>AQ.translate(e,t).scale(n),Fj=(e,t)=>e.target.closest(`.${t}`),v$t=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),hpr=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,cie=(e,t=0,n=hpr,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},y$t=e=>{const t=e.ctrlKey&&KL()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function ppr({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:i,zoomOnPinch:a,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(Fj(d,t))return d.ctrlKey&&d.preventDefault(),!1;d.preventDefault(),d.stopImmediatePropagation();const f=n.property("__zoom").k||1;if(d.ctrlKey&&a){const y=$g(d),b=y$t(d),x=f*Math.pow(2,b);r.scaleTo(n,x,y,d);return}const h=d.deltaMode===1?20:1;let p=s===pC.Vertical?0:d.deltaX*h,m=s===pC.Horizontal?0:d.deltaY*h;!KL()&&d.shiftKey&&s!==pC.Vertical&&(p=d.deltaY*h,m=0),r.translateBy(n,-(p/f)*i,-(m/f)*i,{internal:!0});const v=$Q(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 mpr({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const i=r.type==="wheel",a=!t&&i&&!r.ctrlKey,l=Fj(r,e);if(r.ctrlKey&&i&&l&&r.preventDefault(),a||l)return null;r.preventDefault(),n.call(this,r,s)}}function gpr({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=$Q(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 vpr({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return i=>{e.usedRightMouseButton=!!(n&&v$t(t,e.mouseButton??0)),i.sourceEvent?.sync||r([i.transform.x,i.transform.y,i.transform.k]),s&&!i.sourceEvent?.internal&&s?.(i.sourceEvent,$Q(i.transform))}}function ypr({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:i}){return a=>{if(!a.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,i&&v$t(t,e.mouseButton??0)&&!e.usedRightMouseButton&&a.sourceEvent&&i(a.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=$Q(a.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(a.sourceEvent,l)},n?150:0)}}}function bpr({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:s,zoomOnDoubleClick:i,userSelectionActive:a,noWheelClassName:l,noPanClassName:c,lib:u,connectionInProgress:d}){return f=>{const h=e||t,p=n&&f.ctrlKey,m=f.type==="wheel";if(f.button===1&&f.type==="mousedown"&&(Fj(f,`${u}-flow__node`)||Fj(f,`${u}-flow__edge`)))return!0;if(!r&&!h&&!s&&!i&&!n||a||d&&!m||Fj(f,l)&&m||Fj(f,c)&&(!m||s&&m&&!e)||!n&&f.ctrlKey&&m)return!1;if(!n&&f.type==="touchstart"&&f.touches?.length>1)return f.preventDefault(),!1;if(!h&&!s&&!p&&m||!r&&(f.type==="mousedown"||f.type==="touchstart")||Array.isArray(r)&&!r.includes(f.button)&&f.type==="mousedown")return!1;const v=Array.isArray(r)&&r.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||m)&&v}}function xpr({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:s,onPanZoom:i,onPanZoomStart:a,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=WPt().scaleExtent([t,n]).translateExtent(r),h=Uh(e).call(f);x({x:s.x,y:s.y,zoom:jI(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const p=h.on("wheel.zoom"),m=h.on("dblclick.zoom");f.wheelDelta(y$t);function v(A,P){return h?new Promise(L=>{f?.interpolate(P?.interpolate==="linear"?t0:A7).transform(cie(h,P?.duration,P?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:P,onPaneContextMenu:L,userSelectionActive:M,panOnScroll:V,panOnDrag:q,panOnScrollMode:H,panOnScrollSpeed:B,preventScrolling:W,zoomOnPinch:z,zoomOnScroll:G,zoomOnDoubleClick:F,zoomActivationKeyPressed:R,lib:D,onTransformChange:U,connectionInProgress:Q,paneClickDistance:ee,selectionOnDrag:J}){M&&!u.isZoomingOrPanning&&b();const te=V&&!R&&!M;f.clickDistance(J?1/0:!Wg(ee)||ee<0?0:ee);const re=te?ppr({zoomPanValues:u,noWheelClassName:A,d3Selection:h,d3Zoom:f,panOnScrollMode:H,panOnScrollSpeed:B,zoomOnPinch:z,onPanZoomStart:a,onPanZoom:i,onPanZoomEnd:l}):mpr({noWheelClassName:A,preventScrolling:W,d3ZoomHandler:p});if(h.on("wheel.zoom",re,{passive:!1}),!M){const X=gpr({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:a});f.on("start",X);const ne=vpr({zoomPanValues:u,panOnDrag:q,onPaneContextMenu:!!L,onPanZoom:i,onTransformChange:U});f.on("zoom",ne);const se=ypr({zoomPanValues:u,panOnDrag:q,panOnScroll:V,onPaneContextMenu:L,onPanZoomEnd:l,onDraggingChange:c});f.on("end",se)}const ce=bpr({zoomActivationKeyPressed:R,panOnDrag:q,zoomOnScroll:G,panOnScroll:V,zoomOnDoubleClick:F,zoomOnPinch:z,userSelectionActive:M,noPanClassName:P,noWheelClassName:A,lib:D,connectionInProgress:Q});f.filter(ce),F?h.on("dblclick.zoom",m):h.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,P,L){const M=lie(A),V=f?.constrain()(M,P,L);return V&&await v(V),new Promise(q=>q(V))}async function w(A,P){const L=lie(A);return await v(L,P),new Promise(M=>M(L))}function k(A){if(h){const P=lie(A),L=h.property("__zoom");(L.k!==A.zoom||L.x!==A.x||L.y!==A.y)&&f?.transform(h,P,null,{sync:!0})}}function _(){const A=h?HPt(h.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function C(A,P){return h?new Promise(L=>{f?.interpolate(P?.interpolate==="linear"?t0:A7).scaleTo(cie(h,P?.duration,P?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function T(A,P){return h?new Promise(L=>{f?.interpolate(P?.interpolate==="linear"?t0:A7).scaleBy(cie(h,P?.duration,P?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function E(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const P=!Wg(A)||A<0?0:A;f?.clickDistance(P)}return{update:y,destroy:b,setViewport:w,setViewportConstrained:x,getViewport:_,scaleTo:C,scaleBy:T,setScaleExtent:E,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var AI;(function(e){e.Line="line",e.Handle="handle"})(AI||(AI={}));function wpr({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:s,affectsY:i}){const a=e-t,l=n-r,c=[a>0?1:a<0?-1:0,l>0?1:l<0?-1:0];return a&&s&&(c[0]=c[0]*-1),l&&i&&(c[1]=c[1]*-1),c}function GZe(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 Vw(e,t){return Math.max(0,t-e)}function qw(e,t){return Math.max(0,e-t)}function K9(e,t,n){return Math.max(0,t-e,e-n)}function QZe(e,t){return e?!t:t}function Spr(e,t,n,r,s,i,a,l){let{affectsX:c,affectsY:u}=t;const{isHorizontal:d,isVertical:f}=t,h=d&&f,{xSnapped:p,ySnapped:m}=n,{minWidth:v,maxWidth:y,minHeight:b,maxHeight:x}=r,{x:w,y:k,width:_,height:C,aspectRatio:T}=e;let E=Math.floor(d?p-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=_+(c?-E:E),A=C+(u?-N:N),P=-i[0]*_,L=-i[1]*C;let M=K9(I,v,y),V=K9(A,b,x);if(a){let B=0,W=0;c&&E<0?B=Vw(w+E+P,a[0][0]):!c&&E>0&&(B=qw(w+I+P,a[1][0])),u&&N<0?W=Vw(k+N+L,a[0][1]):!u&&N>0&&(W=qw(k+A+L,a[1][1])),M=Math.max(M,B),V=Math.max(V,W)}if(l){let B=0,W=0;c&&E>0?B=qw(w+E,l[0][0]):!c&&E<0&&(B=Vw(w+I,l[1][0])),u&&N>0?W=qw(k+N,l[0][1]):!u&&N<0&&(W=Vw(k+A,l[1][1])),M=Math.max(M,B),V=Math.max(V,W)}if(s){if(d){const B=K9(I/T,b,x)*T;if(M=Math.max(M,B),a){let W=0;!c&&!u||c&&!u&&h?W=qw(k+L+I/T,a[1][1])*T:W=Vw(k+L+(c?E:-E)/T,a[0][1])*T,M=Math.max(M,W)}if(l){let W=0;!c&&!u||c&&!u&&h?W=Vw(k+I/T,l[1][1])*T:W=qw(k+(c?E:-E)/T,l[0][1])*T,M=Math.max(M,W)}}if(f){const B=K9(A*T,v,y)/T;if(V=Math.max(V,B),a){let W=0;!c&&!u||u&&!c&&h?W=qw(w+A*T+P,a[1][0])/T:W=Vw(w+(u?N:-N)*T+P,a[0][0])/T,V=Math.max(V,W)}if(l){let W=0;!c&&!u||u&&!c&&h?W=Vw(w+A*T,l[1][0])/T:W=qw(w+(u?N:-N)*T,l[0][0])/T,V=Math.max(V,W)}}}N=N+(N<0?V:-V),E=E+(E<0?M:-M),s&&(h?I>A*T?N=(QZe(c,u)?-E:E)/T:E=(QZe(c,u)?-N:N)*T:d?(N=E/T,u=c):(E=N*T,c=u));const q=c?w+E:w,H=u?k+N:k;return{width:_+(c?-E:E),height:C+(u?-N:N),x:i[0]*E*(c?-1:1)+q,y:i[1]*N*(u?-1:1)+H}}const b$t={width:0,height:0,x:0,y:0},kpr={...b$t,pointerX:0,pointerY:0,aspectRatio:1};function Opr(e){return[[0,0],[e.measured.width,e.measured.height]]}function Cpr(e,t,n){const r=t.position.x+e.position.x,s=t.position.y+e.position.y,i=e.measured.width??0,a=e.measured.height??0,l=n[0]*i,c=n[1]*a;return[[r-l,s-c],[r+i-l,s+a-c]]}function _pr({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const i=Uh(e);let a={controlDirection:GZe("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:u,boundaries:d,keepAspectRatio:f,resizeDirection:h,onResizeStart:p,onResize:m,onResizeEnd:v,shouldResize:y}){let b={...b$t},x={...kpr};a={boundaries:d,resizeDirection:h,keepAspectRatio:f,controlDirection:GZe(u)};let w,k=null,_=[],C,T,E,N=!1;const I=IPt().on("start",A=>{const{nodeLookup:P,transform:L,snapGrid:M,snapToGrid:V,nodeOrigin:q,paneDomNode:H}=n();if(w=P.get(t),!w)return;k=H?.getBoundingClientRect()??null;const{xSnapped:B,ySnapped:W}=L2(A.sourceEvent,{transform:L,snapGrid:M,snapToGrid:V,containerBounds:k});b={width:w.measured.width??0,height:w.measured.height??0,x:w.position.x??0,y:w.position.y??0},x={...b,pointerX:B,pointerY:W,aspectRatio:b.width/b.height},C=void 0,w.parentId&&(w.extent==="parent"||w.expandParent)&&(C=P.get(w.parentId),T=C&&w.extent==="parent"?Opr(C):void 0),_=[],E=void 0;for(const[z,G]of P)if(G.parentId===t&&(_.push({id:z,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const F=Cpr(G,w,G.origin??q);E?E=[[Math.min(F[0][0],E[0][0]),Math.min(F[0][1],E[0][1])],[Math.max(F[1][0],E[1][0]),Math.max(F[1][1],E[1][1])]]:E=F}p?.(A,{...b})}).on("drag",A=>{const{transform:P,snapGrid:L,snapToGrid:M,nodeOrigin:V}=n(),q=L2(A.sourceEvent,{transform:P,snapGrid:L,snapToGrid:M,containerBounds:k}),H=[];if(!w)return;const{x:B,y:W,width:z,height:G}=b,F={},R=w.origin??V,{width:D,height:U,x:Q,y:ee}=Spr(x,a.controlDirection,q,a.boundaries,a.keepAspectRatio,R,T,E),J=D!==z,te=U!==G,re=Q!==B&&J,ce=ee!==W&&te;if(!re&&!ce&&!J&&!te)return;if((re||ce||R[0]===1||R[1]===1)&&(F.x=re?Q:b.x,F.y=ce?ee:b.y,b.x=F.x,b.y=F.y,_.length>0)){const le=Q-B,he=ee-W;for(const pe of _)pe.position={x:pe.position.x-le+R[0]*(D-z),y:pe.position.y-he+R[1]*(U-G)},H.push(pe)}if((J||te)&&(F.width=J&&(!a.resizeDirection||a.resizeDirection==="horizontal")?D:b.width,F.height=te&&(!a.resizeDirection||a.resizeDirection==="vertical")?U:b.height,b.width=F.width,b.height=F.height),C&&w.expandParent){const le=R[0]*(F.width??0);F.x&&F.x<le&&(b.x=le,x.x=x.x-(F.x-le));const he=R[1]*(F.height??0);F.y&&F.y<he&&(b.y=he,x.y=x.y-(F.y-he))}const X=wpr({width:b.width,prevWidth:z,height:b.height,prevHeight:G,affectsX:a.controlDirection.affectsX,affectsY:a.controlDirection.affectsY}),ne={...b,direction:X};y?.(A,ne)!==!1&&(N=!0,m?.(A,ne),r(F,H))}).on("end",A=>{N&&(v?.(A,{...b}),s?.({...b}),N=!1)});i.call(I)}function c(){i.on(".drag",null)}return{update:l,destroy:c}}const Epr={},KZe=e=>{let t;const n=new Set,r=(d,f)=>{const h=typeof d=="function"?d(t):d;if(!Object.is(h,t)){const p=t;t=f??(typeof h!="object"||h===null)?h:Object.assign({},t,h),n.forEach(m=>m(t,p))}},s=()=>t,c={setState:r,getState:s,getInitialState:()=>u,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(Epr?"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},Tpr=e=>e?KZe(e):KZe,{useDebugValue:jpr}=Me,{useSyncExternalStoreWithSelector:Npr}=P4n,Ipr=e=>e;function x$t(e,t=Ipr,n){const r=Npr(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return jpr(r),r}const YZe=(e,t)=>{const n=Tpr(e),r=(s,i=t)=>x$t(n,s,i);return Object.assign(r,n),r},Apr=(e,t)=>e?YZe(e,t):YZe;function Wa(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 MQ=g.createContext(null),Rpr=MQ.Provider,w$t=ab.error001();function rs(e,t){const n=g.useContext(MQ);if(n===null)throw new Error(w$t);return x$t(n,e,t)}function Io(){const e=g.useContext(MQ);if(e===null)throw new Error(w$t);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const XZe={display:"none"},Ppr={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},S$t="react-flow__node-desc",k$t="react-flow__edge-desc",$pr="react-flow__aria-live",Mpr=e=>e.ariaLiveMessage,Dpr=e=>e.ariaLabelConfig;function Lpr({rfId:e}){const t=rs(Mpr);return o.jsx("div",{id:`${$pr}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:Ppr,children:t})}function Fpr({rfId:e,disableKeyboardA11y:t}){const n=rs(Dpr);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${S$t}-${e}`,style:XZe,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${k$t}-${e}`,style:XZe,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(Lpr,{rfId:e})]})}const b5=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},i)=>{const a=`${e}`.split("-");return o.jsx("div",{className:Hl(["react-flow__panel",n,...a]),style:r,ref:i,...s,children:t})});b5.displayName="Panel";function zpr({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(b5,{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 Bpr=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}},Y9=e=>e.id;function Upr(e,t){return Wa(e.selectedNodes.map(Y9),t.selectedNodes.map(Y9))&&Wa(e.selectedEdges.map(Y9),t.selectedEdges.map(Y9))}function Vpr({onSelectionChange:e}){const t=Io(),{selectedNodes:n,selectedEdges:r}=rs(Bpr,Upr);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(i=>i(s))},[n,r,e]),null}const qpr=e=>!!e.onSelectionChangeHandlers;function Hpr({onSelectionChange:e}){const t=rs(qpr);return e||t?o.jsx(Vpr,{onSelectionChange:e}):null}const awe=typeof window<"u"?g.useLayoutEffect:g.useEffect,O$t=[0,0],Wpr={x:0,y:0,zoom:1},Zpr=["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"],JZe=[...Zpr,"rfId"],Gpr=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}),eGe={translateExtent:WL,nodeOrigin:O$t,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function Qpr(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:i,setNodeExtent:a,reset:l,setDefaultNodesAndEdges:c}=rs(Gpr,Wa),u=Io();awe(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=eGe,l()}),[]);const d=g.useRef(eGe);return awe(()=>{for(const f of JZe){const h=e[f],p=d.current[f];h!==p&&(typeof e[f]>"u"||(f==="nodes"?t(h):f==="edges"?n(h):f==="minZoom"?r(h):f==="maxZoom"?s(h):f==="translateExtent"?i(h):f==="nodeExtent"?a(h):f==="ariaLabelConfig"?u.setState({ariaLabelConfig:Lhr(h)}):f==="fitView"?u.setState({fitViewQueued:h}):f==="fitViewOptions"?u.setState({fitViewOptions:h}):u.setState({[f]:h})))}d.current=e},JZe.map(f=>e[f])),null}function tGe(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function Kpr(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=tGe(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:tGe()?.matches?"dark":"light"}const nGe=typeof document<"u"?document:null;function YL(e=null,t={target:nGe,actInsideInputWithModifier:!0}){const[n,r]=g.useState(!1),s=g.useRef(!1),i=g.useRef(new Set([])),[a,l]=g.useMemo(()=>{if(e!==null){const u=(Array.isArray(e)?e:[e]).filter(f=>typeof f=="string").map(f=>f.replace("+",`
231
+ `: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 Plr(this):new Ilr(this)}getCursor(t,n=0,r){let s=t.doc?t:gs.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?pj(this,s,n,r):hj(this,s,n,r)}}class oPt{constructor(t){this.spec=t}}function jlr(e,t,n){return(r,s,i,a)=>{if(n&&!n(r,s,i,a))return!1;let l=r>=a&&s<=a+i.length?i.slice(r-a,s-a):t.doc.sliceString(r,s);return e(l,t,r,s)}}function hj(e,t,n,r){let s;return e.wholeWord&&(s=Nlr(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=jlr(e.test,t,s)),new S0(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:i=>i.toLowerCase(),s)}function Nlr(e,t){return(n,r,s,i)=>((i>n||i+s.length<r)&&(i=Math.max(0,n-2),s=e.sliceString(i,Math.min(e.length,r+2))),(t(eH(s,n-i))!=Oo.Word||t(tH(s,n-i))!=Oo.Word)&&(t(tH(s,r-i))!=Oo.Word||t(eH(s,r-i))!=Oo.Word))}class Ilr extends oPt{constructor(t){super(t)}nextMatch(t,n,r){let s=hj(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let i=Math.min(t.doc.length,n+this.spec.unquoted.length);s=hj(this.spec,t,0,i).nextOverlapping()}return s.done||s.value.from==n&&s.value.to==r?null:s.value}prevMatchInRange(t,n,r){for(let s=r;;){let i=Math.max(n,s-1e4-this.spec.unquoted.length),a=hj(this.spec,t,i,s),l=null;for(;!a.nextOverlapping().done;)l=a.value;if(l)return l;if(i==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=hj(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 i=hj(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!i.next().done;)s(i.value.from,i.value.to)}}function Alr(e,t,n){return(r,s,i)=>(!n||n(r,s,i))&&e(i[0],t,r,s)}function pj(e,t,n,r){let s;return e.wholeWord&&(s=Rlr(t.charCategorizer(t.selection.main.head))),e.test&&(s=Alr(e.test,t,s)),new sPt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function eH(e,t){return e.slice(Rc(e,t,!1),t)}function tH(e,t){return e.slice(t,Rc(e,t))}function Rlr(e){return(t,n,r)=>!r[0].length||(e(eH(r.input,r.index))!=Oo.Word||e(tH(r.input,r.index))!=Oo.Word)&&(e(tH(r.input,r.index+r[0].length))!=Oo.Word||e(eH(r.input,r.index+r[0].length))!=Oo.Word)}class Plr extends oPt{nextMatch(t,n,r){let s=pj(this.spec,t,r,t.doc.length).next();return s.done&&(s=pj(this.spec,t,0,n).next()),s.done?null:s.value}prevMatchInRange(t,n,r){for(let s=1;;s++){let i=Math.max(n,r-s*1e4),a=pj(this.spec,t,i,r),l=null;for(;!a.next().done;)l=a.value;if(l&&(i==n||l.from>i+10))return l;if(i==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 i=+r.slice(0,s);if(i>0&&i<t.match.length)return t.match[i]+r.slice(s)}return n})}matchAll(t,n){let r=pj(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 i=pj(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!i.next().done;)s(i.value.from,i.value.to)}}const FL=hr.define(),Yje=hr.define(),zS=Ol.define({create(e){return new Xse(H0e(e).create(),null)},update(e,t){for(let n of t.effects)n.is(FL)?e=new Xse(n.value.create(),e.panel):n.is(Yje)&&(e=new Xse(e.query,n.value?Xje:null));return e},provide:e=>jL.from(e,t=>t.panel)});class Xse{constructor(t,n){this.query=t,this.panel=n}}const $lr=Nn.mark({class:"cm-searchMatch"}),Mlr=Nn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),Dlr=To.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(zS))}update(e){let t=e.state.field(zS);(t!=e.startState.field(zS)||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 rd;for(let s=0,i=n.visibleRanges,a=i.length;s<a;s++){let{from:l,to:c}=i[s];for(;s<a-1&&c>i[s+1].from-500;)c=i[++s].to;e.highlight(n.state,l,c,(u,d)=>{let f=n.state.selection.ranges.some(h=>h.from==u&&h.to==d);r.add(u,d,f?Mlr:$lr)})}return r.finish()}},{decorations:e=>e.decorations});function f5(e){return t=>{let n=t.state.field(zS,!1);return n&&n.query.spec.valid?e(t,n):uPt(t)}}const nH=f5((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),i=e.state.facet(eR);return e.dispatch({selection:s,effects:[Jje(e,r),i.scrollToMatch(s.main,e)],userEvent:"select.search"}),cPt(e),!0}),rH=f5((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let i=wt.single(s.from,s.to),a=e.state.facet(eR);return e.dispatch({selection:i,effects:[Jje(e,s),a.scrollToMatch(i.main,e)],userEvent:"select.search"}),cPt(e),!0}),Llr=f5((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)}),Flr=({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,i=[],a=0;for(let l=new S0(e.doc,e.sliceDoc(r,s));!l.next().done;){if(i.length>1e3)return!1;l.value.from==r&&(a=i.length),i.push(wt.range(l.value.from,l.value.to))}return t(e.update({selection:wt.create(i,a),userEvent:"select.search.matches"})),!0},rZe=f5((e,{query:t})=>{let{state:n}=e,{from:r,to:s}=n.selection.main;if(n.readOnly)return!1;let i=t.nextMatch(n,r,r);if(!i)return!1;let a=i,l=[],c,u,d=[];a.precise?a.from==r&&a.to==s&&(u=n.toText(t.getReplacement(a)),l.push({from:a.from,to:a.to,insert:u}),a=t.nextMatch(n,a.from,a.to),d.push(Rt.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+"."))):a=t.nextMatch(n,a.from,a.to);let f=e.state.changes(l);return a&&(c=wt.single(a.from,a.to).map(f),d.push(Jje(e,a)),d.push(n.facet(eR).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),zlr=f5((e,{query:t})=>{if(e.state.readOnly)return!1;let n=[];for(let s of t.matchAll(e.state,1e9)){let{from:i,to:a,precise:l}=s;l&&n.push({from:i,to:a,insert:t.getReplacement(s)})}if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:Rt.announce.of(r),userEvent:"input.replace.all"}),!0});function Xje(e){return e.state.facet(eR).createPanel(e)}function H0e(e,t){var n,r,s,i,a;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(eR);return new aPt({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:(i=t?.regexp)!==null&&i!==void 0?i:u.regexp,wholeWord:(a=t?.wholeWord)!==null&&a!==void 0?a:u.wholeWord})}function lPt(e){let t=mje(e,Xje);return t&&t.dom.querySelector("[main-field]")}function cPt(e){let t=lPt(e);t&&t==e.root.activeElement&&t.select()}const uPt=e=>{let t=e.state.field(zS,!1);if(t&&t.panel){let n=lPt(e);if(n&&n!=e.root.activeElement){let r=H0e(e.state,t.query.spec);r.valid&&e.dispatch({effects:FL.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[Yje.of(!0),t?FL.of(H0e(e.state,t.query.spec)):hr.appendConfig.of(qlr)]});return!0},dPt=e=>{let t=e.state.field(zS,!1);if(!t||!t.panel)return!1;let n=mje(e,Xje);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:Yje.of(!1)}),!0},Blr=[{key:"Mod-f",run:uPt,scope:"editor search-panel"},{key:"F3",run:nH,shift:rH,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:nH,shift:rH,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:dPt,scope:"editor search-panel"},{key:"Mod-Shift-l",run:Flr},{key:"Mod-Alt-g",run:vlr},{key:"Mod-d",run:Tlr,preventDefault:!0}];class Ulr{constructor(t){this.view=t;let n=this.query=t.state.field(zS).query.spec;this.commit=this.commit.bind(this),this.searchField=pa("input",{value:n.search,placeholder:Oh(t,"Find"),"aria-label":Oh(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=pa("input",{value:n.replace,placeholder:Oh(t,"Replace"),"aria-label":Oh(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=pa("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=pa("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=pa("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,i,a){return pa("button",{class:"cm-button",name:s,onclick:i,type:"button"},a)}this.dom=pa("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>nH(t),[Oh(t,"next")]),r("prev",()=>rH(t),[Oh(t,"previous")]),r("select",()=>Llr(t),[Oh(t,"all")]),pa("label",null,[this.caseField,Oh(t,"match case")]),pa("label",null,[this.reField,Oh(t,"regexp")]),pa("label",null,[this.wordField,Oh(t,"by word")]),...t.state.readOnly?[]:[pa("br"),this.replaceField,r("replace",()=>rZe(t),[Oh(t,"replace")]),r("replaceAll",()=>zlr(t),[Oh(t,"replace all")])],pa("button",{name:"close",onclick:()=>dPt(t),"aria-label":Oh(t,"close"),type:"button"},["×"])])}commit(){let t=new aPt({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:FL.of(t)}))}keydown(t){otr(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?rH:nH)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),rZe(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(FL)&&!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(eR).top}}function Oh(e,t){return e.state.phrase(t)}const B9=30,U9=/[\s\.,:;?!]/;function Jje(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),s=e.state.doc.lineAt(n).to,i=Math.max(r.from,t-B9),a=Math.min(s,n+B9),l=e.state.sliceDoc(i,a);if(i!=r.from){for(let c=0;c<B9;c++)if(!U9.test(l[c+1])&&U9.test(l[c])){l=l.slice(c);break}}if(a!=s){for(let c=l.length-1;c>l.length-B9;c--)if(!U9.test(l[c-1])&&U9.test(l[c])){l=l.slice(0,c);break}}return Rt.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const Vlr=Rt.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),qlr=[zS,bp.low(Dlr),Vlr];class sZe{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class TO{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(zL).markerFilter;s&&(t=s(t,r));let i=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),a=new rd,l=[],c=0;for(let d=0;;){let f=d==i.length?null:i[d];if(!f&&!l.length)break;let h,p;for(l.length?(h=c,p=l.reduce((v,y)=>Math.min(v,y.to),f&&f.from>h?f.from:1e8)):(h=f.from,p=f.to,l.push(f),d++);d<i.length;){let v=i[d];if(v.from==h&&(v.to>v.from||v.to==h))l.push(v),d++,p=Math.min(v.to,p);else{p=Math.min(v.from,p);break}}let m=rcr(l);if(l.some(v=>v.from==v.to||v.from==v.to-1&&r.doc.lineAt(v.from).to==v.from))a.add(h,h,Nn.widget({widget:new Jlr(m),diagnostics:l.slice()}));else{let v=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");a.add(h,p,Nn.mark({class:"cm-lintRange cm-lintRange-"+m+v,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>p)}))}c=p;for(let v=0;v<l.length;v++)l[v].to<=c&&l.splice(v--,1)}let u=a.finish();return new TO(u,n,CI(u))}}function CI(e,t=null,n=0){let r=null;return e.between(n,1e9,(s,i,{spec:a})=>{if(!(t&&a.diagnostics.indexOf(t)<0))if(!r)r=new sZe(s,i,t||a.diagnostics[0]);else{if(a.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new sZe(r.from,i,r.diagnostic)}}),r}function Hlr(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(zL).hideOn(e,n,r);if(s!=null)return s;let i=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(a=>a.is(fPt))||e.changes.touchesRange(i.from,Math.max(i.to,r)))}function Wlr(e,t){return e.field(Qh,!1)?t:t.concat(hr.appendConfig.of(scr))}const fPt=hr.define(),eNe=hr.define(),hPt=hr.define(),Qh=Ol.define({create(){return new TO(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 i=t.changes.mapPos(e.selected.from,1);r=CI(n,e.selected.diagnostic,i)||CI(n,null,i)}!n.size&&s&&t.state.facet(zL).autoPanel&&(s=null),e=new TO(n,s,r)}for(let n of t.effects)if(n.is(fPt)){let r=t.state.facet(zL).autoPanel?n.value.length?BL.open:null:e.panel;e=TO.init(n.value,r,t.state)}else n.is(eNe)?e=new TO(e.diagnostics,n.value?BL.open:null,e.selected):n.is(hPt)&&(e=new TO(e.diagnostics,e.panel,n.value));return e},provide:e=>[jL.from(e,t=>t.panel),Rt.decorations.from(e,t=>t.diagnostics)]}),Zlr=Nn.mark({class:"cm-lintRange cm-lintRange-active"});function Glr(e,t,n){let{diagnostics:r}=e.state.field(Qh),s,i=-1,a=-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,i=c,a=u,!1});let l=e.state.facet(zL).tooltipFilter;return s&&l&&(s=l(s,e.state)),s?{pos:i,end:a,above:e.state.doc.lineAt(i).to<a,create(){return{dom:Qlr(e,s)}}}:null}function Qlr(e,t){return pa("ul",{class:"cm-tooltip-lint"},t.map(n=>mPt(e,n,!1)))}const Klr=e=>{let t=e.state.field(Qh,!1);(!t||!t.panel)&&e.dispatch({effects:Wlr(e.state,[eNe.of(!0)])});let n=mje(e,BL.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},iZe=e=>{let t=e.state.field(Qh,!1);return!t||!t.panel?!1:(e.dispatch({effects:eNe.of(!1)}),!0)},Ylr=e=>{let t=e.state.field(Qh,!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)},Xlr=[{key:"Mod-Shift-m",run:Klr,preventDefault:!0},{key:"F8",run:Ylr}],zL=wn.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),..._b(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:aZe,tooltipFilter:aZe,needsRefresh:(t,n)=>t?n?r=>t(r)||n(r):t:n,hideOn:(t,n)=>t?n?(r,s,i)=>t(r,s,i)||n(r,s,i):t:n,autoPanel:(t,n)=>t||n})}}});function aZe(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function pPt(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(i=>i.toLowerCase()==s.toLowerCase())){t.push(s);continue e}}t.push("")}return t}function mPt(e,t,n){var r;let s=n?pPt(t.actions):[];return pa("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},pa("span",{class:"cm-diagnosticText"},t.renderMessage?t.renderMessage(e):t.message),(r=t.actions)===null||r===void 0?void 0:r.map((i,a)=>{let l=!1,c=p=>{if(p.preventDefault(),l)return;l=!0;let m=CI(e.state.field(Qh).diagnostics,t);m&&i.apply(e,m.from,m.to)},{name:u}=i,d=s[a]?u.indexOf(s[a]):-1,f=d<0?u:[u.slice(0,d),pa("u",u.slice(d,d+1)),u.slice(d+1)],h=i.markClass?" "+i.markClass:"";return pa("button",{type:"button",class:"cm-diagnosticAction"+h,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[a]})"`}.`},f)}),t.source&&pa("div",{class:"cm-diagnosticSource"},t.source))}class Jlr extends xp{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return pa("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class oZe{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=mPt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class BL{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)iZe(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:i}=this.items[this.selectedIndex],a=pPt(i.actions);for(let l=0;l<a.length;l++)if(a[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=CI(this.view.state.field(Qh).diagnostics,i);c&&i.actions[l].apply(t,c.from,c.to)}}else return;s.preventDefault()},r=s=>{for(let i=0;i<this.items.length;i++)this.items[i].dom.contains(s.target)&&this.moveSelection(i)};this.list=pa("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=pa("div",{class:"cm-panel-lint"},this.list,pa("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>iZe(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Qh).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(Qh),r=0,s=!1,i=null,a=new Set;for(t.between(0,this.view.state.doc.length,(l,c,{spec:u})=>{for(let d of u.diagnostics){if(a.has(d))continue;a.add(d);let f=-1,h;for(let p=r;p<this.items.length;p++)if(this.items[p].diagnostic==d){f=p;break}f<0?(h=new oZe(this.view,d),this.items.splice(r,0,h),s=!0):(h=this.items[f],f>r&&(this.items.splice(r,f-r),s=!0)),n&&h.diagnostic==n.diagnostic?h.dom.hasAttribute("aria-selected")||(h.dom.setAttribute("aria-selected","true"),i=h):h.dom.hasAttribute("aria-selected")&&h.dom.removeAttribute("aria-selected"),r++}});r<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0);)s=!0,this.items.pop();this.items.length==0&&(this.items.push(new oZe(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),s=!0),i?(this.list.setAttribute("aria-activedescendant",i.id),this.view.requestMeasure({key:this,read:()=>({sel:i.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(Qh),r=CI(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:hPt.of(r)})}static open(t){return new BL(t)}}function ecr(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 V9(e){return ecr(`<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 tcr=Rt.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:V9("#d11")},".cm-lintRange-warning":{backgroundImage:V9("orange")},".cm-lintRange-info":{backgroundImage:V9("#999")},".cm-lintRange-hint":{backgroundImage:V9("#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 ncr(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function rcr(e){let t="hint",n=1;for(let r of e){let s=ncr(r.severity);s>n&&(n=s,t=r.severity)}return t}const scr=[Qh,Rt.decorations.compute([Qh],e=>{let{selected:t,panel:n}=e.field(Qh);return!t||!n||t.from==t.to?Nn.none:Nn.set([Zlr.range(t.from,t.to)])}),Qtr(Glr,{hideOn:Hlr}),tcr];var lZe=function(t){t===void 0&&(t={});var n=t,r=n.crosshairCursor,s=r===void 0?!1:r,i=[];t.closeBracketsKeymap!==!1&&(i=i.concat(Hrr)),t.defaultKeymap!==!1&&(i=i.concat(plr)),t.searchKeymap!==!1&&(i=i.concat(Blr)),t.historyKeymap!==!1&&(i=i.concat(wor)),t.foldKeymap!==!1&&(i=i.concat(Nnr)),t.completionKeymap!==!1&&(i=i.concat(lAt)),t.lintKeymap!==!1&&(i=i.concat(Xlr));var a=[];return t.lineNumbers!==!1&&a.push(jIt()),t.highlightActiveLineGutter!==!1&&a.push(cnr()),t.highlightSpecialChars!==!1&&a.push(ktr()),t.history!==!1&&a.push(dor()),t.foldGutter!==!1&&a.push(Pnr()),t.drawSelection!==!1&&a.push(htr()),t.dropCursor!==!1&&a.push(ytr()),t.allowMultipleSelections!==!1&&a.push(gs.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&a.push(Snr()),t.syntaxHighlighting!==!1&&a.push(J1(Lnr,{fallback:!0})),t.bracketMatching!==!1&&a.push(Hnr()),t.closeBrackets!==!1&&a.push(Brr()),t.autocompletion!==!1&&a.push(oAt()),t.rectangularSelection!==!1&&a.push(Dtr()),s!==!1&&a.push(ztr()),t.highlightActiveLine!==!1&&a.push(jtr()),t.highlightSelectionMatches!==!1&&a.push(xlr()),t.tabSize&&typeof t.tabSize=="number"&&a.push(KA.of(" ".repeat(t.tabSize))),a.concat([QA.of(i.flat())]).filter(Boolean)};const icr="#e5c07b",cZe="#e06c75",acr="#56b6c2",ocr="#ffffff",N7="#abb2bf",W0e="#7d8799",lcr="#61afef",ccr="#98c379",uZe="#d19a66",ucr="#c678dd",dcr="#21252b",dZe="#2c313a",fZe="#282c34",Jse="#353a42",fcr="#3E4451",hZe="#528bff",hcr=Rt.theme({"&":{color:N7,backgroundColor:fZe},".cm-content":{caretColor:hZe},".cm-cursor, .cm-dropCursor":{borderLeftColor:hZe},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:fcr},".cm-panels":{backgroundColor:dcr,color:N7},".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:fZe,color:W0e,border:"none"},".cm-activeLineGutter":{backgroundColor:dZe},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:Jse},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:Jse,borderBottomColor:Jse},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:dZe,color:N7}}},{dark:!0}),pcr=wv.define([{tag:oe.keyword,color:ucr},{tag:[oe.name,oe.deleted,oe.character,oe.propertyName,oe.macroName],color:cZe},{tag:[oe.function(oe.variableName),oe.labelName],color:lcr},{tag:[oe.color,oe.constant(oe.name),oe.standard(oe.name)],color:uZe},{tag:[oe.definition(oe.name),oe.separator],color:N7},{tag:[oe.typeName,oe.className,oe.number,oe.changed,oe.annotation,oe.modifier,oe.self,oe.namespace],color:icr},{tag:[oe.operator,oe.operatorKeyword,oe.url,oe.escape,oe.regexp,oe.link,oe.special(oe.string)],color:acr},{tag:[oe.meta,oe.comment],color:W0e},{tag:oe.strong,fontWeight:"bold"},{tag:oe.emphasis,fontStyle:"italic"},{tag:oe.strikethrough,textDecoration:"line-through"},{tag:oe.link,color:W0e,textDecoration:"underline"},{tag:oe.heading,fontWeight:"bold",color:cZe},{tag:[oe.atom,oe.bool,oe.special(oe.variableName)],color:uZe},{tag:[oe.processingInstruction,oe.string,oe.inserted],color:ccr},{tag:oe.invalid,color:ocr}]),mcr=[hcr,J1(pcr)];var gcr=Rt.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),vcr=function(t){t===void 0&&(t={});var n=t,r=n.indentWithTab,s=r===void 0?!0:r,i=n.editable,a=i===void 0?!0:i,l=n.readOnly,c=l===void 0?!1:l,u=n.theme,d=u===void 0?"light":u,f=n.placeholder,h=f===void 0?"":f,p=n.basicSetup,m=p===void 0?!0:p,v=[];switch(s&&v.unshift(QA.of([mlr])),m&&(typeof m=="boolean"?v.unshift(lZe()):v.unshift(lZe(m))),h&&v.unshift(Rtr(h)),d){case"light":v.push(gcr);break;case"dark":v.push(mcr);break;case"none":break;default:v.push(d);break}return a===!1&&v.push(Rt.editable.of(!1)),c&&v.push(gs.readOnly.of(!0)),[...v]},ycr=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 bcr{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 pZe{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 eie=null,xcr=()=>typeof window>"u"?new pZe:(eie||(eie=new pZe),eie),wcr=Rt.theme({"& .cm-scroller":{height:"100% !important"}}),mZe=null,tie=null;function Scr(e,t,n,r,s,i){if(!e&&!t&&!n&&!r&&!s&&!i)return null;var a=JSON.stringify({height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:i});return a===mZe||(mZe=a,tie=Rt.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:i}})),tie}var gZe=Cb.define(),kcr=200,Ocr=[];function Ccr(e){var t=e.value,n=e.selection,r=e.onChange,s=e.onStatistics,i=e.onCreateEditor,a=e.onUpdate,l=e.extensions,c=l===void 0?Ocr:l,u=e.autoFocus,d=e.theme,f=d===void 0?"light":d,h=e.height,p=h===void 0?null:h,m=e.minHeight,v=m===void 0?null:m,y=e.maxHeight,b=y===void 0?null:y,x=e.width,w=x===void 0?null:x,k=e.minWidth,_=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,P=e.readOnly,L=P===void 0?!1:P,M=e.indentWithTab,V=M===void 0?!0:M,q=e.basicSetup,H=q===void 0?!0:q,B=e.root,W=e.initialState,z=g.useState(),G=z[0],F=z[1],R=g.useState(),D=R[0],U=R[1],Q=g.useState(),ee=Q[0],J=Q[1],te=g.useState(()=>({current:null}))[0],re=g.useState(()=>({current:null}))[0],ce=Scr(p,v,b,w,_,T),X=Rt.updateListener.of(le=>{if(le.docChanged&&typeof r=="function"&&!le.transactions.some(Se=>Se.annotation(gZe))){te.current?te.current.reset():(te.current=new bcr(()=>{if(re.current){var Se=re.current;re.current=null,Se()}te.current=null},kcr),xcr().add(te.current));var he=le.state.doc,pe=he.toString();r(pe,le)}s&&s(ycr(le))}),ne=vcr({theme:f,editable:A,readOnly:L,placeholder:N,indentWithTab:V,basicSetup:H}),se=[X,...ce?[ce]:[],wcr,...ne];return a&&typeof a=="function"&&se.push(Rt.updateListener.of(a)),se=se.concat(c),g.useLayoutEffect(()=>{if(G&&!ee){var le={doc:t,selection:n,extensions:se},he=W?gs.fromJSON(W.json,le,W.fields):gs.create(le);if(J(he),!D){var pe=new Rt({state:he,parent:G,root:B});U(pe),i&&i(pe,he)}}return()=>{D&&(J(void 0),U(void 0))}},[G,ee]),g.useEffect(()=>{e.container&&F(e.container)},[e.container]),g.useEffect(()=>()=>{D&&(D.destroy(),U(void 0)),te.current&&(te.current.cancel(),te.current=null)},[D]),g.useEffect(()=>{u&&D&&D.focus()},[u,D]),g.useEffect(()=>{D&&D.dispatch({effects:hr.reconfigure.of(se)})},[f,c,p,v,b,w,_,T,N,A,L,V,H,r,a]),g.useEffect(()=>{if(t!==void 0){var le=D?D.state.doc.toString():"";if(D&&t!==le){var he=te.current&&!te.current.isDone,pe=()=>{D&&t!==D.state.doc.toString()&&D.dispatch({changes:{from:0,to:D.state.doc.toString().length,insert:t||""},annotations:[gZe.of(!0)]})};he?re.current=pe:pe()}}},[t,D]),{state:ee,setState:J,view:D,setView:U,container:G,setContainer:F}}var _cr=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],ef=g.forwardRef((e,t)=>{var n=e.className,r=e.value,s=r===void 0?"":r,i=e.selection,a=e.extensions,l=a===void 0?[]:a,c=e.onChange,u=e.onStatistics,d=e.onCreateEditor,f=e.onUpdate,h=e.autoFocus,p=e.theme,m=p===void 0?"light":p,v=e.height,y=e.minHeight,b=e.maxHeight,x=e.width,w=e.minWidth,k=e.maxWidth,_=e.basicSetup,C=e.placeholder,T=e.indentWithTab,E=e.editable,N=e.readOnly,I=e.root,A=e.initialState,P=kRt(e,_cr),L=g.useRef(null),M=Ccr({root:I,value:s,autoFocus:h,theme:m,height:v,minHeight:y,maxHeight:b,width:x,minWidth:w,maxWidth:k,basicSetup:_,placeholder:C,indentWithTab:T,editable:E,readOnly:N,selection:i,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),V=M.state,q=M.view,H=M.container,B=M.setContainer;g.useImperativeHandle(t,()=>({editor:L.current,state:V,view:q}),[L,H,V,q]);var W=g.useCallback(G=>{L.current=G,B(G)},[B]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var z=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",a_({ref:W,className:""+z+(n?" "+n:"")},P))});ef.displayName="CodeMirror";function Ecr(e){return new r_(xje.define(e))}const Tcr=[Pg.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return Bi(()=>Promise.resolve().then(()=>F9),[],import.meta.url).then(e=>e.javascript())}}),Pg.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return Bi(()=>Promise.resolve().then(()=>rrr),void 0,import.meta.url).then(e=>e.json())}}),Pg.of({name:"JSX",extensions:["jsx"],load(){return Bi(()=>Promise.resolve().then(()=>F9),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),Pg.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return Bi(()=>Promise.resolve().then(()=>Xar),void 0,import.meta.url).then(e=>e.markdown())}}),Pg.of({name:"TSX",extensions:["tsx"],load(){return Bi(()=>Promise.resolve().then(()=>F9),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 Bi(()=>Promise.resolve().then(()=>F9),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 Bi(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>Ecr(e.shell))}})];function jcr(e,t=5){if(!e?.properties)return[];const n=[];function r(s,i,a){if(a>t)return;const l=Array.isArray(s.type)?s.type.join(" | "):s.type;if(n.push({path:i,label:i,description:s.description??s.title,type:l}),s.properties)for(const[c,u]of Object.entries(s.properties))r(u,`${i}.${c}`,a+1);if(s.items?.properties)for(const[c,u]of Object.entries(s.items.properties))r(u,`${i}[].${c}`,a+1)}for(const[s,i]of Object.entries(e.properties))r(i,s,1);return n}function Ncr(e){const t=jcr(e);return oAt({override:[Icr(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function Icr(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]??"",i=t.pos-s.length,a=s?e.filter(c=>c.path.toLowerCase().startsWith(s.toLowerCase())):e;if(a.length===0)return null;const l=a.map(c=>({label:c.path,displayLabel:c.path,detail:c.type,info:c.description,apply:(u,d,f,h)=>{const v=u.state.sliceDoc(h,h+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:h,insert:v},selection:{anchor:f+v.length}})}}));return{from:i,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const Acr=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,Rcr=Nn.mark({class:"cm-variable-highlight"}),vZe=new xIt({regexp:Acr,decoration:()=>Rcr}),Pcr=To.fromClass(class{decorations;constructor(e){this.decorations=vZe.createDeco(e)}update(e){this.decorations=vZe.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),$cr=Pcr;function Mcr(){const e=XA({settings:{fontFamily:"var(--font-mono)",fontSize:"var(--text-ui-smd)",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"var(--neutral2)",background:"transparent",foreground:"var(--neutral6)",caret:"var(--neutral6)"},styles:[{tag:[oe.className,oe.propertyName],color:"var(--neutral6)"},{tag:oe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[oe.heading1,oe.heading2,oe.heading3,oe.heading4,oe.heading5,oe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:oe.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:oe.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:oe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:oe.url,color:"var(--accent3)"},{tag:oe.monospace,color:"var(--neutral6)"},{tag:oe.strikethrough,textDecoration:"line-through"},{tag:oe.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=Rt.theme({".cm-editor":{backgroundColor:"transparent"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{color:"var(--neutral3)"},".cm-cursor":{borderLeftColor:"var(--neutral6)"},".cm-selectionBackground, .cm-content ::selection":{backgroundColor:"color-mix(in srgb, var(--accent3) 22%, transparent)"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"var(--text-ui-sm)",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 Dcr(){const e=Rt.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"var(--text-ui-smd)"},"&.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:"var(--text-ui-sm)",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=wv.define([{tag:[oe.comment,oe.bracket],color:"var(--neutral2)"},{tag:[oe.string,oe.meta,oe.regexp],color:"var(--accent1)"},{tag:[oe.atom,oe.bool,oe.special(oe.variableName)],color:"var(--accent6)"},{tag:[oe.keyword,oe.operator,oe.tagName],color:"var(--accent2)"},{tag:[oe.function(oe.propertyName),oe.propertyName],color:"var(--accent5)"},{tag:[oe.definition(oe.variableName),oe.function(oe.variableName),oe.className,oe.attributeName],color:"var(--accent3)"},{tag:[oe.variableName,oe.number],color:"var(--accent5)"},{tag:[oe.name,oe.quote],color:"var(--accent1)"},{tag:oe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[oe.heading1,oe.heading2,oe.heading3,oe.heading4,oe.heading5,oe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[oe.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[oe.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:oe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:oe.url,color:"var(--accent3)"},{tag:oe.monospace,color:"var(--neutral6)"},{tag:oe.strikethrough,textDecoration:"line-through"},{tag:[oe.deleted],color:"var(--accent2)"},{tag:oe.invalid,color:"var(--error)"},{tag:[oe.standard(oe.tagName)],color:"var(--accent1)"}]);return[e,J1(t)]}const tk=()=>{const e=aE().resolvedTheme==="dark";return g.useMemo(()=>e?Mcr():Dcr(),[e])},Lcr=kl(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"}}),Fcr=bp.highest(Rt.editorAttributes.of({style:"outline: none"})),zcr=bp.highest(Rt.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),Bcr=[Fcr,zcr],Lr=g.forwardRef(({data:e,value:t,onChange:n,showCopyButton:r=!0,className:s,language:i="json",highlightVariables:a=!1,placeholder:l,schema:c,autoFocus:u,lineNumbers:d=!0,lineWrapping:f=!0,editable:h,variant:p,...m},v)=>{const y=tk(),b=e?JSON.stringify(e,null,2):t??"",x=g.useMemo(()=>{const w=[...Bcr];return f&&w.push(Rt.lineWrapping),i==="json"?w.push(rp):i==="markdown"&&w.push(wRt({base:OI,codeLanguages:Tcr})),a&&i==="markdown"&&w.push($cr),c&&i==="markdown"&&w.push(Ncr(c)),h===!1&&w.push(gs.readOnly.of(!0)),w},[i,a,c,h,f]);return o.jsxs("div",{className:K(Lcr({variant:p}),s),...m,children:[r&&o.jsx(ci,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(ef,{ref:v,value:b,theme:y,extensions:x,onChange:n,editable:h,"aria-label":"Code editor",placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),gPt={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 nie=null;function Ucr(){return nie||(nie=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Bi(()=>import("./core-DJ3oKHtP.js"),__vite__mapDeps([0,1,2]),import.meta.url),Bi(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[Bi(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Bi(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Bi(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Bi(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Bi(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Bi(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Bi(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Bi(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Bi(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Bi(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Bi(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Bi(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Bi(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Bi(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([4,5,6]),import.meta.url),Bi(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Bi(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),nie}async function Vcr(e,t){const n=gPt[t?.toLowerCase()];if(!n)return null;const r=await Ucr(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function qcr(e){const t=e?.split(".").pop()?.toLowerCase();return t?gPt[t]:void 0}const Hcr=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},Wcr=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=tk(),{settings:r,setSettings:s}=YG(),i=r?.tracingOptions,a=g.useMemo(()=>Hcr(i),[i]),[l,c]=g.useState(()=>a),u=g.useRef(!1);g.useEffect(()=>{u.current||c(a)},[a]);const d=h=>{u.current=!0,c(h)},f=()=>{if(!l){s({...r,tracingOptions:void 0}),t?.();return}try{const h=JSON.parse(l);typeof h=="object"&&h!==null&&s({...r,tracingOptions:h})}catch{return}t?.()};return o.jsxs("div",{className:"space-y-2 px-5 py-2",children:[o.jsx(Te,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),o.jsx(ef,{value:l,onChange:d,theme:n,extensions:[rp],className:K("overflow-y-scroll bg-surface3 rounded-lg overflow-hidden p-3",e)}),o.jsx("div",{className:"flex items-center justify-end",children:o.jsx(ae,{icon:o.jsx(Mn,{}),type:"button",onClick:f,children:"Save"})})]})},Zcr=()=>{const[e,t]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(In,{children:[o.jsx(On,{asChild:!0,children:o.jsx(ae,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(St,{children:o.jsx(RCe,{})})})}),o.jsx(Cn,{children:"Run Options"})]}),o.jsx(hs,{open:e,onOpenChange:t,children:o.jsxs(Jr,{children:[o.jsxs(es,{children:[o.jsx(Kr,{children:"Run Options"}),o.jsx(Ps,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx(vs,{children:o.jsx(Wcr,{onSaved:()=>t(!1)})})]})})]})};function Hl(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=Hl(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var Gcr={value:()=>{}};function TQ(){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 I7(n)}function I7(e){this._=e}function Qcr(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}})}I7.prototype=TQ.prototype={constructor:I7,on:function(e,t){var n=this._,r=Qcr(e+"",n),s,i=-1,a=r.length;if(arguments.length<2){for(;++i<a;)if((s=(e=r[i]).type)&&(s=Kcr(n[s],e.name)))return s;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++i<a;)if(s=(e=r[i]).type)n[s]=yZe(n[s],e.name,t);else if(t==null)for(s in n)n[s]=yZe(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 I7(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),r=0,s,i;r<s;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(i=this._[e],r=0,s=i.length;r<s;++r)i[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,i=r.length;s<i;++s)r[s].value.apply(t,n)}};function Kcr(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function yZe(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=Gcr,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Z0e="http://www.w3.org/1999/xhtml";const bZe={svg:"http://www.w3.org/2000/svg",xhtml:Z0e,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function jQ(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),bZe.hasOwnProperty(t)?{space:bZe[t],local:e}:e}function Ycr(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Z0e&&t.documentElement.namespaceURI===Z0e?t.createElement(e):t.createElementNS(n,e)}}function Xcr(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function vPt(e){var t=jQ(e);return(t.local?Xcr:Ycr)(t)}function Jcr(){}function tNe(e){return e==null?Jcr:function(){return this.querySelector(e)}}function eur(e){typeof e!="function"&&(e=tNe(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var i=t[s],a=i.length,l=r[s]=new Array(a),c,u,d=0;d<a;++d)(c=i[d])&&(u=e.call(c,c.__data__,d,i))&&("__data__"in c&&(u.__data__=c.__data__),l[d]=u);return new hp(r,this._parents)}function tur(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function nur(){return[]}function yPt(e){return e==null?nur:function(){return this.querySelectorAll(e)}}function rur(e){return function(){return tur(e.apply(this,arguments))}}function sur(e){typeof e=="function"?e=rur(e):e=yPt(e);for(var t=this._groups,n=t.length,r=[],s=[],i=0;i<n;++i)for(var a=t[i],l=a.length,c,u=0;u<l;++u)(c=a[u])&&(r.push(e.call(c,c.__data__,u,a)),s.push(c));return new hp(r,s)}function bPt(e){return function(){return this.matches(e)}}function xPt(e){return function(t){return t.matches(e)}}var iur=Array.prototype.find;function aur(e){return function(){return iur.call(this.children,e)}}function our(){return this.firstElementChild}function lur(e){return this.select(e==null?our:aur(typeof e=="function"?e:xPt(e)))}var cur=Array.prototype.filter;function uur(){return Array.from(this.children)}function dur(e){return function(){return cur.call(this.children,e)}}function fur(e){return this.selectAll(e==null?uur:dur(typeof e=="function"?e:xPt(e)))}function hur(e){typeof e!="function"&&(e=bPt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var i=t[s],a=i.length,l=r[s]=[],c,u=0;u<a;++u)(c=i[u])&&e.call(c,c.__data__,u,i)&&l.push(c);return new hp(r,this._parents)}function wPt(e){return new Array(e.length)}function pur(){return new hp(this._enter||this._groups.map(wPt),this._parents)}function sH(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}sH.prototype={constructor:sH,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 mur(e){return function(){return e}}function gur(e,t,n,r,s,i){for(var a=0,l,c=t.length,u=i.length;a<u;++a)(l=t[a])?(l.__data__=i[a],r[a]=l):n[a]=new sH(e,i[a]);for(;a<c;++a)(l=t[a])&&(s[a]=l)}function vur(e,t,n,r,s,i,a){var l,c,u=new Map,d=t.length,f=i.length,h=new Array(d),p;for(l=0;l<d;++l)(c=t[l])&&(h[l]=p=a.call(c,c.__data__,l,t)+"",u.has(p)?s[l]=c:u.set(p,c));for(l=0;l<f;++l)p=a.call(e,i[l],l,i)+"",(c=u.get(p))?(r[l]=c,c.__data__=i[l],u.delete(p)):n[l]=new sH(e,i[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(h[l])===c&&(s[l]=c)}function yur(e){return e.__data__}function bur(e,t){if(!arguments.length)return Array.from(this,yur);var n=t?vur:gur,r=this._parents,s=this._groups;typeof e!="function"&&(e=mur(e));for(var i=s.length,a=new Array(i),l=new Array(i),c=new Array(i),u=0;u<i;++u){var d=r[u],f=s[u],h=f.length,p=xur(e.call(d,d&&d.__data__,u,r)),m=p.length,v=l[u]=new Array(m),y=a[u]=new Array(m),b=c[u]=new Array(h);n(d,f,v,y,b,p,t);for(var x=0,w=0,k,_;x<m;++x)if(k=v[x]){for(x>=w&&(w=x+1);!(_=y[w])&&++w<m;);k._next=_||null}}return a=new hp(a,r),a._enter=l,a._exit=c,a}function xur(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function wur(){return new hp(this._exit||this._groups.map(wPt),this._parents)}function Sur(e,t,n){var r=this.enter(),s=this,i=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?i.remove():n(i),r&&s?r.merge(s).order():s}function kur(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,s=n.length,i=r.length,a=Math.min(s,i),l=new Array(s),c=0;c<a;++c)for(var u=n[c],d=r[c],f=u.length,h=l[c]=new Array(f),p,m=0;m<f;++m)(p=u[m]||d[m])&&(h[m]=p);for(;c<s;++c)l[c]=n[c];return new hp(l,this._parents)}function Our(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],s=r.length-1,i=r[s],a;--s>=0;)(a=r[s])&&(i&&a.compareDocumentPosition(i)^4&&i.parentNode.insertBefore(a,i),i=a);return this}function Cur(e){e||(e=_ur);function t(f,h){return f&&h?e(f.__data__,h.__data__):!f-!h}for(var n=this._groups,r=n.length,s=new Array(r),i=0;i<r;++i){for(var a=n[i],l=a.length,c=s[i]=new Array(l),u,d=0;d<l;++d)(u=a[d])&&(c[d]=u);c.sort(t)}return new hp(s,this._parents).order()}function _ur(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function Eur(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function Tur(){return Array.from(this)}function jur(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,i=r.length;s<i;++s){var a=r[s];if(a)return a}return null}function Nur(){let e=0;for(const t of this)++e;return e}function Iur(){return!this.node()}function Aur(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var s=t[n],i=0,a=s.length,l;i<a;++i)(l=s[i])&&e.call(l,l.__data__,i,s);return this}function Rur(e){return function(){this.removeAttribute(e)}}function Pur(e){return function(){this.removeAttributeNS(e.space,e.local)}}function $ur(e,t){return function(){this.setAttribute(e,t)}}function Mur(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function Dur(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function Lur(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 Fur(e,t){var n=jQ(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?Pur:Rur:typeof t=="function"?n.local?Lur:Dur:n.local?Mur:$ur)(n,t))}function SPt(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function zur(e){return function(){this.style.removeProperty(e)}}function Bur(e,t,n){return function(){this.style.setProperty(e,t,n)}}function Uur(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function Vur(e,t,n){return arguments.length>1?this.each((t==null?zur:typeof t=="function"?Uur:Bur)(e,t,n??"")):_I(this.node(),e)}function _I(e,t){return e.style.getPropertyValue(t)||SPt(e).getComputedStyle(e,null).getPropertyValue(t)}function qur(e){return function(){delete this[e]}}function Hur(e,t){return function(){this[e]=t}}function Wur(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function Zur(e,t){return arguments.length>1?this.each((t==null?qur:typeof t=="function"?Wur:Hur)(e,t)):this.node()[e]}function kPt(e){return e.trim().split(/^|\s+/)}function nNe(e){return e.classList||new OPt(e)}function OPt(e){this._node=e,this._names=kPt(e.getAttribute("class")||"")}OPt.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 CPt(e,t){for(var n=nNe(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function _Pt(e,t){for(var n=nNe(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function Gur(e){return function(){CPt(this,e)}}function Qur(e){return function(){_Pt(this,e)}}function Kur(e,t){return function(){(t.apply(this,arguments)?CPt:_Pt)(this,e)}}function Yur(e,t){var n=kPt(e+"");if(arguments.length<2){for(var r=nNe(this.node()),s=-1,i=n.length;++s<i;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?Kur:t?Gur:Qur)(n,t))}function Xur(){this.textContent=""}function Jur(e){return function(){this.textContent=e}}function edr(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function tdr(e){return arguments.length?this.each(e==null?Xur:(typeof e=="function"?edr:Jur)(e)):this.node().textContent}function ndr(){this.innerHTML=""}function rdr(e){return function(){this.innerHTML=e}}function sdr(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function idr(e){return arguments.length?this.each(e==null?ndr:(typeof e=="function"?sdr:rdr)(e)):this.node().innerHTML}function adr(){this.nextSibling&&this.parentNode.appendChild(this)}function odr(){return this.each(adr)}function ldr(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function cdr(){return this.each(ldr)}function udr(e){var t=typeof e=="function"?e:vPt(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function ddr(){return null}function fdr(e,t){var n=typeof e=="function"?e:vPt(e),r=t==null?ddr:typeof t=="function"?t:tNe(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function hdr(){var e=this.parentNode;e&&e.removeChild(this)}function pdr(){return this.each(hdr)}function mdr(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function gdr(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function vdr(e){return this.select(e?gdr:mdr)}function ydr(e){return arguments.length?this.property("__data__",e):this.node().__data__}function bdr(e){return function(t){e.call(this,t,this.__data__)}}function xdr(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 wdr(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,s=t.length,i;n<s;++n)i=t[n],(!e.type||i.type===e.type)&&i.name===e.name?this.removeEventListener(i.type,i.listener,i.options):t[++r]=i;++r?t.length=r:delete this.__on}}}function Sdr(e,t,n){return function(){var r=this.__on,s,i=bdr(t);if(r){for(var a=0,l=r.length;a<l;++a)if((s=r[a]).type===e.type&&s.name===e.name){this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=i,s.options=n),s.value=t;return}}this.addEventListener(e.type,i,n),s={type:e.type,name:e.name,value:t,listener:i,options:n},r?r.push(s):this.__on=[s]}}function kdr(e,t,n){var r=xdr(e+""),s,i=r.length,a;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<i;++s)if((a=r[s]).type===d.type&&a.name===d.name)return d.value}return}for(l=t?Sdr:wdr,s=0;s<i;++s)this.each(l(r[s],t,n));return this}function EPt(e,t,n){var r=SPt(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 Odr(e,t){return function(){return EPt(this,e,t)}}function Cdr(e,t){return function(){return EPt(this,e,t.apply(this,arguments))}}function _dr(e,t){return this.each((typeof t=="function"?Cdr:Odr)(e,t))}function*Edr(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,i=r.length,a;s<i;++s)(a=r[s])&&(yield a)}var TPt=[null];function hp(e,t){this._groups=e,this._parents=t}function h5(){return new hp([[document.documentElement]],TPt)}function Tdr(){return this}hp.prototype=h5.prototype={constructor:hp,select:eur,selectAll:sur,selectChild:lur,selectChildren:fur,filter:hur,data:bur,enter:pur,exit:wur,join:Sur,merge:kur,selection:Tdr,order:Our,sort:Cur,call:Eur,nodes:Tur,node:jur,size:Nur,empty:Iur,each:Aur,attr:Fur,style:Vur,property:Zur,classed:Yur,text:tdr,html:idr,raise:odr,lower:cdr,append:udr,insert:fdr,remove:pdr,clone:vdr,datum:ydr,on:kdr,dispatch:_dr,[Symbol.iterator]:Edr};function Uh(e){return typeof e=="string"?new hp([[document.querySelector(e)]],[document.documentElement]):new hp([[e]],TPt)}function jdr(e){let t;for(;t=e.sourceEvent;)e=t;return e}function $g(e,t){if(e=jdr(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 Ndr={passive:!1},UL={capture:!0,passive:!1};function rie(e){e.stopImmediatePropagation()}function wN(e){e.preventDefault(),e.stopImmediatePropagation()}function jPt(e){var t=e.document.documentElement,n=Uh(e).on("dragstart.drag",wN,UL);"onselectstart"in t?n.on("selectstart.drag",wN,UL):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function NPt(e,t){var n=e.document.documentElement,r=Uh(e).on("dragstart.drag",null);t&&(r.on("click.drag",wN,UL),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 q9=e=>()=>e;function G0e(e,{sourceEvent:t,subject:n,target:r,identifier:s,active:i,x:a,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:i,enumerable:!0,configurable:!0},x:{value:a,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}})}G0e.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function Idr(e){return!e.ctrlKey&&!e.button}function Adr(){return this.parentNode}function Rdr(e,t){return t??{x:e.x,y:e.y}}function Pdr(){return navigator.maxTouchPoints||"ontouchstart"in this}function IPt(){var e=Idr,t=Adr,n=Rdr,r=Pdr,s={},i=TQ("start","drag","end"),a=0,l,c,u,d,f=0;function h(k){k.on("mousedown.drag",p).filter(r).on("touchstart.drag",y).on("touchmove.drag",b,Ndr).on("touchend.drag touchcancel.drag",x).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function p(k,_){if(!(d||!e.call(this,k,_))){var C=w(this,t.call(this,k,_),k,_,"mouse");C&&(Uh(k.view).on("mousemove.drag",m,UL).on("mouseup.drag",v,UL),jPt(k.view),rie(k),u=!1,l=k.clientX,c=k.clientY,C("start",k))}}function m(k){if(wN(k),!u){var _=k.clientX-l,C=k.clientY-c;u=_*_+C*C>f}s.mouse("drag",k)}function v(k){Uh(k.view).on("mousemove.drag mouseup.drag",null),NPt(k.view,u),wN(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=w(this,T,k,_,C[N].identifier,C[N]))&&(rie(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])&&(wN(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])&&(rie(k),E("end",k,_[T]))}function w(k,_,C,T,E,N){var I=i.copy(),A=$g(N||C,_),P,L,M;if((M=n.call(k,new G0e("beforestart",{sourceEvent:C,target:h,identifier:E,active:a,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),T))!=null)return P=M.x-A[0]||0,L=M.y-A[1]||0,function V(q,H,B){var W=A,z;switch(q){case"start":s[E]=V,z=a++;break;case"end":delete s[E],--a;case"drag":A=$g(B||H,_),z=a;break}I.call(q,k,new G0e(q,{sourceEvent:H,subject:M,target:h,identifier:E,active:z,x:A[0]+P,y:A[1]+L,dx:A[0]-W[0],dy:A[1]-W[1],dispatch:I}),T)}}return h.filter=function(k){return arguments.length?(e=typeof k=="function"?k:q9(!!k),h):e},h.container=function(k){return arguments.length?(t=typeof k=="function"?k:q9(k),h):t},h.subject=function(k){return arguments.length?(n=typeof k=="function"?k:q9(k),h):n},h.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:q9(!!k),h):r},h.on=function(){var k=i.on.apply(i,arguments);return k===i?h:k},h.clickDistance=function(k){return arguments.length?(f=(k=+k)*k,h):Math.sqrt(f)},h}function rNe(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function APt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function p5(){}var VL=.7,iH=1/VL,SN="\\s*([+-]?\\d+)\\s*",qL="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Hy="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",$dr=/^#([0-9a-f]{3,8})$/,Mdr=new RegExp(`^rgb\\(${SN},${SN},${SN}\\)$`),Ddr=new RegExp(`^rgb\\(${Hy},${Hy},${Hy}\\)$`),Ldr=new RegExp(`^rgba\\(${SN},${SN},${SN},${qL}\\)$`),Fdr=new RegExp(`^rgba\\(${Hy},${Hy},${Hy},${qL}\\)$`),zdr=new RegExp(`^hsl\\(${qL},${Hy},${Hy}\\)$`),Bdr=new RegExp(`^hsla\\(${qL},${Hy},${Hy},${qL}\\)$`),xZe={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};rNe(p5,o_,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:wZe,formatHex:wZe,formatHex8:Udr,formatHsl:Vdr,formatRgb:SZe,toString:SZe});function wZe(){return this.rgb().formatHex()}function Udr(){return this.rgb().formatHex8()}function Vdr(){return RPt(this).formatHsl()}function SZe(){return this.rgb().formatRgb()}function o_(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=$dr.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?kZe(t):n===3?new Lf(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?H9(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?H9(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=Mdr.exec(e))?new Lf(t[1],t[2],t[3],1):(t=Ddr.exec(e))?new Lf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Ldr.exec(e))?H9(t[1],t[2],t[3],t[4]):(t=Fdr.exec(e))?H9(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=zdr.exec(e))?_Ze(t[1],t[2]/100,t[3]/100,1):(t=Bdr.exec(e))?_Ze(t[1],t[2]/100,t[3]/100,t[4]):xZe.hasOwnProperty(e)?kZe(xZe[e]):e==="transparent"?new Lf(NaN,NaN,NaN,0):null}function kZe(e){return new Lf(e>>16&255,e>>8&255,e&255,1)}function H9(e,t,n,r){return r<=0&&(e=t=n=NaN),new Lf(e,t,n,r)}function qdr(e){return e instanceof p5||(e=o_(e)),e?(e=e.rgb(),new Lf(e.r,e.g,e.b,e.opacity)):new Lf}function Q0e(e,t,n,r){return arguments.length===1?qdr(e):new Lf(e,t,n,r??1)}function Lf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}rNe(Lf,Q0e,APt(p5,{brighter(e){return e=e==null?iH:Math.pow(iH,e),new Lf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?VL:Math.pow(VL,e),new Lf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Lf(hC(this.r),hC(this.g),hC(this.b),aH(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:OZe,formatHex:OZe,formatHex8:Hdr,formatRgb:CZe,toString:CZe}));function OZe(){return`#${UO(this.r)}${UO(this.g)}${UO(this.b)}`}function Hdr(){return`#${UO(this.r)}${UO(this.g)}${UO(this.b)}${UO((isNaN(this.opacity)?1:this.opacity)*255)}`}function CZe(){const e=aH(this.opacity);return`${e===1?"rgb(":"rgba("}${hC(this.r)}, ${hC(this.g)}, ${hC(this.b)}${e===1?")":`, ${e})`}`}function aH(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function hC(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function UO(e){return e=hC(e),(e<16?"0":"")+e.toString(16)}function _Ze(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Bg(e,t,n,r)}function RPt(e){if(e instanceof Bg)return new Bg(e.h,e.s,e.l,e.opacity);if(e instanceof p5||(e=o_(e)),!e)return new Bg;if(e instanceof Bg)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,s=Math.min(t,n,r),i=Math.max(t,n,r),a=NaN,l=i-s,c=(i+s)/2;return l?(t===i?a=(n-r)/l+(n<r)*6:n===i?a=(r-t)/l+2:a=(t-n)/l+4,l/=c<.5?i+s:2-i-s,a*=60):l=c>0&&c<1?0:a,new Bg(a,l,c,e.opacity)}function Wdr(e,t,n,r){return arguments.length===1?RPt(e):new Bg(e,t,n,r??1)}function Bg(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}rNe(Bg,Wdr,APt(p5,{brighter(e){return e=e==null?iH:Math.pow(iH,e),new Bg(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?VL:Math.pow(VL,e),new Bg(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 Lf(sie(e>=240?e-240:e+120,s,r),sie(e,s,r),sie(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new Bg(EZe(this.h),W9(this.s),W9(this.l),aH(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=aH(this.opacity);return`${e===1?"hsl(":"hsla("}${EZe(this.h)}, ${W9(this.s)*100}%, ${W9(this.l)*100}%${e===1?")":`, ${e})`}`}}));function EZe(e){return e=(e||0)%360,e<0?e+360:e}function W9(e){return Math.max(0,Math.min(1,e||0))}function sie(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 sNe=e=>()=>e;function Zdr(e,t){return function(n){return e+n*t}}function Gdr(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 Qdr(e){return(e=+e)==1?PPt:function(t,n){return n-t?Gdr(t,n,e):sNe(isNaN(t)?n:t)}}function PPt(e,t){var n=t-e;return n?Zdr(e,n):sNe(isNaN(e)?t:e)}const oH=(function e(t){var n=Qdr(t);function r(s,i){var a=n((s=Q0e(s)).r,(i=Q0e(i)).r),l=n(s.g,i.g),c=n(s.b,i.b),u=PPt(s.opacity,i.opacity);return function(d){return s.r=a(d),s.g=l(d),s.b=c(d),s.opacity=u(d),s+""}}return r.gamma=e,r})(1);function Kdr(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),s;return function(i){for(s=0;s<n;++s)r[s]=e[s]*(1-i)+t[s]*i;return r}}function Ydr(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Xdr(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,s=new Array(r),i=new Array(n),a;for(a=0;a<r;++a)s[a]=t0(e[a],t[a]);for(;a<n;++a)i[a]=t[a];return function(l){for(a=0;a<r;++a)i[a]=s[a](l);return i}}function Jdr(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function Dg(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function efr(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]=t0(e[s],t[s]):r[s]=t[s];return function(i){for(s in n)r[s]=n[s](i);return r}}var K0e=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,iie=new RegExp(K0e.source,"g");function tfr(e){return function(){return e}}function nfr(e){return function(t){return e(t)+""}}function $Pt(e,t){var n=K0e.lastIndex=iie.lastIndex=0,r,s,i,a=-1,l=[],c=[];for(e=e+"",t=t+"";(r=K0e.exec(e))&&(s=iie.exec(t));)(i=s.index)>n&&(i=t.slice(n,i),l[a]?l[a]+=i:l[++a]=i),(r=r[0])===(s=s[0])?l[a]?l[a]+=s:l[++a]=s:(l[++a]=null,c.push({i:a,x:Dg(r,s)})),n=iie.lastIndex;return n<t.length&&(i=t.slice(n),l[a]?l[a]+=i:l[++a]=i),l.length<2?c[0]?nfr(c[0].x):tfr(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 t0(e,t){var n=typeof t,r;return t==null||n==="boolean"?sNe(t):(n==="number"?Dg:n==="string"?(r=o_(t))?(t=r,oH):$Pt:t instanceof o_?oH:t instanceof Date?Jdr:Ydr(t)?Kdr:Array.isArray(t)?Xdr:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?efr:Dg)(e,t)}function iNe(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var TZe=180/Math.PI,Y0e={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function MPt(e,t,n,r,s,i){var a,l,c;return(a=Math.sqrt(e*e+t*t))&&(e/=a,t/=a),(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,a=-a),{translateX:s,translateY:i,rotate:Math.atan2(t,e)*TZe,skewX:Math.atan(c)*TZe,scaleX:a,scaleY:l}}var Z9;function rfr(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Y0e:MPt(t.a,t.b,t.c,t.d,t.e,t.f)}function sfr(e){return e==null||(Z9||(Z9=document.createElementNS("http://www.w3.org/2000/svg","g")),Z9.setAttribute("transform",e),!(e=Z9.transform.baseVal.consolidate()))?Y0e:(e=e.matrix,MPt(e.a,e.b,e.c,e.d,e.e,e.f))}function DPt(e,t,n,r){function s(u){return u.length?u.pop()+" ":""}function i(u,d,f,h,p,m){if(u!==f||d!==h){var v=p.push("translate(",null,t,null,n);m.push({i:v-4,x:Dg(u,f)},{i:v-2,x:Dg(d,h)})}else(f||h)&&p.push("translate("+f+t+h+n)}function a(u,d,f,h){u!==d?(u-d>180?d+=360:d-u>180&&(u+=360),h.push({i:f.push(s(f)+"rotate(",null,r)-2,x:Dg(u,d)})):d&&f.push(s(f)+"rotate("+d+r)}function l(u,d,f,h){u!==d?h.push({i:f.push(s(f)+"skewX(",null,r)-2,x:Dg(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,h,p,m){if(u!==f||d!==h){var v=p.push(s(p)+"scale(",null,",",null,")");m.push({i:v-4,x:Dg(u,f)},{i:v-2,x:Dg(d,h)})}else(f!==1||h!==1)&&p.push(s(p)+"scale("+f+","+h+")")}return function(u,d){var f=[],h=[];return u=e(u),d=e(d),i(u.translateX,u.translateY,d.translateX,d.translateY,f,h),a(u.rotate,d.rotate,f,h),l(u.skewX,d.skewX,f,h),c(u.scaleX,u.scaleY,d.scaleX,d.scaleY,f,h),u=d=null,function(p){for(var m=-1,v=h.length,y;++m<v;)f[(y=h[m]).i]=y.x(p);return f.join("")}}}var ifr=DPt(rfr,"px, ","px)","deg)"),afr=DPt(sfr,", ",")",")"),ofr=1e-12;function jZe(e){return((e=Math.exp(e))+1/e)/2}function lfr(e){return((e=Math.exp(e))-1/e)/2}function cfr(e){return((e=Math.exp(2*e))-1)/(e+1)}const A7=(function e(t,n,r){function s(i,a){var l=i[0],c=i[1],u=i[2],d=a[0],f=a[1],h=a[2],p=d-l,m=f-c,v=p*p+m*m,y,b;if(v<ofr)b=Math.log(h/u)/t,y=function(T){return[l+T*p,c+T*m,u*Math.exp(t*T*b)]};else{var x=Math.sqrt(v),w=(h*h-u*u+r*v)/(2*u*n*x),k=(h*h-u*u-r*v)/(2*h*n*x),_=Math.log(Math.sqrt(w*w+1)-w),C=Math.log(Math.sqrt(k*k+1)-k);b=(C-_)/t,y=function(T){var E=T*b,N=jZe(_),I=u/(n*x)*(N*cfr(t*E+_)-lfr(_));return[l+I*p,c+I*m,u*N/jZe(t*E+_)]}}return y.duration=b*1e3*t/Math.SQRT2,y}return s.rho=function(i){var a=Math.max(.001,+i),l=a*a,c=l*l;return e(a,l,c)},s})(Math.SQRT2,2,4);function ufr(e,t){t===void 0&&(t=e,e=t0);for(var n=0,r=t.length-1,s=t[0],i=new Array(r<0?0:r);n<r;)i[n]=e(s,s=t[++n]);return function(a){var l=Math.max(0,Math.min(r-1,Math.floor(a*=r)));return i[l](a-l)}}var EI=0,UM=0,k$=0,LPt=1e3,lH,VM,cH=0,l_=0,NQ=0,HL=typeof performance=="object"&&performance.now?performance:Date,FPt=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function aNe(){return l_||(FPt(dfr),l_=HL.now()+NQ)}function dfr(){l_=0}function uH(){this._call=this._time=this._next=null}uH.prototype=zPt.prototype={constructor:uH,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?aNe():+n)+(t==null?0:+t),!this._next&&VM!==this&&(VM?VM._next=this:lH=this,VM=this),this._call=e,this._time=n,X0e()},stop:function(){this._call&&(this._call=null,this._time=1/0,X0e())}};function zPt(e,t,n){var r=new uH;return r.restart(e,t,n),r}function ffr(){aNe(),++EI;for(var e=lH,t;e;)(t=l_-e._time)>=0&&e._call.call(void 0,t),e=e._next;--EI}function NZe(){l_=(cH=HL.now())+NQ,EI=UM=0;try{ffr()}finally{EI=0,pfr(),l_=0}}function hfr(){var e=HL.now(),t=e-cH;t>LPt&&(NQ-=t,cH=e)}function pfr(){for(var e,t=lH,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:lH=n);VM=e,X0e(r)}function X0e(e){if(!EI){UM&&(UM=clearTimeout(UM));var t=e-l_;t>24?(e<1/0&&(UM=setTimeout(NZe,e-HL.now()-NQ)),k$&&(k$=clearInterval(k$))):(k$||(cH=HL.now(),k$=setInterval(hfr,LPt)),EI=1,FPt(NZe))}}function IZe(e,t,n){var r=new uH;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var mfr=TQ("start","end","cancel","interrupt"),gfr=[],BPt=0,AZe=1,J0e=2,R7=3,RZe=4,ewe=5,P7=6;function IQ(e,t,n,r,s,i){var a=e.__transition;if(!a)e.__transition={};else if(n in a)return;vfr(e,n,{name:t,index:r,group:s,on:mfr,tween:gfr,time:i.time,delay:i.delay,duration:i.duration,ease:i.ease,timer:null,state:BPt})}function oNe(e,t){var n=Ov(e,t);if(n.state>BPt)throw new Error("too late; already scheduled");return n}function Eb(e,t){var n=Ov(e,t);if(n.state>R7)throw new Error("too late; already running");return n}function Ov(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function vfr(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=zPt(i,0,n.time);function i(u){n.state=AZe,n.timer.restart(a,n.delay,n.time),n.delay<=u&&a(u-n.delay)}function a(u){var d,f,h,p;if(n.state!==AZe)return c();for(d in r)if(p=r[d],p.name===n.name){if(p.state===R7)return IZe(a);p.state===RZe?(p.state=P7,p.timer.stop(),p.on.call("interrupt",e,e.__data__,p.index,p.group),delete r[d]):+d<t&&(p.state=P7,p.timer.stop(),p.on.call("cancel",e,e.__data__,p.index,p.group),delete r[d])}if(IZe(function(){n.state===R7&&(n.state=RZe,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=J0e,n.on.call("start",e,e.__data__,n.index,n.group),n.state===J0e){for(n.state=R7,s=new Array(h=n.tween.length),d=0,f=-1;d<h;++d)(p=n.tween[d].value.call(e,e.__data__,n.index,n.group))&&(s[++f]=p);s.length=f+1}}function l(u){for(var d=u<n.duration?n.ease.call(null,u/n.duration):(n.timer.restart(c),n.state=ewe,1),f=-1,h=s.length;++f<h;)s[f].call(e,d);n.state===ewe&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=P7,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function $7(e,t){var n=e.__transition,r,s,i=!0,a;if(n){t=t==null?null:t+"";for(a in n){if((r=n[a]).name!==t){i=!1;continue}s=r.state>J0e&&r.state<ewe,r.state=P7,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[a]}i&&delete e.__transition}}function yfr(e){return this.each(function(){$7(this,e)})}function bfr(e,t){var n,r;return function(){var s=Eb(this,e),i=s.tween;if(i!==n){r=n=i;for(var a=0,l=r.length;a<l;++a)if(r[a].name===t){r=r.slice(),r.splice(a,1);break}}s.tween=r}}function xfr(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var i=Eb(this,e),a=i.tween;if(a!==r){s=(r=a).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)}i.tween=s}}function wfr(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Ov(this.node(),n).tween,s=0,i=r.length,a;s<i;++s)if((a=r[s]).name===e)return a.value;return null}return this.each((t==null?bfr:xfr)(n,e,t))}function lNe(e,t,n){var r=e._id;return e.each(function(){var s=Eb(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return Ov(s,r).value[t]}}function UPt(e,t){var n;return(typeof t=="number"?Dg:t instanceof o_?oH:(n=o_(t))?(t=n,oH):$Pt)(e,t)}function Sfr(e){return function(){this.removeAttribute(e)}}function kfr(e){return function(){this.removeAttributeNS(e.space,e.local)}}function Ofr(e,t,n){var r,s=n+"",i;return function(){var a=this.getAttribute(e);return a===s?null:a===r?i:i=t(r=a,n)}}function Cfr(e,t,n){var r,s=n+"",i;return function(){var a=this.getAttributeNS(e.space,e.local);return a===s?null:a===r?i:i=t(r=a,n)}}function _fr(e,t,n){var r,s,i;return function(){var a,l=n(this),c;return l==null?void this.removeAttribute(e):(a=this.getAttribute(e),c=l+"",a===c?null:a===r&&c===s?i:(s=c,i=t(r=a,l)))}}function Efr(e,t,n){var r,s,i;return function(){var a,l=n(this),c;return l==null?void this.removeAttributeNS(e.space,e.local):(a=this.getAttributeNS(e.space,e.local),c=l+"",a===c?null:a===r&&c===s?i:(s=c,i=t(r=a,l)))}}function Tfr(e,t){var n=jQ(e),r=n==="transform"?afr:UPt;return this.attrTween(e,typeof t=="function"?(n.local?Efr:_fr)(n,r,lNe(this,"attr."+e,t)):t==null?(n.local?kfr:Sfr)(n):(n.local?Cfr:Ofr)(n,r,t))}function jfr(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function Nfr(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function Ifr(e,t){var n,r;function s(){var i=t.apply(this,arguments);return i!==r&&(n=(r=i)&&Nfr(e,i)),n}return s._value=t,s}function Afr(e,t){var n,r;function s(){var i=t.apply(this,arguments);return i!==r&&(n=(r=i)&&jfr(e,i)),n}return s._value=t,s}function Rfr(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=jQ(e);return this.tween(n,(r.local?Ifr:Afr)(r,t))}function Pfr(e,t){return function(){oNe(this,e).delay=+t.apply(this,arguments)}}function $fr(e,t){return t=+t,function(){oNe(this,e).delay=t}}function Mfr(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?Pfr:$fr)(t,e)):Ov(this.node(),t).delay}function Dfr(e,t){return function(){Eb(this,e).duration=+t.apply(this,arguments)}}function Lfr(e,t){return t=+t,function(){Eb(this,e).duration=t}}function Ffr(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?Dfr:Lfr)(t,e)):Ov(this.node(),t).duration}function zfr(e,t){if(typeof t!="function")throw new Error;return function(){Eb(this,e).ease=t}}function Bfr(e){var t=this._id;return arguments.length?this.each(zfr(t,e)):Ov(this.node(),t).ease}function Ufr(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Eb(this,e).ease=n}}function Vfr(e){if(typeof e!="function")throw new Error;return this.each(Ufr(this._id,e))}function qfr(e){typeof e!="function"&&(e=bPt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var i=t[s],a=i.length,l=r[s]=[],c,u=0;u<a;++u)(c=i[u])&&e.call(c,c.__data__,u,i)&&l.push(c);return new k0(r,this._parents,this._name,this._id)}function Hfr(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,s=n.length,i=Math.min(r,s),a=new Array(r),l=0;l<i;++l)for(var c=t[l],u=n[l],d=c.length,f=a[l]=new Array(d),h,p=0;p<d;++p)(h=c[p]||u[p])&&(f[p]=h);for(;l<r;++l)a[l]=t[l];return new k0(a,this._parents,this._name,this._id)}function Wfr(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 Zfr(e,t,n){var r,s,i=Wfr(t)?oNe:Eb;return function(){var a=i(this,e),l=a.on;l!==r&&(s=(r=l).copy()).on(t,n),a.on=s}}function Gfr(e,t){var n=this._id;return arguments.length<2?Ov(this.node(),n).on.on(e):this.each(Zfr(n,e,t))}function Qfr(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function Kfr(){return this.on("end.remove",Qfr(this._id))}function Yfr(e){var t=this._name,n=this._id;typeof e!="function"&&(e=tNe(e));for(var r=this._groups,s=r.length,i=new Array(s),a=0;a<s;++a)for(var l=r[a],c=l.length,u=i[a]=new Array(c),d,f,h=0;h<c;++h)(d=l[h])&&(f=e.call(d,d.__data__,h,l))&&("__data__"in d&&(f.__data__=d.__data__),u[h]=f,IQ(u[h],t,n,h,u,Ov(d,n)));return new k0(i,this._parents,t,n)}function Xfr(e){var t=this._name,n=this._id;typeof e!="function"&&(e=yPt(e));for(var r=this._groups,s=r.length,i=[],a=[],l=0;l<s;++l)for(var c=r[l],u=c.length,d,f=0;f<u;++f)if(d=c[f]){for(var h=e.call(d,d.__data__,f,c),p,m=Ov(d,n),v=0,y=h.length;v<y;++v)(p=h[v])&&IQ(p,t,n,v,h,m);i.push(h),a.push(d)}return new k0(i,a,t,n)}var Jfr=h5.prototype.constructor;function ehr(){return new Jfr(this._groups,this._parents)}function thr(e,t){var n,r,s;return function(){var i=_I(this,e),a=(this.style.removeProperty(e),_I(this,e));return i===a?null:i===n&&a===r?s:s=t(n=i,r=a)}}function VPt(e){return function(){this.style.removeProperty(e)}}function nhr(e,t,n){var r,s=n+"",i;return function(){var a=_I(this,e);return a===s?null:a===r?i:i=t(r=a,n)}}function rhr(e,t,n){var r,s,i;return function(){var a=_I(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),_I(this,e))),a===c?null:a===r&&c===s?i:(s=c,i=t(r=a,l))}}function shr(e,t){var n,r,s,i="style."+t,a="end."+i,l;return function(){var c=Eb(this,e),u=c.on,d=c.value[i]==null?l||(l=VPt(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(a,s=d),c.on=r}}function ihr(e,t,n){var r=(e+="")=="transform"?ifr:UPt;return t==null?this.styleTween(e,thr(e,r)).on("end.style."+e,VPt(e)):typeof t=="function"?this.styleTween(e,rhr(e,r,lNe(this,"style."+e,t))).each(shr(this._id,e)):this.styleTween(e,nhr(e,r,t),n).on("end.style."+e,null)}function ahr(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function ohr(e,t,n){var r,s;function i(){var a=t.apply(this,arguments);return a!==s&&(r=(s=a)&&ahr(e,a,n)),r}return i._value=t,i}function lhr(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,ohr(e,t,n??""))}function chr(e){return function(){this.textContent=e}}function uhr(e){return function(){var t=e(this);this.textContent=t??""}}function dhr(e){return this.tween("text",typeof e=="function"?uhr(lNe(this,"text",e)):chr(e==null?"":e+""))}function fhr(e){return function(t){this.textContent=e.call(this,t)}}function hhr(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&fhr(s)),t}return r._value=e,r}function phr(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,hhr(e))}function mhr(){for(var e=this._name,t=this._id,n=qPt(),r=this._groups,s=r.length,i=0;i<s;++i)for(var a=r[i],l=a.length,c,u=0;u<l;++u)if(c=a[u]){var d=Ov(c,t);IQ(c,e,n,u,a,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new k0(r,this._parents,e,n)}function ghr(){var e,t,n=this,r=n._id,s=n.size();return new Promise(function(i,a){var l={value:a},c={value:function(){--s===0&&i()}};n.each(function(){var u=Eb(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&&i()})}var vhr=0;function k0(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function qPt(){return++vhr}var ax=h5.prototype;k0.prototype={constructor:k0,select:Yfr,selectAll:Xfr,selectChild:ax.selectChild,selectChildren:ax.selectChildren,filter:qfr,merge:Hfr,selection:ehr,transition:mhr,call:ax.call,nodes:ax.nodes,node:ax.node,size:ax.size,empty:ax.empty,each:ax.each,on:Gfr,attr:Tfr,attrTween:Rfr,style:ihr,styleTween:lhr,text:dhr,textTween:phr,remove:Kfr,tween:wfr,delay:Mfr,duration:Ffr,ease:Bfr,easeVarying:Vfr,end:ghr,[Symbol.iterator]:ax[Symbol.iterator]};function yhr(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var bhr={time:null,delay:0,duration:250,ease:yhr};function xhr(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 whr(e){var t,n;e instanceof k0?(t=e._id,e=e._name):(t=qPt(),(n=bhr).time=aNe(),e=e==null?null:e+"");for(var r=this._groups,s=r.length,i=0;i<s;++i)for(var a=r[i],l=a.length,c,u=0;u<l;++u)(c=a[u])&&IQ(c,e,t,u,a,n||xhr(c,t));return new k0(r,this._parents,e,t)}h5.prototype.interrupt=yfr;h5.prototype.transition=whr;const G9=e=>()=>e;function Shr(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 Lx(e,t,n){this.k=e,this.x=t,this.y=n}Lx.prototype={constructor:Lx,scale:function(e){return e===1?this:new Lx(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new Lx(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 AQ=new Lx(1,0,0);HPt.prototype=Lx.prototype;function HPt(e){for(;!e.__zoom;)if(!(e=e.parentNode))return AQ;return e.__zoom}function aie(e){e.stopImmediatePropagation()}function O$(e){e.preventDefault(),e.stopImmediatePropagation()}function khr(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function Ohr(){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 PZe(){return this.__zoom||AQ}function Chr(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function _hr(){return navigator.maxTouchPoints||"ontouchstart"in this}function Ehr(e,t,n){var r=e.invertX(t[0][0])-n[0][0],s=e.invertX(t[1][0])-n[1][0],i=e.invertY(t[0][1])-n[0][1],a=e.invertY(t[1][1])-n[1][1];return e.translate(s>r?(r+s)/2:Math.min(0,r)||Math.max(0,s),a>i?(i+a)/2:Math.min(0,i)||Math.max(0,a))}function WPt(){var e=khr,t=Ohr,n=Ehr,r=Chr,s=_hr,i=[0,1/0],a=[[-1/0,-1/0],[1/0,1/0]],l=250,c=A7,u=TQ("start","zoom","end"),d,f,h,p=500,m=150,v=0,y=10;function b(M){M.property("__zoom",PZe).on("wheel.zoom",E,{passive:!1}).on("mousedown.zoom",N).on("dblclick.zoom",I).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",P).on("touchend.zoom touchcancel.zoom",L).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(M,V,q,H){var B=M.selection?M.selection():M;B.property("__zoom",PZe),M!==B?_(M,V,q,H):B.interrupt().each(function(){C(this,arguments).event(H).start().zoom(null,typeof V=="function"?V.apply(this,arguments):V).end()})},b.scaleBy=function(M,V,q,H){b.scaleTo(M,function(){var B=this.__zoom.k,W=typeof V=="function"?V.apply(this,arguments):V;return B*W},q,H)},b.scaleTo=function(M,V,q,H){b.transform(M,function(){var B=t.apply(this,arguments),W=this.__zoom,z=q==null?k(B):typeof q=="function"?q.apply(this,arguments):q,G=W.invert(z),F=typeof V=="function"?V.apply(this,arguments):V;return n(w(x(W,F),z,G),B,a)},q,H)},b.translateBy=function(M,V,q,H){b.transform(M,function(){return n(this.__zoom.translate(typeof V=="function"?V.apply(this,arguments):V,typeof q=="function"?q.apply(this,arguments):q),t.apply(this,arguments),a)},null,H)},b.translateTo=function(M,V,q,H,B){b.transform(M,function(){var W=t.apply(this,arguments),z=this.__zoom,G=H==null?k(W):typeof H=="function"?H.apply(this,arguments):H;return n(AQ.translate(G[0],G[1]).scale(z.k).translate(typeof V=="function"?-V.apply(this,arguments):-V,typeof q=="function"?-q.apply(this,arguments):-q),W,a)},H,B)};function x(M,V){return V=Math.max(i[0],Math.min(i[1],V)),V===M.k?M:new Lx(V,M.x,M.y)}function w(M,V,q){var H=V[0]-q[0]*M.k,B=V[1]-q[1]*M.k;return H===M.x&&B===M.y?M:new Lx(M.k,H,B)}function k(M){return[(+M[0][0]+ +M[1][0])/2,(+M[0][1]+ +M[1][1])/2]}function _(M,V,q,H){M.on("start.zoom",function(){C(this,arguments).event(H).start()}).on("interrupt.zoom end.zoom",function(){C(this,arguments).event(H).end()}).tween("zoom",function(){var B=this,W=arguments,z=C(B,W).event(H),G=t.apply(B,W),F=q==null?k(G):typeof q=="function"?q.apply(B,W):q,R=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),D=B.__zoom,U=typeof V=="function"?V.apply(B,W):V,Q=c(D.invert(F).concat(R/D.k),U.invert(F).concat(R/U.k));return function(ee){if(ee===1)ee=U;else{var J=Q(ee),te=R/J[2];ee=new Lx(te,F[0]-J[0]*te,F[1]-J[1]*te)}z.zoom(null,ee)}})}function C(M,V,q){return!q&&M.__zooming||new T(M,V)}function T(M,V){this.that=M,this.args=V,this.active=0,this.sourceEvent=null,this.extent=t.apply(M,V),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,V){return this.mouse&&M!=="mouse"&&(this.mouse[1]=V.invert(this.mouse[0])),this.touch0&&M!=="touch"&&(this.touch0[1]=V.invert(this.touch0[0])),this.touch1&&M!=="touch"&&(this.touch1[1]=V.invert(this.touch1[0])),this.that.__zoom=V,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(M){var V=Uh(this.that).datum();u.call(M,this.that,new Shr(M,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),V)}};function E(M,...V){if(!e.apply(this,arguments))return;var q=C(this,V).event(M),H=this.__zoom,B=Math.max(i[0],Math.min(i[1],H.k*Math.pow(2,r.apply(this,arguments)))),W=$g(M);if(q.wheel)(q.mouse[0][0]!==W[0]||q.mouse[0][1]!==W[1])&&(q.mouse[1]=H.invert(q.mouse[0]=W)),clearTimeout(q.wheel);else{if(H.k===B)return;q.mouse=[W,H.invert(W)],$7(this),q.start()}O$(M),q.wheel=setTimeout(z,m),q.zoom("mouse",n(w(x(H,B),q.mouse[0],q.mouse[1]),q.extent,a));function z(){q.wheel=null,q.end()}}function N(M,...V){if(h||!e.apply(this,arguments))return;var q=M.currentTarget,H=C(this,V,!0).event(M),B=Uh(M.view).on("mousemove.zoom",F,!0).on("mouseup.zoom",R,!0),W=$g(M,q),z=M.clientX,G=M.clientY;jPt(M.view),aie(M),H.mouse=[W,this.__zoom.invert(W)],$7(this),H.start();function F(D){if(O$(D),!H.moved){var U=D.clientX-z,Q=D.clientY-G;H.moved=U*U+Q*Q>v}H.event(D).zoom("mouse",n(w(H.that.__zoom,H.mouse[0]=$g(D,q),H.mouse[1]),H.extent,a))}function R(D){B.on("mousemove.zoom mouseup.zoom",null),NPt(D.view,H.moved),O$(D),H.event(D).end()}}function I(M,...V){if(e.apply(this,arguments)){var q=this.__zoom,H=$g(M.changedTouches?M.changedTouches[0]:M,this),B=q.invert(H),W=q.k*(M.shiftKey?.5:2),z=n(w(x(q,W),H,B),t.apply(this,V),a);O$(M),l>0?Uh(this).transition().duration(l).call(_,z,H,M):Uh(this).call(b.transform,z,H,M)}}function A(M,...V){if(e.apply(this,arguments)){var q=M.touches,H=q.length,B=C(this,V,M.changedTouches.length===H).event(M),W,z,G,F;for(aie(M),z=0;z<H;++z)G=q[z],F=$g(G,this),F=[F,this.__zoom.invert(F),G.identifier],B.touch0?!B.touch1&&B.touch0[2]!==F[2]&&(B.touch1=F,B.taps=0):(B.touch0=F,W=!0,B.taps=1+!!d);d&&(d=clearTimeout(d)),W&&(B.taps<2&&(f=F[0],d=setTimeout(function(){d=null},p)),$7(this),B.start())}}function P(M,...V){if(this.__zooming){var q=C(this,V).event(M),H=M.changedTouches,B=H.length,W,z,G,F;for(O$(M),W=0;W<B;++W)z=H[W],G=$g(z,this),q.touch0&&q.touch0[2]===z.identifier?q.touch0[0]=G:q.touch1&&q.touch1[2]===z.identifier&&(q.touch1[0]=G);if(z=q.that.__zoom,q.touch1){var R=q.touch0[0],D=q.touch0[1],U=q.touch1[0],Q=q.touch1[1],ee=(ee=U[0]-R[0])*ee+(ee=U[1]-R[1])*ee,J=(J=Q[0]-D[0])*J+(J=Q[1]-D[1])*J;z=x(z,Math.sqrt(ee/J)),G=[(R[0]+U[0])/2,(R[1]+U[1])/2],F=[(D[0]+Q[0])/2,(D[1]+Q[1])/2]}else if(q.touch0)G=q.touch0[0],F=q.touch0[1];else return;q.zoom("touch",n(w(z,G,F),q.extent,a))}}function L(M,...V){if(this.__zooming){var q=C(this,V).event(M),H=M.changedTouches,B=H.length,W,z;for(aie(M),h&&clearTimeout(h),h=setTimeout(function(){h=null},p),W=0;W<B;++W)z=H[W],q.touch0&&q.touch0[2]===z.identifier?delete q.touch0:q.touch1&&q.touch1[2]===z.identifier&&delete q.touch1;if(q.touch1&&!q.touch0&&(q.touch0=q.touch1,delete q.touch1),q.touch0)q.touch0[1]=this.__zoom.invert(q.touch0[0]);else if(q.end(),q.taps===2&&(z=$g(z,this),Math.hypot(f[0]-z[0],f[1]-z[1])<y)){var G=Uh(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(M){return arguments.length?(r=typeof M=="function"?M:G9(+M),b):r},b.filter=function(M){return arguments.length?(e=typeof M=="function"?M:G9(!!M),b):e},b.touchable=function(M){return arguments.length?(s=typeof M=="function"?M:G9(!!M),b):s},b.extent=function(M){return arguments.length?(t=typeof M=="function"?M:G9([[+M[0][0],+M[0][1]],[+M[1][0],+M[1][1]]]),b):t},b.scaleExtent=function(M){return arguments.length?(i[0]=+M[0],i[1]=+M[1],b):[i[0],i[1]]},b.translateExtent=function(M){return arguments.length?(a[0][0]=+M[0][0],a[1][0]=+M[1][0],a[0][1]=+M[0][1],a[1][1]=+M[1][1],b):[[a[0][0],a[0][1]],[a[1][0],a[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 ab={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."},WL=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],ZPt=["Enter"," ","Escape"],GPt={"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 TI;(function(e){e.Strict="strict",e.Loose="loose"})(TI||(TI={}));var pC;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(pC||(pC={}));var ZL;(function(e){e.Partial="partial",e.Full="full"})(ZL||(ZL={}));const QPt={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var vS;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(vS||(vS={}));var GL;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(GL||(GL={}));var tr;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(tr||(tr={}));const $Ze={[tr.Left]:tr.Right,[tr.Right]:tr.Left,[tr.Top]:tr.Bottom,[tr.Bottom]:tr.Top};function KPt(e){return e===null?null:e?"valid":"invalid"}const YPt=e=>"id"in e&&"source"in e&&"target"in e,Thr=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),cNe=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),m5=(e,t=[0,0])=>{const{width:n,height:r}=Q0(e),s=e.origin??t,i=n*s[0],a=r*s[1];return{x:e.position.x-i,y:e.position.y-a}},jhr=(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 i=typeof s=="string";let a=!t.nodeLookup&&!i?s:void 0;t.nodeLookup&&(a=i?t.nodeLookup.get(s):cNe(s)?s:t.nodeLookup.get(s.id));const l=a?dH(a,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return RQ(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return PQ(n)},g5=(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=RQ(n,dH(s)),r=!0)}),r?PQ(n):{x:0,y:0,width:0,height:0}},uNe=(e,t,[n,r,s]=[0,0,1],i=!1,a=!1)=>{const l={...y5(t,[n,r,s]),width:t.width/s,height:t.height/s},c=[];for(const u of e.values()){const{measured:d,selectable:f=!0,hidden:h=!1}=u;if(a&&!f||h)continue;const p=d.width??u.width??u.initialWidth??null,m=d.height??u.height??u.initialHeight??null,v=QL(l,NI(u)),y=(p??0)*(m??0),b=i&&v>0;(!u.internals.handleBounds||b||v>=y||u.dragging)&&c.push(u)}return c},Nhr=(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 Ihr(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 Ahr({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:i},a){if(e.size===0)return Promise.resolve(!0);const l=Ihr(e,a),c=g5(l),u=dNe(c,t,n,a?.minZoom??s,a?.maxZoom??i,a?.padding??.1);return await r.setViewport(u,{duration:a?.duration,ease:a?.ease,interpolate:a?.interpolate}),Promise.resolve(!0)}function XPt({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:s,onError:i}){const a=n.get(e),l=a.parentId?n.get(a.parentId):void 0,{x:c,y:u}=l?l.internals.positionAbsolute:{x:0,y:0},d=a.origin??r;let f=a.extent||s;if(a.extent==="parent"&&!a.expandParent)if(!l)i?.("005",ab.error005());else{const p=l.measured.width,m=l.measured.height;p&&m&&(f=[[c,u],[c+p,u+m]])}else l&&II(a.extent)&&(f=[[a.extent[0][0]+c,a.extent[0][1]+u],[a.extent[1][0]+c,a.extent[1][1]+u]]);const h=II(f)?c_(t,f,a.measured):t;return(a.measured.width===void 0||a.measured.height===void 0)&&i?.("015",ab.error015()),{position:{x:h.x-c+(a.measured.width??0)*d[0],y:h.y-u+(a.measured.height??0)*d[1]},positionAbsolute:h}}async function Rhr({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const i=new Set(e.map(h=>h.id)),a=[];for(const h of n){if(h.deletable===!1)continue;const p=i.has(h.id),m=!p&&h.parentId&&a.find(v=>v.id===h.parentId);(p||m)&&a.push(h)}const l=new Set(t.map(h=>h.id)),c=r.filter(h=>h.deletable!==!1),d=Nhr(a,c);for(const h of c)l.has(h.id)&&!d.find(m=>m.id===h.id)&&d.push(h);if(!s)return{edges:d,nodes:a};const f=await s({nodes:a,edges:d});return typeof f=="boolean"?f?{edges:d,nodes:a}:{edges:[],nodes:[]}:f}const jI=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),c_=(e={x:0,y:0},t,n)=>({x:jI(e.x,t[0][0],t[1][0]-(n?.width??0)),y:jI(e.y,t[0][1],t[1][1]-(n?.height??0))});function JPt(e,t,n){const{width:r,height:s}=Q0(n),{x:i,y:a}=n.internals.positionAbsolute;return c_(e,[[i,a],[i+r,a+s]],t)}const MZe=(e,t,n)=>e<t?jI(Math.abs(e-t),1,t)/t:e>n?-jI(Math.abs(e-n),1,t)/t:0,e$t=(e,t,n=15,r=40)=>{const s=MZe(e.x,r,t.width-r)*n,i=MZe(e.y,r,t.height-r)*n;return[s,i]},RQ=(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)}),twe=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),PQ=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),NI=(e,t=[0,0])=>{const{x:n,y:r}=cNe(e)?e.internals.positionAbsolute:m5(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}},dH=(e,t=[0,0])=>{const{x:n,y:r}=cNe(e)?e.internals.positionAbsolute:m5(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)}},t$t=(e,t)=>PQ(RQ(twe(e),twe(t))),QL=(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)},DZe=e=>Wg(e.width)&&Wg(e.height)&&Wg(e.x)&&Wg(e.y),Wg=e=>!isNaN(e)&&isFinite(e),Phr=(e,t)=>{},v5=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),y5=({x:e,y:t},[n,r,s],i=!1,a=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return i?v5(l,a):l},fH=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function IT(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 $hr(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=IT(e,n),s=IT(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=IT(e.top??e.y??0,n),s=IT(e.bottom??e.y??0,n),i=IT(e.left??e.x??0,t),a=IT(e.right??e.x??0,t);return{top:r,right:a,bottom:s,left:i,x:i+a,y:r+s}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function Mhr(e,t,n,r,s,i){const{x:a,y:l}=fH(e,[t,n,r]),{x:c,y:u}=fH({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=s-c,f=i-u;return{left:Math.floor(a),top:Math.floor(l),right:Math.floor(d),bottom:Math.floor(f)}}const dNe=(e,t,n,r,s,i)=>{const a=$hr(i,t,n),l=(t-a.x)/e.width,c=(n-a.y)/e.height,u=Math.min(l,c),d=jI(u,r,s),f=e.x+e.width/2,h=e.y+e.height/2,p=t/2-f*d,m=n/2-h*d,v=Mhr(e,p,m,d,t,n),y={left:Math.min(v.left-a.left,0),top:Math.min(v.top-a.top,0),right:Math.min(v.right-a.right,0),bottom:Math.min(v.bottom-a.bottom,0)};return{x:p-y.left+y.right,y:m-y.top+y.bottom,zoom:d}},KL=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function II(e){return e!=null&&e!=="parent"}function Q0(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function fNe(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function n$t(e,t={width:0,height:0},n,r,s){const i={...e},a=r.get(n);if(a){const l=a.origin||s;i.x+=a.internals.positionAbsolute.x-(t.width??0)*l[0],i.y+=a.internals.positionAbsolute.y-(t.height??0)*l[1]}return i}function LZe(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function Dhr(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function Lhr(e){return{...GPt,...e||{}}}function L2(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:i,y:a}=Zg(e),l=y5({x:i-(s?.left??0),y:a-(s?.top??0)},r),{x:c,y:u}=n?v5(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const hNe=e=>({width:e.offsetWidth,height:e.offsetHeight}),r$t=e=>e?.getRootNode?.()||window?.document,Fhr=["INPUT","SELECT","TEXTAREA"];function s$t(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:Fhr.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const i$t=e=>"clientX"in e,Zg=(e,t)=>{const n=i$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)}},FZe=(e,t,n,r,s)=>{const i=t.querySelectorAll(`.${e}`);return!i||!i.length?null:Array.from(i).map(a=>{const l=a.getBoundingClientRect();return{id:a.getAttribute("data-handleid"),type:e,nodeId:s,position:a.getAttribute("data-handlepos"),x:(l.left-n.left)/r,y:(l.top-n.top)/r,...hNe(a)}})};function a$t({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:s,sourceControlY:i,targetControlX:a,targetControlY:l}){const c=e*.125+s*.375+a*.375+n*.125,u=t*.125+i*.375+l*.375+r*.125,d=Math.abs(c-e),f=Math.abs(u-t);return[c,u,d,f]}function Q9(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function zZe({pos:e,x1:t,y1:n,x2:r,y2:s,c:i}){switch(e){case tr.Left:return[t-Q9(t-r,i),n];case tr.Right:return[t+Q9(r-t,i),n];case tr.Top:return[t,n-Q9(n-s,i)];case tr.Bottom:return[t,n+Q9(s-n,i)]}}function pNe({sourceX:e,sourceY:t,sourcePosition:n=tr.Bottom,targetX:r,targetY:s,targetPosition:i=tr.Top,curvature:a=.25}){const[l,c]=zZe({pos:n,x1:e,y1:t,x2:r,y2:s,c:a}),[u,d]=zZe({pos:i,x1:r,y1:s,x2:e,y2:t,c:a}),[f,h,p,m]=a$t({sourceX:e,sourceY:t,targetX:r,targetY:s,sourceControlX:l,sourceControlY:c,targetControlX:u,targetControlY:d});return[`M${e},${t} C${l},${c} ${u},${d} ${r},${s}`,f,h,p,m]}function o$t({sourceX:e,sourceY:t,targetX:n,targetY:r}){const s=Math.abs(n-e)/2,i=n<e?n+s:n-s,a=Math.abs(r-t)/2,l=r<t?r+a:r-a;return[i,l,s,a]}function zhr({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:s=!1,zIndexMode:i="basic"}){if(i==="manual")return r;const a=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 a+l}function Bhr({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const i=RQ(dH(e),dH(t));i.x===i.x2&&(i.x2+=1),i.y===i.y2&&(i.y2+=1);const a={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:r/s[2]};return QL(a,PQ(i))>0}const Uhr=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,Vhr=(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)),qhr=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||Uhr;let s;return YPt(e)?s={...e}:s={...e,id:r(e)},Vhr(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function l$t({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,i,a,l]=o$t({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,i,a,l]}const BZe={[tr.Left]:{x:-1,y:0},[tr.Right]:{x:1,y:0},[tr.Top]:{x:0,y:-1},[tr.Bottom]:{x:0,y:1}},Hhr=({source:e,sourcePosition:t=tr.Bottom,target:n})=>t===tr.Left||t===tr.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},UZe=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function Whr({source:e,sourcePosition:t=tr.Bottom,target:n,targetPosition:r=tr.Top,center:s,offset:i,stepPosition:a}){const l=BZe[t],c=BZe[r],u={x:e.x+l.x*i,y:e.y+l.y*i},d={x:n.x+c.x*i,y:n.y+c.y*i},f=Hhr({source:u,sourcePosition:t,target:d}),h=f.x!==0?"x":"y",p=f[h];let m=[],v,y;const b={x:0,y:0},x={x:0,y:0},[,,w,k]=o$t({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[h]*c[h]===-1){h==="x"?(v=s.x??u.x+(d.x-u.x)*a,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)*a);const E=[{x:v,y:u.y},{x:v,y:d.y}],N=[{x:u.x,y},{x:d.x,y}];l[h]===p?m=h==="x"?E:N:m=h==="x"?N:E}else{const E=[{x:u.x,y:d.y}],N=[{x:d.x,y:u.y}];if(h==="x"?m=l.x===p?N:E:m=l.y===p?E:N,t===r){const M=Math.abs(e[h]-n[h]);if(M<=i){const V=Math.min(i-1,i-M);l[h]===p?b[h]=(u[h]>e[h]?-1:1)*V:x[h]=(d[h]>n[h]?-1:1)*V}}if(t!==r){const M=h==="x"?"y":"x",V=l[h]===c[M],q=u[M]>d[M],H=u[M]<d[M];(l[h]===1&&(!V&&q||V&&H)||l[h]!==1&&(!V&&H||V&&q))&&(m=h==="x"?E:N)}const I={x:u.x+b.x,y:u.y+b.y},A={x:d.x+x.x,y:d.y+x.y},P=Math.max(Math.abs(I.x-m[0].x),Math.abs(A.x-m[0].x)),L=Math.max(Math.abs(I.y-m[0].y),Math.abs(A.y-m[0].y));P>=L?(v=(I.x+A.x)/2,y=m[0].y):(v=m[0].x,y=(I.y+A.y)/2)}const _={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,w,k]}function Zhr(e,t,n,r){const s=Math.min(UZe(e,t)/2,UZe(t,n)/2,r),{x:i,y:a}=t;if(e.x===i&&i===n.x||e.y===a&&a===n.y)return`L${i} ${a}`;if(e.y===a){const u=e.x<n.x?-1:1,d=e.y<n.y?1:-1;return`L ${i+s*u},${a}Q ${i},${a} ${i},${a+s*d}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${i},${a+s*c}Q ${i},${a} ${i+s*l},${a}`}function nwe({sourceX:e,sourceY:t,sourcePosition:n=tr.Bottom,targetX:r,targetY:s,targetPosition:i=tr.Top,borderRadius:a=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,h,p,m,v]=Whr({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:s},targetPosition:i,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+=Zhr(f[b-1],f[b],f[b+1],a);return y+=`L${f[f.length-1].x} ${f[f.length-1].y}`,[y,h,p,m,v]}function VZe(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function Ghr(e){const{sourceNode:t,targetNode:n}=e;if(!VZe(t)||!VZe(n))return null;const r=t.internals.handleBounds||qZe(t.handles),s=n.internals.handleBounds||qZe(n.handles),i=HZe(r?.source??[],e.sourceHandle),a=HZe(e.connectionMode===TI.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!i||!a)return e.onError?.("008",ab.error008(i?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=i?.position||tr.Bottom,c=a?.position||tr.Top,u=u_(t,i,l),d=u_(n,a,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function qZe(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 u_(e,t,n=tr.Left,r=!1){const s=(t?.x??0)+e.internals.positionAbsolute.x,i=(t?.y??0)+e.internals.positionAbsolute.y,{width:a,height:l}=t??Q0(e);if(r)return{x:s+a/2,y:i+l/2};switch(t?.position??n){case tr.Top:return{x:s+a/2,y:i};case tr.Right:return{x:s+a,y:i+l/2};case tr.Bottom:return{x:s+a/2,y:i+l};case tr.Left:return{x:s,y:i+l/2}}}function HZe(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function rwe(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function Qhr(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:s}){const i=new Set;return e.reduce((a,l)=>([l.markerStart||r,l.markerEnd||s].forEach(c=>{if(c&&typeof c=="object"){const u=rwe(c,t);i.has(u)||(a.push({id:u,color:c.color||n,...c}),i.add(u))}}),a),[]).sort((a,l)=>a.id.localeCompare(l.id))}const c$t=1e3,Khr=10,mNe={nodeOrigin:[0,0],nodeExtent:WL,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},Yhr={...mNe,checkEquality:!0};function gNe(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function Xhr(e,t,n){const r=gNe(mNe,n);for(const s of e.values())if(s.parentId)yNe(s,e,t,r);else{const i=m5(s,r.nodeOrigin),a=II(s.extent)?s.extent:r.nodeExtent,l=c_(i,a,Q0(s));s.internals.positionAbsolute=l}}function Jhr(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;const n=[],r=[];for(const s of e.handles){const i={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(i):s.type==="target"&&r.push(i)}return{source:n,target:r}}function vNe(e){return e==="manual"}function swe(e,t,n,r={}){const s=gNe(Yhr,r),i={i:0},a=new Map(t),l=s?.elevateNodesOnSelect&&!vNe(s.zIndexMode)?c$t:0;let c=e.length>0,u=!1;t.clear(),n.clear();for(const d of e){let f=a.get(d.id);if(s.checkEquality&&d===f?.internals.userNode)t.set(d.id,f);else{const h=m5(d,s.nodeOrigin),p=II(d.extent)?d.extent:s.nodeExtent,m=c_(h,p,Q0(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:Jhr(d,f),z:u$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&&yNe(f,t,n,r,i),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function epr(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 yNe(e,t,n,r,s){const{elevateNodesOnSelect:i,nodeOrigin:a,nodeExtent:l,zIndexMode:c}=gNe(mNe,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}epr(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*Khr),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=i&&!vNe(c)?c$t:0,{x:h,y:p,z:m}=tpr(e,d,a,l,f,c),{positionAbsolute:v}=e.internals,y=h!==v.x||p!==v.y;(y||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:h,y:p}:v,z:m}})}function u$t(e,t,n){const r=Wg(e.zIndex)?e.zIndex:0;return vNe(n)?r:r+(e.selected?t:0)}function tpr(e,t,n,r,s,i){const{x:a,y:l}=t.internals.positionAbsolute,c=Q0(e),u=m5(e,n),d=II(e.extent)?c_(u,e.extent,c):u;let f=c_({x:a+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=JPt(f,c,t));const h=u$t(e,s,i),p=t.internals.z??0;return{x:f.x,y:f.y,z:p>=h?p+1:h}}function bNe(e,t,n,r=[0,0]){const s=[],i=new Map;for(const a of e){const l=t.get(a.parentId);if(!l)continue;const c=i.get(a.parentId)?.expandedRect??NI(l),u=t$t(c,a.rect);i.set(a.parentId,{expandedRect:u,parent:l})}return i.size>0&&i.forEach(({expandedRect:a,parent:l},c)=>{const u=l.internals.positionAbsolute,d=Q0(l),f=l.origin??r,h=a.x<u.x?Math.round(Math.abs(u.x-a.x)):0,p=a.y<u.y?Math.round(Math.abs(u.y-a.y)):0,m=Math.max(d.width,Math.round(a.width)),v=Math.max(d.height,Math.round(a.height)),y=(m-d.width)*f[0],b=(v-d.height)*f[1];(h>0||p>0||y||b)&&(s.push({id:c,type:"position",position:{x:l.position.x-h+y,y:l.position.y-p+b}}),n.get(c)?.forEach(x=>{e.some(w=>w.id===x.id)||s.push({id:x.id,type:"position",position:{x:x.position.x+h,y:x.position.y+p}})})),(d.width<a.width||d.height<a.height||h||p)&&s.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:m+(h?f[0]*h-y:0),height:v+(p?f[1]*p-b:0)}})}),s}function npr(e,t,n,r,s,i,a){const l=r?.querySelector(".xyflow__viewport");let c=!1;if(!l)return{changes:[],updatedInternals:c};const u=[],d=window.getComputedStyle(l),{m22:f}=new window.DOMMatrixReadOnly(d.transform),h=[];for(const p of e.values()){const m=t.get(p.id);if(!m)continue;if(m.hidden){t.set(m.id,{...m,internals:{...m.internals,handleBounds:void 0}}),c=!0;continue}const v=hNe(p.nodeElement),y=m.measured.width!==v.width||m.measured.height!==v.height;if(!!(v.width&&v.height&&(y||!m.internals.handleBounds||p.force))){const x=p.nodeElement.getBoundingClientRect(),w=II(m.extent)?m.extent:i;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=JPt(k,v,t.get(m.parentId)):w&&(k=c_(k,w,v));const _={...m,measured:v,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:FZe("source",p.nodeElement,x,f,m.id),target:FZe("target",p.nodeElement,x,f,m.id)}}};t.set(m.id,_),m.parentId&&yNe(_,t,n,{nodeOrigin:s,zIndexMode:a}),c=!0,y&&(u.push({id:m.id,type:"dimensions",dimensions:v}),m.expandParent&&m.parentId&&h.push({id:m.id,parentId:m.parentId,rect:NI(_,s)}))}}if(h.length>0){const p=bNe(h,t,n,s);u.push(...p)}return{changes:u,updatedInternals:c}}async function rpr({delta:e,panZoom:t,transform:n,translateExtent:r,width:s,height:i}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const a=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[s,i]],r),l=!!a&&(a.x!==n[0]||a.y!==n[1]||a.k!==n[2]);return Promise.resolve(l)}function WZe(e,t,n,r,s,i){let a=s;const l=r.get(a)||new Map;r.set(a,l.set(n,t)),a=`${s}-${e}`;const c=r.get(a)||new Map;if(r.set(a,c.set(n,t)),i){a=`${s}-${e}-${i}`;const u=r.get(a)||new Map;r.set(a,u.set(n,t))}}function d$t(e,t,n){e.clear(),t.clear();for(const r of n){const{source:s,target:i,sourceHandle:a=null,targetHandle:l=null}=r,c={edgeId:r.id,source:s,target:i,sourceHandle:a,targetHandle:l},u=`${s}-${a}--${i}-${l}`,d=`${i}-${l}--${s}-${a}`;WZe("source",c,d,e,s,a),WZe("target",c,u,e,i,l),t.set(r.id,r)}}function f$t(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:f$t(n,t):!1}function ZZe(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 spr(e,t,n,r){const s=new Map;for(const[i,a]of e)if((a.selected||a.id===r)&&(!a.parentId||!f$t(a,e))&&(a.draggable||t&&typeof a.draggable>"u")){const l=e.get(i);l&&s.set(i,{id:i,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 oie({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){const s=[];for(const[a,l]of t){const c=n.get(a)?.internals.userNode;c&&s.push({...c,position:l.position,dragging:r})}if(!e)return[s[0],s];const i=n.get(e)?.internals.userNode;return[i?{...i,position:t.get(e)?.position||i.position,dragging:r}:s[0],s]}function ipr({dragItems:e,snapGrid:t,x:n,y:r}){const s=e.values().next().value;if(!s)return null;const i={x:n-s.distance.x,y:r-s.distance.y},a=v5(i,t);return{x:a.x-i.x,y:a.y-i.y}}function apr({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:s}){let i={x:null,y:null},a=0,l=new Map,c=!1,u={x:0,y:0},d=null,f=!1,h=null,p=!1,m=!1,v=null;function y({noDragClassName:x,handleSelector:w,domNode:k,isSelectable:_,nodeId:C,nodeClickDistance:T=0}){h=Uh(k);function E({x:P,y:L}){const{nodeLookup:M,nodeExtent:V,snapGrid:q,snapToGrid:H,nodeOrigin:B,onNodeDrag:W,onSelectionDrag:z,onError:G,updateNodePositions:F}=t();i={x:P,y:L};let R=!1;const D=l.size>1,U=D&&V?twe(g5(l)):null,Q=D&&H?ipr({dragItems:l,snapGrid:q,x:P,y:L}):null;for(const[ee,J]of l){if(!M.has(ee))continue;let te={x:P-J.distance.x,y:L-J.distance.y};H&&(te=Q?{x:Math.round(te.x+Q.x),y:Math.round(te.y+Q.y)}:v5(te,q));let re=null;if(D&&V&&!J.extent&&U){const{positionAbsolute:ne}=J.internals,se=ne.x-U.x+V[0][0],le=ne.x+J.measured.width-U.x2+V[1][0],he=ne.y-U.y+V[0][1],pe=ne.y+J.measured.height-U.y2+V[1][1];re=[[se,he],[le,pe]]}const{position:ce,positionAbsolute:X}=XPt({nodeId:ee,nextPosition:te,nodeLookup:M,nodeExtent:re||V,nodeOrigin:B,onError:G});R=R||J.position.x!==ce.x||J.position.y!==ce.y,J.position=ce,J.internals.positionAbsolute=X}if(m=m||R,!!R&&(F(l,!0),v&&(r||W||!C&&z))){const[ee,J]=oie({nodeId:C,dragItems:l,nodeLookup:M});r?.(v,l,ee,J),W?.(v,ee,J),C||z?.(v,J)}}async function N(){if(!d)return;const{transform:P,panBy:L,autoPanSpeed:M,autoPanOnNodeDrag:V}=t();if(!V){c=!1,cancelAnimationFrame(a);return}const[q,H]=e$t(u,d,M);(q!==0||H!==0)&&(i.x=(i.x??0)-q/P[2],i.y=(i.y??0)-H/P[2],await L({x:q,y:H})&&E(i)),a=requestAnimationFrame(N)}function I(P){const{nodeLookup:L,multiSelectionActive:M,nodesDraggable:V,transform:q,snapGrid:H,snapToGrid:B,selectNodesOnDrag:W,onNodeDragStart:z,onSelectionDragStart:G,unselectNodesAndEdges:F}=t();f=!0,(!W||!_)&&!M&&C&&(L.get(C)?.selected||F()),_&&W&&C&&e?.(C);const R=L2(P.sourceEvent,{transform:q,snapGrid:H,snapToGrid:B,containerBounds:d});if(i=R,l=spr(L,V,R,C),l.size>0&&(n||z||!C&&G)){const[D,U]=oie({nodeId:C,dragItems:l,nodeLookup:L});n?.(P.sourceEvent,l,D,U),z?.(P.sourceEvent,D,U),C||G?.(P.sourceEvent,U)}}const A=IPt().clickDistance(T).on("start",P=>{const{domNode:L,nodeDragThreshold:M,transform:V,snapGrid:q,snapToGrid:H}=t();d=L?.getBoundingClientRect()||null,p=!1,m=!1,v=P.sourceEvent,M===0&&I(P),i=L2(P.sourceEvent,{transform:V,snapGrid:q,snapToGrid:H,containerBounds:d}),u=Zg(P.sourceEvent,d)}).on("drag",P=>{const{autoPanOnNodeDrag:L,transform:M,snapGrid:V,snapToGrid:q,nodeDragThreshold:H,nodeLookup:B}=t(),W=L2(P.sourceEvent,{transform:M,snapGrid:V,snapToGrid:q,containerBounds:d});if(v=P.sourceEvent,(P.sourceEvent.type==="touchmove"&&P.sourceEvent.touches.length>1||C&&!B.has(C))&&(p=!0),!p){if(!c&&L&&f&&(c=!0,N()),!f){const z=Zg(P.sourceEvent,d),G=z.x-u.x,F=z.y-u.y;Math.sqrt(G*G+F*F)>H&&I(P)}(i.x!==W.xSnapped||i.y!==W.ySnapped)&&l&&f&&(u=Zg(P.sourceEvent,d),E(W))}}).on("end",P=>{if(!(!f||p)&&(c=!1,f=!1,cancelAnimationFrame(a),l.size>0)){const{nodeLookup:L,updateNodePositions:M,onNodeDragStop:V,onSelectionDragStop:q}=t();if(m&&(M(l,!1),m=!1),s||V||!C&&q){const[H,B]=oie({nodeId:C,dragItems:l,nodeLookup:L,dragging:!1});s?.(P.sourceEvent,l,H,B),V?.(P.sourceEvent,H,B),C||q?.(P.sourceEvent,B)}}}).filter(P=>{const L=P.target;return!P.button&&(!x||!ZZe(L,`.${x}`,k))&&(!w||ZZe(L,w,k))});h.call(A)}function b(){h?.on(".drag",null)}return{update:y,destroy:b}}function opr(e,t,n){const r=[],s={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const i of t.values())QL(s,NI(i))>0&&r.push(i);return r}const lpr=250;function cpr(e,t,n,r){let s=[],i=1/0;const a=opr(e,n,t+lpr);for(const l of a){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}=u_(l,u,u.position,!0),h=Math.sqrt(Math.pow(d-e.x,2)+Math.pow(f-e.y,2));h>t||(h<i?(s=[{...u,x:d,y:f}],i=h):h===i&&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 h$t(e,t,n,r,s,i=!1){const a=r.get(e);if(!a)return null;const l=s==="strict"?a.internals.handleBounds?.[t]:[...a.internals.handleBounds?.source??[],...a.internals.handleBounds?.target??[]],c=(n?l?.find(u=>u.id===n):l?.[0])??null;return c&&i?{...c,...u_(a,c,c.position,!0)}:c}function p$t(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function upr(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const m$t=()=>!0;function dpr(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:i,isTarget:a,domNode:l,nodeLookup:c,lib:u,autoPanOnConnect:d,flowId:f,panBy:h,cancelConnection:p,onConnectStart:m,onConnect:v,onConnectEnd:y,isValidConnection:b=m$t,onReconnectEnd:x,updateConnection:w,getTransform:k,getFromHandle:_,autoPanSpeed:C,dragThreshold:T=1,handleDomNode:E}){const N=r$t(e.target);let I=0,A;const{x:P,y:L}=Zg(e),M=p$t(i,E),V=l?.getBoundingClientRect();let q=!1;if(!V||!M)return;const H=h$t(s,M,r,c,t);if(!H)return;let B=Zg(e,V),W=!1,z=null,G=!1,F=null;function R(){if(!d||!V)return;const[ce,X]=e$t(B,V,C);h({x:ce,y:X}),I=requestAnimationFrame(R)}const D={...H,nodeId:s,type:M,position:H.position},U=c.get(s);let ee={inProgress:!0,isValid:null,from:u_(U,D,tr.Left,!0),fromHandle:D,fromPosition:D.position,fromNode:U,to:B,toHandle:null,toPosition:$Ze[D.position],toNode:null,pointer:B};function J(){q=!0,w(ee),m?.(e,{nodeId:s,handleId:r,handleType:M})}T===0&&J();function te(ce){if(!q){const{x:pe,y:Se}=Zg(ce),Ee=pe-P,Re=Se-L;if(!(Ee*Ee+Re*Re>T*T))return;J()}if(!_()||!D){re(ce);return}const X=k();B=Zg(ce,V),A=cpr(y5(B,X,!1,[1,1]),n,c,D),W||(R(),W=!0);const ne=g$t(ce,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:a?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});F=ne.handleDomNode,z=ne.connection,G=upr(!!A,ne.isValid);const se=c.get(s),le=se?u_(se,D,tr.Left,!0):ee.from,he={...ee,from:le,isValid:G,to:ne.toHandle&&G?fH({x:ne.toHandle.x,y:ne.toHandle.y},X):B,toHandle:ne.toHandle,toPosition:G&&ne.toHandle?ne.toHandle.position:$Ze[D.position],toNode:ne.toHandle?c.get(ne.toHandle.nodeId):null,pointer:B};w(he),ee=he}function re(ce){if(!("touches"in ce&&ce.touches.length>0)){if(q){(A||F)&&z&&G&&v?.(z);const{inProgress:X,...ne}=ee,se={...ne,toPosition:ee.toHandle?ee.toPosition:null};y?.(ce,se),i&&x?.(ce,se)}p(),cancelAnimationFrame(I),W=!1,G=!1,z=null,F=null,N.removeEventListener("mousemove",te),N.removeEventListener("mouseup",re),N.removeEventListener("touchmove",te),N.removeEventListener("touchend",re)}}N.addEventListener("mousemove",te),N.addEventListener("mouseup",re),N.addEventListener("touchmove",te),N.addEventListener("touchend",re)}function g$t(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:i,doc:a,lib:l,flowId:c,isValidConnection:u=m$t,nodeLookup:d}){const f=i==="target",h=t?a.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:p,y:m}=Zg(e),v=a.elementFromPoint(p,m),y=v?.classList.contains(`${l}-flow__handle`)?v:h,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){const x=p$t(void 0,y),w=y.getAttribute("data-nodeid"),k=y.getAttribute("data-handleid"),_=y.classList.contains("connectable"),C=y.classList.contains("connectableend");if(!w||!x)return b;const T={source:f?w:r,sourceHandle:f?k:s,target:f?r:w,targetHandle:f?s:k};b.connection=T;const N=_&&C&&(n===TI.Strict?f&&x==="source"||!f&&x==="target":w!==r||k!==s);b.isValid=N&&u(T),b.toHandle=h$t(w,x,k,d,n,!0)}return b}const iwe={onPointerDown:dpr,isValid:g$t};function fpr({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Uh(e);function i({translateExtent:l,width:c,height:u,zoomStep:d=1,pannable:f=!0,zoomable:h=!0,inversePan:p=!1}){const m=w=>{if(w.sourceEvent.type!=="wheel"||!t)return;const k=n(),_=w.sourceEvent.ctrlKey&&KL()?10:1,C=-w.sourceEvent.deltaY*(w.sourceEvent.deltaMode===1?.05:w.sourceEvent.deltaMode?1:.002)*d,T=k[2]*Math.pow(2,C*_);t.scaleTo(T)};let v=[0,0];const y=w=>{(w.sourceEvent.type==="mousedown"||w.sourceEvent.type==="touchstart")&&(v=[w.sourceEvent.clientX??w.sourceEvent.touches[0].clientX,w.sourceEvent.clientY??w.sourceEvent.touches[0].clientY])},b=w=>{const k=n();if(w.sourceEvent.type!=="mousemove"&&w.sourceEvent.type!=="touchmove"||!t)return;const _=[w.sourceEvent.clientX??w.sourceEvent.touches[0].clientX,w.sourceEvent.clientY??w.sourceEvent.touches[0].clientY],C=[_[0]-v[0],_[1]-v[1]];v=_;const T=r()*Math.max(k[2],Math.log(k[2]))*(p?-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=WPt().on("start",y).on("zoom",f?b:null).on("zoom.wheel",h?m:null);s.call(x,{})}function a(){s.on("zoom",null)}return{update:i,destroy:a,pointer:$g}}const $Q=e=>({x:e.x,y:e.y,zoom:e.k}),lie=({x:e,y:t,zoom:n})=>AQ.translate(e,t).scale(n),Fj=(e,t)=>e.target.closest(`.${t}`),v$t=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),hpr=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,cie=(e,t=0,n=hpr,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},y$t=e=>{const t=e.ctrlKey&&KL()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function ppr({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:i,zoomOnPinch:a,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(Fj(d,t))return d.ctrlKey&&d.preventDefault(),!1;d.preventDefault(),d.stopImmediatePropagation();const f=n.property("__zoom").k||1;if(d.ctrlKey&&a){const y=$g(d),b=y$t(d),x=f*Math.pow(2,b);r.scaleTo(n,x,y,d);return}const h=d.deltaMode===1?20:1;let p=s===pC.Vertical?0:d.deltaX*h,m=s===pC.Horizontal?0:d.deltaY*h;!KL()&&d.shiftKey&&s!==pC.Vertical&&(p=d.deltaY*h,m=0),r.translateBy(n,-(p/f)*i,-(m/f)*i,{internal:!0});const v=$Q(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 mpr({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const i=r.type==="wheel",a=!t&&i&&!r.ctrlKey,l=Fj(r,e);if(r.ctrlKey&&i&&l&&r.preventDefault(),a||l)return null;r.preventDefault(),n.call(this,r,s)}}function gpr({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=$Q(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 vpr({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return i=>{e.usedRightMouseButton=!!(n&&v$t(t,e.mouseButton??0)),i.sourceEvent?.sync||r([i.transform.x,i.transform.y,i.transform.k]),s&&!i.sourceEvent?.internal&&s?.(i.sourceEvent,$Q(i.transform))}}function ypr({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:i}){return a=>{if(!a.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,i&&v$t(t,e.mouseButton??0)&&!e.usedRightMouseButton&&a.sourceEvent&&i(a.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=$Q(a.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(a.sourceEvent,l)},n?150:0)}}}function bpr({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:s,zoomOnDoubleClick:i,userSelectionActive:a,noWheelClassName:l,noPanClassName:c,lib:u,connectionInProgress:d}){return f=>{const h=e||t,p=n&&f.ctrlKey,m=f.type==="wheel";if(f.button===1&&f.type==="mousedown"&&(Fj(f,`${u}-flow__node`)||Fj(f,`${u}-flow__edge`)))return!0;if(!r&&!h&&!s&&!i&&!n||a||d&&!m||Fj(f,l)&&m||Fj(f,c)&&(!m||s&&m&&!e)||!n&&f.ctrlKey&&m)return!1;if(!n&&f.type==="touchstart"&&f.touches?.length>1)return f.preventDefault(),!1;if(!h&&!s&&!p&&m||!r&&(f.type==="mousedown"||f.type==="touchstart")||Array.isArray(r)&&!r.includes(f.button)&&f.type==="mousedown")return!1;const v=Array.isArray(r)&&r.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||m)&&v}}function xpr({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:s,onPanZoom:i,onPanZoomStart:a,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=WPt().scaleExtent([t,n]).translateExtent(r),h=Uh(e).call(f);x({x:s.x,y:s.y,zoom:jI(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const p=h.on("wheel.zoom"),m=h.on("dblclick.zoom");f.wheelDelta(y$t);function v(A,P){return h?new Promise(L=>{f?.interpolate(P?.interpolate==="linear"?t0:A7).transform(cie(h,P?.duration,P?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:P,onPaneContextMenu:L,userSelectionActive:M,panOnScroll:V,panOnDrag:q,panOnScrollMode:H,panOnScrollSpeed:B,preventScrolling:W,zoomOnPinch:z,zoomOnScroll:G,zoomOnDoubleClick:F,zoomActivationKeyPressed:R,lib:D,onTransformChange:U,connectionInProgress:Q,paneClickDistance:ee,selectionOnDrag:J}){M&&!u.isZoomingOrPanning&&b();const te=V&&!R&&!M;f.clickDistance(J?1/0:!Wg(ee)||ee<0?0:ee);const re=te?ppr({zoomPanValues:u,noWheelClassName:A,d3Selection:h,d3Zoom:f,panOnScrollMode:H,panOnScrollSpeed:B,zoomOnPinch:z,onPanZoomStart:a,onPanZoom:i,onPanZoomEnd:l}):mpr({noWheelClassName:A,preventScrolling:W,d3ZoomHandler:p});if(h.on("wheel.zoom",re,{passive:!1}),!M){const X=gpr({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:a});f.on("start",X);const ne=vpr({zoomPanValues:u,panOnDrag:q,onPaneContextMenu:!!L,onPanZoom:i,onTransformChange:U});f.on("zoom",ne);const se=ypr({zoomPanValues:u,panOnDrag:q,panOnScroll:V,onPaneContextMenu:L,onPanZoomEnd:l,onDraggingChange:c});f.on("end",se)}const ce=bpr({zoomActivationKeyPressed:R,panOnDrag:q,zoomOnScroll:G,panOnScroll:V,zoomOnDoubleClick:F,zoomOnPinch:z,userSelectionActive:M,noPanClassName:P,noWheelClassName:A,lib:D,connectionInProgress:Q});f.filter(ce),F?h.on("dblclick.zoom",m):h.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,P,L){const M=lie(A),V=f?.constrain()(M,P,L);return V&&await v(V),new Promise(q=>q(V))}async function w(A,P){const L=lie(A);return await v(L,P),new Promise(M=>M(L))}function k(A){if(h){const P=lie(A),L=h.property("__zoom");(L.k!==A.zoom||L.x!==A.x||L.y!==A.y)&&f?.transform(h,P,null,{sync:!0})}}function _(){const A=h?HPt(h.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function C(A,P){return h?new Promise(L=>{f?.interpolate(P?.interpolate==="linear"?t0:A7).scaleTo(cie(h,P?.duration,P?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function T(A,P){return h?new Promise(L=>{f?.interpolate(P?.interpolate==="linear"?t0:A7).scaleBy(cie(h,P?.duration,P?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function E(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const P=!Wg(A)||A<0?0:A;f?.clickDistance(P)}return{update:y,destroy:b,setViewport:w,setViewportConstrained:x,getViewport:_,scaleTo:C,scaleBy:T,setScaleExtent:E,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var AI;(function(e){e.Line="line",e.Handle="handle"})(AI||(AI={}));function wpr({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:s,affectsY:i}){const a=e-t,l=n-r,c=[a>0?1:a<0?-1:0,l>0?1:l<0?-1:0];return a&&s&&(c[0]=c[0]*-1),l&&i&&(c[1]=c[1]*-1),c}function GZe(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 Vw(e,t){return Math.max(0,t-e)}function qw(e,t){return Math.max(0,e-t)}function K9(e,t,n){return Math.max(0,t-e,e-n)}function QZe(e,t){return e?!t:t}function Spr(e,t,n,r,s,i,a,l){let{affectsX:c,affectsY:u}=t;const{isHorizontal:d,isVertical:f}=t,h=d&&f,{xSnapped:p,ySnapped:m}=n,{minWidth:v,maxWidth:y,minHeight:b,maxHeight:x}=r,{x:w,y:k,width:_,height:C,aspectRatio:T}=e;let E=Math.floor(d?p-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=_+(c?-E:E),A=C+(u?-N:N),P=-i[0]*_,L=-i[1]*C;let M=K9(I,v,y),V=K9(A,b,x);if(a){let B=0,W=0;c&&E<0?B=Vw(w+E+P,a[0][0]):!c&&E>0&&(B=qw(w+I+P,a[1][0])),u&&N<0?W=Vw(k+N+L,a[0][1]):!u&&N>0&&(W=qw(k+A+L,a[1][1])),M=Math.max(M,B),V=Math.max(V,W)}if(l){let B=0,W=0;c&&E>0?B=qw(w+E,l[0][0]):!c&&E<0&&(B=Vw(w+I,l[1][0])),u&&N>0?W=qw(k+N,l[0][1]):!u&&N<0&&(W=Vw(k+A,l[1][1])),M=Math.max(M,B),V=Math.max(V,W)}if(s){if(d){const B=K9(I/T,b,x)*T;if(M=Math.max(M,B),a){let W=0;!c&&!u||c&&!u&&h?W=qw(k+L+I/T,a[1][1])*T:W=Vw(k+L+(c?E:-E)/T,a[0][1])*T,M=Math.max(M,W)}if(l){let W=0;!c&&!u||c&&!u&&h?W=Vw(k+I/T,l[1][1])*T:W=qw(k+(c?E:-E)/T,l[0][1])*T,M=Math.max(M,W)}}if(f){const B=K9(A*T,v,y)/T;if(V=Math.max(V,B),a){let W=0;!c&&!u||u&&!c&&h?W=qw(w+A*T+P,a[1][0])/T:W=Vw(w+(u?N:-N)*T+P,a[0][0])/T,V=Math.max(V,W)}if(l){let W=0;!c&&!u||u&&!c&&h?W=Vw(w+A*T,l[1][0])/T:W=qw(w+(u?N:-N)*T,l[0][0])/T,V=Math.max(V,W)}}}N=N+(N<0?V:-V),E=E+(E<0?M:-M),s&&(h?I>A*T?N=(QZe(c,u)?-E:E)/T:E=(QZe(c,u)?-N:N)*T:d?(N=E/T,u=c):(E=N*T,c=u));const q=c?w+E:w,H=u?k+N:k;return{width:_+(c?-E:E),height:C+(u?-N:N),x:i[0]*E*(c?-1:1)+q,y:i[1]*N*(u?-1:1)+H}}const b$t={width:0,height:0,x:0,y:0},kpr={...b$t,pointerX:0,pointerY:0,aspectRatio:1};function Opr(e){return[[0,0],[e.measured.width,e.measured.height]]}function Cpr(e,t,n){const r=t.position.x+e.position.x,s=t.position.y+e.position.y,i=e.measured.width??0,a=e.measured.height??0,l=n[0]*i,c=n[1]*a;return[[r-l,s-c],[r+i-l,s+a-c]]}function _pr({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const i=Uh(e);let a={controlDirection:GZe("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:u,boundaries:d,keepAspectRatio:f,resizeDirection:h,onResizeStart:p,onResize:m,onResizeEnd:v,shouldResize:y}){let b={...b$t},x={...kpr};a={boundaries:d,resizeDirection:h,keepAspectRatio:f,controlDirection:GZe(u)};let w,k=null,_=[],C,T,E,N=!1;const I=IPt().on("start",A=>{const{nodeLookup:P,transform:L,snapGrid:M,snapToGrid:V,nodeOrigin:q,paneDomNode:H}=n();if(w=P.get(t),!w)return;k=H?.getBoundingClientRect()??null;const{xSnapped:B,ySnapped:W}=L2(A.sourceEvent,{transform:L,snapGrid:M,snapToGrid:V,containerBounds:k});b={width:w.measured.width??0,height:w.measured.height??0,x:w.position.x??0,y:w.position.y??0},x={...b,pointerX:B,pointerY:W,aspectRatio:b.width/b.height},C=void 0,w.parentId&&(w.extent==="parent"||w.expandParent)&&(C=P.get(w.parentId),T=C&&w.extent==="parent"?Opr(C):void 0),_=[],E=void 0;for(const[z,G]of P)if(G.parentId===t&&(_.push({id:z,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const F=Cpr(G,w,G.origin??q);E?E=[[Math.min(F[0][0],E[0][0]),Math.min(F[0][1],E[0][1])],[Math.max(F[1][0],E[1][0]),Math.max(F[1][1],E[1][1])]]:E=F}p?.(A,{...b})}).on("drag",A=>{const{transform:P,snapGrid:L,snapToGrid:M,nodeOrigin:V}=n(),q=L2(A.sourceEvent,{transform:P,snapGrid:L,snapToGrid:M,containerBounds:k}),H=[];if(!w)return;const{x:B,y:W,width:z,height:G}=b,F={},R=w.origin??V,{width:D,height:U,x:Q,y:ee}=Spr(x,a.controlDirection,q,a.boundaries,a.keepAspectRatio,R,T,E),J=D!==z,te=U!==G,re=Q!==B&&J,ce=ee!==W&&te;if(!re&&!ce&&!J&&!te)return;if((re||ce||R[0]===1||R[1]===1)&&(F.x=re?Q:b.x,F.y=ce?ee:b.y,b.x=F.x,b.y=F.y,_.length>0)){const le=Q-B,he=ee-W;for(const pe of _)pe.position={x:pe.position.x-le+R[0]*(D-z),y:pe.position.y-he+R[1]*(U-G)},H.push(pe)}if((J||te)&&(F.width=J&&(!a.resizeDirection||a.resizeDirection==="horizontal")?D:b.width,F.height=te&&(!a.resizeDirection||a.resizeDirection==="vertical")?U:b.height,b.width=F.width,b.height=F.height),C&&w.expandParent){const le=R[0]*(F.width??0);F.x&&F.x<le&&(b.x=le,x.x=x.x-(F.x-le));const he=R[1]*(F.height??0);F.y&&F.y<he&&(b.y=he,x.y=x.y-(F.y-he))}const X=wpr({width:b.width,prevWidth:z,height:b.height,prevHeight:G,affectsX:a.controlDirection.affectsX,affectsY:a.controlDirection.affectsY}),ne={...b,direction:X};y?.(A,ne)!==!1&&(N=!0,m?.(A,ne),r(F,H))}).on("end",A=>{N&&(v?.(A,{...b}),s?.({...b}),N=!1)});i.call(I)}function c(){i.on(".drag",null)}return{update:l,destroy:c}}const Epr={},KZe=e=>{let t;const n=new Set,r=(d,f)=>{const h=typeof d=="function"?d(t):d;if(!Object.is(h,t)){const p=t;t=f??(typeof h!="object"||h===null)?h:Object.assign({},t,h),n.forEach(m=>m(t,p))}},s=()=>t,c={setState:r,getState:s,getInitialState:()=>u,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(Epr?"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},Tpr=e=>e?KZe(e):KZe,{useDebugValue:jpr}=Me,{useSyncExternalStoreWithSelector:Npr}=P4n,Ipr=e=>e;function x$t(e,t=Ipr,n){const r=Npr(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return jpr(r),r}const YZe=(e,t)=>{const n=Tpr(e),r=(s,i=t)=>x$t(n,s,i);return Object.assign(r,n),r},Apr=(e,t)=>e?YZe(e,t):YZe;function Wa(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 MQ=g.createContext(null),Rpr=MQ.Provider,w$t=ab.error001();function rs(e,t){const n=g.useContext(MQ);if(n===null)throw new Error(w$t);return x$t(n,e,t)}function Io(){const e=g.useContext(MQ);if(e===null)throw new Error(w$t);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const XZe={display:"none"},Ppr={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},S$t="react-flow__node-desc",k$t="react-flow__edge-desc",$pr="react-flow__aria-live",Mpr=e=>e.ariaLiveMessage,Dpr=e=>e.ariaLabelConfig;function Lpr({rfId:e}){const t=rs(Mpr);return o.jsx("div",{id:`${$pr}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:Ppr,children:t})}function Fpr({rfId:e,disableKeyboardA11y:t}){const n=rs(Dpr);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${S$t}-${e}`,style:XZe,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${k$t}-${e}`,style:XZe,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(Lpr,{rfId:e})]})}const b5=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},i)=>{const a=`${e}`.split("-");return o.jsx("div",{className:Hl(["react-flow__panel",n,...a]),style:r,ref:i,...s,children:t})});b5.displayName="Panel";function zpr({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(b5,{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 Bpr=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}},Y9=e=>e.id;function Upr(e,t){return Wa(e.selectedNodes.map(Y9),t.selectedNodes.map(Y9))&&Wa(e.selectedEdges.map(Y9),t.selectedEdges.map(Y9))}function Vpr({onSelectionChange:e}){const t=Io(),{selectedNodes:n,selectedEdges:r}=rs(Bpr,Upr);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(i=>i(s))},[n,r,e]),null}const qpr=e=>!!e.onSelectionChangeHandlers;function Hpr({onSelectionChange:e}){const t=rs(qpr);return e||t?o.jsx(Vpr,{onSelectionChange:e}):null}const awe=typeof window<"u"?g.useLayoutEffect:g.useEffect,O$t=[0,0],Wpr={x:0,y:0,zoom:1},Zpr=["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"],JZe=[...Zpr,"rfId"],Gpr=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}),eGe={translateExtent:WL,nodeOrigin:O$t,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function Qpr(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:i,setNodeExtent:a,reset:l,setDefaultNodesAndEdges:c}=rs(Gpr,Wa),u=Io();awe(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=eGe,l()}),[]);const d=g.useRef(eGe);return awe(()=>{for(const f of JZe){const h=e[f],p=d.current[f];h!==p&&(typeof e[f]>"u"||(f==="nodes"?t(h):f==="edges"?n(h):f==="minZoom"?r(h):f==="maxZoom"?s(h):f==="translateExtent"?i(h):f==="nodeExtent"?a(h):f==="ariaLabelConfig"?u.setState({ariaLabelConfig:Lhr(h)}):f==="fitView"?u.setState({fitViewQueued:h}):f==="fitViewOptions"?u.setState({fitViewOptions:h}):u.setState({[f]:h})))}d.current=e},JZe.map(f=>e[f])),null}function tGe(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function Kpr(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=tGe(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:tGe()?.matches?"dark":"light"}const nGe=typeof document<"u"?document:null;function YL(e=null,t={target:nGe,actInsideInputWithModifier:!0}){const[n,r]=g.useState(!1),s=g.useRef(!1),i=g.useRef(new Set([])),[a,l]=g.useMemo(()=>{if(e!==null){const u=(Array.isArray(e)?e:[e]).filter(f=>typeof f=="string").map(f=>f.replace("+",`
232
232
  `).replace(`
233
233
 
234
234
  `,`
@@ -688,7 +688,7 @@ Token usage: ${n} input + ${r} output = ${s} total`:`The model stopped generatin
688
688
  }
689
689
  ]`,oMs=[{name:"input",description:"What the agent receives. A string or any JSON value.",required:!0},{name:"groundTruth",description:"Expected answer used by scorers.",required:!1},{name:"metadata",description:"Any object, useful for filtering and grouping.",required:!1}];function lMs(){const{isCopied:e,handleCopy:t}=Kd({text:Nct,showToast:!1});return o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsx("p",{className:"text-ui-sm text-neutral5 flex h-8 items-center font-medium",children:"Each item looks like this"}),o.jsx("dl",{className:"border-border1 divide-border1 divide-y rounded-lg border",children:oMs.map(n=>o.jsxs("div",{className:"grid grid-cols-[7rem_1fr] gap-3 px-3 py-2.5",children:[o.jsx("dt",{className:"text-ui-xs text-neutral6 font-mono",children:n.name}),o.jsxs("dd",{className:"text-ui-xs text-neutral4 flex flex-col items-start gap-1.5",children:[o.jsx("span",{children:n.description}),n.required?o.jsx(jt,{variant:"green",size:"xs",children:"required"}):o.jsx(jt,{variant:"neutral",emphasis:"muted",size:"xs",children:"optional"})]})]},n.name))}),o.jsxs("div",{className:"border-border1 overflow-hidden rounded-lg border",children:[o.jsxs("div",{className:"border-border1 bg-surface3 flex items-center justify-between border-b py-1.5 pr-1.5 pl-3",children:[o.jsx("span",{className:"text-ui-xs text-neutral4 font-mono",children:"example.json"}),o.jsx(ae,{icon:e?o.jsx(Mn,{}):o.jsx(ed,{}),variant:"ghost",size:"xs",onClick:t,children:e?"Copied":"Copy"})]}),o.jsx(Lr,{variant:"embedded",language:"json",editable:!1,lineNumbers:!1,showCopyButton:!1,value:Nct,className:"p-3"})]}),o.jsx(ae,{variant:"ghost",render:o.jsx("a",{href:aMs,target:"_blank",rel:"noopener noreferrer"}),className:"self-start",icon:o.jsx(_s,{}),children:"Datasets documentation"})]})}const Aue=10,cMs=`[
690
690
  { "input": "…", "groundTruth": "…" }
691
- ]`,Ict="flex min-h-0 flex-1 flex-col py-0";function uMs({tab:e,onTabChange:t,file:n,onFileSelect:r,onReplace:s,pastedText:i,onPastedTextChange:a,validation:l,isImporting:c}){return o.jsxs(hl,{value:e,defaultTab:"upload",onValueChange:t,className:"flex h-full flex-col gap-3",children:[o.jsxs(fl,{variant:"pill",children:[o.jsx(Sr,{value:"upload",children:"Upload file"}),o.jsx(Sr,{value:"paste",children:"Paste JSON"})]}),o.jsx(ts,{value:"upload",className:Ict,children:n?o.jsx(pMs,{file:n,validation:l,onReplace:s,isImporting:c}):o.jsx(dMs,{onFileSelect:r,disabled:c})}),o.jsx(ts,{value:"paste",className:Ict,children:o.jsx(Yd,{"aria-label":"JSON items",className:"text-ui-sm min-h-[200px] flex-1 resize-none font-mono",placeholder:cMs,spellCheck:!1,value:i,onChange:u=>a(u.target.value),disabled:c})})]})}function dMs({onFileSelect:e,disabled:t}){const[n,r]=g.useState(!1),s=g.useCallback(c=>{const u=c.target.files?.[0];u&&e(u),c.target.value=""},[e]),i=g.useCallback(c=>{c.preventDefault(),c.stopPropagation(),r(!0)},[]),a=g.useCallback(c=>{c.preventDefault(),c.stopPropagation(),r(!1)},[]),l=g.useCallback(c=>{if(c.preventDefault(),c.stopPropagation(),r(!1),t)return;const u=c.dataTransfer.files?.[0];u&&e(u)},[t,e]);return o.jsxs("div",{"data-testid":"json-dropzone",onDragOver:i,onDragLeave:a,onDrop:l,className:K("border-border1 bg-surface3 relative flex flex-1 flex-col items-center justify-center gap-3 rounded-lg border border-dashed px-4 py-6 text-center transition-colors","hover:border-accent1/50 hover:bg-accent1/5",n&&"border-accent1/50 bg-accent1/5",t&&"cursor-wait opacity-60"),children:[o.jsx("input",{type:"file",accept:".json,application/json","aria-label":"Choose a JSON file",onChange:s,disabled:t,className:"absolute inset-0 cursor-pointer opacity-0"}),o.jsx("div",{className:"border-border1 bg-surface2 text-neutral4 flex size-9 items-center justify-center rounded-md border",children:o.jsx(NA,{className:"size-4"})}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("p",{className:"text-ui-md text-neutral6",children:"Drop a JSON file here"}),o.jsxs("p",{className:"text-ui-sm text-neutral4",children:["or ",o.jsx("span",{className:"underline",children:"choose a file"})," from your computer"]})]}),o.jsxs("p",{className:"text-ui-xs text-neutral3",children:[".json · an array of items · up to ",JDe]})]})}function fMs(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function hMs(e){return typeof e=="string"?e:JSON.stringify(e)??""}function pMs({file:e,validation:t,onReplace:n,isImporting:r}){const s="rows"in t?t.rows:[],i="total"in t?t.total:0,a=s.slice(0,Aue);return o.jsxs("div",{"data-testid":"json-file-card",className:"border-border1 rounded-lg border",children:[o.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[o.jsx(CA,{className:"text-neutral4 size-4 shrink-0"}),o.jsx("span",{className:"text-ui-sm text-neutral6 min-w-0 flex-1 truncate font-mono",children:e.name}),o.jsx("span",{className:"text-ui-xs text-neutral3 shrink-0",children:fMs(e.size)}),o.jsx(ae,{icon:o.jsx(d0,{}),variant:"ghost",size:"xs",onClick:n,disabled:r,children:"Replace"})]}),a.map(l=>o.jsxs("div",{className:"border-border1 grid grid-cols-[2rem_1fr_auto] items-center gap-2 border-t px-3 py-1.5",children:[o.jsx("span",{className:"text-ui-xs text-neutral3",children:l.index}),o.jsx("span",{className:"text-ui-sm text-neutral5 truncate font-mono",children:hMs(l.input)}),l.hasInput?l.hasGroundTruth?null:o.jsx(jt,{variant:"yellow",size:"xs",children:"no groundTruth"}):o.jsx(jt,{variant:"red",size:"xs",children:"no input"})]},l.index)),i>Aue&&o.jsxs("div",{className:"border-border1 text-ui-xs text-neutral3 border-t px-3 py-1.5",children:["+ ",i-Aue," more"]})]})}const mMs=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)});function gMs({datasetId:e,datasetName:t,open:n,onOpenChange:r,onSuccess:s}){const[i,a]=g.useState("upload"),[l,c]=g.useState(null),[u,d]=g.useState(""),[f,h]=g.useState(null),[p,m]=g.useState(""),[v,y]=g.useState(!1),b=g.useRef(0),{batchInsertItems:x}=pl(),w=i==="upload"?u:p,k=g.useMemo(()=>i==="upload"&&f?{status:"error",kind:"parse",message:f}:e$s(w),[i,f,w]),_=g.useCallback(async I=>{const A=++b.current;if(!I.name.toLowerCase().endsWith(".json")){h("Only .json files are supported");return}if(I.size>Dnn){h(`File is larger than ${JDe}`);return}try{const P=await mMs(I);if(A!==b.current)return;c({name:I.name,size:I.size}),d(P),h(null)}catch{if(A!==b.current)return;h("Could not read the file")}},[]),C=g.useCallback(()=>{b.current++,c(null),d(""),h(null)},[]),T=g.useCallback(()=>{b.current++,a("upload"),c(null),d(""),h(null),m("")},[]),E=g.useCallback(()=>{v||(r(!1),setTimeout(T,150))},[v,r,T]),N=g.useCallback(async()=>{if(k.status==="ready"){y(!0);try{await x.mutateAsync({datasetId:e,items:k.items}),Ge.success(`Imported ${k.total} item${k.total!==1?"s":""}`),s?.(),r(!1),setTimeout(T,150)}catch(I){Ge.error(I instanceof Error?I.message:"Failed to import items")}finally{y(!1)}}},[k,x,e,s,r,T]);return o.jsx(hs,{open:n,onOpenChange:E,children:o.jsxs(Jr,{className:"flex max-h-[90vh] w-[960px] max-w-[calc(100vw-2rem)] flex-col gap-0 p-0",children:[o.jsxs(es,{className:"border-border1 border-b px-4 py-4",children:[o.jsx(Kr,{children:"Import into dataset"}),o.jsxs(Ps,{className:"text-ui-sm text-neutral3 not-sr-only",children:["Add items to"," ",t?o.jsx("code",{className:"bg-surface3 text-ui-xs text-neutral6 rounded px-1 font-mono",children:t}):"this dataset"," ","from a JSON file or paste them directly."]})]}),o.jsx(vs,{className:"max-h-none min-h-0 flex-1 overflow-y-auto p-0",children:o.jsxs("div",{className:"divide-border1 grid divide-y md:grid-cols-[1.15fr_1fr] md:divide-x md:divide-y-0",children:[o.jsx("div",{className:"flex min-h-[360px] flex-col p-4",children:o.jsx(uMs,{tab:i,onTabChange:a,file:l,onFileSelect:_,onReplace:C,pastedText:p,onPastedTextChange:m,validation:k,isImporting:v})}),o.jsx("div",{className:"p-4",children:o.jsx(lMs,{})})]})}),o.jsxs(lc,{className:"border-border1 items-center border-t px-4 py-3 sm:justify-between",children:[o.jsx(vMs,{validation:k}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(ae,{icon:o.jsx(Yt,{}),onClick:E,disabled:v,children:"Cancel"}),o.jsxs(ae,{variant:"primary",onClick:N,disabled:k.status!=="ready"||v,children:[v&&o.jsx(_n,{}),k.status==="ready"?`Import ${k.total} item${k.total!==1?"s":""}`:"Import"]})]})]})]})})}function vMs({validation:e}){const t=K("size-1.5 shrink-0 rounded-full",e.status==="idle"&&"bg-neutral3",e.status==="ready"&&"bg-accent1",e.status==="error"&&"bg-accent2");let n;switch(e.status){case"idle":n="No items yet";break;case"ready":n=o.jsxs(o.Fragment,{children:[o.jsx("b",{className:"text-neutral6 font-medium",children:e.total})," item",e.total!==1?"s":""," ready",e.missingGroundTruthCount>0&&` · ${e.missingGroundTruthCount} without groundTruth`]});break;case"error":switch(e.kind){case"parse":n=`Not valid JSON — ${e.message}`;break;case"not-array":n="Top level must be an array of items";break;case"empty":n="The array has no items";break;case"too-large":n=`JSON is larger than ${JDe}`;break;case"missing-input":n=o.jsxs(o.Fragment,{children:[o.jsx("b",{className:"text-neutral6 font-medium",children:e.missingInputCount})," of ",e.total," item",e.total!==1?"s":""," ",e.missingInputCount!==1?"have":"has"," no"," ",o.jsx("code",{className:"font-mono",children:"input"})]});break}break}return o.jsxs("div",{role:"status",className:"text-ui-sm text-neutral4 flex min-w-0 items-center gap-2",children:[o.jsx("span",{className:t}),o.jsx("span",{className:"truncate",children:n})]})}function yMs(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 Knn({active:e,onPrevious:t,onNext:n,onClose:r}){g.useEffect(()=>{if(!e)return;const s=i=>{i.defaultPrevented||yMs(i.target)||(i.key==="PageUp"?(i.preventDefault(),t?.()):i.key==="PageDown"?(i.preventDefault(),n?.()):i.key==="Escape"&&(i.preventDefault(),r()))};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,t,n,r])}const Ynn=g.createContext(null);function bMs({datasetId:e,items:t,isLoadingItems:n,children:r}){const s=Fr(),a=q1t("/datasets/:datasetId/items/:itemId")?.params.itemId,l=g.useCallback(p=>{s(`/datasets/${e}/items/${encodeURIComponent(p)}`)},[s,e]),c=g.useCallback(()=>{s(`/datasets/${e}`)},[s,e]),u=g.useMemo(()=>a?t.findIndex(p=>p.id===a):-1,[t,a]),d=g.useMemo(()=>{if(u<=0)return;const p=t[u-1].id;return()=>l(p)},[u,t,l]),f=g.useMemo(()=>{if(u<0||u>=t.length-1)return;const p=t[u+1].id;return()=>l(p)},[u,t,l]);Knn({active:!!a,onPrevious:d,onNext:f,onClose:c});const h=g.useMemo(()=>({datasetId:e,items:t,isLoadingItems:n,currentItemId:a,openItem:l,close:c,goToPreviousItem:d,goToNextItem:f}),[e,t,n,a,l,c,d,f]);return o.jsx(Ynn.Provider,{value:h,children:r})}function Xnn(){const e=g.useContext(Ynn);if(!e)throw new Error("useDatasetItemPanel must be used within a DatasetItemPanelProvider");return e}function xMs({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,leftSlot:r,rightSlot:s,belowToolbarSlot:i}){const[a,l]=bi(),{activeVersion:c}=tLe(a,l),[u,d]=g.useState(!1),[f,h]=g.useState(!1),[p,m]=g.useState(!1),[v,y]=g.useState([]),[b,x]=g.useState(!1),[w,k]=g.useState([]),[_,C]=g.useState(!1),[T,E]=g.useState([]),[N,I]=g.useState(0),[A,P]=g.useState(""),[L]=RTe(A,300),{data:M}=bv(e),{data:V=[],isLoading:q,setEndOfListElement:H,isFetchingNextPage:B,hasNextPage:W}=gA(e,L||void 0,c),{deleteItems:z}=pl(),{currentItemId:G,openItem:F,close:R}=Xnn(),D=X=>{G===X?R():F(X)},U=X=>{y(X),m(!0)},Q=X=>{k(X),x(!0)},ee=X=>{x(X),X||(k([]),I(ne=>ne+1))},J=X=>{E(X),C(!0)},te=async()=>{await z.mutateAsync({datasetId:e,itemIds:T}),Ge.success(`Deleted ${T.length} items`),C(!1),E([]),I(X=>X+1)},re=X=>{m(!1),y([]),I(ne=>ne+1),n?.(X)},ce=X=>{m(X),X||(y([]),I(ne=>ne+1))};return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"grid h-full overflow-auto",children:o.jsx(iMs,{items:V,leftSlot:r,rightSlot:s,belowToolbarSlot:i,isLoading:q,onItemClick:D,featuredItemId:G,onAddClick:t??(()=>{}),onImportClick:()=>d(!0),onImportJsonClick:()=>h(!0),onBulkDeleteClick:J,onCreateDatasetClick:U,onAddToDatasetClick:Q,datasetName:M?.name,clearSelectionTrigger:N,setEndOfListElement:H,isFetchingNextPage:B,hasNextPage:W,searchQuery:A,activeSearchQuery:L,onSearchChange:P,currentDatasetVersion:M?.version})}),o.jsx(J$s,{datasetId:e,open:u,onOpenChange:d}),o.jsx(gMs,{datasetId:e,datasetName:M?.name,open:f,onOpenChange:h}),o.jsx(P$s,{open:p,onOpenChange:ce,items:v,onSuccess:re}),o.jsx($$s,{open:b,onOpenChange:ee,items:w,currentDatasetId:e}),o.jsx(At,{open:_,onOpenChange:C,children:o.jsxs(At.Content,{children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Delete Items"}),o.jsxs(At.Description,{children:["Are you sure you want to delete ",T.length," item",T.length!==1?"s":"","? This action cannot be undone."]})]}),o.jsxs(At.Footer,{children:[o.jsx(At.Cancel,{children:"Cancel"}),o.jsx(At.Action,{onClick:te,children:z.isPending?"Deleting...":"Delete"})]})]})})]})}const Act="__create_tag__";function wMs({datasetId:e}){const{data:t}=bv(e),{data:n}=q0(),{updateDataset:r}=pl(),[s,i]=g.useState(""),a=g.useMemo(()=>Array.isArray(t?.tags)?t.tags:[],[t?.tags]),l=g.useMemo(()=>Bnn(n?.datasets??[]),[n?.datasets]),c=g.useMemo(()=>{const h=l.map(v=>({label:v,value:v,end:a.includes(v)?o.jsx(Mn,{"data-testid":"tag-applied",className:"size-3.5"}):void 0})),p=s.trim();return p.length>0&&!l.includes(p)&&!a.includes(p)?[{label:`Create "${p}"`,value:Act},...h]:h},[l,a,s]),u=h=>{r.mutate({datasetId:e,tags:h},{onError:()=>Ge.error("Failed to update tags")})},d=h=>{const p=h===Act?s.trim():h;!p||a.includes(p)||u([...a,p])},f=h=>{u(a.filter(p=>p!==h))};return o.jsxs("div",{"data-testid":"dataset-tags-editor",className:"flex flex-wrap items-center gap-2",children:[a.map(h=>o.jsxs(mJ,{value:h,size:"md",className:"gap-1 pr-1",children:[h,o.jsx("button",{type:"button","aria-label":`Remove tag ${h}`,disabled:r.isPending,onClick:()=>f(h),className:"cursor-pointer rounded-sm hover:opacity-70 disabled:opacity-50",children:o.jsx(Yt,{className:"size-3"})})]},h)),o.jsx(qo,{options:c,value:void 0,onValueChange:d,onInputValueChange:i,placeholder:o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(B_,{className:"size-3.5"}),"Add tag"]}),searchPlaceholder:"Search or create tag...",emptyText:"Type to create a tag",variant:"ghost",size:"xs",className:"w-auto min-w-0",disabled:r.isPending})]})}function Jnn({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(uc,{id:"override-dataset-scorers",checked:e,onCheckedChange:t,disabled:s}),o.jsx(Vt,{htmlFor:"override-dataset-scorers",children:"Override dataset scorers"})]}),o.jsx("p",{className:"text-muted-foreground text-ui-sm",children:e?"Only selected scorers run for this item. Leave empty to run no scorers.":"Use scorers attached to the dataset."}),e?o.jsx(vJ,{selectedScorers:n,setSelectedScorers:r,disabled:s,label:"Item scorers",helperText:"Choose from scorers that can be resolved by this Mastra instance."}):null]})}function SMs(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 Rue({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-ui-sm",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function kMs({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,i]=g.useState("{}"),[a,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState(""),[h,p]=g.useState(!1),[m,v]=g.useState([]),[y,b]=g.useState(""),[x,w]=g.useState(null),{addItem:k}=pl(),_=()=>{i("{}"),l(""),u(""),f(""),p(!1),v([]),b(""),w(null)},C=P=>{_(),n(P)},T=async P=>{P.preventDefault();let L;try{L=JSON.parse(s)}catch{Ge.error("Input must be valid JSON");return}let M;if(a.trim())try{M=JSON.parse(a)}catch{Ge.error("Ground Truth must be valid JSON");return}let V;if(c.trim())try{V=JSON.parse(c)}catch{Ge.error("Expected Trajectory must be valid JSON");return}let q;if(d.trim())try{const B=JSON.parse(d);if(!Array.isArray(B)){Ge.error("Tool Mocks must be a JSON array");return}q=B}catch{Ge.error("Tool Mocks must be valid JSON");return}let H;if(y.trim())try{H=JSON.parse(y)}catch{Ge.error("Request Context must be valid JSON");return}try{await k.mutateAsync({datasetId:e,input:L,groundTruth:M,expectedTrajectory:V,toolMocks:q,scorerIds:h?m:void 0,requestContext:H}),Ge.success("Item added successfully"),C(!1),r?.()}catch(B){const W=SMs(B);W?w(W):Ge.error(`Failed to add item: ${B instanceof Error?B.message:"Unknown error"}`)}},E=P=>{i(P),x?.field==="input"&&w(null)},N=P=>{l(P),x?.field==="groundTruth"&&w(null)},I=P=>{f(P),x?.field==="toolMocks"&&w(null)},A=()=>{C(!1)};return o.jsxs(_a,{dialogTitle:"Add Item",dialogDescription:"Create a new dataset item",isOpen:t,onClose:A,level:1,children:[o.jsx(_a.Top,{children:"Add Item"}),o.jsxs(_a.Content,{children:[o.jsx(_a.Header,{children:o.jsx(_a.Heading,{children:"Add Item"})}),o.jsxs("form",{onSubmit:T,className:"grid gap-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Vt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Lr,{value:s,onChange:E,showCopyButton:!1,className:"min-h-[240px]"}),x?.field==="input"&&o.jsx(Rue,{field:"input",errors:x.errors})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Vt,{htmlFor:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),o.jsx(Lr,{value:a,onChange:N,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="groundTruth"&&o.jsx(Rue,{field:"groundTruth",errors:x.errors})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Vt,{htmlFor:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),o.jsx(Lr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[200px]"})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Vt,{htmlFor:"item-tool-mocks",children:"Tool Mocks (JSON array, optional)"}),o.jsx(Lr,{value:d,onChange:I,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="toolMocks"&&o.jsx(Rue,{field:"toolMocks",errors:x.errors})]}),o.jsx(Jnn,{overrideEnabled:h,onOverrideEnabledChange:p,selectedScorerIds:m,onSelectedScorerIdsChange:v,disabled:k.isPending}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Vt,{htmlFor:"item-request-context",children:"Request Context (JSON, optional)"}),o.jsx(Lr,{value:y,onChange:b,showCopyButton:!1,className:"min-h-[200px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ae,{icon:o.jsx(Yt,{}),type:"button",onClick:A,children:"Cancel"}),o.jsx(ae,{icon:o.jsx(Yr,{}),type:"submit",variant:"primary",disabled:k.isPending,children:k.isPending?"Adding...":"Add Item"})]})]})]})]})}const uO=e=>JSON.stringify(e??null,null,2),OMs=[{key:"input",title:"Input",icon:o.jsx(eI,{}),value:e=>uO(e.input)},{key:"groundTruth",title:"Ground Truth",icon:o.jsx(Gx,{}),value:e=>uO(e.groundTruth)},{key:"expectedTrajectory",title:"Expected Trajectory",icon:o.jsx(i1t,{}),value:e=>e.expectedTrajectory!=null?uO(e.expectedTrajectory):void 0},{key:"toolMocks",title:"Tool Mocks",icon:o.jsx(xu,{}),value:e=>uO(e.toolMocks??[])},{key:"scorerIds",title:"Scorers",icon:o.jsx(TCe,{}),value:e=>e.scorerIds===void 0?"Inherited from dataset":uO(e.scorerIds)},{key:"requestContext",title:"Request Context",icon:o.jsx(Bl,{}),value:e=>e.requestContext!=null?uO(e.requestContext):void 0},{key:"metadata",title:"Metadata",icon:o.jsx(B_,{}),value:e=>uO(e.metadata)}];function Rke({item:e,diff:t}){return o.jsxs(o.Fragment,{children:[o.jsxs(fn,{children:[o.jsx(fn.Key,{children:"Dataset Id"}),o.jsx(fn.ValueWithCopyBtn,{copyTooltip:"Copy Dataset Id to clipboard",copyValue:e.datasetId,children:e.datasetId}),o.jsx(fn.Key,{children:"Version"}),o.jsxs(fn.Value,{children:["v",e.datasetVersion]}),o.jsx(fn.Key,{children:"Created"}),o.jsx(fn.Value,{children:gr(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")}),o.jsx(fn.Key,{children:"Updated"}),o.jsx(fn.Value,{children:e.updatedAt&&new Date(e.updatedAt).getTime()!==new Date(e.createdAt).getTime()?gr(new Date(e.updatedAt),"MMM d, yyyy h:mm aaa"):"n/a"})]}),o.jsx("div",{className:"mt-3 grid gap-3",children:OMs.map(n=>{const r=n.value(e),s=t?n.value(t.against):void 0;return r===void 0&&s===void 0?null:o.jsx($t.CodeSection,{title:n.title,icon:n.icon,codeStr:r??"",diff:t?{against:s??"",side:t.side}:void 0},n.key)})})]})}function Pue({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-ui-sm",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function CMs({inputValue:e,setInputValue:t,groundTruthValue:n,setGroundTruthValue:r,metadataValue:s,setMetadataValue:i,trajectoryValue:a,setTrajectoryValue:l,toolMocksValue:c,setToolMocksValue:u,scorerOverrideEnabled:d,setScorerOverrideEnabled:f,selectedScorerIds:h,setSelectedScorerIds:p,requestContextValue:m,setRequestContextValue:v,validationErrors:y,onSave:b,onCancel:x,isSaving:w}){return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"mb-4",children:o.jsxs("h3",{className:"text-header-sm flex items-center gap-2 font-medium",children:[o.jsx(Gd,{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(Vt,{children:"Input (JSON) *"}),o.jsx(Lr,{value:e,onChange:t,showCopyButton:!1,className:"min-h-[120px]"}),y?.field==="input"&&o.jsx(Pue,{field:"input",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Vt,{children:"Ground Truth (JSON, optional)"}),o.jsx(Lr,{value:n,onChange:r,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="groundTruth"&&o.jsx(Pue,{field:"groundTruth",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Vt,{children:"Expected Trajectory (JSON, optional)"}),o.jsx(Lr,{value:a,onChange:l,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Vt,{children:"Tool Mocks (JSON array, optional)"}),o.jsxs("p",{className:"text-muted-foreground text-ui-sm",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(Lr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="toolMocks"&&o.jsx(Pue,{field:"toolMocks",errors:y.errors})]}),o.jsx(Jnn,{overrideEnabled:d,onOverrideEnabledChange:f,selectedScorerIds:h,onSelectedScorerIdsChange:p,disabled:w}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Vt,{children:"Request Context (JSON, optional)"}),o.jsx(Lr,{value:m,onChange:v,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Vt,{children:"Metadata (JSON, optional)"}),o.jsx(Lr,{value:s,onChange:i,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex gap-2 pt-4",children:[o.jsx(ae,{icon:o.jsx(Mn,{}),variant:"primary",onClick:b,disabled:w,children:w?"Saving...":"Save Changes"}),o.jsx(ae,{icon:o.jsx(Yt,{}),onClick:x,disabled:w,children:"Cancel"})]})]})]})}const _Ms=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function EMs({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:i,isLoading:a}=rh(),{data:l,isLoading:c}=eg(),{data:u,isLoading:d}=Ep(),f=e==="agent"?Object.entries(i??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="workflow"?Object.entries(l??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="scorer"?Object.entries(u??{}).map(([v,y])=>({value:v,label:y.scorer?.config?.name??v})):[],h=e==="agent"&&a||e==="workflow"&&c||e==="scorer"&&d,p=v=>{t(v),r("")},m=e==="agent"?"Agent":e==="workflow"?"Workflow":"Scorer";return o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Vt,{children:"Target Type"}),o.jsx(qo,{options:_Ms,value:e,onValueChange:p,placeholder:"Select target type",searchPlaceholder:"Search types...",emptyText:"No types available",container:s})]}),e&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Vt,{children:m}),o.jsx(qo,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:h,container:s})]})]})}const TMs=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform);function jMs({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return Pm(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(Vt,{children:"Request Context"}),o.jsx(i5,{schema:n,onValuesChange:t,className:"[&_button[type=submit]]:hidden"})]}):o.jsx("p",{className:"text-destructive text-ui-md",children:"Failed to parse request context schema"})}function $ue({index:e,done:t,isLast:n,children:r}){return o.jsxs("li",{className:"flex gap-4",children:[o.jsxs("div",{className:"flex flex-col items-center",children:[o.jsx("span",{"aria-hidden":"true",className:K("flex size-6 shrink-0 items-center justify-center rounded-full border text-ui-xs font-medium",t?"border-accent1 bg-accent1 text-white":"border-border1 text-neutral3"),children:e}),!n&&o.jsx("span",{"aria-hidden":"true",className:"bg-border1 mt-2 w-px flex-1"})]}),o.jsx("div",{className:K("min-w-0 flex-1 space-y-3",!n&&"pb-4"),children:r})]})}function yJ({initialDatasetId:e,initialDatasetVersion:t,initialScorerIds:n,initialTargetType:r,initialTargetId:s,initialName:i,initialDescription:a,open:l,onOpenChange:c,onSuccess:u}){const d=g.useRef(null),[f,h]=g.useState(i??""),[p,m]=g.useState(a??""),[v,y]=g.useState(e??""),[b,x]=g.useState(t??null),[w,k]=g.useState(r??""),[_,C]=g.useState(s??""),[T,E]=g.useState(n??null),[N,I]=g.useState({}),[A,P]=g.useState(""),{triggerExperiment:L}=pl(),{data:M}=bv(v),{total:V}=gA(v,void 0,b),q=M?.requestContextSchema,H=M?.scorerIds??[],B=T===null&&H.length>0,W=T??H,z=!!(q&&Object.keys(q).length>0),G=!!(v&&w&&_&&f.trim()),F=L.isPending,R=[!f.trim()&&"name",!v&&"dataset",!_&&"target"].filter(Boolean),D=z?Object.values(N).some(ce=>ce!==void 0&&ce!==""):A.trim().length>0,U=ce=>{y(ce),x(null),E(n??null),I({})},Q=()=>{h(i??""),m(a??""),y(e??""),x(t??null),k(r??""),C(s??""),E(n??null),I({}),P("")},ee=()=>{if(z){const ce=Object.entries(N).filter(([,X])=>X!==void 0&&X!=="");return ce.length>0?Object.fromEntries(ce):void 0}if(A.trim()){let ce;try{ce=JSON.parse(A)}catch{throw new Error("Request Context must be valid JSON")}if(!ce||typeof ce!="object"||Array.isArray(ce))throw new Error("Request Context must be a JSON object");return ce}},J=async()=>{if(!v||!w||!_||!f.trim())return;let ce;try{ce=ee()}catch(X){const ne=X instanceof Error?X.message:"Request Context must be valid JSON";hu.error(ne);return}try{const X=await L.mutateAsync({datasetId:v,name:f.trim(),description:p.trim()||void 0,targetType:w,targetId:_,scorerIds:W.length>0?W:void 0,version:b??void 0,requestContext:ce});hu.success("Experiment triggered successfully"),c(!1),u?.(X.experimentId),Q()}catch(X){const ne=X instanceof Error?X.message:"Failed to trigger experiment";hu.error(ne)}},te=()=>{F||(c(!1),Q())},re=ce=>{(ce.metaKey||ce.ctrlKey)&&ce.key==="Enter"&&G&&!F&&(ce.preventDefault(),J())};return o.jsx(hs,{open:l,onOpenChange:te,children:o.jsxs(Jr,{ref:d,className:"w-[640px] max-w-[calc(100vw-2rem)] gap-0 p-0",onKeyDown:re,children:[o.jsxs(es,{className:"border-border1 border-b px-4 py-4",children:[o.jsx(Kr,{children:"Run experiment"}),o.jsx(Ps,{className:"text-ui-sm text-neutral3 not-sr-only",children:"Pick a dataset, choose what to run it against, and optionally score the results."})]}),o.jsxs(vs,{className:"max-h-[70vh] space-y-6 overflow-y-auto px-4 py-5",children:[o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Vt,{htmlFor:"experiment-name",children:"Name *"}),o.jsx($n,{id:"experiment-name",value:f,onChange:ce=>h(ce.target.value),placeholder:"Enter experiment name",autoFocus:!0,disabled:F})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Vt,{htmlFor:"experiment-description",children:"Description"}),o.jsx(Yd,{id:"experiment-description",value:p,onChange:ce=>m(ce.target.value),placeholder:"Enter experiment description (optional)",disabled:F,rows:2})]})]}),o.jsxs("ol",{className:"list-none",children:[o.jsxs($ue,{index:1,done:!!v,children:[o.jsxs("div",{className:"grid grid-cols-[1fr_140px] gap-3",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Vt,{children:"Dataset"}),o.jsx(OEt,{value:v,onValueChange:U,container:d})]}),v&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Vt,{children:"Version"}),o.jsx(Qnn,{datasetId:v,value:b,onValueChange:x,container:d})]})]}),v&&V!==void 0&&o.jsxs("p",{className:"text-ui-xs text-neutral3",children:[V," ",V===1?"item":"items"]})]}),o.jsxs($ue,{index:2,done:!!_,children:[o.jsx(EMs,{targetType:w,setTargetType:k,targetId:_,setTargetId:C,container:d}),w&&!_&&o.jsxs("p",{className:"text-ui-xs text-neutral3",children:["Choose ",w==="agent"?"an":"a"," ",w," to run"]})]}),o.jsx($ue,{index:3,done:W.length>0,isLast:!0,children:o.jsx(vJ,{selectedScorers:W,setSelectedScorers:E,disabled:F,container:d,helperText:B?"Pre-filled from the dataset's default scorers.":"Scores are computed after each item runs."})})]}),o.jsxs(dl,{children:[o.jsxs(Zo,{className:"text-ui-sm flex items-center gap-2",children:[o.jsx(mr,{className:"size-4"}),"Request Context (JSON, optional)",D&&o.jsx(jt,{size:"xs",variant:"blue",children:"set"})]}),o.jsx(Go,{className:"pt-3",children:z?o.jsx(jMs,{requestContextSchema:q,onChange:I}):o.jsx(Lr,{value:A,onChange:P,showCopyButton:!1,"aria-label":"Request context JSON",className:"min-h-[160px]"})})]})]}),o.jsxs(lc,{className:"border-border1 items-center border-t px-4 py-4 sm:justify-between",children:[o.jsx("p",{"data-testid":"experiment-run-status","aria-live":"polite",className:"flex items-center gap-2",children:R.length===0?o.jsxs(o.Fragment,{children:[o.jsx(jt,{variant:"green",indicator:"dot",children:"Ready"}),o.jsxs("span",{className:"text-ui-xs text-neutral3",children:[V??0," items · ",w," · ",W.length," scorers"]})]}):o.jsxs(jt,{variant:"neutral",indicator:"dot",children:["Missing ",R.join(", ")]})}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ae,{icon:o.jsx(Yt,{}),onClick:te,disabled:F,children:"Cancel"}),o.jsx(ae,{variant:"primary",onClick:J,disabled:!G||F,children:F?o.jsxs(o.Fragment,{children:[o.jsx(_n,{className:"h-4 w-4"}),"Running..."]}):o.jsxs(o.Fragment,{children:["Run",o.jsxs("span",{className:"ml-1 inline-flex gap-0.5","aria-hidden":"true",children:[o.jsx(Pf,{size:"xs",children:TMs?"⌘":"Ctrl"}),o.jsx(Pf,{size:"xs",children:"↵"})]})]})})]})]})]})})}const ern=g.createContext(null);function NMs({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:i,children:a}){const l=Fr(),u=q1t("/experiments/:experimentId/items/:itemId")?.params.itemId,d=g.useCallback(y=>{l(`/experiments/${e}/items/${encodeURIComponent(y)}`)},[l,e]),f=g.useCallback(()=>{l(`/experiments/${e}`)},[l,e]),h=g.useMemo(()=>u?r.findIndex(y=>y.itemId===u):-1,[r,u]),p=g.useMemo(()=>{if(h<=0)return;const y=r[h-1].itemId;return()=>d(y)},[h,r,d]),m=g.useMemo(()=>{if(h<0||h>=r.length-1)return;const y=r[h+1].itemId;return()=>d(y)},[h,r,d]);Knn({active:!!u,onPrevious:p,onNext:m,onClose:f});const v=g.useMemo(()=>({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:i,currentItemId:u,openItem:d,close:f,goToPreviousItem:p,goToNextItem:m}),[e,t,n,r,s,i,u,d,f,p,m]);return o.jsx(ern.Provider,{value:v,children:a})}function trn(){const e=g.useContext(ern);if(!e)throw new Error("useExperimentItemPanel must be used within an ExperimentItemPanelProvider");return e}const IMs=new Set(["itemId","id","status","input","tags","scores"]);function nLe({results:e,isLoading:t,featuredResultId:n,onResultClick:r,columns:s,scoresByItemId:i,scorerIds:a,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u,emptyMessage:d="No results yet",selectedIds:f,onToggleSelect:h,onToggleSelectAll:p}){const{Link:m,paths:v}=un(),y=!!(f&&h),b=s.filter(M=>IMs.has(M.name)||a?.includes(M.name)),x=[y?"2rem":"",...b.map(M=>M.size)].filter(Boolean).join(" "),w=M=>b.some(V=>V.name===M),k=w("itemId")||w("id"),_=w("status"),C=w("input"),T=w("tags"),E=w("scores"),N=f?e.filter(M=>f.has(M.id)).length:0,I=e.length>0&&N===e.length,{containerRef:A,getRowProps:P}=Zc({count:e.length}),L=M=>a?.includes(M.name)?o.jsx(we.TopCell,{children:o.jsxs(m,{href:v.scorerLink(M.name),className:"flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[o.jsx(dw,{}),o.jsx("span",{className:"min-w-0 truncate",children:M.label})]})},M.name):o.jsx(we.TopCell,{children:M.label},M.name);return t?o.jsx(Wl,{columns:x}):o.jsxs(we,{columns:x,className:"min-w-0",scrollRef:A,fit:"container",children:[o.jsxs(we.Top,{hasLeadingCell:y,children:[y&&(p?o.jsx(we.TopSelectCell,{checked:I?!0:N>0?"indeterminate":!1,onToggle:p,"aria-label":"Select all"}):o.jsx(we.TopCell,{children:" "})),y?o.jsx(we.TopCells,{colStart:2,children:b.map(L)}):b.map(L)]}),e.length===0?o.jsx(we.NoMatch,{message:d}):o.jsxs(o.Fragment,{children:[e.map((M,V)=>{const q=!!M.error,H=M.id===n,B=o.jsxs(o.Fragment,{children:[k&&o.jsxs(we.Cell,{className:"text-ui-smd text-neutral3 flex items-center gap-1.5 tracking-wide",children:[o.jsx("span",{children:M.itemId?.slice(0,8)??""}),q&&o.jsxs(In,{children:[o.jsx(On,{render:o.jsx(JN,{role:"img","aria-label":"Error",className:"text-error size-3.5"})}),o.jsx(Cn,{children:RMs(M.error)})]})]}),_&&o.jsx(we.Cell,{className:"flex items-center","data-testid":`result-status-${M.id}`,children:M.status?o.jsx(HDe,{status:M.status}):o.jsx("span",{className:"text-neutral2",children:"—"})}),C&&o.jsx(we.TextCell,{font:"mono",children:$Ms(PMs(M.input),200)}),T&&o.jsx(we.Cell,{className:"flex items-center gap-1 overflow-hidden","data-testid":`result-tags-${M.id}`,children:M.tags?.map(W=>o.jsx(mJ,{value:W,className:"shrink-0"},W))}),E&&o.jsx(we.Cell,{children:o.jsx(AMs,{scores:M.scores})}),a?.map(W=>{const G=i?.[M.itemId]?.find(F=>F.scorerId===W);return o.jsx(we.Cell,{className:"text-neutral3 text-ui-smd font-mono",children:G!=null?G.score.toFixed(3):"-"},W)})]});return y?o.jsxs(we.RowWrapper,{children:[o.jsx(we.SelectCell,{checked:f.has(M.id),onToggle:()=>h(M.id),"aria-label":`Select result ${M.itemId}`}),o.jsx(we.RowButton,{colStart:2,featured:H,"data-selected":H||void 0,onClick:()=>r(M.id),...P(V),children:B})]},M.id):o.jsx(we.RowButton,{featured:H,"data-selected":H||void 0,onClick:()=>r(M.id),...P(V),children:B},M.id)}),o.jsx(we.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function AMs({scores:e}){const t=Array.isArray(e)?e.map(n=>n.score).filter(n=>n!=null):Object.values(e??{});return t.length===0?o.jsx(Te,{variant:"ui-xs",className:"text-neutral2",children:"—"}):o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(St,{size:"sm",className:"text-neutral3",children:o.jsx(gb,{})}),o.jsx(Te,{variant:"ui-xs",className:"text-neutral4 font-mono",children:t[0].toFixed(2)}),t.length>1&&o.jsxs(jt,{children:["+",t.length-1]})]})}function RMs(e){return e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?e.message||"Error":typeof e=="string"&&e?e:"Error"}function PMs(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function $Ms(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}function MMs({experimentId:e,experimentStatus:t,results:n,isLoading:r,setEndOfListElement:s,isFetchingNextPage:i,hasNextPage:a,selectedIds:l,onToggleSelect:c}){const{currentItemId:u,openItem:d,close:f}=trn(),h=g.useMemo(()=>u?n.find(b=>b.itemId===u)?.id??null:null,[n,u]),{data:p}=M1(e,t),m=g.useMemo(()=>{if(!p)return[];const b=new Set;for(const x of Object.values(p))for(const w of x)b.add(w.scorerId);return[...b].sort()},[p]),v=g.useCallback(b=>{const x=n.find(w=>w.id===b);x&&(x.itemId===u?f():d(x.itemId))},[n,u,f,d]),y=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"auto"},{name:"status",label:"Status",size:"auto"},{name:"input",label:"Input",size:"1fr"},{name:"tags",label:"Tags",size:"auto"},...m.map(b=>({name:b,label:b,size:"auto"}))],[m]);return o.jsx("div",{className:"h-full min-h-0 min-w-0 overflow-y-auto",children:o.jsx(nLe,{results:n,isLoading:r,featuredResultId:h,onResultClick:v,columns:y,scoresByItemId:p,scorerIds:m,setEndOfListElement:s,isFetchingNextPage:i,hasNextPage:a,selectedIds:l,onToggleSelect:c})})}function DMs({children:e,className:t}){return o.jsx("div",{className:K("grid content-start gap-4 overflow-y-auto",t),children:e})}function LMs({children:e,className:t,withLeftSeparator:n,withRightSeparator:r}){return o.jsxs("div",{className:"flex w-full overflow-y-auto",children:[n&&o.jsx(Rct,{}),o.jsx("div",{className:K("grid w-full content-start gap-4 overflow-y-auto",t),children:e}),r&&o.jsx(Rct,{})]})}function Rct(){return o.jsx("div",{className:K("mx-3 w-[3px] shrink-0 bg-surface5")})}function FMs({children:e,className:t}){return o.jsx("div",{className:K("flex w-full flex-wrap items-center justify-between gap-3 gap-x-4",t),children:e})}const nrn=Object.assign(LMs,{Content:DMs,Toolbar:FMs});function zMs({children:e,className:t}){return o.jsx("div",{className:K("grid size-full grid-cols-1 overflow-y-auto",t),children:e})}const BMs=e=>{const t=Ye();return yt({queryKey:["experiment-trace-light",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return t.getTraceLight(e)},select:qtn,enabled:!!e})};function UMs(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${gr(n,"MMM dd 'at' H:mm:ss a")}`}return`v${e}`}function VMs({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=$nn(e),i=(s??[]).map(a=>({value:String(a.version),label:`${UMs(a.version,a.createdAt)}${a.isCurrent?" (current)":""}`}));return o.jsxs(nrn.Toolbar,{className:"grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4",children:[o.jsx("div",{}),o.jsx(of,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:i,value:t??"",onValueChange:a=>r?.(a,n??"")}),o.jsx(of,{label:"Version B",labelIsHidden:!0,name:"version-b",options:i,value:n??"",onValueChange:a=>r?.(t??"",a)}),o.jsx("div",{})]})}function rrn({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?djt(new Date(e)):!1,s=e?e5(new Date(e))?"Today":gr(new Date(e),"MMM dd"):"",i=e&&!r?gr(new Date(e),"yyyy"):"",a=e&&n?`${gr(new Date(e),"'at' h:mm aaa")}`:"";return o.jsxs("div",{className:K("truncate text-ui-md text-neutral2",t),children:[s," ",i," ",a]})}function rLe(e){return!e||e.length===0?"":e?.map(t=>t.size).join(" ")}function HMs({columns:e,isSelectionActive:t,children:n}){return o.jsx("div",{className:K("sticky top-0 z-10 mb-2 rounded-lg bg-surface3 px-3"),children:o.jsx("div",{className:K("grid items-center gap-3 text-left text-ui-xs tracking-widest text-neutral3 uppercase",{"pl-12 [&>label]:absolute [&>label]:left-0":t}),style:{gridTemplateColumns:rLe(e)},children:n})})}function WMs({children:e,className:t}){return o.jsx("span",{className:K("py-3",t),children:e})}function ZMs({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 GMs({children:e}){return o.jsx("ul",{className:"grid content-start",children:e})}function QMs({children:e}){const t=g.useRef(null);return o.jsx("div",{ref:t,className:K("overflow-y-auto"),children:e})}function KMs({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 YMs({children:e,href:t,className:n,LinkComponent:r,tooltip:s}){const i=o.jsx(r,{href:t,className:K("flex w-full items-center justify-center gap-4 rounded-lg px-3 py-2 text-left","hover:bg-surface4",Vr.colors,LA.visible,n),children:e});return s==null?i:o.jsxs(In,{children:[o.jsx(On,{render:i}),o.jsx(Cn,{children:s})]})}function XMs({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-5 text-center text-ui-md text-neutral3","[&>svg]:size-[1.5em] [&>svg]:opacity-75",{"[&>svg]:text-red-500":r==="error"}),children:[r==="error"?o.jsx(Pc,{}):o.jsx(Yf,{})," ",t]}):e})}function JMs({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-4 flex justify-center opacity-50",children:[e&&r,!t&&!e&&s]}):null}function e2s({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-4 pt-4 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(id,{}),"Previous"]}),t&&o.jsxs("button",{onClick:n,children:["Next",o.jsx(Kf,{})]})]})]})}function t2s({children:e,className:t}){return o.jsx("div",{className:K("grid grid-rows-[auto_1fr] overflow-y-auto",t),children:e})}function n2s({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",Vr.colors,{"selected-row":e,"grid px-3 gap-3":n}),style:{gridTemplateColumns:rLe(n)},children:t})}function r2s({item:e,isFeatured:t,onClick:n,children:r,columns:s,className:i,disabled:a,tooltip:l,...c}){const u=()=>{n?.(e?.id)},d=o.jsx("button",{...c,onClick:u,className:K("grid w-full items-center gap-3 rounded-lg px-3 text-left",Vr.colors,LA.visible,{"bg-surface4":t,"hover:bg-surface4":e&&!t&&!a},i),style:{gridTemplateColumns:rLe(s)},disabled:a,children:r});return l==null?d:o.jsxs(In,{children:[o.jsx(On,{render:d}),o.jsx(Cn,{children:l})]})}function s2s(e){return e.charAt(0).toUpperCase()+e.slice(1)}function i2s({status:e}){return e?o.jsxs(In,{children:[o.jsx(On,{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(Cn,{children:s2s(e)})]}):null}function a2s({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 Pct={latest:"Latest version",deleted:"Deleted in this version"};function o2s({version:e,date:t,isLatest:n,isDeleted:r}){return o.jsxs(rrn,{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?gr(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":Pct.latest,children:o.jsx(jt,{variant:"blue",size:"sm",icon:o.jsx($C,{})})}),r&&o.jsx("span",{className:"inline-flex",role:"img","aria-label":Pct.deleted,children:o.jsx(jt,{variant:"red",size:"sm",icon:o.jsx(vCe,{})})})]})]})}const Hp=Object.assign(t2s,{Header:HMs,HeaderCol:WMs,Items:GMs,Scroller:QMs,Row:n2s,RowButton:r2s,Message:XMs,NextPageLoading:JMs,Pagination:e2s,Cell:rrn,TextCell:a2s,StatusCell:i2s,VersionCell:o2s,IdCell:ZMs,DateCell:qMs,LinkCell:YMs,LabelCell:KMs}),l2s=[{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"}],hU={added:{badgeVariant:"blue",borderColor:"border-blue-900",icon:o.jsx(Yr,{}),tooltip:"Added in this version"},changed:{badgeVariant:"yellow",borderColor:"border-yellow-900",icon:o.jsx(uPn,{}),tooltip:"Changed in this version"},same:{badgeVariant:"green",borderColor:"border-green-900",icon:o.jsx(zSt,{}),tooltip:"Same in both versions"}};function Mue({red:e=!1,tooltip:t}){return o.jsxs(In,{children:[o.jsx(On,{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(vCe,{className:K("text-neutral3/40 w-5 h-5 ",{"text-red-900":e})})}),o.jsx(Cn,{children:t})]})}function Due({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}=hU[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(jt,{variant:n,size:"xs",icon:r})})]})}function c2s(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function $ct({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return"added";if(t==="changed"&&n)return"changed"}function u2s({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:i}){const{Link:a}=un(),l=t>n;return o.jsx(Hp,{children:o.jsx(Hp.Scroller,{children:o.jsx(Hp.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=i.get(c),f=c2s(u,d),h=$ct({otherVersionExists:d!==void 0,status:f,isNewer:l}),p=$ct({otherVersionExists:u!==void 0,status:f,isNewer:!l});return o.jsxs(Hp.Row,{columns:l2s,children:[o.jsx(Hp.IdCell,{id:c,isShortened:!1}),f!=="same"?o.jsxs(o.Fragment,{children:[u?.datasetVersion?o.jsx(Hp.LinkCell,{LinkComponent:a,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:h?hU[h].tooltip:void 0,children:o.jsx(Due,{variant:h,version:u.datasetVersion})}):o.jsx(Hp.Cell,{className:"flex items-center justify-center",children:o.jsx(Mue,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?o.jsx(Hp.LinkCell,{LinkComponent:a,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:p?hU[p].tooltip:void 0,children:o.jsx(Due,{variant:p,version:d.datasetVersion})}):o.jsx(Hp.Cell,{className:"flex items-center justify-center",children:o.jsx(Mue,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):o.jsx(Hp.LinkCell,{LinkComponent:a,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",tooltip:hU.same.tooltip,children:o.jsx(Due,{variant:"same",version:d?.datasetVersion})}),f==="changed"?o.jsx(Hp.LinkCell,{LinkComponent:a,href:`/datasets/${e}/items/${c}/versions?version=${u?.datasetVersion}&compare=${d?.datasetVersion}`,children:"Compare"}):o.jsx(Hp.Cell,{children:o.jsx(Mue,{tooltip:"Comparing is available only for changed items"})})]},c)})})})})}const pU="targetType",o2="targetId";function sLe({resetParams:e=[]}={}){const[t,n]=bi(),r=e.join(","),s=t.get(pU),i=Vnn(s)?s:"",a=i?t.get(o2)??"":"",l=g.useCallback(d=>{n(f=>{const h=new URLSearchParams(f);d?h.set(pU,d):h.delete(pU),h.delete(o2);for(const p of r.split(","))p&&h.delete(p);return h},{replace:!0})},[n,r]),c=g.useCallback(d=>{n(f=>{const h=new URLSearchParams(f);d?h.set(o2,d):h.delete(o2);for(const p of r.split(","))p&&h.delete(p);return h},{replace:!0})},[n,r]),u=g.useCallback(()=>l(""),[l]);return{targetType:i,targetId:a,setTargetType:l,setTargetId:c,clear:u}}function d2s(){const e=Fr(),[t,n]=g.useState(""),[r,s]=g.useState("all"),[i,a]=g.useState("all"),{targetType:l,targetId:c,setTargetType:u,setTargetId:d,clear:f}=sLe(),{data:h=[],isLoading:p,error:m,isFetchingNextPage:v,hasNextPage:y,setEndOfListElement:b}=_Un({targetType:l,targetId:c}),{data:x,isLoading:w,error:k}=KG(),_=g.useMemo(()=>x?.experiments??[],[x?.experiments]),C=g.useMemo(()=>c$s(h),[h]),T=p||w,E=m||k,N=()=>{e("/datasets/new")},I=o.jsx(xv,{owner:"dataset-list",children:o.jsx(J_,{onClick:N,tooltip:"Create a dataset",variant:"ghost",size:"sm",children:"New dataset"})});if(E&&ks(E))return o.jsx(Qn,{children:o.jsx(Gs,{})});if(E&&Es(E))return o.jsx(Qn,{children:o.jsx(Fs,{resource:"datasets"})});if(E)return o.jsx(Qn,{children:o.jsx(Ws,{title:"Failed to load datasets",message:E.message})});if(h.length===0&&!T&&!l)return o.jsxs(Qn,{children:[I,o.jsx(u$s,{onCreateClick:N})]});const A=r!=="all"||i!=="all"||t!==""||l!=="",P=()=>{n(""),s("all"),a("all"),f()};return o.jsxs(Ft,{height:"full",children:[I,o.jsx(Ft.TopArea,{children:o.jsx(b$s,{search:t,onSearchChange:n,experimentFilter:r,onExperimentFilterChange:s,tagFilter:i,onTagFilterChange:a,tagOptions:C,targetType:l,onTargetTypeChange:u,targetId:c,onTargetIdChange:d,onReset:P,hasActiveFilters:A})}),o.jsx(o$s,{datasets:h,experiments:_,isLoading:T,search:t,experimentFilter:r,tagFilter:i,isFetchingNextPage:v,hasNextPage:y,setEndOfListElement:b})]})}function f2s(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 h2s({item:e,itemId:t,fallback:n,onClose:r,...s}){const i=e?.id??t;return o.jsx($t,{open:!!i,onClose:r,title:`Dataset item ${i??""}`,children:e?o.jsx(p2s,{item:e,onClose:r,...s},e.id):t?o.jsxs(o.Fragment,{children:[o.jsxs($t.Header,{children:[o.jsx($t.CloseButton,{onClick:r,tooltip:"Close detail panel"}),o.jsxs($t.Heading,{children:["Item",o.jsx($t.CopyId,{id:t})]})]}),n]}):null})}function p2s({datasetId:e,item:t,items:n,onItemChange:r,onClose:s}){const{Link:i}=un(),{updateItem:a,deleteItem:l}=pl(),[c,u]=g.useState(!1),[d,f]=g.useState(""),[h,p]=g.useState(""),[m,v]=g.useState(""),[y,b]=g.useState(""),[x,w]=g.useState(""),[k,_]=g.useState(t.scorerIds!==void 0),[C,T]=g.useState(t.scorerIds??[]),[E,N]=g.useState(""),[I,A]=g.useState(null),[P,L]=g.useState(!1);g.useEffect(()=>{t&&(f(JSON.stringify(t.input,null,2)),p(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),v(t.metadata?JSON.stringify(t.metadata,null,2):""),b(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),w(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),_(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 M=n.findIndex(F=>F.id===t.id),V=M>0?()=>r(n[M-1].id):void 0,q=M>=0&&M<n.length-1?()=>r(n[M+1].id):void 0,H=async()=>{let F;try{F=JSON.parse(d)}catch{Ge.error("Input must be valid JSON");return}let R;if(h.trim())try{R=JSON.parse(h)}catch{Ge.error("Ground Truth must be valid JSON");return}let D;if(m.trim())try{D=JSON.parse(m)}catch{Ge.error("Metadata must be valid JSON");return}let U=null;if(y.trim())try{U=JSON.parse(y)}catch{Ge.error("Expected Trajectory must be valid JSON");return}let Q;if(x.trim())try{const te=JSON.parse(x);if(!Array.isArray(te)){Ge.error("Tool Mocks must be a JSON array");return}Q=te}catch{Ge.error("Tool Mocks must be valid JSON");return}else Q=[];let ee;if(E.trim())try{ee=JSON.parse(E)}catch{Ge.error("Request Context must be valid JSON");return}let J;k?J=C:t.scorerIds!==void 0&&(J=null);try{const te=await a.mutateAsync({datasetId:e,itemId:t.id,input:F,groundTruth:R,metadata:D,expectedTrajectory:U,toolMocks:Q,scorerIds:J,requestContext:ee});Ge.success("Item updated successfully"),_(te.scorerIds!==void 0),T(te.scorerIds??[]),u(!1),A(null)}catch(te){const re=f2s(te);re?A(re):Ge.error(`Failed to update item: ${te instanceof Error?te.message:"Unknown error"}`)}},B=()=>{f(JSON.stringify(t.input,null,2)),p(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),v(t.metadata?JSON.stringify(t.metadata,null,2):""),b(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),w(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),_(t.scorerIds!==void 0),T(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),A(null)},W=F=>{f(F),I?.field==="input"&&A(null)},z=F=>{p(F),I?.field==="groundTruth"&&A(null)},G=async()=>{try{await l.mutateAsync({datasetId:e,itemId:t.id}),Ge.success("Item deleted successfully"),L(!1),s()}catch(F){Ge.error(`Failed to delete item: ${F instanceof Error?F.message:"Unknown error"}`)}};return o.jsxs(o.Fragment,{children:[o.jsxs($t.Header,{children:[o.jsx($t.CloseButton,{onClick:s,tooltip:"Close detail panel"}),o.jsxs($t.Heading,{children:["Item",o.jsx($t.CopyId,{id:t.id})]}),o.jsxs($t.HeaderActions,{children:[!c&&o.jsxs(o.Fragment,{children:[o.jsx(ae,{render:o.jsx(i,{href:`/datasets/${e}/items/${t.id}/versions?version=${t.datasetVersion}`}),size:"sm",variant:"ghost",tooltip:"Go to item versions history","aria-label":"Go to item versions history",children:o.jsx(ACe,{})}),o.jsxs(xt,{children:[o.jsx(xt.Trigger,{asChild:!0,children:o.jsx(ae,{size:"sm",variant:"ghost",tooltip:"Open actions menu","aria-label":"Open actions menu",children:o.jsx(F1,{})})}),o.jsxs(xt.Content,{align:"end",className:"w-48",children:[o.jsxs(xt.Item,{onSelect:()=>u(!0),children:[o.jsx(Gd,{}),"Edit"]}),o.jsxs(xt.Item,{onSelect:()=>L(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(co,{}),"Delete Item"]})]})]})]}),o.jsx($t.NextPrevNav,{onPrevious:V,onNext:q,previousLabel:"Go to previous item",nextLabel:"Go to next item"})]})]}),o.jsx($t.Content,{children:c?o.jsx(CMs,{inputValue:d,setInputValue:W,groundTruthValue:h,setGroundTruthValue:z,metadataValue:m,setMetadataValue:v,trajectoryValue:y,setTrajectoryValue:b,toolMocksValue:x,setToolMocksValue:w,scorerOverrideEnabled:k,setScorerOverrideEnabled:_,selectedScorerIds:C,setSelectedScorerIds:T,requestContextValue:E,setRequestContextValue:N,validationErrors:I,onSave:H,onCancel:B,isSaving:a.isPending}):o.jsx(Rke,{item:t})}),o.jsx(At,{open:P,onOpenChange:L,children:o.jsxs(At.Content,{children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Delete Item"}),o.jsx(At.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),o.jsxs(At.Footer,{children:[o.jsx(At.Cancel,{children:"Cancel"}),o.jsx(At.Action,{onClick:G,children:l.isPending?"Deleting...":"Yes, Delete"})]})]})})]})}function m2s(){const{datasetId:e,items:t,isLoadingItems:n,currentItemId:r,openItem:s,close:i}=Xnn(),a=g.useMemo(()=>r?t.find(d=>d.id===r):void 0,[t,r]),{data:l,isLoading:c}=Ktn(a?"":e,!a&&r?r:""),u=a??l??void 0;return o.jsx(h2s,{datasetId:e,item:u,itemId:r,fallback:n||c?o.jsx($t.LoadingData,{}):o.jsxs($t.NoData,{children:['No loaded item "',r,'".']}),items:t,onItemChange:s,onClose:i})}function SB({children:e}){return o.jsxs(Ft,{height:"full",children:[o.jsx("div",{}),o.jsx(Ft.MainArea,{isCentered:!0,children:e})]})}function g2s(){const{datasetId:e}=ur(),t=Fr(),[n,r]=bi(),{activeVersion:s,handleVersionChange:i}=tLe(n,r),[a,l]=g.useState(!1),[c,u]=g.useState(!1),[d,f]=g.useState(!1),[h,p]=g.useState(!1),{data:m,error:v,isLoading:y}=bv(e),{data:b=[],isLoading:x}=gA(e,void 0,s),w=!x&&b.length===0;if(y)return null;if(v&&ks(v))return o.jsx(SB,{children:o.jsx(Gs,{})});if(v&&Es(v))return o.jsx(SB,{children:o.jsx(Fs,{resource:"datasets"})});if(v&&CR(v)||!y&&!v&&!m)return o.jsx(SB,{children:o.jsx(Ar,{iconSlot:o.jsx(rv,{}),titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:o.jsx(ae,{render:o.jsx(oo,{to:"/datasets"}),icon:o.jsx(id,{}),children:"Back to Datasets"})})});if(v)return o.jsx(SB,{children:o.jsx(Ws,{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(bMs,{datasetId:e,items:b,isLoadingItems:x,children:[o.jsxs("div",{className:"h-full",children:[o.jsx(Ft,{height:"full",className:"grid-rows-[1fr] p-0",children:o.jsx(Ft.MainArea,{children:o.jsx(xMs,{datasetId:e,onAddItemClick:()=>u(!0),belowToolbarSlot:o.jsx(wMs,{datasetId:e}),leftSlot:o.jsx("span",{className:"text-ui-sm text-neutral3 mr-3 whitespace-nowrap",children:m?.createdAt?`Created ${gr(new Date(m.createdAt),"MMM d")}`:""}),rightSlot:o.jsxs(Ms,{children:[o.jsx(ae,{render:o.jsx(oo,{to:`/experiments?dataset=${e}`}),icon:o.jsx(OCe,{}),children:"View experiments"}),o.jsx(Qnn,{datasetId:e,value:s,onValueChange:i,currentVersion:m?.version,className:"w-36"}),w?o.jsxs(In,{children:[o.jsx(On,{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.jsx(ae,{variant:"primary",icon:o.jsx(bu,{}),children:"Run Experiment"})})})}),o.jsx(Cn,{children:"Add items to the dataset before running an experiment"})]}):o.jsx(ae,{variant:"primary",onClick:()=>l(!0),icon:o.jsx(bu,{}),children:"Run Experiment"}),o.jsxs(xt,{children:[o.jsx(xt.Trigger,{asChild:!0,children:o.jsx(ae,{size:"lg","aria-label":"Dataset actions menu",children:o.jsx(F1,{})})}),o.jsxs(xt.Content,{align:"end",className:"w-48",children:[o.jsxs(xt.Item,{onSelect:()=>{t(`/datasets/${e}/edit`)},children:[o.jsx(Gd,{})," Edit Dataset"]}),o.jsxs(xt.Item,{onSelect:()=>p(!0),children:[o.jsx(ed,{})," Duplicate Dataset"]}),o.jsxs(xt.Item,{onSelect:()=>f(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(co,{})," Delete Dataset"]})]})]})]})})})}),o.jsx(m2s,{})]}),o.jsx(yJ,{initialDatasetId:e,initialDatasetVersion:s??void 0,open:a,onOpenChange:l,onSuccess:k},`${e}:${s??"latest"}`),o.jsx(kMs,{datasetId:e,open:c,onOpenChange:u}),m&&o.jsx(M$s,{open:h,onOpenChange:p,sourceDatasetId:m.id,sourceDatasetName:m.name,sourceDatasetDescription:m.description,sourceDatasetTargetType:m.targetType}),m&&o.jsx(z$s,{open:d,onOpenChange:f,datasetId:m.id,datasetName:m.name,onSuccess:_})]})}function Lue({children:e}){return o.jsxs(Ft,{height:"full",children:[o.jsx("div",{}),o.jsx(Ft.MainArea,{isCentered:!0,children:e})]})}function v2s(){const{datasetId:e}=ur(),t=Fr(),{data:n,error:r,isLoading:s}=bv(e),i=()=>{t(`/datasets/${e}`)};return s?null:r&&ks(r)?o.jsx(Lue,{children:o.jsx(Gs,{})}):r&&Es(r)?o.jsx(Lue,{children:o.jsx(Fs,{resource:"datasets"})}):r||!n?o.jsx(Lue,{children:o.jsx(Ws,{title:"Failed to load dataset",message:r instanceof Error?r.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Ft,{height:"full",children:[o.jsx("div",{}),o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-4 py-5",children:[o.jsx(qh,{className:"mb-6 p-0",children:o.jsxs(qh.Column,{children:[o.jsxs(qh.Title,{children:[o.jsx(rv,{})," Edit dataset"]}),o.jsx(qh.Description,{children:n.name})]})}),o.jsx(Jf,{className:"p-4",children:o.jsx(F$s,{dataset:{id:n.id,name:n.name,description:n.description||"",inputSchema:n.inputSchema,groundTruthSchema:n.groundTruthSchema,requestContextSchema:n.requestContextSchema,scorerIds:n.scorerIds},onSuccess:i,onCancel:i})})]})})]})}function Mct(e,t){return{id:e.id,datasetId:t,datasetVersion:e.datasetVersion,input:e.input,groundTruth:e.groundTruth,expectedTrajectory:e.expectedTrajectory,toolMocks:e.toolMocks,scorerIds:e.scorerIds,requestContext:e.requestContext,metadata:e.metadata,createdAt:e.createdAt,updatedAt:e.updatedAt}}function Dct(e,t){return e.map(n=>{const r=typeof n.updatedAt=="string"?new Date(n.updatedAt):n.updatedAt;return{value:String(n.datasetVersion),label:o.jsxs("span",{className:"flex w-full items-center gap-2",children:[o.jsxs("span",{children:[o.jsxs("b",{children:["v. ",n.datasetVersion]})," · ",gr(r,"MMM d, HH:mm")]}),n.isLatest?o.jsx(jt,{variant:"blue",size:"xs",className:"ml-auto",children:"Latest"}):null]}),disabled:t?.has(n.datasetVersion)??!1}})}function Lct(e){const t=Number(e);return e!=null&&Number.isFinite(t)&&t>0?t:null}function y2s(){const{datasetId:e,itemId:t}=ur(),[n,r]=bi(),s=Lct(n.get("version")),i=Lct(n.get("compare")),a=n.get("view")==="diff",{data:l,error:c}=bv(e??""),{data:u,isLoading:d}=UPs(e??"",t??""),f=(s!=null?u?.find(C=>C.datasetVersion===s):void 0)??u?.[0],h=f?.datasetVersion??null,p=i!=null&&i!==h?i:null,{data:m,isLoading:v}=VPs(e??"",t??"",p??0,l?.version),y=(C,T)=>r(E=>{const N=new URLSearchParams(E);return T==null?N.delete(C):N.set(C,String(T)),N},{replace:!0});if(c&&ks(c))return o.jsx(oi,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Gs,{})})});if(c&&Es(c))return o.jsx(oi,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{resource:"datasets"})})});if(!e||!t)return o.jsx(oi,{children:o.jsx(i0,{children:o.jsx("div",{className:"text-neutral4 py-5 text-center",children:o.jsx("p",{children:"Item not found."})})})});const b=!!(f&&m),x=a&&b,w=f?Mct(f,e):null,k=m?Mct(m,e):null,_=(f?.datasetVersion??0)<(m?.datasetVersion??0);return o.jsxs(oi,{children:[o.jsx(xv,{owner:"dataset-item-versions",children:b&&o.jsx(ae,{variant:"outline",onClick:()=>y("view",a?null:"diff"),children:a?o.jsxs(o.Fragment,{children:[o.jsx(wCe,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(MAn,{})," Diff View"]})})}),o.jsx(Ft,{height:"full",className:"grid-rows-[minmax(0,1fr)]",children:o.jsxs("div",{className:"grid min-h-0 grid-cols-1 gap-4 md:grid-cols-2",children:[o.jsxs(Jf,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[o.jsx(xwe,{children:o.jsx(Fct,{name:"version",value:h!=null?String(h):"",options:Dct(u??[],p!=null?new Set([p]):void 0),onValueChange:C=>y("version",Number(C))})}),o.jsx(O0,{className:"grid content-start gap-5 overflow-y-auto",children:d?o.jsx("div",{className:"text-neutral4 text-ui-md",children:"Loading..."}):w?o.jsx(Rke,{item:w,diff:x&&k?{against:k,side:_?"a":"b"}:void 0}):o.jsx("div",{className:"text-neutral4 text-ui-md",children:"Item data not available"})})]}),o.jsxs(Jf,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[o.jsx(xwe,{children:o.jsx(Fct,{name:"compare",value:p!=null?String(p):"",placeholder:"Select a version to compare",options:Dct(u??[],h!=null?new Set([h]):void 0),onValueChange:C=>y("compare",Number(C))})}),o.jsx(O0,{className:"grid content-start gap-5 overflow-y-auto",children:p==null?o.jsx(Ar,{className:"h-full",iconSlot:o.jsx(rbe,{className:"text-neutral3 size-8"}),titleSlot:"No version selected",descriptionSlot:"Pick a version above to compare it with the one on the left."}):v?o.jsx("div",{className:"text-neutral4 text-ui-md",children:"Loading..."}):k?o.jsx(Rke,{item:k,diff:x&&w?{against:w,side:_?"b":"a"}:void 0}):o.jsxs("div",{className:"text-neutral4 text-ui-md",children:["Version ",p," not found"]})})]})]})})]})}function Fct({name:e,value:t,options:n,placeholder:r="Select version",onValueChange:s}){return o.jsxs("div",{className:"grid grid-cols-[auto_1fr] items-center gap-4",children:[o.jsx(ACe,{className:"size-4 opacity-50"}),o.jsxs(Ci,{name:e,value:t,onValueChange:s,children:[o.jsx(Ei,{"aria-label":e==="compare"?"Compare version":"Version",className:"w-full",children:o.jsx(_i,{placeholder:r,className:"flex-1"})}),o.jsx(Ti,{children:n.map(i=>o.jsx(Cr,{value:i.value,disabled:i.disabled,children:i.label},i.value))})]})]})}function b2s(){const{datasetId:e}=ur(),[t]=bi(),n=t.get("ids")?.split(",").map(Number).filter(m=>!isNaN(m)&&m>0)??[],r=Fr(),{data:s,error:i}=bv(e??""),a=gA(e??"",void 0,n[0]??null),l=gA(e??"",void 0,n[1]??null),c=g.useMemo(()=>a.data??[],[a.data]),u=g.useMemo(()=>l.data??[],[l.data]),d=g.useMemo(()=>{const m=new Map;for(const v of[...c,...u])m.has(v.id)||m.set(v.id,{id:v.id,createdAt:new Date(v.createdAt)});return[...m.values()].sort((v,y)=>y.createdAt.getTime()-v.createdAt.getTime())},[c,u]),f=g.useMemo(()=>new Map(c.map(m=>[m.id,m])),[c]),h=g.useMemo(()=>new Map(u.map(m=>[m.id,m])),[u]);if(i&&ks(i))return o.jsx(oi,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Gs,{})})});if(i&&Es(i))return o.jsx(oi,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{resource:"datasets"})})});if(!e||n.length<2)return o.jsx(oi,{children:o.jsx(i0,{children:o.jsx("div",{className:"text-neutral4 py-5 text-center",children:o.jsx("p",{children:"Select at least two versions to compare."})})})});const p=(m,v)=>{r(`/datasets/${e}/versions?ids=${m},${v}`,{replace:!0})};return o.jsx(oi,{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-4",children:[o.jsxs(qh,{children:[o.jsxs(qh.Column,{children:[o.jsxs(qh.Title,{children:[o.jsx(zPn,{})," Compare Dataset Versions"]}),o.jsx(qh.Description,{children:o.jsxs(Bd,{children:[o.jsx(ACe,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),o.jsx(qh.Column,{children:o.jsx(ae,{render:o.jsx(oo,{to:`/datasets/${e}`}),icon:o.jsx(id,{}),children:"Back to Dataset"})})]}),o.jsx(zMs,{children:o.jsxs(nrn,{children:[o.jsx(VMs,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:p}),o.jsx(u2s,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:h})]})})]})})})}function x2s(){const e=Fr(),[t]=bi(),n=t.get("targetType"),r=Vnn(n)?n:void 0,s=t.get("targetIds"),i=r&&s?s.split(",").map(l=>l.trim()).filter(Boolean):void 0,a=l=>{e(`/datasets/${l}`)};return o.jsxs(Ft,{height:"full",children:[o.jsx("div",{}),o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-4 py-5",children:[o.jsx(qh,{className:"mb-6 p-0",children:o.jsxs(qh.Column,{children:[o.jsxs(qh.Title,{children:[o.jsx(rv,{})," Create new dataset"]}),o.jsx(qh.Description,{children:"Datasets group test cases used to evaluate your agents and workflows."})]})}),o.jsx(Jf,{className:"p-4",children:o.jsx(I$s,{targetType:r,targetIds:i,onSuccess:a,onCancel:()=>{e(-1)}})})]})})]})}function Pke({children:e,className:t}){return o.jsx("div",{className:K("flex flex-wrap gap-4",t),children:e})}function w2s(e){if(!e||e.length<2)return null;const t=[...e].sort((a,l)=>new Date(a.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 i=(s-r)/r*100;return{changePct:Math.round(i*10)/10,prevValue:String(r)}}function S2s({scorers:e,datasets:t,experiments:n,avgScore:r,prevAvgScore:s,totalNeedsReview:i,isLoadingScorers:a,isLoadingDatasets:l,isLoadingExperiments:c,isLoadingScores:u,isLoadingReview:d}){const f=e?Object.keys(e).length:void 0,h=t?.length,p=n?.length,m=r!=null&&s!=null&&s!==0?{changePct:Math.round((r-s)/s*100*10)/10,prevValue:String(s)}:null,v=w2s(n);return o.jsxs(o.Fragment,{children:[o.jsxs(Mr,{children:[o.jsx(Mr.Label,{children:"Total Scorers"}),a?o.jsx(Mr.Loading,{}):f!=null?o.jsxs(o.Fragment,{children:[o.jsx(Mr.Value,{children:String(f)}),o.jsx(Mr.NoChange,{message:"Static count"})]}):o.jsx(Mr.NoData,{})]}),o.jsxs(Mr,{children:[o.jsx(Mr.Label,{children:"Total Datasets"}),l?o.jsx(Mr.Loading,{}):h!=null?o.jsxs(o.Fragment,{children:[o.jsx(Mr.Value,{children:String(h)}),o.jsx(Mr.NoChange,{message:"Static count"})]}):o.jsx(Mr.NoData,{})]}),o.jsxs(Mr,{children:[o.jsx(Mr.Label,{children:"Avg Score"}),u?o.jsx(Mr.Loading,{}):r!=null?o.jsxs(o.Fragment,{children:[o.jsx(Mr.Value,{children:String(r)}),m?o.jsx(Mr.Change,{changePct:m.changePct,prevValue:m.prevValue}):o.jsx(Mr.NoChange,{})]}):o.jsx(Mr.NoData,{})]}),o.jsxs(Mr,{children:[o.jsx(Mr.Label,{children:"Total Experiments"}),c?o.jsx(Mr.Loading,{}):p!=null?o.jsxs(o.Fragment,{children:[o.jsx(Mr.Value,{children:String(p)}),v?o.jsx(Mr.Change,{changePct:v.changePct,prevValue:v.prevValue}):o.jsx(Mr.NoChange,{})]}):o.jsx(Mr.NoData,{})]}),o.jsxs(Mr,{children:[o.jsx(Mr.Label,{children:"Needs Review"}),d?o.jsx(Mr.Loading,{}):i!=null?o.jsxs(o.Fragment,{children:[o.jsx(Mr.Value,{children:String(i)}),i>0?o.jsx(Mr.NoChange,{message:"items pending review"}):o.jsx(Mr.NoChange,{message:"All caught up"})]}):o.jsx(Mr.NoData,{})]})]})}function srn({open:e,onOpenChange:t,experimentId:n,experimentName:r,onSuccess:s}){const{deleteExperiment:i}=pl(),a=async()=>{try{await i.mutateAsync(n),Ge.success("Experiment deleted successfully"),t(!1),s?.()}catch(l){Ge.error(`Failed to delete experiment: ${l instanceof Error?l.message:"Unknown error"}`)}};return o.jsx(At,{open:e,onOpenChange:t,children:o.jsxs(At.Content,{children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Delete Experiment"}),o.jsxs(At.Description,{children:['Are you sure you want to delete "',r||n,'"? This will permanently delete the experiment, all its results, and the traces it produced, including their spans and any scores, feedback, metrics and logs attached to those traces. This action cannot be undone.']})]}),o.jsxs(At.Footer,{children:[o.jsx(ae,{icon:o.jsx(co,{}),variant:"primary",size:"lg",onClick:a,disabled:i.isPending,children:i.isPending?"Deleting...":"Delete"}),o.jsx(At.Cancel,{children:"Cancel"})]})]})})}const k2s="minmax(9rem,1fr)",O2s="minmax(8rem,16rem)",C2s="1fr",_2s="auto auto auto auto auto auto auto",Yv={experiment:"Experiment",description:"Description",dataset:"Dataset",target:"Target",status:"Status",items:"Items",succeeded:"Processed",failed:"Errored",review:"Review",date:"Date"},E2s={completed:"neutral",running:"yellow",failed:"red",pending:"neutral"},T2s={completed:"Run completed",running:"Run in progress",failed:"Run failed",pending:"Run queued"};function j2s(e){return e?(typeof e=="string"?new Date(e):e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function irn(e){const t=ub(e.id)??e.id;return e.name||`Experiment #${t}`}const N2s=60;function I2s({experiment:e}){return o.jsx("span",{className:"text-neutral4 block min-w-0 truncate text-left",children:irn(e)})}function A2s({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<=N2s?n:o.jsxs(In,{children:[o.jsx(On,{asChild:!0,children:n}),o.jsx(Cn,{children:t})]})}function arn(){const{data:e}=rh(),{data:t}=eg(),{data:n}=Ep(),{data:r}=eP();return{agents:e,workflows:t,scorers:n,processors:r}}function orn(e){return o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 10.123 10.123",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M4.50195 1.53809H5.62109V0H6.75098V1.53809H7.5293L7.64258 1.54395C8.19939 1.60066 8.63379 2.0708 8.63379 2.64258V3.37305H10.123V4.50195H8.63379V5.62109H10.123V6.75H8.63379V7.57812L8.62891 7.69141C8.57589 8.2109 8.16211 8.62387 7.64258 8.67676L7.5293 8.68262H6.75098V10.123H5.62109V8.68262H4.50195V10.123H3.37305V8.68262H2.59375L2.48047 8.67676C1.96102 8.62383 1.54817 8.21082 1.49512 7.69141L1.48926 7.57812V6.75H0V5.62109H1.48926V4.50195H0V3.37305H1.48926V2.64258C1.48926 2.07084 1.92371 1.60071 2.48047 1.54395L2.59375 1.53809H3.37305V0H4.50195V1.53809ZM2.61914 7.55273H7.50488V2.66699H2.61914V7.55273Z",fill:"currentColor"})})}const lrn={agent:Ma,workflow:Bc,scorer:dw,processor:orn},crn={agent:"Agent",workflow:"Workflow",scorer:"Scorer",processor:"Processor"},R2s="External (caller-run)";function urn(e,{agents:t,workflows:n,scorers:r,processors:s}){const{targetType:i,targetId:a}=e;if(!a)return R2s;switch(i){case"agent":return t?.[a]?.name??a;case"workflow":return n?.[a]?.name??a;case"scorer":return r?.[a]?.scorer?.config?.name??a;case"processor":return s?.[a]?.name??a;default:return a}}function P2s({experiment:e,datasetName:t,review:n}){const r=e.status??"pending",s=e.succeededCount??0,i=e.failedCount??0,a=e.totalItems??0;return o.jsxs(o.Fragment,{children:[o.jsx(we.Cell,{children:o.jsx(I2s,{experiment:e})}),o.jsx(we.Cell,{children:o.jsx(A2s,{experiment:e})}),t!==void 0&&o.jsx(we.TextCell,{children:t}),o.jsx(we.Cell,{children:o.jsx($2s,{experiment:e})}),o.jsx(we.Cell,{children:o.jsx(jt,{variant:E2s[r]??"neutral",indicator:"dot",children:T2s[r]??r})}),o.jsx(we.TextCell,{className:"text-center",children:a}),o.jsx(we.TextCell,{className:"text-center",children:s}),o.jsx(we.TextCell,{className:"text-center",children:o.jsx("span",{className:i>0?"text-accent2":"",children:i})}),o.jsx(we.Cell,{className:"text-center",children:o.jsx(M2s,{review:n})}),o.jsx(we.TextCell,{children:j2s(e.createdAt)})]})}function $2s({experiment:e}){const t=arn(),n=urn(e,t),r=e.targetId?e.targetType:null,s=r?lrn[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":crn[r],children:o.jsx(s,{})}),o.jsx("span",{className:r?"truncate":"text-neutral2 truncate",children:n})]})}function M2s({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(jt,{size:"xs",variant:"yellow",children:[e.needsReview," pending"]}):o.jsxs(jt,{size:"xs",variant:"green",children:[e.complete,"/",t," reviewed"]})}const drn=`${k2s} ${O2s} ${C2s} ${_2s}`,zct=`${drn} auto`,D2s=[{label:Yv.experiment},{label:Yv.description},{label:Yv.dataset},{label:Yv.target},{label:Yv.status},{label:Yv.items,className:"text-center"},{label:Yv.succeeded,className:"text-center"},{label:Yv.failed,className:"text-center"},{label:Yv.review,className:"text-center"},{label:Yv.date}],frn=e=>e.stopPropagation();function L2s({experiment:e,rowProps:t,onSelect:n,featured:r,onDelete:s,children:i}){const{paths:a,Link:l}=un(),c=g.useRef(null);return o.jsxs(we.RowWrapper,{...t,onSelectRow:n??(()=>c.current?.click()),children:[n?o.jsx(we.RowButton,{colEnd:-2,featured:r,tabIndex:-1,onClick:u=>{u.stopPropagation(),n()},children:i}):o.jsx(we.RowLink,{ref:c,colEnd:-2,to:a.experimentLink(e.id),LinkComponent:l,tabIndex:-1,onClick:frn,children:i}),o.jsx(we.ActionsCell,{className:"pl-2",children:o.jsx(ae,{type:"button",variant:"ghost",size:"icon-xs",tooltip:"Delete experiment","aria-label":`Delete experiment ${e.name??e.id}`,onClick:u=>{u.stopPropagation(),s()},children:o.jsx(co,{className:"size-4"})})})]})}function F2s({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:i="all",datasetFilter:a="all",selection:l,onSelectExperiment:c,selectedExperimentId:u,keyboardGlobal:d=!0,isFetchingNextPage:f,hasNextPage:h,setEndOfListElement:p}){const m=l!==void 0,v=g.useMemo(()=>{const E=new Map;return t?.forEach(N=>E.set(N.id,N.name)),E},[t]),y=g.useMemo(()=>[...e].sort((E,N)=>{const I=E.createdAt?new Date(E.createdAt).getTime():0;return(N.createdAt?new Date(N.createdAt).getTime():0)-I}),[e]),b=g.useMemo(()=>{const E=s.toLowerCase();return y.filter(N=>{const I=N.datasetId?v.get(N.datasetId)??"":"",A=!E||N.id.toLowerCase().includes(E)||(N.name??"").toLowerCase().includes(E)||I.toLowerCase().includes(E)||(N.targetId??"").toLowerCase().includes(E),P=i==="all"||N.status===i,L=a==="all"||N.datasetId===a;return A&&P&&L})},[y,s,v,i,a]),{containerRef:x,getRowProps:w}=Zc({count:b.length,global:d}),[k,_]=g.useState(null);if(r)return o.jsx(Wl,{columns:zct});const C=m?`auto ${drn}`:zct,T=D2s.map(E=>o.jsx(we.TopCell,{className:E.className,children:E.label},E.label));return o.jsxs(we,{columns:C,scrollRef:x,children:[o.jsx(we.Top,{hasLeadingCell:m,children:m?o.jsxs(o.Fragment,{children:[o.jsx(we.TopCell,{children:" "}),o.jsx(we.TopCells,{colStart:2,children:T})]}):o.jsxs(o.Fragment,{children:[T,o.jsx(we.TopCell,{"aria-hidden":!0,children:null})]})}),b.map((E,N)=>{const I=E.datasetId?v.get(E.datasetId)??ub(E.datasetId)??E.datasetId:"—",A=o.jsx(P2s,{experiment:E,datasetName:I,review:n?.get(E.id)});if(!l)return o.jsx(L2s,{experiment:E,rowProps:w(N),onSelect:c?()=>c(E):void 0,featured:u===E.id,onDelete:()=>_(E),children:A},E.id);const P=l.selectedExperimentIds.includes(E.id),L=()=>l.onToggleSelection(E.id);return o.jsxs(we.RowWrapper,{...w(N),onSelectRow:L,children:[o.jsx(we.SelectCell,{checked:P,onToggle:L,"aria-label":`Select experiment ${E.id}`}),o.jsx(we.RowButton,{colStart:2,featured:P,tabIndex:-1,onClick:frn,children:A})]},E.id)}),o.jsx(we.NextPageLoading,{isLoading:f,hasMore:h,setEndOfListElement:p}),k&&o.jsx(srn,{open:!0,onOpenChange:E=>{E||_(null)},experimentId:k.id,experimentName:k.name??void 0})]})}const z2s=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function B2s(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const kB={completed:wV.neutral3,running:"#facc15",pending:"#fb923c",failed:"#f87171"},U2s=[{label:"Completed",color:kB.completed},{label:"Running",color:kB.running},{label:"Pending",color:kB.pending},{label:"Failed",color:kB.failed}];function V2s({experiments:e,datasets:t,isLoading:n,isError:r}){const{data:s,maxVal:i}=g.useMemo(()=>{if(!e||e.length===0)return{data:[],maxVal:0};const l=new Map;if(t)for(const f of t)l.set(f.id,f.name);const c=new Map;for(const f of e){const h=f.datasetId??"unknown";c.has(h)||c.set(h,{completed:0,running:0,pending:0,failed:0});const p=c.get(h),m=f.status;m in p&&p[m]++}let u=0;return{data:Array.from(c.entries()).map(([f,h])=>{const p=h.completed+h.running+h.pending+h.failed;return p>u&&(u=p),{name:l.get(f)??f.slice(0,12),values:[h.completed,h.running,h.pending,h.failed]}}),maxVal:u}},[e,t]),a=s.length>0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Experiments by Dataset",description:"Experiment status breakdown per dataset."}),a&&o.jsx(Ht.Summary,{value:String(e?.length??0),label:"Total experiments"})]}),n?o.jsx(Ht.Loading,{}):r?o.jsx(Ht.Error,{message:"Failed to load experiments data"}):o.jsx(Ht.Content,{children:a?o.jsx(vA,{data:s,segments:U2s,maxVal:i,fmt:l=>String(l)}):o.jsx(Ht.NoData,{message:"No experiments have been run yet"})})]})}const q2s=({onRunExperiment:e})=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ar,{iconSlot:o.jsx(Ls,{}),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.jsx(ae,{variant:"primary",onClick:e,icon:o.jsx(bu,{}),children:"Run Experiment"}),o.jsx(ae,{variant:"ghost",render:o.jsx("a",{href:"https://mastra.ai/docs/evals/experiments",target:"_blank",rel:"noopener noreferrer"}),icon:o.jsx(_s,{}),children:"Experiments Documentation"})]})})});function H2s({search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:i,datasetOptions:a,targetType:l,onTargetTypeChange:c,targetId:u,onTargetIdChange:d,onReset:f,hasActiveFilters:h,onRunClick:p,runTooltip:m="Run an experiment",onCompareClick:v,selection:y}){const b=y?.selectedCount===2&&!y.compareDisabledReason;return o.jsxs("div",{className:"min-h-form-md flex flex-wrap items-center gap-2",children:[o.jsx("div",{className:"max-w-120 min-w-48 flex-1",children:o.jsx(Wc,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t})}),o.jsxs(Ms,{children:[o.jsx(of,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...z2s],value:n,onValueChange:r,className:"whitespace-nowrap"}),o.jsx(of,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:a,value:s,onValueChange:i,className:"whitespace-nowrap"}),o.jsx(eLe,{targetType:l,targetId:u,onTargetTypeChange:c,onTargetIdChange:d}),f&&h&&o.jsx(ae,{onClick:f,size:"sm",variant:"default",icon:o.jsx(Yt,{}),children:"Reset"})]}),y?o.jsxs(Ms,{className:"ml-auto shrink-0 whitespace-nowrap",children:[o.jsxs(Xh,{className:"gap-2",children:[o.jsxs(jt,{size:"sm",variant:y.selectedCount<2?"red":"green",children:[y.selectedCount," / 2"]}),"selected",y.compareDisabledReason&&o.jsxs("span",{className:"text-accent2",children:["· ",y.compareDisabledReason]})]}),o.jsx(ae,{variant:"primary",disabled:!b,onClick:y.onExecuteCompare,icon:o.jsx(rbe,{}),children:"Compare Experiments"}),o.jsx(ae,{icon:o.jsx(Yt,{}),onClick:y.onCancelSelection,children:"Cancel"})]}):o.jsxs(Ms,{className:"ml-auto shrink-0",children:[v&&o.jsx(ae,{onClick:v,tooltip:"Select two experiments of the same dataset to compare",icon:o.jsx(rbe,{}),children:"Compare"}),p&&o.jsx(ae,{onClick:p,tooltip:m,variant:"primary",icon:o.jsx(bu,{}),children:"Run Experiment"})]})]})}const W2s={present:!1,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},Bct=e=>e?e instanceof Date?e.toISOString():e:null,Uct=e=>{const t=new Map;for(const n of e??[])t.set(n.itemId,n);return t},Vct=(e,t,n)=>{if(!e)return W2s;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:Bct(t?.startedAt),completedAt:Bct(t?.completedAt),scores:Object.entries(e.scores).map(([s,i])=>({scorerId:s,value:i,reason:r.get(s)??null})).sort((s,i)=>s.scorerId.localeCompare(i.scorerId))}},Z2s=({comparison:e,baselineId:t,contenderId:n,baselineResults:r,contenderResults:s,baselineScores:i,contenderScores:a})=>{if(!e)return[];const l=Uct(r),c=Uct(s);return e.items.map(u=>{const d=Vct(u.results[t],l.get(u.itemId),i?.[u.itemId]),f=Vct(u.results[n],c.get(u.itemId),a?.[u.itemId]),h={};for(const p of new Set([...d.scores,...f.scores].map(m=>m.scorerId))){const m=d.scores.find(y=>y.scorerId===p)?.value??null,v=f.scores.find(y=>y.scorerId===p)?.value??null;h[p]=m!=null&&v!=null?v-m:null}return{itemId:u.itemId,input:u.input,groundTruth:u.groundTruth,baseline:d,contender:f,deltas:h}})};function IO({title:e,actions:t,tone:n="default",defaultOpen:r=!0,children:s}){return o.jsxs(dl,{defaultOpen:r,className:"grid gap-2",children:[o.jsxs("div",{className:"flex min-h-6 items-center justify-between gap-2",children:[o.jsxs(Zo,{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(mr,{}),e]}),t]}),o.jsx(Go,{role:"region","aria-label":e,children:s})]})}function qct({label:e,value:t}){return t==null?null:o.jsx(IO,{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 hrn({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-ui-md",t),children:[o.jsx("span",{className:"inline-block w-3",children:e>0?"+":e<0?"-":""}),Math.abs(e).toFixed(2),e>0?o.jsx(ISt,{className:"size-3.5"}):e<0?o.jsx(cNn,{className:"size-3.5"}):null]})}function prn({scorerId:e,value:t,delta:n,reason:r}){const{Link:s,paths:i}=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:i.scorerLink(e),"aria-label":`Open ${e}`,className:"text-neutral5 text-ui-md flex min-w-0 items-center gap-1.5 font-medium hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[o.jsx(dw,{}),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 text-ui-md font-mono",children:t!=null?t.toFixed(2):"-"}),n!=null&&o.jsx(hrn,{delta:n})]})]}),r&&o.jsx("p",{className:"text-neutral3 text-ui-md",children:r})]})}function Hct(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function G2s(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 Q2s="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 Wct({side:e,row:t,showDeltas:n,isLoading:r}){const s=t[e],i=G2s(s);if(r)return o.jsx("div",{className:"flex h-32 items-center justify-center",children:o.jsx(_n,{})});if(!s.present)return o.jsx("p",{className:"text-neutral3 text-ui-md py-5 text-center",children:"Not present in this experiment"});const a=Hct(s.output);return o.jsxs("div",{className:"grid content-start gap-5",children:[i&&o.jsxs(In,{children:[o.jsx(On,{render:o.jsxs("p",{className:"text-neutral3 text-ui-md flex items-center justify-end gap-1.5 [&>svg]:size-3.5",children:[o.jsx($C,{}),i]})}),o.jsx(Cn,{children:"Run duration"})]}),s.error?o.jsx(IO,{title:"Error",tone:"negative",actions:o.jsx(ci,{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(IO,{title:"Output",actions:o.jsx(ci,{content:a}),children:o.jsx("pre",{className:Q2s,children:a})}),s.scores.length>0&&o.jsx(IO,{title:"Scores",children:o.jsx("div",{className:"grid gap-2",children:s.scores.map(l=>o.jsx(prn,{scorerId:l.scorerId,value:l.value,delta:n?t.deltas[l.scorerId]:null,reason:l.reason},l.scorerId))})}),s.comment&&o.jsx(IO,{title:"Comment",defaultOpen:!1,children:o.jsx("p",{className:"text-neutral3 text-ui-md",children:s.comment})}),s.metadata&&Object.keys(s.metadata).length>0&&o.jsx(IO,{title:"Metadata",defaultOpen:!1,children:o.jsx("dl",{className:"grid gap-1",children:Object.entries(s.metadata).map(([l,c])=>o.jsxs("div",{className:"text-ui-md flex items-start justify-between gap-4",children:[o.jsx("dt",{className:"text-neutral3",children:l}),o.jsx("dd",{className:"text-neutral5 font-mono break-all",children:Hct(c)})]},l))})})]})}const K2s={baseline:"Baseline",contender:"Contender"},Y2s={baseline:"purple",contender:"blue"},X2s="flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0";function Zct({side:e,experiment:t,summary:n,showDeltas:r,versionMismatch:s}){const{Link:i,paths:a}=un(),l=K2s[e],c=t?ub(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(jt,{variant:Y2s[e],size:"xs",children:l}),t&&o.jsx(ae,{render:o.jsx(i,{href:`/experiments/${t.id}`}),size:"xs","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(Bd,{children:[o.jsx(TA,{})," ",c]}),t.targetType==="agent"&&t.targetId?o.jsxs(i,{href:a.agentLink(t.targetId),className:X2s,children:[o.jsx(Ma,{}),o.jsx("span",{className:"min-w-0 truncate",children:t.targetId})]}):o.jsxs(Bd,{children:[o.jsx(d1t,{})," ",t.targetId]}),o.jsx("span",{className:K(s&&"text-accent6"),children:o.jsxs(Bd,{children:[o.jsx(g4,{})," v",t.datasetVersion??"—",s&&" · different dataset version"]})}),u&&o.jsxs(Bd,{children:[o.jsx(mV,{})," ",gr(u,"MMM d, yyyy HH:mm")]})]}),d.length>0&&o.jsx(IO,{title:"Overall score",children:o.jsx("div",{className:"grid gap-2",children:d.map(({scorerId:f,average:h,delta:p})=>o.jsx(prn,{scorerId:f,value:h,delta:r?p:null},f))})})]})}const JT="min-w-0 px-4 py-3";function J2s({datasetId:e,experimentIdA:t,experimentIdB:n}){const{Link:r,paths:s}=un(),{data:i,isLoading:a,error:l}=qPs(e,t,n),{data:c}=X3(e,t),{data:u}=X3(e,n),d=c&&u&&c.datasetVersion!==u.datasetVersion,f=i?.baselineId??t,h=t===f?n:t,p=c?.id===f?c:u,m=c?.id===h?c:u,{data:v,isLoading:y}=Nke({datasetId:e,experimentId:f,experimentStatus:p?.status}),{data:b,isLoading:x}=Nke({datasetId:e,experimentId:h,experimentStatus:m?.status}),{data:w}=M1(f,p?.status),{data:k}=M1(h,m?.status),_=g.useMemo(()=>Z2s({comparison:i,baselineId:f,contenderId:h,baselineResults:v,contenderResults:b,baselineScores:w,contenderScores:k}),[i,f,h,v,b,w,k]),C=g.useMemo(()=>[...new Set(_.flatMap(E=>Object.keys(E.deltas)))].sort(),[_]),T=g.useMemo(()=>{const E=(A,P)=>{const L=_.map(M=>M[A].scores.find(V=>V.scorerId===P)?.value).filter(M=>M!=null);return L.length>0?L.reduce((M,V)=>M+V,0)/L.length:null},N=C.map(A=>({scorerId:A,average:E("baseline",A),delta:null})),I=C.map(A=>{const P=E("baseline",A),L=E("contender",A);return{scorerId:A,average:L,delta:P!=null&&L!=null?L-P:null}});return{baseline:N,contender:I}},[_,C]);return a?o.jsx("div",{className:"flex h-64 items-center justify-center",children:o.jsx(_n,{})}):l?o.jsx(xn,{variant:"warning",title:"Error loading comparison",children:o.jsx(xn.Message,{children:l instanceof Error?l.message:"Unknown error"})}):!i||i.items.length===0?o.jsx("div",{className:"text-neutral4 text-ui-md py-5 text-center",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:`${JT} text-neutral3 text-ui-sm uppercase`,children:"Items"}),o.jsx("div",{role:"columnheader","aria-label":"Baseline",className:JT,children:o.jsx(Zct,{side:"baseline",experiment:p??void 0,summary:T.baseline,versionMismatch:d??void 0})}),o.jsx("div",{role:"columnheader","aria-label":"Contender",className:JT,children:o.jsx(Zct,{side:"contender",experiment:m??void 0,summary:T.contender,versionMismatch:d??void 0,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:`${JT} 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(hrn,{delta:A},I))}),o.jsxs("div",{className:"grid pt-3",children:[o.jsx(qct,{label:"Input",value:E.input}),o.jsx(qct,{label:"Ground truth",value:E.groundTruth})]})]}),o.jsx("div",{role:"cell","aria-label":"Baseline",className:JT,children:o.jsx(Wct,{side:"baseline",row:E,isLoading:y})}),o.jsx("div",{role:"cell","aria-label":"Contender",className:JT,children:o.jsx(Wct,{side:"contender",row:E,isLoading:x,showDeltas:!0})})]},E.itemId)})]})})}function eDs({selectedCount:e,vocabulary:t,onApplyTag:n,onRemoveTag:r,onNewTag:s,size:i="sm"}){const[a,l]=g.useState(!1),[c,u]=g.useState(""),d=t.filter(h=>h.toLowerCase().includes(c.toLowerCase())),f=c.trim()&&!t.includes(c.trim());return o.jsxs(Zm,{open:a,onOpenChange:l,children:[o.jsx(Xf,{asChild:!0,children:o.jsxs(ae,{variant:"outline",size:i,icon:o.jsx(B_,{}),children:["Tag ",e," items"]})}),o.jsxs(vp,{className:"w-56 p-2",align:"end",children:[o.jsx($n,{value:c,onChange:h=>u(h.target.value),onKeyDown:h=>{h.key==="Enter"&&c.trim()&&(h.preventDefault(),f?s(c.trim()):n(c.trim()),u(""))},placeholder:"Search or create tag...",className:"text-ui-sm mb-1 h-7",autoFocus:!0}),o.jsxs("div",{className:"max-h-40 space-y-0.5 overflow-y-auto",children:[d.map(h=>o.jsxs("div",{className:"hover:bg-surface3 text-ui-sm flex items-center justify-between rounded px-2 py-1",children:[o.jsx("button",{type:"button",onClick:()=>n(h),className:"text-neutral4 flex-1 text-left",children:h}),o.jsx("button",{type:"button",onClick:()=>r(h),className:"text-neutral2 hover:text-negative1 ml-2",children:o.jsx(Yt,{className:"h-3 w-3"})})]},h)),f&&o.jsxs("button",{type:"button",onClick:()=>{s(c.trim()),u("")},className:"hover:bg-surface3 text-accent1 text-ui-sm w-full rounded px-2 py-1 text-left",children:['Create & apply "',c.trim(),'"']})]})]})]})}function tDs({tag:e,onRename:t,onRemove:n}){const[r,s]=g.useState(!1),[i,a]=g.useState(e),l=g.useRef(null);g.useEffect(()=>{r&&(l.current?.focus(),l.current?.select())},[r]);const c=()=>{const u=i.trim();u&&u!==e&&t(u),s(!1)};return r?o.jsxs("span",{className:"bg-surface3 border-border1 inline-flex items-center gap-0.5 rounded-md border px-1",children:[o.jsx("input",{ref:l,value:i,onChange:u=>a(u.target.value),onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),c()),u.key==="Escape"&&(a(e),s(!1))},onBlur:c,className:"text-neutral4 text-ui-sm w-20 bg-transparent py-0.5 outline-hidden"}),o.jsx("button",{type:"button",onMouseDown:u=>{u.preventDefault(),c()},className:"text-positive1 hover:text-positive2 p-0.5",children:o.jsx(Mn,{className:"h-3 w-3"})})]}):o.jsxs("span",{className:"bg-surface3 border-border1 text-neutral4 group text-ui-sm inline-flex items-center gap-0.5 rounded-md border px-1.5 py-0.5",children:[e,o.jsx("button",{type:"button",onClick:()=>{a(e),s(!0)},className:"text-neutral2 hover:text-neutral4 p-0.5 opacity-0 transition-opacity group-hover:opacity-100",title:"Edit tag",children:o.jsx(Gd,{className:"h-3 w-3"})}),o.jsx("button",{type:"button",onClick:n,className:"text-neutral2 hover:text-negative1 p-0.5 opacity-0 transition-opacity group-hover:opacity-100",title:"Remove tag",children:o.jsx(Yt,{className:"h-3 w-3"})})]})}const nDs=100;function iLe(e,t,{enabled:n=!0}={}){const r=Ye(),s={perPage:nDs};return t?.targetType&&(s.targetType=t.targetType),t?.targetId&&(s.targetId=t.targetId),yt({enabled:n,queryKey:["experiments",s],queryFn:()=>r.listExperiments(s)})}const mrn=(e,{experimentId:t,targetType:n,targetId:r,experiments:s,isLoadingExperiments:i=!1})=>{const a=Ye(),l=s!==void 0,{data:c,isLoading:u}=iLe(void 0,{targetType:n,targetId:r},{enabled:!l}),d=l?s:c?.experiments,f=l?i:u,h=t?d?.filter(m=>m.id===t):d,p=yt({queryKey:["review-items",e,t??"all",l?"supplied":"discovered",l?void 0:n||"all",l?void 0:r||"all",h?.map(m=>[m.datasetId,m.id])],queryFn:async()=>!h||h.length===0?[]:(await Promise.all(h.map(async v=>{if(!v.datasetId)return[];try{const{results:y}=await a.listDatasetExperimentResults(v.datasetId,v.id);return y.filter(b=>b.status===e).map(b=>({id:b.id,input:b.input,output:b.output,error:b.error,itemId:b.itemId,experimentId:b.experimentId,datasetId:v.datasetId??void 0,traceId:b.traceId??void 0,scores:b.scores?Object.fromEntries(b.scores.map(x=>[x.scorerId,x.score??0])):{},tags:b.tags??[],createdAt:b.createdAt,status:b.status,groundTruth:b.groundTruth,toolMockReport:b.toolMockReport}))}catch{return[]}}))).flat(),enabled:!!d,refetchOnWindowFocus:!1});return{...p,isLoading:p.isLoading||f}},rDs=(e={})=>mrn("needs-review",e),sDs=(e={})=>mrn("complete",e);function iDs(e){const{data:t}=zE(e),r=t?.spans.find(a=>!a.parentSpanId)?.entityType==="agent",{supportsMetrics:s}=rF(),i=_ke({traceIds:e?[e]:[],enabled:r&&s,autoRefetch:!1});return e?i.data?.get(e):void 0}const Gct="__create_tag__";function grn({selectedResults:e,vocabulary:t,onAddTag:n,disabled:r,appearance:s="toolbar"}){const[i,a]=g.useState(""),l=g.useMemo(()=>[...t].sort(),[t]),c=g.useMemo(()=>{if(e.length===0)return new Set;const[f,...h]=e;return new Set((f.tags??[]).filter(p=>h.every(m=>(m.tags??[]).includes(p))))},[e]),u=g.useMemo(()=>{const f=l.map(m=>({label:m,value:m,end:c.has(m)?o.jsx(Mn,{"data-testid":"tag-applied",className:"size-3.5"}):void 0})),h=i.trim();return h.length>0&&!l.includes(h)?[{label:`Create "${h}"`,value:Gct},...f]:f},[l,c,i]),d=f=>{const h=f===Gct?i.trim():f;!h||c.has(h)||n(h)};return o.jsx(qo,{"data-testid":"experiment-results-tag-picker",options:u,value:void 0,onValueChange:d,onInputValueChange:a,placeholder:o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(B_,{className:"size-3.5"}),"Add tag"]}),searchPlaceholder:"Search or create tag...",emptyText:"Type to create a tag",variant:s==="inline"?"ghost":"outline",size:s==="inline"?"xs":"md",className:"w-auto min-w-0",disabled:r})}function Fue(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function aDs({report:e}){const{served:t,unconsumed:n,liveCalls:r,failure:s}=e,i=[...t.map(a=>({outcome:"served",toolName:a.toolName,args:a.args})),...r.map(a=>({outcome:"live",toolName:a.toolName,args:a.args})),...n.map(a=>({outcome:"unconsumed",toolName:a.toolName,args:a.args}))];return o.jsxs("div",{className:"grid gap-2","data-testid":"tool-mock-report",children:[o.jsx($t.SectionHeading,{icon:o.jsx(xu,{}),children:"Tool Mocks"}),s&&o.jsx(xn,{variant:"destructive",title:"Mock mismatch",children:o.jsxs(xn.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:"text-ui-sm mt-1 block font-mono",children:["Called with: ",Fue(s.args)]}),n.length>0&&o.jsxs("span",{className:"text-ui-sm mt-1 block font-mono",children:["Unconsumed mocks: ",n.map(a=>Fue(a.args)).join(", ")]})]})}),o.jsx("div",{className:"border-border1 divide-border1 text-ui-md divide-y rounded border",children:i.map((a,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:a.toolName}),o.jsx("span",{className:"text-neutral3 text-ui-sm ml-2 font-mono",children:Fue(a.args)})]}),o.jsx("span",{className:`text-ui-sm shrink-0 rounded px-2 py-0.5 ${oDs(a.outcome)}`,children:a.outcome})]},`${a.outcome}-${a.toolName}-${l}`))})]})}function oDs(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 lDs({result:e,itemId:t,fallback:n,title:r,onClose:s,...i}){const a=r??(t?`Experiment item ${t}`:`Result ${e?.id??""}`);return o.jsx($t,{open:!!(e??t),onClose:s,title:a,depth:1,size:"half",children:e?o.jsx(cDs,{result:e,onClose:s,...i}):t?o.jsxs(o.Fragment,{children:[o.jsxs($t.Header,{children:[o.jsx($t.CloseButton,{onClick:s,tooltip:"Close result panel"}),o.jsxs($t.Heading,{children:["Experiment item",o.jsx($t.CopyId,{id:t})]})]}),n]}):null})}function cDs({result:e,scores:t,onPrevious:n,onNext:r,onClose:s,onShowTrace:i,onScoreClick:a,featuredScoreId:l,onFlagForReview:c,onTagsChange:u,tagVocabulary:d=[],isUpdatingTags:f=!1,experimentLink:h,onComplete:p,feedbackTabSlot:m}){const v=!!e?.error,y=OB(e?.input),b=OB(e?.output),x=OB(e?.groundTruth),w=c&&e.status!=="needs-review"&&e.status!=="complete",k=Array.isArray(e.tags)?e.tags:[],_=g.useMemo(()=>[e],[e]),C=!!u||k.length>0,{Link:T}=un(),E=m&&e.traceId?e.traceId:void 0,{data:N}=sF({traceId:E}),I=iDs(e.traceId),A=o.jsxs($t.Content,{children:[o.jsxs("div",{className:"mb-6 grid gap-4",children:[o.jsxs(fn,{children:[o.jsx(fn.Key,{children:"Item Id"}),o.jsx(fn.ValueWithCopyBtn,{copyTooltip:"Copy Item Id to clipboard",copyValue:e.itemId,children:e.itemId}),e.createdAt&&o.jsxs(o.Fragment,{children:[o.jsx(fn.Key,{children:"Created"}),o.jsx(fn.Value,{children:gr(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")})]}),e.status&&o.jsxs(o.Fragment,{children:[o.jsx(fn.Key,{children:"Status"}),o.jsx(fn.Value,{children:o.jsx(HDe,{status:e.status})})]}),C&&o.jsxs(o.Fragment,{children:[o.jsx(fn.Key,{children:"Tags"}),o.jsx(fn.Value,{children:o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[k.map(P=>o.jsxs(mJ,{value:P,className:u?"gap-1 pr-1":void 0,children:[P,u&&o.jsx("button",{type:"button","aria-label":`Remove tag ${P}`,disabled:f,onClick:()=>u(k.filter(L=>L!==P)),className:"cursor-pointer rounded-sm hover:opacity-70 disabled:opacity-50",children:o.jsx(Yt,{className:"size-3"})})]},P)),u&&o.jsx(grn,{appearance:"inline",selectedResults:_,vocabulary:d,onAddTag:P=>u([...k,P]),disabled:f})]})})]}),I&&o.jsxs(o.Fragment,{children:[o.jsx(fn.Key,{children:"Input tokens"}),o.jsx(fn.Value,{children:I.inputTokens!==void 0?lo(I.inputTokens):"—"}),o.jsx(fn.Key,{children:"Output tokens"}),o.jsx(fn.Value,{children:I.outputTokens!==void 0?lo(I.outputTokens):"—"}),o.jsx(fn.Key,{children:"Cost"}),o.jsx(fn.Value,{children:I.estimatedCost!==void 0?Zd(I.estimatedCost,I.costUnit):"—"})]})]}),v&&o.jsx(xn,{variant:"destructive",title:"Error",children:o.jsx(xn.Message,{children:OB(e?.error&&typeof e.error=="object"?e.error.message:e?.error)})}),t&&t.length>0&&o.jsxs(we,{columns:"1fr 1fr",children:[o.jsxs(we.Top,{children:[o.jsx(we.TopCell,{children:"Scorer"}),o.jsx(we.TopCell,{children:"Score"})]}),t.map(P=>a?o.jsxs(we.RowButton,{featured:l===P.id,onClick:()=>a(P.id),children:[o.jsx(we.Cell,{children:P.scorerId}),o.jsx(we.TextCell,{font:"mono",children:P.score.toFixed(3)})]},P.id):o.jsxs(we.RowStatic,{children:[o.jsx(we.Cell,{children:P.scorerId}),o.jsx(we.TextCell,{font:"mono",children:P.score.toFixed(3)})]},P.id))]}),e.toolMockReport&&o.jsx(aDs,{report:e.toolMockReport})]}),o.jsxs("div",{className:"grid gap-3",children:[o.jsx($t.CodeSection,{title:"Input",icon:o.jsx(kCe,{}),codeStr:y}),o.jsx($t.CodeSection,{title:"Output",icon:o.jsx(Gx,{}),codeStr:b}),e.groundTruth!==void 0&&o.jsx($t.CodeSection,{title:"Ground Truth",icon:o.jsx(d1t,{}),codeStr:x})]})]});return o.jsxs(o.Fragment,{children:[o.jsxs($t.Header,{children:[o.jsx($t.CloseButton,{onClick:s,tooltip:"Close result panel"}),o.jsxs($t.Heading,{children:["Result",o.jsx($t.CopyId,{id:e.id})]}),o.jsxs($t.HeaderActions,{children:[w&&o.jsx(ae,{size:"sm",variant:"primary",onClick:()=>c(e.id),icon:o.jsx(F_,{}),children:"Flag for Review"}),p&&e.status==="needs-review"&&o.jsx(ae,{size:"sm",variant:"primary",onClick:p,icon:o.jsx(rG,{}),children:"Mark as reviewed"}),h&&o.jsx(ae,{size:"sm",variant:"ghost",render:o.jsx(T,{href:h}),tooltip:"See experiment","aria-label":"See experiment",children:o.jsx(OCe,{})}),e.traceId&&i&&o.jsx(ae,{size:"sm",variant:"ghost",onClick:i,tooltip:"See trace","aria-label":"See trace",children:o.jsx(fE,{})}),o.jsx($t.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Go to previous result",nextLabel:"Go to next result"})]})]}),E?o.jsxs(hl,{defaultTab:"details",className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[o.jsx($t.Header,{children:o.jsxs(fl,{variant:"pill-ghost",size:"sm",children:[o.jsx(Sr,{value:"details",children:"Details"}),o.jsxs(Sr,{value:"feedback",children:["Feedback",N?.pagination?.total!=null&&o.jsxs(o.Fragment,{children:[" (",N.pagination.total,")"]})]})]})}),o.jsx(ts,{value:"details",flush:!0,children:A}),o.jsx(ts,{value:"feedback",flush:!0,children:o.jsx($t.Content,{children:m({traceId:E})})})]}):A]})}function OB(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function uDs(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function dDs({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s}){return o.jsx($t,{open:!!e,onClose:r,title:e?`Score ${e.scorerId}`:"Score",depth:2,children:e&&o.jsx(fDs,{score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s})})}function fDs({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s}){const i=uDs(e),a=i?"N/A — code-based scorer":"N/A — step not configured";return o.jsxs(o.Fragment,{children:[o.jsxs($t.Header,{children:[o.jsx($t.CloseButton,{onClick:r,tooltip:"Close score panel"}),o.jsxs($t.Heading,{children:["Score",o.jsx($t.CopyId,{id:e.scorerId})]}),o.jsxs($t.HeaderActions,{children:[s&&e.traceId&&o.jsx(ae,{size:"sm",variant:"ghost",onClick:s,tooltip:"See trace","aria-label":"See trace",children:o.jsx(fE,{})}),(n||t)&&o.jsx($t.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:"Go to previous score",nextLabel:"Go to next score"})]})]}),o.jsx($t.Content,{children:o.jsxs("div",{className:"grid gap-3",children:[o.jsx($t.CodeSection,{title:`Score: ${e.score}`,icon:o.jsx(gb,{}),codeStr:e.reason||a,simplified:!0}),!i&&o.jsxs(o.Fragment,{children:[o.jsx($t.CodeSection,{title:"Preprocess Prompt",icon:o.jsx(Kp,{}),codeStr:e.preprocessPrompt||a,simplified:!0}),o.jsx($t.CodeSection,{title:"Analyze Prompt",icon:o.jsx(Kp,{}),codeStr:e.analyzePrompt||a,simplified:!0}),o.jsx($t.CodeSection,{title:"Generate Score Prompt",icon:o.jsx(Kp,{}),codeStr:e.generateScorePrompt||a,simplified:!0}),o.jsx($t.CodeSection,{title:"Generate Reason Prompt",icon:o.jsx(Kp,{}),codeStr:e.generateReasonPrompt||a,simplified:!0})]})]})})]})}function vrn(e,t){const[n,r]=g.useState(null),[s,i]=g.useState(void 0),[a,l]=g.useState(null),[c,u]=g.useState(t);t!==c&&(u(t),r(null),i(void 0),l(null));const d=e?.find(f=>f.id===a)??null;return{featuredTraceId:n,setFeaturedTraceId:r,featuredSpanId:s,setFeaturedSpanId:i,featuredScoreId:a,setFeaturedScoreId:l,featuredScore:d}}function yrn({result:e,scores:t,state:n,...r}){const s=vrn(t,e?.id),{featuredTraceId:i,setFeaturedTraceId:a,featuredSpanId:l,setFeaturedSpanId:c,featuredScoreId:u,setFeaturedScoreId:d,featuredScore:f}=n??s,h=T=>{d(E=>T===E?null:T),a(null),c(void 0)},p=T=>{T&&(a(T),c(void 0),d(null))},m=()=>{if(!u||!t)return;const T=t.findIndex(E=>E.id===u);if(T>=0&&T<t.length-1)return()=>d(t[T+1].id)},v=()=>{if(!u||!t)return;const T=t.findIndex(E=>E.id===u);if(T>0)return()=>d(t[T-1].id)},{data:y,isLoading:b}=BMs(i),x=y?.spans,w=x?.find(T=>!T.parentSpanId),{data:k}=sF({traceId:i??void 0}),{data:_}=qDe({traceId:i??void 0,spanId:l}),{data:C}=UX({traceId:i??void 0,spanId:w?.spanId,page:0});return o.jsxs(o.Fragment,{children:[o.jsx(lDs,{...r,result:e,scores:t,onScoreClick:h,featuredScoreId:u,onShowTrace:e?.traceId?()=>p(e.traceId):void 0,feedbackTabSlot:({traceId:T})=>o.jsx(Y3,{traceId:T},T)}),o.jsx(dDs,{score:f??void 0,onNext:m(),onPrevious:v(),onClose:()=>d(null),onShowTrace:f?()=>p(f.traceId):void 0}),o.jsx(XDe,{size:"wide",depth:2,traceId:i??void 0,spans:x,isLoadingSpans:b,selectedSpanId:l??null,onClose:()=>{a(null),c(void 0)},onSpanSelect:c,showUnavailableFeaturesMsg:!1,traceHref:i?`/traces?traceId=${encodeURIComponent(i)}`:void 0,anchorSpanId:w?.spanId,feedbackTabBadge:k?.pagination?.total??void 0,feedbackTabSlot:({traceId:T})=>o.jsx(Y3,{traceId:T}),scoresTabBadge:C?.pagination?.total??void 0,scoresTabSlot:({traceId:T,rootSpanId:E})=>E?o.jsx(GDe,{traceId:T,spanId:E,onScoreSelect:N=>{t?.some(I=>I.id===N)&&(a(null),c(void 0),d(N))}}):null,spanFeedbackTabBadge:_?.pagination?.total??void 0,spanFeedbackTabSlot:({traceId:T,spanId:E})=>T&&E?o.jsx(ZDe,{traceId:T,spanId:E},`${T}:${E}`):null})]})}const hDs=[{name:"itemId",label:"Item ID",size:"auto"},{name:"input",label:"Input",size:"minmax(0,1fr)"},{name:"tags",label:"Tags",size:"auto"},{name:"scores",label:"Scores",size:"6rem"}],zue="__untagged__",Bue="all",pDs=[{value:"review",label:"Review queue"},{value:"completed",label:"Completed"}];function mDs({datasetId:e,experimentId:t,experiments:n,isLoadingExperiments:r,targetType:s,targetId:i,featuredItemId:a,toolbarStart:l,toolbarEnd:c,onCreateScorer:u}){const d=Ye(),{paths:f}=un(),{data:h}=bv(e??""),{data:p,isLoading:m}=rDs({experimentId:t,targetType:s,targetId:i,experiments:n,isLoadingExperiments:r}),{data:v,isLoading:y}=sDs({experimentId:t,targetType:s,targetId:i,experiments:n,isLoadingExperiments:r}),{updateExperimentResult:b}=pl(),[x,w]=g.useState(a??null);g.useEffect(()=>{a!==void 0&&w(a)},[a]);const[k,_]=g.useState(null),[C,T]=g.useState(new Set),[E,N]=g.useState(!1),[I,A]=g.useState(!1),[P,L]=g.useState(!1),[M,V]=g.useState(""),[q,H]=g.useState(""),[B,W]=g.useState(""),[z,G]=g.useState([]),[F,R]=g.useState(!1),D=g.useMemo(()=>p??[],[p]),U=g.useMemo(()=>{const Ce=new Set;if(h?.tags)for(const Ne of h.tags)Ce.add(Ne);for(const Ne of D)for(const $e of Ne.tags)Ce.add($e);return[...Ce].sort()},[h,D]),Q=g.useCallback(Ce=>{!h||!e||(h.tags??[]).includes(Ce)},[h,e]),ee=g.useMemo(()=>k?k===zue?D.filter(Ce=>Ce.tags.length===0):D.filter(Ce=>Ce.tags.includes(k)):D,[D,k]),J=g.useMemo(()=>{const Ce=new Map;let Ne=0;for(const De of D){De.tags.length===0&&Ne++;for(const tt of De.tags)Ce.set(tt,(Ce.get(tt)??0)+1)}const $e=[...Ce.entries()].sort((De,tt)=>tt[1]-De[1]).map(([De])=>({value:De,label:De}));return[{value:Bue,label:"All tags"},...Ne>0?[{value:zue,label:"Untagged"}]:[],...$e]},[D]),te=!!k||E,re=g.useCallback(()=>{_(null),N(!1),w(null)},[]),ce=g.useCallback((Ce,Ne)=>{const $e=D.find(De=>De.id===Ce);$e?.experimentId&&$e?.datasetId&&b.mutate({datasetId:$e.datasetId,experimentId:$e.experimentId,resultId:$e.id,tags:Ne})},[D,b]),X=g.useCallback(Ce=>{const Ne=D.find($e=>$e.id===Ce);T($e=>{const De=new Set($e);return De.delete(Ce),De}),x===Ce&&w(null),Ne?.experimentId&&Ne?.datasetId&&b.mutate({datasetId:Ne.datasetId,experimentId:Ne.experimentId,resultId:Ne.id,status:null})},[D,b,x]),ne=g.useCallback(Ce=>{const Ne=D.find($e=>$e.id===Ce);T($e=>{const De=new Set($e);return De.delete(Ce),De}),x===Ce&&w(null),Ne?.experimentId&&Ne?.datasetId&&b.mutate({datasetId:Ne.datasetId,experimentId:Ne.experimentId,resultId:Ne.id,status:"complete"})},[D,b,x]),se=g.useMemo(()=>{const Ce=E?v??[]:ee;return!E||!k?Ce:k===zue?Ce.filter(Ne=>Ne.tags.length===0):Ce.filter(Ne=>Ne.tags.includes(k))},[E,v,ee,k]),le=E?y:!1,he=g.useMemo(()=>new Set(se.map(Ce=>Ce.id)),[se]),pe=g.useMemo(()=>[...C].filter(Ce=>he.has(Ce)).length,[C,he]),Se=se.length>0&&pe===se.length,Ee=g.useCallback(Ce=>{T(Ne=>{const $e=new Set(Ne);return $e.has(Ce)?$e.delete(Ce):$e.add(Ce),$e})},[]),Re=g.useCallback(()=>{T(Se?new Set:new Set(se.map(Ce=>Ce.id)))},[Se,se]),We=g.useCallback(Ce=>{for(const Ne of C){const $e=D.find(De=>De.id===Ne);$e&&!$e.tags.includes(Ce)&&ce(Ne,[...$e.tags,Ce])}},[D,C,ce]),Ue=g.useCallback(Ce=>{for(const Ne of C){const $e=D.find(De=>De.id===Ne);$e&&$e.tags.includes(Ce)&&ce(Ne,$e.tags.filter(De=>De!==Ce))}},[D,C,ce]),Fe=g.useCallback(()=>{for(const Ce of C)ne(Ce);T(new Set)},[C,ne]),me=g.useCallback(()=>{for(const Ce of C)X(Ce);T(new Set)},[C,X]),je=g.useCallback(()=>{V(""),L(!0)},[]),fe=g.useCallback(async()=>{if(!(!q||!B)){A(!0),L(!1);try{const Ce=D.filter($e=>C.has($e.id));if(Ce.length===0){A(!1);return}const Ne=await d.clusterFailures({modelId:`${q}/${B}`,items:Ce.map($e=>({id:$e.id,input:$e.input,output:$e.output??void 0,error:typeof $e.error=="string"?$e.error:$e.error?String($e.error):void 0,scores:$e.scores,existingTags:$e.tags.length>0?$e.tags:void 0})),availableTags:U.length>0?U:void 0,prompt:M||void 0});Ne.proposedTags&&Ne.proposedTags.length>0&&(G(Ne.proposedTags.map($e=>({...$e,accepted:!0}))),R(!0))}catch(Ce){console.error("Analysis failed:",Ce)}finally{A(!1)}}},[q,B,D,C,d,U,M]),ve=g.useCallback(()=>{for(const Ce of z){if(!Ce.accepted)continue;const Ne=D.find($e=>$e.id===Ce.itemId);if(Ne){const $e=[...new Set([...Ne.tags,...Ce.tags])];ce(Ne.id,$e)}}R(!1)},[z,D,ce]),_e=g.useCallback(Ce=>{w(Ne=>Ne===Ce?null:Ce)},[]),ge=g.useMemo(()=>x?se.find(Ce=>Ce.id===x)??null:null,[x,se]),{data:Ie}=M1(ge?.experimentId??""),Ze=x?se.findIndex(Ce=>Ce.id===x):-1,qe=Ze>0?()=>w(se[Ze-1].id):void 0,de=Ze>=0&&Ze<se.length-1?()=>w(se[Ze+1].id):void 0,be=!E&&C.size>0,ke=!!u&&!E&&ee.length>0,ze=o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs(Ms,{children:[l,o.jsx(of,{label:"Status",labelIsHidden:!0,name:"filter-status",options:pDs,value:E?"completed":"review",onValueChange:Ce=>{N(Ce==="completed"),w(null)},className:"whitespace-nowrap"}),J.length>1&&o.jsx(of,{label:"Tags",labelIsHidden:!0,name:"filter-tags",options:J,value:k??Bue,onValueChange:Ce=>_(Ce===Bue?null:Ce),className:"whitespace-nowrap"}),te&&o.jsx(ae,{onClick:re,size:"sm",variant:"default",icon:o.jsx(Yt,{}),children:"Reset"})]}),(be||c||ke)&&o.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-2",children:[c,ke&&o.jsxs(ae,{variant:"outline",size:"md",onClick:()=>u?.(ee.map(Ce=>({input:Ce.input,output:Ce.output}))),children:[o.jsx(St,{size:"sm",children:o.jsx(gb,{})}),"Create Scorer"]}),be&&o.jsxs(o.Fragment,{children:[o.jsx(eDs,{size:"md",selectedCount:C.size,vocabulary:U,onApplyTag:We,onRemoveTag:Ue,onNewTag:Ce=>We(Ce)}),o.jsx(ae,{variant:"primary",onClick:Fe,icon:o.jsx(rG,{}),children:"Mark as reviewed"}),o.jsxs(xt,{children:[o.jsx(xt.Trigger,{asChild:!0,children:o.jsx(ae,{variant:"outline",disabled:I,"aria-label":"More actions",children:I?o.jsx(_n,{className:"h-4 w-4"}):o.jsx(BD,{})})}),o.jsxs(xt.Content,{align:"end",children:[o.jsxs(xt.Item,{onSelect:je,children:[o.jsx(St,{size:"sm",children:o.jsx(y4,{})}),"Analyze"]}),o.jsx(xt.Separator,{}),o.jsxs(xt.Item,{onSelect:me,children:[o.jsx(St,{size:"sm",children:o.jsx(co,{})}),"Remove from queue"]})]})]})]})]})]});if(m)return o.jsxs(o.Fragment,{children:[o.jsx(Ft.TopArea,{children:ze}),o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsx(_n,{className:"h-6 w-6"})})]});const He=o.jsx(yrn,{result:ge??void 0,title:`Review item ${ge?.id??""}`,scores:ge?Ie?.[ge.itemId]:void 0,experimentLink:ge?.experimentId?f.experimentItemLink(ge.experimentId,ge.itemId):void 0,tagVocabulary:U,onTagsChange:E||!ge?void 0:Ce=>{ce(ge.id,Ce);for(const Ne of Ce)U.includes(Ne)||Q(Ne)},onComplete:E||!ge?void 0:()=>ne(ge.id),onPrevious:qe,onNext:de,onClose:()=>w(null)});return o.jsxs(o.Fragment,{children:[o.jsx(Ft.TopArea,{children:ze}),o.jsx(hs,{open:P,onOpenChange:L,children:o.jsxs(Jr,{children:[o.jsxs(es,{children:[o.jsx(Kr,{children:"Analyze Items"}),o.jsx(Ps,{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(Vt,{className:"text-ui-sm mb-1 block",children:"Provider"}),o.jsx(ak,{value:q,onValueChange:H})]}),o.jsxs("div",{children:[o.jsx(Vt,{className:"text-ui-sm mb-1 block",children:"Model"}),o.jsx(ok,{llmId:q,value:B,onValueChange:W})]})]}),o.jsxs(Te,{variant:"ui-xs",className:"text-neutral3",children:[C.size," item",C.size!==1?"s":""," will be analyzed"]}),o.jsxs("div",{children:[o.jsx(Vt,{className:"text-ui-sm",children:"Instructions (optional)"}),o.jsx(Yd,{value:M,onChange:Ce=>V(Ce.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3,className:"text-ui-sm mt-1"})]})]}),o.jsxs(lc,{children:[o.jsx(ae,{icon:o.jsx(Yt,{}),variant:"outline",onClick:()=>L(!1),children:"Cancel"}),o.jsxs(ae,{onClick:fe,disabled:!q||!B||I,children:[I?o.jsx(_n,{className:"mr-1 h-4 w-4"}):null,"Analyze"]})]})]})}),o.jsx(hs,{open:F,onOpenChange:R,children:o.jsxs(Jr,{className:"max-h-[80vh] max-w-2xl overflow-y-auto",children:[o.jsxs(es,{children:[o.jsx(Kr,{children:"Review Proposed Tags"}),o.jsxs(Ps,{children:[z.filter(Ce=>Ce.accepted).length," of ",z.length," proposals selected"]})]}),o.jsx("div",{className:"space-y-3 py-2",children:z.map((Ce,Ne)=>{const $e=D.find(De=>De.id===Ce.itemId);return o.jsx("div",{className:K("p-3 border rounded-lg",!Ce.accepted&&"opacity-50"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(od,{checked:Ce.accepted,onCheckedChange:De=>G(tt=>tt.map((Et,Ae)=>Ae===Ne?{...Et,accepted:!!De}:Et))}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(Te,{variant:"ui-xs",className:"text-neutral4 block truncate",children:$e?typeof $e.input=="string"?$e.input.slice(0,100):JSON.stringify($e.input).slice(0,100):Ce.itemId}),o.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:Ce.tags.map((De,tt)=>o.jsx(tDs,{tag:De,onRename:Et=>G(Ae=>Ae.map((Xe,dt)=>dt===Ne?{...Xe,tags:Xe.tags.map((zt,qt)=>qt===tt?Et:zt)}:Xe)),onRemove:()=>G(Et=>Et.map((Ae,Xe)=>Xe===Ne?{...Ae,tags:Ae.tags.filter((dt,zt)=>zt!==tt)}:Ae))},`${De}-${tt}`))}),Ce.reason&&o.jsx(Te,{variant:"ui-xs",className:"text-neutral3 mt-1 block italic",children:Ce.reason})]})]})},Ce.itemId)})}),o.jsxs(lc,{children:[o.jsx(ae,{icon:o.jsx(Yt,{}),variant:"outline",onClick:()=>R(!1),children:"Cancel"}),o.jsxs(ae,{icon:o.jsx(Mn,{}),onClick:ve,disabled:z.filter(Ce=>Ce.accepted).length===0,children:["Accept ",z.filter(Ce=>Ce.accepted).length," proposals"]})]})]})}),o.jsxs(Ft.MainArea,{className:"grid h-full min-h-0 w-full grid-cols-1 gap-4 overflow-hidden",children:[o.jsx("div",{className:"min-h-0 w-full overflow-hidden",children:le?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(_n,{className:"h-6 w-6"})}):se.length===0?o.jsx("div",{className:"flex h-full items-center-safe justify-center-safe overflow-auto py-8",children:o.jsx(Ar,{iconSlot:o.jsx(Ls,{className:"text-neutral3 h-8 w-8"}),titleSlot:E?"No completed reviews yet":"No items to review",descriptionSlot:E?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here."})}):o.jsx(nLe,{results:se,isLoading:!1,featuredResultId:x,onResultClick:_e,columns:hDs,selectedIds:E?void 0:C,onToggleSelect:E?void 0:Ee,onToggleSelectAll:E?void 0:Re})}),He]})]})}const Qct={needsReview:"#facc15",complete:"#22c55e"},gDs=[{label:"Needs Review",color:Qct.needsReview},{label:"Reviewed",color:Qct.complete}];function vDs({reviewSummary:e,experiments:t,datasets:n,isLoading:r,isError:s}){const{data:i,maxVal:a,totalInPipeline:l}=g.useMemo(()=>{if(!e?.counts||!t)return{data:[],maxVal:0,totalInPipeline:0};const u=new Map;for(const m of t)u.set(m.id,m);const d=new Map;if(n)for(const m of n)d.set(m.id,m.name);let f=0,h=0;const p=[];for(const m of e.counts){const v=m.needsReview+m.complete;if(v===0)continue;h+=v,v>f&&(f=v);const y=u.get(m.experimentId),b=y?.datasetId?d.get(y.datasetId):void 0,x=b?`${b} · ${m.experimentId.slice(0,8)}`:m.experimentId.slice(0,8);p.push({name:x,values:[m.needsReview,m.complete]})}return{data:p,maxVal:f,totalInPipeline:h}},[e,t,n]),c=i.length>0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Review Pipeline",description:"Items in review across experiments."}),c&&o.jsx(Ht.Summary,{value:String(l),label:"Items in pipeline"})]}),r?o.jsx(Ht.Loading,{}):s?o.jsx(Ht.Error,{message:"Failed to load review data"}):o.jsx(Ht.Content,{children:c?o.jsx(vA,{data:i,segments:gDs,maxVal:a,fmt:u=>String(u)}):o.jsx(Ht.NoData,{message:"No items have been sent to review yet"})})]})}function brn(){const e=Ye();return yt({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function yDs(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 bDs(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 xDs(){const[e,t]=g.useState("all"),[n,r]=g.useState({}),{data:s,isLoading:i,error:a}=Ep(),{data:l,isLoading:c,error:u}=q0(),{data:d,isLoading:f,error:h}=KG(),{data:p,isLoading:m,isError:v,error:y}=$ks(n),{data:b,isLoading:x,isError:w,error:k}=brn(),_=l?.datasets,C=d?.experiments,T=g.useMemo(()=>bDs(b),[b]),E=a||u||h||y||k;return E&&ks(E)?o.jsx(Qn,{children:o.jsx(Gs,{})}):E&&Es(E)?o.jsx(Qn,{children:o.jsx(Fs,{resource:"evaluation"})}):E?o.jsx(Qn,{children:o.jsx(Ws,{title:"Failed to load evaluation data",message:E.message})}):o.jsxs(Ft,{width:"wide",height:"full",children:[o.jsx(Ft.TopArea,{children:o.jsx(Ft.Row,{children:o.jsx(Ft.Column,{children:o.jsx(n6,{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-4",children:[o.jsx(Pke,{children:o.jsx(S2s,{scorers:s,datasets:_,experiments:C,avgScore:p?.avgScore??null,prevAvgScore:p?.prevAvgScore??null,totalNeedsReview:T.needsReview,isLoadingScorers:i,isLoadingDatasets:c,isLoadingExperiments:f,isLoadingScores:m,isLoadingReview:x})}),o.jsx(c1s,{summaryData:p?.summaryData??[],overTimeData:p?.overTimeData??[],scorerNames:p?.scorerNames??[],avgScore:p?.avgScore??null,isLoading:m,isError:v}),o.jsxs("div",{className:"grid grid-cols-1 gap-4 lg:grid-cols-2",children:[o.jsx(p$s,{experiments:C,isLoading:f,isError:!!h}),o.jsx(V2s,{experiments:C,datasets:_,isLoading:f,isError:!!h})]}),o.jsx(vDs,{reviewSummary:b,experiments:C,datasets:_,isLoading:x,isError:!!w})]})]})}const wDs=100;function SDs(e,t){const n=Ye(),{inView:r,setRef:s}=Sb(),i=t?.targetType||void 0,a=t?.targetId||void 0,l=yv({queryKey:e?["dataset-experiments",e,"infinite",{targetType:i,targetId:a}]:["experiments","infinite",{targetType:i,targetId:a}],queryFn:({pageParam:c})=>{const u={page:c,perPage:wDs};return i&&(u.targetType=i),a&&(u.targetId=a),e?n.listDatasetExperiments(e,u):n.listExperiments(u)},initialPageParam:0,getNextPageParam:(c,u,d)=>{if(!(!c?.experiments?.length||!c.pagination?.hasMore))return d+1},select:c=>c.pages.flatMap(u=>u?.experiments??[])});return g.useEffect(()=>{r&&l.hasNextPage&&!l.isFetchingNextPage&&l.fetchNextPage()},[r,l]),{...l,setEndOfListElement:s}}function kDs(){const[e,t]=g.useState(""),[n,r]=g.useState("all"),[s,i]=g.useState(!1),[a,l]=g.useState(!1),[c,u]=g.useState([]),d=Fr(),[f,h]=bi(),p=f.get("dataset")??"all",m=g.useCallback(J=>{h(te=>{const re=new URLSearchParams(te);return J==="all"?re.delete("dataset"):re.set("dataset",J),re},{replace:!0})},[h]),{targetType:v,targetId:y,setTargetType:b,setTargetId:x}=sLe(),{data:w,isLoading:k,error:_}=q0(),{data:C,isLoading:T,error:E,isFetchingNextPage:N,hasNextPage:I,setEndOfListElement:A}=SDs(p==="all"?void 0:p,{targetType:v,targetId:y}),{data:P}=brn(),L=g.useMemo(()=>w?.datasets??[],[w?.datasets]),M=g.useMemo(()=>C??[],[C]),V=g.useMemo(()=>B2s(L),[L]),q=g.useMemo(()=>yDs(P),[P]),H=k||T,B=E||_,W=J=>{u(te=>te.includes(J)?te.filter(re=>re!==J):te.length>=2?[te[0],J]:[...te,J])},z=()=>{u([]),l(!1)},{selectedIds:G,selectedDatasetIds:F}=g.useMemo(()=>{const J=new Map(M.map(re=>[re.id,re.datasetId])),te=c.filter(re=>J.has(re));return{selectedIds:te,selectedDatasetIds:new Set(te.map(re=>J.get(re)))}},[M,c]),R=G.length===2&&F.size!==1?"not the same dataset":void 0,D=()=>{if(G.length!==2||R)return;const[J,te]=G,[re]=F;if(!re)return;const ce=new URLSearchParams({dataset:re,baseline:J,contender:te});d(`/experiments/compare?${ce.toString()}`)};if(B&&ks(B))return o.jsx(Qn,{children:o.jsx(Gs,{})});if(E&&Es(E))return o.jsx(Qn,{children:o.jsx(Fs,{resource:"experiments"})});if(_&&Es(_))return o.jsx(Qn,{children:o.jsx(Fs,{resource:"datasets"})});if(B)return o.jsx(Qn,{children:o.jsx(Ws,{title:"Failed to load experiments",message:B.message})});const U=o.jsx(yJ,{open:s,onOpenChange:i,onSuccess:J=>{d(`/experiments/${J}`)}});if(M.length===0&&!H&&p==="all"&&!v)return o.jsxs(Qn,{children:[o.jsx(q2s,{onRunExperiment:()=>i(!0)}),U]});const Q=n!=="all"||p!=="all"||e!==""||v!=="",ee=()=>{t(""),r("all"),h(J=>{const te=new URLSearchParams(J);return te.delete("dataset"),te.delete(pU),te.delete(o2),te},{replace:!0})};return o.jsxs(Ft,{height:"full",children:[o.jsx(Ft.TopArea,{children:o.jsx(H2s,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:p,onDatasetFilterChange:m,datasetOptions:V,targetType:v,onTargetTypeChange:b,targetId:y,onTargetIdChange:x,onReset:ee,hasActiveFilters:Q,onRunClick:()=>i(!0),onCompareClick:()=>l(!0),selection:a?{selectedCount:G.length,onExecuteCompare:D,onCancelSelection:z,compareDisabledReason:R}:void 0})}),o.jsx(F2s,{experiments:M,datasets:L,reviewByExperiment:q,isLoading:H,search:e,statusFilter:n,datasetFilter:p,isFetchingNextPage:N,hasNextPage:I,setEndOfListElement:A,selection:a?{selectedExperimentIds:G,onToggleSelection:W}:void 0}),U]})}function CB({experimentId:e}){const{Link:t,paths:n}=un();return o.jsx(ae,{render:o.jsx(t,{href:n.experimentLink(e)}),size:"sm","aria-label":`Open experiment ${e}`,children:e.slice(0,8)})}function ODs(){const[e,t]=bi(),n=e.get("dataset")??"",r=e.get("baseline")??"",s=e.get("contender")??"",i=X3(n,r),a=X3(n,s),l=i.isLoading||a.isLoading,c=i.error??a.error;return c&&ks(c)?o.jsx(oi,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Gs,{})})}):c&&Es(c)?o.jsx(oi,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{resource:"experiments"})})}):!n||!r||!s?o.jsx(oi,{children:o.jsx(i0,{children:o.jsxs("div",{className:"text-neutral4 py-5 text-center",children:[o.jsx("p",{children:"Select two experiments to compare."}),o.jsxs("p",{className:"text-ui-md mt-2",children:["Use the URL format: /experiments/compare?dataset=","{datasetId}","&baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})}):l?null:c&&!CR(c)?o.jsx(oi,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ws,{title:"Failed to load experiments",message:c.message})})}):c||!i.data||!a.data?o.jsx(oi,{children:o.jsx(i0,{children:o.jsxs("div",{className:"text-neutral4 py-5 text-center",children:[o.jsxs("p",{children:["Experiments must belong to the same dataset (",n,") to be compared."]}),o.jsxs("p",{className:"text-ui-md mt-2 flex items-center justify-center gap-2",children:["One of",o.jsx(CB,{experimentId:r}),"and",o.jsx(CB,{experimentId:s}),"was not found in it."]})]})})}):o.jsx(oi,{children:o.jsx(i0,{children:o.jsxs("div",{className:"grid w-full content-start",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4 px-4 py-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[o.jsx(Te,{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(CB,{experimentId:r}),"and",o.jsx(CB,{experimentId:s})]})]}),o.jsxs(In,{children:[o.jsx(On,{asChild:!0,children:o.jsx(ae,{onClick:()=>t({dataset:n,baseline:s,contender:r}),icon:o.jsx(NSt,{}),children:"Swap sides"})}),o.jsx(Cn,{children:"Switch baseline and contender"})]})]}),o.jsx(J2s,{datasetId:n,experimentIdA:r,experimentIdB:s})]})})})}function xrn(e,t){const{data:n}=bv(e);return g.useMemo(()=>[...new Set([...n?.tags??[],...t.flatMap(r=>r.tags??[])])].sort(),[n?.tags,t])}function CDs(){const{currentItemId:e,experimentId:t,datasetId:n,experimentStatus:r,results:s,isLoadingResults:i,hasNextPage:a,close:l,goToPreviousItem:c,goToNextItem:u}=trn(),d=g.useMemo(()=>e?s.find(w=>w.itemId===e):void 0,[s,e]),{data:f}=M1(t,r),{updateExperimentResult:h}=pl(),p=g.useCallback(async w=>{try{await h.mutateAsync({datasetId:n,experimentId:t,resultId:w,status:"needs-review"}),Ge("Result flagged for review")}catch{Ge.error("Failed to flag result for review")}},[n,t,h]),m=xrn(n,s),v=g.useCallback(async(w,k)=>{try{await h.mutateAsync({datasetId:n,experimentId:t,resultId:w,tags:k})}catch{Ge.error("Failed to update tags")}},[n,t,h]),y=g.useCallback(async w=>{try{await h.mutateAsync({datasetId:n,experimentId:t,resultId:w,status:"complete"}),Ge("Result marked as reviewed")}catch{Ge.error("Failed to complete result")}},[n,t,h]),b=d?f?.[d.itemId]:void 0,x=vrn(b,d?.id);return o.jsx(yrn,{result:d,itemId:e,fallback:i||a?o.jsx($t.LoadingData,{}):o.jsxs($t.NoData,{children:['No loaded result for item "',e,'".']}),scores:b,state:x,onPrevious:c,onNext:u,onClose:l,onComplete:d?()=>y(d.id):void 0,onFlagForReview:d?()=>{p(d.id)}:void 0,onTagsChange:d?w=>{v(d.id,w)}:void 0,tagVocabulary:m,isUpdatingTags:h.isPending})}function _Ds({selection:e}){const{selectedIds:t,selectedResults:n,tagVocabulary:r,isFlagging:s,isTagging:i}=e;if(t.size===0)return null;const a=s||i;return o.jsxs(Ms,{className:"whitespace-nowrap",children:[o.jsxs(ae,{variant:"outline",disabled:a,onClick:e.flagSelectedForReview,icon:o.jsx(F_,{}),children:["Flag ",t.size," to review"]}),o.jsx(grn,{selectedResults:n,vocabulary:r,onAddTag:e.addTagToSelected,disabled:a}),o.jsx(ae,{icon:o.jsx(Yt,{}),variant:"ghost",onClick:e.clearSelection,children:"Clear"})]})}function wrn(e){const{data:t}=M1(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 Uue({icon:e,typeLabel:t,subject:n,description:r,isLast:s=!1}){return o.jsxs("li",{className:"relative grid grid-cols-[auto_1fr] gap-x-2.5 pb-4 last:pb-0",children:[o.jsxs("div",{className:"flex flex-col items-center",children:[o.jsxs(In,{children:[o.jsx(On,{render:o.jsx("span",{className:"text-neutral3 flex size-5 shrink-0 items-center justify-center [&_svg]:size-3.5",role:"img","aria-label":t}),children:e}),o.jsx(Cn,{children:t})]}),!s&&o.jsx("span",{"aria-hidden":!0,className:"bg-border1 mt-1 w-px flex-1"})]}),o.jsxs("div",{className:"grid min-w-0 gap-0.5",children:[o.jsx("div",{className:"text-ui-sm text-neutral5 flex min-h-5 items-center",children:n}),o.jsx("p",{className:"text-ui-xs text-neutral2",children:r})]})]})}const Vue="text-neutral5 inline-flex min-w-0 items-center gap-1.5 hover:underline";function EDs({experiment:e,className:t}){const{Link:n,paths:r}=un(),s=arn(),{scorers:i}=s,{data:a,isLoading:l}=bv(e.datasetId??""),c=wrn(e),u=e.targetType,d=e.targetId,f=urn(e,s),h=(()=>{if(!d)return null;switch(u){case"agent":return r.agentLink(d);case"workflow":return r.workflowLink(d);case"scorer":return r.scorerLink(d);default:return null}})(),p=u&&lrn[u]||Ma,m=u&&crn[u]||"Evaluation target";return o.jsxs("ol",{className:K("grid",t),children:[o.jsx(Uue,{icon:o.jsx(gJ,{}),typeLabel:"Dataset",description:`Each item will be passed to the ${m.toLowerCase()}`,subject:e.datasetId?o.jsxs(n,{href:r.datasetLink(e.datasetId),className:Vue,children:[o.jsx("span",{className:"truncate",children:l?o.jsx(ut,{className:"h-4 w-28"}):a?.name??e.datasetId}),e.datasetVersion!=null&&o.jsxs("span",{className:"text-neutral3 shrink-0",children:["(v",e.datasetVersion,")"]})]}):o.jsx("span",{className:"text-neutral3",children:"No dataset"})}),o.jsx(Uue,{icon:o.jsx(p,{}),typeLabel:m,description:"Its output is then scored",subject:h?o.jsx(n,{href:h,className:Vue,children:o.jsx("span",{className:"truncate",children:f})}):o.jsx("span",{className:"text-neutral3 truncate",children:f})}),o.jsx(Uue,{icon:o.jsx(dw,{}),typeLabel:"Scorers",description:"It gives a score by comparing ground truth",isLast:!0,subject:c.length===0?o.jsx("span",{className:"text-neutral3",children:"No scorer has produced a score yet"}):o.jsx("ul",{className:"grid min-w-0 gap-0.5",children:c.map(v=>{const y=i?.[v]?.scorer?.config?.name??v;return o.jsx("li",{className:"min-w-0",children:o.jsx(n,{href:r.scorerLink(v),className:Vue,children:o.jsx("span",{className:"truncate",children:y})})},v)})})})]})}function ej({label:e,children:t}){return o.jsxs(o.Fragment,{children:[o.jsx(fn.Key,{children:e}),o.jsx(fn.Value,{className:"flex flex-wrap items-baseline justify-end gap-x-1.5 text-right",children:t})]})}function Kct(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 TDs({experiment:e,metrics:t}){const{data:n}=M1(e.id,e.status),r=e.status==="running"||e.status==="pending",s=g.useMemo(()=>{if(!n)return;const c=Object.values(n).flat();if(c.length!==0)return c.reduce((u,d)=>u+d.score,0)/c.length},[n]),i=e.startedAt??e.createdAt,a=i?new Date(i):null,l=(()=>{if(e.status==="running")return"Running…";if(!e.startedAt||!e.completedAt)return"—";const c=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return c<0?"—":Kct(c)})();return o.jsxs(fn,{children:[o.jsx(ej,{label:"Avg score",children:s===void 0?o.jsx("span",{className:"text-neutral3",children:"—"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{children:s.toFixed(3)}),r&&o.jsx("span",{className:"text-neutral3",children:"· so far"})]})}),o.jsx(ej,{label:"Items",children:r?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(ej,{label:"Started",children:a?o.jsx("span",{title:yZn(a,{addSuffix:!0}),children:gr(a,"MMM d, h:mm a")}):o.jsx("span",{children:"—"})}),o.jsx(ej,{label:"Duration",children:o.jsx("span",{children:l})}),t?.isEnabled&&o.jsxs(o.Fragment,{children:[o.jsx(ej,{label:"Tokens",children:t.data?.totalTokens==null?o.jsx("span",{className:"text-neutral3",children:"—"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{children:lo(t.data.totalTokens)}),t.data.estimatedCost!=null&&o.jsxs("span",{className:"text-neutral3",children:["· ",Zd(t.data.estimatedCost,t.data.costUnit)]}),r&&o.jsx("span",{className:"text-neutral3",children:"· so far"})]})}),o.jsx(ej,{label:"Latency (avg)",children:t.data?.avgAgentDurationMs==null?o.jsx("span",{className:"text-neutral3",children:"—"}):o.jsx("span",{children:Kct(Math.round(t.data.avgAgentDurationMs))})})]})]})}function jDs({scoresByItemId:e,experimentStatus:t}){const{Link:n,paths:r}=un(),{data:s}=Ep(),i=g.useMemo(()=>{if(!e)return[];const a={};for(const l of Object.values(e))for(const c of l)a[c.scorerId]||(a[c.scorerId]={sum:0,count:0}),a[c.scorerId].sum+=c.score,a[c.scorerId].count++;return Object.entries(a).map(([l,{sum:c,count:u}])=>({scorerId:l,avg:c/u})).sort((l,c)=>l.scorerId.localeCompare(c.scorerId))},[e]);if(i.length===0){const a=t==="running"||t==="pending",l=e!==void 0;let c,u;return a?(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(gb,{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 flex-col gap-2",children:i.map(({scorerId:a,avg:l})=>{const c=s?.[a]?.scorer?.config?.name??a;return o.jsxs(Mr,{className:"min-w-0 p-3",children:[o.jsxs(n,{href:r.scorerLink(a),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(In,{children:[o.jsx(On,{render:o.jsx(dw,{role:"img","aria-label":"Scorer"})}),o.jsx(Cn,{children:"Scorer"})]}),o.jsx("span",{className:"truncate",children:c})]}),o.jsxs("strong",{className:"text-ui-md 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"})]})]},a)})})}function que({title:e,children:t}){return o.jsxs("section",{className:"grid gap-3",children:[o.jsx("h2",{className:"text-ui-md text-neutral2 tracking-widest uppercase",children:e}),t]})}function NDs({experiment:e,metrics:t,className:n}){const{Link:r,paths:s}=un(),{data:i}=M1(e.id,e.status),a=e.agentVersion&&e.targetType==="agent"&&e.targetId?`${s.agentLink(e.targetId)}/editor?version=${encodeURIComponent(e.agentVersion)}`:null;return o.jsxs(Jf,{as:"aside","aria-label":"Experiment details",className:K("grid content-start gap-5 p-5",n),children:[o.jsxs(que,{title:"Pipeline",children:[o.jsx(EDs,{experiment:e}),e.agentVersion&&o.jsxs(fn,{children:[o.jsx(fn.Key,{children:"Version"}),a?o.jsx(fn.ValueLink,{href:a,as:r,children:e.agentVersion}):o.jsx(fn.Value,{children:e.agentVersion})]})]}),o.jsx(que,{title:"Run",children:o.jsx(TDs,{experiment:e,metrics:t})}),o.jsx(que,{title:"Scorers",children:o.jsx(jDs,{scoresByItemId:i,experimentStatus:e.status})})]})}function IDs({experiment:e,open:t,onOpenChange:n}){const[r,s]=g.useState(e.name??""),[i,a]=g.useState(e.description??""),{updateExperiment:l}=pl(),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:i.trim()}),Ge.success("Experiment renamed"),n(!1)}catch(f){Ge.error(`Failed to rename experiment: ${f instanceof Error?f.message:"Unknown error"}`)}};return o.jsx(hs,{open:t,onOpenChange:n,children:o.jsxs(Jr,{className:"max-w-md",children:[o.jsx(es,{children:o.jsx(Kr,{children:"Rename Experiment"})}),o.jsx(vs,{children:o.jsxs("form",{onSubmit:u,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Vt,{htmlFor:"rename-experiment-name",children:"Name *"}),o.jsx($n,{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(Vt,{htmlFor:"rename-experiment-description",children:"Description"}),o.jsx($n,{id:"rename-experiment-description",value:i,onChange:d=>a(d.target.value),placeholder:"Enter experiment description (optional)"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ae,{icon:o.jsx(Yt,{}),type:"button",onClick:()=>n(!1),disabled:l.isPending,children:"Cancel"}),o.jsx(ae,{icon:o.jsx(Mn,{}),type:"submit",variant:"primary",disabled:!c,children:l.isPending?"Saving...":"Save"})]})]})})]})})}const ADs=["agent","workflow","scorer"];function RDs({experiment:e}){const[t,n]=g.useState(!1),r=Fr(),{paths:s}=un(),i=wrn(e),a=ADs.find(l=>l===e.targetType);return!e.datasetId||!a||!e.targetId?null:o.jsxs(o.Fragment,{children:[o.jsx(ae,{variant:"primary",onClick:()=>n(!0),tooltip:"Run this experiment again with the same configuration",icon:o.jsx(bu,{}),children:"Rerun"}),t&&o.jsx(yJ,{open:!0,onOpenChange:n,initialDatasetId:e.datasetId,initialDatasetVersion:e.datasetVersion??void 0,initialTargetType:a,initialTargetId:e.targetId,initialScorerIds:i,initialName:e.name??void 0,initialDescription:e.description??void 0,onSuccess:l=>{r(s.experimentLink(l))}},i.join(","))]})}function PDs({experiment:e,onDeleteClick:t,children:n}){const{Link:r}=un(),[s,i]=g.useState(!1),a=!!e.datasetId,l=a||!!t;return o.jsxs(Ft.TopArea,{children:[o.jsxs(Ft.Row,{className:"items-center justify-start gap-2",children:[o.jsxs(Ms,{className:"whitespace-nowrap",children:[o.jsx(RDs,{experiment:e}),o.jsx(ae,{render:o.jsx(r,{href:q8t(e.id)}),icon:o.jsx(F_,{}),children:"Review queue"}),l&&o.jsxs(xt,{children:[o.jsx(xt.Trigger,{asChild:!0,children:o.jsx(ae,{size:"lg","aria-label":"Experiment actions menu",children:o.jsx(F1,{})})}),o.jsxs(xt.Content,{align:"start",className:"w-48",children:[a&&o.jsxs(xt.Item,{onSelect:()=>i(!0),children:[o.jsx(Gd,{})," Rename Experiment"]}),t&&o.jsxs(xt.Item,{onSelect:t,className:"text-red-500 focus:text-red-400",children:[o.jsx(co,{})," Delete Experiment"]})]})]})]}),n]}),s&&o.jsx(IDs,{experiment:e,open:!0,onOpenChange:i})]})}const $Ds=({experimentId:e,experimentStatus:t})=>{const n=Ye(),{supportsMetrics:r}=rF(),s=!!e&&r,a=yt({queryKey:["experiment-metrics",e],enabled:s,refetchInterval:t==="running"||t==="pending"?2e3:!1,queryFn:async()=>{if(!e)throw new Error("experimentId is required");const l={experimentId:e},[c,u,d]=await Promise.all([n.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:l}),n.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"avg",filters:l}),n.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:l})]);return{totalTokens:c.value??null,estimatedCost:c.estimatedCost??null,costUnit:c.costUnit??null,avgAgentDurationMs:u.value??null,agentRuns:d.value??null}}});return{data:a.data,isLoading:a.isLoading,isEnabled:s}};function MDs({datasetId:e,experimentId:t}){const[n,r]=g.useState(!1),{updateExperimentResult:s}=pl();return{addTag:g.useCallback(async(a,l)=>{const c=l.filter(d=>!(d.tags??[]).includes(a));if(n||c.length===0)return;r(!0);let u=0;try{u=(await Promise.allSettled(c.map(f=>s.mutateAsync({datasetId:e,experimentId:t,resultId:f.id,tags:[...f.tags??[],a]})))).filter(f=>f.status==="fulfilled").length}finally{r(!1)}u>0?Ge(`Tag "${a}" added to ${u} result${u>1?"s":""}`):Ge.error("Failed to add tag")},[e,t,n,s]),isPending:n}}function DDs({datasetId:e,experimentId:t,results:n}){const[r,s]=g.useState(new Set),[i,a]=g.useState(!1),{updateExperimentResult:l}=pl(),{addTag:c,isPending:u}=MDs({datasetId:e,experimentId:t}),d=xrn(e,n),f=g.useMemo(()=>n.filter(y=>r.has(y.id)),[n,r]),h=g.useCallback(y=>{s(b=>{const x=new Set(b);return x.has(y)?x.delete(y):x.add(y),x})},[]),p=g.useCallback(()=>s(new Set),[]),m=g.useCallback(async()=>{if(i||r.size===0)return;a(!0);const y=new Set;try{for(const b of r)try{await l.mutateAsync({datasetId:e,experimentId:t,resultId:b,status:"needs-review"}),y.add(b)}catch{}}finally{a(!1)}y.size>0&&(s(b=>{const x=new Set(b);for(const w of y)x.delete(w);return x}),Ge(`${y.size} result${y.size>1?"s":""} flagged for review`))},[e,t,i,r,l]),v=g.useCallback(y=>c(y,f),[c,f]);return{selectedIds:r,selectedResults:f,toggleSelect:h,clearSelection:p,flagSelectedForReview:m,isFlagging:i,addTagToSelected:v,isTagging:u,tagVocabulary:d}}const LDs=[];function _B({children:e}){return o.jsxs(Ft,{height:"full",children:[o.jsx("div",{}),o.jsx(Ft.MainArea,{isCentered:!0,children:e})]})}function FDs(){const{experimentId:e}=ur(),t=Fr(),[n,r]=g.useState(!1),{data:s,isLoading:i}=KG(),l=s?.experiments?.find(w=>w.id===e)?.datasetId??"",{data:c,isLoading:u,error:d}=X3(l,e??""),{data:f,isLoading:h,setEndOfListElement:p,isFetchingNextPage:m,hasNextPage:v}=Nke({datasetId:l,experimentId:e??"",experimentStatus:c?.status}),y=$Ds({experimentId:e,experimentStatus:c?.status}),b=DDs({datasetId:l,experimentId:e??"",results:f??LDs});if(!e||i||u)return null;if(d&&ks(d))return o.jsx(_B,{children:o.jsx(Gs,{})});if(d&&Es(d))return o.jsx(_B,{children:o.jsx(Fs,{resource:"datasets"})});const x=o.jsx(_B,{children:o.jsx(Ar,{iconSlot:o.jsx(DSt,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:o.jsx(ae,{render:o.jsx(oo,{to:"/experiments"}),icon:o.jsx(id,{}),children:"Back to Experiments"})})});return d&&CR(d)?x:d?o.jsx(_B,{children:o.jsx(Ws,{title:"Failed to load experiment",message:d instanceof Error?d.message:"An unexpected error occurred. Please try again."})}):!l||!c?x:o.jsx(NMs,{experimentId:e,datasetId:l,experimentStatus:c.status,results:f??[],isLoadingResults:h,hasNextPage:v,children:o.jsxs("div",{className:"h-full",children:[o.jsxs(Ft,{height:"full",children:[o.jsx(PDs,{experiment:c,onDeleteClick:()=>r(!0),children:o.jsx(_Ds,{selection:b})}),o.jsxs(Ft.MainArea,{className:"grid grid-cols-[1fr_auto] gap-4 overflow-visible",children:[o.jsx(MMs,{experimentId:e,experimentStatus:c.status,results:f??[],isLoading:h,setEndOfListElement:p,isFetchingNextPage:m,hasNextPage:v,selectedIds:b.selectedIds,onToggleSelect:b.toggleSelect}),o.jsx(NDs,{experiment:c,metrics:y,className:"w-80 overflow-y-auto"})]})]}),o.jsx(CDs,{}),o.jsx(srn,{open:n,onOpenChange:r,experimentId:e,experimentName:c.name??void 0,onSuccess:()=>t("/experiments")})]})})}const aLe=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"})}),IZ="all",Yct=60,zDs=e=>e.length>Yct?`${e.slice(0,Yct)}…`:e;function BDs({value:e,onValueChange:t,className:n,variant:r,allOption:s,targetType:i,targetId:a}){const{data:l,isLoading:c,isError:u}=iLe(void 0,{targetType:i,targetId:a}),d=(l?.experiments??[]).map(h=>({label:irn(h),value:h.id,start:o.jsx(aLe,{className:"text-neutral3 size-4 shrink-0","data-testid":"experiments-icon"}),description:h.description?zDs(h.description):ub(h.id)??h.id})),f=s?[{label:"All experiments",value:IZ},...d]:d;return o.jsx(qo,{options:f,value:e??(s?IZ:""),onValueChange:t,placeholder:c?"Loading experiments...":u?"Failed to load experiments":"Select experiment",searchPlaceholder:"Search experiments...",emptyText:"No experiments found.",className:n,disabled:c||u,variant:r})}function UDs(){const[e,t]=bi(),n=e.get("experiment"),r=e.get("review"),{targetType:s,targetId:i,setTargetType:a,setTargetId:l}=sLe({resetParams:["experiment","review"]}),{Link:c,paths:u}=un(),{data:d,error:f}=iLe(void 0,{targetType:s,targetId:i}),h=d?.experiments.find(m=>m.id===n),p=m=>{t(v=>{const y=new URLSearchParams(v);return m===IZ?y.delete("experiment"):y.set("experiment",m),y.delete("review"),y},{replace:!0})};return f&&ks(f)?o.jsx(Qn,{children:o.jsx(Gs,{})}):f&&Es(f)?o.jsx(Qn,{children:o.jsx(Fs,{resource:"experiments"})}):f?o.jsx(Qn,{children:o.jsx(Ws,{title:"Failed to load experiments",message:f.message})}):o.jsx(Ft,{height:"full",children:o.jsx(mDs,{datasetId:h?.datasetId??void 0,experimentId:n??void 0,targetType:s,targetId:i,featuredItemId:r,toolbarStart:o.jsxs(o.Fragment,{children:[o.jsx(eLe,{targetType:s,targetId:i,onTargetTypeChange:a,onTargetIdChange:l}),o.jsx(BDs,{allOption:!0,value:n??void 0,onValueChange:p,targetType:s,targetId:i,className:"w-72"})]}),toolbarEnd:n?o.jsx(ae,{render:o.jsx(c,{href:u.experimentLink(n)}),icon:o.jsx(ISt,{}),children:"See experiment"}):void 0},`${s}:${i}:${n??IZ}`)})}const Srn=[{name:"itemId",label:"Item ID",size:"auto"},{name:"status",label:"Status",size:"auto"},{name:"input",label:"Input",size:"minmax(0,1fr)"},{name:"tags",label:"Tags",size:"auto"}],VDs=Srn.map(e=>e.size).join(" ");function qDs({items:e,isLoading:t,error:n}){const r=Fr(),[s,i]=g.useState(""),a=s.trim().toLowerCase(),l=a?e.filter(c=>[c.itemId,c.experimentId,c.datasetId,c.traceId??""].some(u=>u.toLowerCase().includes(a))):e;return t?o.jsx(Wl,{columns:VDs}):n?o.jsx(Ws,{title:"Failed to load dataset items",message:n.message}):e.length===0?o.jsx(Ar,{iconSlot:o.jsx(Ls,{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(Wc,{onSearch:i,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.jsx(nLe,{results:l,isLoading:!1,featuredResultId:null,onResultClick:c=>{const u=l.find(d=>d.id===c);u&&r(q8t(u.experimentId,u.id))},columns:Srn,emptyMessage:"No dataset items match your search"})})]})}function HDs(){return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ar,{iconSlot:o.jsx(Ls,{}),titleSlot:"Your inbox is empty",descriptionSlot:o.jsxs(o.Fragment,{children:["Feedback left on traces and experiment results flagged for review ",o.jsx("br",{}),"will show up here until you mark them reviewed."]}),actionSlot:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ae,{icon:o.jsx(aLe,{}),render:o.jsx(oo,{to:"/experiments"}),variant:"outline",children:"Go to experiments"}),o.jsx(ae,{icon:o.jsx(fE,{}),render:o.jsx(oo,{to:"/traces"}),variant:"outline",children:"Go to traces"})]})})})}function $ke(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 Xct="minmax(0, 2fr) minmax(0, 1fr) auto minmax(0, 1fr) auto auto",WDs=e=>e.stopPropagation();function ZDs({items:e,isLoading:t,error:n,hasNextPage:r,isFetchingNextPage:s,fetchNextPage:i,onMarkReviewed:a,pendingFeedbackId:l,onSelect:c,selectedFeedbackId:u}){const[d,f]=g.useState(""),h=d.trim().toLowerCase(),p=h?e.filter(x=>$ke(x).toLowerCase().includes(h)||(EZ(x)??"").toLowerCase().includes(h)||(x.traceId??"").toLowerCase().includes(h)||(x.feedbackSource??"").toLowerCase().includes(h)):e,{containerRef:m,getRowProps:v}=Zc({count:p.length,global:!0}),{inView:y,setRef:b}=Sb({root:m});return g.useEffect(()=>{y&&r&&!s&&i()},[y,r,s,i]),t?o.jsx(Wl,{columns:Xct}):n?o.jsx(Ws,{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(Wc,{onSearch:f,label:"Filter feedback",placeholder:"Filter loaded feedback by text, author, trace or source"})}),o.jsx("div",{className:"min-h-0 overflow-hidden",children:o.jsxs(we,{columns:Xct,fit:"container",scrollRef:m,children:[o.jsxs(we.Top,{children:[o.jsx(we.TopCell,{children:"Feedback"}),o.jsx(we.TopCell,{children:"Author"}),o.jsx(we.TopCell,{children:"Source"}),o.jsx(we.TopCell,{children:"Trace"}),o.jsx(we.TopCell,{children:"Date"}),o.jsx(we.TopCell,{children:" "})]}),p.length===0?o.jsx(we.NoMatch,{message:h?"No feedback matches your search":"No feedback needs review"}):p.map((x,w)=>{const k=x.feedbackId,_=EZ(x);return o.jsxs(we.RowWrapper,{...v(w),onSelectRow:x.traceId?()=>c(x):void 0,children:[o.jsxs(we.RowButton,{colEnd:-2,disabled:!x.traceId,featured:k!==void 0&&k===u,tabIndex:-1,onClick:C=>{C.stopPropagation(),c(x)},children:[o.jsx(we.TextCell,{className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:$ke(x)})}),o.jsx(we.Cell,{className:"flex gap-2",children:_&&o.jsxs(o.Fragment,{children:[o.jsx(cb,{name:_,src:x.author?.avatarUrl,size:"sm"}),o.jsx("span",{className:"truncate",children:_})]})}),o.jsx(we.Cell,{children:o.jsx(jt,{size:"sm",children:x.feedbackSource})}),o.jsx(we.TextCell,{font:"mono",className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:x.traceId??"—"})}),o.jsx(we.TextCell,{children:gr(x.timestamp,"MMM d, h:mm a")})]}),o.jsx(we.ActionsCell,{className:"pl-2",onClick:WDs,children:k?o.jsx(ae,{icon:o.jsx(F_,{}),variant:"ghost",size:"sm",onClick:()=>a(k),disabled:l===k,children:"Mark reviewed"}):null})]},k??`${String(x.timestamp)}-${x.traceId}`)}),o.jsx(we.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:b})]})})]})}function GDs({feedback:e,traceId:t,initialSpanId:n,onClose:r,onPrevious:s,onNext:i,onMarkReviewed:a,isMarkingReviewed:l}){const[c,u]=g.useState(n),[d,f]=g.useState(e?.feedbackId);e?.feedbackId!==d&&(f(e?.feedbackId),u(n));const{spans:h,isLoading:p}=Htn({traceId:t,anchorSpanId:null,listMode:"traces"});return o.jsx(XDe,{title:`Review feedback for trace ${t??""}`,size:c?"full":"wide",headerSlot:e&&o.jsx(QDs,{feedback:e,onMarkReviewed:a,isMarkingReviewed:l}),traceId:e?t:void 0,spans:h,isLoadingSpans:p,selectedSpanId:c??null,initialSpanId:n,onSpanSelect:u,onClose:r,onPrevious:s,onNext:i,traceHref:t?`/traces?traceId=${encodeURIComponent(t)}`:void 0,feedbackTabSlot:({traceId:m})=>o.jsx(Y3,{traceId:m}),spanFeedbackTabSlot:({traceId:m,spanId:v})=>m&&v?o.jsx(ZDe,{traceId:m,spanId:v},`${m}:${v}`):null})}function QDs({feedback:e,onMarkReviewed:t,isMarkingReviewed:n}){const r=EZ(e)??e.feedbackUserId;return o.jsxs("section",{"aria-label":"Feedback",className:"border-border1 flex max-h-[33vh] shrink-0 flex-col border-b",children:[o.jsxs($t.Header,{children:[o.jsxs($t.HeaderContent,{children:[o.jsxs($t.Heading,{children:["Feedback",o.jsx(jt,{variant:"neutral",emphasis:"muted",children:e.feedbackType}),e.feedbackSource&&o.jsx(jt,{variant:"neutral",emphasis:"muted",children:e.feedbackSource})]}),o.jsxs($t.Metadata,{children:[r&&o.jsx($t.Meta,{icon:o.jsx(cb,{name:r,src:e.author?.avatarUrl,size:"sm"}),tooltip:"Author",children:r}),o.jsx($t.Meta,{icon:o.jsx(M0,{}),tooltip:`Submitted at ${gr(new Date(e.timestamp),"MMM dd, yyyy HH:mm:ss")}`,children:gr(new Date(e.timestamp),"MMM dd, yyyy HH:mm")})]})]}),o.jsx($t.HeaderActions,{children:o.jsx(ae,{variant:"primary",size:"sm",onClick:t,disabled:n,icon:o.jsx(Mn,{}),children:"Mark as reviewed"})})]}),o.jsx("div",{className:"min-h-0 overflow-y-auto p-3",children:o.jsx(Te,{as:"p",variant:"ui-md",className:"text-neutral5 whitespace-pre-wrap",children:$ke(e)})})]})}const krn=100;async function KDs(e){const t=[];let n=0,r=!0;for(;r;){const s=await e.listExperiments({page:n,perPage:krn});t.push(...s.experiments),r=s.pagination.hasMore,n+=1}return t}async function YDs(e,t,n){const r=[];let s=0,i=!0;for(;i;){const a=await e.listDatasetExperimentResults(t,n,{page:s,perPage:krn});r.push(...a.results),i=a.pagination.hasMore,s+=1}return r}function XDs(){const e=Ye();return yt({queryKey:["inbox-dataset-review-items"],queryFn:async()=>{const t=await KDs(e);return(await Promise.all(t.map(async r=>{const s=r.datasetId;return s?(await YDs(e,s,r.id)).filter(a=>a.status==="needs-review").map(a=>({id:a.id,datasetId:s,experimentId:r.id,itemId:a.itemId,traceId:a.traceId??void 0,input:a.input,output:a.output,error:a.error,status:a.status,tags:a.tags})):[]}))).flat()},refetchInterval:3e3,refetchOnWindowFocus:!1})}function JDs({enabled:e}){const t=Ye();return yt({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 eLs(e){return e==="dataset"||e==="feedback"}function tLs(){const[e,t]=bi(),n=e.get("tab"),r=eLs(n)?n:"feedback",s=FAs({reviewStatus:"needs-review"}),i=WDe(),a=XDs(),l=a.data??[],c=s.total??0,u=!s.isLoading&&!a.isLoading&&!s.error&&!a.error&&s.items.length===0&&l.length===0,d=e.get("feedbackId")??void 0,f=e.get("traceId")??void 0,h=e.get("spanId")??void 0,p=T=>{t(E=>{const N=new URLSearchParams(E);for(const I of["feedbackId","traceId","spanId"]){const A=T[I];A?N.set(I,A):N.delete(I)}return N},{replace:!0})},m=()=>p({}),v=T=>p({feedbackId:T.feedbackId??void 0,traceId:T.traceId??void 0,spanId:T.spanId??void 0}),y=s.items.findIndex(T=>T.feedbackId===d),b=y>=0?s.items[y]:void 0,x=y>0?s.items[y-1]:void 0,w=y>=0&&y<s.items.length-1?s.items[y+1]:void 0,k=!!f&&!!d&&!!b,_=T=>{i.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.jsx(Ft,{height:"full",className:"grid-rows-[minmax(0,1fr)]",children:o.jsx(Ft.MainArea,{className:"min-h-0 overflow-hidden",children:u?o.jsx(HDs,{}):o.jsxs(hl,{defaultTab:"feedback",value:r,onValueChange:C,className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[o.jsxs(fl,{variant:"pill-ghost",children:[o.jsxs(Sr,{value:"feedback",children:[o.jsx(St,{size:"sm",children:o.jsx(jA,{})}),o.jsx(Te,{variant:"ui-sm",className:"text-inherit",children:"Feedback"}),c>0&&o.jsx(jt,{variant:"yellow",size:"sm",children:c})]}),o.jsxs(Sr,{value:"dataset",children:[o.jsx(St,{size:"sm",children:o.jsx(F_,{})}),o.jsx(Te,{variant:"ui-sm",className:"text-inherit",children:"Dataset items"}),l.length>0&&o.jsx(jt,{variant:"yellow",size:"sm",children:l.length})]})]}),o.jsx(ts,{value:"feedback",className:"h-full min-h-0 pt-4",children:o.jsx(ZDs,{items:s.items,isLoading:s.isLoading,error:s.error??void 0,hasNextPage:s.hasNextPage,isFetchingNextPage:s.isFetchingNextPage,fetchNextPage:s.fetchNextPage,onMarkReviewed:_,pendingFeedbackId:i.isPending?i.variables?.feedbackId:void 0,onSelect:v,selectedFeedbackId:d})}),o.jsx(ts,{value:"dataset",className:"h-full min-h-0 pt-4",children:o.jsx(qDs,{items:l,isLoading:a.isLoading,error:a.error??void 0})})]})})}),o.jsx(GDs,{feedback:k?b:void 0,traceId:k?f:void 0,initialSpanId:h,onClose:m,onPrevious:x?()=>v(x):void 0,onNext:w?()=>v(w):void 0,onMarkReviewed:()=>d&&_(d),isMarkingReviewed:i.isPending})]})}function nLs({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-ui-sm",children:e.connectionId}),o.jsxs("div",{className:"text-ui-sm 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 Orn({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("ul",{className:"space-y-1",children:e.map(s=>o.jsx(nLs,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function rLs({groups:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("div",{className:"space-y-4",children:e.map(([s,i])=>o.jsxs("div",{children:[o.jsx("h3",{className:"text-ui-md font-semibold text-gray-700","data-testid":`integration-author-group-${s}`,children:s==="shared"?"Shared":`Owned by ${s}`}),o.jsx(Orn,{connections:i,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function sLs({providerId:e,toolkit:t,connections:n,groupedByAuthor:r,isAdmin:s,isLoading:i,error:a,disconnectPending:l,disconnectError:c,onDisconnect:u}){return o.jsxs("div",{className:"space-y-2 border rounded p-4",children:[o.jsx("h2",{className:"text-header-sm font-semibold",children:"Existing connections"}),!e||!t?o.jsx("p",{className:"text-gray-500",children:"Pick a provider and toolkit to list connections."}):i?o.jsx("p",{className:"text-gray-500",children:"Loading…"}):a?o.jsx("p",{className:"text-red-600",children:String(a)}):n.length===0?o.jsx("p",{className:"text-gray-500",children:"No connections."}):r?o.jsx(rLs,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):o.jsx(Orn,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?o.jsx("p",{className:"text-red-600",children:String(c)}):null]})}function iLs({providers:e,toolkits:t,providerId:n,toolkit:r,label:s,providersLoading:i,providersError:a,toolkitsLoading:l,toolkitsError:c,authorizePending:u,authorizeError:d,authorizedConnection:f,onProviderChange:h,onToolkitChange:p,onLabelChange:m,onConnect:v}){return o.jsxs("div",{className:"space-y-4 border rounded p-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"provider-select",children:"Provider"}),o.jsxs("select",{id:"provider-select",className:"border rounded px-2 py-1 w-full",value:n,onChange:y=>h(y.target.value),disabled:i,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))]}),i&&o.jsx("span",{className:"text-gray-500",children:"Loading providers…"}),a?o.jsx("span",{className:"text-red-600",children:String(a)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"toolkit-select",children:"Toolkit"}),o.jsxs("select",{id:"toolkit-select",className:"border rounded px-2 py-1 w-full",value:r,onChange:y=>p(y.target.value),disabled:!n||l,children:[o.jsx("option",{value:"",children:"— select toolkit —"}),t.map(y=>o.jsxs("option",{value:y.slug,children:[y.name," (",y.slug,")"]},y.slug))]}),l&&o.jsx("span",{className:"text-gray-500",children:"Loading toolkits…"}),c?o.jsx("span",{className:"text-red-600",children:String(c)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"label-input",children:"Label (optional)"}),o.jsx("input",{id:"label-input",type:"text",className:"border rounded px-2 py-1 w-full",placeholder:"My personal Gmail",value:s,onChange:y=>m(y.target.value),disabled:!n||!r})]}),o.jsx("button",{type:"button",className:"bg-blue-600 text-white rounded px-4 py-2 disabled:opacity-50",onClick:v,disabled:!n||!r||u,children:u?"Authorizing…":"Connect"}),d?o.jsx("p",{className:"text-red-600",children:String(d)}):null,f&&o.jsxs("p",{className:"text-green-700",children:["Authorized: ",f.connectionId," (status: ",f.status,")"]})]})}const Jct=e=>e.authorId?.trim()||"shared",aLs=(e,t)=>{if(!t||new Set(e.map(Jct)).size<=1)return null;const r=new Map;for(const i of e){const a=Jct(i);r.set(a,[...r.get(a)??[],i])}const s=Array.from(r.entries());return s.sort(([i],[a])=>i==="shared"?1:a==="shared"?-1:i.localeCompare(a)),s},oLs=["*","tool-providers:*","tool-providers:admin"];function lLs(){const{data:e}=Jm();return e?.permissions?.some(t=>oLs.includes(t))??!1}function cLs(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,i]=g.useState(""),a=IR(),l=_Y(e||null),c=lVt(e||null,n||null),u=oVt(),d=sVt(),f=lLs(),h=a.data?.providers??[],p=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),v=g.useMemo(()=>aLs(m,f),[m,f]),y=w=>{t(w),r("")},b=()=>{!e||!n||u.mutate({providerId:e,toolkit:n,label:s.trim()||null},{onSuccess:()=>{i(""),c.refetch()}})},x=w=>{d.mutate({providerId:e,connectionId:w})};return o.jsxs("div",{className:"p-4 max-w-3xl space-y-6 text-ui-md",children:[o.jsx("h1",{className:"text-header-md 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(iLs,{providers:h,toolkits:p,providerId:e,toolkit:n,label:s,providersLoading:a.isLoading,providersError:a.error,toolkitsLoading:l.isLoading,toolkitsError:l.error,authorizePending:u.isPending,authorizeError:u.error,authorizedConnection:u.data,onProviderChange:y,onToolkitChange:r,onLabelChange:i,onConnect:b}),o.jsx(sLs,{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 uLs({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(Om,{className:"h-10 w-10"}),o.jsx("h1",{className:"text-neutral6 text-header-md font-semibold",children:e})]}),t,n,r]})})}function Crn({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:i}=hc(),{mutate:a,isPending:l,error:c}=ZQr(),{mutate:u,isPending:d,error:f}=QQr(),{mutate:h,isPending:p}=_Bt(),[m,v]=g.useState(n),[y,b]=g.useState(""),[x,w]=g.useState(""),[k,_]=g.useState("");if(i)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,P=A?l:d,L=A?c:f,M=()=>{t?t():e?window.location.href=e:window.location.href=NY("/")},V=z=>{z.preventDefault(),A?a({email:x,password:k},{onSuccess:M}):u({email:x,password:k,name:y||void 0},{onSuccess:M})},q=()=>{h({redirectUri:e},{onSuccess:z=>{window.location.href=z.url}})},H=()=>{v(A?"signup":"signin")},B=C.description?o.jsxs("div",{className:"border-border1 bg-surface1 flex items-start gap-2.5 rounded-md border p-3",children:[o.jsx(td,{className:"text-neutral4 mt-0.5 h-4 w-4 shrink-0"}),o.jsx("p",{className:"text-neutral3 text-ui-md",children:C.description})]}):null,W=r?o.jsx("div",{className:"text-ui-md rounded-md bg-red-500/10 p-3 text-red-400",children:r}):null;return o.jsxs(uLs,{title:A?"Sign in to Mastra Studio":"Create your account",description:B,errorBanner:W,children:[E&&o.jsxs("form",{onSubmit:V,className:"space-y-4",children:[!A&&o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"name",className:"text-neutral4 text-ui-md block",children:"Name"}),o.jsx($n,{id:"name",type:"text",value:y,onChange:z=>b(z.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 text-ui-md block",children:"Email"}),o.jsx($n,{id:"email",type:"email",value:x,onChange:z=>w(z.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 text-ui-md block",children:"Password"}),o.jsx($n,{id:"password",type:"password",value:k,onChange:z=>_(z.target.value),placeholder:A?"Enter your password":"Create a password",required:!0,variant:"default",size:"lg"})]}),L&&o.jsx("div",{className:"text-ui-md rounded-md bg-red-500/10 p-3 text-red-400",children:L.message}),o.jsx(ae,{icon:o.jsx(vV,{}),type:"submit",disabled:P,className:"w-full",size:"lg",children:P?A?"Signing in...":"Creating account...":A?"Sign in":"Create account"}),I&&o.jsxs("div",{className:"text-ui-md text-center",children:[o.jsx("span",{className:"text-neutral3",children:A?"Don't have an account? ":"Already have an account? "}),o.jsx("button",{type:"button",onClick:H,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:"text-ui-md relative flex justify-center",children:o.jsx("span",{className:"bg-surface1 text-neutral3 px-2",children:"or continue with"})})]}),T&&N&&o.jsxs(ae,{onClick:q,disabled:p,className:"w-full",size:"lg",variant:"outline",children:[N.icon&&o.jsx("span",{className:"mr-2",children:N.icon}),p?"Redirecting...":N.text||"Sign in"]})]})}function dLs(){const[e]=bi(),t=Fr(),n=e.get("redirect")||"/",s=e.get("mode")==="signup"?"signup":"signin",i=e.get("error_description")||e.get("error")||null,a=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(Crn,{redirectUri:n,onSuccess:a,initialMode:s,errorMessage:i})}function _rn({disabled:e,onClear:t,onRemoveAll:n,onSave:r,onRemoveSaved:s}){const i=!!(n||r||s);return!t&&!i?null:o.jsxs("div",{className:"flex items-center gap-2",children:[t&&o.jsx(ae,{disabled:e,size:"md",onClick:t,icon:o.jsx(Yt,{}),children:"Clear"}),i&&o.jsxs(xt,{children:[o.jsx(xt.Trigger,{asChild:!0,children:o.jsx(ae,{disabled:e,size:"md","aria-label":"More filter actions",children:o.jsx(F1,{})})}),o.jsxs(xt.Content,{align:"end",children:[n&&o.jsxs(xt.Item,{onSelect:()=>n(),children:[o.jsx(Yt,{}),"Remove all filters"]}),n&&(r||s)&&o.jsx(xt.Separator,{}),r&&o.jsxs(xt.Item,{onSelect:()=>r(),children:[o.jsx(Uf,{}),"Save filters for next time"]}),s&&o.jsxs(xt.Item,{onSelect:()=>s(),children:[o.jsx(co,{}),"Remove saved filters"]})]})]})]})}const fLs=K(V0,"min-w-0 focus:bg-neutral6/5 focus:text-neutral6");function Hue({role:e,checked:t,label:n,onClick:r}){return o.jsxs("button",{type:"button",role:e,"aria-checked":t,"data-selected":t||void 0,"data-pick-multi-item":"",title:n,className:fLs,onClick:r,children:[o.jsx("span",{className:"min-w-0 flex-1 truncate",children:n}),t&&o.jsx("span",{className:q4,children:o.jsx(Mn,{})})]})}function Ern({field:e,tokens:t,onChange:n}){const[r,s]=g.useState(""),i=g.useMemo(()=>{const u=r.trim().toLowerCase();return u?e.options.filter(d=>d.label.toLowerCase().includes(u)):e.options},[e.options,r]),a=g.useMemo(()=>t.find(u=>u.fieldId===e.id),[t,e.id]),l=typeof a?.value=="string"?a.value:e.multi?void 0:e.defaultValue,c=g.useMemo(()=>{const u=a?.value;return Array.isArray(u)?u:typeof u=="string"?[u]:[]},[a]);return o.jsxs(o.Fragment,{children:[e.searchable!==!1&&o.jsxs("div",{className:cN.container,children:[o.jsx(Oi,{className:cN.icon}),o.jsx("input",{type:"text",value:r,onChange:u=>s(u.target.value),placeholder:`Search ${e.label.toLowerCase()}...`,className:cN.input,onKeyDown:u=>{if(u.key!=="ArrowDown")return;const f=u.currentTarget.closest("[data-pick-multi-panel]")?.querySelector("[data-pick-multi-item]:not([disabled])");f&&(u.preventDefault(),u.stopPropagation(),f.focus())}})]}),e.isLoading?o.jsxs("div",{className:K($V,"m-1"),children:[o.jsx(_n,{size:"sm",className:"text-neutral3 size-3"}),"Loading options…"]}):i.length===0?o.jsx("div",{className:K($V,"m-1"),children:e.emptyText??"No option found."}):e.multi?o.jsx("div",{className:"max-h-[80dvh] overflow-auto p-1",children:i.map(u=>{const d=c.includes(u.value);return o.jsx(Hue,{role:"checkbox",checked:d,label:u.label,onClick:()=>n(e.id,d?c.filter(f=>f!==u.value):[...c,u.value])},u.value)})}):o.jsxs("div",{role:"radiogroup",className:"max-h-[80dvh] overflow-auto p-1",children:[i.map(u=>o.jsx(Hue,{role:"radio",checked:l===u.value,label:u.label,onClick:()=>n(e.id,u.value)},u.value)),!e.omitAnyOption&&o.jsx(Hue,{role:"radio",checked:l==="Any",label:"Any",onClick:()=>n(e.id,"Any")})]})]})}function oLe(e){return Array.isArray(e)?e.length===0?"Any":e.join(", "):e}const hLs="This filter is set by the current context and cannot be removed here.";function pLs(e,t){return e.kind==="pick-multi"&&e.options?Array.isArray(t)?t.length===0?"Any":t.map(n=>e.options.find(r=>r.value===n)?.label??n).join(", "):e.options.find(n=>n.value===t)?.label??t:oLe(t)}function mLs({field:e,value:t,tooltipContent:n}){const r=pLs(e,t),s=`${e.label} filter is locked by context`;return o.jsx(fc,{delayDuration:150,children:o.jsxs(In,{children:[o.jsx(On,{asChild:!0,children:o.jsxs(Ms,{spacing:"close","data-locked-field-id":e.id,"data-property-filter-pill":"locked",tabIndex:0,"aria-label":s,children:[o.jsx(Xh,{size:"md",children:e.label}),o.jsx(Xh,{size:"md",children:"is"}),o.jsx(Xh,{size:"md",children:r}),o.jsx(Xh,{size:"md",children:o.jsx(td,{})})]})}),o.jsx(Cn,{children:n})]})})}function gLs({field:e,value:t,onChange:n,onRemove:r,disabled:s,autoFocus:i}){const[a,l]=g.useState(t),c=g.useRef(null);return g.useEffect(()=>{a.trim()!==t&&l(t)},[t]),g.useEffect(()=>{i&&c.current?.focus()},[i]),o.jsxs(Ms,{spacing:"close",children:[o.jsx(Xh,{size:"md",children:e.label}),o.jsx(Xh,{size:"md",children:"is"}),o.jsx($n,{ref:c,size:"md",disabled:s,value:a,placeholder:e.placeholder??`Enter ${e.label}`,onChange:u=>{const d=u.target.value;l(d),d.trim()!==t&&n(d)},onKeyDown:u=>{if(u.key==="Enter"){u.preventDefault();const d=a.trim();d!==t&&n(d)}else u.key==="Escape"&&(u.preventDefault(),l(t),u.target.blur())}}),o.jsx(ae,{type:"button",disabled:s,"aria-label":`Remove ${e.label} filter`,size:"md",onMouseDown:u=>u.preventDefault(),onClick:r,children:o.jsx(Yt,{})})]})}function vLs({field:e,token:t,tokens:n,onChange:r,onRemove:s,disabled:i}){const[a,l]=g.useState(!1);return o.jsxs(Ms,{spacing:"close",children:[o.jsx(Xh,{size:"md",children:e.label}),o.jsx(Xh,{size:"md",children:"is"}),o.jsxs(Zm,{open:a,onOpenChange:l,children:[o.jsx(Xf,{asChild:!0,children:o.jsx(ae,{type:"button",disabled:i,size:"md",children:oLe(t.value)})}),o.jsx(vp,{align:"start",sideOffset:sE,className:"w-64 p-0","data-pick-multi-panel":!0,children:o.jsx(Ern,{field:e,tokens:n,onChange:r})})]}),o.jsx(ae,{type:"button",disabled:i,"aria-label":`Remove ${e.label} filter`,size:"md",onClick:s,children:o.jsx(Yt,{})})]})}function Trn({fields:e,tokens:t,onTokensChange:n,disabled:r,autoFocusFieldId:s,lockedFieldIds:i,lockedTooltipContent:a=hLs}){if(t.length===0)return null;const l=new Set(i??[]),c=(d,f)=>{const h=[...t];h[d]=f,n(h)},u=d=>{n(t.filter((f,h)=>h!==d))};return o.jsx("div",{className:"flex flex-wrap items-center gap-2",children:t.map((d,f)=>{const h=e.find(p=>p.id===d.fieldId);return h?l.has(d.fieldId)?o.jsx(mLs,{field:h,value:d.value,tooltipContent:a},`${d.fieldId}-${f}`):h.kind==="text"&&typeof d.value=="string"?o.jsx(gLs,{field:h,value:d.value,disabled:r,autoFocus:s===d.fieldId,onChange:p=>c(f,{fieldId:d.fieldId,value:p}),onRemove:()=>u(f)},`${d.fieldId}-${f}`):h.kind==="pick-multi"?o.jsx(vLs,{field:h,token:d,tokens:t,disabled:r,onChange:(p,m)=>c(f,{fieldId:p,value:m}),onRemove:()=>u(f)},`${d.fieldId}-${f}`):o.jsxs(Ms,{spacing:"close",children:[o.jsx(Xh,{size:"md",children:h.label}),o.jsx(Xh,{size:"md",children:"is"}),o.jsx(Xh,{size:"md",children:oLe(d.value)}),o.jsx(ae,{type:"button",disabled:r,size:"md","aria-label":`Remove ${h.label} filter`,onClick:()=>u(f),children:o.jsx(Yt,{})})]},`${d.fieldId}-${f}`):null})})}const jrn="focus:bg-neutral6/5 focus:text-neutral6";function Nrn({fields:e,tokens:t,onTokensChange:n,label:r="Add Filter",disabled:s,size:i,onStartTextFilter:a,hiddenFieldIds:l}){const c=g.useMemo(()=>{if(!l||l.length===0)return e;const A=new Set(l);return e.filter(P=>!A.has(P.id))},[e,l]),[u,d]=g.useState(!1),[f,h]=g.useState(),[p,m]=g.useState([]),[v,y]=g.useState(),[b,x]=g.useState(),w=g.useRef(!1),k=g.useCallback(A=>{x(P=>P===A?void 0:A)},[]),_=g.useCallback(()=>x(void 0),[]);g.useEffect(()=>{u||x(void 0)},[u]);const C=g.useMemo(()=>c.find(A=>A.id===f),[c,f]),T=g.useMemo(()=>{const A=new Set;for(const P of t){const L=e.find(M=>M.id===P.fieldId);L&&L.kind!=="pick-multi"&&A.add(P.fieldId)}return A},[t,e]),E=g.useCallback(()=>{h(void 0),m([]),y(void 0)},[]);g.useEffect(()=>{u||E()},[u,E]);const N=g.useCallback((A,P)=>{const L=t.findIndex(V=>V.fieldId===A);if(Array.isArray(P)&&P.length===0){if(L===-1)return;n(t.filter((V,q)=>q!==L));return}if(L===-1){n([...t,{fieldId:A,value:P}]);return}const M=[...t];M[L]={fieldId:A,value:P},n(M)},[n,t]),I=g.useCallback(()=>{if(!C){y("Choose a property first.");return}if(T.has(C.id)){y(`Remove the existing ${C.label} filter before adding another.`);return}if(p.length===0){y(`Choose at least one ${C.label.toLowerCase()} value.`);return}n([...t,{fieldId:C.id,value:p}]),d(!1)},[p,n,C,T,t]);return o.jsxs(Zm,{open:u,onOpenChange:d,children:[o.jsx(Xf,{asChild:!0,children:o.jsx(ae,{variant:"outline",size:i,disabled:s,icon:o.jsx(Z8e,{}),children:r})}),o.jsx(vp,{align:"end",sideOffset:sE,className:K("w-64",C?"p-3":"p-1"),initialFocus:!1,finalFocus:()=>w.current?(w.current=!1,!1):!0,children:o.jsxs("div",{className:K("grid",C&&"gap-3"),children:[C&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("button",{type:"button","aria-label":"Back to properties",className:"text-neutral3 hover:text-neutral6 transition-colors",onClick:E,children:o.jsx(id,{className:"size-4"})}),o.jsx(AAn,{className:"text-neutral3 size-4 shrink-0"}),o.jsx("span",{className:"text-ui-sm text-neutral3",children:`${C.label} · is`})]}),!C&&o.jsx("div",{role:"menu",className:"max-h-[80dvh] overflow-auto",onKeyDown:A=>{if(A.key!=="ArrowDown"&&A.key!=="ArrowUp"&&A.key!=="Home"&&A.key!=="End")return;const P=Array.from(A.currentTarget.querySelectorAll("[data-filter-item]:not([disabled])"));if(P.length===0)return;A.preventDefault();const L=document.activeElement,M=P.findIndex(q=>q===L);let V;A.key==="Home"?V=0:A.key==="End"?V=P.length-1:A.key==="ArrowDown"?V=M<0?0:(M+1)%P.length:V=M<=0?P.length-1:M-1,P[V]?.focus()},children:c.length>0?c.map(A=>{const P=T.has(A.id);return A.kind==="pick-multi"?o.jsx(yLs,{field:A,tokens:t,onChange:N,open:b===A.id,onToggle:k,onClose:_},A.id):o.jsxs("button",{type:"button",role:"menuitem","data-filter-item":"",className:K(V0,"group",jrn),disabled:P,onClick:()=>{if(y(void 0),A.kind==="text"){n([...t,{fieldId:A.id,value:""}]),a?.(A.id),w.current=!0,d(!1);return}h(A.id)},children:[o.jsx("span",{className:"truncate",children:A.label}),P?o.jsx("span",{className:"text-neutral3 ml-auto",children:"In use"}):o.jsx("span",{className:K(BG,"text-neutral3 opacity-0 transition-opacity group-hover:opacity-100 group-focus:opacity-100"),children:o.jsx(Yr,{})})]},A.id)}):o.jsx("div",{className:$V,children:"No matching property."})}),C&&o.jsx(qo,{multiple:!0,options:C.options??[],value:p,onValueChange:A=>{m(A),y(void 0)},placeholder:C.placeholder??`Choose ${C.label}`,searchPlaceholder:`Search ${C.label.toLowerCase()}...`,emptyText:C.emptyText??"No option found.",size:"md"}),v&&o.jsx("div",{className:"text-ui-sm text-red-500",children:v}),C&&o.jsxs("div",{className:"flex items-center justify-end gap-2",children:[o.jsx(ae,{icon:o.jsx(Yt,{}),variant:"ghost",size:"md",onClick:()=>d(!1),children:"Cancel"}),o.jsx(ae,{icon:o.jsx(Z8e,{}),variant:"outline",size:"md",onClick:I,children:"Add filter"})]})]})})]})}function yLs({field:e,tokens:t,onChange:n,open:r,onToggle:s,onClose:i}){const a=g.useRef(null);return o.jsxs(Zm,{open:r,onOpenChange:l=>{l?s(e.id):i()},children:[o.jsx(Xf,{asChild:!0,children:o.jsxs("button",{type:"button",role:"menuitem","data-filter-item":"",className:K(V0,jrn),onKeyDown:l=>{l.key!=="ArrowRight"&&l.key!=="ArrowLeft"||(r||s(e.id),l.preventDefault(),requestAnimationFrame(()=>{a.current?.querySelector('input, button, [tabindex]:not([tabindex="-1"])')?.focus()}))},children:[r&&o.jsx(mr,{className:"text-neutral3"}),o.jsx("span",{className:"truncate",children:e.label}),!r&&o.jsx("span",{className:K(BG,"text-neutral3"),children:o.jsx(mr,{})})]})}),o.jsx(vp,{ref:a,side:"right",align:"start",sideOffset:sE,className:"w-64 p-0",initialFocus:!1,onKeyDown:l=>{if(l.key!=="ArrowDown"&&l.key!=="ArrowUp"&&l.key!=="Home"&&l.key!=="End")return;const c=Array.from(l.currentTarget.querySelectorAll("[data-pick-multi-item]:not([disabled])"));if(c.length===0)return;l.preventDefault(),l.stopPropagation();const u=document.activeElement,d=c.findIndex(h=>h===u);let f;l.key==="Home"?f=0:l.key==="End"?f=c.length-1:l.key==="ArrowDown"?f=d<0?0:(d+1)%c.length:f=d<=0?c.length-1:d-1,c[f]?.focus()},"data-pick-multi-panel":!0,children:o.jsx(Ern,{field:e,tokens:t,onChange:n})})]})}const _h=Ca.KeyValueList;function bLs(e){return e instanceof Date?e:new Date(e)}function xLs({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:i,collapsed:a,onCollapsedChange:l}){const[c,u]=g.useState(!1),d=a??c,f=l??u,h=bLs(e.timestamp),p=e.traceId,m=e.spanId;return o.jsxs(Ca,{collapsed:d,children:[o.jsxs(Ca.Header,{children:[o.jsxs(Ca.Heading,{children:["Log ",o.jsx("b",{children:gr(h,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(Ms,{className:"ml-auto shrink-0",children:[l&&o.jsx(ae,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(bCe,{}):o.jsx($St,{})}),o.jsxs(Ms,{spacing:"close",children:[o.jsx(ae,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(mb,{})}),o.jsx(ae,{size:"md",tooltip:"Next log",onClick:i,disabled:!i,children:o.jsx(f4,{})})]}),o.jsx(Ca.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(Ca.Content,{children:[o.jsx("p",{className:"text-ui-md text-neutral4 font-mono wrap-break-word whitespace-pre-wrap",children:e.message}),(p||m)&&o.jsxs("div",{className:K("my-8 grid gap-2","[&>button]:justify-between [&>button]:overflow-hidden"),children:[p&&o.jsxs(Ms,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(ae,{size:"md",className:"min-w-0 flex-1 overflow-hidden",icon:o.jsx(Kf,{}),onClick:()=>n?.(p),children:[o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",p]})]}),o.jsx(ci,{content:p,size:"md",tooltip:"Copy Trace ID to clipboard"})]}),m&&o.jsxs(Ms,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(ae,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!p||!r,onClick:()=>p&&r?.(p,m),icon:o.jsx(Kf,{}),children:[o.jsx("span",{children:"Span"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",m]})]}),o.jsx(ci,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(_h,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(_h.Key,{children:"Entity Type"}),o.jsx(_h.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(_h.Key,{children:"Entity Name"}),o.jsx(_h.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(_h.Key,{children:"Service"}),o.jsx(_h.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(_h.Key,{children:"Environment"}),o.jsx(_h.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(_h.Key,{children:"Source"}),o.jsx(_h.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(_h.Key,{children:v}),o.jsx(_h.Value,{children:String(y)})]},v))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(Ca.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function wLs({error:e,resource:t,errorTitle:n}){if(ks(e))return o.jsx(Gs,{});if(Es(e))return o.jsx(Fs,{resource:t});if(t6(e))return o.jsx(Ar,{iconSlot:o.jsx(Ls,{}),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(e6(e,"logs"))return o.jsx(Ar,{iconSlot:o.jsx(Ls,{}),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(Ws,{title:n,message:r??"Unknown error"})}function SLs({listSlot:e,logPanelSlot:t,tracePanelSlot:n,spanPanelSlot:r,logCollapsed:s}){const i=!!t;return o.jsxs("div",{className:K("grid h-full min-h-0 items-start gap-4",i?"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[e,i&&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 kLs={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 OLs({level:e}){const t=kLs[e];return o.jsx(mo,{children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function CLs({entityType:e,className:t}){const n=K("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case"agent":return o.jsx(Ma,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return o.jsx(Bc,{className:n,"aria-hidden":!0});case"tool":return o.jsx(eh,{className:n,"aria-hidden":!0});default:return null}}function _Ls({entityType:e,entityName:t}){const n=e??"";return o.jsxs(mo,{className:"flex min-w-0 items-center gap-2",children:[o.jsx(CLs,{entityType:n}),t?o.jsx("span",{className:"text-ui-smd min-w-0 truncate",children:t}):"-"]})}function ELs({message:e}){return o.jsx(mo,{className:"text-ui-smd text-neutral4 min-w-0 truncate font-mono",children:e})}function TLs({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(mo,{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(bRe,{font:"mono",children:t})}const Yl=Object.assign(Y5,{Top:X5,TopCell:ew,TopCellWithTooltip:uY,TopCellSmart:t9t,RowWrapper:kRe,RowButton:J5,RowLink:SRe,Spacer:ORe,NoMatch:fY,DateCell:Jzt,TimeCell:e9t,LevelCell:OLs,EntityCell:_Ls,MessageCell:ELs,DataCell:TLs,NextPageLoading:dY}),eut="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",jLs=36,NLs=8;function ILs({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:i,featuredLogId:a,onLogClick:l}){const c=g.useRef(null),u=Ftn({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>jLs,overscan:NLs}),{getRowProps:d}=Zc({count:e.length,containerRef:c,onNavigate:y=>u.scrollToIndex(y),global:!0}),f=g.useRef(t);if(g.useEffect(()=>{f.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),f.current=t},[t]),t)return o.jsx(Wl,{columns:eut});const h=u.getVirtualItems(),p=u.getTotalSize(),m=h[0]?.start??0,v=h.length>0?Math.max(0,p-(h[h.length-1]?.end??0)):0;return o.jsxs(Yl,{columns:eut,scrollRef:c,className:"min-w-0",children:[o.jsxs(Yl.Top,{children:[o.jsx(Yl.TopCell,{children:"Date"}),o.jsx(Yl.TopCell,{children:"Time"}),o.jsx(Yl.TopCell,{children:"Level"}),o.jsx(Yl.TopCell,{children:"Entity"}),o.jsx(Yl.TopCell,{children:"Message"}),o.jsx(Yl.TopCell,{children:"Data"})]}),e.length===0?o.jsx(Yl.NoMatch,{message:"No logs match your search"}):o.jsxs(o.Fragment,{children:[o.jsx(Yl.Spacer,{height:m}),h.map(y=>{const b=e[y.index];if(!b)return null;const x=i.get(b);if(!x)return null;const w=x===a;return o.jsxs(Yl.RowButton,{ref:u.measureElement,"data-index":y.index,...d(y.index),onClick:()=>l(b),featured:w,variant:b.level==="error"||b.level==="fatal"?"error":"default",children:[o.jsx(Yl.DateCell,{timestamp:b.timestamp}),o.jsx(Yl.TimeCell,{timestamp:b.timestamp}),o.jsx(Yl.LevelCell,{level:b.level}),o.jsx(Yl.EntityCell,{entityType:b.entityType,entityName:b.entityName}),o.jsx(Yl.MessageCell,{message:b.message}),o.jsx(Yl.DataCell,{data:b.data})]},x)}),o.jsx(Yl.Spacer,{height:v})]}),o.jsx(Yl.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function ALs({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:i,filterTokens:a,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=a.length>0,d=a.some(f=>RLs(f,i));return u?o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(Trn,{fields:i,tokens:a,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(_rn,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function RLs(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 PLs={"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"},Wue="MMM d, yyyy HH:mm",Zue="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function $Ls({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${PLs[e]}`,description:Zue}:t&&n?{title:`No logs between ${gr(t,Wue)} and ${gr(n,Wue)}`,description:Zue}:t?{title:`No logs since ${gr(t,Wue)}`,description:Zue}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const MLs=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=$Ls({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ar,{iconSlot:o.jsx(Ls,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsx(ae,{variant:"ghost",render:o.jsx("a",{href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer"}),icon:o.jsx(_s,{}),children:"Logging Documentation"})})})},DLs=20,LLs=1e4;function FLs(e,t,n){if(e?.pagination?.hasMore)return n+1}function zLs(e){const t=new Set,n=[];for(const r of e.pages)for(const s of r.logs??[]){const i=s.logId??JSON.stringify(s);t.has(i)||(t.add(i),n.push(s))}return n}function BLs(e){return e6(e.state.error,"logs")||t6(e.state.error)?!1:LLs}const ULs=({filters:e}={})=>{const t=Ye(),{inView:n,setRef:r}=Sb(),s=yv({queryKey:["logs",e],queryFn:({pageParam:h})=>t.listLogsVNext({pagination:{page:h,perPage:DLs},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:FLs,select:zLs,retry:!1,refetchInterval:BLs}),{hasNextPage:i,isFetchingNextPage:a,fetchNextPage:l,data:c,isLoading:u,isError:d,error:f}=s;return g.useEffect(()=>{n&&i&&!a&&l()},[n,i,a,l]),{data:c,hasNextPage:i,isFetchingNextPage:a,fetchNextPage:l,isLoading:u,isError:d,error:f,setEndOfListElement:r}},EB={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},Irn=[{label:"Agent",entityType:EB.AGENT},{label:"Workflow",entityType:EB.WORKFLOW},{label:"Scorer",entityType:EB.SCORER},{label:"Ingest",entityType:EB.INGEST}],VLs=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],P0="rootEntityType",Px="datePreset",$x="dateFrom",Mx="dateTo",qLs=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),Pl={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"},oF=Object.keys(Pl),lLe=new Set(["tags"]),cLe="mastra:logs:saved-filters";function HLs(e,t=cLe){const n=KLs(e),r=e.get(Px);r&&n.set(Px,r);const s=e.get($x);s&&n.set($x,s);const i=e.get(Mx);i&&n.set(Mx,i);try{localStorage.setItem(t,n.toString())}catch{}}function WLs(e=cLe){try{localStorage.removeItem(e)}catch{}}function tut(e=cLe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function ZLs(e){if(e.has(Px)||e.has($x)||e.has(Mx)||e.has(P0))return!0;for(const t of oF)if(e.has(Pl[t]))return!0;return!1}function GLs({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const i=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:Irn.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:VLs.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"}],a=(u,d)=>u.label.localeCompare(d.label),l=i.filter(u=>u.kind==="pick-multi").sort(a),c=i.filter(u=>u.kind==="text").sort(a);return[...l,...c]}function QLs(e){const t=[],n=new Map([[P0,"rootEntityType"]]);for(const s of oF)n.set(Pl[s],s);const r=new Set;for(const[s]of e.entries()){const i=n.get(s);if(!i||r.has(i))continue;if(r.add(i),lLe.has(i)){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:i,value:l.filter(Boolean)});continue}const a=e.get(s);a!==null&&t.push({fieldId:i,value:a})}return t}function KLs(e){const t=new URLSearchParams,n=e.get(P0);n&&t.set(P0,n);for(const r of oF){const s=Pl[r];if(lLe.has(r)){for(const a of e.getAll(s))t.append(s,a);continue}const i=e.get(s);i&&t.set(s,i)}return t}function YLs(e,t){e.delete(P0);for(const n of oF)e.delete(Pl[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(P0,n.value);continue}const r=Pl[n.fieldId];if(r){if(lLe.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 XLs({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 i of r){if(i.fieldId==="tags"){Array.isArray(i.value)&&i.value.length>0?s.tags=i.value:typeof i.value=="string"&&i.value.trim()&&(s.tags=[i.value.trim()]);continue}if(i.fieldId==="level"){typeof i.value=="string"&&i.value.trim()&&i.value!=="Any"&&(s.level=i.value);continue}if(typeof i.value=="string"&&i.value.trim()&&i.value!=="Any")switch(i.fieldId){case"entityName":s.rootEntityName=i.value;break;case"traceId":s.traceId=i.value;break;case"spanId":s.spanId=i.value;break;case"runId":s.runId=i.value;break;case"threadId":s.threadId=i.value;break;case"sessionId":s.sessionId=i.value;break;case"requestId":s.requestId=i.value;break;case"resourceId":s.resourceId=i.value;break;case"userId":s.userId=i.value;break;case"organizationId":s.organizationId=i.value;break;case"serviceName":s.serviceName=i.value;break;case"environment":s.environment=i.value;break;case"experimentId":s.experimentId=i.value;break}}return s}function JLs(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 e3s="Filters setting for Logs saved",t3s="Filters setting for Logs cleared up";function n3s(e,t,n){const{storageKey:r,messages:s,skipHydration:i}={},[a,l]=g.useState(()=>tut(r)!==null),c=g.useCallback(()=>{HLs(e,r),l(!0);const f=s?.saved??e3s;f!==!1&&Ge.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{WLs(r),l(!1);const f=s?.cleared??t3s;f!==!1&&Ge.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(i||d.current||(d.current=!0,ZLs(e)))return;const f=tut(r);f&&t(h=>{const p=new URLSearchParams(h);for(const[m,v]of f)p.append(m,v);return p},{replace:!0})},[]),{hasSavedFilters:a,handleSave:c,handleRemoveSaved:u}}function r3s(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 s3s(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,r3s(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function i3s(e,t,n,r){const s=g.useMemo(()=>s3s(e),[e]),i=g.useMemo(()=>{const p=new Map;for(const[m,v]of e.entries()){const y=s.get(v);y&&p.set(y,{log:v,idx:m})}return p},[e,s]),l=(t?i.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=g.useCallback(p=>s.get(p),[s]),d=g.useCallback(p=>{const m=s.get(p);if(m){if(t===m){n({logId:null});return}n(r?{logId:m,traceId:p.traceId??null,spanId:null}:{logId:m})}},[s,t,r,n]),f=l>0?()=>{const p=e[l-1];if(!p)return;const m=s.get(p);m&&n(r?{logId:m,traceId:p.traceId??null,spanId:null}:{logId:m})}:void 0,h=l>=0&&l<e.length-1?()=>{const p=e[l+1];if(!p)return;const m=s.get(p);m&&n(r?{logId:m,traceId:p.traceId??null,spanId:null}:{logId:m})}:void 0;return{logIdMap:s,getLogId:u,featuredLog:c,handleLogClick:d,handlePreviousLog:f,handleNextLog:h}}const Mke="logId",Dke="traceId",Lke="spanId",pM=1440*60*1e3,a3s={"last-24h":pM,"last-3d":3*pM,"last-7d":7*pM,"last-14d":14*pM,"last-30d":30*pM};function TB(e){e.delete(Mke),e.delete(Dke),e.delete(Lke)}function o3s(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const _=e.get(Px);return _&&qLs.has(_)?_:"last-24h"},[e]),i=e.get($x),a=e.get(Mx),l=g.useMemo(()=>{if(s==="custom"){if(!i)return;const C=new Date(i);return Number.isNaN(C.getTime())?void 0:C}if(s==="all")return;const _=a3s[s];return _?new Date(Date.now()-_):void 0},[s,i]),c=g.useMemo(()=>{if(s!=="custom"||!a)return;const _=new Date(a);return Number.isNaN(_.getTime())?void 0:_},[s,a]),u=g.useRef(s);u.current=s;const d=e.get(Mke),f=e.get(Dke),h=e.get(Lke),p=g.useMemo(()=>Irn.find(_=>_.entityType===e.get(P0)),[e]),m=g.useMemo(()=>QLs(e),[e]),v=g.useCallback(_=>{t(C=>{const T=new URLSearchParams(C);for(const[E,N]of Object.entries(_)){const I=E==="logId"?Mke:E==="traceId"?Dke:Lke;N?T.set(I,N):T.delete(I)}return T},{replace:!0})},[t]),y=g.useCallback(_=>{t(C=>{const T=new URLSearchParams(C);return YLs(T,_),TB(T),T},{replace:!0})},[t]),b=y,x=g.useCallback((_,C)=>{if(u.current!=="custom")return;const T=C==="from"?$x:Mx;t(E=>{const N=new URLSearchParams(E);return _?N.set(T,_.toISOString()):N.delete(T),TB(N),N},{replace:!0})},[t]),w=g.useCallback(_=>{u.current=_,t(C=>{const T=new URLSearchParams(C);return _==="last-24h"?(T.delete(Px),T.delete($x),T.delete(Mx)):_==="custom"?T.set(Px,"custom"):(T.set(Px,_),T.delete($x),T.delete(Mx)),TB(T),T},{replace:!0})},[t]),k=g.useCallback(()=>{t(_=>{const C=new URLSearchParams(_);C.delete(P0);for(const T of oF)C.delete(Pl[T]);return C.delete(Px),C.delete($x),C.delete(Mx),TB(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:h,selectedEntityOption:p,filterTokens:m,handleFeaturedChange:v,handleFilterTokensChange:b,handleDateChange:x,handleDatePresetChange:w,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,h,p,m,v,b,x,w,k,y])}const Gue=Ca.KeyValueList;function l3s({spanId:e,span:t,isLoading:n,onClose:r}){return o.jsxs(Ca,{children:[o.jsxs(Ca.Header,{children:[o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[o.jsxs(Ca.Heading,{className:"items-center",children:["Span",o.jsx(hJ,{id:e})]}),t&&o.jsx(mnn,{span:t})]}),o.jsx(Ca.CloseButton,{onClick:r})]}),n?o.jsx(Ca.LoadingData,{children:"Loading span..."}):t?o.jsxs(Ca.Content,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsxs(Gue,{children:[o.jsx(Gue.Key,{children:"Type"}),o.jsx(Gue.Value,{children:t.spanType})]}),o.jsx("br",{})]}),o.jsx(Sy,{title:"Error",raw:t.error,layout:"details",className:"mb-3",children:o.jsx(pnn,{span:t})}),o.jsx(Sy,{title:"Input",icon:o.jsx(eI,{}),raw:t.input,hasPreview:TDe(t)?.type!=="json",layout:"details",children:o.jsx(fnn,{span:t})}),o.jsx(Sy,{title:"Output",icon:o.jsx(Gx,{}),raw:t.output,hasPreview:jDe(t)?.type!=="json",layout:"details",children:o.jsx(hnn,{span:t})}),o.jsx(Sy,{title:"Metadata",icon:o.jsx(Bl,{}),raw:t.metadata,hasPreview:!1,layout:"details",children:null}),o.jsx(Sy,{title:"Attributes",icon:o.jsx(Bl,{}),raw:t.attributes,hasPreview:!1,layout:"details",children:null})]}):o.jsx(Ca.NoData,{children:"Span not found."})]})}function c3s({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:i}){const a=g.useMemo(()=>iF(t??[]),[t]),[l,c]=g.useState([]);g.useEffect(()=>{a.length>0&&c(pJ(a))},[a]);const u=d=>{s?.(i===d?void 0:d)};return o.jsxs(Ca,{children:[o.jsxs(Ca.Header,{children:[o.jsxs(Ca.Heading,{className:"items-center",children:["Trace",o.jsx(hJ,{id:e})]}),o.jsx(Ca.CloseButton,{onClick:r})]}),n?o.jsx(Ca.LoadingData,{children:"Loading trace..."}):a.length===0?o.jsx(Ca.NoData,{children:"No spans found for this trace."}):o.jsx(Ca.Content,{children:o.jsx(YDe,{hierarchicalSpans:a,onSpanClick:u,selectedSpanId:i??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}const Arn=()=>{const e=Ye();return yt({queryKey:["observability-service-names"],queryFn:async()=>{try{return await e.getServiceNames()}catch{return{serviceNames:[]}}},select:t=>t?.serviceNames??[],retry:!1,staleTime:nF})},Rrn=()=>{const e=Ye();return yt({queryKey:["observability-tags"],queryFn:async()=>{try{return await e.getTags()}catch{return{tags:[]}}},select:t=>t?.tags??[],retry:!1,staleTime:nF})};function u3s(){const[e,t]=bi(),n=o3s(e,t),r=n3s(e,t),[s,i]=g.useState(),[a,l]=g.useState(!1),{data:c=[],isPending:u}=Rrn(),{data:d=[],isPending:f}=zDe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:h=[],isPending:p}=BDe(),{data:m=[],isPending:v}=Arn(),y=g.useMemo(()=>GLs({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:h,loading:{tags:u,entityNames:f,serviceNames:v,environments:p}}),[c,d,m,h,u,f,v,p]),b=g.useMemo(()=>XLs({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:x=[],isLoading:w,error:k,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:T}=ULs({filters:b}),{logIdMap:E,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:P}=i3s(x,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:L,isLoading:M}=zE(n.featuredTraceId??null),{data:V,isLoading:q}=fJ(n.featuredTraceId??"",n.featuredSpanId??""),H=g.useCallback(()=>n.applyFilterTokens(JLs(y,n.filterTokens)),[y,n]),B=g.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),W=g.useCallback(Q=>n.handleFeaturedChange({traceId:Q,spanId:null}),[n]),z=g.useCallback((Q,ee)=>n.handleFeaturedChange({traceId:Q,spanId:ee}),[n]),G=g.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),F=g.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),R=g.useCallback(Q=>n.handleFeaturedChange({spanId:Q??null}),[n]),D=o.jsxs(Ft.TopArea,{children:[o.jsx(Ft.Row,{children:o.jsxs(Ft.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(n6,{preset:n.datePreset,onPresetChange:n.handleDatePresetChange,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,onDateChange:n.handleDateChange,disabled:w,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),o.jsx(Nrn,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:w,onStartTextFilter:i})]})}),o.jsx(ALs,{isLoading:w,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:H,onRemoveAll:n.handleRemoveAll,onSave:r.handleSave,onRemoveSaved:r.hasSavedFilters?r.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(k)return o.jsxs(Ft,{width:"wide",height:"full",children:[D,o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsx(wLs,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const U=!!n.selectedEntityOption||n.filterTokens.length>0;return x.length===0&&!w&&!U?o.jsxs(Ft,{width:"wide",height:"full",children:[D,o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsx(MLs,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Ft,{width:"wide",height:"full",children:[D,o.jsx(SLs,{logCollapsed:a,listSlot:o.jsx(ILs,{logs:x,isLoading:w,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:T,logIdMap:E,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(xLs,{log:N,onClose:B,onTraceClick:W,onSpanClick:z,onPrevious:A,onNext:P,collapsed:a,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(c3s,{traceId:n.featuredTraceId,spans:L?.spans,isLoading:M,onClose:G,onSpanSelect:R,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(l3s,{spanId:n.featuredSpanId,span:V?.span,isLoading:q,onClose:F}):null})]})}function d3s({server:e,rowProps:t}){const{paths:n,Link:r}=un(),i=Ye().options.baseUrl,a=i?`${i}/api/mcp/${e.id}/sse`:"",{data:l}=lXt(e),c=Object.values(l||{}),u=c.length,d=c.filter(p=>p.toolType==="agent").length,f=c.filter(p=>p.toolType==="workflow").length,h=af(e.name,50);return o.jsxs(we.RowLink,{to:n.mcpServerLink(e.id),LinkComponent:r,...t,children:[o.jsx(we.NameCell,{children:h}),o.jsx(we.DescriptionCell,{children:a}),o.jsx(we.TextCell,{className:"text-center",children:d||""}),o.jsx(we.TextCell,{className:"text-center",children:u||""}),o.jsx(we.TextCell,{className:"text-center",children:f||""})]})}function f3s({mcpServers:e,isLoading:t,search:n=""}){const r=g.useMemo(()=>{const a=n.toLowerCase();return e.filter(l=>l.name?.toLowerCase().includes(a)||l.id?.toLowerCase().includes(a))},[e,n]),{containerRef:s,getRowProps:i}=Zc({count:r.length,global:!0});return t?o.jsx(Wl,{columns:"auto 1fr auto auto auto"}):o.jsxs(we,{columns:"auto 1fr auto auto auto",scrollRef:s,children:[o.jsxs(we.Top,{children:[o.jsx(we.TopCell,{children:"Name"}),o.jsx(we.TopCell,{children:"URL"}),o.jsx(we.TopCellSmart,{long:"Agents",short:o.jsx(Ma,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(we.TopCellSmart,{long:"Tools",short:o.jsx(eh,{}),tooltip:"Tools",className:"text-center"}),o.jsx(we.TopCellSmart,{long:"Workflows",short:o.jsx(Bc,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(we.NoMatch,{message:"No MCP Servers match your search"}):null,r.map((a,l)=>o.jsx(d3s,{server:a,rowProps:i(l)},a.id))]})}const h3s=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ar,{iconSlot:o.jsx(Ls,{}),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.jsx(ae,{variant:"ghost",render:o.jsx("a",{href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer"}),icon:o.jsx(_s,{}),children:"MCP Documentation"})})}),p3s=()=>{const{data:e=[],isLoading:t,error:n}=UR(),[r,s]=g.useState("");return n&&ks(n)?o.jsx(Qn,{children:o.jsx(Gs,{})}):n&&Es(n)?o.jsx(Qn,{children:o.jsx(Fs,{resource:"MCP servers"})}):n?o.jsx(Qn,{children:o.jsx(Ws,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(Qn,{children:o.jsx(h3s,{})}):o.jsxs(Ft,{height:"full",children:[o.jsx(Ft.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx(Wc,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(f3s,{mcpServers:e,isLoading:t,search:r})]})},m3s=(e,t)=>{const n=new Map,r=Object.keys(t);for(const s of r){const i=t[s],a=i.tools,l=Object.keys(a);for(const c of l){const u=a[c];n.has(u.id)||n.set(u.id,{...u,agents:[]}),n.get(u.id).agents.push({...i,id:s})}}for(const[s,i]of Object.entries(e))n.has(i.id)||n.set(i.id,{...i,agents:[]});return Array.from(n.values())};function g3s({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:i}=un(),a=g.useMemo(()=>m3s(e,t),[e,t]),l=g.useMemo(()=>a.filter(d=>d.id.toLowerCase().includes(r.toLowerCase())),[a,r]),{containerRef:c,getRowProps:u}=Zc({count:l.length,global:!0});return n?o.jsx(Wl,{columns:"auto 1fr auto"}):o.jsxs(we,{columns:"auto 1fr auto",scrollRef:c,children:[o.jsxs(we.Top,{children:[o.jsx(we.TopCell,{children:"Name"}),o.jsx(we.TopCell,{children:"Description"}),o.jsx(we.TopCellSmart,{long:"Agents",short:o.jsx(Ma,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(we.NoMatch,{message:"No Tools match your search"}):null,l.map((d,f)=>{const h=af(d.id,50),p=af(d.description??"",200),m=d.agents.length;return o.jsxs(we.RowLink,{to:s.toolLink(d.id),LinkComponent:i,...u(f),children:[o.jsx(we.NameCell,{children:h}),o.jsx(we.DescriptionCell,{children:p}),o.jsx(we.TextCell,{className:"text-center",children:m||""})]},d.id)})]})}const v3s=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ar,{iconSlot:o.jsx(Ls,{}),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.jsx(ae,{variant:"ghost",render:o.jsx("a",{href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer"}),icon:o.jsx(_s,{}),children:"Tools Documentation"})})}),y3s=()=>{const e=Ye();return yn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new P_;Object.entries(r??{}).forEach(([i,a])=>{s.set(i,a)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(i){throw Ge.error("Error executing dev tool"),console.error("Error executing dev tool:",i),i}}})},b3s=({toolId:e})=>{const{canExecute:t}=No(),n=t("tools"),{data:r={}}=rh(),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:i,isLoading:a,error:l}=oQr(e,{enabled:!s}),c=s||i,{mutateAsync:u,isPending:d,data:f}=y3s(),{requestContext:h}=ys();g.useEffect(()=>{if(l){const v=l instanceof Error?l.message:"Failed to load tool";Ge.error(`Error loading tool: ${v}`)}},[l]);const p=async(v,y)=>{if(!c)return;const b={...h??{},...y??{}};return u({toolId:c.id,input:v,requestContext:b})},m=c?.inputSchema?Pm(m0(c?.inputSchema)):Nr({});return a?o.jsxs("div",{className:"p-4",children:[o.jsx(ut,{className:"mb-4 h-8 w-48"}),o.jsx(ut,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(G2e,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:p,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"px-4 py-8 text-center",children:o.jsx(Te,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})}):o.jsx("div",{className:"px-4 py-8 text-center",children:o.jsx(Te,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function x3s({value:e,onValueChange:t,placeholder:n="Select a tool...",searchPlaceholder:r="Search tools...",emptyText:s="No tools found.",className:i,disabled:a=!1,variant:l,size:c,"aria-label":u,align:d}){const{data:f={},isLoading:h,isError:p,error:m}=ER(),{data:v={},isLoading:y,isError:b,error:x}=rh(),{navigate:w,paths:k}=un();g.useEffect(()=>{if(p){const E=m instanceof Error?m.message:"Failed to load tools";Ge.error(`Error loading tools: ${E}`)}},[p,m]),g.useEffect(()=>{if(b){const E=x instanceof Error?x.message:"Failed to load agents";Ge.error(`Error loading agents: ${E}`)}},[b,x]);const _=new Map;Object.values(v).forEach(E=>{E.tools&&Object.values(E.tools).forEach(N=>{_.has(N.id)||_.set(N.id,N)})}),Object.values(f).forEach(E=>{_.has(E.id)||_.set(E.id,E)});const C=Array.from(_.values()).map(E=>({label:E.id,value:E.id})),T=E=>{t?t(E):E&&E!==e&&w(k.toolLink(E))};return o.jsx(qo,{options:C,value:e,onValueChange:T,placeholder:h||y?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:i,disabled:a||h||y||p||b,variant:l,size:c,"aria-label":u,align:d})}const w3s=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=g.useState({sseUrl:"",httpStreamUrl:""});if(g.useEffect(()=>{if(!t)return;const a=window.MASTRA_SERVER_HOST,l=window.MASTRA_SERVER_PORT;let c=null;a&&l&&(c=`http://${a}:${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(i0,{children:o.jsx(Te,{as:"h1",variant:"header-md",className:"text-neutral3 py-20 text-center font-medium",children:"Server not found"})});const i=`npx -y mcp-remote ${n}`;return o.jsxs(i0,{isDivided:!0,children:[o.jsxs("div",{className:"mx-auto w-full max-w-2xl px-5 py-8",children:[o.jsx(Te,{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-4",children:[o.jsx(jt,{icon:o.jsx(ynn,{}),size:"sm",children:"Version"}),o.jsx(jt,{size:"sm",children:t.version_detail.version})]}),o.jsx(Te,{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(jt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"HTTP"}),children:"Regular HTTP Endpoint"}),o.jsx(Te,{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(Te,{className:"bg-surface4 rounded-lg px-2 py-1",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx(ci,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(jt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"SSE"}),children:"Server-Sent Events"}),o.jsx(Te,{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(Te,{className:"bg-surface4 rounded-lg px-2 py-1",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx(ci,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(jt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"CLI"}),children:"Command Line"}),o.jsx(Te,{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(Te,{className:"bg-surface4 rounded-lg px-2 py-1",children:i}),o.jsx("div",{className:"pt-1",children:o.jsx(ci,{tooltip:"Copy Command Line Config",content:i})})]})]})]})]}),o.jsx("div",{className:"border-border1 h-full overflow-y-scroll border-l",children:o.jsx(S3s,{server:t})})]})},S3s=({server:e})=>{const{data:t={},isLoading:n}=lXt(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(St,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(ME,{})}),o.jsx(Te,{variant:"header-md",as:"h2",className:"font-medium",children:"Available Tools"})]}),o.jsx("div",{className:"flex flex-col gap-2 pt-4",children:r.map(s=>{const i=t[s];return o.jsx(O3s,{tool:i,serverId:e.id},s)})})]})};function k3s(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 O3s=({tool:e,serverId:t})=>{const n=g.useRef(null),{Link:r,paths:s}=un(),i=e.toolType==="agent"?iU.agent:e.toolType==="workflow"?iU.workflow:iU.tool,a=k3s(e._meta);return o.jsxs(ih,{onClick:()=>n.current?.click(),children:[o.jsx(aVt,{children:o.jsx(i,{className:"group-hover/entity:text-accent6"})}),o.jsxs(oh,{children:[o.jsx(ah,{children:o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(r,{ref:n,href:s.mcpServerToolLink(t,e.name),children:e.name}),a&&o.jsx(jt,{size:"xs",children:"App"})]})}),o.jsx(kp,{children:e.description})]})]})},C3s=()=>{const{serverId:e}=ur(),{data:t=[],isLoading:n}=UR(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(w3s,{isLoading:n,server:r})})};function _3s(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 E3s=({toolId:e,serverId:t})=>{const{canExecute:n}=No(),r=n("tools"),s=Ye(),{data:i,isLoading:a,error:l}=P2e(t,e),{mutateAsync:c,isPending:u,data:d}=I0s(t,e),f=i?_3s(i._meta):void 0,{data:h}=yt({queryKey:["mcp-app-resource",t,f],queryFn:async()=>f?(await s.readMcpServerResource(t,f)).contents[0]?.text??null:null,enabled:!!f}),p=g.useCallback(async(y,b)=>await c(b),[c]);g.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";Ge.error(`Error loading tool: ${y}`)}},[l]);const m=async y=>{if(i)return await c(y)};if(a)return o.jsxs("div",{className:"p-4",children:[o.jsx(ut,{className:"mb-4 h-8 w-48"}),o.jsx(ut,{className:"h-32 w-full"})]});if(l)return null;if(!i)return o.jsx("div",{className:"px-4 py-8 text-center",children:o.jsx(Te,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"px-4 py-8 text-center",children:o.jsx(Te,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let v;try{v=Pm(i.inputSchema)}catch(y){console.error("Error processing input schema:",y),Ge.error("Failed to process tool input schema."),v=Nr({})}return o.jsxs("div",{className:"flex flex-col gap-4",children:[h&&o.jsx("div",{className:"border-border1 border-b p-4",children:o.jsx(oXt,{html:h,toolName:i.name,onToolCall:p})}),o.jsx(G2e,{executionResult:d,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:m,toolDescription:i.description||"",toolId:i.name})]})},T3s=()=>{const{serverId:e,toolId:t}=ur(),{data:n,isLoading:r}=P2e(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(E3s,{toolId:t,serverId:e})})},Prn=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],yA="rootEntityType",bA={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"},bJ=Object.keys(bA),uLe="mastra:metrics:saved-filters";function j3s(e){const t=R3s(e);try{localStorage.setItem(uLe,t.toString())}catch{}}function N3s(){try{localStorage.removeItem(uLe)}catch{}}function $rn(){try{const e=localStorage.getItem(uLe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function I3s(e){if(e.has(yA))return!0;for(const t of bJ)if(e.has(bA[t]))return!0;return!1}function Mrn({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const i=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:Prn.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"}],a=(u,d)=>u.label.localeCompare(d.label),l=i.filter(u=>u.kind==="pick-multi").sort(a),c=i.filter(u=>u.kind==="text").sort(a);return[...l,...c]}function A3s(e){const t=[],n=new Map([[yA,"rootEntityType"]]);for(const s of bJ)n.set(bA[s],s);const r=new Set;for(const[s]of e.entries()){const i=n.get(s);if(!i||r.has(i))continue;if(r.add(i),i==="tags"){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:i,value:l.filter(Boolean)});continue}if(i==="rootEntityType"||i==="entityName"||i==="serviceName"||i==="environment"||i==="provider"||i==="model"){const l=e.getAll(s);if(l.length>1){t.push({fieldId:i,value:l});continue}}const a=e.get(s);a!==null&&t.push({fieldId:i,value:a})}return t}function R3s(e){const t=new URLSearchParams,n=e.getAll(yA);for(const r of n)t.append(yA,r);for(const r of bJ){const s=bA[r],i=e.getAll(s);for(const a of i)t.append(s,a)}return t}function P3s(e,t){e.delete(yA);for(const n of bJ)e.delete(bA[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?yA:bA[n.fieldId];if(r)if(Array.isArray(n.value)){const s=n.value.filter(i=>typeof i=="string"&&i!=="");if(s.length===0){n.fieldId==="tags"&&e.append(r,"");continue}for(const i of s)e.append(r,i)}else typeof n.value=="string"&&e.set(r,n.value.trim())}}const $3s="Any";function nut(e){const t=e.trim();return t===""||t===$3s}const M3s=new Set(Prn.map(e=>e.entityType));function rut(e){const t=e.trim();return M3s.has(t)?t:void 0}function D3s(e){const t={};for(const n of e){const r=n.fieldId;if(Array.isArray(n.value)){const s=n.value.filter(i=>typeof i=="string").map(i=>i.trim()).filter(i=>!nut(i));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const i=s[0],a=i!==void 0?rut(i):void 0;a&&(t.rootEntityType=a)}else t[r]=s[0]}else if(typeof n.value=="string"){if(nut(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const i=rut(s);i&&(t.rootEntityType=i)}else t[r]=s}}return t}const Drn=[{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"}],L3s=new Set(Drn.map(e=>e.value));function F3s(e){return typeof e=="string"&&(L3s.has(e)||e==="custom")}const Lrn=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function xJ(){return g.useContext(Lrn)}function z3s(e,t){return e!=="custom"?Drn.find(n=>n.value===e)?.label??e:t?.from?t.to?`${gr(t.from,"MMM d, yyyy")} – ${gr(t.to,"MMM d, yyyy")}`:gr(t.from,"MMM d, yyyy"):"Custom range"}function B3s({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:i,onCustomRangeChange:a,tracesBasePath:l,logsBasePath:c}){const u=g.useMemo(()=>JSON.stringify(n),[n]),d=g.useMemo(()=>n,[u]),f=g.useMemo(()=>D3s(d),[d]),h=g.useMemo(()=>JSON.stringify(f),[f]),p=z3s(t,i),m=g.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:i,setCustomRange:a??(()=>{}),dateRangeLabel:p,filterTokens:d,setFilterTokens:s,dimensionalFilter:f,dimensionalFilterKey:h,tracesBasePath:l,logsBasePath:c}),[t,r,i,a,p,d,s,f,h,l,c]);return o.jsx(Lrn.Provider,{value:m,children:e})}const Fke=1440*60*1e3,U3s={"24h":Fke,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function V3s(e,t,n){if(e!=="custom"){const r=U3s[e]??Fke;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-Fke),end:t?.to??new Date(n)}}function og(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=xJ(),s=g.useRef(null),i=e==="custom"?`custom:${t?.from?.getTime()??""}:${t?.to?.getTime()??""}`:`preset:${e}`;(!s.current||s.current.key!==i)&&(s.current={key:i,anchor:Date.now()});const a=s.current.anchor,l=g.useMemo(()=>V3s(e,t,a),[e,t,a]),c=g.useMemo(()=>({timestamp:l,...n}),[l,r]),u=g.useMemo(()=>`${i}|${r}`,[i,r]);return{datePreset:e,customRange:t,timestamp:l,filters:c,dimensionalFilter:n,filterKey:u}}function Frn(){const e=Ye(),{filters:t,filterKey:n}=og();return yt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function lF({href:e,LinkComponent:t="a"}){return o.jsx(ae,{render:o.jsx(t,{href:e}),variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(ko,{})})}function q3s({href:e,LinkComponent:t="a"}){return o.jsx(ae,{render:o.jsx(t,{href:e}),variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(ORn,{})})}function H3s(e){return e==="agents"||e==="workflows"||e==="tools"}function sut(e,t){if(e.length===0)return"0";const n=e.reduce((r,s)=>{const i=s[t];return r+(typeof i=="number"&&Number.isFinite(i)?i:0)},0);return`${Math.round(n/e.length)}`}function W3s(e){const t=e;return typeof t?.tsMs=="number"&&Number.isFinite(t.tsMs)}const Z3s=[{dataKey:"p50",label:"p50",color:cp.blue,aggregate:e=>({value:sut(e,"p50"),suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:cp.yellow,aggregate:e=>({value:sut(e,"p95"),suffix:"avg ms"})}];function Que({data:e,onPointClick:t}){return e.length===0?o.jsx(Ht.NoData,{message:"No latency data yet"}):o.jsx(vZ,{data:e,series:Z3s,onPointClick:t?n=>W3s(n)?t(n):void 0:void 0})}function G3s({data:e,isLoading:t,isError:n,onPointClick:r,actions:s}){const i=(e?.agentData.length??0)>0,a=(e?.workflowData.length??0)>0,l=(e?.toolData.length??0)>0,c={agents:i,workflows:a,tools:l},u=i?"agents":a?"workflows":l?"tools":"agents",[d,f]=g.useState("agents"),h=c[d]?d:u,p=typeof s=="function"?s(h):s,m=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),v=e?Object.values(e).filter(Array.isArray).flat().map(b=>b.p50).filter(b=>typeof b=="number"):[],y=v.length>0?`${Math.round(v.reduce((b,x)=>b+x,0)/v.length)}ms`:"—";return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(Ht.Summary,{value:y,label:"Avg p50"}),p?o.jsx(Ht.Actions,{children:p}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load latency data"}):o.jsx(Ht.Content,{children:m?o.jsxs(hl,{value:h,onValueChange:b=>{H3s(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(fl,{children:[o.jsx(Sr,{value:"agents",disabled:!i,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(Sr,{value:"workflows",disabled:!a,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(Sr,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(ts,{value:"agents",children:o.jsx(Que,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(ts,{value:"workflows",children:o.jsx(Que,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(ts,{value:"tools",children:o.jsx(Que,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Ht.NoData,{message:"No latency data yet"})})]})}function Q3s(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 K3s(e,t){if(t==="1h"){const s=new Date(e);s.setUTCMinutes(0,0,0);const i=new Date(s.getTime()+3600*1e3);return{from:s,to:i}}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 zrn(e,t,n,r,s,i,a){if(a){e.set(t,"custom"),e.set(n,a.from.toISOString()),e.set(r,a.to.toISOString());return}if(s==="custom"){e.set(t,"custom"),i?.from&&e.set(n,i.from.toISOString()),i?.to&&e.set(r,i.to.toISOString());return}const l=Q3s(s);l&&e.set(t,l)}function Lo(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function Brn(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function iut({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const i=new URLSearchParams;i.set(TS,"branches"),zrn(i,jS,cS,uS,e,t,r.window);const a=r.rootEntityType??n.rootEntityType;a&&i.set(A0,a),r.status&&i.set(R0,r.status),Lo(i,Rl.entityName,r.entityName??n.entityName),Lo(i,Rl.threadId,r.threadId??n.threadId),Lo(i,Rl.resourceId,r.resourceId??n.resourceId),Lo(i,Rl.entityId,n.entityId),Lo(i,Rl.runId,n.runId),Lo(i,Rl.sessionId,n.sessionId),Lo(i,Rl.requestId,n.requestId),Lo(i,Rl.userId,n.userId),Lo(i,Rl.organizationId,n.organizationId),Lo(i,Rl.experimentId,n.experimentId),Lo(i,Rl.serviceName,n.serviceName),Lo(i,Rl.environment,n.environment),Brn(i,Rl.tags,n.tags);const l=i.toString();return l?`${s}?${l}`:s}function Y3s({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const i=new URLSearchParams;zrn(i,Px,$x,Mx,e,t,r.window);const a=r.rootEntityType??n.rootEntityType;a&&i.set(P0,a),Lo(i,Pl.entityName,r.entityName??n.entityName),Lo(i,Pl.threadId,r.threadId??n.threadId),Lo(i,Pl.resourceId,r.resourceId??n.resourceId),Lo(i,Pl.runId,n.runId),Lo(i,Pl.sessionId,n.sessionId),Lo(i,Pl.requestId,n.requestId),Lo(i,Pl.userId,n.userId),Lo(i,Pl.organizationId,n.organizationId),Lo(i,Pl.experimentId,n.experimentId),Lo(i,Pl.serviceName,n.serviceName),Lo(i,Pl.environment,n.environment),Brn(i,Pl.tags,n.tags),r.status==="error"&&i.append(Pl.level,"error");const l=i.toString();return l?`${s}?${l}`:s}function tP(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=xJ(),i=g.useCallback((c={})=>iut({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),a=g.useCallback((c={})=>Y3s({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=K3s(u,d);return iut({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:i,getLogsHref:a,getBucketTracesHref:l}}const Urn="1h";async function Kue(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:Urn,filters:n}),s=r.series.find(l=>l.percentile===.5),i=r.series.find(l=>l.percentile===.95);if(!s||!i)return[];const a=new Map(i.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(a.get(u)??0)}})}function X3s(){const e=Ye(),{filters:t,filterKey:n}=og();return yt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,i]=await Promise.all([Kue(e,"mastra_agent_duration_ms",t),Kue(e,"mastra_workflow_duration_ms",t),Kue(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:i,interval:Urn}}})}const aut={agents:Yu.AGENT,workflows:Yu.WORKFLOW_RUN,tools:Yu.TOOL};function J3s(){const{data:e,isLoading:t,isError:n}=X3s(),{getTracesHref:r,getBucketTracesHref:s}=tP(),{Link:i}=un(),a=Fr();return o.jsx(G3s,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&a(s({rootEntityType:aut[l]},c.tsMs,"1h"))},actions:l=>o.jsx(lF,{href:r({rootEntityType:aut[l]}),LinkComponent:i})})}function e4s(e){return e==="threads"||e==="resources"}function Yue(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function t4s({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:i}){const[a,l]=g.useState("threads"),c=e.data?.map(y=>({...y,key:y.threadId}))??[],u=t.data?.map(y=>({...y,key:y.resourceId}))??[],d=c.length>0,f=u.length>0,h=e.data?.reduce((y,b)=>y+b.runs,0)??0,p=t.data?.reduce((y,b)=>y+b.threadCount,0)??0,m=a==="threads"?e:t,v=typeof s=="function"?s(a):s;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),a==="threads"&&d&&o.jsx(Ht.Summary,{value:h.toLocaleString(),label:"Total runs"}),a==="resources"&&f&&o.jsx(Ht.Summary,{value:p.toLocaleString(),label:"Total threads"}),v?o.jsx(Ht.Actions,{children:v}):null]}),m.isLoading?o.jsx(Ht.Loading,{}):m.isError?o.jsx(Ht.Error,{message:"Failed to load memory data"}):o.jsx(Ht.Content,{children:o.jsxs(hl,{defaultTab:"threads",value:a,onValueChange:y=>{e4s(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(fl,{children:[o.jsx(Sr,{value:"threads",children:"Threads"}),o.jsx(Sr,{value:"resources",children:"Resources"})]}),o.jsx(ts,{value:"threads",children:d?o.jsxs(we,{columns:"auto auto auto auto auto",...Oke,children:[o.jsxs(we.Top,{children:[o.jsx(we.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(we.RowHeaderCell,{className:"text-ui-sm",children:Yue(y.threadId)}),o.jsx(we.NumberCell,{children:y.resourceId?Yue(y.resourceId):"—"}),o.jsx(we.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(we.NumberCell,{children:y.tokens>0?lo(y.tokens):"—"}),o.jsx(we.NumberCell,{children:y.cost!=null?Zd(y.cost,y.costUnit):"—"})]});return b?o.jsx(we.RowLink,{to:b,LinkComponent:i,children:x},y.key):o.jsx(we.RowStatic,{children:x},y.key)})]}):o.jsx(Ht.NoData,{message:"No thread activity yet"})}),o.jsx(ts,{value:"resources",children:f?o.jsxs(we,{columns:"auto auto auto auto",...Oke,children:[o.jsxs(we.Top,{children:[o.jsx(we.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(we.RowHeaderCell,{className:"text-ui-sm",children:Yue(y.resourceId)}),o.jsx(we.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(we.NumberCell,{children:y.tokens>0?lo(y.tokens):"—"}),o.jsx(we.NumberCell,{children:y.cost!=null?Zd(y.cost,y.costUnit):"—"})]});return b?o.jsx(we.RowLink,{to:b,LinkComponent:i,children:x},y.key):o.jsx(we.RowStatic,{children:x},y.key)})]}):o.jsx(Ht.NoData,{message:"No resource activity yet"})})]})})]})}const Xue=20;function n4s(){const e=Ye(),{filters:t,filterKey:n}=og();return yt({queryKey:["metrics","top-active-threads",n],queryFn:async()=>{const r={groupBy:["threadId","resourceId"],orderDirection:"DESC",filters:t},[s,i,a]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count",limit:Xue}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:Xue}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:Xue})]),l=new Map,c=d=>XR(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const h=f.dimensions.threadId;if(!h)continue;const p=c(h);p.tokens+=f.value,f.estimatedCost!=null&&(p.cost=(p.cost??0)+f.estimatedCost,f.costUnit&&(p.costUnit=f.costUnit))}};return u(i.groups),u(a.groups),s.groups.filter(d=>!!d.dimensions.threadId).map(d=>{const f=d.dimensions.threadId,h=l.get(f);return{threadId:f,resourceId:d.dimensions.resourceId??null,runs:d.value,tokens:h?.tokens??0,cost:h?.cost??null,costUnit:h?.costUnit??null}})}})}const Jue=20;function r4s(){const e=Ye(),{filters:t,filterKey:n}=og();return yt({queryKey:["metrics","top-resources-by-threads",n],queryFn:async()=>{const r={groupBy:["resourceId"],orderDirection:"DESC",filters:t},[s,i,a]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",limit:Jue}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:Jue}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:Jue})]),l=new Map,c=d=>XR(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const h=f.dimensions.resourceId;if(!h)continue;const p=c(h);p.tokens+=f.value,f.estimatedCost!=null&&(p.cost=(p.cost??0)+f.estimatedCost,f.costUnit&&(p.costUnit=f.costUnit))}};return u(i.groups),u(a.groups),s.groups.filter(d=>!!d.dimensions.resourceId).map(d=>{const f=d.dimensions.resourceId,h=l.get(f);return{resourceId:f,threadCount:d.value,tokens:h?.tokens??0,cost:h?.cost??null,costUnit:h?.costUnit??null}})}})}function s4s(){const e=n4s(),t=r4s(),{getTracesHref:n}=tP(),{Link:r}=un();return o.jsx(t4s,{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 cF({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:i}){const a=t!=null;return o.jsxs(Mr,{children:[o.jsx(Mr.Label,{children:e}),o.jsx(Mr.Value,{className:a?void 0:"invisible",children:a?t:"—"}),i?o.jsx(Mr.Error,{}):s?o.jsx(Mr.Loading,{}):a?r!=null?o.jsx(Mr.Change,{changePct:r,prevValue:n}):o.jsx(Mr.NoChange,{}):o.jsx(Mr.NoData,{})]})}function i4s(){const e=Ye(),{filters:t,filterKey:n}=og();return yt({queryKey:["metrics","active-resources-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"resourceId",filters:t,comparePeriod:"previous_period"})})}function a4s(){const e=Ye(),{filters:t,filterKey:n}=og();return yt({queryKey:["metrics","active-threads-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",filters:t,comparePeriod:"previous_period"})})}function o4s(){const e=Ye(),{filters:t,filterKey:n}=og();return yt({queryKey:["metrics","model-cost-kpi",n],queryFn:async()=>{const r=await e.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"});return{cost:r.estimatedCost??null,costUnit:r.costUnit??null,previousCost:r.previousEstimatedCost??null,costChangePercent:r.costChangePercent??null}}})}function l4s(){const e=Ye(),{filters:t,filterKey:n}=og();return yt({queryKey:["metrics","total-tokens-kpi",n],queryFn:async()=>{const[r,s]=await Promise.all([e.getMetricAggregate({name:["mastra_model_total_input_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"}),e.getMetricAggregate({name:["mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"})]),i=r.value!=null||s.value!=null,a=r.previousValue!=null||s.previousValue!=null,l=(r.value??0)+(s.value??0),c=(r.previousValue??0)+(s.previousValue??0),u=a&&c>0?(l-c)/c*100:null;return{value:i?l:null,previousValue:a?c:null,changePercent:u}}})}function c4s(){const{data:e,isLoading:t,isError:n}=Frn();return o.jsx(cF,{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 u4s(){const{data:e,isLoading:t,isError:n}=o4s();return o.jsx(cF,{label:"Total Model Cost",value:e?.cost!=null?Zd(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?Zd(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function d4s(){const{data:e,isLoading:t,isError:n}=l4s();return o.jsx(cF,{label:"Total Tokens",value:e?.value!=null?lo(e.value):null,prevValue:e?.previousValue!=null?lo(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function f4s(){const{data:e,isLoading:t,isError:n}=a4s();return o.jsx(cF,{label:"Total Threads",value:e?.value!=null?lo(e.value):null,prevValue:e?.previousValue!=null?lo(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function h4s(){const{data:e,isLoading:t,isError:n}=i4s();return o.jsx(cF,{label:"Total Resources",value:e?.value!=null?lo(e.value):null,prevValue:e?.previousValue!=null?lo(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}const p4s=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function m4s(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 g4s(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 v4s(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=xJ(),s=g.useRef(e);s.current=e;const i=g.useRef(n);return i.current=n,o.jsx(n6,{preset:m4s(e),onPresetChange:a=>{const l=g4s(a);s.current=l,t(l)},dateFrom:n?.from,dateTo:n?.to,onDateChange:(a,l)=>{if(s.current!=="custom")return;const c={...i.current,[l]:a};i.current=c,r(c)},presets:p4s})}function y4s({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:i,filterTokens:a,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=a.length>0,d=a.some(f=>b4s(f,i));return u?o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(Trn,{fields:i,tokens:a,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(_rn,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function b4s(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 zke({children:e,filterFields:t,isLoading:n=!1}){const[r]=bi(),{filterTokens:s,setFilterTokens:i}=xJ(),[a,l]=g.useState(),[c,u]=g.useState(()=>!!$rn()),d=()=>{j3s(r),u(!0),Ge.success("Filters setting for Metrics saved")},f=()=>{N3s(),u(!1),Ge.success("Filters setting for Metrics cleared up")},h=()=>{const p=s.map(m=>{const v=t.find(y=>y.id===m.fieldId);return v?v.kind==="text"?{fieldId:m.fieldId,value:""}:v.kind==="pick-multi"?v.multi?{fieldId:m.fieldId,value:[]}:{fieldId:m.fieldId,value:"Any"}:v.kind==="multi-select"?{fieldId:m.fieldId,value:[]}:m:m});i(p)};return o.jsxs(Ft,{width:"wide",height:"full",children:[o.jsxs(Ft.TopArea,{children:[o.jsx(Ft.Row,{children:o.jsxs(Ft.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(v4s,{}),o.jsx(Nrn,{fields:t,tokens:s,onTokensChange:i,disabled:n,onStartTextFilter:l})]})}),o.jsx(y4s,{isLoading:n,filterFields:t,filterTokens:s,onFilterTokensChange:i,onClear:h,onRemoveAll:()=>i([]),onSave:d,onRemoveSaved:c?f:void 0,autoFocusFilterFieldId:a})]}),e]})}function x4s({error:e}){return ks(e)?o.jsx(Gs,{}):Es(e)?o.jsx(Fs,{resource:"metrics"}):o.jsx(Ws,{title:"Failed to load storage capabilities",message:e.message})}const out=Mrn({availableTags:[],availableEntityNames:[],availableServiceNames:[],availableEnvironments:[]});function w4s({children:e}){const{supportsMetrics:t,isLoading:n,error:r}=rF();return n?o.jsx(zke,{filterFields:out,isLoading:!0,children:o.jsxs("div",{className:"flex h-full items-center justify-center gap-2",children:[o.jsx(_n,{"aria-label":"Loading storage capabilities"}),o.jsx("span",{className:"text-ui-sm text-neutral4",children:"Loading storage capabilities"})]})}):r?o.jsx(Qn,{children:o.jsx(x4s,{error:r})}):t?e:o.jsx(zke,{filterFields:out,children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ar,{iconSlot:o.jsx(Ls,{}),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.jsx(ae,{variant:"ghost",render:o.jsx("a",{href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer"}),icon:o.jsx(_s,{}),children:"Metrics Documentation"})})})})}function S4s({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:i}){const a=!!e&&e.length>0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Model Usage & Cost",description:"Token consumption by model."}),a&&(()=>{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?Zd(l):"—":c.size===1?u=l>0?Zd(l,[...c][0]):"—":u="Mixed",o.jsx(Ht.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(Ht.Actions,{children:s}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load model usage data"}):o.jsx(Ht.Content,{children:a?o.jsxs(we,{columns:"auto auto auto auto auto auto",...Oke,children:[o.jsxs(we.Top,{children:[o.jsx(we.TopCell,{sticky:"start",children:"Model"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(we.RowHeaderCell,{className:"text-ui-sm",children:l.model}),o.jsx(we.NumberCell,{children:l.input}),o.jsx(we.NumberCell,{children:l.output}),o.jsx(we.NumberCell,{children:l.cacheRead}),o.jsx(we.NumberCell,{children:l.cacheWrite}),o.jsx(we.NumberCell,{highlight:!0,children:l.cost!=null?Zd(l.cost,l.costUnit):"—"})]});return c?o.jsx(we.RowLink,{to:c,LinkComponent:i,children:u},l.model):o.jsx(we.RowStatic,{children:u},l.model)})]}):o.jsx(Ht.NoData,{message:"No model usage data yet"})})]})}function k4s(){const e=Ye(),{filters:t,filterKey:n}=og();return yt({queryKey:["metrics","model-usage-cost",n],queryFn:async()=>{const[r,s,i,a]=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||!i||!a)return[];const l=new Map,c=d=>XR(l,d,()=>({input:0,output:0,cacheRead:0,cacheWrite:0,cost:null,costUnit:null})),u=(d,f)=>{f.estimatedCost!=null&&(d.cost=(d.cost??0)+f.estimatedCost,f.costUnit&&(d.costUnit=f.costUnit))};for(const d of r.groups){const f=d.dimensions.model??"unknown",h=c(f);h.input=d.value,u(h,d)}for(const d of s.groups){const f=d.dimensions.model??"unknown",h=c(f);h.output=d.value,u(h,d)}for(const d of i.groups){const f=d.dimensions.model??"unknown",h=c(f);h.cacheRead=d.value}for(const d of a.groups){const f=d.dimensions.model??"unknown",h=c(f);h.cacheWrite=d.value}return Array.from(l.entries()).map(([d,f])=>({model:d,input:lo(f.input),output:lo(f.output),cacheRead:lo(f.cacheRead),cacheWrite:lo(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function O4s(){const{data:e,isLoading:t,isError:n}=k4s(),{getTracesHref:r}=tP(),{Link:s}=un();return o.jsx(S4s,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:Yu.AGENT}),actions:o.jsx(lF,{href:r({rootEntityType:Yu.AGENT}),LinkComponent:s})})}function C4s(e){return e==="tokens"||e==="cost"}function _4s({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:i}){const[a,l]=g.useState("tokens"),c=e??[],u=c.length>0,d=c.reduce((b,x)=>b+x.total,0),f=c.filter(b=>b.cost!=null&&b.cost>0),h=new Set(f.map(b=>b.costUnit??"usd")),p=h.size<=1,m=p?[...h][0]??"usd":null,v=p?f.reduce((b,x)=>b+(x.cost??0),0):0,y=p&&v>0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(a==="cost"&&y?o.jsx(Ht.Summary,{value:Zd(v,m),label:"Total cost"}):o.jsx(Ht.Summary,{value:lo(d),label:"Total tokens"})),u&&s?o.jsx(Ht.Actions,{children:s}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load token usage data"}):o.jsx(Ht.Content,{children:u?o.jsxs(hl,{defaultTab:"tokens",value:a,onValueChange:b=>{C4s(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(fl,{children:[o.jsx(Sr,{value:"tokens",children:"Tokens"}),o.jsx(Sr,{value:"cost",children:"Cost"})]}),o.jsx(ts,{value:"tokens",children:o.jsx(vA,{LinkComponent:i,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:cp.blueDark},{label:"Output",color:cp.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:lo})}),o.jsx(ts,{value:"cost",children:y?o.jsx(vA,{LinkComponent:i,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:cp.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>Zd(b,m)}):o.jsx(Ht.NoData,{message:"No cost data yet"})})]}):o.jsx(Ht.NoData,{message:"No token usage data yet"})})]})}function E4s(){const e=Ye(),{filters:t,filterKey:n}=og();return yt({queryKey:["metrics","token-usage-by-agent",n],queryFn:async()=>{const r={groupBy:["entityName"],aggregation:"sum",orderDirection:"DESC",filters:t},[s,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"]}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"]})]),a=new Map,l=u=>XR(a,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 i.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.output=u.value,c(f,u)}return Array.from(a.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 T4s(){const{data:e,isLoading:t,isError:n}=E4s(),{getTracesHref:r}=tP(),{Link:s}=un();return o.jsx(_4s,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:i=>r({rootEntityType:Yu.AGENT,entityName:i.name}),actions:o.jsx(lF,{href:r({rootEntityType:Yu.AGENT}),LinkComponent:s})})}function Bke(e,t=lo){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const j4s=[{dataKey:"input",label:"Input tokens",color:cp.blue,aggregate:Bke("input")},{dataKey:"output",label:"Output tokens",color:cp.yellow,aggregate:Bke("output")}];function N4s(e){return e==="tokens"||e==="cost"}function I4s({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[i,a]=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),h=f.map(k=>({...k})),p=new Set(f.map(k=>k.costUnit).filter(k=>!!k)),m=p.size===1&&f.every(k=>k.costUnit!=null),v=m?[...p][0]??null:null,y=m?f.reduce((k,_)=>k+(_.cost??0),0):0,b=m&&y>0,x=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",w=[{dataKey:"cost",label:"Cost",color:cp.purple,aggregate:Bke("cost",k=>Zd(k,v))}];return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Token usage over time",description:x}),u&&(i==="cost"&&b?o.jsx(Ht.Summary,{value:Zd(y,v),label:"Total cost"}):o.jsx(Ht.Summary,{value:lo(d),label:"Total tokens"})),u&&s?o.jsx(Ht.Actions,{children:s}):null]}),n?o.jsx(Ht.Loading,{}):r?o.jsx(Ht.Error,{message:"Failed to load token usage timeline"}):o.jsx(Ht.Content,{children:u?o.jsxs(hl,{defaultTab:"tokens",value:i,onValueChange:k=>{N4s(k)&&a(k)},className:"overflow-visible",children:[o.jsxs(fl,{children:[o.jsx(Sr,{value:"tokens",children:"Tokens"}),o.jsx(Sr,{value:"cost",children:"Cost"})]}),o.jsx(ts,{value:"tokens",children:o.jsx(vZ,{data:c,series:j4s})}),o.jsx(ts,{value:"cost",children:b?o.jsx(vZ,{data:h,series:w}):o.jsx(Ht.NoData,{message:"No cost data yet"})})]}):o.jsx(Ht.NoData,{message:"No token usage data yet"})})]})}function A4s(e){return e==="24h"?"1h":"1d"}function R4s(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 lut(e,t,n){for(const r of t?.points??[]){const s=new Date(r.timestamp).getTime();if(!Number.isFinite(s))continue;const i=e.get(s)??{tsMs:s,input:0,output:0,cost:null,costUnits:new Set,hasUnknownCostUnit:!1};i[n]+=r.value,r.estimatedCost!=null&&(i.cost=(i.cost??0)+r.estimatedCost,t?.costUnit?i.costUnits.add(t.costUnit):i.hasUnknownCostUnit=!0),e.set(s,i)}}function P4s(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function $4s(){const e=Ye(),{datePreset:t,filters:n,filterKey:r}=og(),s=A4s(t);return yt({queryKey:["metrics","token-usage-timeseries",r,s],queryFn:async()=>{const[i,a]=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 lut(l,i.series[0],"input"),lut(l,a.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:R4s(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:P4s(u)}}),interval:s}}})}function M4s(){const{data:e,isLoading:t,isError:n}=$4s(),{getTracesHref:r}=tP(),{Link:s}=un();return o.jsx(I4s,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(lF,{href:r(),LinkComponent:s})})}function ede({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(vA,{LinkComponent:r,data:e.map(s=>{const i=n?.(s),a=t?.(s);return i?{name:s.name,values:[s.completed,s.errors],hrefs:[a,i]}:{name:s.name,values:[s.completed,s.errors],href:a}}),segments:[{label:"Completed",color:cp.blueDark},{label:"Errors",color:cp.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:lo})}function D4s({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:i,LinkComponent:a}){const[l,c]=g.useState("agents"),u=typeof i=="function"?i(l):i,d=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),f=e?[...e.agentData,...e.workflowData,...e.toolData].reduce((m,v)=>m+v.completed+v.errors,0):0,h=m=>r?v=>r(m,v):void 0,p=m=>s?v=>s(m,v):void 0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(Ht.Summary,{value:lo(f),label:"Total runs"}),u?o.jsx(Ht.Actions,{children:u}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load trace volume data"}):o.jsx(Ht.Content,{children:d?o.jsxs(hl,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(fl,{children:[o.jsx(Sr,{value:"agents",children:"Agents"}),o.jsx(Sr,{value:"workflows",children:"Workflows"}),o.jsx(Sr,{value:"tools",children:"Tools"})]}),o.jsx(ts,{value:"agents",children:e.agentData.length>0?o.jsx(ede,{data:e.agentData,rowHrefs:h("agents"),errorHrefs:p("agents"),LinkComponent:a}):o.jsx(Ht.NoData,{message:"No agent data yet"})}),o.jsx(ts,{value:"workflows",children:e.workflowData.length>0?o.jsx(ede,{data:e.workflowData,rowHrefs:h("workflows"),errorHrefs:p("workflows"),LinkComponent:a}):o.jsx(Ht.NoData,{message:"No workflow data yet"})}),o.jsx(ts,{value:"tools",children:e.toolData.length>0?o.jsx(ede,{data:e.toolData,rowHrefs:h("tools"),errorHrefs:p("tools"),LinkComponent:a}):o.jsx(Ht.NoData,{message:"No tool data yet"})})]}):o.jsx(Ht.NoData,{message:"No trace volume data yet"})})]})}async function tde(e,t,n){const r=await e.getMetricBreakdown({name:[t],groupBy:["entityName","status"],aggregation:"count",orderDirection:"DESC",filters:n}),s=new Map;for(const i of r.groups){const a=i.dimensions.entityName??"unknown",l=i.dimensions.status??"ok",c=XR(s,a,()=>({completed:0,errors:0}));l==="error"?c.errors+=i.value:c.completed+=i.value}return Array.from(s.entries()).map(([i,a])=>({name:i,...a})).sort((i,a)=>a.completed+a.errors-(i.completed+i.errors))}function L4s(){const e=Ye(),{filters:t,filterKey:n}=og();return yt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,i]=await Promise.all([tde(e,"mastra_agent_duration_ms",t),tde(e,"mastra_workflow_duration_ms",t),tde(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:i}}})}const jB={agents:Yu.AGENT,workflows:Yu.WORKFLOW_RUN,tools:Yu.TOOL};function F4s(){const{data:e,isLoading:t,isError:n}=L4s(),{getTracesHref:r,getLogsHref:s}=tP(),{Link:i}=un();return o.jsx(D4s,{data:e,isLoading:t,isError:n,LinkComponent:i,getRowHref:(a,l)=>r({rootEntityType:jB[a],entityName:l.name}),getErrorSegmentHref:(a,l)=>l.errors>0?s({rootEntityType:jB[a],entityName:l.name,status:"error"}):void 0,actions:a=>o.jsxs(o.Fragment,{children:[o.jsx(lF,{href:r({rootEntityType:jB[a]}),LinkComponent:i}),o.jsx(q3s,{href:s({rootEntityType:jB[a],status:"error"}),LinkComponent:i})]})})}const nde="period",NB="dateFrom",IB="dateTo";function z4s(){const[e,t]=bi(),n=e.get(nde),r=F3s(n)?n:"24h",s=g.useMemo(()=>{if(r!=="custom")return;const d=p=>{if(!p)return;const m=new Date(p);return Number.isNaN(m.getTime())?void 0:m},f=d(e.get(NB)),h=d(e.get(IB));if(!(!f&&!h))return{from:f,to:h}},[r,e.toString()]),i=g.useMemo(()=>A3s(e),[e.toString()]),a=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d==="24h"?h.delete(nde):h.set(nde,d),d!=="custom"&&(h.delete(NB),h.delete(IB)),h},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d?.from?h.set(NB,d.from.toISOString()):h.delete(NB),d?.to?h.set(IB,d.to.toISOString()):h.delete(IB),h},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return P3s(h,d),h},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,I3s(e)))return;const d=$rn();d&&t(f=>{const h=new URLSearchParams(f);for(const[p,m]of d)h.append(p,m);return h},{replace:!0})},[]),o.jsx(B3s,{preset:r,filterTokens:i,onPresetChange:a,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(w4s,{children:o.jsx(B4s,{})})})}function B4s(){const{error:e,isLoading:t}=Frn(),{isInMemory:n}=rF(),{data:r,isLoading:s}=Rrn(),{data:i,isLoading:a}=zDe(),{data:l,isLoading:c}=Arn(),{data:u,isLoading:d}=BDe(),f=g.useMemo(()=>Mrn({availableTags:r??[],availableEntityNames:i??[],availableServiceNames:l??[],availableEnvironments:u??[],loading:{tags:s,entityNames:a,serviceNames:c,environments:d}}),[r,i,l,u,s,a,c,d]);return e&&ks(e)?o.jsx(Qn,{children:o.jsx(Gs,{})}):e&&Es(e)?o.jsx(Qn,{children:o.jsx(Fs,{resource:"metrics"})}):e?o.jsx(Qn,{children:o.jsx(Ws,{title:"Failed to load metrics",message:e.message})}):o.jsx(zke,{filterFields:f,isLoading:t,children:o.jsxs("div",{className:"grid content-start gap-4 pb-6",children:[n&&o.jsx(xn,{variant:"info",title:"Metrics are not persisted",children:o.jsx(xn.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(Pke,{children:[o.jsx(c4s,{}),o.jsx(u4s,{}),o.jsx(d4s,{}),o.jsx(f4s,{}),o.jsx(h4s,{})]}),o.jsxs(Pke,{children:[o.jsx(O4s,{}),o.jsx(T4s,{}),o.jsx(M4s,{}),o.jsx(s4s,{}),o.jsx(F4s,{}),o.jsx(J3s,{})]})]})})}function cut(){const{isCmsAvailable:e}=Ab(),{Link:t,paths:n}=un();return e?o.jsx(xv,{owner:"prompt-block-list",children:o.jsx(J_,{render:o.jsx(t,{href:n.cmsPromptBlockCreateLink()}),tooltip:"Create a prompt",variant:"ghost",size:"sm",children:"New prompt"})}):null}const U4s=50;function V4s(){const[e,t]=g.useState(""),[n,r]=g.useState(0),{data:s,isLoading:i,error:a,isPlaceholderData:l}=NJt({page:n,perPage:U4s}),c=s?.promptBlocks??[],u=s?.hasMore??!1,d=g.useCallback(()=>{l||r(p=>p+1)},[l]),f=g.useCallback(()=>{l||r(p=>Math.max(0,p-1))},[l]),h=g.useCallback(p=>{t(p),r(0)},[]);return a&&ks(a)?o.jsx(Qn,{children:o.jsx(Gs,{})}):a&&Es(a)?o.jsx(Qn,{children:o.jsx(Fs,{resource:"prompt blocks"})}):a?o.jsx(Qn,{children:o.jsx(Ws,{title:"Failed to load prompt blocks",message:a.message})}):c.length===0&&!i&&n===0?o.jsxs(Qn,{children:[o.jsx(cut,{}),o.jsx(qCs,{})]}):o.jsxs(Ft,{height:"full",children:[o.jsx(cut,{}),o.jsx(Ft.TopArea,{children:o.jsx(Ft.Row,{align:"center",stack:"responsive",children:o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(Wc,{onSearch:h,label:"Filter prompts",placeholder:"Filter by name or description"})})})}),o.jsx(VCs,{promptBlocks:c,isLoading:i,search:e,currentPage:n,hasMore:u,onNextPage:d,onPrevPage:f})]})}function q4s(){return o.jsx(Ft,{width:"narrow",children:o.jsx(Ft.MainArea,{children:o.jsx(ows,{children:o.jsx(X1e,{})})})})}const H4s=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:qIn,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:RSt,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:_s,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:jA,href:"https://discord.gg/mastra-ai",external:!0},{title:"Share with your team",description:"Running Mastra Studio locally? Deploy to the cloud so your team can collaborate.",icon:FSt,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:yCe,href:"https://mastra.ai/contact?ref=studio",external:!0}];function W4s(){return o.jsx(Ft,{width:"narrow",children:o.jsx(Ft.MainArea,{children:o.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:H4s.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(_s,{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",children:e.description})]},e.href))})})})}function uut(){const{isCmsAvailable:e}=Ab(),{Link:t,paths:n}=un();return e?o.jsx(xv,{owner:"scorer-list",children:o.jsx(J_,{render:o.jsx(t,{href:n.cmsScorersCreateLink()}),tooltip:"Create a scorer",variant:"ghost",size:"sm",children:"New scorer"})}):null}function Z4s(){const{data:e={},isLoading:t,error:n}=Ep(),[r,s]=g.useState(""),[i,a]=g.useState("all");if(n&&ks(n))return o.jsx(Qn,{children:o.jsx(Gs,{})});if(n&&Es(n))return o.jsx(Qn,{children:o.jsx(Fs,{resource:"scorers"})});if(n)return o.jsx(Qn,{children:o.jsx(Ws,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsxs(Qn,{children:[o.jsx(uut,{}),o.jsx(d1s,{})]});const l=i!=="all"||r!=="",c=()=>{s(""),a("all")};return o.jsxs(Ft,{height:"full",children:[o.jsx(uut,{}),o.jsx(Ft.TopArea,{children:o.jsx(h1s,{search:r,onSearchChange:s,sourceFilter:i,onSourceFilterChange:a,onReset:c,hasActiveFilters:l})}),o.jsx(u1s,{scorers:e,isLoading:t,search:r,sourceFilter:i})]})}const Vrn=["input","entity"],G4s={input:"Input",entity:"Entity"};function Q4s(e){const t=["auto","auto","minmax(0, 10rem)"];return e.has("entity")&&t.push("minmax(0, 14rem)"),e.has("input")&&t.push("minmax(0, 40rem)"),t.join(" ")}function K4s(){const[e,t]=g.useState(new Set),n=g.useMemo(()=>new Set(Vrn.filter(i=>!e.has(i))),[e]),r=g.useMemo(()=>Q4s(n),[n]),s=g.useCallback(i=>{t(a=>{const l=new Set(a);return l.has(i)?l.delete(i):l.add(i),l})},[]);return{visibleColumns:n,columns:r,toggleColumn:s}}function Y4s({visibleColumns:e,toggleColumn:t}){return o.jsxs(xt,{children:[o.jsx(xt.Trigger,{asChild:!0,children:o.jsx(ae,{icon:o.jsx(nbe,{}),children:"Columns"})}),o.jsxs(xt.Content,{align:"end",children:[o.jsx(xt.Label,{children:"Toggle columns"}),Vrn.map(n=>o.jsx(xt.CheckboxItem,{checked:e.has(n),onClick:()=>t(n),children:G4s[n]},n))]})]})}function X4s(){const{scorerId:e}=ur(),[t,n]=bi(),r=t.get("scoreId")??void 0,[s,i]=g.useState(r),[a,l]=g.useState(!1),c=Fr(),[u,d]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:f,error:h}=qSs(e),p=K4s(),{data:m={},isLoading:v,error:y}=rh(),{isLoading:b,error:x}=eg(),{data:w=[],isLoading:k,error:_,isFetchingNextPage:C,hasNextPage:T,setEndOfListElement:E}=VSs({scorerId:e,entityId:u?.value==="all"?void 0:u?.value,entityType:u?.type==="ALL"?void 0:u?.type}),N=g.useMemo(()=>f?.agentIds?.filter(U=>m[U]).map(U=>({value:U,label:m[U].name,type:"AGENT"}))||[],[f?.agentIds,m]),I=g.useMemo(()=>f?.workflowIds?.map(U=>({value:U,label:U,type:"WORKFLOW"}))||[],[f?.workflowIds]),A=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...N,...I],[N,I]),P=t.get("entity")??"all",L=A.find(U=>U.value===P);L&&L.value!==u?.value&&d(L),g.useEffect(()=>{if(h){const U=h instanceof Error?h.message:"Failed to load scorer";Ge.error(`Error loading scorer: ${U}`)}},[h]),g.useEffect(()=>{if(y){const U=y instanceof Error?y.message:"Failed to load agents";Ge.error(`Error loading agents: ${U}`)}},[y]),g.useEffect(()=>{if(x){const U=x instanceof Error?x.message:"Failed to load workflows";Ge.error(`Error loading workflows: ${U}`)}},[x]);const M=U=>{U?.value&&n(Q=>{const ee=new URLSearchParams(Q);return ee.set("entity",U.value),ee})};g.useEffect(()=>{const U=t.get("scoreId")??void 0;if(U===s)return;if(!U){i(void 0);return}w.find(ee=>ee.id===U)&&i(U)},[t,w]);const V=g.useCallback(U=>{i(U||void 0),n(Q=>{const ee=new URLSearchParams(Q);return U?ee.set("scoreId",U):ee.delete("scoreId"),ee})},[n]);if(!f)return null;const q=ks(h)||ks(y)||ks(x),H=h&&Es(h),B=!q&&!H&&(h||y||x),W=!k&&w.length===0,z=u?.value!=="all",G=f?.source==="stored",F=e?o.jsx(yJ,{open:a,onOpenChange:l,initialScorerIds:[e],onSuccess:U=>{c(`/experiments/${U}`)}}):null,R=G?o.jsxs(xt,{children:[o.jsx(xt.Trigger,{asChild:!0,children:o.jsx(ae,{size:"lg","aria-label":"Scorer actions menu",children:o.jsx(F1,{})})}),o.jsx(xt.Content,{align:"end",className:"w-48",children:o.jsxs(xt.Item,{onSelect:()=>{c(`/cms/scorers/${e}/edit`)},children:[o.jsx(Gd,{})," Edit Scorer"]})})]}):null;if(q||H||B||W&&!z){const U=(h instanceof Error?h.message:void 0)??(y instanceof Error?y.message:void 0)??(x instanceof Error?x.message:void 0)??"An unexpected error occurred",Q=q||H||B;return o.jsxs(Ft,{width:"wide",height:"full",className:Q||!R?"grid-rows-[1fr]":void 0,children:[!Q&&R&&o.jsx(Ft.TopArea,{children:o.jsx(Ms,{className:"ml-auto",children:R})}),o.jsx(Ft.MainArea,{isCentered:!0,children:q?o.jsx(Gs,{}):H?o.jsx(Fs,{resource:"scorers"}):B?o.jsx(Ws,{title:"Failed to load scorer",message:U}):o.jsx(MSs,{onRunExperiment:()=>l(!0)})}),F]})}return o.jsxs(Ft,{width:"wide",height:"full",children:[o.jsx(Ft.TopArea,{children:o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx(DSs,{selectedEntity:u,entityOptions:A,onEntityChange:M,onReset:()=>{n(U=>{const Q=new URLSearchParams(U);return Q.set("entity","all"),Q})},isLoading:k||v||b}),o.jsxs(Ms,{children:[o.jsx(Y4s,{visibleColumns:p.visibleColumns,toggleColumn:p.toggleColumn}),o.jsx(ae,{variant:"primary",onClick:()=>l(!0),icon:o.jsx(bu,{}),children:"Run Experiment"}),R]})]})}),o.jsx($Ss,{scores:w,isLoading:k,selectedScoreId:s,isFetchingNextPage:C,hasNextPage:T,setEndOfListElement:E,onScoreClick:V,errorMsg:_?.message,columnsState:p}),F]})}const J4s=[{value:"system",label:"System",icon:o.jsx(JSt,{})},{value:"light",label:"Light",icon:o.jsx(d$n,{})},{value:"dark",label:"Dark",icon:o.jsx(BRn,{})}],e5s={md:{itemGap:2,itemWidth:28,root:"gap-0.5 p-0.5",indicator:"inset-y-0.5 left-0.5",item:"h-6 [&_svg]:size-3.5"},xs:{itemGap:1,itemWidth:20,root:"gap-px p-px",indicator:"inset-y-px left-px",item:"h-4 [&_svg]:h-icon-sm [&_svg]:w-icon-sm"},sm:{itemGap:1,itemWidth:24,root:"gap-px p-px",indicator:"inset-y-px left-px",item:"h-5 [&_svg]:h-icon-sm [&_svg]:w-icon-sm"}},t5s=({value:e,onChange:t,options:n=J4s,size:r="md",className:s,"aria-label":i="Theme",...a})=>{const{theme:l,setTheme:c}=aE(),u=e??l,d=t??c,f=n.some(y=>y.value===u)?u:n[0]?.value??"system",h=y=>{const b=n.find(x=>x.value===y);b&&d(b.value)},p=Math.max(0,n.findIndex(y=>y.value===f)),m=e5s[r],v=p*(m.itemWidth+m.itemGap);return o.jsxs(zXt,{...a,value:f,onValueChange:h,"aria-label":i,className:K("relative inline-flex w-fit items-center rounded-full border border-border1 bg-surface3",m.root,s),children:[o.jsx("span",{"aria-hidden":"true",className:K("pointer-events-none absolute rounded-full bg-surface5 motion-reduce:transition-none",Vr.transform,m.indicator),style:{width:m.itemWidth,transform:`translateX(${v}px)`}}),n.map(y=>o.jsx(FXt,{value:y.value,"aria-label":y.label,style:{width:m.itemWidth},className:K("relative inline-flex cursor-pointer items-center justify-center rounded-full","text-icon3 hover:text-icon6 data-[checked]:text-icon6",m.item,"focus-visible:outline-hidden","active:scale-90 motion-reduce:transition-none",Vr.colors,Vr.transform),children:o.jsx("span",{"aria-hidden":"true",className:"pointer-events-none inline-flex items-center justify-center",children:y.icon})},y.value))]})},n5s=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=B4();return o.jsx(Ft,{className:"p-0",children:o.jsx(U1s,{children:o.jsxs("div",{className:"mx-auto flex max-w-4xl flex-col gap-8",children:[o.jsxs(Jat,{children:[o.jsxs(eot,{children:[o.jsx(tot,{children:"General"}),o.jsx(not,{children:"Stored in this browser."})]}),o.jsx(NXt,{children:o.jsx(ske,{label:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(t5s,{})})})]}),o.jsxs(Jat,{children:[o.jsxs(eot,{children:[o.jsx(tot,{children:"Mastra Connection"}),o.jsx(not,{children:"Configure the Mastra instance URL, API prefix, and request headers used by the studio."})]}),o.jsx(QXt,{variant:"factory",initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})]})]})})})};function r5s(){const[e]=bi(),t=Fr(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(Crn,{redirectUri:n,onSuccess:r,initialMode:"signup"})}function s5s(e){return e.replace(/\/$/,"").split("/").pop()}function wJ({children:e,className:t}){return o.jsx("div",{className:K("border border-border1 rounded-lg mt-12 py-5 lg:min-h-[25rem] transition-height px-4 lg:px-12",t),children:e})}function i5s({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((i,a)=>o.jsx("div",{className:"bg-surface3 h-16 animate-pulse rounded-lg"},a))}):o.jsx("div",{className:K("grid gap-y-4",n),children:e.map(i=>{const a=i?.agents||i?.tools||i?.networks||i?.workflows||i?.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/${i.slug}`,className:K("grid [&:hover_p]:text-neutral5",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":i.imageURL}),children:[i.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(${i.imageURL})`}})}),o.jsxs("div",{className:K("grid py-3 px-4 w-full gap-0.5","[&_svg]:w-[1em] [&_svg]:h-[1em] [&_svg]:text-neutral3"),children:[o.jsx("h2",{className:"text-ui-md text-neutral5",children:i.title}),o.jsx("p",{className:"text-ui-md text-neutral4 transition-colors duration-500",children:i.description}),o.jsxs("div",{className:"text-neutral3 text-ui-md mt-3 hidden flex-wrap items-center gap-4 2xl:flex",children:[a&&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:[i?.agents&&i.agents.length>0&&o.jsxs("li",{children:[o.jsx(Ma,{})," ",i.agents.length]}),i?.tools&&i.tools.length>0&&o.jsxs("li",{children:[o.jsx(eh,{})," ",i.tools.length]}),i?.networks&&i.networks.length>0&&o.jsxs("li",{children:[o.jsx(e1t,{})," ",i.networks.length]}),i?.workflows&&i.workflows.length>0&&o.jsxs("li",{children:[o.jsx(z1,{})," ",i.workflows.length]}),i?.mcp&&i.mcp.length>0&&o.jsxs("li",{children:[o.jsx(ME,{})," ",i.mcp.length]})]}),a&&i.supportedProviders&&o.jsx("small",{children:"|"}),o.jsx("div",{className:"text-neutral3 flex items-center gap-4",children:i.supportedProviders.map(l=>o.jsx("span",{className:"",children:l},l))})]})]})]}),o.jsx("a",{href:i.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(jY,{})," ",s5s(i.githubUrl)]})})]},i.slug)})})}function a5s({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:s,onProviderChange:i,searchTerm:a,onSearchChange:l,onReset:c,className:u,isLoading:d}){return d?o.jsxs("div",{className:K("h-[6.5rem] flex items-center gap-5","[&>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-5",u),children:[o.jsx(C3,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:a,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(of,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(of,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:i,options:n}),c&&o.jsx(ae,{onClick:c,icon:o.jsx(Yt,{}),children:"Reset"})]})}function o5s(){const{data:e,isLoading:t}=z1r(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[i,a]=g.useState("all"),[l,c]=g.useState("all"),[u,d]=g.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(x=>{f.push({value:x,label:x})});const h=[{value:"all",label:"Any provider"}];(s||[]).forEach(x=>{h.push({value:x,label:x})});const p=(x,w)=>{w==="tag"?a(x):w==="provider"&&c(x)},m=x=>{d(x)},v=()=>{a("all"),c("all"),d("")},y=n.filter(x=>!(u&&!x.title.toLowerCase().includes(u)&&!x.description.toLowerCase().includes(u)||i!=="all"&&!x.tags.includes(i)||l!=="all"&&!x.supportedProviders.includes(l))),b=u||i!=="all"||l!=="all";return o.jsxs(oi,{children:[o.jsx(Q4,{children:o.jsxs(EEt,{children:[o.jsx(St,{children:o.jsx(Qx,{})}),"Templates"]})}),o.jsxs("div",{className:K("overflow-y-auto w-full h-full px-5 pb-12 z-10"),children:[o.jsx(a5s,{selectedTag:i,onTagChange:x=>p(x,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:x=>p(x,"provider"),providerOptions:h,searchTerm:u,onSearchChange:m,onReset:b?v:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(i5s,{templates:y,linkComponent:oo,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const l5s="1.68.0-alpha.8";function c5s({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,i=()=>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.",a=()=>s?{icon:o.jsx(Pc,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(rAn,{}),title:"Template Installation Failed"},{icon:l,title:c}=a();return o.jsxs(wJ,{className:"text-neutral3 mb-5 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:i()})]})]}),t&&t.length>0&&o.jsxs("details",{className:"text-ui-sm",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:"text-ui-sm mt-4 max-h-60 space-y-2 overflow-auto rounded bg-gray-100 p-3 text-left 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:"text-ui-sm mt-1 font-mono wrap-break-word whitespace-pre-wrap text-gray-700 dark:text-gray-300",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-ui-sm",children:[o.jsx("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:"Show Details"}),o.jsx("div",{className:"text-ui-sm mt-4 max-h-60 overflow-auto rounded bg-gray-100 p-3 text-left font-mono dark:bg-gray-800",children:o.jsx("div",{className:"wrap-break-word whitespace-pre-wrap",children:n})})]})]})}const u5s=g.createContext(null);function d5s(){const e=g.useContext(u5s);return e||{registerResetFn:()=>{},triggerReset:()=>{}}}const qrn=({defaultProvider:e,defaultModel:t,updateModel:n,resetModel:r})=>{const[s]=g.useState(e),[i]=g.useState(t),[a,l]=g.useState(t),[c,u]=g.useState(e||""),[d,f]=g.useState(!1),[h,p]=g.useState(!1),[m,v]=g.useState(!1),{data:y,isLoading:b}=r6(),x=z0(),{models:w}=tw(),k=g.useMemo(()=>y?.providers||[],[y]);g.useEffect(()=>{l(t),u(e||"")},[t,e]);const _=sa(c),T=NN(k,_)?.id||_,E=async M=>{if(l(M),M&&T){f(!0);try{const V=await n({provider:T,modelId:M});console.info("Model updated:",V)}catch(V){console.error("Failed to update model:",V)}finally{f(!1)}}},N=M=>{const V=sa(M);u(V),V!==_&&(l(""),v(!0))},{registerResetFn:I}=d5s();if(g.useEffect(()=>(I(()=>{if(h||m)return;if(_&&_!==s&&(!a||a==="")){u(sa(s)),l(i);const B=NN(k,s)?.id||s;B&&i&&n({provider:B,modelId:i}).catch(W=>{console.error("Failed to reset model:",W)})}}),()=>{I(null)}),[I,_,a,s,i,n,h,m,k]),b)return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(_n,{}),o.jsx("span",{className:"text-ui-md text-gray-500",children:"Loading providers..."})]});const A=async()=>{if(!r){console.warn("Reset model function not provided");return}try{f(!0),await r()}catch(M){console.error("Failed to reset model:",M)}finally{f(!1)}},P=NN(k,_);if(x.active&&x.pickerVisible===!1){const M=x.default&&x.default.provider&&x.default.modelId?`${x.default.provider}/${x.default.modelId}`:c&&a?`${c}/${a}`:"Locked by admin";return o.jsxs("div",{className:"border-border1 bg-surface3 flex items-center gap-2 rounded-md border px-3 py-2","data-testid":"agent-metadata-model-locked",children:[o.jsx(td,{className:"text-neutral3 h-4 w-4 shrink-0"}),o.jsx("span",{className:"text-ui-sm text-neutral6 truncate",children:M}),o.jsx("span",{className:"text-ui-xs text-neutral3 ml-auto shrink-0",children:"Set by admin"})]})}const L=!!(_&&a)&&x.active&&x.allowed!==void 0&&!w.some(M=>sa(M.provider)===_&&M.model===a);return o.jsxs("div",{className:"@container",children:[o.jsxs("div",{className:"flex w-full flex-col items-stretch gap-2 @xs:flex-row @xs:items-center",children:[o.jsx("div",{className:"w-full @xs:w-2/5",children:o.jsx(ak,{value:_,onValueChange:N,open:h,onOpenChange:p})}),o.jsx("div",{className:"w-full @xs:w-3/5",children:o.jsx(ok,{llmId:_,value:a,onValueChange:E,open:m,onOpenChange:v})}),o.jsx(ae,{variant:"default",size:"md",onClick:A,disabled:d,className:"text-ui-sm flex items-center gap-1.5 border-0! whitespace-nowrap",title:"Reset to original model",children:o.jsx(z_,{className:"h-3.5 w-3.5"})})]}),L&&o.jsx("div",{className:"p-2 pt-2","data-testid":"agent-metadata-model-stale-warning",children:o.jsx(xn,{variant:"warning",title:"Model not allowed",children:o.jsxs(xn.Message,{children:[o.jsxs("code",{className:"rounded bg-yellow-100 px-1 py-0.5 dark:bg-yellow-900/50",children:[c,"/",a]})," ","is no longer allowed by the admin policy. Pick a different model to save changes."]})})}),P&&!P.connected&&o.jsx("div",{className:"p-2 pt-2",children:o.jsx(xn,{variant:"warning",title:"Provider not connected",children:o.jsxs(xn.Message,{children:["Set the"," ",o.jsx("code",{className:"rounded bg-yellow-100 px-1 py-0.5 dark:bg-yellow-900/50",children:Array.isArray(P.envVar)?P.envVar.join(", "):P.envVar})," ","environment"," ",Array.isArray(P.envVar)&&P.envVar.length>1?"variables":"variable"," to use this provider."]})})})]})};function f5s({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:s,handleInstallTemplate:i,handleVariableChange:a,isLoadingEnvVars:l,isInstalling:c,defaultModelProvider:u,defaultModelId:d,onModelUpdate:f}){return o.jsx(wJ,{children:o.jsxs("div",{className:"mx-auto my-4 grid max-w-[40rem] gap-5 p-4 lg:p-5",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(t1t,{})]}),o.jsx(of,{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(_n,{})," Loading variables..."]}):Object.entries(r).map(([h,p])=>o.jsxs(g.Fragment,{children:[o.jsx(Rm,{name:`env-${h}`,labelIsHidden:!0,label:"Key",value:h,disabled:!0,className:"w-full"}),o.jsx(Rm,{name:h,labelIsHidden:!0,label:"Value",value:p,onChange:a,errorMsg:s.includes(h)?"Value is required.":"",autoComplete:"off",className:"w-full"})]},h))}),o.jsxs("div",{className:"border-border1 relative mt-3.5 border-t pt-12",children:[o.jsx("div",{className:"bg-surface2 text-ui-sm text-neutral3 absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full",children:"And"}),o.jsx("h3",{className:"text-neutral4 text-ui-md",children:"Set AI Model for Template Installation"}),o.jsx("p",{className:"text-neutral3 text-ui-md mt-2 mb-5",children:"This model will be used by the workflow to process and install the template"}),o.jsx(qrn,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(ae,{className:K("flex items-center gap-2 mt-4 justify-center text-ui-md w-full bg-surface5 min-h-10 rounded-lg text-neutral5 hover:bg-surface6 transition-colors","[&>svg]:w-[1.1em] [&_svg]:h-[1.1em] [&_svg]:text-neutral5"),onClick:i,disabled:!t||!u||!d||s.length>0||c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(_n,{className:"h-4 w-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(Kf,{})]})})]})})}function h5s({title:e,description:t,githubUrl:n,isLoading:r,infoData:s,templateSlug:i}){const a=i?`feat/install-template-${i}`:"feat/install-template-[slug]";return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:K("grid mt-5 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(Qx,{}),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",{"bg-surface4 rounded-lg ":r}),children:r?o.jsx(o.Fragment,{children:" "}):t}),!r&&i&&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(Yf,{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(gV,{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:a})]}),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(jY,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(F2e,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function dut(e){switch(e){case"running":return o.jsx(_n,{size:"sm","aria-hidden":!0});case"success":return o.jsx(Mn,{"aria-hidden":!0});case"failed":return o.jsx(Yt,{"aria-hidden":!0});default:return null}}function p5s(){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 m5s({status:e,variant:t}){return t==="plain"?o.jsx("span",{className:K("flex size-4 items-center justify-center self-center [&>svg]:size-4",Vr.colors,{"[&>svg]:text-positive1":e==="success","[&>svg]:text-negative1":e==="failed"}),children:e==="pending"?o.jsx(p5s,{}):dut(e)}):o.jsx("span",{className:K("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",Vr.colors,Vr.transform,Vr.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:dut(e)})}function g5s({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",Vr.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",Vr.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",Vr.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(m5s,{status:e.status,variant:r})]})}function v5s({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:K(n),children:t.map((r,s)=>o.jsx(g5s,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function y5s({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",Vr.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",Vr.colors,Vr.transform,Vr.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(_n,{}):s+1})},r.id))}),o.jsxs("div",{className:K("text-center text-ui-sm text-neutral3",Vr.colors),children:[n," of ",t," steps completed"]})]})}function b5s({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",i=t?.payload?.workflowState,a=t?.payload?.currentStep,l=t?.error,c=i?.steps||{},u=Object.keys(c).length>0,d=v=>v==="input"||v.endsWith(".input")||v.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(v)||/[0-9a-f]{8,}/.test(v)?!1:r?.allSteps?v in r.allSteps:!0,f=Object.entries(c).filter(([v,y])=>d(v)),h=f.length,p=()=>{switch(s){case"initializing":return"Preparing template installation...";case"processing":return`Installing ${e} template`;case"completed":return"Template installation completed!";case"error":return"Template installation failed";default:return"Installing template..."}},m=f.map(([v,y])=>({id:v,status:y?.status,description:y?.description,title:v.charAt(0).toUpperCase()+v.slice(1).replace(/-/g," "),isActive:a?.id===v}));return o.jsxs(wJ,{className:"text-neutral3 mb-5 content-center space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h3",{className:"text-neutral5 text-header-sm font-semibold",children:p()}),(t?.runId||n)&&o.jsxs("div",{className:"text-ui-sm text-neutral3 mt-2",children:["Run ID: ",t?.runId??n]})]}),u&&h>0&&!["error"].includes(s)&&o.jsx("div",{className:"mx-auto w-full max-w-[30rem] px-4",children:o.jsx(y5s,{steps:m})}),l&&s==="error"&&o.jsxs("div",{className:K("rounded-lg text-neutral5 p-4 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(ePn,{}),l||"Something went wrong"]}),u&&o.jsx(v5s,{steps:m,currentStep:a,className:"pb-4"}),!u&&s==="initializing"&&o.jsxs("div",{className:"text-neutral3 text-ui-md grid justify-items-center gap-4 text-center",children:[o.jsx(_n,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function x5s({name:e,installedEntities:t}){return o.jsxs(wJ,{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(t1t,{}),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(F2e,{data:t})]})}function w5s(){const{templateSlug:e}=ur(),[t,n]=bi(),[r,s]=g.useState(""),[i,a]=g.useState(""),[l,c]=g.useState(""),[u,d]=g.useState({}),[f,h]=g.useState([]),[p,m]=g.useState(null),[v,y]=g.useState(!1),[b,x]=g.useState(""),[w,k]=g.useState(!1),[_,C]=g.useState(!1),[T,E]=g.useState([]),{data:N,isLoading:I}=B1r({repoOrSlug:e,owner:"mastra-ai"}),P=l5s?.includes("beta")??!1?"beta":"main",{data:L,isLoading:M}=U1r({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:P}),{data:V,isLoading:q}=V1r(),{mutateAsync:H,isPending:B}=q1r(),{mutateAsync:W}=H1r(),{streamInstall:z,streamResult:G,isStreaming:F}=Z1r(V),{observeInstall:R,streamResult:D,isStreaming:U}=G1r(V);g.useEffect(()=>{const ne=t.get("runId");ne&&!v&&!p&&!F&&!U&&(console.info("🔄 Checking completed run after hot reload:",{runId:ne}),x(ne),W({runId:ne}).then(se=>{const le=se.snapshot;if(le?.status==="success"&&le?.result?.success)y(!0);else if(le?.result?.success===!1)if(le?.result?.validationResults&&!le?.result?.validationResults?.valid&&le?.result?.validationResults?.remainingErrors>0){const{remainingErrors:pe,errors:Se}=le.result.validationResults,Ee=`Template installation completed but ${pe} validation issue${pe>1?"s":""} remain unresolved.`;m(Ee),E(Se||[])}else{const pe=le?.result?.message||le?.result?.error||"Template installation failed";m(typeof pe=="string"?pe:String(pe))}}).catch(se=>{console.error("❌ Failed to fetch run details:",se),m("Failed to retrieve installation status after reload")}))},[t,v,p,F,U,W]),g.useEffect(()=>{const ne=t.get("runId"),se=t.get("resume"),le=t.get("provider");if(ne&&se==="true"&&le&&!F&&!U&&!w&&!_&&V){x(ne),k(!0);try{W({runId:ne}).then(he=>{if(he.snapshot?.status==="running")return R.mutateAsync({runId:ne})}).then(()=>{n(he=>{const pe=new URLSearchParams(he);return pe.delete("resume"),pe})}).catch(he=>{console.error("❌ Failed to resume template installation:",he),he.message?.includes("404")||he.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(he){console.error("❌ Auto-resume failed with error:",he),m("Failed to resume template installation. Please refresh and try again.")}}},[t,e,F,U,w,_,V,W,R,n]);const Q=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],ee=[{key:"tools",label:"Tools",value:N?.tools?.length?N.tools.map(ne=>ne).join(", "):"n/a",icon:o.jsx(eh,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(ne=>ne).join(", "):"n/a",icon:o.jsx(Ma,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(ne=>ne).join(", "):"n/a",icon:o.jsx(z1,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(qg,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(B_,{})}],J=[{...ee[0]},{...ee[1]},{...ee[2]}].filter(ne=>ne.value!=="n/a");g.useEffect(()=>{L&&d(L)},[L]),g.useEffect(()=>{const ne=G||D;ne?.phase==="error"&&ne?.error&&m(typeof ne.error=="string"?ne.error:String(ne.error))},[G?.phase,G?.error,D?.phase,D?.error]);const te=ne=>{s(ne)},re=async ne=>(a(ne.provider),c(ne.modelId),{message:"Model updated successfully"}),ce=async()=>{const ne=Object.entries(u).reduce((se,[le,he])=>(he===""&&se.push(le),se),[]);if(ne.length>0){h(ne);return}if(N){m(null),y(!1),x(""),C(!0);try{const le={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:P,slug:N.slug,variables:u},{runId:he}=await H({});x(he),n(pe=>{const Se=new URLSearchParams(pe);return Se.set("runId",he),Se.set("resume","true"),Se.set("provider",r||"openai"),Se}),await z.mutateAsync({inputData:le,selectedModel:{provider:i,modelId:l},runId:he})}catch(se){C(!1),m(se?.message||"Template installation failed"),console.error("Template installation failed",se)}}},X=ne=>{const{name:se,value:le}=ne.target;le.trim()===""?h(he=>[...he,se]):h(he=>he.filter(pe=>pe!==se)),d(he=>({...he,[se]:le}))};return o.jsx(oi,{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-4",children:[o.jsx(h5s,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:ee,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(F||U)&&o.jsx(b5s,{name:N.title,streamResult:U?D:G,runId:b,workflowInfo:V}),v&&o.jsx(x5s,{name:N.title,installedEntities:J,linkComponent:oo}),p&&o.jsx(c5s,{errorMsg:p,validationErrors:T.length>0?T:G?.validationResults?.errors||D?.validationResults?.errors}),!F&&!U&&!v&&!p&&o.jsx(f5s,{providerOptions:Q,selectedProvider:r,onProviderChange:te,variables:u,setVariables:d,errors:f,setErrors:h,handleInstallTemplate:ce,handleVariableChange:X,isLoadingEnvVars:M||q,isInstalling:B,defaultModelProvider:i,defaultModelId:l,onModelUpdate:re})]})]})})})}const S5s=()=>{const{toolId:e,agentId:t}=ur();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(uOs,{toolId:e,agentId:t})})},k5s=()=>{const{toolId:e}=ur();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(b3s,{toolId:e})})};function O5s(){const{data:e,isLoading:t,error:n}=eg(),[r,s]=g.useState("");return n&&ks(n)?o.jsx(Qn,{children:o.jsx(Gs,{})}):n&&Es(n)?o.jsx(Qn,{children:o.jsx(Fs,{resource:"workflows"})}):n?o.jsx(Qn,{children:o.jsx(Ws,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(Qn,{children:o.jsx(mms,{})}):o.jsxs(Ft,{height:"full",children:[o.jsx(Ft.TopArea,{children:o.jsxs(Ft.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(Wc,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsx(ae,{render:o.jsx(oo,{to:"/workflows/schedules"}),variant:"primary",className:"shrink-0",icon:o.jsx(M0,{}),children:"Schedules"})]})}),o.jsx(pms,{workflows:e||{},isLoading:t,search:r})]})}const C5s={active:"bg-accent1",paused:"bg-accent3"},_5s={active:"text-accent1",paused:"text-accent3"},Hrn=({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 ${C5s[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${_5s[e]}`,children:e})]}),zN=e=>!e||e<=0?"—":new Date(e).toLocaleString(),cD=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 i=Math.floor(s/60);if(i<24)return t>=0?`in ${i}h`:`${i}h ago`;const a=Math.floor(i/24);return t>=0?`in ${a}d`:`${a}d ago`};function Wrn({status:e}){const{icon:t,color:n}=E5s(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 E5s(e){switch(e){case"success":return{icon:o.jsx(Mn,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(Yt,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(_n,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(sG,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(Ls,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx($C,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const fut="auto auto auto auto 1fr";function T5s(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 j5s(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 N5s=3e4,I5s=5*6e4;function A5s({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:i}){const{Link:a,paths:l}=un(),c=p=>!!(n&&p.runId&&p.outcome!=="failed"),u=e.filter(c).length,{containerRef:d,getRowProps:f}=Zc({count:u});let h=-1;return t?o.jsx(Wl,{columns:fut}):e.length===0?o.jsx(Te,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(we,{columns:fut,className:"min-w-0",scrollRef:d,children:[o.jsxs(we.Top,{children:[o.jsx(we.TopCell,{children:"Run"}),o.jsx(we.TopCell,{children:"Status"}),o.jsx(we.TopCell,{children:"Started"}),o.jsx(we.TopCell,{children:"Duration"}),o.jsx(we.TopCell,{children:" "})]}),e.map(p=>{const m=p.actualFireAt-p.scheduledFireAt,v=j5s(m),y=`Scheduled ${zN(p.scheduledFireAt)} — published ${zN(p.actualFireAt)} (drift ${v})`,b=p.outcome==="failed",x=b?p.error:p.run?.error,w=Math.abs(m),k=!b&&w>N5s&&w<=I5s,_=`${p.scheduleId}-${p.runId}-${p.actualFireAt}`,C=c(p);C&&(h+=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:p.runId}),E=o.jsxs(o.Fragment,{children:[o.jsx(we.Cell,{children:T}),o.jsx(we.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[b?o.jsxs("span",{className:"text-ui-sm text-accent2 inline-flex items-center gap-1.5 whitespace-nowrap",children:[o.jsx(Pc,{size:14}),"publish failed"]}):p.run?o.jsx(Wrn,{status:p.run.status}):o.jsx("span",{className:"text-ui-sm text-neutral3 inline-flex items-center gap-1.5 whitespace-nowrap",children:"pending"}),x?o.jsxs(In,{children:[o.jsx(On,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(Pc,{size:14})})}),o.jsx(Cn,{children:x})]}):null]})}),o.jsx(we.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:y,children:cD(p.actualFireAt)}),k?o.jsxs(In,{children:[o.jsx(On,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(Pc,{size:14})})}),o.jsxs(Cn,{children:["Published ",v," after the scheduled fire time"]})]}):null]})}),o.jsx(we.Cell,{children:p.run?o.jsx("span",{children:T5s(p.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(we.Cell,{children:" "})]});return C?o.jsx(we.RowLink,{to:l.workflowRunLink(n,p.runId),LinkComponent:a,...f(h),children:E},_):o.jsx(we.RowStatic,{children:E},_)}),o.jsx(we.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:i})]})}const R5s=e=>{const t=Ye();return yt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},hut=25,P5s=e=>{const t=Ye(),{inView:n,setRef:r}=Sb(),s=yv({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:hut,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<hut))return u.triggers[u.triggers.length-1].actualFireAt},refetchInterval:u=>(u.state.data?.pages.flatMap(h=>h.triggers)??[]).some(h=>h.run?h.run.status==="pending"||h.run.status==="running"||h.run.status==="waiting":h.outcome==="published")?5e3:!1}),i=s.data?.pages.flatMap(u=>u?.triggers??[])??[],{hasNextPage:a,isFetchingNextPage:l,fetchNextPage:c}=s;return g.useEffect(()=>{n&&a&&!l&&c()},[n,a,l,c]),{...s,data:i,setEndOfListElement:r}},$5s=e=>{const t=Ye(),n=kr();return yn({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"]}),Ge.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{Ge.error(r.message)}})};function AB({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(Te,{variant:"ui-xs",className:"text-neutral4 tracking-wide uppercase",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function M5s(){const{scheduleId:e}=ur(),{paths:t}=un(),{data:n,error:r}=R5s(e),{data:s,isLoading:i,error:a,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=P5s(e),d=$5s(e);if(r&&ks(r))return o.jsx(Qn,{children:o.jsx(Gs,{})});if(r&&Es(r))return o.jsx(Qn,{children:o.jsx(Fs,{resource:"schedules"})});if(r)return o.jsx(Qn,{children:o.jsx(Ws,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,h=n?.agentId;return o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsx(Ft.Row,{className:"justify-end",children:o.jsxs(Ft.Column,{className:"flex justify-end gap-2",children:[o.jsx(ae,{render:o.jsx(oo,{to:t.schedulesLink()}),variant:"ghost",icon:o.jsx(id,{}),children:"Back to schedules"}),f?o.jsx(ae,{icon:o.jsx(Bc,{}),render:o.jsx(oo,{to:t.workflowLink(f)}),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(ae,{onClick:()=>d.mutate(n.status==="active"?"pause":"resume"),disabled:d.isPending,"data-testid":"schedule-toggle-button",children:n.status==="active"?o.jsxs(o.Fragment,{children:[o.jsx(MC,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(bu,{}),"Resume"]})}):null]})})}),n?o.jsxs("div",{className:"grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-4 overflow-hidden",children:[o.jsxs("div",{className:"border-border1 flex h-fit flex-col gap-4 rounded-md border p-4",children:[o.jsx(AB,{label:h?"Agent":"Workflow",children:f?o.jsx(oo,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):h?o.jsx(oo,{to:t.agentLink(h),className:"text-accent1 hover:underline",children:h}):"—"}),o.jsxs(AB,{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(AB,{label:"Status",children:o.jsx(Hrn,{status:n.status})}),o.jsx(AB,{label:"Next fire",children:o.jsx("span",{title:zN(n.nextFireAt),children:cD(n.nextFireAt)})})]}),o.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[o.jsx(Te,{variant:"ui-md",className:"mb-3",children:"Trigger history"}),a?o.jsx(Ws,{title:"Failed to load trigger history",message:a.message}):o.jsx(A5s,{triggers:s??[],isLoading:i,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const put="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function D5s({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=un(),i=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:a,getRowProps:l}=Zc({count:i.length,global:!0});return t?o.jsx(Wl,{columns:put}):o.jsxs(we,{columns:put,className:"min-w-0",scrollRef:a,children:[o.jsxs(we.Top,{children:[o.jsx(we.TopCell,{children:"Target"}),o.jsx(we.TopCell,{children:"Schedule ID"}),o.jsx(we.TopCell,{children:"Cron"}),o.jsx(we.TopCell,{children:"Status"}),o.jsx(we.TopCell,{children:"Next fire"}),o.jsx(we.TopCell,{children:"Last run"})]}),i.length===0&&n?o.jsx(we.NoMatch,{message:"No schedules match your search"}):null,i.length===0&&!n?o.jsx(we.NoMatch,{message:"No schedules configured"}):null,i.map((c,u)=>o.jsxs(we.RowLink,{to:r.scheduleLink(c.id),LinkComponent:s,...l(u),children:[o.jsx(we.NameCell,{children:c.workflowId??c.agentId}),o.jsx(we.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(we.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(we.Cell,{children:o.jsx(Hrn,{status:c.status})}),o.jsx(we.Cell,{children:o.jsx("span",{className:"whitespace-nowrap",title:zN(c.nextFireAt),children:cD(c.nextFireAt)})}),o.jsx(we.Cell,{children:c.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(Wrn,{status:c.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:zN(c.lastFireAt),children:c.lastFireAt?cD(c.lastFireAt):""})]}):c.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:zN(c.lastFireAt),children:cD(c.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},c.id))]})}function L5s({workflowId:e}={}){const{data:t,isLoading:n,error:r}=HEe(e?{workflowId:e}:{}),[s,i]=g.useState("");return r?o.jsx(Ws,{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(Wc,{onSearch:i,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(D5s,{schedules:t??[],isLoading:n,search:s})})]})}function F5s(){const[e]=bi(),t=e.get("workflowId")??void 0,{error:n}=HEe(t?{workflowId:t}:{});return n&&ks(n)?o.jsx(Qn,{children:o.jsx(Gs,{})}):n&&Es(n)?o.jsx(Qn,{children:o.jsx(Fs,{resource:"schedules"})}):o.jsx(Ft,{children:o.jsx("div",{className:"h-full",children:o.jsx(L5s,{workflowId:t})})})}const z5s={"--belt-hue":"var(--warning1)"};function B5s(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function U5s(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 V5s({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:o.jsxs("section",{className:"rounded-studio-panel border-border1/50 bg-surface3 shadow-panel pointer-events-auto relative isolate border","data-testid":"workflow-suspended-steps","aria-label":"Step suspended",children:[o.jsxs("div",{className:"max-h-[calc(100cqh-64px)] overflow-y-auto overscroll-contain rounded-[inherit]",children:[o.jsxs("div",{className:"border-border1/50 bg-surface2 flex items-center justify-between gap-3 border-b px-5 py-4",children:[o.jsxs(Te,{as:"h2",variant:"ui-sm",className:"text-neutral6 flex items-center gap-2 font-medium",children:[o.jsx(St,{children:o.jsx(sG,{})}),"Step suspended"]}),o.jsx(jt,{variant:"orange",emphasis:"muted",children:"Needs input"})]}),e.map(s=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const a=i?.resumeSchema?Pm(m0(i.resumeSchema)):Of(rr(),$f());return o.jsx(q5s,{step:s,stepSchema:a,description:i.description,onResume:r},`${s.runId}-${s.stepId}`)})]}),o.jsx(aMt,{status:"ready",label:"Needs input",className:"before:hidden",style:z5s})]})}function q5s({step:e,stepSchema:t,description:n,onResume:r}){const[s,i]=g.useState(!1),[a,l]=g.useState(!1),c=async u=>{l(!0);try{await r({stepId:e.stepId.split("."),runId:e.runId,resumeData:u})}catch(d){Ge.error(d instanceof Error?d.message:"Error resuming workflow")}finally{l(!1)}};return o.jsxs("div",{className:"[&+&]:border-border1/50 space-y-5 p-5 [&+&]:border-t",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Te,{as:"p",variant:"ui-md",className:"text-neutral6 font-medium break-words",children:e.stepId}),n&&o.jsx(Te,{as:"p",variant:"ui-sm",className:"text-neutral3",children:n})]}),e.suspendPayload!==void 0&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs(Te,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(St,{children:o.jsx(VRn,{})}),"The step is asking"]}),o.jsxs(dl,{open:s,onOpenChange:i,children:[o.jsxs(Zo,{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(St,{children:o.jsx(mr,{className:K("transition-transform text-neutral3",{"transform rotate-90":s})})}),o.jsx(Te,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:U5s(e.suspendPayload,e.stepId)})]}),o.jsx(Te,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:B5s(e.suspendPayload)})]}),o.jsx(Go,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Lr,{value:JSON.stringify(e.suspendPayload,null,2),editable:!1,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs(Te,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(St,{children:o.jsx(ZRn,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(jNe,{schema:t,isSubmitLoading:a,submitButtonLabel:"Resume",submitButtonVariant:"primary",submitButtonIcon:o.jsx(bu,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:c})})]})]})}function H5s({hidden:e}){const{result:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext(mc),{canExecute:i,isLoading:a}=No(),l=o2t(t,r),c=bbr(),u=t?.status==="suspended"&&l.length>0&&!s,d=!a&&i("workflows");return!n||!u||!d?null:o.jsx("div",{hidden:e,"data-testid":"workflow-suspended-overlay",className:"animate-in fade-in-0 slide-in-from-top-2 pointer-events-none absolute top-12 right-2 z-30 w-[380px] max-w-[calc(100%-16px)] duration-300 motion-reduce:animate-none",children:o.jsx(V5s,{suspendedSteps:l,workflow:n,isStreaming:s,onResume:c})},r)}const W5s=e=>e.includes("."),Z5s=e=>e==="input"||e.endsWith(".input"),mut=1;function G5s(e){return e<1e3?`${Number(e.toPrecision(3))}ms`:`${Number((e/1e3).toPrecision(3))}s`}const Zrn=e=>e.status==="running"&&e.endedAt===void 0;function Q5s(e,t){const n=e.startedAt;if(n===void 0||!Number.isFinite(n))return;const r=Zrn(e)?Math.max(t,n):e.endedAt;if(!(r===void 0||!Number.isFinite(r)||r<n))return{start:n,end:r}}function K5s(e,t){const n=Object.entries(e).filter(([l])=>!Z5s(l)).map(([l,c])=>({stepId:l,step:c,span:Q5s(c,t)})).sort((l,c)=>(l.span?.start??1/0)-(c.span?.start??1/0)||l.stepId.localeCompare(c.stepId)),r=n.flatMap(l=>l.span?[l.span]:[]),s=Math.min(...r.map(l=>l.start)),i=Math.max(s,...r.map(l=>l.end)),a=Math.max(i-s,1);return n.map(({stepId:l,step:c,span:u})=>{let d;if(u){const f=u.end-u.start,h=Math.min((u.start-s)/a*100,100-mut),p=Math.min(Math.max(f/a*100,mut),100-h);d={durationMs:f,offsetPct:h,widthPct:p}}return{stepId:l,step:c,status:c.status,timing:d,isRunning:Zrn(c),isNestedEntry:W5s(l)}})}const gut={success:{label:"Completed",icon:Mn,color:"text-positive1",bar:"bg-neutral3/60"},failed:{label:"Failed",icon:zD,color:"text-negative1",bar:"bg-negative1/60"},suspended:{label:"Needs input",icon:MC,color:"text-accent3",bar:"bg-accent3/60"},waiting:{label:"Waiting",icon:DC,color:"text-neutral3",bar:"bg-neutral3/40"},paused:{label:"Paused",icon:MC,color:"text-neutral3",bar:"bg-neutral3/40"},skipped:{label:"Skipped",icon:JPn,color:"text-neutral3",bar:"bg-neutral3/25"},running:{label:"Running",icon:vi,color:"text-accent6",bar:"bg-accent6/60"},canceled:{label:"Canceled",icon:Ls,color:"text-neutral3",bar:"bg-neutral3/40"}},Y5s={label:"Status unavailable",icon:gIn,color:"text-neutral3",bar:"bg-neutral3/25"};function X5s({row:e,isSelected:t,isHovered:n,onSelectStep:r,onHoverStep:s,onOpenInput:i,onOpenOutput:a}){const l=Object.hasOwn(gut,e.status)?gut[e.status]:Y5s,c=l.icon,u=e.stepId.slice(0,e.stepId.lastIndexOf(".")),d=e.isNestedEntry?e.stepId.slice(e.stepId.lastIndexOf(".")+1):e.stepId;return o.jsxs("div",{"data-testid":"workflow-timeline-row","data-workflow-step-key":e.stepId,onMouseEnter:()=>!e.isNestedEntry&&s(e.stepId),onMouseLeave:()=>!e.isNestedEntry&&s(null),className:K("grid grid-cols-[minmax(130px,1fr)_minmax(64px,1fr)_56px_64px] items-center gap-3 rounded-md px-2 py-1","@max-[540px]/workflow-timeline:grid-cols-[minmax(0,1fr)_48px_64px] @max-[540px]/workflow-timeline:gap-x-1.5 @max-[540px]/workflow-timeline:gap-y-1 @max-[540px]/workflow-timeline:py-2",(t||n)&&"bg-surface4"),children:[o.jsxs("button",{type:"button",className:"text-ui-xs text-neutral5 focus-visible:outline-neutral3 flex min-h-9 min-w-0 cursor-pointer items-center gap-2.5 text-left focus-visible:rounded-sm focus-visible:outline-2 focus-visible:outline-offset-2 aria-disabled:cursor-default","aria-disabled":e.isNestedEntry,"aria-pressed":t,onClick:()=>{e.isNestedEntry||r(e.stepId)},title:e.stepId,children:[o.jsx("span",{"aria-label":l.label,className:K("border-border1 bg-surface2 grid size-6 flex-none place-items-center rounded-md border",l.color),children:o.jsx(c,{"aria-hidden":!0,className:K("size-3.5",e.status==="running"&&"motion-safe:animate-spin")})}),o.jsxs("span",{className:"min-w-0",children:[o.jsx("span",{className:"block truncate",children:d}),e.isNestedEntry&&o.jsxs("span",{className:"text-neutral3 text-ui-xs flex min-w-0 items-center gap-1",children:[o.jsx(SCe,{"aria-hidden":!0,className:"size-3 shrink-0"}),o.jsx("span",{className:"truncate",children:u})]})]})]}),o.jsx("div",{className:"bg-surface4 relative h-5 min-w-0 overflow-hidden rounded-sm @max-[540px]/workflow-timeline:col-span-full @max-[540px]/workflow-timeline:row-start-2 @max-[540px]/workflow-timeline:ml-[34px]","aria-hidden":!0,children:e.timing&&o.jsx("div",{"data-testid":"workflow-timeline-bar","data-offset":e.timing.offsetPct,"data-width":e.timing.widthPct,className:K("absolute top-0 h-full min-w-0.5 rounded-sm",l.bar),style:{left:`${e.timing.offsetPct}%`,width:`${e.timing.widthPct}%`}})}),o.jsx("span",{className:"text-neutral3 text-ui-xs text-right whitespace-nowrap tabular-nums",children:e.timing?G5s(e.timing.durationMs):o.jsx("span",{"aria-label":"Timing unavailable",children:"—"})}),o.jsxs("div",{className:"flex items-center",children:[o.jsx(ae,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step input",disabled:e.step.input===void 0,onClick:f=>i(e,f.currentTarget),children:o.jsx(tG,{})}),o.jsx(ae,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step output",disabled:e.step.output===void 0,onClick:f=>a(e,f.currentTarget),children:o.jsx(nG,{})})]})]})}function J5s(){const{steps:e}=LR(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=eQ(),[i,a]=g.useState(()=>Date.now()),[l,c]=g.useState(!0),[u,d]=g.useState(!1),{showData:f}=nk(),h=g.useRef(null),p=K5s(e,i),m=p.some(v=>v.isRunning);return VEt(h,{enabled:m&&!l}),g.useEffect(()=>{if(!m||l)return;const v=setInterval(()=>a(Date.now()),100);return()=>clearInterval(v)},[m,l]),p.length===0?null:o.jsx("div",{"data-testid":"workflow-timeline",className:"relative z-20 shrink-0 px-2 pb-2",children:o.jsxs(dl,{open:!l,onOpenChange:v=>c(!v),className:"border-border1 bg-surface3 @container/workflow-timeline pointer-events-auto overflow-hidden rounded-xl border",children:[o.jsxs("div",{className:"flex items-center",children:[o.jsxs(Zo,{className:"hover:bg-surface4 text-ui-sm text-neutral5 flex min-h-11 min-w-0 flex-1 items-center gap-2 px-3.5 py-2.5","aria-label":l?"Expand timeline":"Collapse timeline",children:[o.jsx("span",{children:o.jsx(PSt,{"aria-hidden":!0,className:"text-neutral3 size-4"})}),o.jsx("span",{children:"Timeline"}),o.jsxs("span",{className:"text-neutral3 text-ui-xs",children:[p.length," events"]}),o.jsx("span",{className:"ml-auto",children:o.jsx($i,{"aria-hidden":!0,className:K("size-4 transition-transform motion-reduce:transition-none",l&&"-rotate-90")})})]}),!l&&o.jsx(ae,{variant:"ghost",size:"icon-sm",tooltip:u?"Restore timeline height":"Enlarge timeline","aria-pressed":u,onClick:()=>d(!u),className:"mr-2 shrink-0",children:u?o.jsx($St,{}):o.jsx(bCe,{})})]}),o.jsx(Go,{children:o.jsx("div",{ref:h,"data-testid":"workflow-timeline-list",className:K("overflow-auto overscroll-contain px-1.5 pb-1.5",u?"max-h-[min(720px,calc(100dvh-112px))]":"max-h-[min(320px,40dvh)]"),children:p.map(v=>o.jsx(X5s,{row:v,isSelected:t===v.stepId,isHovered:n===v.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:(y,b)=>f({type:"step-input",stepId:y.stepId},b),onOpenOutput:(y,b)=>f({type:"step-output",stepId:y.stepId},b)},v.stepId))})})]})})}const e6s=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=nk(),s=nR(),i=r?.type==="data",a=o.jsxs("div",{className:"[container-type:size] relative h-full min-h-0",children:[o.jsx(CHt,{workflowId:e,workflow:t,isLoading:n}),o.jsx(H5s,{hidden:i}),i&&o.jsx("div",{className:"pointer-events-auto absolute top-12 right-2 z-30 flex max-h-[calc(100cqh-64px)] w-[440px] max-w-[calc(100%-16px)] flex-col",children:o.jsx(rU,{})}),o.jsx("div",{className:"pointer-events-none absolute right-0 bottom-0 left-[var(--workflow-left-panel-width,0px)] z-20",children:o.jsx(J5s,{})})]});return s&&r&&!i?o.jsx("div",{className:"h-full min-h-0 overflow-hidden",children:o.jsx(rU,{})}):o.jsxs("div",{className:"relative h-full min-h-0",children:[a,o.jsxs(iDe,{className:"pointer-events-none absolute inset-0 z-30 min-h-0 w-full min-w-0 p-2",children:[o.jsx(I_,{id:"workflow-graph",className:"pointer-events-none min-w-0"}),r&&!i&&o.jsxs(o.Fragment,{children:[o.jsx(bZ,{className:"pointer-events-auto"}),o.jsx(I_,{id:"workflow-step-detail",minSize:300,maxSize:"60%",defaultSize:420,className:"min-w-0",children:o.jsx("div",{className:"rounded-studio-panel border-border1 bg-surface2 pointer-events-auto h-full min-h-0 overflow-hidden border",children:o.jsx(rU,{})})})]})]})]})},vut=()=>{const{workflowId:e}=ur(),{data:t,isLoading:n,error:r}=E5(e);return r&&ks(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Gs,{})}):r&&Es(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{resource:"workflows"})}):o.jsx(e6s,{workflowId:e,workflow:t??void 0,isLoading:n})};function t6s(e,t){if(e==null)return{};var n,r,s=kRt(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function Uke(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 n6s(e){if(Array.isArray(e))return Uke(e)}function r6s(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function s6s(e,t){if(e){if(typeof e=="string")return Uke(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)?Uke(e,t):void 0}}function i6s(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
691
+ ]`,Ict="flex min-h-0 flex-1 flex-col py-0";function uMs({tab:e,onTabChange:t,file:n,onFileSelect:r,onReplace:s,pastedText:i,onPastedTextChange:a,validation:l,isImporting:c}){return o.jsxs(hl,{value:e,defaultTab:"upload",onValueChange:t,className:"flex h-full flex-col gap-3",children:[o.jsxs(fl,{variant:"pill",children:[o.jsx(Sr,{value:"upload",children:"Upload file"}),o.jsx(Sr,{value:"paste",children:"Paste JSON"})]}),o.jsx(ts,{value:"upload",className:Ict,children:n?o.jsx(pMs,{file:n,validation:l,onReplace:s,isImporting:c}):o.jsx(dMs,{onFileSelect:r,disabled:c})}),o.jsx(ts,{value:"paste",className:Ict,children:o.jsx(Yd,{"aria-label":"JSON items",className:"text-ui-sm min-h-[200px] flex-1 resize-none font-mono",placeholder:cMs,spellCheck:!1,value:i,onChange:u=>a(u.target.value),disabled:c})})]})}function dMs({onFileSelect:e,disabled:t}){const[n,r]=g.useState(!1),s=g.useCallback(c=>{const u=c.target.files?.[0];u&&e(u),c.target.value=""},[e]),i=g.useCallback(c=>{c.preventDefault(),c.stopPropagation(),r(!0)},[]),a=g.useCallback(c=>{c.preventDefault(),c.stopPropagation(),r(!1)},[]),l=g.useCallback(c=>{if(c.preventDefault(),c.stopPropagation(),r(!1),t)return;const u=c.dataTransfer.files?.[0];u&&e(u)},[t,e]);return o.jsxs("div",{"data-testid":"json-dropzone",onDragOver:i,onDragLeave:a,onDrop:l,className:K("border-border1 bg-surface3 relative flex flex-1 flex-col items-center justify-center gap-3 rounded-lg border border-dashed px-4 py-6 text-center transition-colors","hover:border-accent1/50 hover:bg-accent1/5",n&&"border-accent1/50 bg-accent1/5",t&&"cursor-wait opacity-60"),children:[o.jsx("input",{type:"file",accept:".json,application/json","aria-label":"Choose a JSON file",onChange:s,disabled:t,className:"absolute inset-0 cursor-pointer opacity-0"}),o.jsx("div",{className:"border-border1 bg-surface2 text-neutral4 flex size-9 items-center justify-center rounded-md border",children:o.jsx(NA,{className:"size-4"})}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("p",{className:"text-ui-md text-neutral6",children:"Drop a JSON file here"}),o.jsxs("p",{className:"text-ui-sm text-neutral4",children:["or ",o.jsx("span",{className:"underline",children:"choose a file"})," from your computer"]})]}),o.jsxs("p",{className:"text-ui-xs text-neutral3",children:[".json · an array of items · up to ",JDe]})]})}function fMs(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function hMs(e){return typeof e=="string"?e:JSON.stringify(e)??""}function pMs({file:e,validation:t,onReplace:n,isImporting:r}){const s="rows"in t?t.rows:[],i="total"in t?t.total:0,a=s.slice(0,Aue);return o.jsxs("div",{"data-testid":"json-file-card",className:"border-border1 rounded-lg border",children:[o.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[o.jsx(CA,{className:"text-neutral4 size-4 shrink-0"}),o.jsx("span",{className:"text-ui-sm text-neutral6 min-w-0 flex-1 truncate font-mono",children:e.name}),o.jsx("span",{className:"text-ui-xs text-neutral3 shrink-0",children:fMs(e.size)}),o.jsx(ae,{icon:o.jsx(d0,{}),variant:"ghost",size:"xs",onClick:n,disabled:r,children:"Replace"})]}),a.map(l=>o.jsxs("div",{className:"border-border1 grid grid-cols-[2rem_1fr_auto] items-center gap-2 border-t px-3 py-1.5",children:[o.jsx("span",{className:"text-ui-xs text-neutral3",children:l.index}),o.jsx("span",{className:"text-ui-sm text-neutral5 truncate font-mono",children:hMs(l.input)}),l.hasInput?l.hasGroundTruth?null:o.jsx(jt,{variant:"yellow",size:"xs",children:"no groundTruth"}):o.jsx(jt,{variant:"red",size:"xs",children:"no input"})]},l.index)),i>Aue&&o.jsxs("div",{className:"border-border1 text-ui-xs text-neutral3 border-t px-3 py-1.5",children:["+ ",i-Aue," more"]})]})}const mMs=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)});function gMs({datasetId:e,datasetName:t,open:n,onOpenChange:r,onSuccess:s}){const[i,a]=g.useState("upload"),[l,c]=g.useState(null),[u,d]=g.useState(""),[f,h]=g.useState(null),[p,m]=g.useState(""),[v,y]=g.useState(!1),b=g.useRef(0),{batchInsertItems:x}=pl(),w=i==="upload"?u:p,k=g.useMemo(()=>i==="upload"&&f?{status:"error",kind:"parse",message:f}:e$s(w),[i,f,w]),_=g.useCallback(async I=>{const A=++b.current;if(!I.name.toLowerCase().endsWith(".json")){h("Only .json files are supported");return}if(I.size>Dnn){h(`File is larger than ${JDe}`);return}try{const P=await mMs(I);if(A!==b.current)return;c({name:I.name,size:I.size}),d(P),h(null)}catch{if(A!==b.current)return;h("Could not read the file")}},[]),C=g.useCallback(()=>{b.current++,c(null),d(""),h(null)},[]),T=g.useCallback(()=>{b.current++,a("upload"),c(null),d(""),h(null),m("")},[]),E=g.useCallback(()=>{v||(r(!1),setTimeout(T,150))},[v,r,T]),N=g.useCallback(async()=>{if(k.status==="ready"){y(!0);try{await x.mutateAsync({datasetId:e,items:k.items}),Ge.success(`Imported ${k.total} item${k.total!==1?"s":""}`),s?.(),r(!1),setTimeout(T,150)}catch(I){Ge.error(I instanceof Error?I.message:"Failed to import items")}finally{y(!1)}}},[k,x,e,s,r,T]);return o.jsx(hs,{open:n,onOpenChange:E,children:o.jsxs(Jr,{className:"flex max-h-[90vh] w-[960px] max-w-[calc(100vw-2rem)] flex-col gap-0 p-0",children:[o.jsxs(es,{className:"border-border1 border-b px-4 py-4",children:[o.jsx(Kr,{children:"Import into dataset"}),o.jsxs(Ps,{className:"text-ui-sm text-neutral3 not-sr-only",children:["Add items to"," ",t?o.jsx("code",{className:"bg-surface3 text-ui-xs text-neutral6 rounded px-1 font-mono",children:t}):"this dataset"," ","from a JSON file or paste them directly."]})]}),o.jsx(vs,{className:"max-h-none min-h-0 flex-1 overflow-y-auto p-0",children:o.jsxs("div",{className:"divide-border1 grid divide-y md:grid-cols-[1.15fr_1fr] md:divide-x md:divide-y-0",children:[o.jsx("div",{className:"flex min-h-[360px] flex-col p-4",children:o.jsx(uMs,{tab:i,onTabChange:a,file:l,onFileSelect:_,onReplace:C,pastedText:p,onPastedTextChange:m,validation:k,isImporting:v})}),o.jsx("div",{className:"p-4",children:o.jsx(lMs,{})})]})}),o.jsxs(lc,{className:"border-border1 items-center border-t px-4 py-3 sm:justify-between",children:[o.jsx(vMs,{validation:k}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(ae,{icon:o.jsx(Yt,{}),onClick:E,disabled:v,children:"Cancel"}),o.jsxs(ae,{variant:"primary",onClick:N,disabled:k.status!=="ready"||v,children:[v&&o.jsx(_n,{}),k.status==="ready"?`Import ${k.total} item${k.total!==1?"s":""}`:"Import"]})]})]})]})})}function vMs({validation:e}){const t=K("size-1.5 shrink-0 rounded-full",e.status==="idle"&&"bg-neutral3",e.status==="ready"&&"bg-accent1",e.status==="error"&&"bg-accent2");let n;switch(e.status){case"idle":n="No items yet";break;case"ready":n=o.jsxs(o.Fragment,{children:[o.jsx("b",{className:"text-neutral6 font-medium",children:e.total})," item",e.total!==1?"s":""," ready",e.missingGroundTruthCount>0&&` · ${e.missingGroundTruthCount} without groundTruth`]});break;case"error":switch(e.kind){case"parse":n=`Not valid JSON — ${e.message}`;break;case"not-array":n="Top level must be an array of items";break;case"empty":n="The array has no items";break;case"too-large":n=`JSON is larger than ${JDe}`;break;case"missing-input":n=o.jsxs(o.Fragment,{children:[o.jsx("b",{className:"text-neutral6 font-medium",children:e.missingInputCount})," of ",e.total," item",e.total!==1?"s":""," ",e.missingInputCount!==1?"have":"has"," no"," ",o.jsx("code",{className:"font-mono",children:"input"})]});break}break}return o.jsxs("div",{role:"status",className:"text-ui-sm text-neutral4 flex min-w-0 items-center gap-2",children:[o.jsx("span",{className:t}),o.jsx("span",{className:"truncate",children:n})]})}function yMs(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 Knn({active:e,onPrevious:t,onNext:n,onClose:r}){g.useEffect(()=>{if(!e)return;const s=i=>{i.defaultPrevented||yMs(i.target)||(i.key==="PageUp"?(i.preventDefault(),t?.()):i.key==="PageDown"?(i.preventDefault(),n?.()):i.key==="Escape"&&(i.preventDefault(),r()))};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,t,n,r])}const Ynn=g.createContext(null);function bMs({datasetId:e,items:t,isLoadingItems:n,children:r}){const s=Fr(),a=q1t("/datasets/:datasetId/items/:itemId")?.params.itemId,l=g.useCallback(p=>{s(`/datasets/${e}/items/${encodeURIComponent(p)}`)},[s,e]),c=g.useCallback(()=>{s(`/datasets/${e}`)},[s,e]),u=g.useMemo(()=>a?t.findIndex(p=>p.id===a):-1,[t,a]),d=g.useMemo(()=>{if(u<=0)return;const p=t[u-1].id;return()=>l(p)},[u,t,l]),f=g.useMemo(()=>{if(u<0||u>=t.length-1)return;const p=t[u+1].id;return()=>l(p)},[u,t,l]);Knn({active:!!a,onPrevious:d,onNext:f,onClose:c});const h=g.useMemo(()=>({datasetId:e,items:t,isLoadingItems:n,currentItemId:a,openItem:l,close:c,goToPreviousItem:d,goToNextItem:f}),[e,t,n,a,l,c,d,f]);return o.jsx(Ynn.Provider,{value:h,children:r})}function Xnn(){const e=g.useContext(Ynn);if(!e)throw new Error("useDatasetItemPanel must be used within a DatasetItemPanelProvider");return e}function xMs({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,leftSlot:r,rightSlot:s,belowToolbarSlot:i}){const[a,l]=bi(),{activeVersion:c}=tLe(a,l),[u,d]=g.useState(!1),[f,h]=g.useState(!1),[p,m]=g.useState(!1),[v,y]=g.useState([]),[b,x]=g.useState(!1),[w,k]=g.useState([]),[_,C]=g.useState(!1),[T,E]=g.useState([]),[N,I]=g.useState(0),[A,P]=g.useState(""),[L]=RTe(A,300),{data:M}=bv(e),{data:V=[],isLoading:q,setEndOfListElement:H,isFetchingNextPage:B,hasNextPage:W}=gA(e,L||void 0,c),{deleteItems:z}=pl(),{currentItemId:G,openItem:F,close:R}=Xnn(),D=X=>{G===X?R():F(X)},U=X=>{y(X),m(!0)},Q=X=>{k(X),x(!0)},ee=X=>{x(X),X||(k([]),I(ne=>ne+1))},J=X=>{E(X),C(!0)},te=async()=>{await z.mutateAsync({datasetId:e,itemIds:T}),Ge.success(`Deleted ${T.length} items`),C(!1),E([]),I(X=>X+1)},re=X=>{m(!1),y([]),I(ne=>ne+1),n?.(X)},ce=X=>{m(X),X||(y([]),I(ne=>ne+1))};return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"grid h-full overflow-auto",children:o.jsx(iMs,{items:V,leftSlot:r,rightSlot:s,belowToolbarSlot:i,isLoading:q,onItemClick:D,featuredItemId:G,onAddClick:t??(()=>{}),onImportClick:()=>d(!0),onImportJsonClick:()=>h(!0),onBulkDeleteClick:J,onCreateDatasetClick:U,onAddToDatasetClick:Q,datasetName:M?.name,clearSelectionTrigger:N,setEndOfListElement:H,isFetchingNextPage:B,hasNextPage:W,searchQuery:A,activeSearchQuery:L,onSearchChange:P,currentDatasetVersion:M?.version})}),o.jsx(J$s,{datasetId:e,open:u,onOpenChange:d}),o.jsx(gMs,{datasetId:e,datasetName:M?.name,open:f,onOpenChange:h}),o.jsx(P$s,{open:p,onOpenChange:ce,items:v,onSuccess:re}),o.jsx($$s,{open:b,onOpenChange:ee,items:w,currentDatasetId:e}),o.jsx(At,{open:_,onOpenChange:C,children:o.jsxs(At.Content,{children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Delete Items"}),o.jsxs(At.Description,{children:["Are you sure you want to delete ",T.length," item",T.length!==1?"s":"","? This action cannot be undone."]})]}),o.jsxs(At.Footer,{children:[o.jsx(At.Cancel,{children:"Cancel"}),o.jsx(At.Action,{onClick:te,children:z.isPending?"Deleting...":"Delete"})]})]})})]})}const Act="__create_tag__";function wMs({datasetId:e}){const{data:t}=bv(e),{data:n}=q0(),{updateDataset:r}=pl(),[s,i]=g.useState(""),a=g.useMemo(()=>Array.isArray(t?.tags)?t.tags:[],[t?.tags]),l=g.useMemo(()=>Bnn(n?.datasets??[]),[n?.datasets]),c=g.useMemo(()=>{const h=l.map(v=>({label:v,value:v,end:a.includes(v)?o.jsx(Mn,{"data-testid":"tag-applied",className:"size-3.5"}):void 0})),p=s.trim();return p.length>0&&!l.includes(p)&&!a.includes(p)?[{label:`Create "${p}"`,value:Act},...h]:h},[l,a,s]),u=h=>{r.mutate({datasetId:e,tags:h},{onError:()=>Ge.error("Failed to update tags")})},d=h=>{const p=h===Act?s.trim():h;!p||a.includes(p)||u([...a,p])},f=h=>{u(a.filter(p=>p!==h))};return o.jsxs("div",{"data-testid":"dataset-tags-editor",className:"flex flex-wrap items-center gap-2",children:[a.map(h=>o.jsxs(mJ,{value:h,size:"md",className:"gap-1 pr-1",children:[h,o.jsx("button",{type:"button","aria-label":`Remove tag ${h}`,disabled:r.isPending,onClick:()=>f(h),className:"cursor-pointer rounded-sm hover:opacity-70 disabled:opacity-50",children:o.jsx(Yt,{className:"size-3"})})]},h)),o.jsx(qo,{options:c,value:void 0,onValueChange:d,onInputValueChange:i,placeholder:o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(B_,{className:"size-3.5"}),"Add tag"]}),searchPlaceholder:"Search or create tag...",emptyText:"Type to create a tag",variant:"ghost",size:"xs",className:"w-auto min-w-0",disabled:r.isPending})]})}function Jnn({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(uc,{id:"override-dataset-scorers",checked:e,onCheckedChange:t,disabled:s}),o.jsx(Vt,{htmlFor:"override-dataset-scorers",children:"Override dataset scorers"})]}),o.jsx("p",{className:"text-muted-foreground text-ui-sm",children:e?"Only selected scorers run for this item. Leave empty to run no scorers.":"Use scorers attached to the dataset."}),e?o.jsx(vJ,{selectedScorers:n,setSelectedScorers:r,disabled:s,label:"Item scorers",helperText:"Choose from scorers that can be resolved by this Mastra instance."}):null]})}function SMs(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 Rue({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-ui-sm",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function kMs({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,i]=g.useState("{}"),[a,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState(""),[h,p]=g.useState(!1),[m,v]=g.useState([]),[y,b]=g.useState(""),[x,w]=g.useState(null),{addItem:k}=pl(),_=()=>{i("{}"),l(""),u(""),f(""),p(!1),v([]),b(""),w(null)},C=P=>{_(),n(P)},T=async P=>{P.preventDefault();let L;try{L=JSON.parse(s)}catch{Ge.error("Input must be valid JSON");return}let M;if(a.trim())try{M=JSON.parse(a)}catch{Ge.error("Ground Truth must be valid JSON");return}let V;if(c.trim())try{V=JSON.parse(c)}catch{Ge.error("Expected Trajectory must be valid JSON");return}let q;if(d.trim())try{const B=JSON.parse(d);if(!Array.isArray(B)){Ge.error("Tool Mocks must be a JSON array");return}q=B}catch{Ge.error("Tool Mocks must be valid JSON");return}let H;if(y.trim())try{H=JSON.parse(y)}catch{Ge.error("Request Context must be valid JSON");return}try{await k.mutateAsync({datasetId:e,input:L,groundTruth:M,expectedTrajectory:V,toolMocks:q,scorerIds:h?m:void 0,requestContext:H}),Ge.success("Item added successfully"),C(!1),r?.()}catch(B){const W=SMs(B);W?w(W):Ge.error(`Failed to add item: ${B instanceof Error?B.message:"Unknown error"}`)}},E=P=>{i(P),x?.field==="input"&&w(null)},N=P=>{l(P),x?.field==="groundTruth"&&w(null)},I=P=>{f(P),x?.field==="toolMocks"&&w(null)},A=()=>{C(!1)};return o.jsxs(_a,{dialogTitle:"Add Item",dialogDescription:"Create a new dataset item",isOpen:t,onClose:A,level:1,children:[o.jsx(_a.Top,{children:"Add Item"}),o.jsxs(_a.Content,{children:[o.jsx(_a.Header,{children:o.jsx(_a.Heading,{children:"Add Item"})}),o.jsxs("form",{onSubmit:T,className:"grid gap-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Vt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Lr,{value:s,onChange:E,showCopyButton:!1,className:"min-h-[240px]"}),x?.field==="input"&&o.jsx(Rue,{field:"input",errors:x.errors})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Vt,{htmlFor:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),o.jsx(Lr,{value:a,onChange:N,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="groundTruth"&&o.jsx(Rue,{field:"groundTruth",errors:x.errors})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Vt,{htmlFor:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),o.jsx(Lr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[200px]"})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Vt,{htmlFor:"item-tool-mocks",children:"Tool Mocks (JSON array, optional)"}),o.jsx(Lr,{value:d,onChange:I,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="toolMocks"&&o.jsx(Rue,{field:"toolMocks",errors:x.errors})]}),o.jsx(Jnn,{overrideEnabled:h,onOverrideEnabledChange:p,selectedScorerIds:m,onSelectedScorerIdsChange:v,disabled:k.isPending}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Vt,{htmlFor:"item-request-context",children:"Request Context (JSON, optional)"}),o.jsx(Lr,{value:y,onChange:b,showCopyButton:!1,className:"min-h-[200px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ae,{icon:o.jsx(Yt,{}),type:"button",onClick:A,children:"Cancel"}),o.jsx(ae,{icon:o.jsx(Yr,{}),type:"submit",variant:"primary",disabled:k.isPending,children:k.isPending?"Adding...":"Add Item"})]})]})]})]})}const uO=e=>JSON.stringify(e??null,null,2),OMs=[{key:"input",title:"Input",icon:o.jsx(eI,{}),value:e=>uO(e.input)},{key:"groundTruth",title:"Ground Truth",icon:o.jsx(Gx,{}),value:e=>uO(e.groundTruth)},{key:"expectedTrajectory",title:"Expected Trajectory",icon:o.jsx(i1t,{}),value:e=>e.expectedTrajectory!=null?uO(e.expectedTrajectory):void 0},{key:"toolMocks",title:"Tool Mocks",icon:o.jsx(xu,{}),value:e=>uO(e.toolMocks??[])},{key:"scorerIds",title:"Scorers",icon:o.jsx(TCe,{}),value:e=>e.scorerIds===void 0?"Inherited from dataset":uO(e.scorerIds)},{key:"requestContext",title:"Request Context",icon:o.jsx(Bl,{}),value:e=>e.requestContext!=null?uO(e.requestContext):void 0},{key:"metadata",title:"Metadata",icon:o.jsx(B_,{}),value:e=>uO(e.metadata)}];function Rke({item:e,diff:t}){return o.jsxs(o.Fragment,{children:[o.jsxs(fn,{children:[o.jsx(fn.Key,{children:"Dataset Id"}),o.jsx(fn.ValueWithCopyBtn,{copyTooltip:"Copy Dataset Id to clipboard",copyValue:e.datasetId,children:e.datasetId}),o.jsx(fn.Key,{children:"Version"}),o.jsxs(fn.Value,{children:["v",e.datasetVersion]}),o.jsx(fn.Key,{children:"Created"}),o.jsx(fn.Value,{children:gr(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")}),o.jsx(fn.Key,{children:"Updated"}),o.jsx(fn.Value,{children:e.updatedAt&&new Date(e.updatedAt).getTime()!==new Date(e.createdAt).getTime()?gr(new Date(e.updatedAt),"MMM d, yyyy h:mm aaa"):"n/a"})]}),o.jsx("div",{className:"mt-3 grid gap-3",children:OMs.map(n=>{const r=n.value(e),s=t?n.value(t.against):void 0;return r===void 0&&s===void 0?null:o.jsx($t.CodeSection,{title:n.title,icon:n.icon,codeStr:r??"",diff:t?{against:s??"",side:t.side}:void 0},n.key)})})]})}function Pue({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-ui-sm",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function CMs({inputValue:e,setInputValue:t,groundTruthValue:n,setGroundTruthValue:r,metadataValue:s,setMetadataValue:i,trajectoryValue:a,setTrajectoryValue:l,toolMocksValue:c,setToolMocksValue:u,scorerOverrideEnabled:d,setScorerOverrideEnabled:f,selectedScorerIds:h,setSelectedScorerIds:p,requestContextValue:m,setRequestContextValue:v,validationErrors:y,onSave:b,onCancel:x,isSaving:w}){return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"mb-4",children:o.jsxs("h3",{className:"text-header-sm flex items-center gap-2 font-medium",children:[o.jsx(Gd,{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(Vt,{children:"Input (JSON) *"}),o.jsx(Lr,{value:e,onChange:t,showCopyButton:!1,className:"min-h-[120px]"}),y?.field==="input"&&o.jsx(Pue,{field:"input",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Vt,{children:"Ground Truth (JSON, optional)"}),o.jsx(Lr,{value:n,onChange:r,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="groundTruth"&&o.jsx(Pue,{field:"groundTruth",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Vt,{children:"Expected Trajectory (JSON, optional)"}),o.jsx(Lr,{value:a,onChange:l,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Vt,{children:"Tool Mocks (JSON array, optional)"}),o.jsxs("p",{className:"text-muted-foreground text-ui-sm",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(Lr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="toolMocks"&&o.jsx(Pue,{field:"toolMocks",errors:y.errors})]}),o.jsx(Jnn,{overrideEnabled:d,onOverrideEnabledChange:f,selectedScorerIds:h,onSelectedScorerIdsChange:p,disabled:w}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Vt,{children:"Request Context (JSON, optional)"}),o.jsx(Lr,{value:m,onChange:v,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Vt,{children:"Metadata (JSON, optional)"}),o.jsx(Lr,{value:s,onChange:i,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex gap-2 pt-4",children:[o.jsx(ae,{icon:o.jsx(Mn,{}),variant:"primary",onClick:b,disabled:w,children:w?"Saving...":"Save Changes"}),o.jsx(ae,{icon:o.jsx(Yt,{}),onClick:x,disabled:w,children:"Cancel"})]})]})]})}const _Ms=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function EMs({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:i,isLoading:a}=rh(),{data:l,isLoading:c}=eg(),{data:u,isLoading:d}=Ep(),f=e==="agent"?Object.entries(i??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="workflow"?Object.entries(l??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="scorer"?Object.entries(u??{}).map(([v,y])=>({value:v,label:y.scorer?.config?.name??v})):[],h=e==="agent"&&a||e==="workflow"&&c||e==="scorer"&&d,p=v=>{t(v),r("")},m=e==="agent"?"Agent":e==="workflow"?"Workflow":"Scorer";return o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Vt,{children:"Target Type"}),o.jsx(qo,{options:_Ms,value:e,onValueChange:p,placeholder:"Select target type",searchPlaceholder:"Search types...",emptyText:"No types available",container:s})]}),e&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Vt,{children:m}),o.jsx(qo,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:h,container:s})]})]})}const TMs=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform);function jMs({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return Pm(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(Vt,{children:"Request Context"}),o.jsx(i5,{schema:n,onValuesChange:t,className:"[&_button[type=submit]]:hidden"})]}):o.jsx("p",{className:"text-destructive text-ui-md",children:"Failed to parse request context schema"})}function $ue({index:e,done:t,isLast:n,children:r}){return o.jsxs("li",{className:"flex gap-4",children:[o.jsxs("div",{className:"flex flex-col items-center",children:[o.jsx("span",{"aria-hidden":"true",className:K("flex size-6 shrink-0 items-center justify-center rounded-full border text-ui-xs font-medium",t?"border-accent1 bg-accent1 text-white":"border-border1 text-neutral3"),children:e}),!n&&o.jsx("span",{"aria-hidden":"true",className:"bg-border1 mt-2 w-px flex-1"})]}),o.jsx("div",{className:K("min-w-0 flex-1 space-y-3",!n&&"pb-4"),children:r})]})}function yJ({initialDatasetId:e,initialDatasetVersion:t,initialScorerIds:n,initialTargetType:r,initialTargetId:s,initialName:i,initialDescription:a,open:l,onOpenChange:c,onSuccess:u}){const d=g.useRef(null),[f,h]=g.useState(i??""),[p,m]=g.useState(a??""),[v,y]=g.useState(e??""),[b,x]=g.useState(t??null),[w,k]=g.useState(r??""),[_,C]=g.useState(s??""),[T,E]=g.useState(n??null),[N,I]=g.useState({}),[A,P]=g.useState(""),{triggerExperiment:L}=pl(),{data:M}=bv(v),{total:V}=gA(v,void 0,b),q=M?.requestContextSchema,H=M?.scorerIds??[],B=T===null&&H.length>0,W=T??H,z=!!(q&&Object.keys(q).length>0),G=!!(v&&w&&_&&f.trim()),F=L.isPending,R=[!f.trim()&&"name",!v&&"dataset",!_&&"target"].filter(Boolean),D=z?Object.values(N).some(ce=>ce!==void 0&&ce!==""):A.trim().length>0,U=ce=>{y(ce),x(null),E(n??null),I({})},Q=()=>{h(i??""),m(a??""),y(e??""),x(t??null),k(r??""),C(s??""),E(n??null),I({}),P("")},ee=()=>{if(z){const ce=Object.entries(N).filter(([,X])=>X!==void 0&&X!=="");return ce.length>0?Object.fromEntries(ce):void 0}if(A.trim()){let ce;try{ce=JSON.parse(A)}catch{throw new Error("Request Context must be valid JSON")}if(!ce||typeof ce!="object"||Array.isArray(ce))throw new Error("Request Context must be a JSON object");return ce}},J=async()=>{if(!v||!w||!_||!f.trim())return;let ce;try{ce=ee()}catch(X){const ne=X instanceof Error?X.message:"Request Context must be valid JSON";hu.error(ne);return}try{const X=await L.mutateAsync({datasetId:v,name:f.trim(),description:p.trim()||void 0,targetType:w,targetId:_,scorerIds:W.length>0?W:void 0,version:b??void 0,requestContext:ce});hu.success("Experiment triggered successfully"),c(!1),u?.(X.experimentId),Q()}catch(X){const ne=X instanceof Error?X.message:"Failed to trigger experiment";hu.error(ne)}},te=()=>{F||(c(!1),Q())},re=ce=>{(ce.metaKey||ce.ctrlKey)&&ce.key==="Enter"&&G&&!F&&(ce.preventDefault(),J())};return o.jsx(hs,{open:l,onOpenChange:te,children:o.jsxs(Jr,{ref:d,className:"w-[640px] max-w-[calc(100vw-2rem)] gap-0 p-0",onKeyDown:re,children:[o.jsxs(es,{className:"border-border1 border-b px-4 py-4",children:[o.jsx(Kr,{children:"Run experiment"}),o.jsx(Ps,{className:"text-ui-sm text-neutral3 not-sr-only",children:"Pick a dataset, choose what to run it against, and optionally score the results."})]}),o.jsxs(vs,{className:"max-h-[70vh] space-y-6 overflow-y-auto px-4 py-5",children:[o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Vt,{htmlFor:"experiment-name",children:"Name *"}),o.jsx($n,{id:"experiment-name",value:f,onChange:ce=>h(ce.target.value),placeholder:"Enter experiment name",autoFocus:!0,disabled:F})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Vt,{htmlFor:"experiment-description",children:"Description"}),o.jsx(Yd,{id:"experiment-description",value:p,onChange:ce=>m(ce.target.value),placeholder:"Enter experiment description (optional)",disabled:F,rows:2})]})]}),o.jsxs("ol",{className:"list-none",children:[o.jsxs($ue,{index:1,done:!!v,children:[o.jsxs("div",{className:"grid grid-cols-[1fr_140px] gap-3",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Vt,{children:"Dataset"}),o.jsx(OEt,{value:v,onValueChange:U,container:d})]}),v&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Vt,{children:"Version"}),o.jsx(Qnn,{datasetId:v,value:b,onValueChange:x,container:d})]})]}),v&&V!==void 0&&o.jsxs("p",{className:"text-ui-xs text-neutral3",children:[V," ",V===1?"item":"items"]})]}),o.jsxs($ue,{index:2,done:!!_,children:[o.jsx(EMs,{targetType:w,setTargetType:k,targetId:_,setTargetId:C,container:d}),w&&!_&&o.jsxs("p",{className:"text-ui-xs text-neutral3",children:["Choose ",w==="agent"?"an":"a"," ",w," to run"]})]}),o.jsx($ue,{index:3,done:W.length>0,isLast:!0,children:o.jsx(vJ,{selectedScorers:W,setSelectedScorers:E,disabled:F,container:d,helperText:B?"Pre-filled from the dataset's default scorers.":"Scores are computed after each item runs."})})]}),o.jsxs(dl,{children:[o.jsxs(Zo,{className:"text-ui-sm flex items-center gap-2",children:[o.jsx(mr,{className:"size-4"}),"Request Context (JSON, optional)",D&&o.jsx(jt,{size:"xs",variant:"blue",children:"set"})]}),o.jsx(Go,{className:"pt-3",children:z?o.jsx(jMs,{requestContextSchema:q,onChange:I}):o.jsx(Lr,{value:A,onChange:P,showCopyButton:!1,"aria-label":"Request context JSON",className:"min-h-[160px]"})})]})]}),o.jsxs(lc,{className:"border-border1 items-center border-t px-4 py-4 sm:justify-between",children:[o.jsx("p",{"data-testid":"experiment-run-status","aria-live":"polite",className:"flex items-center gap-2",children:R.length===0?o.jsxs(o.Fragment,{children:[o.jsx(jt,{variant:"green",indicator:"dot",children:"Ready"}),o.jsxs("span",{className:"text-ui-xs text-neutral3",children:[V??0," items · ",w," · ",W.length," scorers"]})]}):o.jsxs(jt,{variant:"neutral",indicator:"dot",children:["Missing ",R.join(", ")]})}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ae,{icon:o.jsx(Yt,{}),onClick:te,disabled:F,children:"Cancel"}),o.jsx(ae,{variant:"primary",onClick:J,disabled:!G||F,children:F?o.jsxs(o.Fragment,{children:[o.jsx(_n,{className:"h-4 w-4"}),"Running..."]}):o.jsxs(o.Fragment,{children:["Run",o.jsxs("span",{className:"ml-1 inline-flex gap-0.5","aria-hidden":"true",children:[o.jsx(Pf,{size:"xs",children:TMs?"⌘":"Ctrl"}),o.jsx(Pf,{size:"xs",children:"↵"})]})]})})]})]})]})})}const ern=g.createContext(null);function NMs({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:i,children:a}){const l=Fr(),u=q1t("/experiments/:experimentId/items/:itemId")?.params.itemId,d=g.useCallback(y=>{l(`/experiments/${e}/items/${encodeURIComponent(y)}`)},[l,e]),f=g.useCallback(()=>{l(`/experiments/${e}`)},[l,e]),h=g.useMemo(()=>u?r.findIndex(y=>y.itemId===u):-1,[r,u]),p=g.useMemo(()=>{if(h<=0)return;const y=r[h-1].itemId;return()=>d(y)},[h,r,d]),m=g.useMemo(()=>{if(h<0||h>=r.length-1)return;const y=r[h+1].itemId;return()=>d(y)},[h,r,d]);Knn({active:!!u,onPrevious:p,onNext:m,onClose:f});const v=g.useMemo(()=>({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:i,currentItemId:u,openItem:d,close:f,goToPreviousItem:p,goToNextItem:m}),[e,t,n,r,s,i,u,d,f,p,m]);return o.jsx(ern.Provider,{value:v,children:a})}function trn(){const e=g.useContext(ern);if(!e)throw new Error("useExperimentItemPanel must be used within an ExperimentItemPanelProvider");return e}const IMs=new Set(["itemId","id","status","input","tags","scores"]);function nLe({results:e,isLoading:t,featuredResultId:n,onResultClick:r,columns:s,scoresByItemId:i,scorerIds:a,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u,emptyMessage:d="No results yet",selectedIds:f,onToggleSelect:h,onToggleSelectAll:p}){const{Link:m,paths:v}=un(),y=!!(f&&h),b=s.filter(M=>IMs.has(M.name)||a?.includes(M.name)),x=[y?"2rem":"",...b.map(M=>M.size)].filter(Boolean).join(" "),w=M=>b.some(V=>V.name===M),k=w("itemId")||w("id"),_=w("status"),C=w("input"),T=w("tags"),E=w("scores"),N=f?e.filter(M=>f.has(M.id)).length:0,I=e.length>0&&N===e.length,{containerRef:A,getRowProps:P}=Zc({count:e.length}),L=M=>a?.includes(M.name)?o.jsx(we.TopCell,{children:o.jsxs(m,{href:v.scorerLink(M.name),className:"flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[o.jsx(dw,{}),o.jsx("span",{className:"min-w-0 truncate",children:M.label})]})},M.name):o.jsx(we.TopCell,{children:M.label},M.name);return t?o.jsx(Wl,{columns:x}):o.jsxs(we,{columns:x,className:"min-w-0",scrollRef:A,fit:"container",children:[o.jsxs(we.Top,{hasLeadingCell:y,children:[y&&(p?o.jsx(we.TopSelectCell,{checked:I?!0:N>0?"indeterminate":!1,onToggle:p,"aria-label":"Select all"}):o.jsx(we.TopCell,{children:" "})),y?o.jsx(we.TopCells,{colStart:2,children:b.map(L)}):b.map(L)]}),e.length===0?o.jsx(we.NoMatch,{message:d}):o.jsxs(o.Fragment,{children:[e.map((M,V)=>{const q=!!M.error,H=M.id===n,B=o.jsxs(o.Fragment,{children:[k&&o.jsxs(we.Cell,{className:"text-ui-smd text-neutral3 flex items-center gap-1.5 tracking-wide",children:[o.jsx("span",{children:M.itemId?.slice(0,8)??""}),q&&o.jsxs(In,{children:[o.jsx(On,{render:o.jsx(JN,{role:"img","aria-label":"Error",className:"text-error size-3.5"})}),o.jsx(Cn,{children:RMs(M.error)})]})]}),_&&o.jsx(we.Cell,{className:"flex items-center","data-testid":`result-status-${M.id}`,children:M.status?o.jsx(HDe,{status:M.status}):o.jsx("span",{className:"text-neutral2",children:"—"})}),C&&o.jsx(we.TextCell,{font:"mono",children:$Ms(PMs(M.input),200)}),T&&o.jsx(we.Cell,{className:"flex items-center gap-1 overflow-hidden","data-testid":`result-tags-${M.id}`,children:M.tags?.map(W=>o.jsx(mJ,{value:W,className:"shrink-0"},W))}),E&&o.jsx(we.Cell,{children:o.jsx(AMs,{scores:M.scores})}),a?.map(W=>{const G=i?.[M.itemId]?.find(F=>F.scorerId===W);return o.jsx(we.Cell,{className:"text-neutral3 text-ui-smd font-mono",children:G!=null?G.score.toFixed(3):"-"},W)})]});return y?o.jsxs(we.RowWrapper,{children:[o.jsx(we.SelectCell,{checked:f.has(M.id),onToggle:()=>h(M.id),"aria-label":`Select result ${M.itemId}`}),o.jsx(we.RowButton,{colStart:2,featured:H,"data-selected":H||void 0,onClick:()=>r(M.id),...P(V),children:B})]},M.id):o.jsx(we.RowButton,{featured:H,"data-selected":H||void 0,onClick:()=>r(M.id),...P(V),children:B},M.id)}),o.jsx(we.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function AMs({scores:e}){const t=Array.isArray(e)?e.map(n=>n.score).filter(n=>n!=null):Object.values(e??{});return t.length===0?o.jsx(Te,{variant:"ui-xs",className:"text-neutral2",children:"—"}):o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(St,{size:"sm",className:"text-neutral3",children:o.jsx(gb,{})}),o.jsx(Te,{variant:"ui-xs",className:"text-neutral4 font-mono",children:t[0].toFixed(2)}),t.length>1&&o.jsxs(jt,{children:["+",t.length-1]})]})}function RMs(e){return e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?e.message||"Error":typeof e=="string"&&e?e:"Error"}function PMs(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function $Ms(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}function MMs({experimentId:e,experimentStatus:t,results:n,isLoading:r,setEndOfListElement:s,isFetchingNextPage:i,hasNextPage:a,selectedIds:l,onToggleSelect:c}){const{currentItemId:u,openItem:d,close:f}=trn(),h=g.useMemo(()=>u?n.find(b=>b.itemId===u)?.id??null:null,[n,u]),{data:p}=M1(e,t),m=g.useMemo(()=>{if(!p)return[];const b=new Set;for(const x of Object.values(p))for(const w of x)b.add(w.scorerId);return[...b].sort()},[p]),v=g.useCallback(b=>{const x=n.find(w=>w.id===b);x&&(x.itemId===u?f():d(x.itemId))},[n,u,f,d]),y=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"auto"},{name:"status",label:"Status",size:"auto"},{name:"input",label:"Input",size:"1fr"},{name:"tags",label:"Tags",size:"auto"},...m.map(b=>({name:b,label:b,size:"auto"}))],[m]);return o.jsx("div",{className:"h-full min-h-0 min-w-0 overflow-y-auto",children:o.jsx(nLe,{results:n,isLoading:r,featuredResultId:h,onResultClick:v,columns:y,scoresByItemId:p,scorerIds:m,setEndOfListElement:s,isFetchingNextPage:i,hasNextPage:a,selectedIds:l,onToggleSelect:c})})}function DMs({children:e,className:t}){return o.jsx("div",{className:K("grid content-start gap-4 overflow-y-auto",t),children:e})}function LMs({children:e,className:t,withLeftSeparator:n,withRightSeparator:r}){return o.jsxs("div",{className:"flex w-full overflow-y-auto",children:[n&&o.jsx(Rct,{}),o.jsx("div",{className:K("grid w-full content-start gap-4 overflow-y-auto",t),children:e}),r&&o.jsx(Rct,{})]})}function Rct(){return o.jsx("div",{className:K("mx-3 w-[3px] shrink-0 bg-surface5")})}function FMs({children:e,className:t}){return o.jsx("div",{className:K("flex w-full flex-wrap items-center justify-between gap-3 gap-x-4",t),children:e})}const nrn=Object.assign(LMs,{Content:DMs,Toolbar:FMs});function zMs({children:e,className:t}){return o.jsx("div",{className:K("grid size-full grid-cols-1 overflow-y-auto",t),children:e})}const BMs=e=>{const t=Ye();return yt({queryKey:["experiment-trace-light",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return t.getTraceLight(e)},select:qtn,enabled:!!e})};function UMs(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${gr(n,"MMM dd 'at' H:mm:ss a")}`}return`v${e}`}function VMs({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=$nn(e),i=(s??[]).map(a=>({value:String(a.version),label:`${UMs(a.version,a.createdAt)}${a.isCurrent?" (current)":""}`}));return o.jsxs(nrn.Toolbar,{className:"grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4",children:[o.jsx("div",{}),o.jsx(of,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:i,value:t??"",onValueChange:a=>r?.(a,n??"")}),o.jsx(of,{label:"Version B",labelIsHidden:!0,name:"version-b",options:i,value:n??"",onValueChange:a=>r?.(t??"",a)}),o.jsx("div",{})]})}function rrn({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?djt(new Date(e)):!1,s=e?e5(new Date(e))?"Today":gr(new Date(e),"MMM dd"):"",i=e&&!r?gr(new Date(e),"yyyy"):"",a=e&&n?`${gr(new Date(e),"'at' h:mm aaa")}`:"";return o.jsxs("div",{className:K("truncate text-ui-md text-neutral2",t),children:[s," ",i," ",a]})}function rLe(e){return!e||e.length===0?"":e?.map(t=>t.size).join(" ")}function HMs({columns:e,isSelectionActive:t,children:n}){return o.jsx("div",{className:K("sticky top-0 z-10 mb-2 rounded-lg bg-surface3 px-3"),children:o.jsx("div",{className:K("grid items-center gap-3 text-left text-ui-xs tracking-widest text-neutral3 uppercase",{"pl-12 [&>label]:absolute [&>label]:left-0":t}),style:{gridTemplateColumns:rLe(e)},children:n})})}function WMs({children:e,className:t}){return o.jsx("span",{className:K("py-3",t),children:e})}function ZMs({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 GMs({children:e}){return o.jsx("ul",{className:"grid content-start",children:e})}function QMs({children:e}){const t=g.useRef(null);return o.jsx("div",{ref:t,className:K("overflow-y-auto"),children:e})}function KMs({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 YMs({children:e,href:t,className:n,LinkComponent:r,tooltip:s}){const i=o.jsx(r,{href:t,className:K("flex w-full items-center justify-center gap-4 rounded-lg px-3 py-2 text-left","hover:bg-surface4",Vr.colors,LA.visible,n),children:e});return s==null?i:o.jsxs(In,{children:[o.jsx(On,{render:i}),o.jsx(Cn,{children:s})]})}function XMs({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-5 text-center text-ui-md text-neutral3","[&>svg]:size-[1.5em] [&>svg]:opacity-75",{"[&>svg]:text-red-500":r==="error"}),children:[r==="error"?o.jsx(Pc,{}):o.jsx(Yf,{})," ",t]}):e})}function JMs({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-4 flex justify-center opacity-50",children:[e&&r,!t&&!e&&s]}):null}function e2s({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-4 pt-4 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(id,{}),"Previous"]}),t&&o.jsxs("button",{onClick:n,children:["Next",o.jsx(Kf,{})]})]})]})}function t2s({children:e,className:t}){return o.jsx("div",{className:K("grid grid-rows-[auto_1fr] overflow-y-auto",t),children:e})}function n2s({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",Vr.colors,{"selected-row":e,"grid px-3 gap-3":n}),style:{gridTemplateColumns:rLe(n)},children:t})}function r2s({item:e,isFeatured:t,onClick:n,children:r,columns:s,className:i,disabled:a,tooltip:l,...c}){const u=()=>{n?.(e?.id)},d=o.jsx("button",{...c,onClick:u,className:K("grid w-full items-center gap-3 rounded-lg px-3 text-left",Vr.colors,LA.visible,{"bg-surface4":t,"hover:bg-surface4":e&&!t&&!a},i),style:{gridTemplateColumns:rLe(s)},disabled:a,children:r});return l==null?d:o.jsxs(In,{children:[o.jsx(On,{render:d}),o.jsx(Cn,{children:l})]})}function s2s(e){return e.charAt(0).toUpperCase()+e.slice(1)}function i2s({status:e}){return e?o.jsxs(In,{children:[o.jsx(On,{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(Cn,{children:s2s(e)})]}):null}function a2s({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 Pct={latest:"Latest version",deleted:"Deleted in this version"};function o2s({version:e,date:t,isLatest:n,isDeleted:r}){return o.jsxs(rrn,{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?gr(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":Pct.latest,children:o.jsx(jt,{variant:"blue",size:"sm",icon:o.jsx($C,{})})}),r&&o.jsx("span",{className:"inline-flex",role:"img","aria-label":Pct.deleted,children:o.jsx(jt,{variant:"red",size:"sm",icon:o.jsx(vCe,{})})})]})]})}const Hp=Object.assign(t2s,{Header:HMs,HeaderCol:WMs,Items:GMs,Scroller:QMs,Row:n2s,RowButton:r2s,Message:XMs,NextPageLoading:JMs,Pagination:e2s,Cell:rrn,TextCell:a2s,StatusCell:i2s,VersionCell:o2s,IdCell:ZMs,DateCell:qMs,LinkCell:YMs,LabelCell:KMs}),l2s=[{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"}],hU={added:{badgeVariant:"blue",borderColor:"border-blue-900",icon:o.jsx(Yr,{}),tooltip:"Added in this version"},changed:{badgeVariant:"yellow",borderColor:"border-yellow-900",icon:o.jsx(uPn,{}),tooltip:"Changed in this version"},same:{badgeVariant:"green",borderColor:"border-green-900",icon:o.jsx(zSt,{}),tooltip:"Same in both versions"}};function Mue({red:e=!1,tooltip:t}){return o.jsxs(In,{children:[o.jsx(On,{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(vCe,{className:K("text-neutral3/40 w-5 h-5 ",{"text-red-900":e})})}),o.jsx(Cn,{children:t})]})}function Due({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}=hU[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(jt,{variant:n,size:"xs",icon:r})})]})}function c2s(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function $ct({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return"added";if(t==="changed"&&n)return"changed"}function u2s({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:i}){const{Link:a}=un(),l=t>n;return o.jsx(Hp,{children:o.jsx(Hp.Scroller,{children:o.jsx(Hp.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=i.get(c),f=c2s(u,d),h=$ct({otherVersionExists:d!==void 0,status:f,isNewer:l}),p=$ct({otherVersionExists:u!==void 0,status:f,isNewer:!l});return o.jsxs(Hp.Row,{columns:l2s,children:[o.jsx(Hp.IdCell,{id:c,isShortened:!1}),f!=="same"?o.jsxs(o.Fragment,{children:[u?.datasetVersion?o.jsx(Hp.LinkCell,{LinkComponent:a,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:h?hU[h].tooltip:void 0,children:o.jsx(Due,{variant:h,version:u.datasetVersion})}):o.jsx(Hp.Cell,{className:"flex items-center justify-center",children:o.jsx(Mue,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?o.jsx(Hp.LinkCell,{LinkComponent:a,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:p?hU[p].tooltip:void 0,children:o.jsx(Due,{variant:p,version:d.datasetVersion})}):o.jsx(Hp.Cell,{className:"flex items-center justify-center",children:o.jsx(Mue,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):o.jsx(Hp.LinkCell,{LinkComponent:a,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",tooltip:hU.same.tooltip,children:o.jsx(Due,{variant:"same",version:d?.datasetVersion})}),f==="changed"?o.jsx(Hp.LinkCell,{LinkComponent:a,href:`/datasets/${e}/items/${c}/versions?version=${u?.datasetVersion}&compare=${d?.datasetVersion}`,children:"Compare"}):o.jsx(Hp.Cell,{children:o.jsx(Mue,{tooltip:"Comparing is available only for changed items"})})]},c)})})})})}const pU="targetType",o2="targetId";function sLe({resetParams:e=[]}={}){const[t,n]=bi(),r=e.join(","),s=t.get(pU),i=Vnn(s)?s:"",a=i?t.get(o2)??"":"",l=g.useCallback(d=>{n(f=>{const h=new URLSearchParams(f);d?h.set(pU,d):h.delete(pU),h.delete(o2);for(const p of r.split(","))p&&h.delete(p);return h},{replace:!0})},[n,r]),c=g.useCallback(d=>{n(f=>{const h=new URLSearchParams(f);d?h.set(o2,d):h.delete(o2);for(const p of r.split(","))p&&h.delete(p);return h},{replace:!0})},[n,r]),u=g.useCallback(()=>l(""),[l]);return{targetType:i,targetId:a,setTargetType:l,setTargetId:c,clear:u}}function d2s(){const e=Fr(),[t,n]=g.useState(""),[r,s]=g.useState("all"),[i,a]=g.useState("all"),{targetType:l,targetId:c,setTargetType:u,setTargetId:d,clear:f}=sLe(),{data:h=[],isLoading:p,error:m,isFetchingNextPage:v,hasNextPage:y,setEndOfListElement:b}=_Un({targetType:l,targetId:c}),{data:x,isLoading:w,error:k}=KG(),_=g.useMemo(()=>x?.experiments??[],[x?.experiments]),C=g.useMemo(()=>c$s(h),[h]),T=p||w,E=m||k,N=()=>{e("/datasets/new")},I=o.jsx(xv,{owner:"dataset-list",children:o.jsx(J_,{onClick:N,tooltip:"Create a dataset",variant:"ghost",size:"sm",children:"New dataset"})});if(E&&ks(E))return o.jsx(Qn,{children:o.jsx(Gs,{})});if(E&&Es(E))return o.jsx(Qn,{children:o.jsx(Fs,{resource:"datasets"})});if(E)return o.jsx(Qn,{children:o.jsx(Ws,{title:"Failed to load datasets",message:E.message})});if(h.length===0&&!T&&!l)return o.jsxs(Qn,{children:[I,o.jsx(u$s,{onCreateClick:N})]});const A=r!=="all"||i!=="all"||t!==""||l!=="",P=()=>{n(""),s("all"),a("all"),f()};return o.jsxs(Ft,{height:"full",children:[I,o.jsx(Ft.TopArea,{children:o.jsx(b$s,{search:t,onSearchChange:n,experimentFilter:r,onExperimentFilterChange:s,tagFilter:i,onTagFilterChange:a,tagOptions:C,targetType:l,onTargetTypeChange:u,targetId:c,onTargetIdChange:d,onReset:P,hasActiveFilters:A})}),o.jsx(o$s,{datasets:h,experiments:_,isLoading:T,search:t,experimentFilter:r,tagFilter:i,isFetchingNextPage:v,hasNextPage:y,setEndOfListElement:b})]})}function f2s(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 h2s({item:e,itemId:t,fallback:n,onClose:r,...s}){const i=e?.id??t;return o.jsx($t,{open:!!i,onClose:r,title:`Dataset item ${i??""}`,children:e?o.jsx(p2s,{item:e,onClose:r,...s},e.id):t?o.jsxs(o.Fragment,{children:[o.jsxs($t.Header,{children:[o.jsx($t.CloseButton,{onClick:r,tooltip:"Close detail panel"}),o.jsxs($t.Heading,{children:["Item",o.jsx($t.CopyId,{id:t})]})]}),n]}):null})}function p2s({datasetId:e,item:t,items:n,onItemChange:r,onClose:s}){const{Link:i}=un(),{updateItem:a,deleteItem:l}=pl(),[c,u]=g.useState(!1),[d,f]=g.useState(""),[h,p]=g.useState(""),[m,v]=g.useState(""),[y,b]=g.useState(""),[x,w]=g.useState(""),[k,_]=g.useState(t.scorerIds!==void 0),[C,T]=g.useState(t.scorerIds??[]),[E,N]=g.useState(""),[I,A]=g.useState(null),[P,L]=g.useState(!1);g.useEffect(()=>{t&&(f(JSON.stringify(t.input,null,2)),p(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),v(t.metadata?JSON.stringify(t.metadata,null,2):""),b(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),w(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),_(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 M=n.findIndex(F=>F.id===t.id),V=M>0?()=>r(n[M-1].id):void 0,q=M>=0&&M<n.length-1?()=>r(n[M+1].id):void 0,H=async()=>{let F;try{F=JSON.parse(d)}catch{Ge.error("Input must be valid JSON");return}let R;if(h.trim())try{R=JSON.parse(h)}catch{Ge.error("Ground Truth must be valid JSON");return}let D;if(m.trim())try{D=JSON.parse(m)}catch{Ge.error("Metadata must be valid JSON");return}let U=null;if(y.trim())try{U=JSON.parse(y)}catch{Ge.error("Expected Trajectory must be valid JSON");return}let Q;if(x.trim())try{const te=JSON.parse(x);if(!Array.isArray(te)){Ge.error("Tool Mocks must be a JSON array");return}Q=te}catch{Ge.error("Tool Mocks must be valid JSON");return}else Q=[];let ee;if(E.trim())try{ee=JSON.parse(E)}catch{Ge.error("Request Context must be valid JSON");return}let J;k?J=C:t.scorerIds!==void 0&&(J=null);try{const te=await a.mutateAsync({datasetId:e,itemId:t.id,input:F,groundTruth:R,metadata:D,expectedTrajectory:U,toolMocks:Q,scorerIds:J,requestContext:ee});Ge.success("Item updated successfully"),_(te.scorerIds!==void 0),T(te.scorerIds??[]),u(!1),A(null)}catch(te){const re=f2s(te);re?A(re):Ge.error(`Failed to update item: ${te instanceof Error?te.message:"Unknown error"}`)}},B=()=>{f(JSON.stringify(t.input,null,2)),p(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),v(t.metadata?JSON.stringify(t.metadata,null,2):""),b(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),w(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),_(t.scorerIds!==void 0),T(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),A(null)},W=F=>{f(F),I?.field==="input"&&A(null)},z=F=>{p(F),I?.field==="groundTruth"&&A(null)},G=async()=>{try{await l.mutateAsync({datasetId:e,itemId:t.id}),Ge.success("Item deleted successfully"),L(!1),s()}catch(F){Ge.error(`Failed to delete item: ${F instanceof Error?F.message:"Unknown error"}`)}};return o.jsxs(o.Fragment,{children:[o.jsxs($t.Header,{children:[o.jsx($t.CloseButton,{onClick:s,tooltip:"Close detail panel"}),o.jsxs($t.Heading,{children:["Item",o.jsx($t.CopyId,{id:t.id})]}),o.jsxs($t.HeaderActions,{children:[!c&&o.jsxs(o.Fragment,{children:[o.jsx(ae,{render:o.jsx(i,{href:`/datasets/${e}/items/${t.id}/versions?version=${t.datasetVersion}`}),size:"sm",variant:"ghost",tooltip:"Go to item versions history","aria-label":"Go to item versions history",children:o.jsx(ACe,{})}),o.jsxs(xt,{children:[o.jsx(xt.Trigger,{asChild:!0,children:o.jsx(ae,{size:"sm",variant:"ghost",tooltip:"Open actions menu","aria-label":"Open actions menu",children:o.jsx(F1,{})})}),o.jsxs(xt.Content,{align:"end",className:"w-48",children:[o.jsxs(xt.Item,{onSelect:()=>u(!0),children:[o.jsx(Gd,{}),"Edit"]}),o.jsxs(xt.Item,{onSelect:()=>L(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(co,{}),"Delete Item"]})]})]})]}),o.jsx($t.NextPrevNav,{onPrevious:V,onNext:q,previousLabel:"Go to previous item",nextLabel:"Go to next item"})]})]}),o.jsx($t.Content,{children:c?o.jsx(CMs,{inputValue:d,setInputValue:W,groundTruthValue:h,setGroundTruthValue:z,metadataValue:m,setMetadataValue:v,trajectoryValue:y,setTrajectoryValue:b,toolMocksValue:x,setToolMocksValue:w,scorerOverrideEnabled:k,setScorerOverrideEnabled:_,selectedScorerIds:C,setSelectedScorerIds:T,requestContextValue:E,setRequestContextValue:N,validationErrors:I,onSave:H,onCancel:B,isSaving:a.isPending}):o.jsx(Rke,{item:t})}),o.jsx(At,{open:P,onOpenChange:L,children:o.jsxs(At.Content,{children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Delete Item"}),o.jsx(At.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),o.jsxs(At.Footer,{children:[o.jsx(At.Cancel,{children:"Cancel"}),o.jsx(At.Action,{onClick:G,children:l.isPending?"Deleting...":"Yes, Delete"})]})]})})]})}function m2s(){const{datasetId:e,items:t,isLoadingItems:n,currentItemId:r,openItem:s,close:i}=Xnn(),a=g.useMemo(()=>r?t.find(d=>d.id===r):void 0,[t,r]),{data:l,isLoading:c}=Ktn(a?"":e,!a&&r?r:""),u=a??l??void 0;return o.jsx(h2s,{datasetId:e,item:u,itemId:r,fallback:n||c?o.jsx($t.LoadingData,{}):o.jsxs($t.NoData,{children:['No loaded item "',r,'".']}),items:t,onItemChange:s,onClose:i})}function SB({children:e}){return o.jsxs(Ft,{height:"full",children:[o.jsx("div",{}),o.jsx(Ft.MainArea,{isCentered:!0,children:e})]})}function g2s(){const{datasetId:e}=ur(),t=Fr(),[n,r]=bi(),{activeVersion:s,handleVersionChange:i}=tLe(n,r),[a,l]=g.useState(!1),[c,u]=g.useState(!1),[d,f]=g.useState(!1),[h,p]=g.useState(!1),{data:m,error:v,isLoading:y}=bv(e),{data:b=[],isLoading:x}=gA(e,void 0,s),w=!x&&b.length===0;if(y)return null;if(v&&ks(v))return o.jsx(SB,{children:o.jsx(Gs,{})});if(v&&Es(v))return o.jsx(SB,{children:o.jsx(Fs,{resource:"datasets"})});if(v&&CR(v)||!y&&!v&&!m)return o.jsx(SB,{children:o.jsx(Ar,{iconSlot:o.jsx(rv,{}),titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:o.jsx(ae,{render:o.jsx(oo,{to:"/datasets"}),icon:o.jsx(id,{}),children:"Back to Datasets"})})});if(v)return o.jsx(SB,{children:o.jsx(Ws,{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(bMs,{datasetId:e,items:b,isLoadingItems:x,children:[o.jsxs("div",{className:"h-full",children:[o.jsx(Ft,{height:"full",className:"grid-rows-[1fr] p-0",children:o.jsx(Ft.MainArea,{children:o.jsx(xMs,{datasetId:e,onAddItemClick:()=>u(!0),belowToolbarSlot:o.jsx(wMs,{datasetId:e}),leftSlot:o.jsx("span",{className:"text-ui-sm text-neutral3 mr-3 whitespace-nowrap",children:m?.createdAt?`Created ${gr(new Date(m.createdAt),"MMM d")}`:""}),rightSlot:o.jsxs(Ms,{children:[o.jsx(ae,{render:o.jsx(oo,{to:`/experiments?dataset=${e}`}),icon:o.jsx(OCe,{}),children:"View experiments"}),o.jsx(Qnn,{datasetId:e,value:s,onValueChange:i,currentVersion:m?.version,className:"w-36"}),w?o.jsxs(In,{children:[o.jsx(On,{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.jsx(ae,{variant:"primary",icon:o.jsx(bu,{}),children:"Run Experiment"})})})}),o.jsx(Cn,{children:"Add items to the dataset before running an experiment"})]}):o.jsx(ae,{variant:"primary",onClick:()=>l(!0),icon:o.jsx(bu,{}),children:"Run Experiment"}),o.jsxs(xt,{children:[o.jsx(xt.Trigger,{asChild:!0,children:o.jsx(ae,{size:"lg","aria-label":"Dataset actions menu",children:o.jsx(F1,{})})}),o.jsxs(xt.Content,{align:"end",className:"w-48",children:[o.jsxs(xt.Item,{onSelect:()=>{t(`/datasets/${e}/edit`)},children:[o.jsx(Gd,{})," Edit Dataset"]}),o.jsxs(xt.Item,{onSelect:()=>p(!0),children:[o.jsx(ed,{})," Duplicate Dataset"]}),o.jsxs(xt.Item,{onSelect:()=>f(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(co,{})," Delete Dataset"]})]})]})]})})})}),o.jsx(m2s,{})]}),o.jsx(yJ,{initialDatasetId:e,initialDatasetVersion:s??void 0,open:a,onOpenChange:l,onSuccess:k},`${e}:${s??"latest"}`),o.jsx(kMs,{datasetId:e,open:c,onOpenChange:u}),m&&o.jsx(M$s,{open:h,onOpenChange:p,sourceDatasetId:m.id,sourceDatasetName:m.name,sourceDatasetDescription:m.description,sourceDatasetTargetType:m.targetType}),m&&o.jsx(z$s,{open:d,onOpenChange:f,datasetId:m.id,datasetName:m.name,onSuccess:_})]})}function Lue({children:e}){return o.jsxs(Ft,{height:"full",children:[o.jsx("div",{}),o.jsx(Ft.MainArea,{isCentered:!0,children:e})]})}function v2s(){const{datasetId:e}=ur(),t=Fr(),{data:n,error:r,isLoading:s}=bv(e),i=()=>{t(`/datasets/${e}`)};return s?null:r&&ks(r)?o.jsx(Lue,{children:o.jsx(Gs,{})}):r&&Es(r)?o.jsx(Lue,{children:o.jsx(Fs,{resource:"datasets"})}):r||!n?o.jsx(Lue,{children:o.jsx(Ws,{title:"Failed to load dataset",message:r instanceof Error?r.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Ft,{height:"full",children:[o.jsx("div",{}),o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-4 py-5",children:[o.jsx(qh,{className:"mb-6 p-0",children:o.jsxs(qh.Column,{children:[o.jsxs(qh.Title,{children:[o.jsx(rv,{})," Edit dataset"]}),o.jsx(qh.Description,{children:n.name})]})}),o.jsx(Jf,{className:"p-4",children:o.jsx(F$s,{dataset:{id:n.id,name:n.name,description:n.description||"",inputSchema:n.inputSchema,groundTruthSchema:n.groundTruthSchema,requestContextSchema:n.requestContextSchema,scorerIds:n.scorerIds},onSuccess:i,onCancel:i})})]})})]})}function Mct(e,t){return{id:e.id,datasetId:t,datasetVersion:e.datasetVersion,input:e.input,groundTruth:e.groundTruth,expectedTrajectory:e.expectedTrajectory,toolMocks:e.toolMocks,scorerIds:e.scorerIds,requestContext:e.requestContext,metadata:e.metadata,createdAt:e.createdAt,updatedAt:e.updatedAt}}function Dct(e,t){return e.map(n=>{const r=typeof n.updatedAt=="string"?new Date(n.updatedAt):n.updatedAt;return{value:String(n.datasetVersion),label:o.jsxs("span",{className:"flex w-full items-center gap-2",children:[o.jsxs("span",{children:[o.jsxs("b",{children:["v. ",n.datasetVersion]})," · ",gr(r,"MMM d, HH:mm")]}),n.isLatest?o.jsx(jt,{variant:"blue",size:"xs",className:"ml-auto",children:"Latest"}):null]}),disabled:t?.has(n.datasetVersion)??!1}})}function Lct(e){const t=Number(e);return e!=null&&Number.isFinite(t)&&t>0?t:null}function y2s(){const{datasetId:e,itemId:t}=ur(),[n,r]=bi(),s=Lct(n.get("version")),i=Lct(n.get("compare")),a=n.get("view")==="diff",{data:l,error:c}=bv(e??""),{data:u,isLoading:d}=UPs(e??"",t??""),f=(s!=null?u?.find(C=>C.datasetVersion===s):void 0)??u?.[0],h=f?.datasetVersion??null,p=i!=null&&i!==h?i:null,{data:m,isLoading:v}=VPs(e??"",t??"",p??0,l?.version),y=(C,T)=>r(E=>{const N=new URLSearchParams(E);return T==null?N.delete(C):N.set(C,String(T)),N},{replace:!0});if(c&&ks(c))return o.jsx(oi,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Gs,{})})});if(c&&Es(c))return o.jsx(oi,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{resource:"datasets"})})});if(!e||!t)return o.jsx(oi,{children:o.jsx(i0,{children:o.jsx("div",{className:"text-neutral4 py-5 text-center",children:o.jsx("p",{children:"Item not found."})})})});const b=!!(f&&m),x=a&&b,w=f?Mct(f,e):null,k=m?Mct(m,e):null,_=(f?.datasetVersion??0)<(m?.datasetVersion??0);return o.jsxs(oi,{children:[o.jsx(xv,{owner:"dataset-item-versions",children:b&&o.jsx(ae,{variant:"outline",onClick:()=>y("view",a?null:"diff"),children:a?o.jsxs(o.Fragment,{children:[o.jsx(wCe,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(MAn,{})," Diff View"]})})}),o.jsx(Ft,{height:"full",className:"grid-rows-[minmax(0,1fr)]",children:o.jsxs("div",{className:"grid min-h-0 grid-cols-1 gap-4 md:grid-cols-2",children:[o.jsxs(Jf,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[o.jsx(xwe,{children:o.jsx(Fct,{name:"version",value:h!=null?String(h):"",options:Dct(u??[],p!=null?new Set([p]):void 0),onValueChange:C=>y("version",Number(C))})}),o.jsx(O0,{className:"grid content-start gap-5 overflow-y-auto",children:d?o.jsx("div",{className:"text-neutral4 text-ui-md",children:"Loading..."}):w?o.jsx(Rke,{item:w,diff:x&&k?{against:k,side:_?"a":"b"}:void 0}):o.jsx("div",{className:"text-neutral4 text-ui-md",children:"Item data not available"})})]}),o.jsxs(Jf,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[o.jsx(xwe,{children:o.jsx(Fct,{name:"compare",value:p!=null?String(p):"",placeholder:"Select a version to compare",options:Dct(u??[],h!=null?new Set([h]):void 0),onValueChange:C=>y("compare",Number(C))})}),o.jsx(O0,{className:"grid content-start gap-5 overflow-y-auto",children:p==null?o.jsx(Ar,{className:"h-full",iconSlot:o.jsx(rbe,{className:"text-neutral3 size-8"}),titleSlot:"No version selected",descriptionSlot:"Pick a version above to compare it with the one on the left."}):v?o.jsx("div",{className:"text-neutral4 text-ui-md",children:"Loading..."}):k?o.jsx(Rke,{item:k,diff:x&&w?{against:w,side:_?"b":"a"}:void 0}):o.jsxs("div",{className:"text-neutral4 text-ui-md",children:["Version ",p," not found"]})})]})]})})]})}function Fct({name:e,value:t,options:n,placeholder:r="Select version",onValueChange:s}){return o.jsxs("div",{className:"grid grid-cols-[auto_1fr] items-center gap-4",children:[o.jsx(ACe,{className:"size-4 opacity-50"}),o.jsxs(Ci,{name:e,value:t,onValueChange:s,children:[o.jsx(Ei,{"aria-label":e==="compare"?"Compare version":"Version",className:"w-full",children:o.jsx(_i,{placeholder:r,className:"flex-1"})}),o.jsx(Ti,{children:n.map(i=>o.jsx(Cr,{value:i.value,disabled:i.disabled,children:i.label},i.value))})]})]})}function b2s(){const{datasetId:e}=ur(),[t]=bi(),n=t.get("ids")?.split(",").map(Number).filter(m=>!isNaN(m)&&m>0)??[],r=Fr(),{data:s,error:i}=bv(e??""),a=gA(e??"",void 0,n[0]??null),l=gA(e??"",void 0,n[1]??null),c=g.useMemo(()=>a.data??[],[a.data]),u=g.useMemo(()=>l.data??[],[l.data]),d=g.useMemo(()=>{const m=new Map;for(const v of[...c,...u])m.has(v.id)||m.set(v.id,{id:v.id,createdAt:new Date(v.createdAt)});return[...m.values()].sort((v,y)=>y.createdAt.getTime()-v.createdAt.getTime())},[c,u]),f=g.useMemo(()=>new Map(c.map(m=>[m.id,m])),[c]),h=g.useMemo(()=>new Map(u.map(m=>[m.id,m])),[u]);if(i&&ks(i))return o.jsx(oi,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Gs,{})})});if(i&&Es(i))return o.jsx(oi,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{resource:"datasets"})})});if(!e||n.length<2)return o.jsx(oi,{children:o.jsx(i0,{children:o.jsx("div",{className:"text-neutral4 py-5 text-center",children:o.jsx("p",{children:"Select at least two versions to compare."})})})});const p=(m,v)=>{r(`/datasets/${e}/versions?ids=${m},${v}`,{replace:!0})};return o.jsx(oi,{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-4",children:[o.jsxs(qh,{children:[o.jsxs(qh.Column,{children:[o.jsxs(qh.Title,{children:[o.jsx(zPn,{})," Compare Dataset Versions"]}),o.jsx(qh.Description,{children:o.jsxs(Bd,{children:[o.jsx(ACe,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),o.jsx(qh.Column,{children:o.jsx(ae,{render:o.jsx(oo,{to:`/datasets/${e}`}),icon:o.jsx(id,{}),children:"Back to Dataset"})})]}),o.jsx(zMs,{children:o.jsxs(nrn,{children:[o.jsx(VMs,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:p}),o.jsx(u2s,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:h})]})})]})})})}function x2s(){const e=Fr(),[t]=bi(),n=t.get("targetType"),r=Vnn(n)?n:void 0,s=t.get("targetIds"),i=r&&s?s.split(",").map(l=>l.trim()).filter(Boolean):void 0,a=l=>{e(`/datasets/${l}`)};return o.jsxs(Ft,{height:"full",children:[o.jsx("div",{}),o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-4 py-5",children:[o.jsx(qh,{className:"mb-6 p-0",children:o.jsxs(qh.Column,{children:[o.jsxs(qh.Title,{children:[o.jsx(rv,{})," Create new dataset"]}),o.jsx(qh.Description,{children:"Datasets group test cases used to evaluate your agents and workflows."})]})}),o.jsx(Jf,{className:"p-4",children:o.jsx(I$s,{targetType:r,targetIds:i,onSuccess:a,onCancel:()=>{e(-1)}})})]})})]})}function Pke({children:e,className:t}){return o.jsx("div",{className:K("flex flex-wrap gap-4",t),children:e})}function w2s(e){if(!e||e.length<2)return null;const t=[...e].sort((a,l)=>new Date(a.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 i=(s-r)/r*100;return{changePct:Math.round(i*10)/10,prevValue:String(r)}}function S2s({scorers:e,datasets:t,experiments:n,avgScore:r,prevAvgScore:s,totalNeedsReview:i,isLoadingScorers:a,isLoadingDatasets:l,isLoadingExperiments:c,isLoadingScores:u,isLoadingReview:d}){const f=e?Object.keys(e).length:void 0,h=t?.length,p=n?.length,m=r!=null&&s!=null&&s!==0?{changePct:Math.round((r-s)/s*100*10)/10,prevValue:String(s)}:null,v=w2s(n);return o.jsxs(o.Fragment,{children:[o.jsxs(Mr,{children:[o.jsx(Mr.Label,{children:"Total Scorers"}),a?o.jsx(Mr.Loading,{}):f!=null?o.jsxs(o.Fragment,{children:[o.jsx(Mr.Value,{children:String(f)}),o.jsx(Mr.NoChange,{message:"Static count"})]}):o.jsx(Mr.NoData,{})]}),o.jsxs(Mr,{children:[o.jsx(Mr.Label,{children:"Total Datasets"}),l?o.jsx(Mr.Loading,{}):h!=null?o.jsxs(o.Fragment,{children:[o.jsx(Mr.Value,{children:String(h)}),o.jsx(Mr.NoChange,{message:"Static count"})]}):o.jsx(Mr.NoData,{})]}),o.jsxs(Mr,{children:[o.jsx(Mr.Label,{children:"Avg Score"}),u?o.jsx(Mr.Loading,{}):r!=null?o.jsxs(o.Fragment,{children:[o.jsx(Mr.Value,{children:String(r)}),m?o.jsx(Mr.Change,{changePct:m.changePct,prevValue:m.prevValue}):o.jsx(Mr.NoChange,{})]}):o.jsx(Mr.NoData,{})]}),o.jsxs(Mr,{children:[o.jsx(Mr.Label,{children:"Total Experiments"}),c?o.jsx(Mr.Loading,{}):p!=null?o.jsxs(o.Fragment,{children:[o.jsx(Mr.Value,{children:String(p)}),v?o.jsx(Mr.Change,{changePct:v.changePct,prevValue:v.prevValue}):o.jsx(Mr.NoChange,{})]}):o.jsx(Mr.NoData,{})]}),o.jsxs(Mr,{children:[o.jsx(Mr.Label,{children:"Needs Review"}),d?o.jsx(Mr.Loading,{}):i!=null?o.jsxs(o.Fragment,{children:[o.jsx(Mr.Value,{children:String(i)}),i>0?o.jsx(Mr.NoChange,{message:"items pending review"}):o.jsx(Mr.NoChange,{message:"All caught up"})]}):o.jsx(Mr.NoData,{})]})]})}function srn({open:e,onOpenChange:t,experimentId:n,experimentName:r,onSuccess:s}){const{deleteExperiment:i}=pl(),a=async()=>{try{await i.mutateAsync(n),Ge.success("Experiment deleted successfully"),t(!1),s?.()}catch(l){Ge.error(`Failed to delete experiment: ${l instanceof Error?l.message:"Unknown error"}`)}};return o.jsx(At,{open:e,onOpenChange:t,children:o.jsxs(At.Content,{children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Delete Experiment"}),o.jsxs(At.Description,{children:['Are you sure you want to delete "',r||n,'"? This will permanently delete the experiment, all its results, and the traces it produced, including their spans and any scores, feedback, metrics and logs attached to those traces. This action cannot be undone.']})]}),o.jsxs(At.Footer,{children:[o.jsx(ae,{icon:o.jsx(co,{}),variant:"primary",size:"lg",onClick:a,disabled:i.isPending,children:i.isPending?"Deleting...":"Delete"}),o.jsx(At.Cancel,{children:"Cancel"})]})]})})}const k2s="minmax(9rem,1fr)",O2s="minmax(8rem,16rem)",C2s="1fr",_2s="auto auto auto auto auto auto auto",Yv={experiment:"Experiment",description:"Description",dataset:"Dataset",target:"Target",status:"Status",items:"Items",succeeded:"Processed",failed:"Errored",review:"Review",date:"Date"},E2s={completed:"neutral",running:"yellow",failed:"red",pending:"neutral"},T2s={completed:"Run completed",running:"Run in progress",failed:"Run failed",pending:"Run queued"};function j2s(e){return e?(typeof e=="string"?new Date(e):e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function irn(e){const t=ub(e.id)??e.id;return e.name||`Experiment #${t}`}const N2s=60;function I2s({experiment:e}){return o.jsx("span",{className:"text-neutral4 block min-w-0 truncate text-left",children:irn(e)})}function A2s({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<=N2s?n:o.jsxs(In,{children:[o.jsx(On,{asChild:!0,children:n}),o.jsx(Cn,{children:t})]})}function arn(){const{data:e}=rh(),{data:t}=eg(),{data:n}=Ep(),{data:r}=eP();return{agents:e,workflows:t,scorers:n,processors:r}}function orn(e){return o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 10.123 10.123",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M4.50195 1.53809H5.62109V0H6.75098V1.53809H7.5293L7.64258 1.54395C8.19939 1.60066 8.63379 2.0708 8.63379 2.64258V3.37305H10.123V4.50195H8.63379V5.62109H10.123V6.75H8.63379V7.57812L8.62891 7.69141C8.57589 8.2109 8.16211 8.62387 7.64258 8.67676L7.5293 8.68262H6.75098V10.123H5.62109V8.68262H4.50195V10.123H3.37305V8.68262H2.59375L2.48047 8.67676C1.96102 8.62383 1.54817 8.21082 1.49512 7.69141L1.48926 7.57812V6.75H0V5.62109H1.48926V4.50195H0V3.37305H1.48926V2.64258C1.48926 2.07084 1.92371 1.60071 2.48047 1.54395L2.59375 1.53809H3.37305V0H4.50195V1.53809ZM2.61914 7.55273H7.50488V2.66699H2.61914V7.55273Z",fill:"currentColor"})})}const lrn={agent:Ma,workflow:Bc,scorer:dw,processor:orn},crn={agent:"Agent",workflow:"Workflow",scorer:"Scorer",processor:"Processor"},R2s="External (caller-run)";function urn(e,{agents:t,workflows:n,scorers:r,processors:s}){const{targetType:i,targetId:a}=e;if(!a)return R2s;switch(i){case"agent":return t?.[a]?.name??a;case"workflow":return n?.[a]?.name??a;case"scorer":return r?.[a]?.scorer?.config?.name??a;case"processor":return s?.[a]?.name??a;default:return a}}function P2s({experiment:e,datasetName:t,review:n}){const r=e.status??"pending",s=e.succeededCount??0,i=e.failedCount??0,a=e.totalItems??0;return o.jsxs(o.Fragment,{children:[o.jsx(we.Cell,{children:o.jsx(I2s,{experiment:e})}),o.jsx(we.Cell,{children:o.jsx(A2s,{experiment:e})}),t!==void 0&&o.jsx(we.TextCell,{children:t}),o.jsx(we.Cell,{children:o.jsx($2s,{experiment:e})}),o.jsx(we.Cell,{children:o.jsx(jt,{variant:E2s[r]??"neutral",indicator:"dot",children:T2s[r]??r})}),o.jsx(we.TextCell,{className:"text-center",children:a}),o.jsx(we.TextCell,{className:"text-center",children:s}),o.jsx(we.TextCell,{className:"text-center",children:o.jsx("span",{className:i>0?"text-accent2":"",children:i})}),o.jsx(we.Cell,{className:"text-center",children:o.jsx(M2s,{review:n})}),o.jsx(we.TextCell,{children:j2s(e.createdAt)})]})}function $2s({experiment:e}){const t=arn(),n=urn(e,t),r=e.targetId?e.targetType:null,s=r?lrn[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":crn[r],children:o.jsx(s,{})}),o.jsx("span",{className:r?"truncate":"text-neutral2 truncate",children:n})]})}function M2s({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(jt,{size:"xs",variant:"yellow",children:[e.needsReview," pending"]}):o.jsxs(jt,{size:"xs",variant:"green",children:[e.complete,"/",t," reviewed"]})}const drn=`${k2s} ${O2s} ${C2s} ${_2s}`,zct=`${drn} auto`,D2s=[{label:Yv.experiment},{label:Yv.description},{label:Yv.dataset},{label:Yv.target},{label:Yv.status},{label:Yv.items,className:"text-center"},{label:Yv.succeeded,className:"text-center"},{label:Yv.failed,className:"text-center"},{label:Yv.review,className:"text-center"},{label:Yv.date}],frn=e=>e.stopPropagation();function L2s({experiment:e,rowProps:t,onSelect:n,featured:r,onDelete:s,children:i}){const{paths:a,Link:l}=un(),c=g.useRef(null);return o.jsxs(we.RowWrapper,{...t,onSelectRow:n??(()=>c.current?.click()),children:[n?o.jsx(we.RowButton,{colEnd:-2,featured:r,tabIndex:-1,onClick:u=>{u.stopPropagation(),n()},children:i}):o.jsx(we.RowLink,{ref:c,colEnd:-2,to:a.experimentLink(e.id),LinkComponent:l,tabIndex:-1,onClick:frn,children:i}),o.jsx(we.ActionsCell,{className:"pl-2",children:o.jsx(ae,{type:"button",variant:"ghost",size:"icon-xs",tooltip:"Delete experiment","aria-label":`Delete experiment ${e.name??e.id}`,onClick:u=>{u.stopPropagation(),s()},children:o.jsx(co,{className:"size-4"})})})]})}function F2s({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:i="all",datasetFilter:a="all",selection:l,onSelectExperiment:c,selectedExperimentId:u,keyboardGlobal:d=!0,isFetchingNextPage:f,hasNextPage:h,setEndOfListElement:p}){const m=l!==void 0,v=g.useMemo(()=>{const E=new Map;return t?.forEach(N=>E.set(N.id,N.name)),E},[t]),y=g.useMemo(()=>[...e].sort((E,N)=>{const I=E.createdAt?new Date(E.createdAt).getTime():0;return(N.createdAt?new Date(N.createdAt).getTime():0)-I}),[e]),b=g.useMemo(()=>{const E=s.toLowerCase();return y.filter(N=>{const I=N.datasetId?v.get(N.datasetId)??"":"",A=!E||N.id.toLowerCase().includes(E)||(N.name??"").toLowerCase().includes(E)||I.toLowerCase().includes(E)||(N.targetId??"").toLowerCase().includes(E),P=i==="all"||N.status===i,L=a==="all"||N.datasetId===a;return A&&P&&L})},[y,s,v,i,a]),{containerRef:x,getRowProps:w}=Zc({count:b.length,global:d}),[k,_]=g.useState(null);if(r)return o.jsx(Wl,{columns:zct});const C=m?`auto ${drn}`:zct,T=D2s.map(E=>o.jsx(we.TopCell,{className:E.className,children:E.label},E.label));return o.jsxs(we,{columns:C,scrollRef:x,children:[o.jsx(we.Top,{hasLeadingCell:m,children:m?o.jsxs(o.Fragment,{children:[o.jsx(we.TopCell,{children:" "}),o.jsx(we.TopCells,{colStart:2,children:T})]}):o.jsxs(o.Fragment,{children:[T,o.jsx(we.TopCell,{"aria-hidden":!0,children:null})]})}),b.map((E,N)=>{const I=E.datasetId?v.get(E.datasetId)??ub(E.datasetId)??E.datasetId:"—",A=o.jsx(P2s,{experiment:E,datasetName:I,review:n?.get(E.id)});if(!l)return o.jsx(L2s,{experiment:E,rowProps:w(N),onSelect:c?()=>c(E):void 0,featured:u===E.id,onDelete:()=>_(E),children:A},E.id);const P=l.selectedExperimentIds.includes(E.id),L=()=>l.onToggleSelection(E.id);return o.jsxs(we.RowWrapper,{...w(N),onSelectRow:L,children:[o.jsx(we.SelectCell,{checked:P,onToggle:L,"aria-label":`Select experiment ${E.id}`}),o.jsx(we.RowButton,{colStart:2,featured:P,tabIndex:-1,onClick:frn,children:A})]},E.id)}),o.jsx(we.NextPageLoading,{isLoading:f,hasMore:h,setEndOfListElement:p}),k&&o.jsx(srn,{open:!0,onOpenChange:E=>{E||_(null)},experimentId:k.id,experimentName:k.name??void 0})]})}const z2s=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function B2s(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const kB={completed:wV.neutral3,running:"#facc15",pending:"#fb923c",failed:"#f87171"},U2s=[{label:"Completed",color:kB.completed},{label:"Running",color:kB.running},{label:"Pending",color:kB.pending},{label:"Failed",color:kB.failed}];function V2s({experiments:e,datasets:t,isLoading:n,isError:r}){const{data:s,maxVal:i}=g.useMemo(()=>{if(!e||e.length===0)return{data:[],maxVal:0};const l=new Map;if(t)for(const f of t)l.set(f.id,f.name);const c=new Map;for(const f of e){const h=f.datasetId??"unknown";c.has(h)||c.set(h,{completed:0,running:0,pending:0,failed:0});const p=c.get(h),m=f.status;m in p&&p[m]++}let u=0;return{data:Array.from(c.entries()).map(([f,h])=>{const p=h.completed+h.running+h.pending+h.failed;return p>u&&(u=p),{name:l.get(f)??f.slice(0,12),values:[h.completed,h.running,h.pending,h.failed]}}),maxVal:u}},[e,t]),a=s.length>0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Experiments by Dataset",description:"Experiment status breakdown per dataset."}),a&&o.jsx(Ht.Summary,{value:String(e?.length??0),label:"Total experiments"})]}),n?o.jsx(Ht.Loading,{}):r?o.jsx(Ht.Error,{message:"Failed to load experiments data"}):o.jsx(Ht.Content,{children:a?o.jsx(vA,{data:s,segments:U2s,maxVal:i,fmt:l=>String(l)}):o.jsx(Ht.NoData,{message:"No experiments have been run yet"})})]})}const q2s=({onRunExperiment:e})=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ar,{iconSlot:o.jsx(Ls,{}),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.jsx(ae,{variant:"primary",onClick:e,icon:o.jsx(bu,{}),children:"Run Experiment"}),o.jsx(ae,{variant:"ghost",render:o.jsx("a",{href:"https://mastra.ai/docs/evals/experiments",target:"_blank",rel:"noopener noreferrer"}),icon:o.jsx(_s,{}),children:"Experiments Documentation"})]})})});function H2s({search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:i,datasetOptions:a,targetType:l,onTargetTypeChange:c,targetId:u,onTargetIdChange:d,onReset:f,hasActiveFilters:h,onRunClick:p,runTooltip:m="Run an experiment",onCompareClick:v,selection:y}){const b=y?.selectedCount===2&&!y.compareDisabledReason;return o.jsxs("div",{className:"min-h-form-md flex flex-wrap items-center gap-2",children:[o.jsx("div",{className:"max-w-120 min-w-48 flex-1",children:o.jsx(Wc,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t})}),o.jsxs(Ms,{children:[o.jsx(of,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...z2s],value:n,onValueChange:r,className:"whitespace-nowrap"}),o.jsx(of,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:a,value:s,onValueChange:i,className:"whitespace-nowrap"}),o.jsx(eLe,{targetType:l,targetId:u,onTargetTypeChange:c,onTargetIdChange:d}),f&&h&&o.jsx(ae,{onClick:f,size:"sm",variant:"default",icon:o.jsx(Yt,{}),children:"Reset"})]}),y?o.jsxs(Ms,{className:"ml-auto shrink-0 whitespace-nowrap",children:[o.jsxs(Xh,{className:"gap-2",children:[o.jsxs(jt,{size:"sm",variant:y.selectedCount<2?"red":"green",children:[y.selectedCount," / 2"]}),"selected",y.compareDisabledReason&&o.jsxs("span",{className:"text-accent2",children:["· ",y.compareDisabledReason]})]}),o.jsx(ae,{variant:"primary",disabled:!b,onClick:y.onExecuteCompare,icon:o.jsx(rbe,{}),children:"Compare Experiments"}),o.jsx(ae,{icon:o.jsx(Yt,{}),onClick:y.onCancelSelection,children:"Cancel"})]}):o.jsxs(Ms,{className:"ml-auto shrink-0",children:[v&&o.jsx(ae,{onClick:v,tooltip:"Select two experiments of the same dataset to compare",icon:o.jsx(rbe,{}),children:"Compare"}),p&&o.jsx(ae,{onClick:p,tooltip:m,variant:"primary",icon:o.jsx(bu,{}),children:"Run Experiment"})]})]})}const W2s={present:!1,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},Bct=e=>e?e instanceof Date?e.toISOString():e:null,Uct=e=>{const t=new Map;for(const n of e??[])t.set(n.itemId,n);return t},Vct=(e,t,n)=>{if(!e)return W2s;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:Bct(t?.startedAt),completedAt:Bct(t?.completedAt),scores:Object.entries(e.scores).map(([s,i])=>({scorerId:s,value:i,reason:r.get(s)??null})).sort((s,i)=>s.scorerId.localeCompare(i.scorerId))}},Z2s=({comparison:e,baselineId:t,contenderId:n,baselineResults:r,contenderResults:s,baselineScores:i,contenderScores:a})=>{if(!e)return[];const l=Uct(r),c=Uct(s);return e.items.map(u=>{const d=Vct(u.results[t],l.get(u.itemId),i?.[u.itemId]),f=Vct(u.results[n],c.get(u.itemId),a?.[u.itemId]),h={};for(const p of new Set([...d.scores,...f.scores].map(m=>m.scorerId))){const m=d.scores.find(y=>y.scorerId===p)?.value??null,v=f.scores.find(y=>y.scorerId===p)?.value??null;h[p]=m!=null&&v!=null?v-m:null}return{itemId:u.itemId,input:u.input,groundTruth:u.groundTruth,baseline:d,contender:f,deltas:h}})};function IO({title:e,actions:t,tone:n="default",defaultOpen:r=!0,children:s}){return o.jsxs(dl,{defaultOpen:r,className:"grid gap-2",children:[o.jsxs("div",{className:"flex min-h-6 items-center justify-between gap-2",children:[o.jsxs(Zo,{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(mr,{}),e]}),t]}),o.jsx(Go,{role:"region","aria-label":e,children:s})]})}function qct({label:e,value:t}){return t==null?null:o.jsx(IO,{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 hrn({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-ui-md",t),children:[o.jsx("span",{className:"inline-block w-3",children:e>0?"+":e<0?"-":""}),Math.abs(e).toFixed(2),e>0?o.jsx(ISt,{className:"size-3.5"}):e<0?o.jsx(cNn,{className:"size-3.5"}):null]})}function prn({scorerId:e,value:t,delta:n,reason:r}){const{Link:s,paths:i}=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:i.scorerLink(e),"aria-label":`Open ${e}`,className:"text-neutral5 text-ui-md flex min-w-0 items-center gap-1.5 font-medium hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[o.jsx(dw,{}),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 text-ui-md font-mono",children:t!=null?t.toFixed(2):"-"}),n!=null&&o.jsx(hrn,{delta:n})]})]}),r&&o.jsx("p",{className:"text-neutral3 text-ui-md",children:r})]})}function Hct(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function G2s(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 Q2s="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 Wct({side:e,row:t,showDeltas:n,isLoading:r}){const s=t[e],i=G2s(s);if(r)return o.jsx("div",{className:"flex h-32 items-center justify-center",children:o.jsx(_n,{})});if(!s.present)return o.jsx("p",{className:"text-neutral3 text-ui-md py-5 text-center",children:"Not present in this experiment"});const a=Hct(s.output);return o.jsxs("div",{className:"grid content-start gap-5",children:[i&&o.jsxs(In,{children:[o.jsx(On,{render:o.jsxs("p",{className:"text-neutral3 text-ui-md flex items-center justify-end gap-1.5 [&>svg]:size-3.5",children:[o.jsx($C,{}),i]})}),o.jsx(Cn,{children:"Run duration"})]}),s.error?o.jsx(IO,{title:"Error",tone:"negative",actions:o.jsx(ci,{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(IO,{title:"Output",actions:o.jsx(ci,{content:a}),children:o.jsx("pre",{className:Q2s,children:a})}),s.scores.length>0&&o.jsx(IO,{title:"Scores",children:o.jsx("div",{className:"grid gap-2",children:s.scores.map(l=>o.jsx(prn,{scorerId:l.scorerId,value:l.value,delta:n?t.deltas[l.scorerId]:null,reason:l.reason},l.scorerId))})}),s.comment&&o.jsx(IO,{title:"Comment",defaultOpen:!1,children:o.jsx("p",{className:"text-neutral3 text-ui-md",children:s.comment})}),s.metadata&&Object.keys(s.metadata).length>0&&o.jsx(IO,{title:"Metadata",defaultOpen:!1,children:o.jsx("dl",{className:"grid gap-1",children:Object.entries(s.metadata).map(([l,c])=>o.jsxs("div",{className:"text-ui-md flex items-start justify-between gap-4",children:[o.jsx("dt",{className:"text-neutral3",children:l}),o.jsx("dd",{className:"text-neutral5 font-mono break-all",children:Hct(c)})]},l))})})]})}const K2s={baseline:"Baseline",contender:"Contender"},Y2s={baseline:"purple",contender:"blue"},X2s="flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0";function Zct({side:e,experiment:t,summary:n,showDeltas:r,versionMismatch:s}){const{Link:i,paths:a}=un(),l=K2s[e],c=t?ub(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(jt,{variant:Y2s[e],size:"xs",children:l}),t&&o.jsx(ae,{render:o.jsx(i,{href:`/experiments/${t.id}`}),size:"xs","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(Bd,{children:[o.jsx(TA,{})," ",c]}),t.targetType==="agent"&&t.targetId?o.jsxs(i,{href:a.agentLink(t.targetId),className:X2s,children:[o.jsx(Ma,{}),o.jsx("span",{className:"min-w-0 truncate",children:t.targetId})]}):o.jsxs(Bd,{children:[o.jsx(d1t,{})," ",t.targetId]}),o.jsx("span",{className:K(s&&"text-accent6"),children:o.jsxs(Bd,{children:[o.jsx(g4,{})," v",t.datasetVersion??"—",s&&" · different dataset version"]})}),u&&o.jsxs(Bd,{children:[o.jsx(mV,{})," ",gr(u,"MMM d, yyyy HH:mm")]})]}),d.length>0&&o.jsx(IO,{title:"Overall score",children:o.jsx("div",{className:"grid gap-2",children:d.map(({scorerId:f,average:h,delta:p})=>o.jsx(prn,{scorerId:f,value:h,delta:r?p:null},f))})})]})}const JT="min-w-0 px-4 py-3";function J2s({datasetId:e,experimentIdA:t,experimentIdB:n}){const{Link:r,paths:s}=un(),{data:i,isLoading:a,error:l}=qPs(e,t,n),{data:c}=X3(e,t),{data:u}=X3(e,n),d=c&&u&&c.datasetVersion!==u.datasetVersion,f=i?.baselineId??t,h=t===f?n:t,p=c?.id===f?c:u,m=c?.id===h?c:u,{data:v,isLoading:y}=Nke({datasetId:e,experimentId:f,experimentStatus:p?.status}),{data:b,isLoading:x}=Nke({datasetId:e,experimentId:h,experimentStatus:m?.status}),{data:w}=M1(f,p?.status),{data:k}=M1(h,m?.status),_=g.useMemo(()=>Z2s({comparison:i,baselineId:f,contenderId:h,baselineResults:v,contenderResults:b,baselineScores:w,contenderScores:k}),[i,f,h,v,b,w,k]),C=g.useMemo(()=>[...new Set(_.flatMap(E=>Object.keys(E.deltas)))].sort(),[_]),T=g.useMemo(()=>{const E=(A,P)=>{const L=_.map(M=>M[A].scores.find(V=>V.scorerId===P)?.value).filter(M=>M!=null);return L.length>0?L.reduce((M,V)=>M+V,0)/L.length:null},N=C.map(A=>({scorerId:A,average:E("baseline",A),delta:null})),I=C.map(A=>{const P=E("baseline",A),L=E("contender",A);return{scorerId:A,average:L,delta:P!=null&&L!=null?L-P:null}});return{baseline:N,contender:I}},[_,C]);return a?o.jsx("div",{className:"flex h-64 items-center justify-center",children:o.jsx(_n,{})}):l?o.jsx(xn,{variant:"warning",title:"Error loading comparison",children:o.jsx(xn.Message,{children:l instanceof Error?l.message:"Unknown error"})}):!i||i.items.length===0?o.jsx("div",{className:"text-neutral4 text-ui-md py-5 text-center",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:`${JT} text-neutral3 text-ui-sm uppercase`,children:"Items"}),o.jsx("div",{role:"columnheader","aria-label":"Baseline",className:JT,children:o.jsx(Zct,{side:"baseline",experiment:p??void 0,summary:T.baseline,versionMismatch:d??void 0})}),o.jsx("div",{role:"columnheader","aria-label":"Contender",className:JT,children:o.jsx(Zct,{side:"contender",experiment:m??void 0,summary:T.contender,versionMismatch:d??void 0,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:`${JT} 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(hrn,{delta:A},I))}),o.jsxs("div",{className:"grid pt-3",children:[o.jsx(qct,{label:"Input",value:E.input}),o.jsx(qct,{label:"Ground truth",value:E.groundTruth})]})]}),o.jsx("div",{role:"cell","aria-label":"Baseline",className:JT,children:o.jsx(Wct,{side:"baseline",row:E,isLoading:y})}),o.jsx("div",{role:"cell","aria-label":"Contender",className:JT,children:o.jsx(Wct,{side:"contender",row:E,isLoading:x,showDeltas:!0})})]},E.itemId)})]})})}function eDs({selectedCount:e,vocabulary:t,onApplyTag:n,onRemoveTag:r,onNewTag:s,size:i="sm"}){const[a,l]=g.useState(!1),[c,u]=g.useState(""),d=t.filter(h=>h.toLowerCase().includes(c.toLowerCase())),f=c.trim()&&!t.includes(c.trim());return o.jsxs(Zm,{open:a,onOpenChange:l,children:[o.jsx(Xf,{asChild:!0,children:o.jsxs(ae,{variant:"outline",size:i,icon:o.jsx(B_,{}),children:["Tag ",e," items"]})}),o.jsxs(vp,{className:"w-56 p-2",align:"end",children:[o.jsx($n,{value:c,onChange:h=>u(h.target.value),onKeyDown:h=>{h.key==="Enter"&&c.trim()&&(h.preventDefault(),f?s(c.trim()):n(c.trim()),u(""))},placeholder:"Search or create tag...",className:"text-ui-sm mb-1 h-7",autoFocus:!0}),o.jsxs("div",{className:"max-h-40 space-y-0.5 overflow-y-auto",children:[d.map(h=>o.jsxs("div",{className:"hover:bg-surface3 text-ui-sm flex items-center justify-between rounded px-2 py-1",children:[o.jsx("button",{type:"button",onClick:()=>n(h),className:"text-neutral4 flex-1 text-left",children:h}),o.jsx("button",{type:"button",onClick:()=>r(h),className:"text-neutral2 hover:text-negative1 ml-2",children:o.jsx(Yt,{className:"h-3 w-3"})})]},h)),f&&o.jsxs("button",{type:"button",onClick:()=>{s(c.trim()),u("")},className:"hover:bg-surface3 text-accent1 text-ui-sm w-full rounded px-2 py-1 text-left",children:['Create & apply "',c.trim(),'"']})]})]})]})}function tDs({tag:e,onRename:t,onRemove:n}){const[r,s]=g.useState(!1),[i,a]=g.useState(e),l=g.useRef(null);g.useEffect(()=>{r&&(l.current?.focus(),l.current?.select())},[r]);const c=()=>{const u=i.trim();u&&u!==e&&t(u),s(!1)};return r?o.jsxs("span",{className:"bg-surface3 border-border1 inline-flex items-center gap-0.5 rounded-md border px-1",children:[o.jsx("input",{ref:l,value:i,onChange:u=>a(u.target.value),onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),c()),u.key==="Escape"&&(a(e),s(!1))},onBlur:c,className:"text-neutral4 text-ui-sm w-20 bg-transparent py-0.5 outline-hidden"}),o.jsx("button",{type:"button",onMouseDown:u=>{u.preventDefault(),c()},className:"text-positive1 hover:text-positive2 p-0.5",children:o.jsx(Mn,{className:"h-3 w-3"})})]}):o.jsxs("span",{className:"bg-surface3 border-border1 text-neutral4 group text-ui-sm inline-flex items-center gap-0.5 rounded-md border px-1.5 py-0.5",children:[e,o.jsx("button",{type:"button",onClick:()=>{a(e),s(!0)},className:"text-neutral2 hover:text-neutral4 p-0.5 opacity-0 transition-opacity group-hover:opacity-100",title:"Edit tag",children:o.jsx(Gd,{className:"h-3 w-3"})}),o.jsx("button",{type:"button",onClick:n,className:"text-neutral2 hover:text-negative1 p-0.5 opacity-0 transition-opacity group-hover:opacity-100",title:"Remove tag",children:o.jsx(Yt,{className:"h-3 w-3"})})]})}const nDs=100;function iLe(e,t,{enabled:n=!0}={}){const r=Ye(),s={perPage:nDs};return t?.targetType&&(s.targetType=t.targetType),t?.targetId&&(s.targetId=t.targetId),yt({enabled:n,queryKey:["experiments",s],queryFn:()=>r.listExperiments(s)})}const mrn=(e,{experimentId:t,targetType:n,targetId:r,experiments:s,isLoadingExperiments:i=!1})=>{const a=Ye(),l=s!==void 0,{data:c,isLoading:u}=iLe(void 0,{targetType:n,targetId:r},{enabled:!l}),d=l?s:c?.experiments,f=l?i:u,h=t?d?.filter(m=>m.id===t):d,p=yt({queryKey:["review-items",e,t??"all",l?"supplied":"discovered",l?void 0:n||"all",l?void 0:r||"all",h?.map(m=>[m.datasetId,m.id])],queryFn:async()=>!h||h.length===0?[]:(await Promise.all(h.map(async v=>{if(!v.datasetId)return[];try{const{results:y}=await a.listDatasetExperimentResults(v.datasetId,v.id);return y.filter(b=>b.status===e).map(b=>({id:b.id,input:b.input,output:b.output,error:b.error,itemId:b.itemId,experimentId:b.experimentId,datasetId:v.datasetId??void 0,traceId:b.traceId??void 0,scores:b.scores?Object.fromEntries(b.scores.map(x=>[x.scorerId,x.score??0])):{},tags:b.tags??[],createdAt:b.createdAt,status:b.status,groundTruth:b.groundTruth,toolMockReport:b.toolMockReport}))}catch{return[]}}))).flat(),enabled:!!d,refetchOnWindowFocus:!1});return{...p,isLoading:p.isLoading||f}},rDs=(e={})=>mrn("needs-review",e),sDs=(e={})=>mrn("complete",e);function iDs(e){const{data:t}=zE(e),r=t?.spans.find(a=>!a.parentSpanId)?.entityType==="agent",{supportsMetrics:s}=rF(),i=_ke({traceIds:e?[e]:[],enabled:r&&s,autoRefetch:!1});return e?i.data?.get(e):void 0}const Gct="__create_tag__";function grn({selectedResults:e,vocabulary:t,onAddTag:n,disabled:r,appearance:s="toolbar"}){const[i,a]=g.useState(""),l=g.useMemo(()=>[...t].sort(),[t]),c=g.useMemo(()=>{if(e.length===0)return new Set;const[f,...h]=e;return new Set((f.tags??[]).filter(p=>h.every(m=>(m.tags??[]).includes(p))))},[e]),u=g.useMemo(()=>{const f=l.map(m=>({label:m,value:m,end:c.has(m)?o.jsx(Mn,{"data-testid":"tag-applied",className:"size-3.5"}):void 0})),h=i.trim();return h.length>0&&!l.includes(h)?[{label:`Create "${h}"`,value:Gct},...f]:f},[l,c,i]),d=f=>{const h=f===Gct?i.trim():f;!h||c.has(h)||n(h)};return o.jsx(qo,{"data-testid":"experiment-results-tag-picker",options:u,value:void 0,onValueChange:d,onInputValueChange:a,placeholder:o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(B_,{className:"size-3.5"}),"Add tag"]}),searchPlaceholder:"Search or create tag...",emptyText:"Type to create a tag",variant:s==="inline"?"ghost":"outline",size:s==="inline"?"xs":"md",className:"w-auto min-w-0",disabled:r})}function Fue(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function aDs({report:e}){const{served:t,unconsumed:n,liveCalls:r,failure:s}=e,i=[...t.map(a=>({outcome:"served",toolName:a.toolName,args:a.args})),...r.map(a=>({outcome:"live",toolName:a.toolName,args:a.args})),...n.map(a=>({outcome:"unconsumed",toolName:a.toolName,args:a.args}))];return o.jsxs("div",{className:"grid gap-2","data-testid":"tool-mock-report",children:[o.jsx($t.SectionHeading,{icon:o.jsx(xu,{}),children:"Tool Mocks"}),s&&o.jsx(xn,{variant:"destructive",title:"Mock mismatch",children:o.jsxs(xn.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:"text-ui-sm mt-1 block font-mono",children:["Called with: ",Fue(s.args)]}),n.length>0&&o.jsxs("span",{className:"text-ui-sm mt-1 block font-mono",children:["Unconsumed mocks: ",n.map(a=>Fue(a.args)).join(", ")]})]})}),o.jsx("div",{className:"border-border1 divide-border1 text-ui-md divide-y rounded border",children:i.map((a,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:a.toolName}),o.jsx("span",{className:"text-neutral3 text-ui-sm ml-2 font-mono",children:Fue(a.args)})]}),o.jsx("span",{className:`text-ui-sm shrink-0 rounded px-2 py-0.5 ${oDs(a.outcome)}`,children:a.outcome})]},`${a.outcome}-${a.toolName}-${l}`))})]})}function oDs(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 lDs({result:e,itemId:t,fallback:n,title:r,onClose:s,...i}){const a=r??(t?`Experiment item ${t}`:`Result ${e?.id??""}`);return o.jsx($t,{open:!!(e??t),onClose:s,title:a,depth:1,size:"half",children:e?o.jsx(cDs,{result:e,onClose:s,...i}):t?o.jsxs(o.Fragment,{children:[o.jsxs($t.Header,{children:[o.jsx($t.CloseButton,{onClick:s,tooltip:"Close result panel"}),o.jsxs($t.Heading,{children:["Experiment item",o.jsx($t.CopyId,{id:t})]})]}),n]}):null})}function cDs({result:e,scores:t,onPrevious:n,onNext:r,onClose:s,onShowTrace:i,onScoreClick:a,featuredScoreId:l,onFlagForReview:c,onTagsChange:u,tagVocabulary:d=[],isUpdatingTags:f=!1,experimentLink:h,onComplete:p,feedbackTabSlot:m}){const v=!!e?.error,y=OB(e?.input),b=OB(e?.output),x=OB(e?.groundTruth),w=c&&e.status!=="needs-review"&&e.status!=="complete",k=Array.isArray(e.tags)?e.tags:[],_=g.useMemo(()=>[e],[e]),C=!!u||k.length>0,{Link:T}=un(),E=m&&e.traceId?e.traceId:void 0,{data:N}=sF({traceId:E}),I=iDs(e.traceId),A=o.jsxs($t.Content,{children:[o.jsxs("div",{className:"mb-6 grid gap-4",children:[o.jsxs(fn,{children:[o.jsx(fn.Key,{children:"Item Id"}),o.jsx(fn.ValueWithCopyBtn,{copyTooltip:"Copy Item Id to clipboard",copyValue:e.itemId,children:e.itemId}),e.createdAt&&o.jsxs(o.Fragment,{children:[o.jsx(fn.Key,{children:"Created"}),o.jsx(fn.Value,{children:gr(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")})]}),e.status&&o.jsxs(o.Fragment,{children:[o.jsx(fn.Key,{children:"Status"}),o.jsx(fn.Value,{children:o.jsx(HDe,{status:e.status})})]}),C&&o.jsxs(o.Fragment,{children:[o.jsx(fn.Key,{children:"Tags"}),o.jsx(fn.Value,{children:o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[k.map(P=>o.jsxs(mJ,{value:P,className:u?"gap-1 pr-1":void 0,children:[P,u&&o.jsx("button",{type:"button","aria-label":`Remove tag ${P}`,disabled:f,onClick:()=>u(k.filter(L=>L!==P)),className:"cursor-pointer rounded-sm hover:opacity-70 disabled:opacity-50",children:o.jsx(Yt,{className:"size-3"})})]},P)),u&&o.jsx(grn,{appearance:"inline",selectedResults:_,vocabulary:d,onAddTag:P=>u([...k,P]),disabled:f})]})})]}),I&&o.jsxs(o.Fragment,{children:[o.jsx(fn.Key,{children:"Input tokens"}),o.jsx(fn.Value,{children:I.inputTokens!==void 0?lo(I.inputTokens):"—"}),o.jsx(fn.Key,{children:"Output tokens"}),o.jsx(fn.Value,{children:I.outputTokens!==void 0?lo(I.outputTokens):"—"}),o.jsx(fn.Key,{children:"Cost"}),o.jsx(fn.Value,{children:I.estimatedCost!==void 0?Zd(I.estimatedCost,I.costUnit):"—"})]})]}),v&&o.jsx(xn,{variant:"destructive",title:"Error",children:o.jsx(xn.Message,{children:OB(e?.error&&typeof e.error=="object"?e.error.message:e?.error)})}),t&&t.length>0&&o.jsxs(we,{columns:"1fr 1fr",children:[o.jsxs(we.Top,{children:[o.jsx(we.TopCell,{children:"Scorer"}),o.jsx(we.TopCell,{children:"Score"})]}),t.map(P=>a?o.jsxs(we.RowButton,{featured:l===P.id,onClick:()=>a(P.id),children:[o.jsx(we.Cell,{children:P.scorerId}),o.jsx(we.TextCell,{font:"mono",children:P.score.toFixed(3)})]},P.id):o.jsxs(we.RowStatic,{children:[o.jsx(we.Cell,{children:P.scorerId}),o.jsx(we.TextCell,{font:"mono",children:P.score.toFixed(3)})]},P.id))]}),e.toolMockReport&&o.jsx(aDs,{report:e.toolMockReport})]}),o.jsxs("div",{className:"grid gap-3",children:[o.jsx($t.CodeSection,{title:"Input",icon:o.jsx(kCe,{}),codeStr:y}),o.jsx($t.CodeSection,{title:"Output",icon:o.jsx(Gx,{}),codeStr:b}),e.groundTruth!==void 0&&o.jsx($t.CodeSection,{title:"Ground Truth",icon:o.jsx(d1t,{}),codeStr:x})]})]});return o.jsxs(o.Fragment,{children:[o.jsxs($t.Header,{children:[o.jsx($t.CloseButton,{onClick:s,tooltip:"Close result panel"}),o.jsxs($t.Heading,{children:["Result",o.jsx($t.CopyId,{id:e.id})]}),o.jsxs($t.HeaderActions,{children:[w&&o.jsx(ae,{size:"sm",variant:"primary",onClick:()=>c(e.id),icon:o.jsx(F_,{}),children:"Flag for Review"}),p&&e.status==="needs-review"&&o.jsx(ae,{size:"sm",variant:"primary",onClick:p,icon:o.jsx(rG,{}),children:"Mark as reviewed"}),h&&o.jsx(ae,{size:"sm",variant:"ghost",render:o.jsx(T,{href:h}),tooltip:"See experiment","aria-label":"See experiment",children:o.jsx(OCe,{})}),e.traceId&&i&&o.jsx(ae,{size:"sm",variant:"ghost",onClick:i,tooltip:"See trace","aria-label":"See trace",children:o.jsx(fE,{})}),o.jsx($t.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Go to previous result",nextLabel:"Go to next result"})]})]}),E?o.jsxs(hl,{defaultTab:"details",className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[o.jsx($t.Header,{children:o.jsxs(fl,{variant:"pill-ghost",size:"sm",children:[o.jsx(Sr,{value:"details",children:"Details"}),o.jsxs(Sr,{value:"feedback",children:["Feedback",N?.pagination?.total!=null&&o.jsxs(o.Fragment,{children:[" (",N.pagination.total,")"]})]})]})}),o.jsx(ts,{value:"details",flush:!0,children:A}),o.jsx(ts,{value:"feedback",flush:!0,children:o.jsx($t.Content,{children:m({traceId:E})})})]}):A]})}function OB(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function uDs(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function dDs({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s}){return o.jsx($t,{open:!!e,onClose:r,title:e?`Score ${e.scorerId}`:"Score",depth:2,children:e&&o.jsx(fDs,{score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s})})}function fDs({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s}){const i=uDs(e),a=i?"N/A — code-based scorer":"N/A — step not configured";return o.jsxs(o.Fragment,{children:[o.jsxs($t.Header,{children:[o.jsx($t.CloseButton,{onClick:r,tooltip:"Close score panel"}),o.jsxs($t.Heading,{children:["Score",o.jsx($t.CopyId,{id:e.scorerId})]}),o.jsxs($t.HeaderActions,{children:[s&&e.traceId&&o.jsx(ae,{size:"sm",variant:"ghost",onClick:s,tooltip:"See trace","aria-label":"See trace",children:o.jsx(fE,{})}),(n||t)&&o.jsx($t.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:"Go to previous score",nextLabel:"Go to next score"})]})]}),o.jsx($t.Content,{children:o.jsxs("div",{className:"grid gap-3",children:[o.jsx($t.CodeSection,{title:`Score: ${e.score}`,icon:o.jsx(gb,{}),codeStr:e.reason||a,simplified:!0}),!i&&o.jsxs(o.Fragment,{children:[o.jsx($t.CodeSection,{title:"Preprocess Prompt",icon:o.jsx(Kp,{}),codeStr:e.preprocessPrompt||a,simplified:!0}),o.jsx($t.CodeSection,{title:"Analyze Prompt",icon:o.jsx(Kp,{}),codeStr:e.analyzePrompt||a,simplified:!0}),o.jsx($t.CodeSection,{title:"Generate Score Prompt",icon:o.jsx(Kp,{}),codeStr:e.generateScorePrompt||a,simplified:!0}),o.jsx($t.CodeSection,{title:"Generate Reason Prompt",icon:o.jsx(Kp,{}),codeStr:e.generateReasonPrompt||a,simplified:!0})]})]})})]})}function vrn(e,t){const[n,r]=g.useState(null),[s,i]=g.useState(void 0),[a,l]=g.useState(null),[c,u]=g.useState(t);t!==c&&(u(t),r(null),i(void 0),l(null));const d=e?.find(f=>f.id===a)??null;return{featuredTraceId:n,setFeaturedTraceId:r,featuredSpanId:s,setFeaturedSpanId:i,featuredScoreId:a,setFeaturedScoreId:l,featuredScore:d}}function yrn({result:e,scores:t,state:n,...r}){const s=vrn(t,e?.id),{featuredTraceId:i,setFeaturedTraceId:a,featuredSpanId:l,setFeaturedSpanId:c,featuredScoreId:u,setFeaturedScoreId:d,featuredScore:f}=n??s,h=T=>{d(E=>T===E?null:T),a(null),c(void 0)},p=T=>{T&&(a(T),c(void 0),d(null))},m=()=>{if(!u||!t)return;const T=t.findIndex(E=>E.id===u);if(T>=0&&T<t.length-1)return()=>d(t[T+1].id)},v=()=>{if(!u||!t)return;const T=t.findIndex(E=>E.id===u);if(T>0)return()=>d(t[T-1].id)},{data:y,isLoading:b}=BMs(i),x=y?.spans,w=x?.find(T=>!T.parentSpanId),{data:k}=sF({traceId:i??void 0}),{data:_}=qDe({traceId:i??void 0,spanId:l}),{data:C}=UX({traceId:i??void 0,spanId:w?.spanId,page:0});return o.jsxs(o.Fragment,{children:[o.jsx(lDs,{...r,result:e,scores:t,onScoreClick:h,featuredScoreId:u,onShowTrace:e?.traceId?()=>p(e.traceId):void 0,feedbackTabSlot:({traceId:T})=>o.jsx(Y3,{traceId:T},T)}),o.jsx(dDs,{score:f??void 0,onNext:m(),onPrevious:v(),onClose:()=>d(null),onShowTrace:f?()=>p(f.traceId):void 0}),o.jsx(XDe,{size:"wide",depth:2,traceId:i??void 0,spans:x,isLoadingSpans:b,selectedSpanId:l??null,onClose:()=>{a(null),c(void 0)},onSpanSelect:c,showUnavailableFeaturesMsg:!1,traceHref:i?`/traces?traceId=${encodeURIComponent(i)}`:void 0,anchorSpanId:w?.spanId,feedbackTabBadge:k?.pagination?.total??void 0,feedbackTabSlot:({traceId:T})=>o.jsx(Y3,{traceId:T}),scoresTabBadge:C?.pagination?.total??void 0,scoresTabSlot:({traceId:T,rootSpanId:E})=>E?o.jsx(GDe,{traceId:T,spanId:E,onScoreSelect:N=>{t?.some(I=>I.id===N)&&(a(null),c(void 0),d(N))}}):null,spanFeedbackTabBadge:_?.pagination?.total??void 0,spanFeedbackTabSlot:({traceId:T,spanId:E})=>T&&E?o.jsx(ZDe,{traceId:T,spanId:E},`${T}:${E}`):null})]})}const hDs=[{name:"itemId",label:"Item ID",size:"auto"},{name:"input",label:"Input",size:"minmax(0,1fr)"},{name:"tags",label:"Tags",size:"auto"},{name:"scores",label:"Scores",size:"6rem"}],zue="__untagged__",Bue="all",pDs=[{value:"review",label:"Review queue"},{value:"completed",label:"Completed"}];function mDs({datasetId:e,experimentId:t,experiments:n,isLoadingExperiments:r,targetType:s,targetId:i,featuredItemId:a,toolbarStart:l,toolbarEnd:c,onCreateScorer:u}){const d=Ye(),{paths:f}=un(),{data:h}=bv(e??""),{data:p,isLoading:m}=rDs({experimentId:t,targetType:s,targetId:i,experiments:n,isLoadingExperiments:r}),{data:v,isLoading:y}=sDs({experimentId:t,targetType:s,targetId:i,experiments:n,isLoadingExperiments:r}),{updateExperimentResult:b}=pl(),[x,w]=g.useState(a??null);g.useEffect(()=>{a!==void 0&&w(a)},[a]);const[k,_]=g.useState(null),[C,T]=g.useState(new Set),[E,N]=g.useState(!1),[I,A]=g.useState(!1),[P,L]=g.useState(!1),[M,V]=g.useState(""),[q,H]=g.useState(""),[B,W]=g.useState(""),[z,G]=g.useState([]),[F,R]=g.useState(!1),D=g.useMemo(()=>p??[],[p]),U=g.useMemo(()=>{const Ce=new Set;if(h?.tags)for(const Ne of h.tags)Ce.add(Ne);for(const Ne of D)for(const $e of Ne.tags)Ce.add($e);return[...Ce].sort()},[h,D]),Q=g.useCallback(Ce=>{!h||!e||(h.tags??[]).includes(Ce)},[h,e]),ee=g.useMemo(()=>k?k===zue?D.filter(Ce=>Ce.tags.length===0):D.filter(Ce=>Ce.tags.includes(k)):D,[D,k]),J=g.useMemo(()=>{const Ce=new Map;let Ne=0;for(const De of D){De.tags.length===0&&Ne++;for(const tt of De.tags)Ce.set(tt,(Ce.get(tt)??0)+1)}const $e=[...Ce.entries()].sort((De,tt)=>tt[1]-De[1]).map(([De])=>({value:De,label:De}));return[{value:Bue,label:"All tags"},...Ne>0?[{value:zue,label:"Untagged"}]:[],...$e]},[D]),te=!!k||E,re=g.useCallback(()=>{_(null),N(!1),w(null)},[]),ce=g.useCallback((Ce,Ne)=>{const $e=D.find(De=>De.id===Ce);$e?.experimentId&&$e?.datasetId&&b.mutate({datasetId:$e.datasetId,experimentId:$e.experimentId,resultId:$e.id,tags:Ne})},[D,b]),X=g.useCallback(Ce=>{const Ne=D.find($e=>$e.id===Ce);T($e=>{const De=new Set($e);return De.delete(Ce),De}),x===Ce&&w(null),Ne?.experimentId&&Ne?.datasetId&&b.mutate({datasetId:Ne.datasetId,experimentId:Ne.experimentId,resultId:Ne.id,status:null})},[D,b,x]),ne=g.useCallback(Ce=>{const Ne=D.find($e=>$e.id===Ce);T($e=>{const De=new Set($e);return De.delete(Ce),De}),x===Ce&&w(null),Ne?.experimentId&&Ne?.datasetId&&b.mutate({datasetId:Ne.datasetId,experimentId:Ne.experimentId,resultId:Ne.id,status:"complete"})},[D,b,x]),se=g.useMemo(()=>{const Ce=E?v??[]:ee;return!E||!k?Ce:k===zue?Ce.filter(Ne=>Ne.tags.length===0):Ce.filter(Ne=>Ne.tags.includes(k))},[E,v,ee,k]),le=E?y:!1,he=g.useMemo(()=>new Set(se.map(Ce=>Ce.id)),[se]),pe=g.useMemo(()=>[...C].filter(Ce=>he.has(Ce)).length,[C,he]),Se=se.length>0&&pe===se.length,Ee=g.useCallback(Ce=>{T(Ne=>{const $e=new Set(Ne);return $e.has(Ce)?$e.delete(Ce):$e.add(Ce),$e})},[]),Re=g.useCallback(()=>{T(Se?new Set:new Set(se.map(Ce=>Ce.id)))},[Se,se]),We=g.useCallback(Ce=>{for(const Ne of C){const $e=D.find(De=>De.id===Ne);$e&&!$e.tags.includes(Ce)&&ce(Ne,[...$e.tags,Ce])}},[D,C,ce]),Ue=g.useCallback(Ce=>{for(const Ne of C){const $e=D.find(De=>De.id===Ne);$e&&$e.tags.includes(Ce)&&ce(Ne,$e.tags.filter(De=>De!==Ce))}},[D,C,ce]),Fe=g.useCallback(()=>{for(const Ce of C)ne(Ce);T(new Set)},[C,ne]),me=g.useCallback(()=>{for(const Ce of C)X(Ce);T(new Set)},[C,X]),je=g.useCallback(()=>{V(""),L(!0)},[]),fe=g.useCallback(async()=>{if(!(!q||!B)){A(!0),L(!1);try{const Ce=D.filter($e=>C.has($e.id));if(Ce.length===0){A(!1);return}const Ne=await d.clusterFailures({modelId:`${q}/${B}`,items:Ce.map($e=>({id:$e.id,input:$e.input,output:$e.output??void 0,error:typeof $e.error=="string"?$e.error:$e.error?String($e.error):void 0,scores:$e.scores,existingTags:$e.tags.length>0?$e.tags:void 0})),availableTags:U.length>0?U:void 0,prompt:M||void 0});Ne.proposedTags&&Ne.proposedTags.length>0&&(G(Ne.proposedTags.map($e=>({...$e,accepted:!0}))),R(!0))}catch(Ce){console.error("Analysis failed:",Ce)}finally{A(!1)}}},[q,B,D,C,d,U,M]),ve=g.useCallback(()=>{for(const Ce of z){if(!Ce.accepted)continue;const Ne=D.find($e=>$e.id===Ce.itemId);if(Ne){const $e=[...new Set([...Ne.tags,...Ce.tags])];ce(Ne.id,$e)}}R(!1)},[z,D,ce]),_e=g.useCallback(Ce=>{w(Ne=>Ne===Ce?null:Ce)},[]),ge=g.useMemo(()=>x?se.find(Ce=>Ce.id===x)??null:null,[x,se]),{data:Ie}=M1(ge?.experimentId??""),Ze=x?se.findIndex(Ce=>Ce.id===x):-1,qe=Ze>0?()=>w(se[Ze-1].id):void 0,de=Ze>=0&&Ze<se.length-1?()=>w(se[Ze+1].id):void 0,be=!E&&C.size>0,ke=!!u&&!E&&ee.length>0,ze=o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs(Ms,{children:[l,o.jsx(of,{label:"Status",labelIsHidden:!0,name:"filter-status",options:pDs,value:E?"completed":"review",onValueChange:Ce=>{N(Ce==="completed"),w(null)},className:"whitespace-nowrap"}),J.length>1&&o.jsx(of,{label:"Tags",labelIsHidden:!0,name:"filter-tags",options:J,value:k??Bue,onValueChange:Ce=>_(Ce===Bue?null:Ce),className:"whitespace-nowrap"}),te&&o.jsx(ae,{onClick:re,size:"sm",variant:"default",icon:o.jsx(Yt,{}),children:"Reset"})]}),(be||c||ke)&&o.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-2",children:[c,ke&&o.jsxs(ae,{variant:"outline",size:"md",onClick:()=>u?.(ee.map(Ce=>({input:Ce.input,output:Ce.output}))),children:[o.jsx(St,{size:"sm",children:o.jsx(gb,{})}),"Create Scorer"]}),be&&o.jsxs(o.Fragment,{children:[o.jsx(eDs,{size:"md",selectedCount:C.size,vocabulary:U,onApplyTag:We,onRemoveTag:Ue,onNewTag:Ce=>We(Ce)}),o.jsx(ae,{variant:"primary",onClick:Fe,icon:o.jsx(rG,{}),children:"Mark as reviewed"}),o.jsxs(xt,{children:[o.jsx(xt.Trigger,{asChild:!0,children:o.jsx(ae,{variant:"outline",disabled:I,"aria-label":"More actions",children:I?o.jsx(_n,{className:"h-4 w-4"}):o.jsx(BD,{})})}),o.jsxs(xt.Content,{align:"end",children:[o.jsxs(xt.Item,{onSelect:je,children:[o.jsx(St,{size:"sm",children:o.jsx(y4,{})}),"Analyze"]}),o.jsx(xt.Separator,{}),o.jsxs(xt.Item,{onSelect:me,children:[o.jsx(St,{size:"sm",children:o.jsx(co,{})}),"Remove from queue"]})]})]})]})]})]});if(m)return o.jsxs(o.Fragment,{children:[o.jsx(Ft.TopArea,{children:ze}),o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsx(_n,{className:"h-6 w-6"})})]});const He=o.jsx(yrn,{result:ge??void 0,title:`Review item ${ge?.id??""}`,scores:ge?Ie?.[ge.itemId]:void 0,experimentLink:ge?.experimentId?f.experimentItemLink(ge.experimentId,ge.itemId):void 0,tagVocabulary:U,onTagsChange:E||!ge?void 0:Ce=>{ce(ge.id,Ce);for(const Ne of Ce)U.includes(Ne)||Q(Ne)},onComplete:E||!ge?void 0:()=>ne(ge.id),onPrevious:qe,onNext:de,onClose:()=>w(null)});return o.jsxs(o.Fragment,{children:[o.jsx(Ft.TopArea,{children:ze}),o.jsx(hs,{open:P,onOpenChange:L,children:o.jsxs(Jr,{children:[o.jsxs(es,{children:[o.jsx(Kr,{children:"Analyze Items"}),o.jsx(Ps,{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(Vt,{className:"text-ui-sm mb-1 block",children:"Provider"}),o.jsx(ak,{value:q,onValueChange:H})]}),o.jsxs("div",{children:[o.jsx(Vt,{className:"text-ui-sm mb-1 block",children:"Model"}),o.jsx(ok,{llmId:q,value:B,onValueChange:W})]})]}),o.jsxs(Te,{variant:"ui-xs",className:"text-neutral3",children:[C.size," item",C.size!==1?"s":""," will be analyzed"]}),o.jsxs("div",{children:[o.jsx(Vt,{className:"text-ui-sm",children:"Instructions (optional)"}),o.jsx(Yd,{value:M,onChange:Ce=>V(Ce.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3,className:"text-ui-sm mt-1"})]})]}),o.jsxs(lc,{children:[o.jsx(ae,{icon:o.jsx(Yt,{}),variant:"outline",onClick:()=>L(!1),children:"Cancel"}),o.jsxs(ae,{onClick:fe,disabled:!q||!B||I,children:[I?o.jsx(_n,{className:"mr-1 h-4 w-4"}):null,"Analyze"]})]})]})}),o.jsx(hs,{open:F,onOpenChange:R,children:o.jsxs(Jr,{className:"max-h-[80vh] max-w-2xl overflow-y-auto",children:[o.jsxs(es,{children:[o.jsx(Kr,{children:"Review Proposed Tags"}),o.jsxs(Ps,{children:[z.filter(Ce=>Ce.accepted).length," of ",z.length," proposals selected"]})]}),o.jsx("div",{className:"space-y-3 py-2",children:z.map((Ce,Ne)=>{const $e=D.find(De=>De.id===Ce.itemId);return o.jsx("div",{className:K("p-3 border rounded-lg",!Ce.accepted&&"opacity-50"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(od,{checked:Ce.accepted,onCheckedChange:De=>G(tt=>tt.map((Et,Ae)=>Ae===Ne?{...Et,accepted:!!De}:Et))}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(Te,{variant:"ui-xs",className:"text-neutral4 block truncate",children:$e?typeof $e.input=="string"?$e.input.slice(0,100):JSON.stringify($e.input).slice(0,100):Ce.itemId}),o.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:Ce.tags.map((De,tt)=>o.jsx(tDs,{tag:De,onRename:Et=>G(Ae=>Ae.map((Xe,dt)=>dt===Ne?{...Xe,tags:Xe.tags.map((zt,qt)=>qt===tt?Et:zt)}:Xe)),onRemove:()=>G(Et=>Et.map((Ae,Xe)=>Xe===Ne?{...Ae,tags:Ae.tags.filter((dt,zt)=>zt!==tt)}:Ae))},`${De}-${tt}`))}),Ce.reason&&o.jsx(Te,{variant:"ui-xs",className:"text-neutral3 mt-1 block italic",children:Ce.reason})]})]})},Ce.itemId)})}),o.jsxs(lc,{children:[o.jsx(ae,{icon:o.jsx(Yt,{}),variant:"outline",onClick:()=>R(!1),children:"Cancel"}),o.jsxs(ae,{icon:o.jsx(Mn,{}),onClick:ve,disabled:z.filter(Ce=>Ce.accepted).length===0,children:["Accept ",z.filter(Ce=>Ce.accepted).length," proposals"]})]})]})}),o.jsxs(Ft.MainArea,{className:"grid h-full min-h-0 w-full grid-cols-1 gap-4 overflow-hidden",children:[o.jsx("div",{className:"min-h-0 w-full overflow-hidden",children:le?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(_n,{className:"h-6 w-6"})}):se.length===0?o.jsx("div",{className:"flex h-full items-center-safe justify-center-safe overflow-auto py-8",children:o.jsx(Ar,{iconSlot:o.jsx(Ls,{className:"text-neutral3 h-8 w-8"}),titleSlot:E?"No completed reviews yet":"No items to review",descriptionSlot:E?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here."})}):o.jsx(nLe,{results:se,isLoading:!1,featuredResultId:x,onResultClick:_e,columns:hDs,selectedIds:E?void 0:C,onToggleSelect:E?void 0:Ee,onToggleSelectAll:E?void 0:Re})}),He]})]})}const Qct={needsReview:"#facc15",complete:"#22c55e"},gDs=[{label:"Needs Review",color:Qct.needsReview},{label:"Reviewed",color:Qct.complete}];function vDs({reviewSummary:e,experiments:t,datasets:n,isLoading:r,isError:s}){const{data:i,maxVal:a,totalInPipeline:l}=g.useMemo(()=>{if(!e?.counts||!t)return{data:[],maxVal:0,totalInPipeline:0};const u=new Map;for(const m of t)u.set(m.id,m);const d=new Map;if(n)for(const m of n)d.set(m.id,m.name);let f=0,h=0;const p=[];for(const m of e.counts){const v=m.needsReview+m.complete;if(v===0)continue;h+=v,v>f&&(f=v);const y=u.get(m.experimentId),b=y?.datasetId?d.get(y.datasetId):void 0,x=b?`${b} · ${m.experimentId.slice(0,8)}`:m.experimentId.slice(0,8);p.push({name:x,values:[m.needsReview,m.complete]})}return{data:p,maxVal:f,totalInPipeline:h}},[e,t,n]),c=i.length>0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Review Pipeline",description:"Items in review across experiments."}),c&&o.jsx(Ht.Summary,{value:String(l),label:"Items in pipeline"})]}),r?o.jsx(Ht.Loading,{}):s?o.jsx(Ht.Error,{message:"Failed to load review data"}):o.jsx(Ht.Content,{children:c?o.jsx(vA,{data:i,segments:gDs,maxVal:a,fmt:u=>String(u)}):o.jsx(Ht.NoData,{message:"No items have been sent to review yet"})})]})}function brn(){const e=Ye();return yt({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function yDs(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 bDs(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 xDs(){const[e,t]=g.useState("all"),[n,r]=g.useState({}),{data:s,isLoading:i,error:a}=Ep(),{data:l,isLoading:c,error:u}=q0(),{data:d,isLoading:f,error:h}=KG(),{data:p,isLoading:m,isError:v,error:y}=$ks(n),{data:b,isLoading:x,isError:w,error:k}=brn(),_=l?.datasets,C=d?.experiments,T=g.useMemo(()=>bDs(b),[b]),E=a||u||h||y||k;return E&&ks(E)?o.jsx(Qn,{children:o.jsx(Gs,{})}):E&&Es(E)?o.jsx(Qn,{children:o.jsx(Fs,{resource:"evaluation"})}):E?o.jsx(Qn,{children:o.jsx(Ws,{title:"Failed to load evaluation data",message:E.message})}):o.jsxs(Ft,{width:"wide",height:"full",children:[o.jsx(Ft.TopArea,{children:o.jsx(Ft.Row,{children:o.jsx(Ft.Column,{children:o.jsx(n6,{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-4",children:[o.jsx(Pke,{children:o.jsx(S2s,{scorers:s,datasets:_,experiments:C,avgScore:p?.avgScore??null,prevAvgScore:p?.prevAvgScore??null,totalNeedsReview:T.needsReview,isLoadingScorers:i,isLoadingDatasets:c,isLoadingExperiments:f,isLoadingScores:m,isLoadingReview:x})}),o.jsx(c1s,{summaryData:p?.summaryData??[],overTimeData:p?.overTimeData??[],scorerNames:p?.scorerNames??[],avgScore:p?.avgScore??null,isLoading:m,isError:v}),o.jsxs("div",{className:"grid grid-cols-1 gap-4 lg:grid-cols-2",children:[o.jsx(p$s,{experiments:C,isLoading:f,isError:!!h}),o.jsx(V2s,{experiments:C,datasets:_,isLoading:f,isError:!!h})]}),o.jsx(vDs,{reviewSummary:b,experiments:C,datasets:_,isLoading:x,isError:!!w})]})]})}const wDs=100;function SDs(e,t){const n=Ye(),{inView:r,setRef:s}=Sb(),i=t?.targetType||void 0,a=t?.targetId||void 0,l=yv({queryKey:e?["dataset-experiments",e,"infinite",{targetType:i,targetId:a}]:["experiments","infinite",{targetType:i,targetId:a}],queryFn:({pageParam:c})=>{const u={page:c,perPage:wDs};return i&&(u.targetType=i),a&&(u.targetId=a),e?n.listDatasetExperiments(e,u):n.listExperiments(u)},initialPageParam:0,getNextPageParam:(c,u,d)=>{if(!(!c?.experiments?.length||!c.pagination?.hasMore))return d+1},select:c=>c.pages.flatMap(u=>u?.experiments??[])});return g.useEffect(()=>{r&&l.hasNextPage&&!l.isFetchingNextPage&&l.fetchNextPage()},[r,l]),{...l,setEndOfListElement:s}}function kDs(){const[e,t]=g.useState(""),[n,r]=g.useState("all"),[s,i]=g.useState(!1),[a,l]=g.useState(!1),[c,u]=g.useState([]),d=Fr(),[f,h]=bi(),p=f.get("dataset")??"all",m=g.useCallback(J=>{h(te=>{const re=new URLSearchParams(te);return J==="all"?re.delete("dataset"):re.set("dataset",J),re},{replace:!0})},[h]),{targetType:v,targetId:y,setTargetType:b,setTargetId:x}=sLe(),{data:w,isLoading:k,error:_}=q0(),{data:C,isLoading:T,error:E,isFetchingNextPage:N,hasNextPage:I,setEndOfListElement:A}=SDs(p==="all"?void 0:p,{targetType:v,targetId:y}),{data:P}=brn(),L=g.useMemo(()=>w?.datasets??[],[w?.datasets]),M=g.useMemo(()=>C??[],[C]),V=g.useMemo(()=>B2s(L),[L]),q=g.useMemo(()=>yDs(P),[P]),H=k||T,B=E||_,W=J=>{u(te=>te.includes(J)?te.filter(re=>re!==J):te.length>=2?[te[0],J]:[...te,J])},z=()=>{u([]),l(!1)},{selectedIds:G,selectedDatasetIds:F}=g.useMemo(()=>{const J=new Map(M.map(re=>[re.id,re.datasetId])),te=c.filter(re=>J.has(re));return{selectedIds:te,selectedDatasetIds:new Set(te.map(re=>J.get(re)))}},[M,c]),R=G.length===2&&F.size!==1?"not the same dataset":void 0,D=()=>{if(G.length!==2||R)return;const[J,te]=G,[re]=F;if(!re)return;const ce=new URLSearchParams({dataset:re,baseline:J,contender:te});d(`/experiments/compare?${ce.toString()}`)};if(B&&ks(B))return o.jsx(Qn,{children:o.jsx(Gs,{})});if(E&&Es(E))return o.jsx(Qn,{children:o.jsx(Fs,{resource:"experiments"})});if(_&&Es(_))return o.jsx(Qn,{children:o.jsx(Fs,{resource:"datasets"})});if(B)return o.jsx(Qn,{children:o.jsx(Ws,{title:"Failed to load experiments",message:B.message})});const U=o.jsx(yJ,{open:s,onOpenChange:i,onSuccess:J=>{d(`/experiments/${J}`)}});if(M.length===0&&!H&&p==="all"&&!v)return o.jsxs(Qn,{children:[o.jsx(q2s,{onRunExperiment:()=>i(!0)}),U]});const Q=n!=="all"||p!=="all"||e!==""||v!=="",ee=()=>{t(""),r("all"),h(J=>{const te=new URLSearchParams(J);return te.delete("dataset"),te.delete(pU),te.delete(o2),te},{replace:!0})};return o.jsxs(Ft,{height:"full",children:[o.jsx(Ft.TopArea,{children:o.jsx(H2s,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:p,onDatasetFilterChange:m,datasetOptions:V,targetType:v,onTargetTypeChange:b,targetId:y,onTargetIdChange:x,onReset:ee,hasActiveFilters:Q,onRunClick:()=>i(!0),onCompareClick:()=>l(!0),selection:a?{selectedCount:G.length,onExecuteCompare:D,onCancelSelection:z,compareDisabledReason:R}:void 0})}),o.jsx(F2s,{experiments:M,datasets:L,reviewByExperiment:q,isLoading:H,search:e,statusFilter:n,datasetFilter:p,isFetchingNextPage:N,hasNextPage:I,setEndOfListElement:A,selection:a?{selectedExperimentIds:G,onToggleSelection:W}:void 0}),U]})}function CB({experimentId:e}){const{Link:t,paths:n}=un();return o.jsx(ae,{render:o.jsx(t,{href:n.experimentLink(e)}),size:"sm","aria-label":`Open experiment ${e}`,children:e.slice(0,8)})}function ODs(){const[e,t]=bi(),n=e.get("dataset")??"",r=e.get("baseline")??"",s=e.get("contender")??"",i=X3(n,r),a=X3(n,s),l=i.isLoading||a.isLoading,c=i.error??a.error;return c&&ks(c)?o.jsx(oi,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Gs,{})})}):c&&Es(c)?o.jsx(oi,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{resource:"experiments"})})}):!n||!r||!s?o.jsx(oi,{children:o.jsx(i0,{children:o.jsxs("div",{className:"text-neutral4 py-5 text-center",children:[o.jsx("p",{children:"Select two experiments to compare."}),o.jsxs("p",{className:"text-ui-md mt-2",children:["Use the URL format: /experiments/compare?dataset=","{datasetId}","&baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})}):l?null:c&&!CR(c)?o.jsx(oi,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ws,{title:"Failed to load experiments",message:c.message})})}):c||!i.data||!a.data?o.jsx(oi,{children:o.jsx(i0,{children:o.jsxs("div",{className:"text-neutral4 py-5 text-center",children:[o.jsxs("p",{children:["Experiments must belong to the same dataset (",n,") to be compared."]}),o.jsxs("p",{className:"text-ui-md mt-2 flex items-center justify-center gap-2",children:["One of",o.jsx(CB,{experimentId:r}),"and",o.jsx(CB,{experimentId:s}),"was not found in it."]})]})})}):o.jsx(oi,{children:o.jsx(i0,{children:o.jsxs("div",{className:"grid w-full content-start",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4 px-4 py-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[o.jsx(Te,{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(CB,{experimentId:r}),"and",o.jsx(CB,{experimentId:s})]})]}),o.jsxs(In,{children:[o.jsx(On,{asChild:!0,children:o.jsx(ae,{onClick:()=>t({dataset:n,baseline:s,contender:r}),icon:o.jsx(NSt,{}),children:"Swap sides"})}),o.jsx(Cn,{children:"Switch baseline and contender"})]})]}),o.jsx(J2s,{datasetId:n,experimentIdA:r,experimentIdB:s})]})})})}function xrn(e,t){const{data:n}=bv(e);return g.useMemo(()=>[...new Set([...n?.tags??[],...t.flatMap(r=>r.tags??[])])].sort(),[n?.tags,t])}function CDs(){const{currentItemId:e,experimentId:t,datasetId:n,experimentStatus:r,results:s,isLoadingResults:i,hasNextPage:a,close:l,goToPreviousItem:c,goToNextItem:u}=trn(),d=g.useMemo(()=>e?s.find(w=>w.itemId===e):void 0,[s,e]),{data:f}=M1(t,r),{updateExperimentResult:h}=pl(),p=g.useCallback(async w=>{try{await h.mutateAsync({datasetId:n,experimentId:t,resultId:w,status:"needs-review"}),Ge("Result flagged for review")}catch{Ge.error("Failed to flag result for review")}},[n,t,h]),m=xrn(n,s),v=g.useCallback(async(w,k)=>{try{await h.mutateAsync({datasetId:n,experimentId:t,resultId:w,tags:k})}catch{Ge.error("Failed to update tags")}},[n,t,h]),y=g.useCallback(async w=>{try{await h.mutateAsync({datasetId:n,experimentId:t,resultId:w,status:"complete"}),Ge("Result marked as reviewed")}catch{Ge.error("Failed to complete result")}},[n,t,h]),b=d?f?.[d.itemId]:void 0,x=vrn(b,d?.id);return o.jsx(yrn,{result:d,itemId:e,fallback:i||a?o.jsx($t.LoadingData,{}):o.jsxs($t.NoData,{children:['No loaded result for item "',e,'".']}),scores:b,state:x,onPrevious:c,onNext:u,onClose:l,onComplete:d?()=>y(d.id):void 0,onFlagForReview:d?()=>{p(d.id)}:void 0,onTagsChange:d?w=>{v(d.id,w)}:void 0,tagVocabulary:m,isUpdatingTags:h.isPending})}function _Ds({selection:e}){const{selectedIds:t,selectedResults:n,tagVocabulary:r,isFlagging:s,isTagging:i}=e;if(t.size===0)return null;const a=s||i;return o.jsxs(Ms,{className:"whitespace-nowrap",children:[o.jsxs(ae,{variant:"outline",disabled:a,onClick:e.flagSelectedForReview,icon:o.jsx(F_,{}),children:["Flag ",t.size," to review"]}),o.jsx(grn,{selectedResults:n,vocabulary:r,onAddTag:e.addTagToSelected,disabled:a}),o.jsx(ae,{icon:o.jsx(Yt,{}),variant:"ghost",onClick:e.clearSelection,children:"Clear"})]})}function wrn(e){const{data:t}=M1(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 Uue({icon:e,typeLabel:t,subject:n,description:r,isLast:s=!1}){return o.jsxs("li",{className:"relative grid grid-cols-[auto_1fr] gap-x-2.5 pb-4 last:pb-0",children:[o.jsxs("div",{className:"flex flex-col items-center",children:[o.jsxs(In,{children:[o.jsx(On,{render:o.jsx("span",{className:"text-neutral3 flex size-5 shrink-0 items-center justify-center [&_svg]:size-3.5",role:"img","aria-label":t}),children:e}),o.jsx(Cn,{children:t})]}),!s&&o.jsx("span",{"aria-hidden":!0,className:"bg-border1 mt-1 w-px flex-1"})]}),o.jsxs("div",{className:"grid min-w-0 gap-0.5",children:[o.jsx("div",{className:"text-ui-sm text-neutral5 flex min-h-5 items-center",children:n}),o.jsx("p",{className:"text-ui-xs text-neutral2",children:r})]})]})}const Vue="text-neutral5 inline-flex min-w-0 items-center gap-1.5 hover:underline";function EDs({experiment:e,className:t}){const{Link:n,paths:r}=un(),s=arn(),{scorers:i}=s,{data:a,isLoading:l}=bv(e.datasetId??""),c=wrn(e),u=e.targetType,d=e.targetId,f=urn(e,s),h=(()=>{if(!d)return null;switch(u){case"agent":return r.agentLink(d);case"workflow":return r.workflowLink(d);case"scorer":return r.scorerLink(d);default:return null}})(),p=u&&lrn[u]||Ma,m=u&&crn[u]||"Evaluation target";return o.jsxs("ol",{className:K("grid",t),children:[o.jsx(Uue,{icon:o.jsx(gJ,{}),typeLabel:"Dataset",description:`Each item will be passed to the ${m.toLowerCase()}`,subject:e.datasetId?o.jsxs(n,{href:r.datasetLink(e.datasetId),className:Vue,children:[o.jsx("span",{className:"truncate",children:l?o.jsx(ut,{className:"h-4 w-28"}):a?.name??e.datasetId}),e.datasetVersion!=null&&o.jsxs("span",{className:"text-neutral3 shrink-0",children:["(v",e.datasetVersion,")"]})]}):o.jsx("span",{className:"text-neutral3",children:"No dataset"})}),o.jsx(Uue,{icon:o.jsx(p,{}),typeLabel:m,description:"Its output is then scored",subject:h?o.jsx(n,{href:h,className:Vue,children:o.jsx("span",{className:"truncate",children:f})}):o.jsx("span",{className:"text-neutral3 truncate",children:f})}),o.jsx(Uue,{icon:o.jsx(dw,{}),typeLabel:"Scorers",description:"It gives a score by comparing ground truth",isLast:!0,subject:c.length===0?o.jsx("span",{className:"text-neutral3",children:"No scorer has produced a score yet"}):o.jsx("ul",{className:"grid min-w-0 gap-0.5",children:c.map(v=>{const y=i?.[v]?.scorer?.config?.name??v;return o.jsx("li",{className:"min-w-0",children:o.jsx(n,{href:r.scorerLink(v),className:Vue,children:o.jsx("span",{className:"truncate",children:y})})},v)})})})]})}function ej({label:e,children:t}){return o.jsxs(o.Fragment,{children:[o.jsx(fn.Key,{children:e}),o.jsx(fn.Value,{className:"flex flex-wrap items-baseline justify-end gap-x-1.5 text-right",children:t})]})}function Kct(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 TDs({experiment:e,metrics:t}){const{data:n}=M1(e.id,e.status),r=e.status==="running"||e.status==="pending",s=g.useMemo(()=>{if(!n)return;const c=Object.values(n).flat();if(c.length!==0)return c.reduce((u,d)=>u+d.score,0)/c.length},[n]),i=e.startedAt??e.createdAt,a=i?new Date(i):null,l=(()=>{if(e.status==="running")return"Running…";if(!e.startedAt||!e.completedAt)return"—";const c=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return c<0?"—":Kct(c)})();return o.jsxs(fn,{children:[o.jsx(ej,{label:"Avg score",children:s===void 0?o.jsx("span",{className:"text-neutral3",children:"—"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{children:s.toFixed(3)}),r&&o.jsx("span",{className:"text-neutral3",children:"· so far"})]})}),o.jsx(ej,{label:"Items",children:r?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(ej,{label:"Started",children:a?o.jsx("span",{title:yZn(a,{addSuffix:!0}),children:gr(a,"MMM d, h:mm a")}):o.jsx("span",{children:"—"})}),o.jsx(ej,{label:"Duration",children:o.jsx("span",{children:l})}),t?.isEnabled&&o.jsxs(o.Fragment,{children:[o.jsx(ej,{label:"Tokens",children:t.data?.totalTokens==null?o.jsx("span",{className:"text-neutral3",children:"—"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{children:lo(t.data.totalTokens)}),t.data.estimatedCost!=null&&o.jsxs("span",{className:"text-neutral3",children:["· ",Zd(t.data.estimatedCost,t.data.costUnit)]}),r&&o.jsx("span",{className:"text-neutral3",children:"· so far"})]})}),o.jsx(ej,{label:"Latency (avg)",children:t.data?.avgAgentDurationMs==null?o.jsx("span",{className:"text-neutral3",children:"—"}):o.jsx("span",{children:Kct(Math.round(t.data.avgAgentDurationMs))})})]})]})}function jDs({scoresByItemId:e,experimentStatus:t}){const{Link:n,paths:r}=un(),{data:s}=Ep(),i=g.useMemo(()=>{if(!e)return[];const a={};for(const l of Object.values(e))for(const c of l)a[c.scorerId]||(a[c.scorerId]={sum:0,count:0}),a[c.scorerId].sum+=c.score,a[c.scorerId].count++;return Object.entries(a).map(([l,{sum:c,count:u}])=>({scorerId:l,avg:c/u})).sort((l,c)=>l.scorerId.localeCompare(c.scorerId))},[e]);if(i.length===0){const a=t==="running"||t==="pending",l=e!==void 0;let c,u;return a?(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(gb,{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 flex-col gap-2",children:i.map(({scorerId:a,avg:l})=>{const c=s?.[a]?.scorer?.config?.name??a;return o.jsxs(Mr,{className:"min-w-0 p-3",children:[o.jsxs(n,{href:r.scorerLink(a),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(In,{children:[o.jsx(On,{render:o.jsx(dw,{role:"img","aria-label":"Scorer"})}),o.jsx(Cn,{children:"Scorer"})]}),o.jsx("span",{className:"truncate",children:c})]}),o.jsxs("strong",{className:"text-ui-md 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"})]})]},a)})})}function que({title:e,children:t}){return o.jsxs("section",{className:"grid gap-3",children:[o.jsx("h2",{className:"text-ui-md text-neutral2 tracking-widest uppercase",children:e}),t]})}function NDs({experiment:e,metrics:t,className:n}){const{Link:r,paths:s}=un(),{data:i}=M1(e.id,e.status),a=e.agentVersion&&e.targetType==="agent"&&e.targetId?`${s.agentLink(e.targetId)}/editor?version=${encodeURIComponent(e.agentVersion)}`:null;return o.jsxs(Jf,{as:"aside","aria-label":"Experiment details",className:K("grid content-start gap-5 p-5",n),children:[o.jsxs(que,{title:"Pipeline",children:[o.jsx(EDs,{experiment:e}),e.agentVersion&&o.jsxs(fn,{children:[o.jsx(fn.Key,{children:"Version"}),a?o.jsx(fn.ValueLink,{href:a,as:r,children:e.agentVersion}):o.jsx(fn.Value,{children:e.agentVersion})]})]}),o.jsx(que,{title:"Run",children:o.jsx(TDs,{experiment:e,metrics:t})}),o.jsx(que,{title:"Scorers",children:o.jsx(jDs,{scoresByItemId:i,experimentStatus:e.status})})]})}function IDs({experiment:e,open:t,onOpenChange:n}){const[r,s]=g.useState(e.name??""),[i,a]=g.useState(e.description??""),{updateExperiment:l}=pl(),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:i.trim()}),Ge.success("Experiment renamed"),n(!1)}catch(f){Ge.error(`Failed to rename experiment: ${f instanceof Error?f.message:"Unknown error"}`)}};return o.jsx(hs,{open:t,onOpenChange:n,children:o.jsxs(Jr,{className:"max-w-md",children:[o.jsx(es,{children:o.jsx(Kr,{children:"Rename Experiment"})}),o.jsx(vs,{children:o.jsxs("form",{onSubmit:u,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Vt,{htmlFor:"rename-experiment-name",children:"Name *"}),o.jsx($n,{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(Vt,{htmlFor:"rename-experiment-description",children:"Description"}),o.jsx($n,{id:"rename-experiment-description",value:i,onChange:d=>a(d.target.value),placeholder:"Enter experiment description (optional)"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ae,{icon:o.jsx(Yt,{}),type:"button",onClick:()=>n(!1),disabled:l.isPending,children:"Cancel"}),o.jsx(ae,{icon:o.jsx(Mn,{}),type:"submit",variant:"primary",disabled:!c,children:l.isPending?"Saving...":"Save"})]})]})})]})})}const ADs=["agent","workflow","scorer"];function RDs({experiment:e}){const[t,n]=g.useState(!1),r=Fr(),{paths:s}=un(),i=wrn(e),a=ADs.find(l=>l===e.targetType);return!e.datasetId||!a||!e.targetId?null:o.jsxs(o.Fragment,{children:[o.jsx(ae,{variant:"primary",onClick:()=>n(!0),tooltip:"Run this experiment again with the same configuration",icon:o.jsx(bu,{}),children:"Rerun"}),t&&o.jsx(yJ,{open:!0,onOpenChange:n,initialDatasetId:e.datasetId,initialDatasetVersion:e.datasetVersion??void 0,initialTargetType:a,initialTargetId:e.targetId,initialScorerIds:i,initialName:e.name??void 0,initialDescription:e.description??void 0,onSuccess:l=>{r(s.experimentLink(l))}},i.join(","))]})}function PDs({experiment:e,onDeleteClick:t,children:n}){const{Link:r}=un(),[s,i]=g.useState(!1),a=!!e.datasetId,l=a||!!t;return o.jsxs(Ft.TopArea,{children:[o.jsxs(Ft.Row,{className:"items-center justify-start gap-2",children:[o.jsxs(Ms,{className:"whitespace-nowrap",children:[o.jsx(RDs,{experiment:e}),o.jsx(ae,{render:o.jsx(r,{href:q8t(e.id)}),icon:o.jsx(F_,{}),children:"Review queue"}),l&&o.jsxs(xt,{children:[o.jsx(xt.Trigger,{asChild:!0,children:o.jsx(ae,{size:"lg","aria-label":"Experiment actions menu",children:o.jsx(F1,{})})}),o.jsxs(xt.Content,{align:"start",className:"w-48",children:[a&&o.jsxs(xt.Item,{onSelect:()=>i(!0),children:[o.jsx(Gd,{})," Rename Experiment"]}),t&&o.jsxs(xt.Item,{onSelect:t,className:"text-red-500 focus:text-red-400",children:[o.jsx(co,{})," Delete Experiment"]})]})]})]}),n]}),s&&o.jsx(IDs,{experiment:e,open:!0,onOpenChange:i})]})}const $Ds=({experimentId:e,experimentStatus:t})=>{const n=Ye(),{supportsMetrics:r}=rF(),s=!!e&&r,a=yt({queryKey:["experiment-metrics",e],enabled:s,refetchInterval:t==="running"||t==="pending"?2e3:!1,queryFn:async()=>{if(!e)throw new Error("experimentId is required");const l={experimentId:e},[c,u,d]=await Promise.all([n.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:l}),n.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"avg",filters:l}),n.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:l})]);return{totalTokens:c.value??null,estimatedCost:c.estimatedCost??null,costUnit:c.costUnit??null,avgAgentDurationMs:u.value??null,agentRuns:d.value??null}}});return{data:a.data,isLoading:a.isLoading,isEnabled:s}};function MDs({datasetId:e,experimentId:t}){const[n,r]=g.useState(!1),{updateExperimentResult:s}=pl();return{addTag:g.useCallback(async(a,l)=>{const c=l.filter(d=>!(d.tags??[]).includes(a));if(n||c.length===0)return;r(!0);let u=0;try{u=(await Promise.allSettled(c.map(f=>s.mutateAsync({datasetId:e,experimentId:t,resultId:f.id,tags:[...f.tags??[],a]})))).filter(f=>f.status==="fulfilled").length}finally{r(!1)}u>0?Ge(`Tag "${a}" added to ${u} result${u>1?"s":""}`):Ge.error("Failed to add tag")},[e,t,n,s]),isPending:n}}function DDs({datasetId:e,experimentId:t,results:n}){const[r,s]=g.useState(new Set),[i,a]=g.useState(!1),{updateExperimentResult:l}=pl(),{addTag:c,isPending:u}=MDs({datasetId:e,experimentId:t}),d=xrn(e,n),f=g.useMemo(()=>n.filter(y=>r.has(y.id)),[n,r]),h=g.useCallback(y=>{s(b=>{const x=new Set(b);return x.has(y)?x.delete(y):x.add(y),x})},[]),p=g.useCallback(()=>s(new Set),[]),m=g.useCallback(async()=>{if(i||r.size===0)return;a(!0);const y=new Set;try{for(const b of r)try{await l.mutateAsync({datasetId:e,experimentId:t,resultId:b,status:"needs-review"}),y.add(b)}catch{}}finally{a(!1)}y.size>0&&(s(b=>{const x=new Set(b);for(const w of y)x.delete(w);return x}),Ge(`${y.size} result${y.size>1?"s":""} flagged for review`))},[e,t,i,r,l]),v=g.useCallback(y=>c(y,f),[c,f]);return{selectedIds:r,selectedResults:f,toggleSelect:h,clearSelection:p,flagSelectedForReview:m,isFlagging:i,addTagToSelected:v,isTagging:u,tagVocabulary:d}}const LDs=[];function _B({children:e}){return o.jsxs(Ft,{height:"full",children:[o.jsx("div",{}),o.jsx(Ft.MainArea,{isCentered:!0,children:e})]})}function FDs(){const{experimentId:e}=ur(),t=Fr(),[n,r]=g.useState(!1),{data:s,isLoading:i}=KG(),l=s?.experiments?.find(w=>w.id===e)?.datasetId??"",{data:c,isLoading:u,error:d}=X3(l,e??""),{data:f,isLoading:h,setEndOfListElement:p,isFetchingNextPage:m,hasNextPage:v}=Nke({datasetId:l,experimentId:e??"",experimentStatus:c?.status}),y=$Ds({experimentId:e,experimentStatus:c?.status}),b=DDs({datasetId:l,experimentId:e??"",results:f??LDs});if(!e||i||u)return null;if(d&&ks(d))return o.jsx(_B,{children:o.jsx(Gs,{})});if(d&&Es(d))return o.jsx(_B,{children:o.jsx(Fs,{resource:"datasets"})});const x=o.jsx(_B,{children:o.jsx(Ar,{iconSlot:o.jsx(DSt,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:o.jsx(ae,{render:o.jsx(oo,{to:"/experiments"}),icon:o.jsx(id,{}),children:"Back to Experiments"})})});return d&&CR(d)?x:d?o.jsx(_B,{children:o.jsx(Ws,{title:"Failed to load experiment",message:d instanceof Error?d.message:"An unexpected error occurred. Please try again."})}):!l||!c?x:o.jsx(NMs,{experimentId:e,datasetId:l,experimentStatus:c.status,results:f??[],isLoadingResults:h,hasNextPage:v,children:o.jsxs("div",{className:"h-full",children:[o.jsxs(Ft,{height:"full",children:[o.jsx(PDs,{experiment:c,onDeleteClick:()=>r(!0),children:o.jsx(_Ds,{selection:b})}),o.jsxs(Ft.MainArea,{className:"grid grid-cols-[1fr_auto] gap-4 overflow-visible",children:[o.jsx(MMs,{experimentId:e,experimentStatus:c.status,results:f??[],isLoading:h,setEndOfListElement:p,isFetchingNextPage:m,hasNextPage:v,selectedIds:b.selectedIds,onToggleSelect:b.toggleSelect}),o.jsx(NDs,{experiment:c,metrics:y,className:"w-80 overflow-y-auto"})]})]}),o.jsx(CDs,{}),o.jsx(srn,{open:n,onOpenChange:r,experimentId:e,experimentName:c.name??void 0,onSuccess:()=>t("/experiments")})]})})}const aLe=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"})}),IZ="all",Yct=60,zDs=e=>e.length>Yct?`${e.slice(0,Yct)}…`:e;function BDs({value:e,onValueChange:t,className:n,variant:r,allOption:s,targetType:i,targetId:a}){const{data:l,isLoading:c,isError:u}=iLe(void 0,{targetType:i,targetId:a}),d=(l?.experiments??[]).map(h=>({label:irn(h),value:h.id,start:o.jsx(aLe,{className:"text-neutral3 size-4 shrink-0","data-testid":"experiments-icon"}),description:h.description?zDs(h.description):ub(h.id)??h.id})),f=s?[{label:"All experiments",value:IZ},...d]:d;return o.jsx(qo,{options:f,value:e??(s?IZ:""),onValueChange:t,placeholder:c?"Loading experiments...":u?"Failed to load experiments":"Select experiment",searchPlaceholder:"Search experiments...",emptyText:"No experiments found.",className:n,disabled:c||u,variant:r})}function UDs(){const[e,t]=bi(),n=e.get("experiment"),r=e.get("review"),{targetType:s,targetId:i,setTargetType:a,setTargetId:l}=sLe({resetParams:["experiment","review"]}),{Link:c,paths:u}=un(),{data:d,error:f}=iLe(void 0,{targetType:s,targetId:i}),h=d?.experiments.find(m=>m.id===n),p=m=>{t(v=>{const y=new URLSearchParams(v);return m===IZ?y.delete("experiment"):y.set("experiment",m),y.delete("review"),y},{replace:!0})};return f&&ks(f)?o.jsx(Qn,{children:o.jsx(Gs,{})}):f&&Es(f)?o.jsx(Qn,{children:o.jsx(Fs,{resource:"experiments"})}):f?o.jsx(Qn,{children:o.jsx(Ws,{title:"Failed to load experiments",message:f.message})}):o.jsx(Ft,{height:"full",children:o.jsx(mDs,{datasetId:h?.datasetId??void 0,experimentId:n??void 0,targetType:s,targetId:i,featuredItemId:r,toolbarStart:o.jsxs(o.Fragment,{children:[o.jsx(eLe,{targetType:s,targetId:i,onTargetTypeChange:a,onTargetIdChange:l}),o.jsx(BDs,{allOption:!0,value:n??void 0,onValueChange:p,targetType:s,targetId:i,className:"w-72"})]}),toolbarEnd:n?o.jsx(ae,{render:o.jsx(c,{href:u.experimentLink(n)}),icon:o.jsx(ISt,{}),children:"See experiment"}):void 0},`${s}:${i}:${n??IZ}`)})}const Srn=[{name:"itemId",label:"Item ID",size:"auto"},{name:"status",label:"Status",size:"auto"},{name:"input",label:"Input",size:"minmax(0,1fr)"},{name:"tags",label:"Tags",size:"auto"}],VDs=Srn.map(e=>e.size).join(" ");function qDs({items:e,isLoading:t,error:n}){const r=Fr(),[s,i]=g.useState(""),a=s.trim().toLowerCase(),l=a?e.filter(c=>[c.itemId,c.experimentId,c.datasetId,c.traceId??""].some(u=>u.toLowerCase().includes(a))):e;return t?o.jsx(Wl,{columns:VDs}):n?o.jsx(Ws,{title:"Failed to load dataset items",message:n.message}):e.length===0?o.jsx(Ar,{iconSlot:o.jsx(Ls,{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(Wc,{onSearch:i,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.jsx(nLe,{results:l,isLoading:!1,featuredResultId:null,onResultClick:c=>{const u=l.find(d=>d.id===c);u&&r(q8t(u.experimentId,u.id))},columns:Srn,emptyMessage:"No dataset items match your search"})})]})}function HDs(){return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ar,{iconSlot:o.jsx(Ls,{}),titleSlot:"Your inbox is empty",descriptionSlot:o.jsxs(o.Fragment,{children:["Feedback left on traces and experiment results flagged for review ",o.jsx("br",{}),"will show up here until you mark them reviewed."]}),actionSlot:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ae,{icon:o.jsx(aLe,{}),render:o.jsx(oo,{to:"/experiments"}),variant:"outline",children:"Go to experiments"}),o.jsx(ae,{icon:o.jsx(fE,{}),render:o.jsx(oo,{to:"/traces"}),variant:"outline",children:"Go to traces"})]})})})}function $ke(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 Xct="minmax(0, 2fr) minmax(0, 1fr) auto minmax(0, 1fr) auto auto",WDs=e=>e.stopPropagation();function ZDs({items:e,isLoading:t,error:n,hasNextPage:r,isFetchingNextPage:s,fetchNextPage:i,onMarkReviewed:a,pendingFeedbackId:l,onSelect:c,selectedFeedbackId:u}){const[d,f]=g.useState(""),h=d.trim().toLowerCase(),p=h?e.filter(x=>$ke(x).toLowerCase().includes(h)||(EZ(x)??"").toLowerCase().includes(h)||(x.traceId??"").toLowerCase().includes(h)||(x.feedbackSource??"").toLowerCase().includes(h)):e,{containerRef:m,getRowProps:v}=Zc({count:p.length,global:!0}),{inView:y,setRef:b}=Sb({root:m});return g.useEffect(()=>{y&&r&&!s&&i()},[y,r,s,i]),t?o.jsx(Wl,{columns:Xct}):n?o.jsx(Ws,{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(Wc,{onSearch:f,label:"Filter feedback",placeholder:"Filter loaded feedback by text, author, trace or source"})}),o.jsx("div",{className:"min-h-0 overflow-hidden",children:o.jsxs(we,{columns:Xct,fit:"container",scrollRef:m,children:[o.jsxs(we.Top,{children:[o.jsx(we.TopCell,{children:"Feedback"}),o.jsx(we.TopCell,{children:"Author"}),o.jsx(we.TopCell,{children:"Source"}),o.jsx(we.TopCell,{children:"Trace"}),o.jsx(we.TopCell,{children:"Date"}),o.jsx(we.TopCell,{children:" "})]}),p.length===0?o.jsx(we.NoMatch,{message:h?"No feedback matches your search":"No feedback needs review"}):p.map((x,w)=>{const k=x.feedbackId,_=EZ(x);return o.jsxs(we.RowWrapper,{...v(w),onSelectRow:x.traceId?()=>c(x):void 0,children:[o.jsxs(we.RowButton,{colEnd:-2,disabled:!x.traceId,featured:k!==void 0&&k===u,tabIndex:-1,onClick:C=>{C.stopPropagation(),c(x)},children:[o.jsx(we.TextCell,{className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:$ke(x)})}),o.jsx(we.Cell,{className:"flex gap-2",children:_&&o.jsxs(o.Fragment,{children:[o.jsx(cb,{name:_,src:x.author?.avatarUrl,size:"sm"}),o.jsx("span",{className:"truncate",children:_})]})}),o.jsx(we.Cell,{children:o.jsx(jt,{size:"sm",children:x.feedbackSource})}),o.jsx(we.TextCell,{font:"mono",className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:x.traceId??"—"})}),o.jsx(we.TextCell,{children:gr(x.timestamp,"MMM d, h:mm a")})]}),o.jsx(we.ActionsCell,{className:"pl-2",onClick:WDs,children:k?o.jsx(ae,{icon:o.jsx(F_,{}),variant:"ghost",size:"sm",onClick:()=>a(k),disabled:l===k,children:"Mark reviewed"}):null})]},k??`${String(x.timestamp)}-${x.traceId}`)}),o.jsx(we.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:b})]})})]})}function GDs({feedback:e,traceId:t,initialSpanId:n,onClose:r,onPrevious:s,onNext:i,onMarkReviewed:a,isMarkingReviewed:l}){const[c,u]=g.useState(n),[d,f]=g.useState(e?.feedbackId);e?.feedbackId!==d&&(f(e?.feedbackId),u(n));const{spans:h,isLoading:p}=Htn({traceId:t,anchorSpanId:null,listMode:"traces"});return o.jsx(XDe,{title:`Review feedback for trace ${t??""}`,size:c?"full":"wide",headerSlot:e&&o.jsx(QDs,{feedback:e,onMarkReviewed:a,isMarkingReviewed:l}),traceId:e?t:void 0,spans:h,isLoadingSpans:p,selectedSpanId:c??null,initialSpanId:n,onSpanSelect:u,onClose:r,onPrevious:s,onNext:i,traceHref:t?`/traces?traceId=${encodeURIComponent(t)}`:void 0,feedbackTabSlot:({traceId:m})=>o.jsx(Y3,{traceId:m}),spanFeedbackTabSlot:({traceId:m,spanId:v})=>m&&v?o.jsx(ZDe,{traceId:m,spanId:v},`${m}:${v}`):null})}function QDs({feedback:e,onMarkReviewed:t,isMarkingReviewed:n}){const r=EZ(e)??e.feedbackUserId;return o.jsxs("section",{"aria-label":"Feedback",className:"border-border1 flex max-h-[33vh] shrink-0 flex-col border-b",children:[o.jsxs($t.Header,{children:[o.jsxs($t.HeaderContent,{children:[o.jsxs($t.Heading,{children:["Feedback",o.jsx(jt,{variant:"neutral",emphasis:"muted",children:e.feedbackType}),e.feedbackSource&&o.jsx(jt,{variant:"neutral",emphasis:"muted",children:e.feedbackSource})]}),o.jsxs($t.Metadata,{children:[r&&o.jsx($t.Meta,{icon:o.jsx(cb,{name:r,src:e.author?.avatarUrl,size:"sm"}),tooltip:"Author",children:r}),o.jsx($t.Meta,{icon:o.jsx(M0,{}),tooltip:`Submitted at ${gr(new Date(e.timestamp),"MMM dd, yyyy HH:mm:ss")}`,children:gr(new Date(e.timestamp),"MMM dd, yyyy HH:mm")})]})]}),o.jsx($t.HeaderActions,{children:o.jsx(ae,{variant:"primary",size:"sm",onClick:t,disabled:n,icon:o.jsx(Mn,{}),children:"Mark as reviewed"})})]}),o.jsx("div",{className:"min-h-0 overflow-y-auto p-3",children:o.jsx(Te,{as:"p",variant:"ui-md",className:"text-neutral5 whitespace-pre-wrap",children:$ke(e)})})]})}const krn=100;async function KDs(e){const t=[];let n=0,r=!0;for(;r;){const s=await e.listExperiments({page:n,perPage:krn});t.push(...s.experiments),r=s.pagination.hasMore,n+=1}return t}async function YDs(e,t,n){const r=[];let s=0,i=!0;for(;i;){const a=await e.listDatasetExperimentResults(t,n,{page:s,perPage:krn});r.push(...a.results),i=a.pagination.hasMore,s+=1}return r}function XDs(){const e=Ye();return yt({queryKey:["inbox-dataset-review-items"],queryFn:async()=>{const t=await KDs(e);return(await Promise.all(t.map(async r=>{const s=r.datasetId;return s?(await YDs(e,s,r.id)).filter(a=>a.status==="needs-review").map(a=>({id:a.id,datasetId:s,experimentId:r.id,itemId:a.itemId,traceId:a.traceId??void 0,input:a.input,output:a.output,error:a.error,status:a.status,tags:a.tags})):[]}))).flat()},refetchInterval:3e3,refetchOnWindowFocus:!1})}function JDs({enabled:e}){const t=Ye();return yt({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 eLs(e){return e==="dataset"||e==="feedback"}function tLs(){const[e,t]=bi(),n=e.get("tab"),r=eLs(n)?n:"feedback",s=FAs({reviewStatus:"needs-review"}),i=WDe(),a=XDs(),l=a.data??[],c=s.total??0,u=!s.isLoading&&!a.isLoading&&!s.error&&!a.error&&s.items.length===0&&l.length===0,d=e.get("feedbackId")??void 0,f=e.get("traceId")??void 0,h=e.get("spanId")??void 0,p=T=>{t(E=>{const N=new URLSearchParams(E);for(const I of["feedbackId","traceId","spanId"]){const A=T[I];A?N.set(I,A):N.delete(I)}return N},{replace:!0})},m=()=>p({}),v=T=>p({feedbackId:T.feedbackId??void 0,traceId:T.traceId??void 0,spanId:T.spanId??void 0}),y=s.items.findIndex(T=>T.feedbackId===d),b=y>=0?s.items[y]:void 0,x=y>0?s.items[y-1]:void 0,w=y>=0&&y<s.items.length-1?s.items[y+1]:void 0,k=!!f&&!!d&&!!b,_=T=>{i.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.jsx(Ft,{height:"full",className:"grid-rows-[minmax(0,1fr)]",children:o.jsx(Ft.MainArea,{className:"min-h-0 overflow-hidden",children:u?o.jsx(HDs,{}):o.jsxs(hl,{defaultTab:"feedback",value:r,onValueChange:C,className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[o.jsxs(fl,{variant:"pill-ghost",children:[o.jsxs(Sr,{value:"feedback",children:[o.jsx(St,{size:"sm",children:o.jsx(jA,{})}),o.jsx(Te,{variant:"ui-sm",className:"text-inherit",children:"Feedback"}),c>0&&o.jsx(jt,{variant:"yellow",size:"sm",children:c})]}),o.jsxs(Sr,{value:"dataset",children:[o.jsx(St,{size:"sm",children:o.jsx(F_,{})}),o.jsx(Te,{variant:"ui-sm",className:"text-inherit",children:"Dataset items"}),l.length>0&&o.jsx(jt,{variant:"yellow",size:"sm",children:l.length})]})]}),o.jsx(ts,{value:"feedback",className:"h-full min-h-0 pt-4",children:o.jsx(ZDs,{items:s.items,isLoading:s.isLoading,error:s.error??void 0,hasNextPage:s.hasNextPage,isFetchingNextPage:s.isFetchingNextPage,fetchNextPage:s.fetchNextPage,onMarkReviewed:_,pendingFeedbackId:i.isPending?i.variables?.feedbackId:void 0,onSelect:v,selectedFeedbackId:d})}),o.jsx(ts,{value:"dataset",className:"h-full min-h-0 pt-4",children:o.jsx(qDs,{items:l,isLoading:a.isLoading,error:a.error??void 0})})]})})}),o.jsx(GDs,{feedback:k?b:void 0,traceId:k?f:void 0,initialSpanId:h,onClose:m,onPrevious:x?()=>v(x):void 0,onNext:w?()=>v(w):void 0,onMarkReviewed:()=>d&&_(d),isMarkingReviewed:i.isPending})]})}function nLs({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-ui-sm",children:e.connectionId}),o.jsxs("div",{className:"text-ui-sm 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 Orn({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("ul",{className:"space-y-1",children:e.map(s=>o.jsx(nLs,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function rLs({groups:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("div",{className:"space-y-4",children:e.map(([s,i])=>o.jsxs("div",{children:[o.jsx("h3",{className:"text-ui-md font-semibold text-gray-700","data-testid":`integration-author-group-${s}`,children:s==="shared"?"Shared":`Owned by ${s}`}),o.jsx(Orn,{connections:i,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function sLs({providerId:e,toolkit:t,connections:n,groupedByAuthor:r,isAdmin:s,isLoading:i,error:a,disconnectPending:l,disconnectError:c,onDisconnect:u}){return o.jsxs("div",{className:"space-y-2 border rounded p-4",children:[o.jsx("h2",{className:"text-header-sm font-semibold",children:"Existing connections"}),!e||!t?o.jsx("p",{className:"text-gray-500",children:"Pick a provider and toolkit to list connections."}):i?o.jsx("p",{className:"text-gray-500",children:"Loading…"}):a?o.jsx("p",{className:"text-red-600",children:String(a)}):n.length===0?o.jsx("p",{className:"text-gray-500",children:"No connections."}):r?o.jsx(rLs,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):o.jsx(Orn,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?o.jsx("p",{className:"text-red-600",children:String(c)}):null]})}function iLs({providers:e,toolkits:t,providerId:n,toolkit:r,label:s,providersLoading:i,providersError:a,toolkitsLoading:l,toolkitsError:c,authorizePending:u,authorizeError:d,authorizedConnection:f,onProviderChange:h,onToolkitChange:p,onLabelChange:m,onConnect:v}){return o.jsxs("div",{className:"space-y-4 border rounded p-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"provider-select",children:"Provider"}),o.jsxs("select",{id:"provider-select",className:"border rounded px-2 py-1 w-full",value:n,onChange:y=>h(y.target.value),disabled:i,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))]}),i&&o.jsx("span",{className:"text-gray-500",children:"Loading providers…"}),a?o.jsx("span",{className:"text-red-600",children:String(a)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"toolkit-select",children:"Toolkit"}),o.jsxs("select",{id:"toolkit-select",className:"border rounded px-2 py-1 w-full",value:r,onChange:y=>p(y.target.value),disabled:!n||l,children:[o.jsx("option",{value:"",children:"— select toolkit —"}),t.map(y=>o.jsxs("option",{value:y.slug,children:[y.name," (",y.slug,")"]},y.slug))]}),l&&o.jsx("span",{className:"text-gray-500",children:"Loading toolkits…"}),c?o.jsx("span",{className:"text-red-600",children:String(c)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"label-input",children:"Label (optional)"}),o.jsx("input",{id:"label-input",type:"text",className:"border rounded px-2 py-1 w-full",placeholder:"My personal Gmail",value:s,onChange:y=>m(y.target.value),disabled:!n||!r})]}),o.jsx("button",{type:"button",className:"bg-blue-600 text-white rounded px-4 py-2 disabled:opacity-50",onClick:v,disabled:!n||!r||u,children:u?"Authorizing…":"Connect"}),d?o.jsx("p",{className:"text-red-600",children:String(d)}):null,f&&o.jsxs("p",{className:"text-green-700",children:["Authorized: ",f.connectionId," (status: ",f.status,")"]})]})}const Jct=e=>e.authorId?.trim()||"shared",aLs=(e,t)=>{if(!t||new Set(e.map(Jct)).size<=1)return null;const r=new Map;for(const i of e){const a=Jct(i);r.set(a,[...r.get(a)??[],i])}const s=Array.from(r.entries());return s.sort(([i],[a])=>i==="shared"?1:a==="shared"?-1:i.localeCompare(a)),s},oLs=["*","tool-providers:*","tool-providers:admin"];function lLs(){const{data:e}=Jm();return e?.permissions?.some(t=>oLs.includes(t))??!1}function cLs(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,i]=g.useState(""),a=IR(),l=_Y(e||null),c=lVt(e||null,n||null),u=oVt(),d=sVt(),f=lLs(),h=a.data?.providers??[],p=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),v=g.useMemo(()=>aLs(m,f),[m,f]),y=w=>{t(w),r("")},b=()=>{!e||!n||u.mutate({providerId:e,toolkit:n,label:s.trim()||null},{onSuccess:()=>{i(""),c.refetch()}})},x=w=>{d.mutate({providerId:e,connectionId:w})};return o.jsxs("div",{className:"p-4 max-w-3xl space-y-6 text-ui-md",children:[o.jsx("h1",{className:"text-header-md 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(iLs,{providers:h,toolkits:p,providerId:e,toolkit:n,label:s,providersLoading:a.isLoading,providersError:a.error,toolkitsLoading:l.isLoading,toolkitsError:l.error,authorizePending:u.isPending,authorizeError:u.error,authorizedConnection:u.data,onProviderChange:y,onToolkitChange:r,onLabelChange:i,onConnect:b}),o.jsx(sLs,{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 uLs({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(Om,{className:"h-10 w-10"}),o.jsx("h1",{className:"text-neutral6 text-header-md font-semibold",children:e})]}),t,n,r]})})}function Crn({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:i}=hc(),{mutate:a,isPending:l,error:c}=ZQr(),{mutate:u,isPending:d,error:f}=QQr(),{mutate:h,isPending:p}=_Bt(),[m,v]=g.useState(n),[y,b]=g.useState(""),[x,w]=g.useState(""),[k,_]=g.useState("");if(i)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,P=A?l:d,L=A?c:f,M=()=>{t?t():e?window.location.href=e:window.location.href=NY("/")},V=z=>{z.preventDefault(),A?a({email:x,password:k},{onSuccess:M}):u({email:x,password:k,name:y||void 0},{onSuccess:M})},q=()=>{h({redirectUri:e},{onSuccess:z=>{window.location.href=z.url}})},H=()=>{v(A?"signup":"signin")},B=C.description?o.jsxs("div",{className:"border-border1 bg-surface1 flex items-start gap-2.5 rounded-md border p-3",children:[o.jsx(td,{className:"text-neutral4 mt-0.5 h-4 w-4 shrink-0"}),o.jsx("p",{className:"text-neutral3 text-ui-md",children:C.description})]}):null,W=r?o.jsx("div",{className:"text-ui-md rounded-md bg-red-500/10 p-3 text-red-400",children:r}):null;return o.jsxs(uLs,{title:A?"Sign in to Mastra Studio":"Create your account",description:B,errorBanner:W,children:[E&&o.jsxs("form",{onSubmit:V,className:"space-y-4",children:[!A&&o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"name",className:"text-neutral4 text-ui-md block",children:"Name"}),o.jsx($n,{id:"name",type:"text",value:y,onChange:z=>b(z.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 text-ui-md block",children:"Email"}),o.jsx($n,{id:"email",type:"email",value:x,onChange:z=>w(z.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 text-ui-md block",children:"Password"}),o.jsx($n,{id:"password",type:"password",value:k,onChange:z=>_(z.target.value),placeholder:A?"Enter your password":"Create a password",required:!0,variant:"default",size:"lg"})]}),L&&o.jsx("div",{className:"text-ui-md rounded-md bg-red-500/10 p-3 text-red-400",children:L.message}),o.jsx(ae,{icon:o.jsx(vV,{}),type:"submit",disabled:P,className:"w-full",size:"lg",children:P?A?"Signing in...":"Creating account...":A?"Sign in":"Create account"}),I&&o.jsxs("div",{className:"text-ui-md text-center",children:[o.jsx("span",{className:"text-neutral3",children:A?"Don't have an account? ":"Already have an account? "}),o.jsx("button",{type:"button",onClick:H,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:"text-ui-md relative flex justify-center",children:o.jsx("span",{className:"bg-surface1 text-neutral3 px-2",children:"or continue with"})})]}),T&&N&&o.jsxs(ae,{onClick:q,disabled:p,className:"w-full",size:"lg",variant:"outline",children:[N.icon&&o.jsx("span",{className:"mr-2",children:N.icon}),p?"Redirecting...":N.text||"Sign in"]})]})}function dLs(){const[e]=bi(),t=Fr(),n=e.get("redirect")||"/",s=e.get("mode")==="signup"?"signup":"signin",i=e.get("error_description")||e.get("error")||null,a=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(Crn,{redirectUri:n,onSuccess:a,initialMode:s,errorMessage:i})}function _rn({disabled:e,onClear:t,onRemoveAll:n,onSave:r,onRemoveSaved:s}){const i=!!(n||r||s);return!t&&!i?null:o.jsxs("div",{className:"flex items-center gap-2",children:[t&&o.jsx(ae,{disabled:e,size:"md",onClick:t,icon:o.jsx(Yt,{}),children:"Clear"}),i&&o.jsxs(xt,{children:[o.jsx(xt.Trigger,{asChild:!0,children:o.jsx(ae,{disabled:e,size:"md","aria-label":"More filter actions",children:o.jsx(F1,{})})}),o.jsxs(xt.Content,{align:"end",children:[n&&o.jsxs(xt.Item,{onSelect:()=>n(),children:[o.jsx(Yt,{}),"Remove all filters"]}),n&&(r||s)&&o.jsx(xt.Separator,{}),r&&o.jsxs(xt.Item,{onSelect:()=>r(),children:[o.jsx(Uf,{}),"Save filters for next time"]}),s&&o.jsxs(xt.Item,{onSelect:()=>s(),children:[o.jsx(co,{}),"Remove saved filters"]})]})]})]})}const fLs=K(V0,"min-w-0 focus:bg-neutral6/5 focus:text-neutral6");function Hue({role:e,checked:t,label:n,onClick:r}){return o.jsxs("button",{type:"button",role:e,"aria-checked":t,"data-selected":t||void 0,"data-pick-multi-item":"",title:n,className:fLs,onClick:r,children:[o.jsx("span",{className:"min-w-0 flex-1 truncate",children:n}),t&&o.jsx("span",{className:q4,children:o.jsx(Mn,{})})]})}function Ern({field:e,tokens:t,onChange:n}){const[r,s]=g.useState(""),i=g.useMemo(()=>{const u=r.trim().toLowerCase();return u?e.options.filter(d=>d.label.toLowerCase().includes(u)):e.options},[e.options,r]),a=g.useMemo(()=>t.find(u=>u.fieldId===e.id),[t,e.id]),l=typeof a?.value=="string"?a.value:e.multi?void 0:e.defaultValue,c=g.useMemo(()=>{const u=a?.value;return Array.isArray(u)?u:typeof u=="string"?[u]:[]},[a]);return o.jsxs(o.Fragment,{children:[e.searchable!==!1&&o.jsxs("div",{className:cN.container,children:[o.jsx(Oi,{className:cN.icon}),o.jsx("input",{type:"text",value:r,onChange:u=>s(u.target.value),placeholder:`Search ${e.label.toLowerCase()}...`,className:cN.input,onKeyDown:u=>{if(u.key!=="ArrowDown")return;const f=u.currentTarget.closest("[data-pick-multi-panel]")?.querySelector("[data-pick-multi-item]:not([disabled])");f&&(u.preventDefault(),u.stopPropagation(),f.focus())}})]}),e.isLoading?o.jsxs("div",{className:K($V,"m-1"),children:[o.jsx(_n,{size:"sm",className:"text-neutral3 size-3"}),"Loading options…"]}):i.length===0?o.jsx("div",{className:K($V,"m-1"),children:e.emptyText??"No option found."}):e.multi?o.jsx("div",{className:"max-h-[80dvh] overflow-auto p-1",children:i.map(u=>{const d=c.includes(u.value);return o.jsx(Hue,{role:"checkbox",checked:d,label:u.label,onClick:()=>n(e.id,d?c.filter(f=>f!==u.value):[...c,u.value])},u.value)})}):o.jsxs("div",{role:"radiogroup",className:"max-h-[80dvh] overflow-auto p-1",children:[i.map(u=>o.jsx(Hue,{role:"radio",checked:l===u.value,label:u.label,onClick:()=>n(e.id,u.value)},u.value)),!e.omitAnyOption&&o.jsx(Hue,{role:"radio",checked:l==="Any",label:"Any",onClick:()=>n(e.id,"Any")})]})]})}function oLe(e){return Array.isArray(e)?e.length===0?"Any":e.join(", "):e}const hLs="This filter is set by the current context and cannot be removed here.";function pLs(e,t){return e.kind==="pick-multi"&&e.options?Array.isArray(t)?t.length===0?"Any":t.map(n=>e.options.find(r=>r.value===n)?.label??n).join(", "):e.options.find(n=>n.value===t)?.label??t:oLe(t)}function mLs({field:e,value:t,tooltipContent:n}){const r=pLs(e,t),s=`${e.label} filter is locked by context`;return o.jsx(fc,{delayDuration:150,children:o.jsxs(In,{children:[o.jsx(On,{asChild:!0,children:o.jsxs(Ms,{spacing:"close","data-locked-field-id":e.id,"data-property-filter-pill":"locked",tabIndex:0,"aria-label":s,children:[o.jsx(Xh,{size:"md",children:e.label}),o.jsx(Xh,{size:"md",children:"is"}),o.jsx(Xh,{size:"md",children:r}),o.jsx(Xh,{size:"md",children:o.jsx(td,{})})]})}),o.jsx(Cn,{children:n})]})})}function gLs({field:e,value:t,onChange:n,onRemove:r,disabled:s,autoFocus:i}){const[a,l]=g.useState(t),c=g.useRef(null);return g.useEffect(()=>{a.trim()!==t&&l(t)},[t]),g.useEffect(()=>{i&&c.current?.focus()},[i]),o.jsxs(Ms,{spacing:"close",children:[o.jsx(Xh,{size:"md",children:e.label}),o.jsx(Xh,{size:"md",children:"is"}),o.jsx($n,{ref:c,size:"md",disabled:s,value:a,placeholder:e.placeholder??`Enter ${e.label}`,onChange:u=>{const d=u.target.value;l(d),d.trim()!==t&&n(d)},onKeyDown:u=>{if(u.key==="Enter"){u.preventDefault();const d=a.trim();d!==t&&n(d)}else u.key==="Escape"&&(u.preventDefault(),l(t),u.target.blur())}}),o.jsx(ae,{type:"button",disabled:s,"aria-label":`Remove ${e.label} filter`,size:"md",onMouseDown:u=>u.preventDefault(),onClick:r,children:o.jsx(Yt,{})})]})}function vLs({field:e,token:t,tokens:n,onChange:r,onRemove:s,disabled:i}){const[a,l]=g.useState(!1);return o.jsxs(Ms,{spacing:"close",children:[o.jsx(Xh,{size:"md",children:e.label}),o.jsx(Xh,{size:"md",children:"is"}),o.jsxs(Zm,{open:a,onOpenChange:l,children:[o.jsx(Xf,{asChild:!0,children:o.jsx(ae,{type:"button",disabled:i,size:"md",children:oLe(t.value)})}),o.jsx(vp,{align:"start",sideOffset:sE,className:"w-64 p-0","data-pick-multi-panel":!0,children:o.jsx(Ern,{field:e,tokens:n,onChange:r})})]}),o.jsx(ae,{type:"button",disabled:i,"aria-label":`Remove ${e.label} filter`,size:"md",onClick:s,children:o.jsx(Yt,{})})]})}function Trn({fields:e,tokens:t,onTokensChange:n,disabled:r,autoFocusFieldId:s,lockedFieldIds:i,lockedTooltipContent:a=hLs}){if(t.length===0)return null;const l=new Set(i??[]),c=(d,f)=>{const h=[...t];h[d]=f,n(h)},u=d=>{n(t.filter((f,h)=>h!==d))};return o.jsx("div",{className:"flex flex-wrap items-center gap-2",children:t.map((d,f)=>{const h=e.find(p=>p.id===d.fieldId);return h?l.has(d.fieldId)?o.jsx(mLs,{field:h,value:d.value,tooltipContent:a},`${d.fieldId}-${f}`):h.kind==="text"&&typeof d.value=="string"?o.jsx(gLs,{field:h,value:d.value,disabled:r,autoFocus:s===d.fieldId,onChange:p=>c(f,{fieldId:d.fieldId,value:p}),onRemove:()=>u(f)},`${d.fieldId}-${f}`):h.kind==="pick-multi"?o.jsx(vLs,{field:h,token:d,tokens:t,disabled:r,onChange:(p,m)=>c(f,{fieldId:p,value:m}),onRemove:()=>u(f)},`${d.fieldId}-${f}`):o.jsxs(Ms,{spacing:"close",children:[o.jsx(Xh,{size:"md",children:h.label}),o.jsx(Xh,{size:"md",children:"is"}),o.jsx(Xh,{size:"md",children:oLe(d.value)}),o.jsx(ae,{type:"button",disabled:r,size:"md","aria-label":`Remove ${h.label} filter`,onClick:()=>u(f),children:o.jsx(Yt,{})})]},`${d.fieldId}-${f}`):null})})}const jrn="focus:bg-neutral6/5 focus:text-neutral6";function Nrn({fields:e,tokens:t,onTokensChange:n,label:r="Add Filter",disabled:s,size:i,onStartTextFilter:a,hiddenFieldIds:l}){const c=g.useMemo(()=>{if(!l||l.length===0)return e;const A=new Set(l);return e.filter(P=>!A.has(P.id))},[e,l]),[u,d]=g.useState(!1),[f,h]=g.useState(),[p,m]=g.useState([]),[v,y]=g.useState(),[b,x]=g.useState(),w=g.useRef(!1),k=g.useCallback(A=>{x(P=>P===A?void 0:A)},[]),_=g.useCallback(()=>x(void 0),[]);g.useEffect(()=>{u||x(void 0)},[u]);const C=g.useMemo(()=>c.find(A=>A.id===f),[c,f]),T=g.useMemo(()=>{const A=new Set;for(const P of t){const L=e.find(M=>M.id===P.fieldId);L&&L.kind!=="pick-multi"&&A.add(P.fieldId)}return A},[t,e]),E=g.useCallback(()=>{h(void 0),m([]),y(void 0)},[]);g.useEffect(()=>{u||E()},[u,E]);const N=g.useCallback((A,P)=>{const L=t.findIndex(V=>V.fieldId===A);if(Array.isArray(P)&&P.length===0){if(L===-1)return;n(t.filter((V,q)=>q!==L));return}if(L===-1){n([...t,{fieldId:A,value:P}]);return}const M=[...t];M[L]={fieldId:A,value:P},n(M)},[n,t]),I=g.useCallback(()=>{if(!C){y("Choose a property first.");return}if(T.has(C.id)){y(`Remove the existing ${C.label} filter before adding another.`);return}if(p.length===0){y(`Choose at least one ${C.label.toLowerCase()} value.`);return}n([...t,{fieldId:C.id,value:p}]),d(!1)},[p,n,C,T,t]);return o.jsxs(Zm,{open:u,onOpenChange:d,children:[o.jsx(Xf,{asChild:!0,children:o.jsx(ae,{variant:"outline",size:i,disabled:s,icon:o.jsx(Z8e,{}),children:r})}),o.jsx(vp,{align:"end",sideOffset:sE,className:K("w-64",C?"p-3":"p-1"),initialFocus:!1,finalFocus:()=>w.current?(w.current=!1,!1):!0,children:o.jsxs("div",{className:K("grid",C&&"gap-3"),children:[C&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("button",{type:"button","aria-label":"Back to properties",className:"text-neutral3 hover:text-neutral6 transition-colors",onClick:E,children:o.jsx(id,{className:"size-4"})}),o.jsx(AAn,{className:"text-neutral3 size-4 shrink-0"}),o.jsx("span",{className:"text-ui-sm text-neutral3",children:`${C.label} · is`})]}),!C&&o.jsx("div",{role:"menu",className:"max-h-[80dvh] overflow-auto",onKeyDown:A=>{if(A.key!=="ArrowDown"&&A.key!=="ArrowUp"&&A.key!=="Home"&&A.key!=="End")return;const P=Array.from(A.currentTarget.querySelectorAll("[data-filter-item]:not([disabled])"));if(P.length===0)return;A.preventDefault();const L=document.activeElement,M=P.findIndex(q=>q===L);let V;A.key==="Home"?V=0:A.key==="End"?V=P.length-1:A.key==="ArrowDown"?V=M<0?0:(M+1)%P.length:V=M<=0?P.length-1:M-1,P[V]?.focus()},children:c.length>0?c.map(A=>{const P=T.has(A.id);return A.kind==="pick-multi"?o.jsx(yLs,{field:A,tokens:t,onChange:N,open:b===A.id,onToggle:k,onClose:_},A.id):o.jsxs("button",{type:"button",role:"menuitem","data-filter-item":"",className:K(V0,"group",jrn),disabled:P,onClick:()=>{if(y(void 0),A.kind==="text"){n([...t,{fieldId:A.id,value:""}]),a?.(A.id),w.current=!0,d(!1);return}h(A.id)},children:[o.jsx("span",{className:"truncate",children:A.label}),P?o.jsx("span",{className:"text-neutral3 ml-auto",children:"In use"}):o.jsx("span",{className:K(BG,"text-neutral3 opacity-0 transition-opacity group-hover:opacity-100 group-focus:opacity-100"),children:o.jsx(Yr,{})})]},A.id)}):o.jsx("div",{className:$V,children:"No matching property."})}),C&&o.jsx(qo,{multiple:!0,options:C.options??[],value:p,onValueChange:A=>{m(A),y(void 0)},placeholder:C.placeholder??`Choose ${C.label}`,searchPlaceholder:`Search ${C.label.toLowerCase()}...`,emptyText:C.emptyText??"No option found.",size:"md"}),v&&o.jsx("div",{className:"text-ui-sm text-red-500",children:v}),C&&o.jsxs("div",{className:"flex items-center justify-end gap-2",children:[o.jsx(ae,{icon:o.jsx(Yt,{}),variant:"ghost",size:"md",onClick:()=>d(!1),children:"Cancel"}),o.jsx(ae,{icon:o.jsx(Z8e,{}),variant:"outline",size:"md",onClick:I,children:"Add filter"})]})]})})]})}function yLs({field:e,tokens:t,onChange:n,open:r,onToggle:s,onClose:i}){const a=g.useRef(null);return o.jsxs(Zm,{open:r,onOpenChange:l=>{l?s(e.id):i()},children:[o.jsx(Xf,{asChild:!0,children:o.jsxs("button",{type:"button",role:"menuitem","data-filter-item":"",className:K(V0,jrn),onKeyDown:l=>{l.key!=="ArrowRight"&&l.key!=="ArrowLeft"||(r||s(e.id),l.preventDefault(),requestAnimationFrame(()=>{a.current?.querySelector('input, button, [tabindex]:not([tabindex="-1"])')?.focus()}))},children:[r&&o.jsx(mr,{className:"text-neutral3"}),o.jsx("span",{className:"truncate",children:e.label}),!r&&o.jsx("span",{className:K(BG,"text-neutral3"),children:o.jsx(mr,{})})]})}),o.jsx(vp,{ref:a,side:"right",align:"start",sideOffset:sE,className:"w-64 p-0",initialFocus:!1,onKeyDown:l=>{if(l.key!=="ArrowDown"&&l.key!=="ArrowUp"&&l.key!=="Home"&&l.key!=="End")return;const c=Array.from(l.currentTarget.querySelectorAll("[data-pick-multi-item]:not([disabled])"));if(c.length===0)return;l.preventDefault(),l.stopPropagation();const u=document.activeElement,d=c.findIndex(h=>h===u);let f;l.key==="Home"?f=0:l.key==="End"?f=c.length-1:l.key==="ArrowDown"?f=d<0?0:(d+1)%c.length:f=d<=0?c.length-1:d-1,c[f]?.focus()},"data-pick-multi-panel":!0,children:o.jsx(Ern,{field:e,tokens:t,onChange:n})})]})}const _h=Ca.KeyValueList;function bLs(e){return e instanceof Date?e:new Date(e)}function xLs({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:i,collapsed:a,onCollapsedChange:l}){const[c,u]=g.useState(!1),d=a??c,f=l??u,h=bLs(e.timestamp),p=e.traceId,m=e.spanId;return o.jsxs(Ca,{collapsed:d,children:[o.jsxs(Ca.Header,{children:[o.jsxs(Ca.Heading,{children:["Log ",o.jsx("b",{children:gr(h,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(Ms,{className:"ml-auto shrink-0",children:[l&&o.jsx(ae,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(bCe,{}):o.jsx($St,{})}),o.jsxs(Ms,{spacing:"close",children:[o.jsx(ae,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(mb,{})}),o.jsx(ae,{size:"md",tooltip:"Next log",onClick:i,disabled:!i,children:o.jsx(f4,{})})]}),o.jsx(Ca.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(Ca.Content,{children:[o.jsx("p",{className:"text-ui-md text-neutral4 font-mono wrap-break-word whitespace-pre-wrap",children:e.message}),(p||m)&&o.jsxs("div",{className:K("my-8 grid gap-2","[&>button]:justify-between [&>button]:overflow-hidden"),children:[p&&o.jsxs(Ms,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(ae,{size:"md",className:"min-w-0 flex-1 overflow-hidden",icon:o.jsx(Kf,{}),onClick:()=>n?.(p),children:[o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",p]})]}),o.jsx(ci,{content:p,size:"md",tooltip:"Copy Trace ID to clipboard"})]}),m&&o.jsxs(Ms,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(ae,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!p||!r,onClick:()=>p&&r?.(p,m),icon:o.jsx(Kf,{}),children:[o.jsx("span",{children:"Span"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",m]})]}),o.jsx(ci,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(_h,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(_h.Key,{children:"Entity Type"}),o.jsx(_h.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(_h.Key,{children:"Entity Name"}),o.jsx(_h.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(_h.Key,{children:"Service"}),o.jsx(_h.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(_h.Key,{children:"Environment"}),o.jsx(_h.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(_h.Key,{children:"Source"}),o.jsx(_h.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(_h.Key,{children:v}),o.jsx(_h.Value,{children:String(y)})]},v))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(Ca.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function wLs({error:e,resource:t,errorTitle:n}){if(ks(e))return o.jsx(Gs,{});if(Es(e))return o.jsx(Fs,{resource:t});if(t6(e))return o.jsx(Ar,{iconSlot:o.jsx(Ls,{}),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(e6(e,"logs"))return o.jsx(Ar,{iconSlot:o.jsx(Ls,{}),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(Ws,{title:n,message:r??"Unknown error"})}function SLs({listSlot:e,logPanelSlot:t,tracePanelSlot:n,spanPanelSlot:r,logCollapsed:s}){const i=!!t;return o.jsxs("div",{className:K("grid h-full min-h-0 items-start gap-4",i?"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[e,i&&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 kLs={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 OLs({level:e}){const t=kLs[e];return o.jsx(mo,{children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function CLs({entityType:e,className:t}){const n=K("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case"agent":return o.jsx(Ma,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return o.jsx(Bc,{className:n,"aria-hidden":!0});case"tool":return o.jsx(eh,{className:n,"aria-hidden":!0});default:return null}}function _Ls({entityType:e,entityName:t}){const n=e??"";return o.jsxs(mo,{className:"flex min-w-0 items-center gap-2",children:[o.jsx(CLs,{entityType:n}),t?o.jsx("span",{className:"text-ui-smd min-w-0 truncate",children:t}):"-"]})}function ELs({message:e}){return o.jsx(mo,{className:"text-ui-smd text-neutral4 min-w-0 truncate font-mono",children:e})}function TLs({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(mo,{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(bRe,{font:"mono",children:t})}const Yl=Object.assign(Y5,{Top:X5,TopCell:ew,TopCellWithTooltip:uY,TopCellSmart:t9t,RowWrapper:kRe,RowButton:J5,RowLink:SRe,Spacer:ORe,NoMatch:fY,DateCell:Jzt,TimeCell:e9t,LevelCell:OLs,EntityCell:_Ls,MessageCell:ELs,DataCell:TLs,NextPageLoading:dY}),eut="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",jLs=36,NLs=8;function ILs({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:i,featuredLogId:a,onLogClick:l}){const c=g.useRef(null),u=Ftn({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>jLs,overscan:NLs}),{getRowProps:d}=Zc({count:e.length,containerRef:c,onNavigate:y=>u.scrollToIndex(y),global:!0}),f=g.useRef(t);if(g.useEffect(()=>{f.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),f.current=t},[t]),t)return o.jsx(Wl,{columns:eut});const h=u.getVirtualItems(),p=u.getTotalSize(),m=h[0]?.start??0,v=h.length>0?Math.max(0,p-(h[h.length-1]?.end??0)):0;return o.jsxs(Yl,{columns:eut,scrollRef:c,className:"min-w-0",children:[o.jsxs(Yl.Top,{children:[o.jsx(Yl.TopCell,{children:"Date"}),o.jsx(Yl.TopCell,{children:"Time"}),o.jsx(Yl.TopCell,{children:"Level"}),o.jsx(Yl.TopCell,{children:"Entity"}),o.jsx(Yl.TopCell,{children:"Message"}),o.jsx(Yl.TopCell,{children:"Data"})]}),e.length===0?o.jsx(Yl.NoMatch,{message:"No logs match your search"}):o.jsxs(o.Fragment,{children:[o.jsx(Yl.Spacer,{height:m}),h.map(y=>{const b=e[y.index];if(!b)return null;const x=i.get(b);if(!x)return null;const w=x===a;return o.jsxs(Yl.RowButton,{ref:u.measureElement,"data-index":y.index,...d(y.index),onClick:()=>l(b),featured:w,variant:b.level==="error"||b.level==="fatal"?"error":"default",children:[o.jsx(Yl.DateCell,{timestamp:b.timestamp}),o.jsx(Yl.TimeCell,{timestamp:b.timestamp}),o.jsx(Yl.LevelCell,{level:b.level}),o.jsx(Yl.EntityCell,{entityType:b.entityType,entityName:b.entityName}),o.jsx(Yl.MessageCell,{message:b.message}),o.jsx(Yl.DataCell,{data:b.data})]},x)}),o.jsx(Yl.Spacer,{height:v})]}),o.jsx(Yl.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function ALs({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:i,filterTokens:a,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=a.length>0,d=a.some(f=>RLs(f,i));return u?o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(Trn,{fields:i,tokens:a,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(_rn,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function RLs(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 PLs={"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"},Wue="MMM d, yyyy HH:mm",Zue="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function $Ls({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${PLs[e]}`,description:Zue}:t&&n?{title:`No logs between ${gr(t,Wue)} and ${gr(n,Wue)}`,description:Zue}:t?{title:`No logs since ${gr(t,Wue)}`,description:Zue}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const MLs=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=$Ls({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ar,{iconSlot:o.jsx(Ls,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsx(ae,{variant:"ghost",render:o.jsx("a",{href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer"}),icon:o.jsx(_s,{}),children:"Logging Documentation"})})})},DLs=20,LLs=1e4;function FLs(e,t,n){if(e?.pagination?.hasMore)return n+1}function zLs(e){const t=new Set,n=[];for(const r of e.pages)for(const s of r.logs??[]){const i=s.logId??JSON.stringify(s);t.has(i)||(t.add(i),n.push(s))}return n}function BLs(e){return e6(e.state.error,"logs")||t6(e.state.error)?!1:LLs}const ULs=({filters:e}={})=>{const t=Ye(),{inView:n,setRef:r}=Sb(),s=yv({queryKey:["logs",e],queryFn:({pageParam:h})=>t.listLogsVNext({pagination:{page:h,perPage:DLs},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:FLs,select:zLs,retry:!1,refetchInterval:BLs}),{hasNextPage:i,isFetchingNextPage:a,fetchNextPage:l,data:c,isLoading:u,isError:d,error:f}=s;return g.useEffect(()=>{n&&i&&!a&&l()},[n,i,a,l]),{data:c,hasNextPage:i,isFetchingNextPage:a,fetchNextPage:l,isLoading:u,isError:d,error:f,setEndOfListElement:r}},EB={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},Irn=[{label:"Agent",entityType:EB.AGENT},{label:"Workflow",entityType:EB.WORKFLOW},{label:"Scorer",entityType:EB.SCORER},{label:"Ingest",entityType:EB.INGEST}],VLs=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],P0="rootEntityType",Px="datePreset",$x="dateFrom",Mx="dateTo",qLs=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),Pl={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"},oF=Object.keys(Pl),lLe=new Set(["tags"]),cLe="mastra:logs:saved-filters";function HLs(e,t=cLe){const n=KLs(e),r=e.get(Px);r&&n.set(Px,r);const s=e.get($x);s&&n.set($x,s);const i=e.get(Mx);i&&n.set(Mx,i);try{localStorage.setItem(t,n.toString())}catch{}}function WLs(e=cLe){try{localStorage.removeItem(e)}catch{}}function tut(e=cLe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function ZLs(e){if(e.has(Px)||e.has($x)||e.has(Mx)||e.has(P0))return!0;for(const t of oF)if(e.has(Pl[t]))return!0;return!1}function GLs({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const i=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:Irn.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:VLs.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"}],a=(u,d)=>u.label.localeCompare(d.label),l=i.filter(u=>u.kind==="pick-multi").sort(a),c=i.filter(u=>u.kind==="text").sort(a);return[...l,...c]}function QLs(e){const t=[],n=new Map([[P0,"rootEntityType"]]);for(const s of oF)n.set(Pl[s],s);const r=new Set;for(const[s]of e.entries()){const i=n.get(s);if(!i||r.has(i))continue;if(r.add(i),lLe.has(i)){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:i,value:l.filter(Boolean)});continue}const a=e.get(s);a!==null&&t.push({fieldId:i,value:a})}return t}function KLs(e){const t=new URLSearchParams,n=e.get(P0);n&&t.set(P0,n);for(const r of oF){const s=Pl[r];if(lLe.has(r)){for(const a of e.getAll(s))t.append(s,a);continue}const i=e.get(s);i&&t.set(s,i)}return t}function YLs(e,t){e.delete(P0);for(const n of oF)e.delete(Pl[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(P0,n.value);continue}const r=Pl[n.fieldId];if(r){if(lLe.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 XLs({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 i of r){if(i.fieldId==="tags"){Array.isArray(i.value)&&i.value.length>0?s.tags=i.value:typeof i.value=="string"&&i.value.trim()&&(s.tags=[i.value.trim()]);continue}if(i.fieldId==="level"){typeof i.value=="string"&&i.value.trim()&&i.value!=="Any"&&(s.level=i.value);continue}if(typeof i.value=="string"&&i.value.trim()&&i.value!=="Any")switch(i.fieldId){case"entityName":s.rootEntityName=i.value;break;case"traceId":s.traceId=i.value;break;case"spanId":s.spanId=i.value;break;case"runId":s.runId=i.value;break;case"threadId":s.threadId=i.value;break;case"sessionId":s.sessionId=i.value;break;case"requestId":s.requestId=i.value;break;case"resourceId":s.resourceId=i.value;break;case"userId":s.userId=i.value;break;case"organizationId":s.organizationId=i.value;break;case"serviceName":s.serviceName=i.value;break;case"environment":s.environment=i.value;break;case"experimentId":s.experimentId=i.value;break}}return s}function JLs(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 e3s="Filters setting for Logs saved",t3s="Filters setting for Logs cleared up";function n3s(e,t,n){const{storageKey:r,messages:s,skipHydration:i}={},[a,l]=g.useState(()=>tut(r)!==null),c=g.useCallback(()=>{HLs(e,r),l(!0);const f=s?.saved??e3s;f!==!1&&Ge.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{WLs(r),l(!1);const f=s?.cleared??t3s;f!==!1&&Ge.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(i||d.current||(d.current=!0,ZLs(e)))return;const f=tut(r);f&&t(h=>{const p=new URLSearchParams(h);for(const[m,v]of f)p.append(m,v);return p},{replace:!0})},[]),{hasSavedFilters:a,handleSave:c,handleRemoveSaved:u}}function r3s(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 s3s(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,r3s(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function i3s(e,t,n,r){const s=g.useMemo(()=>s3s(e),[e]),i=g.useMemo(()=>{const p=new Map;for(const[m,v]of e.entries()){const y=s.get(v);y&&p.set(y,{log:v,idx:m})}return p},[e,s]),l=(t?i.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=g.useCallback(p=>s.get(p),[s]),d=g.useCallback(p=>{const m=s.get(p);if(m){if(t===m){n({logId:null});return}n(r?{logId:m,traceId:p.traceId??null,spanId:null}:{logId:m})}},[s,t,r,n]),f=l>0?()=>{const p=e[l-1];if(!p)return;const m=s.get(p);m&&n(r?{logId:m,traceId:p.traceId??null,spanId:null}:{logId:m})}:void 0,h=l>=0&&l<e.length-1?()=>{const p=e[l+1];if(!p)return;const m=s.get(p);m&&n(r?{logId:m,traceId:p.traceId??null,spanId:null}:{logId:m})}:void 0;return{logIdMap:s,getLogId:u,featuredLog:c,handleLogClick:d,handlePreviousLog:f,handleNextLog:h}}const Mke="logId",Dke="traceId",Lke="spanId",pM=1440*60*1e3,a3s={"last-24h":pM,"last-3d":3*pM,"last-7d":7*pM,"last-14d":14*pM,"last-30d":30*pM};function TB(e){e.delete(Mke),e.delete(Dke),e.delete(Lke)}function o3s(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const _=e.get(Px);return _&&qLs.has(_)?_:"last-24h"},[e]),i=e.get($x),a=e.get(Mx),l=g.useMemo(()=>{if(s==="custom"){if(!i)return;const C=new Date(i);return Number.isNaN(C.getTime())?void 0:C}if(s==="all")return;const _=a3s[s];return _?new Date(Date.now()-_):void 0},[s,i]),c=g.useMemo(()=>{if(s!=="custom"||!a)return;const _=new Date(a);return Number.isNaN(_.getTime())?void 0:_},[s,a]),u=g.useRef(s);u.current=s;const d=e.get(Mke),f=e.get(Dke),h=e.get(Lke),p=g.useMemo(()=>Irn.find(_=>_.entityType===e.get(P0)),[e]),m=g.useMemo(()=>QLs(e),[e]),v=g.useCallback(_=>{t(C=>{const T=new URLSearchParams(C);for(const[E,N]of Object.entries(_)){const I=E==="logId"?Mke:E==="traceId"?Dke:Lke;N?T.set(I,N):T.delete(I)}return T},{replace:!0})},[t]),y=g.useCallback(_=>{t(C=>{const T=new URLSearchParams(C);return YLs(T,_),TB(T),T},{replace:!0})},[t]),b=y,x=g.useCallback((_,C)=>{if(u.current!=="custom")return;const T=C==="from"?$x:Mx;t(E=>{const N=new URLSearchParams(E);return _?N.set(T,_.toISOString()):N.delete(T),TB(N),N},{replace:!0})},[t]),w=g.useCallback(_=>{u.current=_,t(C=>{const T=new URLSearchParams(C);return _==="last-24h"?(T.delete(Px),T.delete($x),T.delete(Mx)):_==="custom"?T.set(Px,"custom"):(T.set(Px,_),T.delete($x),T.delete(Mx)),TB(T),T},{replace:!0})},[t]),k=g.useCallback(()=>{t(_=>{const C=new URLSearchParams(_);C.delete(P0);for(const T of oF)C.delete(Pl[T]);return C.delete(Px),C.delete($x),C.delete(Mx),TB(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:h,selectedEntityOption:p,filterTokens:m,handleFeaturedChange:v,handleFilterTokensChange:b,handleDateChange:x,handleDatePresetChange:w,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,h,p,m,v,b,x,w,k,y])}const Gue=Ca.KeyValueList;function l3s({spanId:e,span:t,isLoading:n,onClose:r}){return o.jsxs(Ca,{children:[o.jsxs(Ca.Header,{children:[o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[o.jsxs(Ca.Heading,{className:"items-center",children:["Span",o.jsx(hJ,{id:e})]}),t&&o.jsx(mnn,{span:t})]}),o.jsx(Ca.CloseButton,{onClick:r})]}),n?o.jsx(Ca.LoadingData,{children:"Loading span..."}):t?o.jsxs(Ca.Content,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsxs(Gue,{children:[o.jsx(Gue.Key,{children:"Type"}),o.jsx(Gue.Value,{children:t.spanType})]}),o.jsx("br",{})]}),o.jsx(Sy,{title:"Error",raw:t.error,layout:"details",className:"mb-3",children:o.jsx(pnn,{span:t})}),o.jsx(Sy,{title:"Input",icon:o.jsx(eI,{}),raw:t.input,hasPreview:TDe(t)?.type!=="json",layout:"details",children:o.jsx(fnn,{span:t})}),o.jsx(Sy,{title:"Output",icon:o.jsx(Gx,{}),raw:t.output,hasPreview:jDe(t)?.type!=="json",layout:"details",children:o.jsx(hnn,{span:t})}),o.jsx(Sy,{title:"Metadata",icon:o.jsx(Bl,{}),raw:t.metadata,hasPreview:!1,layout:"details",children:null}),o.jsx(Sy,{title:"Attributes",icon:o.jsx(Bl,{}),raw:t.attributes,hasPreview:!1,layout:"details",children:null})]}):o.jsx(Ca.NoData,{children:"Span not found."})]})}function c3s({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:i}){const a=g.useMemo(()=>iF(t??[]),[t]),[l,c]=g.useState([]);g.useEffect(()=>{a.length>0&&c(pJ(a))},[a]);const u=d=>{s?.(i===d?void 0:d)};return o.jsxs(Ca,{children:[o.jsxs(Ca.Header,{children:[o.jsxs(Ca.Heading,{className:"items-center",children:["Trace",o.jsx(hJ,{id:e})]}),o.jsx(Ca.CloseButton,{onClick:r})]}),n?o.jsx(Ca.LoadingData,{children:"Loading trace..."}):a.length===0?o.jsx(Ca.NoData,{children:"No spans found for this trace."}):o.jsx(Ca.Content,{children:o.jsx(YDe,{hierarchicalSpans:a,onSpanClick:u,selectedSpanId:i??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}const Arn=()=>{const e=Ye();return yt({queryKey:["observability-service-names"],queryFn:async()=>{try{return await e.getServiceNames()}catch{return{serviceNames:[]}}},select:t=>t?.serviceNames??[],retry:!1,staleTime:nF})},Rrn=()=>{const e=Ye();return yt({queryKey:["observability-tags"],queryFn:async()=>{try{return await e.getTags()}catch{return{tags:[]}}},select:t=>t?.tags??[],retry:!1,staleTime:nF})};function u3s(){const[e,t]=bi(),n=o3s(e,t),r=n3s(e,t),[s,i]=g.useState(),[a,l]=g.useState(!1),{data:c=[],isPending:u}=Rrn(),{data:d=[],isPending:f}=zDe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:h=[],isPending:p}=BDe(),{data:m=[],isPending:v}=Arn(),y=g.useMemo(()=>GLs({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:h,loading:{tags:u,entityNames:f,serviceNames:v,environments:p}}),[c,d,m,h,u,f,v,p]),b=g.useMemo(()=>XLs({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:x=[],isLoading:w,error:k,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:T}=ULs({filters:b}),{logIdMap:E,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:P}=i3s(x,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:L,isLoading:M}=zE(n.featuredTraceId??null),{data:V,isLoading:q}=fJ(n.featuredTraceId??"",n.featuredSpanId??""),H=g.useCallback(()=>n.applyFilterTokens(JLs(y,n.filterTokens)),[y,n]),B=g.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),W=g.useCallback(Q=>n.handleFeaturedChange({traceId:Q,spanId:null}),[n]),z=g.useCallback((Q,ee)=>n.handleFeaturedChange({traceId:Q,spanId:ee}),[n]),G=g.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),F=g.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),R=g.useCallback(Q=>n.handleFeaturedChange({spanId:Q??null}),[n]),D=o.jsxs(Ft.TopArea,{children:[o.jsx(Ft.Row,{children:o.jsxs(Ft.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(n6,{preset:n.datePreset,onPresetChange:n.handleDatePresetChange,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,onDateChange:n.handleDateChange,disabled:w,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),o.jsx(Nrn,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:w,onStartTextFilter:i})]})}),o.jsx(ALs,{isLoading:w,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:H,onRemoveAll:n.handleRemoveAll,onSave:r.handleSave,onRemoveSaved:r.hasSavedFilters?r.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(k)return o.jsxs(Ft,{width:"wide",height:"full",children:[D,o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsx(wLs,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const U=!!n.selectedEntityOption||n.filterTokens.length>0;return x.length===0&&!w&&!U?o.jsxs(Ft,{width:"wide",height:"full",children:[D,o.jsx(Ft.MainArea,{isCentered:!0,children:o.jsx(MLs,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Ft,{width:"wide",height:"full",children:[D,o.jsx(SLs,{logCollapsed:a,listSlot:o.jsx(ILs,{logs:x,isLoading:w,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:T,logIdMap:E,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(xLs,{log:N,onClose:B,onTraceClick:W,onSpanClick:z,onPrevious:A,onNext:P,collapsed:a,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(c3s,{traceId:n.featuredTraceId,spans:L?.spans,isLoading:M,onClose:G,onSpanSelect:R,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(l3s,{spanId:n.featuredSpanId,span:V?.span,isLoading:q,onClose:F}):null})]})}function d3s({server:e,rowProps:t}){const{paths:n,Link:r}=un(),i=Ye().options.baseUrl,a=i?`${i}/api/mcp/${e.id}/sse`:"",{data:l}=lXt(e),c=Object.values(l||{}),u=c.length,d=c.filter(p=>p.toolType==="agent").length,f=c.filter(p=>p.toolType==="workflow").length,h=af(e.name,50);return o.jsxs(we.RowLink,{to:n.mcpServerLink(e.id),LinkComponent:r,...t,children:[o.jsx(we.NameCell,{children:h}),o.jsx(we.DescriptionCell,{children:a}),o.jsx(we.TextCell,{className:"text-center",children:d||""}),o.jsx(we.TextCell,{className:"text-center",children:u||""}),o.jsx(we.TextCell,{className:"text-center",children:f||""})]})}function f3s({mcpServers:e,isLoading:t,search:n=""}){const r=g.useMemo(()=>{const a=n.toLowerCase();return e.filter(l=>l.name?.toLowerCase().includes(a)||l.id?.toLowerCase().includes(a))},[e,n]),{containerRef:s,getRowProps:i}=Zc({count:r.length,global:!0});return t?o.jsx(Wl,{columns:"auto 1fr auto auto auto"}):o.jsxs(we,{columns:"auto 1fr auto auto auto",scrollRef:s,children:[o.jsxs(we.Top,{children:[o.jsx(we.TopCell,{children:"Name"}),o.jsx(we.TopCell,{children:"URL"}),o.jsx(we.TopCellSmart,{long:"Agents",short:o.jsx(Ma,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(we.TopCellSmart,{long:"Tools",short:o.jsx(eh,{}),tooltip:"Tools",className:"text-center"}),o.jsx(we.TopCellSmart,{long:"Workflows",short:o.jsx(Bc,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(we.NoMatch,{message:"No MCP Servers match your search"}):null,r.map((a,l)=>o.jsx(d3s,{server:a,rowProps:i(l)},a.id))]})}const h3s=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ar,{iconSlot:o.jsx(Ls,{}),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.jsx(ae,{variant:"ghost",render:o.jsx("a",{href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer"}),icon:o.jsx(_s,{}),children:"MCP Documentation"})})}),p3s=()=>{const{data:e=[],isLoading:t,error:n}=UR(),[r,s]=g.useState("");return n&&ks(n)?o.jsx(Qn,{children:o.jsx(Gs,{})}):n&&Es(n)?o.jsx(Qn,{children:o.jsx(Fs,{resource:"MCP servers"})}):n?o.jsx(Qn,{children:o.jsx(Ws,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(Qn,{children:o.jsx(h3s,{})}):o.jsxs(Ft,{height:"full",children:[o.jsx(Ft.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx(Wc,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(f3s,{mcpServers:e,isLoading:t,search:r})]})},m3s=(e,t)=>{const n=new Map,r=Object.keys(t);for(const s of r){const i=t[s],a=i.tools,l=Object.keys(a);for(const c of l){const u=a[c];n.has(u.id)||n.set(u.id,{...u,agents:[]}),n.get(u.id).agents.push({...i,id:s})}}for(const[s,i]of Object.entries(e))n.has(i.id)||n.set(i.id,{...i,agents:[]});return Array.from(n.values())};function g3s({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:i}=un(),a=g.useMemo(()=>m3s(e,t),[e,t]),l=g.useMemo(()=>a.filter(d=>d.id.toLowerCase().includes(r.toLowerCase())),[a,r]),{containerRef:c,getRowProps:u}=Zc({count:l.length,global:!0});return n?o.jsx(Wl,{columns:"auto 1fr auto"}):o.jsxs(we,{columns:"auto 1fr auto",scrollRef:c,children:[o.jsxs(we.Top,{children:[o.jsx(we.TopCell,{children:"Name"}),o.jsx(we.TopCell,{children:"Description"}),o.jsx(we.TopCellSmart,{long:"Agents",short:o.jsx(Ma,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(we.NoMatch,{message:"No Tools match your search"}):null,l.map((d,f)=>{const h=af(d.id,50),p=af(d.description??"",200),m=d.agents.length;return o.jsxs(we.RowLink,{to:s.toolLink(d.id),LinkComponent:i,...u(f),children:[o.jsx(we.NameCell,{children:h}),o.jsx(we.DescriptionCell,{children:p}),o.jsx(we.TextCell,{className:"text-center",children:m||""})]},d.id)})]})}const v3s=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ar,{iconSlot:o.jsx(Ls,{}),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.jsx(ae,{variant:"ghost",render:o.jsx("a",{href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer"}),icon:o.jsx(_s,{}),children:"Tools Documentation"})})}),y3s=()=>{const e=Ye();return yn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new P_;Object.entries(r??{}).forEach(([i,a])=>{s.set(i,a)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(i){throw Ge.error("Error executing dev tool"),console.error("Error executing dev tool:",i),i}}})},b3s=({toolId:e})=>{const{canExecute:t}=No(),n=t("tools"),{data:r={}}=rh(),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:i,isLoading:a,error:l}=oQr(e,{enabled:!s}),c=s||i,{mutateAsync:u,isPending:d,data:f}=y3s(),{requestContext:h}=ys();g.useEffect(()=>{if(l){const v=l instanceof Error?l.message:"Failed to load tool";Ge.error(`Error loading tool: ${v}`)}},[l]);const p=async(v,y)=>{if(!c)return;const b={...h??{},...y??{}};return u({toolId:c.id,input:v,requestContext:b})},m=c?.inputSchema?Pm(m0(c?.inputSchema)):Nr({});return a?o.jsxs("div",{className:"p-4",children:[o.jsx(ut,{className:"mb-4 h-8 w-48"}),o.jsx(ut,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(G2e,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:p,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"px-4 py-8 text-center",children:o.jsx(Te,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})}):o.jsx("div",{className:"px-4 py-8 text-center",children:o.jsx(Te,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function x3s({value:e,onValueChange:t,placeholder:n="Select a tool...",searchPlaceholder:r="Search tools...",emptyText:s="No tools found.",className:i,disabled:a=!1,variant:l,size:c,"aria-label":u,align:d}){const{data:f={},isLoading:h,isError:p,error:m}=ER(),{data:v={},isLoading:y,isError:b,error:x}=rh(),{navigate:w,paths:k}=un();g.useEffect(()=>{if(p){const E=m instanceof Error?m.message:"Failed to load tools";Ge.error(`Error loading tools: ${E}`)}},[p,m]),g.useEffect(()=>{if(b){const E=x instanceof Error?x.message:"Failed to load agents";Ge.error(`Error loading agents: ${E}`)}},[b,x]);const _=new Map;Object.values(v).forEach(E=>{E.tools&&Object.values(E.tools).forEach(N=>{_.has(N.id)||_.set(N.id,N)})}),Object.values(f).forEach(E=>{_.has(E.id)||_.set(E.id,E)});const C=Array.from(_.values()).map(E=>({label:E.id,value:E.id})),T=E=>{t?t(E):E&&E!==e&&w(k.toolLink(E))};return o.jsx(qo,{options:C,value:e,onValueChange:T,placeholder:h||y?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:i,disabled:a||h||y||p||b,variant:l,size:c,"aria-label":u,align:d})}const w3s=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=g.useState({sseUrl:"",httpStreamUrl:""});if(g.useEffect(()=>{if(!t)return;const a=window.MASTRA_SERVER_HOST,l=window.MASTRA_SERVER_PORT;let c=null;a&&l&&(c=`http://${a}:${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(i0,{children:o.jsx(Te,{as:"h1",variant:"header-md",className:"text-neutral3 py-20 text-center font-medium",children:"Server not found"})});const i=`npx -y mcp-remote ${n}`;return o.jsxs(i0,{isDivided:!0,children:[o.jsxs("div",{className:"mx-auto w-full max-w-2xl px-5 py-8",children:[o.jsx(Te,{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-4",children:[o.jsx(jt,{icon:o.jsx(ynn,{}),size:"sm",children:"Version"}),o.jsx(jt,{size:"sm",children:t.version_detail.version})]}),o.jsx(Te,{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(jt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"HTTP"}),children:"Regular HTTP Endpoint"}),o.jsx(Te,{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(Te,{className:"bg-surface4 rounded-lg px-2 py-1",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx(ci,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(jt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"SSE"}),children:"Server-Sent Events"}),o.jsx(Te,{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(Te,{className:"bg-surface4 rounded-lg px-2 py-1",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx(ci,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(jt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"CLI"}),children:"Command Line"}),o.jsx(Te,{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(Te,{className:"bg-surface4 rounded-lg px-2 py-1",children:i}),o.jsx("div",{className:"pt-1",children:o.jsx(ci,{tooltip:"Copy Command Line Config",content:i})})]})]})]})]}),o.jsx("div",{className:"border-border1 h-full overflow-y-scroll border-l",children:o.jsx(S3s,{server:t})})]})},S3s=({server:e})=>{const{data:t={},isLoading:n}=lXt(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(St,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(ME,{})}),o.jsx(Te,{variant:"header-md",as:"h2",className:"font-medium",children:"Available Tools"})]}),o.jsx("div",{className:"flex flex-col gap-2 pt-4",children:r.map(s=>{const i=t[s];return o.jsx(O3s,{tool:i,serverId:e.id},s)})})]})};function k3s(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 O3s=({tool:e,serverId:t})=>{const n=g.useRef(null),{Link:r,paths:s}=un(),i=e.toolType==="agent"?iU.agent:e.toolType==="workflow"?iU.workflow:iU.tool,a=k3s(e._meta);return o.jsxs(ih,{onClick:()=>n.current?.click(),children:[o.jsx(aVt,{children:o.jsx(i,{className:"group-hover/entity:text-accent6"})}),o.jsxs(oh,{children:[o.jsx(ah,{children:o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(r,{ref:n,href:s.mcpServerToolLink(t,e.name),children:e.name}),a&&o.jsx(jt,{size:"xs",children:"App"})]})}),o.jsx(kp,{children:e.description})]})]})},C3s=()=>{const{serverId:e}=ur(),{data:t=[],isLoading:n}=UR(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(w3s,{isLoading:n,server:r})})};function _3s(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 E3s=({toolId:e,serverId:t})=>{const{canExecute:n}=No(),r=n("tools"),s=Ye(),{data:i,isLoading:a,error:l}=P2e(t,e),{mutateAsync:c,isPending:u,data:d}=I0s(t,e),f=i?_3s(i._meta):void 0,{data:h}=yt({queryKey:["mcp-app-resource",t,f],queryFn:async()=>f?(await s.readMcpServerResource(t,f)).contents[0]?.text??null:null,enabled:!!f}),p=g.useCallback(async(y,b)=>await c(b),[c]);g.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";Ge.error(`Error loading tool: ${y}`)}},[l]);const m=async y=>{if(i)return await c(y)};if(a)return o.jsxs("div",{className:"p-4",children:[o.jsx(ut,{className:"mb-4 h-8 w-48"}),o.jsx(ut,{className:"h-32 w-full"})]});if(l)return null;if(!i)return o.jsx("div",{className:"px-4 py-8 text-center",children:o.jsx(Te,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"px-4 py-8 text-center",children:o.jsx(Te,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let v;try{v=Pm(i.inputSchema)}catch(y){console.error("Error processing input schema:",y),Ge.error("Failed to process tool input schema."),v=Nr({})}return o.jsxs("div",{className:"flex flex-col gap-4",children:[h&&o.jsx("div",{className:"border-border1 border-b p-4",children:o.jsx(oXt,{html:h,toolName:i.name,onToolCall:p})}),o.jsx(G2e,{executionResult:d,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:m,toolDescription:i.description||"",toolId:i.name})]})},T3s=()=>{const{serverId:e,toolId:t}=ur(),{data:n,isLoading:r}=P2e(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(E3s,{toolId:t,serverId:e})})},Prn=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],yA="rootEntityType",bA={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"},bJ=Object.keys(bA),uLe="mastra:metrics:saved-filters";function j3s(e){const t=R3s(e);try{localStorage.setItem(uLe,t.toString())}catch{}}function N3s(){try{localStorage.removeItem(uLe)}catch{}}function $rn(){try{const e=localStorage.getItem(uLe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function I3s(e){if(e.has(yA))return!0;for(const t of bJ)if(e.has(bA[t]))return!0;return!1}function Mrn({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const i=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:Prn.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"}],a=(u,d)=>u.label.localeCompare(d.label),l=i.filter(u=>u.kind==="pick-multi").sort(a),c=i.filter(u=>u.kind==="text").sort(a);return[...l,...c]}function A3s(e){const t=[],n=new Map([[yA,"rootEntityType"]]);for(const s of bJ)n.set(bA[s],s);const r=new Set;for(const[s]of e.entries()){const i=n.get(s);if(!i||r.has(i))continue;if(r.add(i),i==="tags"){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:i,value:l.filter(Boolean)});continue}if(i==="rootEntityType"||i==="entityName"||i==="serviceName"||i==="environment"||i==="provider"||i==="model"){const l=e.getAll(s);if(l.length>1){t.push({fieldId:i,value:l});continue}}const a=e.get(s);a!==null&&t.push({fieldId:i,value:a})}return t}function R3s(e){const t=new URLSearchParams,n=e.getAll(yA);for(const r of n)t.append(yA,r);for(const r of bJ){const s=bA[r],i=e.getAll(s);for(const a of i)t.append(s,a)}return t}function P3s(e,t){e.delete(yA);for(const n of bJ)e.delete(bA[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?yA:bA[n.fieldId];if(r)if(Array.isArray(n.value)){const s=n.value.filter(i=>typeof i=="string"&&i!=="");if(s.length===0){n.fieldId==="tags"&&e.append(r,"");continue}for(const i of s)e.append(r,i)}else typeof n.value=="string"&&e.set(r,n.value.trim())}}const $3s="Any";function nut(e){const t=e.trim();return t===""||t===$3s}const M3s=new Set(Prn.map(e=>e.entityType));function rut(e){const t=e.trim();return M3s.has(t)?t:void 0}function D3s(e){const t={};for(const n of e){const r=n.fieldId;if(Array.isArray(n.value)){const s=n.value.filter(i=>typeof i=="string").map(i=>i.trim()).filter(i=>!nut(i));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const i=s[0],a=i!==void 0?rut(i):void 0;a&&(t.rootEntityType=a)}else t[r]=s[0]}else if(typeof n.value=="string"){if(nut(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const i=rut(s);i&&(t.rootEntityType=i)}else t[r]=s}}return t}const Drn=[{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"}],L3s=new Set(Drn.map(e=>e.value));function F3s(e){return typeof e=="string"&&(L3s.has(e)||e==="custom")}const Lrn=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function xJ(){return g.useContext(Lrn)}function z3s(e,t){return e!=="custom"?Drn.find(n=>n.value===e)?.label??e:t?.from?t.to?`${gr(t.from,"MMM d, yyyy")} – ${gr(t.to,"MMM d, yyyy")}`:gr(t.from,"MMM d, yyyy"):"Custom range"}function B3s({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:i,onCustomRangeChange:a,tracesBasePath:l,logsBasePath:c}){const u=g.useMemo(()=>JSON.stringify(n),[n]),d=g.useMemo(()=>n,[u]),f=g.useMemo(()=>D3s(d),[d]),h=g.useMemo(()=>JSON.stringify(f),[f]),p=z3s(t,i),m=g.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:i,setCustomRange:a??(()=>{}),dateRangeLabel:p,filterTokens:d,setFilterTokens:s,dimensionalFilter:f,dimensionalFilterKey:h,tracesBasePath:l,logsBasePath:c}),[t,r,i,a,p,d,s,f,h,l,c]);return o.jsx(Lrn.Provider,{value:m,children:e})}const Fke=1440*60*1e3,U3s={"24h":Fke,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function V3s(e,t,n){if(e!=="custom"){const r=U3s[e]??Fke;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-Fke),end:t?.to??new Date(n)}}function og(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=xJ(),s=g.useRef(null),i=e==="custom"?`custom:${t?.from?.getTime()??""}:${t?.to?.getTime()??""}`:`preset:${e}`;(!s.current||s.current.key!==i)&&(s.current={key:i,anchor:Date.now()});const a=s.current.anchor,l=g.useMemo(()=>V3s(e,t,a),[e,t,a]),c=g.useMemo(()=>({timestamp:l,...n}),[l,r]),u=g.useMemo(()=>`${i}|${r}`,[i,r]);return{datePreset:e,customRange:t,timestamp:l,filters:c,dimensionalFilter:n,filterKey:u}}function Frn(){const e=Ye(),{filters:t,filterKey:n}=og();return yt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function lF({href:e,LinkComponent:t="a"}){return o.jsx(ae,{render:o.jsx(t,{href:e}),variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(ko,{})})}function q3s({href:e,LinkComponent:t="a"}){return o.jsx(ae,{render:o.jsx(t,{href:e}),variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(ORn,{})})}function H3s(e){return e==="agents"||e==="workflows"||e==="tools"}function sut(e,t){if(e.length===0)return"0";const n=e.reduce((r,s)=>{const i=s[t];return r+(typeof i=="number"&&Number.isFinite(i)?i:0)},0);return`${Math.round(n/e.length)}`}function W3s(e){const t=e;return typeof t?.tsMs=="number"&&Number.isFinite(t.tsMs)}const Z3s=[{dataKey:"p50",label:"p50",color:cp.blue,aggregate:e=>({value:sut(e,"p50"),suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:cp.yellow,aggregate:e=>({value:sut(e,"p95"),suffix:"avg ms"})}];function Que({data:e,onPointClick:t}){return e.length===0?o.jsx(Ht.NoData,{message:"No latency data yet"}):o.jsx(vZ,{data:e,series:Z3s,onPointClick:t?n=>W3s(n)?t(n):void 0:void 0})}function G3s({data:e,isLoading:t,isError:n,onPointClick:r,actions:s}){const i=(e?.agentData.length??0)>0,a=(e?.workflowData.length??0)>0,l=(e?.toolData.length??0)>0,c={agents:i,workflows:a,tools:l},u=i?"agents":a?"workflows":l?"tools":"agents",[d,f]=g.useState("agents"),h=c[d]?d:u,p=typeof s=="function"?s(h):s,m=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),v=e?Object.values(e).filter(Array.isArray).flat().map(b=>b.p50).filter(b=>typeof b=="number"):[],y=v.length>0?`${Math.round(v.reduce((b,x)=>b+x,0)/v.length)}ms`:"—";return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(Ht.Summary,{value:y,label:"Avg p50"}),p?o.jsx(Ht.Actions,{children:p}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load latency data"}):o.jsx(Ht.Content,{children:m?o.jsxs(hl,{value:h,onValueChange:b=>{H3s(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(fl,{children:[o.jsx(Sr,{value:"agents",disabled:!i,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(Sr,{value:"workflows",disabled:!a,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(Sr,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(ts,{value:"agents",children:o.jsx(Que,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(ts,{value:"workflows",children:o.jsx(Que,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(ts,{value:"tools",children:o.jsx(Que,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Ht.NoData,{message:"No latency data yet"})})]})}function Q3s(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 K3s(e,t){if(t==="1h"){const s=new Date(e);s.setUTCMinutes(0,0,0);const i=new Date(s.getTime()+3600*1e3);return{from:s,to:i}}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 zrn(e,t,n,r,s,i,a){if(a){e.set(t,"custom"),e.set(n,a.from.toISOString()),e.set(r,a.to.toISOString());return}if(s==="custom"){e.set(t,"custom"),i?.from&&e.set(n,i.from.toISOString()),i?.to&&e.set(r,i.to.toISOString());return}const l=Q3s(s);l&&e.set(t,l)}function Lo(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function Brn(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function iut({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const i=new URLSearchParams;i.set(TS,"branches"),zrn(i,jS,cS,uS,e,t,r.window);const a=r.rootEntityType??n.rootEntityType;a&&i.set(A0,a),r.status&&i.set(R0,r.status),Lo(i,Rl.entityName,r.entityName??n.entityName),Lo(i,Rl.threadId,r.threadId??n.threadId),Lo(i,Rl.resourceId,r.resourceId??n.resourceId),Lo(i,Rl.entityId,n.entityId),Lo(i,Rl.runId,n.runId),Lo(i,Rl.sessionId,n.sessionId),Lo(i,Rl.requestId,n.requestId),Lo(i,Rl.userId,n.userId),Lo(i,Rl.organizationId,n.organizationId),Lo(i,Rl.experimentId,n.experimentId),Lo(i,Rl.serviceName,n.serviceName),Lo(i,Rl.environment,n.environment),Brn(i,Rl.tags,n.tags);const l=i.toString();return l?`${s}?${l}`:s}function Y3s({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const i=new URLSearchParams;zrn(i,Px,$x,Mx,e,t,r.window);const a=r.rootEntityType??n.rootEntityType;a&&i.set(P0,a),Lo(i,Pl.entityName,r.entityName??n.entityName),Lo(i,Pl.threadId,r.threadId??n.threadId),Lo(i,Pl.resourceId,r.resourceId??n.resourceId),Lo(i,Pl.runId,n.runId),Lo(i,Pl.sessionId,n.sessionId),Lo(i,Pl.requestId,n.requestId),Lo(i,Pl.userId,n.userId),Lo(i,Pl.organizationId,n.organizationId),Lo(i,Pl.experimentId,n.experimentId),Lo(i,Pl.serviceName,n.serviceName),Lo(i,Pl.environment,n.environment),Brn(i,Pl.tags,n.tags),r.status==="error"&&i.append(Pl.level,"error");const l=i.toString();return l?`${s}?${l}`:s}function tP(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=xJ(),i=g.useCallback((c={})=>iut({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),a=g.useCallback((c={})=>Y3s({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=K3s(u,d);return iut({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:i,getLogsHref:a,getBucketTracesHref:l}}const Urn="1h";async function Kue(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:Urn,filters:n}),s=r.series.find(l=>l.percentile===.5),i=r.series.find(l=>l.percentile===.95);if(!s||!i)return[];const a=new Map(i.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(a.get(u)??0)}})}function X3s(){const e=Ye(),{filters:t,filterKey:n}=og();return yt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,i]=await Promise.all([Kue(e,"mastra_agent_duration_ms",t),Kue(e,"mastra_workflow_duration_ms",t),Kue(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:i,interval:Urn}}})}const aut={agents:Yu.AGENT,workflows:Yu.WORKFLOW_RUN,tools:Yu.TOOL};function J3s(){const{data:e,isLoading:t,isError:n}=X3s(),{getTracesHref:r,getBucketTracesHref:s}=tP(),{Link:i}=un(),a=Fr();return o.jsx(G3s,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&a(s({rootEntityType:aut[l]},c.tsMs,"1h"))},actions:l=>o.jsx(lF,{href:r({rootEntityType:aut[l]}),LinkComponent:i})})}function e4s(e){return e==="threads"||e==="resources"}function Yue(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function t4s({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:i}){const[a,l]=g.useState("threads"),c=e.data?.map(y=>({...y,key:y.threadId}))??[],u=t.data?.map(y=>({...y,key:y.resourceId}))??[],d=c.length>0,f=u.length>0,h=e.data?.reduce((y,b)=>y+b.runs,0)??0,p=t.data?.reduce((y,b)=>y+b.threadCount,0)??0,m=a==="threads"?e:t,v=typeof s=="function"?s(a):s;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),a==="threads"&&d&&o.jsx(Ht.Summary,{value:h.toLocaleString(),label:"Total runs"}),a==="resources"&&f&&o.jsx(Ht.Summary,{value:p.toLocaleString(),label:"Total threads"}),v?o.jsx(Ht.Actions,{children:v}):null]}),m.isLoading?o.jsx(Ht.Loading,{}):m.isError?o.jsx(Ht.Error,{message:"Failed to load memory data"}):o.jsx(Ht.Content,{children:o.jsxs(hl,{defaultTab:"threads",value:a,onValueChange:y=>{e4s(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(fl,{children:[o.jsx(Sr,{value:"threads",children:"Threads"}),o.jsx(Sr,{value:"resources",children:"Resources"})]}),o.jsx(ts,{value:"threads",children:d?o.jsxs(we,{columns:"auto auto auto auto auto",...Oke,children:[o.jsxs(we.Top,{children:[o.jsx(we.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(we.RowHeaderCell,{className:"text-ui-sm",children:Yue(y.threadId)}),o.jsx(we.NumberCell,{children:y.resourceId?Yue(y.resourceId):"—"}),o.jsx(we.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(we.NumberCell,{children:y.tokens>0?lo(y.tokens):"—"}),o.jsx(we.NumberCell,{children:y.cost!=null?Zd(y.cost,y.costUnit):"—"})]});return b?o.jsx(we.RowLink,{to:b,LinkComponent:i,children:x},y.key):o.jsx(we.RowStatic,{children:x},y.key)})]}):o.jsx(Ht.NoData,{message:"No thread activity yet"})}),o.jsx(ts,{value:"resources",children:f?o.jsxs(we,{columns:"auto auto auto auto",...Oke,children:[o.jsxs(we.Top,{children:[o.jsx(we.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(we.RowHeaderCell,{className:"text-ui-sm",children:Yue(y.resourceId)}),o.jsx(we.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(we.NumberCell,{children:y.tokens>0?lo(y.tokens):"—"}),o.jsx(we.NumberCell,{children:y.cost!=null?Zd(y.cost,y.costUnit):"—"})]});return b?o.jsx(we.RowLink,{to:b,LinkComponent:i,children:x},y.key):o.jsx(we.RowStatic,{children:x},y.key)})]}):o.jsx(Ht.NoData,{message:"No resource activity yet"})})]})})]})}const Xue=20;function n4s(){const e=Ye(),{filters:t,filterKey:n}=og();return yt({queryKey:["metrics","top-active-threads",n],queryFn:async()=>{const r={groupBy:["threadId","resourceId"],orderDirection:"DESC",filters:t},[s,i,a]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count",limit:Xue}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:Xue}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:Xue})]),l=new Map,c=d=>XR(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const h=f.dimensions.threadId;if(!h)continue;const p=c(h);p.tokens+=f.value,f.estimatedCost!=null&&(p.cost=(p.cost??0)+f.estimatedCost,f.costUnit&&(p.costUnit=f.costUnit))}};return u(i.groups),u(a.groups),s.groups.filter(d=>!!d.dimensions.threadId).map(d=>{const f=d.dimensions.threadId,h=l.get(f);return{threadId:f,resourceId:d.dimensions.resourceId??null,runs:d.value,tokens:h?.tokens??0,cost:h?.cost??null,costUnit:h?.costUnit??null}})}})}const Jue=20;function r4s(){const e=Ye(),{filters:t,filterKey:n}=og();return yt({queryKey:["metrics","top-resources-by-threads",n],queryFn:async()=>{const r={groupBy:["resourceId"],orderDirection:"DESC",filters:t},[s,i,a]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",limit:Jue}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:Jue}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:Jue})]),l=new Map,c=d=>XR(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const h=f.dimensions.resourceId;if(!h)continue;const p=c(h);p.tokens+=f.value,f.estimatedCost!=null&&(p.cost=(p.cost??0)+f.estimatedCost,f.costUnit&&(p.costUnit=f.costUnit))}};return u(i.groups),u(a.groups),s.groups.filter(d=>!!d.dimensions.resourceId).map(d=>{const f=d.dimensions.resourceId,h=l.get(f);return{resourceId:f,threadCount:d.value,tokens:h?.tokens??0,cost:h?.cost??null,costUnit:h?.costUnit??null}})}})}function s4s(){const e=n4s(),t=r4s(),{getTracesHref:n}=tP(),{Link:r}=un();return o.jsx(t4s,{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 cF({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:i}){const a=t!=null;return o.jsxs(Mr,{children:[o.jsx(Mr.Label,{children:e}),o.jsx(Mr.Value,{className:a?void 0:"invisible",children:a?t:"—"}),i?o.jsx(Mr.Error,{}):s?o.jsx(Mr.Loading,{}):a?r!=null?o.jsx(Mr.Change,{changePct:r,prevValue:n}):o.jsx(Mr.NoChange,{}):o.jsx(Mr.NoData,{})]})}function i4s(){const e=Ye(),{filters:t,filterKey:n}=og();return yt({queryKey:["metrics","active-resources-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"resourceId",filters:t,comparePeriod:"previous_period"})})}function a4s(){const e=Ye(),{filters:t,filterKey:n}=og();return yt({queryKey:["metrics","active-threads-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",filters:t,comparePeriod:"previous_period"})})}function o4s(){const e=Ye(),{filters:t,filterKey:n}=og();return yt({queryKey:["metrics","model-cost-kpi",n],queryFn:async()=>{const r=await e.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"});return{cost:r.estimatedCost??null,costUnit:r.costUnit??null,previousCost:r.previousEstimatedCost??null,costChangePercent:r.costChangePercent??null}}})}function l4s(){const e=Ye(),{filters:t,filterKey:n}=og();return yt({queryKey:["metrics","total-tokens-kpi",n],queryFn:async()=>{const[r,s]=await Promise.all([e.getMetricAggregate({name:["mastra_model_total_input_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"}),e.getMetricAggregate({name:["mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"})]),i=r.value!=null||s.value!=null,a=r.previousValue!=null||s.previousValue!=null,l=(r.value??0)+(s.value??0),c=(r.previousValue??0)+(s.previousValue??0),u=a&&c>0?(l-c)/c*100:null;return{value:i?l:null,previousValue:a?c:null,changePercent:u}}})}function c4s(){const{data:e,isLoading:t,isError:n}=Frn();return o.jsx(cF,{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 u4s(){const{data:e,isLoading:t,isError:n}=o4s();return o.jsx(cF,{label:"Total Model Cost",value:e?.cost!=null?Zd(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?Zd(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function d4s(){const{data:e,isLoading:t,isError:n}=l4s();return o.jsx(cF,{label:"Total Tokens",value:e?.value!=null?lo(e.value):null,prevValue:e?.previousValue!=null?lo(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function f4s(){const{data:e,isLoading:t,isError:n}=a4s();return o.jsx(cF,{label:"Total Threads",value:e?.value!=null?lo(e.value):null,prevValue:e?.previousValue!=null?lo(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function h4s(){const{data:e,isLoading:t,isError:n}=i4s();return o.jsx(cF,{label:"Total Resources",value:e?.value!=null?lo(e.value):null,prevValue:e?.previousValue!=null?lo(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}const p4s=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function m4s(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 g4s(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 v4s(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=xJ(),s=g.useRef(e);s.current=e;const i=g.useRef(n);return i.current=n,o.jsx(n6,{preset:m4s(e),onPresetChange:a=>{const l=g4s(a);s.current=l,t(l)},dateFrom:n?.from,dateTo:n?.to,onDateChange:(a,l)=>{if(s.current!=="custom")return;const c={...i.current,[l]:a};i.current=c,r(c)},presets:p4s})}function y4s({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:i,filterTokens:a,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=a.length>0,d=a.some(f=>b4s(f,i));return u?o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(Trn,{fields:i,tokens:a,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(_rn,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function b4s(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 zke({children:e,filterFields:t,isLoading:n=!1}){const[r]=bi(),{filterTokens:s,setFilterTokens:i}=xJ(),[a,l]=g.useState(),[c,u]=g.useState(()=>!!$rn()),d=()=>{j3s(r),u(!0),Ge.success("Filters setting for Metrics saved")},f=()=>{N3s(),u(!1),Ge.success("Filters setting for Metrics cleared up")},h=()=>{const p=s.map(m=>{const v=t.find(y=>y.id===m.fieldId);return v?v.kind==="text"?{fieldId:m.fieldId,value:""}:v.kind==="pick-multi"?v.multi?{fieldId:m.fieldId,value:[]}:{fieldId:m.fieldId,value:"Any"}:v.kind==="multi-select"?{fieldId:m.fieldId,value:[]}:m:m});i(p)};return o.jsxs(Ft,{width:"wide",height:"full",children:[o.jsxs(Ft.TopArea,{children:[o.jsx(Ft.Row,{children:o.jsxs(Ft.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(v4s,{}),o.jsx(Nrn,{fields:t,tokens:s,onTokensChange:i,disabled:n,onStartTextFilter:l})]})}),o.jsx(y4s,{isLoading:n,filterFields:t,filterTokens:s,onFilterTokensChange:i,onClear:h,onRemoveAll:()=>i([]),onSave:d,onRemoveSaved:c?f:void 0,autoFocusFilterFieldId:a})]}),e]})}function x4s({error:e}){return ks(e)?o.jsx(Gs,{}):Es(e)?o.jsx(Fs,{resource:"metrics"}):o.jsx(Ws,{title:"Failed to load storage capabilities",message:e.message})}const out=Mrn({availableTags:[],availableEntityNames:[],availableServiceNames:[],availableEnvironments:[]});function w4s({children:e}){const{supportsMetrics:t,isLoading:n,error:r}=rF();return n?o.jsx(zke,{filterFields:out,isLoading:!0,children:o.jsxs("div",{className:"flex h-full items-center justify-center gap-2",children:[o.jsx(_n,{"aria-label":"Loading storage capabilities"}),o.jsx("span",{className:"text-ui-sm text-neutral4",children:"Loading storage capabilities"})]})}):r?o.jsx(Qn,{children:o.jsx(x4s,{error:r})}):t?e:o.jsx(zke,{filterFields:out,children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ar,{iconSlot:o.jsx(Ls,{}),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.jsx(ae,{variant:"ghost",render:o.jsx("a",{href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer"}),icon:o.jsx(_s,{}),children:"Metrics Documentation"})})})})}function S4s({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:i}){const a=!!e&&e.length>0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Model Usage & Cost",description:"Token consumption by model."}),a&&(()=>{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?Zd(l):"—":c.size===1?u=l>0?Zd(l,[...c][0]):"—":u="Mixed",o.jsx(Ht.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(Ht.Actions,{children:s}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load model usage data"}):o.jsx(Ht.Content,{children:a?o.jsxs(we,{columns:"auto auto auto auto auto auto",...Oke,children:[o.jsxs(we.Top,{children:[o.jsx(we.TopCell,{sticky:"start",children:"Model"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(we.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(we.RowHeaderCell,{className:"text-ui-sm",children:l.model}),o.jsx(we.NumberCell,{children:l.input}),o.jsx(we.NumberCell,{children:l.output}),o.jsx(we.NumberCell,{children:l.cacheRead}),o.jsx(we.NumberCell,{children:l.cacheWrite}),o.jsx(we.NumberCell,{highlight:!0,children:l.cost!=null?Zd(l.cost,l.costUnit):"—"})]});return c?o.jsx(we.RowLink,{to:c,LinkComponent:i,children:u},l.model):o.jsx(we.RowStatic,{children:u},l.model)})]}):o.jsx(Ht.NoData,{message:"No model usage data yet"})})]})}function k4s(){const e=Ye(),{filters:t,filterKey:n}=og();return yt({queryKey:["metrics","model-usage-cost",n],queryFn:async()=>{const[r,s,i,a]=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||!i||!a)return[];const l=new Map,c=d=>XR(l,d,()=>({input:0,output:0,cacheRead:0,cacheWrite:0,cost:null,costUnit:null})),u=(d,f)=>{f.estimatedCost!=null&&(d.cost=(d.cost??0)+f.estimatedCost,f.costUnit&&(d.costUnit=f.costUnit))};for(const d of r.groups){const f=d.dimensions.model??"unknown",h=c(f);h.input=d.value,u(h,d)}for(const d of s.groups){const f=d.dimensions.model??"unknown",h=c(f);h.output=d.value,u(h,d)}for(const d of i.groups){const f=d.dimensions.model??"unknown",h=c(f);h.cacheRead=d.value}for(const d of a.groups){const f=d.dimensions.model??"unknown",h=c(f);h.cacheWrite=d.value}return Array.from(l.entries()).map(([d,f])=>({model:d,input:lo(f.input),output:lo(f.output),cacheRead:lo(f.cacheRead),cacheWrite:lo(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function O4s(){const{data:e,isLoading:t,isError:n}=k4s(),{getTracesHref:r}=tP(),{Link:s}=un();return o.jsx(S4s,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:Yu.AGENT}),actions:o.jsx(lF,{href:r({rootEntityType:Yu.AGENT}),LinkComponent:s})})}function C4s(e){return e==="tokens"||e==="cost"}function _4s({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:i}){const[a,l]=g.useState("tokens"),c=e??[],u=c.length>0,d=c.reduce((b,x)=>b+x.total,0),f=c.filter(b=>b.cost!=null&&b.cost>0),h=new Set(f.map(b=>b.costUnit??"usd")),p=h.size<=1,m=p?[...h][0]??"usd":null,v=p?f.reduce((b,x)=>b+(x.cost??0),0):0,y=p&&v>0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(a==="cost"&&y?o.jsx(Ht.Summary,{value:Zd(v,m),label:"Total cost"}):o.jsx(Ht.Summary,{value:lo(d),label:"Total tokens"})),u&&s?o.jsx(Ht.Actions,{children:s}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load token usage data"}):o.jsx(Ht.Content,{children:u?o.jsxs(hl,{defaultTab:"tokens",value:a,onValueChange:b=>{C4s(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(fl,{children:[o.jsx(Sr,{value:"tokens",children:"Tokens"}),o.jsx(Sr,{value:"cost",children:"Cost"})]}),o.jsx(ts,{value:"tokens",children:o.jsx(vA,{LinkComponent:i,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:cp.blueDark},{label:"Output",color:cp.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:lo})}),o.jsx(ts,{value:"cost",children:y?o.jsx(vA,{LinkComponent:i,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:cp.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>Zd(b,m)}):o.jsx(Ht.NoData,{message:"No cost data yet"})})]}):o.jsx(Ht.NoData,{message:"No token usage data yet"})})]})}function E4s(){const e=Ye(),{filters:t,filterKey:n}=og();return yt({queryKey:["metrics","token-usage-by-agent",n],queryFn:async()=>{const r={groupBy:["entityName"],aggregation:"sum",orderDirection:"DESC",filters:t},[s,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"]}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"]})]),a=new Map,l=u=>XR(a,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 i.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.output=u.value,c(f,u)}return Array.from(a.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 T4s(){const{data:e,isLoading:t,isError:n}=E4s(),{getTracesHref:r}=tP(),{Link:s}=un();return o.jsx(_4s,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:i=>r({rootEntityType:Yu.AGENT,entityName:i.name}),actions:o.jsx(lF,{href:r({rootEntityType:Yu.AGENT}),LinkComponent:s})})}function Bke(e,t=lo){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const j4s=[{dataKey:"input",label:"Input tokens",color:cp.blue,aggregate:Bke("input")},{dataKey:"output",label:"Output tokens",color:cp.yellow,aggregate:Bke("output")}];function N4s(e){return e==="tokens"||e==="cost"}function I4s({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[i,a]=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),h=f.map(k=>({...k})),p=new Set(f.map(k=>k.costUnit).filter(k=>!!k)),m=p.size===1&&f.every(k=>k.costUnit!=null),v=m?[...p][0]??null:null,y=m?f.reduce((k,_)=>k+(_.cost??0),0):0,b=m&&y>0,x=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",w=[{dataKey:"cost",label:"Cost",color:cp.purple,aggregate:Bke("cost",k=>Zd(k,v))}];return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Token usage over time",description:x}),u&&(i==="cost"&&b?o.jsx(Ht.Summary,{value:Zd(y,v),label:"Total cost"}):o.jsx(Ht.Summary,{value:lo(d),label:"Total tokens"})),u&&s?o.jsx(Ht.Actions,{children:s}):null]}),n?o.jsx(Ht.Loading,{}):r?o.jsx(Ht.Error,{message:"Failed to load token usage timeline"}):o.jsx(Ht.Content,{children:u?o.jsxs(hl,{defaultTab:"tokens",value:i,onValueChange:k=>{N4s(k)&&a(k)},className:"overflow-visible",children:[o.jsxs(fl,{children:[o.jsx(Sr,{value:"tokens",children:"Tokens"}),o.jsx(Sr,{value:"cost",children:"Cost"})]}),o.jsx(ts,{value:"tokens",children:o.jsx(vZ,{data:c,series:j4s})}),o.jsx(ts,{value:"cost",children:b?o.jsx(vZ,{data:h,series:w}):o.jsx(Ht.NoData,{message:"No cost data yet"})})]}):o.jsx(Ht.NoData,{message:"No token usage data yet"})})]})}function A4s(e){return e==="24h"?"1h":"1d"}function R4s(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 lut(e,t,n){for(const r of t?.points??[]){const s=new Date(r.timestamp).getTime();if(!Number.isFinite(s))continue;const i=e.get(s)??{tsMs:s,input:0,output:0,cost:null,costUnits:new Set,hasUnknownCostUnit:!1};i[n]+=r.value,r.estimatedCost!=null&&(i.cost=(i.cost??0)+r.estimatedCost,t?.costUnit?i.costUnits.add(t.costUnit):i.hasUnknownCostUnit=!0),e.set(s,i)}}function P4s(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function $4s(){const e=Ye(),{datePreset:t,filters:n,filterKey:r}=og(),s=A4s(t);return yt({queryKey:["metrics","token-usage-timeseries",r,s],queryFn:async()=>{const[i,a]=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 lut(l,i.series[0],"input"),lut(l,a.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:R4s(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:P4s(u)}}),interval:s}}})}function M4s(){const{data:e,isLoading:t,isError:n}=$4s(),{getTracesHref:r}=tP(),{Link:s}=un();return o.jsx(I4s,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(lF,{href:r(),LinkComponent:s})})}function ede({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(vA,{LinkComponent:r,data:e.map(s=>{const i=n?.(s),a=t?.(s);return i?{name:s.name,values:[s.completed,s.errors],hrefs:[a,i]}:{name:s.name,values:[s.completed,s.errors],href:a}}),segments:[{label:"Completed",color:cp.blueDark},{label:"Errors",color:cp.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:lo})}function D4s({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:i,LinkComponent:a}){const[l,c]=g.useState("agents"),u=typeof i=="function"?i(l):i,d=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),f=e?[...e.agentData,...e.workflowData,...e.toolData].reduce((m,v)=>m+v.completed+v.errors,0):0,h=m=>r?v=>r(m,v):void 0,p=m=>s?v=>s(m,v):void 0;return o.jsxs(Ht,{children:[o.jsxs(Ht.TopBar,{children:[o.jsx(Ht.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(Ht.Summary,{value:lo(f),label:"Total runs"}),u?o.jsx(Ht.Actions,{children:u}):null]}),t?o.jsx(Ht.Loading,{}):n?o.jsx(Ht.Error,{message:"Failed to load trace volume data"}):o.jsx(Ht.Content,{children:d?o.jsxs(hl,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(fl,{children:[o.jsx(Sr,{value:"agents",children:"Agents"}),o.jsx(Sr,{value:"workflows",children:"Workflows"}),o.jsx(Sr,{value:"tools",children:"Tools"})]}),o.jsx(ts,{value:"agents",children:e.agentData.length>0?o.jsx(ede,{data:e.agentData,rowHrefs:h("agents"),errorHrefs:p("agents"),LinkComponent:a}):o.jsx(Ht.NoData,{message:"No agent data yet"})}),o.jsx(ts,{value:"workflows",children:e.workflowData.length>0?o.jsx(ede,{data:e.workflowData,rowHrefs:h("workflows"),errorHrefs:p("workflows"),LinkComponent:a}):o.jsx(Ht.NoData,{message:"No workflow data yet"})}),o.jsx(ts,{value:"tools",children:e.toolData.length>0?o.jsx(ede,{data:e.toolData,rowHrefs:h("tools"),errorHrefs:p("tools"),LinkComponent:a}):o.jsx(Ht.NoData,{message:"No tool data yet"})})]}):o.jsx(Ht.NoData,{message:"No trace volume data yet"})})]})}async function tde(e,t,n){const r=await e.getMetricBreakdown({name:[t],groupBy:["entityName","status"],aggregation:"count",orderDirection:"DESC",filters:n}),s=new Map;for(const i of r.groups){const a=i.dimensions.entityName??"unknown",l=i.dimensions.status??"ok",c=XR(s,a,()=>({completed:0,errors:0}));l==="error"?c.errors+=i.value:c.completed+=i.value}return Array.from(s.entries()).map(([i,a])=>({name:i,...a})).sort((i,a)=>a.completed+a.errors-(i.completed+i.errors))}function L4s(){const e=Ye(),{filters:t,filterKey:n}=og();return yt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,i]=await Promise.all([tde(e,"mastra_agent_duration_ms",t),tde(e,"mastra_workflow_duration_ms",t),tde(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:i}}})}const jB={agents:Yu.AGENT,workflows:Yu.WORKFLOW_RUN,tools:Yu.TOOL};function F4s(){const{data:e,isLoading:t,isError:n}=L4s(),{getTracesHref:r,getLogsHref:s}=tP(),{Link:i}=un();return o.jsx(D4s,{data:e,isLoading:t,isError:n,LinkComponent:i,getRowHref:(a,l)=>r({rootEntityType:jB[a],entityName:l.name}),getErrorSegmentHref:(a,l)=>l.errors>0?s({rootEntityType:jB[a],entityName:l.name,status:"error"}):void 0,actions:a=>o.jsxs(o.Fragment,{children:[o.jsx(lF,{href:r({rootEntityType:jB[a]}),LinkComponent:i}),o.jsx(q3s,{href:s({rootEntityType:jB[a],status:"error"}),LinkComponent:i})]})})}const nde="period",NB="dateFrom",IB="dateTo";function z4s(){const[e,t]=bi(),n=e.get(nde),r=F3s(n)?n:"24h",s=g.useMemo(()=>{if(r!=="custom")return;const d=p=>{if(!p)return;const m=new Date(p);return Number.isNaN(m.getTime())?void 0:m},f=d(e.get(NB)),h=d(e.get(IB));if(!(!f&&!h))return{from:f,to:h}},[r,e.toString()]),i=g.useMemo(()=>A3s(e),[e.toString()]),a=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d==="24h"?h.delete(nde):h.set(nde,d),d!=="custom"&&(h.delete(NB),h.delete(IB)),h},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d?.from?h.set(NB,d.from.toISOString()):h.delete(NB),d?.to?h.set(IB,d.to.toISOString()):h.delete(IB),h},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return P3s(h,d),h},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,I3s(e)))return;const d=$rn();d&&t(f=>{const h=new URLSearchParams(f);for(const[p,m]of d)h.append(p,m);return h},{replace:!0})},[]),o.jsx(B3s,{preset:r,filterTokens:i,onPresetChange:a,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(w4s,{children:o.jsx(B4s,{})})})}function B4s(){const{error:e,isLoading:t}=Frn(),{isInMemory:n}=rF(),{data:r,isLoading:s}=Rrn(),{data:i,isLoading:a}=zDe(),{data:l,isLoading:c}=Arn(),{data:u,isLoading:d}=BDe(),f=g.useMemo(()=>Mrn({availableTags:r??[],availableEntityNames:i??[],availableServiceNames:l??[],availableEnvironments:u??[],loading:{tags:s,entityNames:a,serviceNames:c,environments:d}}),[r,i,l,u,s,a,c,d]);return e&&ks(e)?o.jsx(Qn,{children:o.jsx(Gs,{})}):e&&Es(e)?o.jsx(Qn,{children:o.jsx(Fs,{resource:"metrics"})}):e?o.jsx(Qn,{children:o.jsx(Ws,{title:"Failed to load metrics",message:e.message})}):o.jsx(zke,{filterFields:f,isLoading:t,children:o.jsxs("div",{className:"grid content-start gap-4 pb-6",children:[n&&o.jsx(xn,{variant:"info",title:"Metrics are not persisted",children:o.jsx(xn.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(Pke,{children:[o.jsx(c4s,{}),o.jsx(u4s,{}),o.jsx(d4s,{}),o.jsx(f4s,{}),o.jsx(h4s,{})]}),o.jsxs(Pke,{children:[o.jsx(O4s,{}),o.jsx(T4s,{}),o.jsx(M4s,{}),o.jsx(s4s,{}),o.jsx(F4s,{}),o.jsx(J3s,{})]})]})})}function cut(){const{isCmsAvailable:e}=Ab(),{Link:t,paths:n}=un();return e?o.jsx(xv,{owner:"prompt-block-list",children:o.jsx(J_,{render:o.jsx(t,{href:n.cmsPromptBlockCreateLink()}),tooltip:"Create a prompt",variant:"ghost",size:"sm",children:"New prompt"})}):null}const U4s=50;function V4s(){const[e,t]=g.useState(""),[n,r]=g.useState(0),{data:s,isLoading:i,error:a,isPlaceholderData:l}=NJt({page:n,perPage:U4s}),c=s?.promptBlocks??[],u=s?.hasMore??!1,d=g.useCallback(()=>{l||r(p=>p+1)},[l]),f=g.useCallback(()=>{l||r(p=>Math.max(0,p-1))},[l]),h=g.useCallback(p=>{t(p),r(0)},[]);return a&&ks(a)?o.jsx(Qn,{children:o.jsx(Gs,{})}):a&&Es(a)?o.jsx(Qn,{children:o.jsx(Fs,{resource:"prompt blocks"})}):a?o.jsx(Qn,{children:o.jsx(Ws,{title:"Failed to load prompt blocks",message:a.message})}):c.length===0&&!i&&n===0?o.jsxs(Qn,{children:[o.jsx(cut,{}),o.jsx(qCs,{})]}):o.jsxs(Ft,{height:"full",children:[o.jsx(cut,{}),o.jsx(Ft.TopArea,{children:o.jsx(Ft.Row,{align:"center",stack:"responsive",children:o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(Wc,{onSearch:h,label:"Filter prompts",placeholder:"Filter by name or description"})})})}),o.jsx(VCs,{promptBlocks:c,isLoading:i,search:e,currentPage:n,hasMore:u,onNextPage:d,onPrevPage:f})]})}function q4s(){return o.jsx(Ft,{width:"narrow",children:o.jsx(Ft.MainArea,{children:o.jsx(ows,{children:o.jsx(X1e,{})})})})}const H4s=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:qIn,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:RSt,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:_s,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:jA,href:"https://discord.gg/mastra-ai",external:!0},{title:"Share with your team",description:"Running Mastra Studio locally? Deploy to the cloud so your team can collaborate.",icon:FSt,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:yCe,href:"https://mastra.ai/contact?ref=studio",external:!0}];function W4s(){return o.jsx(Ft,{width:"narrow",children:o.jsx(Ft.MainArea,{children:o.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:H4s.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(_s,{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",children:e.description})]},e.href))})})})}function uut(){const{isCmsAvailable:e}=Ab(),{Link:t,paths:n}=un();return e?o.jsx(xv,{owner:"scorer-list",children:o.jsx(J_,{render:o.jsx(t,{href:n.cmsScorersCreateLink()}),tooltip:"Create a scorer",variant:"ghost",size:"sm",children:"New scorer"})}):null}function Z4s(){const{data:e={},isLoading:t,error:n}=Ep(),[r,s]=g.useState(""),[i,a]=g.useState("all");if(n&&ks(n))return o.jsx(Qn,{children:o.jsx(Gs,{})});if(n&&Es(n))return o.jsx(Qn,{children:o.jsx(Fs,{resource:"scorers"})});if(n)return o.jsx(Qn,{children:o.jsx(Ws,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsxs(Qn,{children:[o.jsx(uut,{}),o.jsx(d1s,{})]});const l=i!=="all"||r!=="",c=()=>{s(""),a("all")};return o.jsxs(Ft,{height:"full",children:[o.jsx(uut,{}),o.jsx(Ft.TopArea,{children:o.jsx(h1s,{search:r,onSearchChange:s,sourceFilter:i,onSourceFilterChange:a,onReset:c,hasActiveFilters:l})}),o.jsx(u1s,{scorers:e,isLoading:t,search:r,sourceFilter:i})]})}const Vrn=["input","entity"],G4s={input:"Input",entity:"Entity"};function Q4s(e){const t=["auto","auto","minmax(0, 10rem)"];return e.has("entity")&&t.push("minmax(0, 14rem)"),e.has("input")&&t.push("minmax(0, 40rem)"),t.join(" ")}function K4s(){const[e,t]=g.useState(new Set),n=g.useMemo(()=>new Set(Vrn.filter(i=>!e.has(i))),[e]),r=g.useMemo(()=>Q4s(n),[n]),s=g.useCallback(i=>{t(a=>{const l=new Set(a);return l.has(i)?l.delete(i):l.add(i),l})},[]);return{visibleColumns:n,columns:r,toggleColumn:s}}function Y4s({visibleColumns:e,toggleColumn:t}){return o.jsxs(xt,{children:[o.jsx(xt.Trigger,{asChild:!0,children:o.jsx(ae,{icon:o.jsx(nbe,{}),children:"Columns"})}),o.jsxs(xt.Content,{align:"end",children:[o.jsx(xt.Label,{children:"Toggle columns"}),Vrn.map(n=>o.jsx(xt.CheckboxItem,{checked:e.has(n),onClick:()=>t(n),children:G4s[n]},n))]})]})}function X4s(){const{scorerId:e}=ur(),[t,n]=bi(),r=t.get("scoreId")??void 0,[s,i]=g.useState(r),[a,l]=g.useState(!1),c=Fr(),[u,d]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:f,error:h}=qSs(e),p=K4s(),{data:m={},isLoading:v,error:y}=rh(),{isLoading:b,error:x}=eg(),{data:w=[],isLoading:k,error:_,isFetchingNextPage:C,hasNextPage:T,setEndOfListElement:E}=VSs({scorerId:e,entityId:u?.value==="all"?void 0:u?.value,entityType:u?.type==="ALL"?void 0:u?.type}),N=g.useMemo(()=>f?.agentIds?.filter(U=>m[U]).map(U=>({value:U,label:m[U].name,type:"AGENT"}))||[],[f?.agentIds,m]),I=g.useMemo(()=>f?.workflowIds?.map(U=>({value:U,label:U,type:"WORKFLOW"}))||[],[f?.workflowIds]),A=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...N,...I],[N,I]),P=t.get("entity")??"all",L=A.find(U=>U.value===P);L&&L.value!==u?.value&&d(L),g.useEffect(()=>{if(h){const U=h instanceof Error?h.message:"Failed to load scorer";Ge.error(`Error loading scorer: ${U}`)}},[h]),g.useEffect(()=>{if(y){const U=y instanceof Error?y.message:"Failed to load agents";Ge.error(`Error loading agents: ${U}`)}},[y]),g.useEffect(()=>{if(x){const U=x instanceof Error?x.message:"Failed to load workflows";Ge.error(`Error loading workflows: ${U}`)}},[x]);const M=U=>{U?.value&&n(Q=>{const ee=new URLSearchParams(Q);return ee.set("entity",U.value),ee})};g.useEffect(()=>{const U=t.get("scoreId")??void 0;if(U===s)return;if(!U){i(void 0);return}w.find(ee=>ee.id===U)&&i(U)},[t,w]);const V=g.useCallback(U=>{i(U||void 0),n(Q=>{const ee=new URLSearchParams(Q);return U?ee.set("scoreId",U):ee.delete("scoreId"),ee})},[n]);if(!f)return null;const q=ks(h)||ks(y)||ks(x),H=h&&Es(h),B=!q&&!H&&(h||y||x),W=!k&&w.length===0,z=u?.value!=="all",G=f?.source==="stored",F=e?o.jsx(yJ,{open:a,onOpenChange:l,initialScorerIds:[e],onSuccess:U=>{c(`/experiments/${U}`)}}):null,R=G?o.jsxs(xt,{children:[o.jsx(xt.Trigger,{asChild:!0,children:o.jsx(ae,{size:"lg","aria-label":"Scorer actions menu",children:o.jsx(F1,{})})}),o.jsx(xt.Content,{align:"end",className:"w-48",children:o.jsxs(xt.Item,{onSelect:()=>{c(`/cms/scorers/${e}/edit`)},children:[o.jsx(Gd,{})," Edit Scorer"]})})]}):null;if(q||H||B||W&&!z){const U=(h instanceof Error?h.message:void 0)??(y instanceof Error?y.message:void 0)??(x instanceof Error?x.message:void 0)??"An unexpected error occurred",Q=q||H||B;return o.jsxs(Ft,{width:"wide",height:"full",className:Q||!R?"grid-rows-[1fr]":void 0,children:[!Q&&R&&o.jsx(Ft.TopArea,{children:o.jsx(Ms,{className:"ml-auto",children:R})}),o.jsx(Ft.MainArea,{isCentered:!0,children:q?o.jsx(Gs,{}):H?o.jsx(Fs,{resource:"scorers"}):B?o.jsx(Ws,{title:"Failed to load scorer",message:U}):o.jsx(MSs,{onRunExperiment:()=>l(!0)})}),F]})}return o.jsxs(Ft,{width:"wide",height:"full",children:[o.jsx(Ft.TopArea,{children:o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx(DSs,{selectedEntity:u,entityOptions:A,onEntityChange:M,onReset:()=>{n(U=>{const Q=new URLSearchParams(U);return Q.set("entity","all"),Q})},isLoading:k||v||b}),o.jsxs(Ms,{children:[o.jsx(Y4s,{visibleColumns:p.visibleColumns,toggleColumn:p.toggleColumn}),o.jsx(ae,{variant:"primary",onClick:()=>l(!0),icon:o.jsx(bu,{}),children:"Run Experiment"}),R]})]})}),o.jsx($Ss,{scores:w,isLoading:k,selectedScoreId:s,isFetchingNextPage:C,hasNextPage:T,setEndOfListElement:E,onScoreClick:V,errorMsg:_?.message,columnsState:p}),F]})}const J4s=[{value:"system",label:"System",icon:o.jsx(JSt,{})},{value:"light",label:"Light",icon:o.jsx(d$n,{})},{value:"dark",label:"Dark",icon:o.jsx(BRn,{})}],e5s={md:{itemGap:2,itemWidth:28,root:"gap-0.5 p-0.5",indicator:"inset-y-0.5 left-0.5",item:"h-6 [&_svg]:size-3.5"},xs:{itemGap:1,itemWidth:20,root:"gap-px p-px",indicator:"inset-y-px left-px",item:"h-4 [&_svg]:h-icon-sm [&_svg]:w-icon-sm"},sm:{itemGap:1,itemWidth:24,root:"gap-px p-px",indicator:"inset-y-px left-px",item:"h-5 [&_svg]:h-icon-sm [&_svg]:w-icon-sm"}},t5s=({value:e,onChange:t,options:n=J4s,size:r="md",className:s,"aria-label":i="Theme",...a})=>{const{theme:l,setTheme:c}=aE(),u=e??l,d=t??c,f=n.some(y=>y.value===u)?u:n[0]?.value??"system",h=y=>{const b=n.find(x=>x.value===y);b&&d(b.value)},p=Math.max(0,n.findIndex(y=>y.value===f)),m=e5s[r],v=p*(m.itemWidth+m.itemGap);return o.jsxs(zXt,{...a,value:f,onValueChange:h,"aria-label":i,className:K("relative inline-flex w-fit items-center rounded-full border border-border1 bg-surface3",m.root,s),children:[o.jsx("span",{"aria-hidden":"true",className:K("pointer-events-none absolute rounded-full bg-surface5 motion-reduce:transition-none",Vr.transform,m.indicator),style:{width:m.itemWidth,transform:`translateX(${v}px)`}}),n.map(y=>o.jsx(FXt,{value:y.value,"aria-label":y.label,style:{width:m.itemWidth},className:K("relative inline-flex cursor-pointer items-center justify-center rounded-full","text-icon3 hover:text-icon6 data-[checked]:text-icon6",m.item,"focus-visible:outline-hidden","active:scale-90 motion-reduce:transition-none",Vr.colors,Vr.transform),children:o.jsx("span",{"aria-hidden":"true",className:"pointer-events-none inline-flex items-center justify-center",children:y.icon})},y.value))]})},n5s=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=B4();return o.jsx(Ft,{className:"p-0",children:o.jsx(U1s,{children:o.jsxs("div",{className:"mx-auto flex max-w-4xl flex-col gap-8",children:[o.jsxs(Jat,{children:[o.jsxs(eot,{children:[o.jsx(tot,{children:"General"}),o.jsx(not,{children:"Stored in this browser."})]}),o.jsx(NXt,{children:o.jsx(ske,{label:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(t5s,{})})})]}),o.jsxs(Jat,{children:[o.jsxs(eot,{children:[o.jsx(tot,{children:"Mastra Connection"}),o.jsx(not,{children:"Configure the Mastra instance URL, API prefix, and request headers used by the studio."})]}),o.jsx(QXt,{variant:"factory",initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})]})]})})})};function r5s(){const[e]=bi(),t=Fr(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(Crn,{redirectUri:n,onSuccess:r,initialMode:"signup"})}function s5s(e){return e.replace(/\/$/,"").split("/").pop()}function wJ({children:e,className:t}){return o.jsx("div",{className:K("border border-border1 rounded-lg mt-12 py-5 lg:min-h-[25rem] transition-height px-4 lg:px-12",t),children:e})}function i5s({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((i,a)=>o.jsx("div",{className:"bg-surface3 h-16 animate-pulse rounded-lg"},a))}):o.jsx("div",{className:K("grid gap-y-4",n),children:e.map(i=>{const a=i?.agents||i?.tools||i?.networks||i?.workflows||i?.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/${i.slug}`,className:K("grid [&:hover_p]:text-neutral5",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":i.imageURL}),children:[i.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(${i.imageURL})`}})}),o.jsxs("div",{className:K("grid py-3 px-4 w-full gap-0.5","[&_svg]:w-[1em] [&_svg]:h-[1em] [&_svg]:text-neutral3"),children:[o.jsx("h2",{className:"text-ui-md text-neutral5",children:i.title}),o.jsx("p",{className:"text-ui-md text-neutral4 transition-colors duration-500",children:i.description}),o.jsxs("div",{className:"text-neutral3 text-ui-md mt-3 hidden flex-wrap items-center gap-4 2xl:flex",children:[a&&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:[i?.agents&&i.agents.length>0&&o.jsxs("li",{children:[o.jsx(Ma,{})," ",i.agents.length]}),i?.tools&&i.tools.length>0&&o.jsxs("li",{children:[o.jsx(eh,{})," ",i.tools.length]}),i?.networks&&i.networks.length>0&&o.jsxs("li",{children:[o.jsx(e1t,{})," ",i.networks.length]}),i?.workflows&&i.workflows.length>0&&o.jsxs("li",{children:[o.jsx(z1,{})," ",i.workflows.length]}),i?.mcp&&i.mcp.length>0&&o.jsxs("li",{children:[o.jsx(ME,{})," ",i.mcp.length]})]}),a&&i.supportedProviders&&o.jsx("small",{children:"|"}),o.jsx("div",{className:"text-neutral3 flex items-center gap-4",children:i.supportedProviders.map(l=>o.jsx("span",{className:"",children:l},l))})]})]})]}),o.jsx("a",{href:i.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(jY,{})," ",s5s(i.githubUrl)]})})]},i.slug)})})}function a5s({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:s,onProviderChange:i,searchTerm:a,onSearchChange:l,onReset:c,className:u,isLoading:d}){return d?o.jsxs("div",{className:K("h-[6.5rem] flex items-center gap-5","[&>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-5",u),children:[o.jsx(C3,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:a,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(of,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(of,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:i,options:n}),c&&o.jsx(ae,{onClick:c,icon:o.jsx(Yt,{}),children:"Reset"})]})}function o5s(){const{data:e,isLoading:t}=z1r(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[i,a]=g.useState("all"),[l,c]=g.useState("all"),[u,d]=g.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(x=>{f.push({value:x,label:x})});const h=[{value:"all",label:"Any provider"}];(s||[]).forEach(x=>{h.push({value:x,label:x})});const p=(x,w)=>{w==="tag"?a(x):w==="provider"&&c(x)},m=x=>{d(x)},v=()=>{a("all"),c("all"),d("")},y=n.filter(x=>!(u&&!x.title.toLowerCase().includes(u)&&!x.description.toLowerCase().includes(u)||i!=="all"&&!x.tags.includes(i)||l!=="all"&&!x.supportedProviders.includes(l))),b=u||i!=="all"||l!=="all";return o.jsxs(oi,{children:[o.jsx(Q4,{children:o.jsxs(EEt,{children:[o.jsx(St,{children:o.jsx(Qx,{})}),"Templates"]})}),o.jsxs("div",{className:K("overflow-y-auto w-full h-full px-5 pb-12 z-10"),children:[o.jsx(a5s,{selectedTag:i,onTagChange:x=>p(x,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:x=>p(x,"provider"),providerOptions:h,searchTerm:u,onSearchChange:m,onReset:b?v:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(i5s,{templates:y,linkComponent:oo,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const l5s="1.68.0-alpha.9";function c5s({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,i=()=>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.",a=()=>s?{icon:o.jsx(Pc,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(rAn,{}),title:"Template Installation Failed"},{icon:l,title:c}=a();return o.jsxs(wJ,{className:"text-neutral3 mb-5 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:i()})]})]}),t&&t.length>0&&o.jsxs("details",{className:"text-ui-sm",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:"text-ui-sm mt-4 max-h-60 space-y-2 overflow-auto rounded bg-gray-100 p-3 text-left 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:"text-ui-sm mt-1 font-mono wrap-break-word whitespace-pre-wrap text-gray-700 dark:text-gray-300",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-ui-sm",children:[o.jsx("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:"Show Details"}),o.jsx("div",{className:"text-ui-sm mt-4 max-h-60 overflow-auto rounded bg-gray-100 p-3 text-left font-mono dark:bg-gray-800",children:o.jsx("div",{className:"wrap-break-word whitespace-pre-wrap",children:n})})]})]})}const u5s=g.createContext(null);function d5s(){const e=g.useContext(u5s);return e||{registerResetFn:()=>{},triggerReset:()=>{}}}const qrn=({defaultProvider:e,defaultModel:t,updateModel:n,resetModel:r})=>{const[s]=g.useState(e),[i]=g.useState(t),[a,l]=g.useState(t),[c,u]=g.useState(e||""),[d,f]=g.useState(!1),[h,p]=g.useState(!1),[m,v]=g.useState(!1),{data:y,isLoading:b}=r6(),x=z0(),{models:w}=tw(),k=g.useMemo(()=>y?.providers||[],[y]);g.useEffect(()=>{l(t),u(e||"")},[t,e]);const _=sa(c),T=NN(k,_)?.id||_,E=async M=>{if(l(M),M&&T){f(!0);try{const V=await n({provider:T,modelId:M});console.info("Model updated:",V)}catch(V){console.error("Failed to update model:",V)}finally{f(!1)}}},N=M=>{const V=sa(M);u(V),V!==_&&(l(""),v(!0))},{registerResetFn:I}=d5s();if(g.useEffect(()=>(I(()=>{if(h||m)return;if(_&&_!==s&&(!a||a==="")){u(sa(s)),l(i);const B=NN(k,s)?.id||s;B&&i&&n({provider:B,modelId:i}).catch(W=>{console.error("Failed to reset model:",W)})}}),()=>{I(null)}),[I,_,a,s,i,n,h,m,k]),b)return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(_n,{}),o.jsx("span",{className:"text-ui-md text-gray-500",children:"Loading providers..."})]});const A=async()=>{if(!r){console.warn("Reset model function not provided");return}try{f(!0),await r()}catch(M){console.error("Failed to reset model:",M)}finally{f(!1)}},P=NN(k,_);if(x.active&&x.pickerVisible===!1){const M=x.default&&x.default.provider&&x.default.modelId?`${x.default.provider}/${x.default.modelId}`:c&&a?`${c}/${a}`:"Locked by admin";return o.jsxs("div",{className:"border-border1 bg-surface3 flex items-center gap-2 rounded-md border px-3 py-2","data-testid":"agent-metadata-model-locked",children:[o.jsx(td,{className:"text-neutral3 h-4 w-4 shrink-0"}),o.jsx("span",{className:"text-ui-sm text-neutral6 truncate",children:M}),o.jsx("span",{className:"text-ui-xs text-neutral3 ml-auto shrink-0",children:"Set by admin"})]})}const L=!!(_&&a)&&x.active&&x.allowed!==void 0&&!w.some(M=>sa(M.provider)===_&&M.model===a);return o.jsxs("div",{className:"@container",children:[o.jsxs("div",{className:"flex w-full flex-col items-stretch gap-2 @xs:flex-row @xs:items-center",children:[o.jsx("div",{className:"w-full @xs:w-2/5",children:o.jsx(ak,{value:_,onValueChange:N,open:h,onOpenChange:p})}),o.jsx("div",{className:"w-full @xs:w-3/5",children:o.jsx(ok,{llmId:_,value:a,onValueChange:E,open:m,onOpenChange:v})}),o.jsx(ae,{variant:"default",size:"md",onClick:A,disabled:d,className:"text-ui-sm flex items-center gap-1.5 border-0! whitespace-nowrap",title:"Reset to original model",children:o.jsx(z_,{className:"h-3.5 w-3.5"})})]}),L&&o.jsx("div",{className:"p-2 pt-2","data-testid":"agent-metadata-model-stale-warning",children:o.jsx(xn,{variant:"warning",title:"Model not allowed",children:o.jsxs(xn.Message,{children:[o.jsxs("code",{className:"rounded bg-yellow-100 px-1 py-0.5 dark:bg-yellow-900/50",children:[c,"/",a]})," ","is no longer allowed by the admin policy. Pick a different model to save changes."]})})}),P&&!P.connected&&o.jsx("div",{className:"p-2 pt-2",children:o.jsx(xn,{variant:"warning",title:"Provider not connected",children:o.jsxs(xn.Message,{children:["Set the"," ",o.jsx("code",{className:"rounded bg-yellow-100 px-1 py-0.5 dark:bg-yellow-900/50",children:Array.isArray(P.envVar)?P.envVar.join(", "):P.envVar})," ","environment"," ",Array.isArray(P.envVar)&&P.envVar.length>1?"variables":"variable"," to use this provider."]})})})]})};function f5s({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:s,handleInstallTemplate:i,handleVariableChange:a,isLoadingEnvVars:l,isInstalling:c,defaultModelProvider:u,defaultModelId:d,onModelUpdate:f}){return o.jsx(wJ,{children:o.jsxs("div",{className:"mx-auto my-4 grid max-w-[40rem] gap-5 p-4 lg:p-5",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(t1t,{})]}),o.jsx(of,{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(_n,{})," Loading variables..."]}):Object.entries(r).map(([h,p])=>o.jsxs(g.Fragment,{children:[o.jsx(Rm,{name:`env-${h}`,labelIsHidden:!0,label:"Key",value:h,disabled:!0,className:"w-full"}),o.jsx(Rm,{name:h,labelIsHidden:!0,label:"Value",value:p,onChange:a,errorMsg:s.includes(h)?"Value is required.":"",autoComplete:"off",className:"w-full"})]},h))}),o.jsxs("div",{className:"border-border1 relative mt-3.5 border-t pt-12",children:[o.jsx("div",{className:"bg-surface2 text-ui-sm text-neutral3 absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full",children:"And"}),o.jsx("h3",{className:"text-neutral4 text-ui-md",children:"Set AI Model for Template Installation"}),o.jsx("p",{className:"text-neutral3 text-ui-md mt-2 mb-5",children:"This model will be used by the workflow to process and install the template"}),o.jsx(qrn,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(ae,{className:K("flex items-center gap-2 mt-4 justify-center text-ui-md w-full bg-surface5 min-h-10 rounded-lg text-neutral5 hover:bg-surface6 transition-colors","[&>svg]:w-[1.1em] [&_svg]:h-[1.1em] [&_svg]:text-neutral5"),onClick:i,disabled:!t||!u||!d||s.length>0||c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(_n,{className:"h-4 w-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(Kf,{})]})})]})})}function h5s({title:e,description:t,githubUrl:n,isLoading:r,infoData:s,templateSlug:i}){const a=i?`feat/install-template-${i}`:"feat/install-template-[slug]";return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:K("grid mt-5 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(Qx,{}),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",{"bg-surface4 rounded-lg ":r}),children:r?o.jsx(o.Fragment,{children:" "}):t}),!r&&i&&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(Yf,{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(gV,{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:a})]}),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(jY,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(F2e,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function dut(e){switch(e){case"running":return o.jsx(_n,{size:"sm","aria-hidden":!0});case"success":return o.jsx(Mn,{"aria-hidden":!0});case"failed":return o.jsx(Yt,{"aria-hidden":!0});default:return null}}function p5s(){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 m5s({status:e,variant:t}){return t==="plain"?o.jsx("span",{className:K("flex size-4 items-center justify-center self-center [&>svg]:size-4",Vr.colors,{"[&>svg]:text-positive1":e==="success","[&>svg]:text-negative1":e==="failed"}),children:e==="pending"?o.jsx(p5s,{}):dut(e)}):o.jsx("span",{className:K("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",Vr.colors,Vr.transform,Vr.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:dut(e)})}function g5s({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",Vr.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",Vr.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",Vr.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(m5s,{status:e.status,variant:r})]})}function v5s({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:K(n),children:t.map((r,s)=>o.jsx(g5s,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function y5s({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",Vr.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",Vr.colors,Vr.transform,Vr.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(_n,{}):s+1})},r.id))}),o.jsxs("div",{className:K("text-center text-ui-sm text-neutral3",Vr.colors),children:[n," of ",t," steps completed"]})]})}function b5s({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",i=t?.payload?.workflowState,a=t?.payload?.currentStep,l=t?.error,c=i?.steps||{},u=Object.keys(c).length>0,d=v=>v==="input"||v.endsWith(".input")||v.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(v)||/[0-9a-f]{8,}/.test(v)?!1:r?.allSteps?v in r.allSteps:!0,f=Object.entries(c).filter(([v,y])=>d(v)),h=f.length,p=()=>{switch(s){case"initializing":return"Preparing template installation...";case"processing":return`Installing ${e} template`;case"completed":return"Template installation completed!";case"error":return"Template installation failed";default:return"Installing template..."}},m=f.map(([v,y])=>({id:v,status:y?.status,description:y?.description,title:v.charAt(0).toUpperCase()+v.slice(1).replace(/-/g," "),isActive:a?.id===v}));return o.jsxs(wJ,{className:"text-neutral3 mb-5 content-center space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h3",{className:"text-neutral5 text-header-sm font-semibold",children:p()}),(t?.runId||n)&&o.jsxs("div",{className:"text-ui-sm text-neutral3 mt-2",children:["Run ID: ",t?.runId??n]})]}),u&&h>0&&!["error"].includes(s)&&o.jsx("div",{className:"mx-auto w-full max-w-[30rem] px-4",children:o.jsx(y5s,{steps:m})}),l&&s==="error"&&o.jsxs("div",{className:K("rounded-lg text-neutral5 p-4 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(ePn,{}),l||"Something went wrong"]}),u&&o.jsx(v5s,{steps:m,currentStep:a,className:"pb-4"}),!u&&s==="initializing"&&o.jsxs("div",{className:"text-neutral3 text-ui-md grid justify-items-center gap-4 text-center",children:[o.jsx(_n,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function x5s({name:e,installedEntities:t}){return o.jsxs(wJ,{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(t1t,{}),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(F2e,{data:t})]})}function w5s(){const{templateSlug:e}=ur(),[t,n]=bi(),[r,s]=g.useState(""),[i,a]=g.useState(""),[l,c]=g.useState(""),[u,d]=g.useState({}),[f,h]=g.useState([]),[p,m]=g.useState(null),[v,y]=g.useState(!1),[b,x]=g.useState(""),[w,k]=g.useState(!1),[_,C]=g.useState(!1),[T,E]=g.useState([]),{data:N,isLoading:I}=B1r({repoOrSlug:e,owner:"mastra-ai"}),P=l5s?.includes("beta")??!1?"beta":"main",{data:L,isLoading:M}=U1r({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:P}),{data:V,isLoading:q}=V1r(),{mutateAsync:H,isPending:B}=q1r(),{mutateAsync:W}=H1r(),{streamInstall:z,streamResult:G,isStreaming:F}=Z1r(V),{observeInstall:R,streamResult:D,isStreaming:U}=G1r(V);g.useEffect(()=>{const ne=t.get("runId");ne&&!v&&!p&&!F&&!U&&(console.info("🔄 Checking completed run after hot reload:",{runId:ne}),x(ne),W({runId:ne}).then(se=>{const le=se.snapshot;if(le?.status==="success"&&le?.result?.success)y(!0);else if(le?.result?.success===!1)if(le?.result?.validationResults&&!le?.result?.validationResults?.valid&&le?.result?.validationResults?.remainingErrors>0){const{remainingErrors:pe,errors:Se}=le.result.validationResults,Ee=`Template installation completed but ${pe} validation issue${pe>1?"s":""} remain unresolved.`;m(Ee),E(Se||[])}else{const pe=le?.result?.message||le?.result?.error||"Template installation failed";m(typeof pe=="string"?pe:String(pe))}}).catch(se=>{console.error("❌ Failed to fetch run details:",se),m("Failed to retrieve installation status after reload")}))},[t,v,p,F,U,W]),g.useEffect(()=>{const ne=t.get("runId"),se=t.get("resume"),le=t.get("provider");if(ne&&se==="true"&&le&&!F&&!U&&!w&&!_&&V){x(ne),k(!0);try{W({runId:ne}).then(he=>{if(he.snapshot?.status==="running")return R.mutateAsync({runId:ne})}).then(()=>{n(he=>{const pe=new URLSearchParams(he);return pe.delete("resume"),pe})}).catch(he=>{console.error("❌ Failed to resume template installation:",he),he.message?.includes("404")||he.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(he){console.error("❌ Auto-resume failed with error:",he),m("Failed to resume template installation. Please refresh and try again.")}}},[t,e,F,U,w,_,V,W,R,n]);const Q=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],ee=[{key:"tools",label:"Tools",value:N?.tools?.length?N.tools.map(ne=>ne).join(", "):"n/a",icon:o.jsx(eh,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(ne=>ne).join(", "):"n/a",icon:o.jsx(Ma,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(ne=>ne).join(", "):"n/a",icon:o.jsx(z1,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(qg,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(B_,{})}],J=[{...ee[0]},{...ee[1]},{...ee[2]}].filter(ne=>ne.value!=="n/a");g.useEffect(()=>{L&&d(L)},[L]),g.useEffect(()=>{const ne=G||D;ne?.phase==="error"&&ne?.error&&m(typeof ne.error=="string"?ne.error:String(ne.error))},[G?.phase,G?.error,D?.phase,D?.error]);const te=ne=>{s(ne)},re=async ne=>(a(ne.provider),c(ne.modelId),{message:"Model updated successfully"}),ce=async()=>{const ne=Object.entries(u).reduce((se,[le,he])=>(he===""&&se.push(le),se),[]);if(ne.length>0){h(ne);return}if(N){m(null),y(!1),x(""),C(!0);try{const le={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:P,slug:N.slug,variables:u},{runId:he}=await H({});x(he),n(pe=>{const Se=new URLSearchParams(pe);return Se.set("runId",he),Se.set("resume","true"),Se.set("provider",r||"openai"),Se}),await z.mutateAsync({inputData:le,selectedModel:{provider:i,modelId:l},runId:he})}catch(se){C(!1),m(se?.message||"Template installation failed"),console.error("Template installation failed",se)}}},X=ne=>{const{name:se,value:le}=ne.target;le.trim()===""?h(he=>[...he,se]):h(he=>he.filter(pe=>pe!==se)),d(he=>({...he,[se]:le}))};return o.jsx(oi,{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-4",children:[o.jsx(h5s,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:ee,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(F||U)&&o.jsx(b5s,{name:N.title,streamResult:U?D:G,runId:b,workflowInfo:V}),v&&o.jsx(x5s,{name:N.title,installedEntities:J,linkComponent:oo}),p&&o.jsx(c5s,{errorMsg:p,validationErrors:T.length>0?T:G?.validationResults?.errors||D?.validationResults?.errors}),!F&&!U&&!v&&!p&&o.jsx(f5s,{providerOptions:Q,selectedProvider:r,onProviderChange:te,variables:u,setVariables:d,errors:f,setErrors:h,handleInstallTemplate:ce,handleVariableChange:X,isLoadingEnvVars:M||q,isInstalling:B,defaultModelProvider:i,defaultModelId:l,onModelUpdate:re})]})]})})})}const S5s=()=>{const{toolId:e,agentId:t}=ur();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(uOs,{toolId:e,agentId:t})})},k5s=()=>{const{toolId:e}=ur();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(b3s,{toolId:e})})};function O5s(){const{data:e,isLoading:t,error:n}=eg(),[r,s]=g.useState("");return n&&ks(n)?o.jsx(Qn,{children:o.jsx(Gs,{})}):n&&Es(n)?o.jsx(Qn,{children:o.jsx(Fs,{resource:"workflows"})}):n?o.jsx(Qn,{children:o.jsx(Ws,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(Qn,{children:o.jsx(mms,{})}):o.jsxs(Ft,{height:"full",children:[o.jsx(Ft.TopArea,{children:o.jsxs(Ft.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(Wc,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsx(ae,{render:o.jsx(oo,{to:"/workflows/schedules"}),variant:"primary",className:"shrink-0",icon:o.jsx(M0,{}),children:"Schedules"})]})}),o.jsx(pms,{workflows:e||{},isLoading:t,search:r})]})}const C5s={active:"bg-accent1",paused:"bg-accent3"},_5s={active:"text-accent1",paused:"text-accent3"},Hrn=({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 ${C5s[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${_5s[e]}`,children:e})]}),zN=e=>!e||e<=0?"—":new Date(e).toLocaleString(),cD=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 i=Math.floor(s/60);if(i<24)return t>=0?`in ${i}h`:`${i}h ago`;const a=Math.floor(i/24);return t>=0?`in ${a}d`:`${a}d ago`};function Wrn({status:e}){const{icon:t,color:n}=E5s(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 E5s(e){switch(e){case"success":return{icon:o.jsx(Mn,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(Yt,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(_n,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(sG,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(Ls,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx($C,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const fut="auto auto auto auto 1fr";function T5s(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 j5s(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 N5s=3e4,I5s=5*6e4;function A5s({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:i}){const{Link:a,paths:l}=un(),c=p=>!!(n&&p.runId&&p.outcome!=="failed"),u=e.filter(c).length,{containerRef:d,getRowProps:f}=Zc({count:u});let h=-1;return t?o.jsx(Wl,{columns:fut}):e.length===0?o.jsx(Te,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(we,{columns:fut,className:"min-w-0",scrollRef:d,children:[o.jsxs(we.Top,{children:[o.jsx(we.TopCell,{children:"Run"}),o.jsx(we.TopCell,{children:"Status"}),o.jsx(we.TopCell,{children:"Started"}),o.jsx(we.TopCell,{children:"Duration"}),o.jsx(we.TopCell,{children:" "})]}),e.map(p=>{const m=p.actualFireAt-p.scheduledFireAt,v=j5s(m),y=`Scheduled ${zN(p.scheduledFireAt)} — published ${zN(p.actualFireAt)} (drift ${v})`,b=p.outcome==="failed",x=b?p.error:p.run?.error,w=Math.abs(m),k=!b&&w>N5s&&w<=I5s,_=`${p.scheduleId}-${p.runId}-${p.actualFireAt}`,C=c(p);C&&(h+=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:p.runId}),E=o.jsxs(o.Fragment,{children:[o.jsx(we.Cell,{children:T}),o.jsx(we.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[b?o.jsxs("span",{className:"text-ui-sm text-accent2 inline-flex items-center gap-1.5 whitespace-nowrap",children:[o.jsx(Pc,{size:14}),"publish failed"]}):p.run?o.jsx(Wrn,{status:p.run.status}):o.jsx("span",{className:"text-ui-sm text-neutral3 inline-flex items-center gap-1.5 whitespace-nowrap",children:"pending"}),x?o.jsxs(In,{children:[o.jsx(On,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(Pc,{size:14})})}),o.jsx(Cn,{children:x})]}):null]})}),o.jsx(we.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:y,children:cD(p.actualFireAt)}),k?o.jsxs(In,{children:[o.jsx(On,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(Pc,{size:14})})}),o.jsxs(Cn,{children:["Published ",v," after the scheduled fire time"]})]}):null]})}),o.jsx(we.Cell,{children:p.run?o.jsx("span",{children:T5s(p.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(we.Cell,{children:" "})]});return C?o.jsx(we.RowLink,{to:l.workflowRunLink(n,p.runId),LinkComponent:a,...f(h),children:E},_):o.jsx(we.RowStatic,{children:E},_)}),o.jsx(we.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:i})]})}const R5s=e=>{const t=Ye();return yt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},hut=25,P5s=e=>{const t=Ye(),{inView:n,setRef:r}=Sb(),s=yv({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:hut,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<hut))return u.triggers[u.triggers.length-1].actualFireAt},refetchInterval:u=>(u.state.data?.pages.flatMap(h=>h.triggers)??[]).some(h=>h.run?h.run.status==="pending"||h.run.status==="running"||h.run.status==="waiting":h.outcome==="published")?5e3:!1}),i=s.data?.pages.flatMap(u=>u?.triggers??[])??[],{hasNextPage:a,isFetchingNextPage:l,fetchNextPage:c}=s;return g.useEffect(()=>{n&&a&&!l&&c()},[n,a,l,c]),{...s,data:i,setEndOfListElement:r}},$5s=e=>{const t=Ye(),n=kr();return yn({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"]}),Ge.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{Ge.error(r.message)}})};function AB({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(Te,{variant:"ui-xs",className:"text-neutral4 tracking-wide uppercase",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function M5s(){const{scheduleId:e}=ur(),{paths:t}=un(),{data:n,error:r}=R5s(e),{data:s,isLoading:i,error:a,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=P5s(e),d=$5s(e);if(r&&ks(r))return o.jsx(Qn,{children:o.jsx(Gs,{})});if(r&&Es(r))return o.jsx(Qn,{children:o.jsx(Fs,{resource:"schedules"})});if(r)return o.jsx(Qn,{children:o.jsx(Ws,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,h=n?.agentId;return o.jsxs(Ft,{children:[o.jsx(Ft.TopArea,{children:o.jsx(Ft.Row,{className:"justify-end",children:o.jsxs(Ft.Column,{className:"flex justify-end gap-2",children:[o.jsx(ae,{render:o.jsx(oo,{to:t.schedulesLink()}),variant:"ghost",icon:o.jsx(id,{}),children:"Back to schedules"}),f?o.jsx(ae,{icon:o.jsx(Bc,{}),render:o.jsx(oo,{to:t.workflowLink(f)}),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(ae,{onClick:()=>d.mutate(n.status==="active"?"pause":"resume"),disabled:d.isPending,"data-testid":"schedule-toggle-button",children:n.status==="active"?o.jsxs(o.Fragment,{children:[o.jsx(MC,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(bu,{}),"Resume"]})}):null]})})}),n?o.jsxs("div",{className:"grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-4 overflow-hidden",children:[o.jsxs("div",{className:"border-border1 flex h-fit flex-col gap-4 rounded-md border p-4",children:[o.jsx(AB,{label:h?"Agent":"Workflow",children:f?o.jsx(oo,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):h?o.jsx(oo,{to:t.agentLink(h),className:"text-accent1 hover:underline",children:h}):"—"}),o.jsxs(AB,{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(AB,{label:"Status",children:o.jsx(Hrn,{status:n.status})}),o.jsx(AB,{label:"Next fire",children:o.jsx("span",{title:zN(n.nextFireAt),children:cD(n.nextFireAt)})})]}),o.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[o.jsx(Te,{variant:"ui-md",className:"mb-3",children:"Trigger history"}),a?o.jsx(Ws,{title:"Failed to load trigger history",message:a.message}):o.jsx(A5s,{triggers:s??[],isLoading:i,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const put="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function D5s({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=un(),i=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:a,getRowProps:l}=Zc({count:i.length,global:!0});return t?o.jsx(Wl,{columns:put}):o.jsxs(we,{columns:put,className:"min-w-0",scrollRef:a,children:[o.jsxs(we.Top,{children:[o.jsx(we.TopCell,{children:"Target"}),o.jsx(we.TopCell,{children:"Schedule ID"}),o.jsx(we.TopCell,{children:"Cron"}),o.jsx(we.TopCell,{children:"Status"}),o.jsx(we.TopCell,{children:"Next fire"}),o.jsx(we.TopCell,{children:"Last run"})]}),i.length===0&&n?o.jsx(we.NoMatch,{message:"No schedules match your search"}):null,i.length===0&&!n?o.jsx(we.NoMatch,{message:"No schedules configured"}):null,i.map((c,u)=>o.jsxs(we.RowLink,{to:r.scheduleLink(c.id),LinkComponent:s,...l(u),children:[o.jsx(we.NameCell,{children:c.workflowId??c.agentId}),o.jsx(we.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(we.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(we.Cell,{children:o.jsx(Hrn,{status:c.status})}),o.jsx(we.Cell,{children:o.jsx("span",{className:"whitespace-nowrap",title:zN(c.nextFireAt),children:cD(c.nextFireAt)})}),o.jsx(we.Cell,{children:c.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(Wrn,{status:c.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:zN(c.lastFireAt),children:c.lastFireAt?cD(c.lastFireAt):""})]}):c.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:zN(c.lastFireAt),children:cD(c.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},c.id))]})}function L5s({workflowId:e}={}){const{data:t,isLoading:n,error:r}=HEe(e?{workflowId:e}:{}),[s,i]=g.useState("");return r?o.jsx(Ws,{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(Wc,{onSearch:i,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(D5s,{schedules:t??[],isLoading:n,search:s})})]})}function F5s(){const[e]=bi(),t=e.get("workflowId")??void 0,{error:n}=HEe(t?{workflowId:t}:{});return n&&ks(n)?o.jsx(Qn,{children:o.jsx(Gs,{})}):n&&Es(n)?o.jsx(Qn,{children:o.jsx(Fs,{resource:"schedules"})}):o.jsx(Ft,{children:o.jsx("div",{className:"h-full",children:o.jsx(L5s,{workflowId:t})})})}const z5s={"--belt-hue":"var(--warning1)"};function B5s(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function U5s(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 V5s({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:o.jsxs("section",{className:"rounded-studio-panel border-border1/50 bg-surface3 shadow-panel pointer-events-auto relative isolate border","data-testid":"workflow-suspended-steps","aria-label":"Step suspended",children:[o.jsxs("div",{className:"max-h-[calc(100cqh-64px)] overflow-y-auto overscroll-contain rounded-[inherit]",children:[o.jsxs("div",{className:"border-border1/50 bg-surface2 flex items-center justify-between gap-3 border-b px-5 py-4",children:[o.jsxs(Te,{as:"h2",variant:"ui-sm",className:"text-neutral6 flex items-center gap-2 font-medium",children:[o.jsx(St,{children:o.jsx(sG,{})}),"Step suspended"]}),o.jsx(jt,{variant:"orange",emphasis:"muted",children:"Needs input"})]}),e.map(s=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const a=i?.resumeSchema?Pm(m0(i.resumeSchema)):Of(rr(),$f());return o.jsx(q5s,{step:s,stepSchema:a,description:i.description,onResume:r},`${s.runId}-${s.stepId}`)})]}),o.jsx(aMt,{status:"ready",label:"Needs input",className:"before:hidden",style:z5s})]})}function q5s({step:e,stepSchema:t,description:n,onResume:r}){const[s,i]=g.useState(!1),[a,l]=g.useState(!1),c=async u=>{l(!0);try{await r({stepId:e.stepId.split("."),runId:e.runId,resumeData:u})}catch(d){Ge.error(d instanceof Error?d.message:"Error resuming workflow")}finally{l(!1)}};return o.jsxs("div",{className:"[&+&]:border-border1/50 space-y-5 p-5 [&+&]:border-t",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Te,{as:"p",variant:"ui-md",className:"text-neutral6 font-medium break-words",children:e.stepId}),n&&o.jsx(Te,{as:"p",variant:"ui-sm",className:"text-neutral3",children:n})]}),e.suspendPayload!==void 0&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs(Te,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(St,{children:o.jsx(VRn,{})}),"The step is asking"]}),o.jsxs(dl,{open:s,onOpenChange:i,children:[o.jsxs(Zo,{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(St,{children:o.jsx(mr,{className:K("transition-transform text-neutral3",{"transform rotate-90":s})})}),o.jsx(Te,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:U5s(e.suspendPayload,e.stepId)})]}),o.jsx(Te,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:B5s(e.suspendPayload)})]}),o.jsx(Go,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Lr,{value:JSON.stringify(e.suspendPayload,null,2),editable:!1,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs(Te,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(St,{children:o.jsx(ZRn,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(jNe,{schema:t,isSubmitLoading:a,submitButtonLabel:"Resume",submitButtonVariant:"primary",submitButtonIcon:o.jsx(bu,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:c})})]})]})}function H5s({hidden:e}){const{result:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext(mc),{canExecute:i,isLoading:a}=No(),l=o2t(t,r),c=bbr(),u=t?.status==="suspended"&&l.length>0&&!s,d=!a&&i("workflows");return!n||!u||!d?null:o.jsx("div",{hidden:e,"data-testid":"workflow-suspended-overlay",className:"animate-in fade-in-0 slide-in-from-top-2 pointer-events-none absolute top-12 right-2 z-30 w-[380px] max-w-[calc(100%-16px)] duration-300 motion-reduce:animate-none",children:o.jsx(V5s,{suspendedSteps:l,workflow:n,isStreaming:s,onResume:c})},r)}const W5s=e=>e.includes("."),Z5s=e=>e==="input"||e.endsWith(".input"),mut=1;function G5s(e){return e<1e3?`${Number(e.toPrecision(3))}ms`:`${Number((e/1e3).toPrecision(3))}s`}const Zrn=e=>e.status==="running"&&e.endedAt===void 0;function Q5s(e,t){const n=e.startedAt;if(n===void 0||!Number.isFinite(n))return;const r=Zrn(e)?Math.max(t,n):e.endedAt;if(!(r===void 0||!Number.isFinite(r)||r<n))return{start:n,end:r}}function K5s(e,t){const n=Object.entries(e).filter(([l])=>!Z5s(l)).map(([l,c])=>({stepId:l,step:c,span:Q5s(c,t)})).sort((l,c)=>(l.span?.start??1/0)-(c.span?.start??1/0)||l.stepId.localeCompare(c.stepId)),r=n.flatMap(l=>l.span?[l.span]:[]),s=Math.min(...r.map(l=>l.start)),i=Math.max(s,...r.map(l=>l.end)),a=Math.max(i-s,1);return n.map(({stepId:l,step:c,span:u})=>{let d;if(u){const f=u.end-u.start,h=Math.min((u.start-s)/a*100,100-mut),p=Math.min(Math.max(f/a*100,mut),100-h);d={durationMs:f,offsetPct:h,widthPct:p}}return{stepId:l,step:c,status:c.status,timing:d,isRunning:Zrn(c),isNestedEntry:W5s(l)}})}const gut={success:{label:"Completed",icon:Mn,color:"text-positive1",bar:"bg-neutral3/60"},failed:{label:"Failed",icon:zD,color:"text-negative1",bar:"bg-negative1/60"},suspended:{label:"Needs input",icon:MC,color:"text-accent3",bar:"bg-accent3/60"},waiting:{label:"Waiting",icon:DC,color:"text-neutral3",bar:"bg-neutral3/40"},paused:{label:"Paused",icon:MC,color:"text-neutral3",bar:"bg-neutral3/40"},skipped:{label:"Skipped",icon:JPn,color:"text-neutral3",bar:"bg-neutral3/25"},running:{label:"Running",icon:vi,color:"text-accent6",bar:"bg-accent6/60"},canceled:{label:"Canceled",icon:Ls,color:"text-neutral3",bar:"bg-neutral3/40"}},Y5s={label:"Status unavailable",icon:gIn,color:"text-neutral3",bar:"bg-neutral3/25"};function X5s({row:e,isSelected:t,isHovered:n,onSelectStep:r,onHoverStep:s,onOpenInput:i,onOpenOutput:a}){const l=Object.hasOwn(gut,e.status)?gut[e.status]:Y5s,c=l.icon,u=e.stepId.slice(0,e.stepId.lastIndexOf(".")),d=e.isNestedEntry?e.stepId.slice(e.stepId.lastIndexOf(".")+1):e.stepId;return o.jsxs("div",{"data-testid":"workflow-timeline-row","data-workflow-step-key":e.stepId,onMouseEnter:()=>!e.isNestedEntry&&s(e.stepId),onMouseLeave:()=>!e.isNestedEntry&&s(null),className:K("grid grid-cols-[minmax(130px,1fr)_minmax(64px,1fr)_56px_64px] items-center gap-3 rounded-md px-2 py-1","@max-[540px]/workflow-timeline:grid-cols-[minmax(0,1fr)_48px_64px] @max-[540px]/workflow-timeline:gap-x-1.5 @max-[540px]/workflow-timeline:gap-y-1 @max-[540px]/workflow-timeline:py-2",(t||n)&&"bg-surface4"),children:[o.jsxs("button",{type:"button",className:"text-ui-xs text-neutral5 focus-visible:outline-neutral3 flex min-h-9 min-w-0 cursor-pointer items-center gap-2.5 text-left focus-visible:rounded-sm focus-visible:outline-2 focus-visible:outline-offset-2 aria-disabled:cursor-default","aria-disabled":e.isNestedEntry,"aria-pressed":t,onClick:()=>{e.isNestedEntry||r(e.stepId)},title:e.stepId,children:[o.jsx("span",{"aria-label":l.label,className:K("border-border1 bg-surface2 grid size-6 flex-none place-items-center rounded-md border",l.color),children:o.jsx(c,{"aria-hidden":!0,className:K("size-3.5",e.status==="running"&&"motion-safe:animate-spin")})}),o.jsxs("span",{className:"min-w-0",children:[o.jsx("span",{className:"block truncate",children:d}),e.isNestedEntry&&o.jsxs("span",{className:"text-neutral3 text-ui-xs flex min-w-0 items-center gap-1",children:[o.jsx(SCe,{"aria-hidden":!0,className:"size-3 shrink-0"}),o.jsx("span",{className:"truncate",children:u})]})]})]}),o.jsx("div",{className:"bg-surface4 relative h-5 min-w-0 overflow-hidden rounded-sm @max-[540px]/workflow-timeline:col-span-full @max-[540px]/workflow-timeline:row-start-2 @max-[540px]/workflow-timeline:ml-[34px]","aria-hidden":!0,children:e.timing&&o.jsx("div",{"data-testid":"workflow-timeline-bar","data-offset":e.timing.offsetPct,"data-width":e.timing.widthPct,className:K("absolute top-0 h-full min-w-0.5 rounded-sm",l.bar),style:{left:`${e.timing.offsetPct}%`,width:`${e.timing.widthPct}%`}})}),o.jsx("span",{className:"text-neutral3 text-ui-xs text-right whitespace-nowrap tabular-nums",children:e.timing?G5s(e.timing.durationMs):o.jsx("span",{"aria-label":"Timing unavailable",children:"—"})}),o.jsxs("div",{className:"flex items-center",children:[o.jsx(ae,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step input",disabled:e.step.input===void 0,onClick:f=>i(e,f.currentTarget),children:o.jsx(tG,{})}),o.jsx(ae,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step output",disabled:e.step.output===void 0,onClick:f=>a(e,f.currentTarget),children:o.jsx(nG,{})})]})]})}function J5s(){const{steps:e}=LR(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=eQ(),[i,a]=g.useState(()=>Date.now()),[l,c]=g.useState(!0),[u,d]=g.useState(!1),{showData:f}=nk(),h=g.useRef(null),p=K5s(e,i),m=p.some(v=>v.isRunning);return VEt(h,{enabled:m&&!l}),g.useEffect(()=>{if(!m||l)return;const v=setInterval(()=>a(Date.now()),100);return()=>clearInterval(v)},[m,l]),p.length===0?null:o.jsx("div",{"data-testid":"workflow-timeline",className:"relative z-20 shrink-0 px-2 pb-2",children:o.jsxs(dl,{open:!l,onOpenChange:v=>c(!v),className:"border-border1 bg-surface3 @container/workflow-timeline pointer-events-auto overflow-hidden rounded-xl border",children:[o.jsxs("div",{className:"flex items-center",children:[o.jsxs(Zo,{className:"hover:bg-surface4 text-ui-sm text-neutral5 flex min-h-11 min-w-0 flex-1 items-center gap-2 px-3.5 py-2.5","aria-label":l?"Expand timeline":"Collapse timeline",children:[o.jsx("span",{children:o.jsx(PSt,{"aria-hidden":!0,className:"text-neutral3 size-4"})}),o.jsx("span",{children:"Timeline"}),o.jsxs("span",{className:"text-neutral3 text-ui-xs",children:[p.length," events"]}),o.jsx("span",{className:"ml-auto",children:o.jsx($i,{"aria-hidden":!0,className:K("size-4 transition-transform motion-reduce:transition-none",l&&"-rotate-90")})})]}),!l&&o.jsx(ae,{variant:"ghost",size:"icon-sm",tooltip:u?"Restore timeline height":"Enlarge timeline","aria-pressed":u,onClick:()=>d(!u),className:"mr-2 shrink-0",children:u?o.jsx($St,{}):o.jsx(bCe,{})})]}),o.jsx(Go,{children:o.jsx("div",{ref:h,"data-testid":"workflow-timeline-list",className:K("overflow-auto overscroll-contain px-1.5 pb-1.5",u?"max-h-[min(720px,calc(100dvh-112px))]":"max-h-[min(320px,40dvh)]"),children:p.map(v=>o.jsx(X5s,{row:v,isSelected:t===v.stepId,isHovered:n===v.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:(y,b)=>f({type:"step-input",stepId:y.stepId},b),onOpenOutput:(y,b)=>f({type:"step-output",stepId:y.stepId},b)},v.stepId))})})]})})}const e6s=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=nk(),s=nR(),i=r?.type==="data",a=o.jsxs("div",{className:"[container-type:size] relative h-full min-h-0",children:[o.jsx(CHt,{workflowId:e,workflow:t,isLoading:n}),o.jsx(H5s,{hidden:i}),i&&o.jsx("div",{className:"pointer-events-auto absolute top-12 right-2 z-30 flex max-h-[calc(100cqh-64px)] w-[440px] max-w-[calc(100%-16px)] flex-col",children:o.jsx(rU,{})}),o.jsx("div",{className:"pointer-events-none absolute right-0 bottom-0 left-[var(--workflow-left-panel-width,0px)] z-20",children:o.jsx(J5s,{})})]});return s&&r&&!i?o.jsx("div",{className:"h-full min-h-0 overflow-hidden",children:o.jsx(rU,{})}):o.jsxs("div",{className:"relative h-full min-h-0",children:[a,o.jsxs(iDe,{className:"pointer-events-none absolute inset-0 z-30 min-h-0 w-full min-w-0 p-2",children:[o.jsx(I_,{id:"workflow-graph",className:"pointer-events-none min-w-0"}),r&&!i&&o.jsxs(o.Fragment,{children:[o.jsx(bZ,{className:"pointer-events-auto"}),o.jsx(I_,{id:"workflow-step-detail",minSize:300,maxSize:"60%",defaultSize:420,className:"min-w-0",children:o.jsx("div",{className:"rounded-studio-panel border-border1 bg-surface2 pointer-events-auto h-full min-h-0 overflow-hidden border",children:o.jsx(rU,{})})})]})]})]})},vut=()=>{const{workflowId:e}=ur(),{data:t,isLoading:n,error:r}=E5(e);return r&&ks(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Gs,{})}):r&&Es(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{resource:"workflows"})}):o.jsx(e6s,{workflowId:e,workflow:t??void 0,isLoading:n})};function t6s(e,t){if(e==null)return{};var n,r,s=kRt(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function Uke(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 n6s(e){if(Array.isArray(e))return Uke(e)}function r6s(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function s6s(e,t){if(e){if(typeof e=="string")return Uke(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)?Uke(e,t):void 0}}function i6s(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
692
692
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Vke(e){return n6s(e)||r6s(e)||s6s(e)||i6s()}function J3(e){"@babel/helpers - typeof";return J3=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},J3(e)}function a6s(e,t){if(J3(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(J3(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function o6s(e){var t=a6s(e,"string");return J3(t)=="symbol"?t:t+""}function Grn(e,t,n){return(t=o6s(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function yut(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 Yj(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?yut(Object(n),!0).forEach(function(r){Grn(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):yut(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function l6s(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 rde={};function c6s(e){if(e.length===0||e.length===1)return e;var t=e.join(".");return rde[t]||(rde[t]=l6s(e)),rde[t]}function u6s(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2?arguments[2]:void 0,r=e.filter(function(i){return i!=="token"}),s=c6s(r);return s.reduce(function(i,a){return Yj(Yj({},i),n[a])},t)}function but(e){return e.join(" ")}function d6s(e,t){var n=0;return function(r){return n+=1,r.map(function(s,i){return Qrn({node:s,stylesheet:e,useInlineStyles:t,key:"code-segment-".concat(n,"-").concat(i)})})}}function Qrn(e){var t=e.node,n=e.stylesheet,r=e.style,s=r===void 0?{}:r,i=e.useInlineStyles,a=e.key,l=t.properties,c=t.type,u=t.tagName,d=t.value;if(c==="text")return d;if(u){var f=d6s(n,i),h;if(!i)h=Yj(Yj({},l),{},{className:but(l.className)});else{var p=Object.keys(n).reduce(function(b,x){return x.split(".").forEach(function(w){b.includes(w)||b.push(w)}),b},[]),m=l.className&&l.className.includes("token")?["token"]:[],v=l.className&&m.concat(l.className.filter(function(b){return!p.includes(b)}));h=Yj(Yj({},l),{},{className:but(v)||void 0,style:u6s(l.className,Object.assign({},l.style,s),n)})}var y=f(t.children);return Me.createElement(u,a_({key:a},h),y)}}const f6s=(function(e,t){var n=e.listLanguages();return n.indexOf(t)!==-1});var h6s=["language","children","style","customStyle","codeTagProps","useInlineStyles","showLineNumbers","showInlineLineNumbers","startingLineNumber","lineNumberContainerStyle","lineNumberStyle","wrapLines","wrapLongLines","lineProps","renderer","PreTag","CodeTag","code","astGenerator"];function xut(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 NS(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?xut(Object(n),!0).forEach(function(r){Grn(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):xut(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var p6s=/\n/g;function m6s(e){return e.match(p6s)}function g6s(e){var t=e.lines,n=e.startingLineNumber,r=e.style;return t.map(function(s,i){var a=i+n;return Me.createElement("span",{key:"line-".concat(i),className:"react-syntax-highlighter-line-number",style:typeof r=="function"?r(a):r},"".concat(a,`
693
693
  `))})}function v6s(e){var t=e.codeString,n=e.codeStyle,r=e.containerStyle,s=r===void 0?{float:"left",paddingRight:"10px"}:r,i=e.numberStyle,a=i===void 0?{}:i,l=e.startingLineNumber;return Me.createElement("code",{style:Object.assign({},n,s)},g6s({lines:t.replace(/\n$/,"").split(`
694
694
  `),style:a,startingLineNumber:l}))}function y6s(e){return"".concat(e.toString().length,".25em")}function Krn(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 Yrn(e,t,n){var r={display:"inline-block",minWidth:y6s(n),paddingRight:"1em",textAlign:"right",userSelect:"none"},s=typeof e=="function"?e(t):e,i=NS(NS({},r),s);return i}function mU(e){var t=e.children,n=e.lineNumber,r=e.lineNumberStyle,s=e.largestLineNumber,i=e.showInlineLineNumbers,a=e.lineProps,l=a===void 0?{}:a,c=e.className,u=c===void 0?[]:c,d=e.showLineNumbers,f=e.wrapLongLines,h=e.wrapLines,p=h===void 0?!1:h,m=p?NS({},typeof l=="function"?l(n):l):{};if(m.className=m.className?[].concat(Vke(m.className.trim().split(/\s+/)),Vke(u)):u,n&&i){var v=Yrn(r,n,s);t.unshift(Krn(n,v))}return f&d&&(m.style=NS({display:"flex"},m.style)),{type:"element",tagName:"span",properties:m,children:t}}function Xrn(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(mU({children:[s],className:Vke(new Set(t))}));else if(s.children){var i=t.concat(s.properties.className);Xrn(s.children,i).forEach(function(a){return n.push(a)})}}return n}function b6s(e,t,n,r,s,i,a,l,c){var u,d=Xrn(e.value),f=[],h=-1,p=0;function m(_,C){var T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return mU({children:_,lineNumber:C,lineNumberStyle:l,largestLineNumber:a,showInlineLineNumbers:s,lineProps:n,className:T,showLineNumbers:r,wrapLongLines:c,wrapLines:t})}function v(_,C){if(r&&C&&s){var T=Yrn(l,C,a);_.unshift(Krn(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[p],T=C.children[0].value,E=m6s(T);if(E){var N=T.split(`