@mastra/deployer-cloud 1.64.0-alpha.5 → 1.64.0-alpha.6
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.
- package/dist/studio/assets/{core-lanFcZkL.js → core-gZ7e9rsY.js} +1 -1
- package/dist/studio/assets/{index-8xeYD00q.js → index-6o4GQYdR.js} +2 -2
- package/dist/studio/assets/{main-DQ4GlL-n.js → main-VENb-Jfu.js} +4 -4
- package/dist/studio/index.html +1 -1
- package/package.json +5 -5
- package/versions.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./core-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./core-gZ7e9rsY.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 Ma}from"./preload-helper-PPVm8Dsz.js";function hGt(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const s in r)if(s!=="default"&&!(s in e)){const a=Object.getOwnPropertyDescriptor(r,s);a&&Object.defineProperty(e,s,a.get?a:{enumerable:!0,get:()=>r[s]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}var kj=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Fl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var JK={exports:{}},sR={};var z2e;function mGt(){if(z2e)return sR;z2e=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,s,a){var i=null;if(a!==void 0&&(i=""+a),s.key!==void 0&&(i=""+s.key),"key"in s){a={};for(var l in s)l!=="key"&&(a[l]=s[l])}else a=s;return s=a.ref,{$$typeof:e,type:r,key:i,ref:s!==void 0?s:null,props:a}}return sR.Fragment=t,sR.jsx=n,sR.jsxs=n,sR}var B2e;function gGt(){return B2e||(B2e=1,JK.exports=mGt()),JK.exports}var o=gGt(),eX={exports:{}},Wr={},U2e;function vGt(){if(U2e)return Wr;U2e=1;var e={env:{}};var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),i=Symbol.for("react.consumer"),l=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),p=Symbol.for("react.activity"),h=Symbol.iterator;function m(U){return U===null||typeof U!="object"?null:(U=h&&U[h]||U["@@iterator"],typeof U=="function"?U:null)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y=Object.assign,b={};function x(U,$,q){this.props=U,this.context=$,this.refs=b,this.updater=q||v}x.prototype.isReactComponent={},x.prototype.setState=function(U,$){if(typeof U!="object"&&typeof U!="function"&&U!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,U,$,"setState")},x.prototype.forceUpdate=function(U){this.updater.enqueueForceUpdate(this,U,"forceUpdate")};function S(){}S.prototype=x.prototype;function k(U,$,q){this.props=U,this.context=$,this.refs=b,this.updater=q||v}var _=k.prototype=new S;_.constructor=k,y(_,x.prototype),_.isPureReactComponent=!0;var C=Array.isArray;function T(){}var E={H:null,A:null,T:null,S:null},N=Object.prototype.hasOwnProperty;function I(U,$,q){var Z=q.ref;return{$$typeof:t,type:U,key:$,ref:Z!==void 0?Z:null,props:q}}function A(U,$){return I(U.type,$,U.props)}function R(U){return typeof U=="object"&&U!==null&&U.$$typeof===t}function L(U){var $={"=":"=0",":":"=2"};return"$"+U.replace(/[=:]/g,function(q){return $[q]})}var D=/\/+/g;function F(U,$){return typeof U=="object"&&U!==null&&U.key!=null?L(""+U.key):$.toString(36)}function H(U){switch(U.status){case"fulfilled":return U.value;case"rejected":throw U.reason;default:switch(typeof U.status=="string"?U.then(T,T):(U.status="pending",U.then(function($){U.status==="pending"&&(U.status="fulfilled",U.value=$)},function($){U.status==="pending"&&(U.status="rejected",U.reason=$)})),U.status){case"fulfilled":return U.value;case"rejected":throw U.reason}}throw U}function B(U,$,q,Z,Y){var ne=typeof U;(ne==="undefined"||ne==="boolean")&&(U=null);var J=!1;if(U===null)J=!0;else switch(ne){case"bigint":case"string":case"number":J=!0;break;case"object":switch(U.$$typeof){case t:case n:J=!0;break;case f:return J=U._init,B(J(U._payload),$,q,Z,Y)}}if(J)return Y=Y(U),J=Z===""?"."+F(U,0):Z,C(Y)?(q="",J!=null&&(q=J.replace(D,"$&/")+"/"),B(Y,$,q,"",function(le){return le})):Y!=null&&(R(Y)&&(Y=A(Y,q+(Y.key==null||U&&U.key===Y.key?"":(""+Y.key).replace(D,"$&/")+"/")+J)),$.push(Y)),1;J=0;var ee=Z===""?".":Z+":";if(C(U))for(var re=0;re<U.length;re++)Z=U[re],ne=ee+F(Z,re),J+=B(Z,$,q,ne,Y);else if(re=m(U),typeof re=="function")for(U=re.call(U),re=0;!(Z=U.next()).done;)Z=Z.value,ne=ee+F(Z,re++),J+=B(Z,$,q,ne,Y);else if(ne==="object"){if(typeof U.then=="function")return B(H(U),$,q,Z,Y);throw $=String(U),Error("Objects are not valid as a React child (found: "+($==="[object Object]"?"object with keys {"+Object.keys(U).join(", ")+"}":$)+"). If you meant to render a collection of children, use an array instead.")}return J}function z(U,$,q){if(U==null)return U;var Z=[],Y=0;return B(U,Z,"","",function(ne){return $.call(q,ne,Y++)}),Z}function V(U){if(U._status===-1){var $=U._result;$=$(),$.then(function(q){(U._status===0||U._status===-1)&&(U._status=1,U._result=q)},function(q){(U._status===0||U._status===-1)&&(U._status=2,U._result=q)}),U._status===-1&&(U._status=0,U._result=$)}if(U._status===1)return U._result.default;throw U._result}var M=typeof reportError=="function"?reportError:function(U){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var $=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof U=="object"&&U!==null&&typeof U.message=="string"?String(U.message):String(U),error:U});if(!window.dispatchEvent($))return}else if(typeof e=="object"&&typeof e.emit=="function"){e.emit("uncaughtException",U);return}console.error(U)},G={map:z,forEach:function(U,$,q){z(U,function(){$.apply(this,arguments)},q)},count:function(U){var $=0;return z(U,function(){$++}),$},toArray:function(U){return z(U,function($){return $})||[]},only:function(U){if(!R(U))throw Error("React.Children.only expected to receive a single React element child.");return U}};return Wr.Activity=p,Wr.Children=G,Wr.Component=x,Wr.Fragment=r,Wr.Profiler=a,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(U){return E.H.useMemoCache(U)}},Wr.cache=function(U){return function(){return U.apply(null,arguments)}},Wr.cacheSignal=function(){return null},Wr.cloneElement=function(U,$,q){if(U==null)throw Error("The argument must be a React element, but you passed "+U+".");var Z=y({},U.props),Y=U.key;if($!=null)for(ne in $.key!==void 0&&(Y=""+$.key),$)!N.call($,ne)||ne==="key"||ne==="__self"||ne==="__source"||ne==="ref"&&$.ref===void 0||(Z[ne]=$[ne]);var ne=arguments.length-2;if(ne===1)Z.children=q;else if(1<ne){for(var J=Array(ne),ee=0;ee<ne;ee++)J[ee]=arguments[ee+2];Z.children=J}return I(U.type,Y,Z)},Wr.createContext=function(U){return U={$$typeof:l,_currentValue:U,_currentValue2:U,_threadCount:0,Provider:null,Consumer:null},U.Provider=U,U.Consumer={$$typeof:i,_context:U},U},Wr.createElement=function(U,$,q){var Z,Y={},ne=null;if($!=null)for(Z in $.key!==void 0&&(ne=""+$.key),$)N.call($,Z)&&Z!=="key"&&Z!=="__self"&&Z!=="__source"&&(Y[Z]=$[Z]);var J=arguments.length-2;if(J===1)Y.children=q;else if(1<J){for(var ee=Array(J),re=0;re<J;re++)ee[re]=arguments[re+2];Y.children=ee}if(U&&U.defaultProps)for(Z in J=U.defaultProps,J)Y[Z]===void 0&&(Y[Z]=J[Z]);return I(U,ne,Y)},Wr.createRef=function(){return{current:null}},Wr.forwardRef=function(U){return{$$typeof:c,render:U}},Wr.isValidElement=R,Wr.lazy=function(U){return{$$typeof:f,_payload:{_status:-1,_result:U},_init:V}},Wr.memo=function(U,$){return{$$typeof:d,type:U,compare:$===void 0?null:$}},Wr.startTransition=function(U){var $=E.T,q={};E.T=q;try{var Z=U(),Y=E.S;Y!==null&&Y(q,Z),typeof Z=="object"&&Z!==null&&typeof Z.then=="function"&&Z.then(T,M)}catch(ne){M(ne)}finally{$!==null&&q.types!==null&&($.types=q.types),E.T=$}},Wr.unstable_useCacheRefresh=function(){return E.H.useCacheRefresh()},Wr.use=function(U){return E.H.use(U)},Wr.useActionState=function(U,$,q){return E.H.useActionState(U,$,q)},Wr.useCallback=function(U,$){return E.H.useCallback(U,$)},Wr.useContext=function(U){return E.H.useContext(U)},Wr.useDebugValue=function(){},Wr.useDeferredValue=function(U,$){return E.H.useDeferredValue(U,$)},Wr.useEffect=function(U,$){return E.H.useEffect(U,$)},Wr.useEffectEvent=function(U){return E.H.useEffectEvent(U)},Wr.useId=function(){return E.H.useId()},Wr.useImperativeHandle=function(U,$,q){return E.H.useImperativeHandle(U,$,q)},Wr.useInsertionEffect=function(U,$){return E.H.useInsertionEffect(U,$)},Wr.useLayoutEffect=function(U,$){return E.H.useLayoutEffect(U,$)},Wr.useMemo=function(U,$){return E.H.useMemo(U,$)},Wr.useOptimistic=function(U,$){return E.H.useOptimistic(U,$)},Wr.useReducer=function(U,$,q){return E.H.useReducer(U,$,q)},Wr.useRef=function(U){return E.H.useRef(U)},Wr.useState=function(U){return E.H.useState(U)},Wr.useSyncExternalStore=function(U,$,q){return E.H.useSyncExternalStore(U,$,q)},Wr.useTransition=function(){return E.H.useTransition()},Wr.version="19.2.7",Wr}var q2e;function QN(){return q2e||(q2e=1,eX.exports=vGt()),eX.exports}var g=QN();const ze=Fl(g),YN=hGt({__proto__:null,default:ze},[g]);var tX={exports:{}},aR={},nX={exports:{}},rX={};var V2e;function yGt(){return V2e||(V2e=1,(function(e){function t(H,B){var z=H.length;H.push(B);e:for(;0<z;){var V=z-1>>>1,M=H[V];if(0<s(M,B))H[V]=B,H[z]=M,z=V;else break e}}function n(H){return H.length===0?null:H[0]}function r(H){if(H.length===0)return null;var B=H[0],z=H.pop();if(z!==B){H[0]=z;e:for(var V=0,M=H.length,G=M>>>1;V<G;){var U=2*(V+1)-1,$=H[U],q=U+1,Z=H[q];if(0>s($,z))q<M&&0>s(Z,$)?(H[V]=Z,H[q]=z,V=q):(H[V]=$,H[U]=z,V=U);else if(q<M&&0>s(Z,z))H[V]=Z,H[q]=z,V=q;else break e}}return B}function s(H,B){var z=H.sortIndex-B.sortIndex;return z!==0?z:H.id-B.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var a=performance;e.unstable_now=function(){return a.now()}}else{var i=Date,l=i.now();e.unstable_now=function(){return i.now()-l}}var c=[],u=[],d=1,f=null,p=3,h=!1,m=!1,v=!1,y=!1,b=typeof setTimeout=="function"?setTimeout:null,x=typeof clearTimeout=="function"?clearTimeout:null,S=typeof setImmediate<"u"?setImmediate:null;function k(H){for(var B=n(u);B!==null;){if(B.callback===null)r(u);else if(B.startTime<=H)r(u),B.sortIndex=B.expirationTime,t(c,B);else break;B=n(u)}}function _(H){if(v=!1,k(H),!m)if(n(c)!==null)m=!0,C||(C=!0,R());else{var B=n(u);B!==null&&F(_,B.startTime-H)}}var C=!1,T=-1,E=5,N=-1;function I(){return y?!0:!(e.unstable_now()-N<E)}function A(){if(y=!1,C){var H=e.unstable_now();N=H;var B=!0;try{e:{m=!1,v&&(v=!1,x(T),T=-1),h=!0;var z=p;try{t:{for(k(H),f=n(c);f!==null&&!(f.expirationTime>H&&I());){var V=f.callback;if(typeof V=="function"){f.callback=null,p=f.priorityLevel;var M=V(f.expirationTime<=H);if(H=e.unstable_now(),typeof M=="function"){f.callback=M,k(H),B=!0;break t}f===n(c)&&r(c),k(H)}else r(c);f=n(c)}if(f!==null)B=!0;else{var G=n(u);G!==null&&F(_,G.startTime-H),B=!1}}break e}finally{f=null,p=z,h=!1}B=void 0}}finally{B?R():C=!1}}}var R;if(typeof S=="function")R=function(){S(A)};else if(typeof MessageChannel<"u"){var L=new MessageChannel,D=L.port2;L.port1.onmessage=A,R=function(){D.postMessage(null)}}else R=function(){b(A,0)};function F(H,B){T=b(function(){H(e.unstable_now())},B)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(H){H.callback=null},e.unstable_forceFrameRate=function(H){0>H||125<H?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):E=0<H?Math.floor(1e3/H):5},e.unstable_getCurrentPriorityLevel=function(){return p},e.unstable_next=function(H){switch(p){case 1:case 2:case 3:var B=3;break;default:B=p}var z=p;p=B;try{return H()}finally{p=z}},e.unstable_requestPaint=function(){y=!0},e.unstable_runWithPriority=function(H,B){switch(H){case 1:case 2:case 3:case 4:case 5:break;default:H=3}var z=p;p=H;try{return B()}finally{p=z}},e.unstable_scheduleCallback=function(H,B,z){var V=e.unstable_now();switch(typeof z=="object"&&z!==null?(z=z.delay,z=typeof z=="number"&&0<z?V+z:V):z=V,H){case 1:var M=-1;break;case 2:M=250;break;case 5:M=1073741823;break;case 4:M=1e4;break;default:M=5e3}return M=z+M,H={id:d++,callback:B,priorityLevel:H,startTime:z,expirationTime:M,sortIndex:-1},z>V?(H.sortIndex=z,t(u,H),n(c)===null&&H===n(u)&&(v?(x(T),T=-1):v=!0,F(_,z-V))):(H.sortIndex=M,t(c,H),m||h||(m=!0,C||(C=!0,R()))),H},e.unstable_shouldYield=I,e.unstable_wrapCallback=function(H){var B=p;return function(){var z=p;p=B;try{return H.apply(this,arguments)}finally{p=z}}}})(rX)),rX}var H2e;function bGt(){return H2e||(H2e=1,nX.exports=yGt()),nX.exports}var sX={exports:{}},Iu={};var W2e;function xGt(){if(W2e)return Iu;W2e=1;var e=QN();function t(c){var u="https://react.dev/errors/"+c;if(1<arguments.length){u+="?args[]="+encodeURIComponent(arguments[1]);for(var d=2;d<arguments.length;d++)u+="&args[]="+encodeURIComponent(arguments[d])}return"Minified React error #"+c+"; visit "+u+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function n(){}var r={d:{f:n,r:function(){throw Error(t(522))},D:n,C:n,L:n,m:n,X:n,S:n,M:n},p:0,findDOMNode:null},s=Symbol.for("react.portal");function a(c,u,d){var f=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:s,key:f==null?null:""+f,children:c,containerInfo:u,implementation:d}}var i=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function l(c,u){if(c==="font")return"";if(typeof u=="string")return u==="use-credentials"?u:""}return Iu.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,Iu.createPortal=function(c,u){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!u||u.nodeType!==1&&u.nodeType!==9&&u.nodeType!==11)throw Error(t(299));return a(c,u,null,d)},Iu.flushSync=function(c){var u=i.T,d=r.p;try{if(i.T=null,r.p=2,c)return c()}finally{i.T=u,r.p=d,r.d.f()}},Iu.preconnect=function(c,u){typeof c=="string"&&(u?(u=u.crossOrigin,u=typeof u=="string"?u==="use-credentials"?u:"":void 0):u=null,r.d.C(c,u))},Iu.prefetchDNS=function(c){typeof c=="string"&&r.d.D(c)},Iu.preinit=function(c,u){if(typeof c=="string"&&u&&typeof u.as=="string"){var d=u.as,f=l(d,u.crossOrigin),p=typeof u.integrity=="string"?u.integrity:void 0,h=typeof u.fetchPriority=="string"?u.fetchPriority:void 0;d==="style"?r.d.S(c,typeof u.precedence=="string"?u.precedence:void 0,{crossOrigin:f,integrity:p,fetchPriority:h}):d==="script"&&r.d.X(c,{crossOrigin:f,integrity:p,fetchPriority:h,nonce:typeof u.nonce=="string"?u.nonce:void 0})}},Iu.preinitModule=function(c,u){if(typeof c=="string")if(typeof u=="object"&&u!==null){if(u.as==null||u.as==="script"){var d=l(u.as,u.crossOrigin);r.d.M(c,{crossOrigin:d,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0})}}else u==null&&r.d.M(c)},Iu.preload=function(c,u){if(typeof c=="string"&&typeof u=="object"&&u!==null&&typeof u.as=="string"){var d=u.as,f=l(d,u.crossOrigin);r.d.L(c,d,{crossOrigin:f,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0,type:typeof u.type=="string"?u.type:void 0,fetchPriority:typeof u.fetchPriority=="string"?u.fetchPriority:void 0,referrerPolicy:typeof u.referrerPolicy=="string"?u.referrerPolicy:void 0,imageSrcSet:typeof u.imageSrcSet=="string"?u.imageSrcSet:void 0,imageSizes:typeof u.imageSizes=="string"?u.imageSizes:void 0,media:typeof u.media=="string"?u.media:void 0})}},Iu.preloadModule=function(c,u){if(typeof c=="string")if(u){var d=l(u.as,u.crossOrigin);r.d.m(c,{as:typeof u.as=="string"&&u.as!=="script"?u.as:void 0,crossOrigin:d,integrity:typeof u.integrity=="string"?u.integrity:void 0})}else r.d.m(c)},Iu.requestFormReset=function(c){r.d.r(c)},Iu.unstable_batchedUpdates=function(c,u){return c(u)},Iu.useFormState=function(c,u,d){return i.H.useFormState(c,u,d)},Iu.useFormStatus=function(){return i.H.useHostTransitionStatus()},Iu.version="19.2.7",Iu}var Z2e;function _lt(){if(Z2e)return sX.exports;Z2e=1;function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),sX.exports=xGt(),sX.exports}var G2e;function wGt(){if(G2e)return aR;G2e=1;var e={env:{}};var t=bGt(),n=QN(),r=_lt();function s(w){var O="https://react.dev/errors/"+w;if(1<arguments.length){O+="?args[]="+encodeURIComponent(arguments[1]);for(var j=2;j<arguments.length;j++)O+="&args[]="+encodeURIComponent(arguments[j])}return"Minified React error #"+w+"; visit "+O+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function a(w){return!(!w||w.nodeType!==1&&w.nodeType!==9&&w.nodeType!==11)}function i(w){var O=w,j=w;if(w.alternate)for(;O.return;)O=O.return;else{w=O;do O=w,(O.flags&4098)!==0&&(j=O.return),w=O.return;while(w)}return O.tag===3?j:null}function l(w){if(w.tag===13){var O=w.memoizedState;if(O===null&&(w=w.alternate,w!==null&&(O=w.memoizedState)),O!==null)return O.dehydrated}return null}function c(w){if(w.tag===31){var O=w.memoizedState;if(O===null&&(w=w.alternate,w!==null&&(O=w.memoizedState)),O!==null)return O.dehydrated}return null}function u(w){if(i(w)!==w)throw Error(s(188))}function d(w){var O=w.alternate;if(!O){if(O=i(w),O===null)throw Error(s(188));return O!==w?null:w}for(var j=w,P=O;;){var W=j.return;if(W===null)break;var Q=W.alternate;if(Q===null){if(P=W.return,P!==null){j=P;continue}break}if(W.child===Q.child){for(Q=W.child;Q;){if(Q===j)return u(W),w;if(Q===P)return u(W),O;Q=Q.sibling}throw Error(s(188))}if(j.return!==P.return)j=W,P=Q;else{for(var ie=!1,Oe=W.child;Oe;){if(Oe===j){ie=!0,j=W,P=Q;break}if(Oe===P){ie=!0,P=W,j=Q;break}Oe=Oe.sibling}if(!ie){for(Oe=Q.child;Oe;){if(Oe===j){ie=!0,j=Q,P=W;break}if(Oe===P){ie=!0,P=Q,j=W;break}Oe=Oe.sibling}if(!ie)throw Error(s(189))}}if(j.alternate!==P)throw Error(s(190))}if(j.tag!==3)throw Error(s(188));return j.stateNode.current===j?w:O}function f(w){var O=w.tag;if(O===5||O===26||O===27||O===6)return w;for(w=w.child;w!==null;){if(O=f(w),O!==null)return O;w=w.sibling}return null}var p=Object.assign,h=Symbol.for("react.element"),m=Symbol.for("react.transitional.element"),v=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),b=Symbol.for("react.strict_mode"),x=Symbol.for("react.profiler"),S=Symbol.for("react.consumer"),k=Symbol.for("react.context"),_=Symbol.for("react.forward_ref"),C=Symbol.for("react.suspense"),T=Symbol.for("react.suspense_list"),E=Symbol.for("react.memo"),N=Symbol.for("react.lazy"),I=Symbol.for("react.activity"),A=Symbol.for("react.memo_cache_sentinel"),R=Symbol.iterator;function L(w){return w===null||typeof w!="object"?null:(w=R&&w[R]||w["@@iterator"],typeof w=="function"?w:null)}var D=Symbol.for("react.client.reference");function F(w){if(w==null)return null;if(typeof w=="function")return w.$$typeof===D?null:w.displayName||w.name||null;if(typeof w=="string")return w;switch(w){case y:return"Fragment";case x:return"Profiler";case b:return"StrictMode";case C:return"Suspense";case T:return"SuspenseList";case I:return"Activity"}if(typeof w=="object")switch(w.$$typeof){case v:return"Portal";case k:return w.displayName||"Context";case S:return(w._context.displayName||"Context")+".Consumer";case _:var O=w.render;return w=w.displayName,w||(w=O.displayName||O.name||"",w=w!==""?"ForwardRef("+w+")":"ForwardRef"),w;case E:return O=w.displayName||null,O!==null?O:F(w.type)||"Memo";case N:O=w._payload,w=w._init;try{return F(w(O))}catch{}}return null}var H=Array.isArray,B=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,z=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,V={pending:!1,data:null,method:null,action:null},M=[],G=-1;function U(w){return{current:w}}function $(w){0>G||(w.current=M[G],M[G]=null,G--)}function q(w,O){G++,M[G]=w.current,w.current=O}var Z=U(null),Y=U(null),ne=U(null),J=U(null);function ee(w,O){switch(q(ne,O),q(Y,w),q(Z,null),O.nodeType){case 9:case 11:w=(w=O.documentElement)&&(w=w.namespaceURI)?c2e(w):0;break;default:if(w=O.tagName,O=O.namespaceURI)O=c2e(O),w=u2e(O,w);else switch(w){case"svg":w=1;break;case"math":w=2;break;default:w=0}}$(Z),q(Z,w)}function re(){$(Z),$(Y),$(ne)}function le(w){w.memoizedState!==null&&q(J,w);var O=Z.current,j=u2e(O,w.type);O!==j&&(q(Y,w),q(Z,j))}function X(w){Y.current===w&&($(Z),$(Y)),J.current===w&&($(J),eR._currentValue=V)}var te,se;function pe(w){if(te===void 0)try{throw Error()}catch(j){var O=j.stack.trim().match(/\n( *(at )?)/);te=O&&O[1]||"",se=-1<j.stack.indexOf(`
|
|
3
3
|
at`)?" (<anonymous>)":-1<j.stack.indexOf("@")?"@unknown:0:0":""}return`
|
|
4
4
|
`+te+w+se}var ce=!1;function Se(w,O){if(!w||ce)return"";ce=!0;var j=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var P={DetermineComponentFrameRoot:function(){try{if(O){var It=function(){throw Error()};if(Object.defineProperty(It.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(It,[])}catch(ht){var lt=ht}Reflect.construct(w,[],It)}else{try{It.call()}catch(ht){lt=ht}w.call(It.prototype)}}else{try{throw Error()}catch(ht){lt=ht}(It=w())&&typeof It.catch=="function"&&It.catch(function(){})}}catch(ht){if(ht&<&&typeof ht.stack=="string")return[ht.stack,lt.stack]}return[null,null]}};P.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var W=Object.getOwnPropertyDescriptor(P.DetermineComponentFrameRoot,"name");W&&W.configurable&&Object.defineProperty(P.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var Q=P.DetermineComponentFrameRoot(),ie=Q[0],Oe=Q[1];if(ie&&Oe){var qe=ie.split(`
|
|
@@ -231,7 +231,7 @@ attempted value: ${i}
|
|
|
231
231
|
\${}
|
|
232
232
|
}
|
|
233
233
|
}`,{label:"class",detail:"definition",type:"keyword"}),uf('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),uf('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],pSt=Hke.concat([uf("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),uf("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),uf("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),F8e=new v0t,hSt=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function NR(e){return(t,n)=>{let r=t.node.getChild("VariableDefinition");return r&&n(r,e),!0}}const vUn=["FunctionDeclaration"],yUn={FunctionDeclaration:NR("function"),ClassDeclaration:NR("class"),ClassExpression:()=>!0,EnumDeclaration:NR("constant"),TypeAliasDeclaration:NR("type"),NamespaceDeclaration:NR("namespace"),VariableDefinition(e,t){e.matchContext(vUn)||t(e,"variable")},TypeDefinition(e,t){t(e,"type")},__proto__:null};function mSt(e,t){let n=F8e.get(t);if(n)return n;let r=[],s=!0;function a(i,l){let c=e.sliceString(i.from,i.to);r.push({label:c,type:l})}return t.cursor(Da.IncludeAnonymous).iterate(i=>{if(s)s=!1;else if(i.name){let l=yUn[i.name];if(l&&l(i,a)||hSt.has(i.name))return!1}else if(i.to-i.from>8192){for(let l of mSt(e,i.node))r.push(l);return!1}}),F8e.set(t,r),r}const FB=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,Wke=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function gSt(e){let t=pi(e.state).resolveInner(e.pos,-1);if(Wke.indexOf(t.name)>-1)return null;let n=t.name=="VariableName"||t.to-t.from<20&&FB.test(e.state.sliceDoc(t.from,t.to));if(!n&&!e.explicit)return null;let r=[];for(let s=t;s;s=s.parent)hSt.has(s.name)&&(r=r.concat(mSt(e.state.doc,s)));return{options:r,from:n?t.from:e.pos,validFor:FB}}function qee(e,t,n){var r;let s=[];for(;;){let a=t.firstChild,i;if(a?.name=="VariableName")return s.push(e(a)),{path:s.reverse(),name:n};if(a?.name=="MemberExpression"&&((r=i=a.lastChild)===null||r===void 0?void 0:r.name)=="PropertyName")s.push(e(i)),t=a;else return null}}function vSt(e){let t=r=>e.state.doc.sliceString(r.from,r.to),n=pi(e.state).resolveInner(e.pos,-1);return n.name=="PropertyName"?qee(t,n.parent,t(n)):(n.name=="."||n.name=="?.")&&n.parent.name=="MemberExpression"?qee(t,n.parent,""):Wke.indexOf(n.name)>-1?null:n.name=="VariableName"||n.to-n.from<20&&FB.test(t(n))?{path:[],name:t(n)}:n.name=="MemberExpression"?qee(t,n,""):e.explicit?{path:[],name:""}:null}function bUn(e,t){let n=e,r=[],s=new Set;for(let a=0;;a++){for(let l of(Object.getOwnPropertyNames||Object.keys)(e)){if(!/^[a-zA-Z_$\xaa-\uffdc][\w$\xaa-\uffdc]*$/.test(l)||s.has(l))continue;s.add(l);let c;try{c=n[l]}catch{continue}r.push({label:l,type:typeof c=="function"?/^[A-Z]/.test(l)?"class":t?"function":"method":t?"variable":"property",boost:-a})}let i=Object.getPrototypeOf(e);if(!i)return r;e=i}}function xUn(e){let t=new Map;return n=>{let r=vSt(n);if(!r)return null;let s=e;for(let i of r.path)if(s=s[i],!s)return null;let a=t.get(s);return a||t.set(s,a=bUn(s,!r.path.length)),{from:n.pos-r.name.length,options:a,validFor:FB}}}const sm=UO.define({name:"javascript",parser:gUn.configure({props:[J_.add({IfStatement:nj({except:/^\s*({|else\b)/}),TryStatement:nj({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:h8n,SwitchBody:e=>{let t=e.textAfter,n=/^\s*\}/.test(t),r=/^\s*(case|default)\b/.test(t);return e.baseIndent+(n?0:r?1:2)*e.unit},Block:p8n({closing:"}"}),ArrowFunction:e=>e.baseIndent+e.unit,"TemplateString BlockComment":()=>null,"Statement Property":nj({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}}),eC.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":_ke,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:"$"}}),ySt={test:e=>/^JSX/.test(e.name),facet:YH({commentTokens:{block:{open:"{/*",close:"*/}"}}})},Zke=sm.configure({dialect:"ts"},"typescript"),Gke=sm.configure({dialect:"jsx",props:[Ske.add(e=>e.isTop?[ySt]:void 0)]}),Qke=sm.configure({dialect:"jsx ts",props:[Ske.add(e=>e.isTop?[ySt]:void 0)]},"typescript");let bSt=e=>({label:e,type:"keyword"});const xSt="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(bSt),wUn=xSt.concat(["declare","implements","private","protected","public"].map(bSt));function zB(e={}){let t=e.jsx?e.typescript?Qke:Gke:e.typescript?Zke:sm,n=e.typescript?pSt.concat(wUn):Hke.concat(xSt);return new VO(t,[sm.data.of({autocomplete:J8n(Wke,y1t(n))}),sm.data.of({autocomplete:gSt}),e.jsx?wSt:[]])}function SUn(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 z8e(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 kUn=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),wSt=Rt.inputHandler.of((e,t,n,r,s)=>{if((kUn?e.composing:e.compositionStarted)||e.state.readOnly||t!=n||r!=">"&&r!="/"||!sm.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:i}=a,l=i.changeByRange(c=>{var u;let{head:d}=c,f=pi(i).resolveInner(d-1,-1),p;if(f.name=="JSXStartTag"&&(f=f.parent),!(i.doc.sliceString(d-1,d)!=r||f.name=="JSXAttributeValue"&&f.to>d)){if(r==">"&&f.name=="JSXFragmentTag")return{range:c,changes:{from:d,insert:"</>"}};if(r=="/"&&f.name=="JSXStartCloseTag"){let h=f.parent,m=h.parent;if(m&&h.from==d-2&&((p=z8e(i.doc,m.firstChild,d))||((u=m.firstChild)===null||u===void 0?void 0:u.name)=="JSXFragmentTag")){let v=`${p}>`;return{range:wt.cursor(d+v.length,-1),changes:{from:d,insert:v}}}}else if(r==">"){let h=SUn(f);if(h&&h.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(i.doc.sliceString(d,d+2))&&(p=z8e(i.doc,h,d)))return{range:c,changes:{from:d,insert:`</${p}>`}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,i.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)});function OUn(e,t){return t||(t={parserOptions:{ecmaVersion:2019,sourceType:"module"},env:{browser:!0,node:!0,es6:!0,es2015:!0,es2017:!0,es2020:!0},rules:{}},e.getRules().forEach((n,r)=>{var s;!((s=n.meta.docs)===null||s===void 0)&&s.recommended&&(t.rules[r]=2)})),n=>{let{state:r}=n,s=[];for(let{from:a,to:i}of sm.findRegions(r)){let l=r.doc.lineAt(a),c={line:l.number-1,col:a-l.from,pos:a};for(let u of e.verify(r.sliceDoc(a,i),t))s.push(_Un(u,r.doc,c))}return s}}function B8e(e,t,n,r){return n.line(e+r.line).from+t+(e==1?r.col-1:-1)}function _Un(e,t,n){let r=B8e(e.line,e.column,t,n),s={from:r,to:e.endLine!=null&&e.endColumn!=1?B8e(e.endLine,e.endColumn,t,n):r,message:e.message,source:e.ruleId?"eslint:"+e.ruleId:"eslint",severity:e.severity==1?"warning":"error"};if(e.fix){let{range:a,text:i}=e.fix,l=a[0]+n.pos-r,c=a[1]+n.pos-r;s.actions=[{name:"fix",apply(u,d){u.dispatch({changes:{from:d+l,to:d+c,insert:i},scrollIntoView:!0})}}]}return s}const uF=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:wSt,completionPath:vSt,esLint:OUn,javascript:zB,javascriptLanguage:sm,jsxLanguage:Gke,localCompletionSource:gSt,scopeCompletionSource:xUn,snippets:Hke,tsxLanguage:Qke,typescriptLanguage:Zke,typescriptSnippets:pSt},Symbol.toStringTag,{value:"Module"})),IR=["_blank","_self","_top","_parent"],Vee=["ascii","utf-8","utf-16","latin1","latin1"],Hee=["get","post","put","delete"],Wee=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],cp=["true","false"],Xn={},CUn={a:{attrs:{href:null,ping:null,type:null,media:null,target:IR,hreflang:null}},abbr:Xn,address:Xn,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:Xn,aside:Xn,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:Xn,base:{attrs:{href:null,target:IR}},bdi:Xn,bdo:Xn,blockquote:{attrs:{cite:null}},body:Xn,br:Xn,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:Wee,formmethod:Hee,formnovalidate:["novalidate"],formtarget:IR,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:Xn,center:Xn,cite:Xn,code:Xn,col:{attrs:{span:null}},colgroup:{attrs:{span:null}},command:{attrs:{type:["command","checkbox","radio"],label:null,icon:null,radiogroup:null,command:null,title:null,disabled:["disabled"],checked:["checked"]}},data:{attrs:{value:null}},datagrid:{attrs:{disabled:["disabled"],multiple:["multiple"]}},datalist:{attrs:{data:null}},dd:Xn,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:Xn,div:Xn,dl:Xn,dt:Xn,em:Xn,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:Xn,figure:Xn,footer:Xn,form:{attrs:{action:null,name:null,"accept-charset":Vee,autocomplete:["on","off"],enctype:Wee,method:Hee,novalidate:["novalidate"],target:IR}},h1:Xn,h2:Xn,h3:Xn,h4:Xn,h5:Xn,h6:Xn,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:Xn,hgroup:Xn,hr:Xn,html:{attrs:{manifest:null}},i:Xn,iframe:{attrs:{src:null,srcdoc:null,name:null,width:null,height:null,sandbox:["allow-top-navigation","allow-same-origin","allow-forms","allow-scripts"],seamless:["seamless"]}},img:{attrs:{alt:null,src:null,ismap:null,usemap:null,width:null,height:null,crossorigin:["anonymous","use-credentials"]}},input:{attrs:{alt:null,dirname:null,form:null,formaction:null,height:null,list:null,max:null,maxlength:null,min:null,name:null,pattern:null,placeholder:null,size:null,src:null,step:null,value:null,width:null,accept:["audio/*","video/*","image/*"],autocomplete:["on","off"],autofocus:["autofocus"],checked:["checked"],disabled:["disabled"],formenctype:Wee,formmethod:Hee,formnovalidate:["novalidate"],formtarget:IR,multiple:["multiple"],readonly:["readonly"],required:["required"],type:["hidden","text","search","tel","url","email","password","datetime","date","month","week","time","datetime-local","number","range","color","checkbox","radio","file","submit","image","reset","button"]}},ins:{attrs:{cite:null,datetime:null}},kbd:Xn,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:Xn,li:{attrs:{value:null}},link:{attrs:{href:null,type:null,hreflang:null,media:null,sizes:["all","16x16","16x16 32x32","16x16 32x32 64x64"]}},map:{attrs:{name:null}},mark:Xn,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:Vee,name:["viewport","application-name","author","description","generator","keywords"],"http-equiv":["content-language","content-type","default-style","refresh"]}},meter:{attrs:{value:null,min:null,low:null,high:null,max:null,optimum:null}},nav:Xn,noscript:Xn,object:{attrs:{data:null,type:null,name:null,usemap:null,form:null,width:null,height:null,typemustmatch:["typemustmatch"]}},ol:{attrs:{reversed:["reversed"],start:null,type:["1","a","A","i","I"]},children:["li","script","template","ul","ol"]},optgroup:{attrs:{disabled:["disabled"],label:null}},option:{attrs:{disabled:["disabled"],label:null,selected:["selected"],value:null}},output:{attrs:{for:null,form:null,name:null}},p:Xn,param:{attrs:{name:null,value:null}},pre:Xn,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:Xn,rt:Xn,ruby:Xn,samp:Xn,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:Vee}},section:Xn,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:Xn,source:{attrs:{src:null,type:null,media:null}},span:Xn,strong:Xn,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:Xn,summary:Xn,sup:Xn,table:Xn,tbody:Xn,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:Xn,textarea:{attrs:{dirname:null,form:null,maxlength:null,name:null,placeholder:null,rows:null,cols:null,autofocus:["autofocus"],disabled:["disabled"],readonly:["readonly"],required:["required"],wrap:["soft","hard"]}},tfoot:Xn,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:Xn,time:{attrs:{datetime:null}},title:Xn,tr:Xn,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:Xn,video:{attrs:{src:null,poster:null,width:null,height:null,crossorigin:["anonymous","use-credentials"],preload:["auto","metadata","none"],autoplay:["autoplay"],mediagroup:["movie"],muted:["muted"],controls:["controls"]}},wbr:Xn},SSt={accesskey:null,class:null,contenteditable:cp,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:cp,autocorrect:cp,autocapitalize:cp,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":cp,"aria-autocomplete":["inline","list","both","none"],"aria-busy":cp,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":cp,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":cp,"aria-hidden":cp,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":cp,"aria-multiselectable":cp,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":cp,"aria-relevant":null,"aria-required":cp,"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},kSt="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 kSt)SSt[e]=null;class EM{constructor(t,n){this.tags={...CUn,...t},this.globalAttrs={...SSt,...n},this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}}EM.default=new EM;function Xj(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 Jj(e,t=!1){for(;e;e=e.parent)if(e.name=="Element")if(t)t=!1;else return e;return null}function OSt(e,t,n){let r=n.tags[Xj(e,Jj(t))];return r?.children||n.allTags}function Yke(e,t){let n=[];for(let r=Jj(t);r&&!r.type.isTop;r=Jj(r.parent)){let s=Xj(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 _St=/^[:\-\.\w\u00b7-\uffff]*$/;function U8e(e,t,n,r,s){let a=/\s*>/.test(e.sliceDoc(s,s+5))?"":">",i=Jj(n,n.name=="StartTag"||n.name=="TagName");return{from:r,to:s,options:OSt(e.doc,i,t).map(l=>({label:l,type:"type"})).concat(Yke(e.doc,n).map((l,c)=>({label:"/"+l,apply:"/"+l+a,type:"type",boost:99-c}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function q8e(e,t,n,r){let s=/\s*>/.test(e.sliceDoc(r,r+5))?"":">";return{from:n,to:r,options:Yke(e.doc,t).map((a,i)=>({label:a,apply:a+s,type:"type",boost:99-i})),validFor:_St}}function EUn(e,t,n,r){let s=[],a=0;for(let i of OSt(e.doc,n,t))s.push({label:"<"+i,type:"type"});for(let i of Yke(e.doc,n))s.push({label:"</"+i+">",type:"type",boost:99-a++});return{from:r,to:r,options:s,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function TUn(e,t,n,r,s){let a=Jj(n),i=a?t.tags[Xj(e.doc,a)]:null,l=i&&i.attrs?Object.keys(i.attrs):[],c=i&&i.globalAttrs===!1?l:l.length?l.concat(t.globalAttrNames):t.globalAttrNames;return{from:r,to:s,options:c.map(u=>({label:u,type:"property"})),validFor:_St}}function jUn(e,t,n,r,s){var a;let i=(a=n.parent)===null||a===void 0?void 0:a.getChild("AttributeName"),l=[],c;if(i){let u=e.sliceDoc(i.from,i.to),d=t.globalAttrs[u];if(!d){let f=Jj(n),p=f?t.tags[Xj(e.doc,f)]:null;d=p?.attrs&&p.attrs[u]}if(d){let f=e.sliceDoc(r,s).toLowerCase(),p='"',h='"';/^['"]/.test(f)?(c=f[0]=='"'?/^[^"]*$/:/^[^']*$/,p="",h=e.sliceDoc(s,s+1)==f[0]?"":f[0],f=f.slice(1),r++):c=/^[^\s<>='"]*$/;for(let m of d)l.push({label:m,apply:p+m+h,type:"constant"})}}return{from:r,to:s,options:l,validFor:c}}function CSt(e,t){let{state:n,pos:r}=t,s=pi(n).resolveInner(r,-1),a=s.resolve(r);for(let i=r,l;a==s&&(l=s.childBefore(i));){let c=l.lastChild;if(!c||!c.type.isError||c.from<c.to)break;a=s=l,i=c.from}return s.name=="TagName"?s.parent&&/CloseTag$/.test(s.parent.name)?q8e(n,s,s.from,r):U8e(n,e,s,s.from,r):s.name=="StartTag"||s.name=="IncompleteTag"?U8e(n,e,s,r,r):s.name=="StartCloseTag"||s.name=="IncompleteCloseTag"?q8e(n,s,r,r):s.name=="OpenTag"||s.name=="SelfClosingTag"||s.name=="AttributeName"?TUn(n,e,s,s.name=="AttributeName"?s.from:r,r):s.name=="Is"||s.name=="AttributeValue"||s.name=="UnquotedAttributeValue"?jUn(n,e,s,s.name=="Is"?r:s.from,r):t.explicit&&(a.name=="Element"||a.name=="Text"||a.name=="Document")?EUn(n,e,s,r):null}function NUn(e){return CSt(EM.default,e)}function IUn(e){let{extraTags:t,extraGlobalAttributes:n}=e,r=n||t?new EM(t,n):EM.default;return s=>CSt(r,s)}const AUn=sm.parser.configure({top:"SingleExpression"}),ESt=[{tag:"script",attrs:e=>e.type=="text/typescript"||e.lang=="ts",parser:Zke.parser},{tag:"script",attrs:e=>e.type=="text/babel"||e.type=="text/jsx",parser:Gke.parser},{tag:"script",attrs:e=>e.type=="text/typescript-jsx",parser:Qke.parser},{tag:"script",attrs(e){return/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(e.type)},parser:AUn},{tag:"script",attrs(e){return!e.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(e.type)},parser:sm.parser},{tag:"style",attrs(e){return(!e.lang||e.lang=="css")&&(!e.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(e.type))},parser:LB.parser}],TSt=[{name:"style",parser:LB.parser.configure({top:"Styles"})}].concat(kSt.map(e=>({name:e,parser:sm.parser}))),jSt=UO.define({name:"html",parser:rBn.configure({props:[J_.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}}),eC.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}}}),d1t.add({"OpenTag CloseTag":e=>e.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:"<!--",close:"-->"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-_"}}),q8=jSt.configure({wrap:iSt(ESt,TSt)});function RUn(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=iSt((e.nestedLanguages||[]).concat(ESt),(e.nestedAttributes||[]).concat(TSt)));let r=n?jSt.configure({wrap:n,dialect:t}):t?q8.configure({dialect:t}):q8;return new VO(r,[q8.data.of({autocomplete:IUn(e)}),e.autoCloseTags!==!1?PUn:[],zB().support,FBn().support])}const V8e=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" ")),PUn=Rt.inputHandler.of((e,t,n,r,s)=>{if(e.composing||e.state.readOnly||t!=n||r!=">"&&r!="/"||!q8.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:i}=a,l=i.changeByRange(c=>{var u,d,f;let p=i.doc.sliceString(c.from-1,c.to)==r,{head:h}=c,m=pi(i).resolveInner(h,-1),v;if(p&&r==">"&&m.name=="EndTag"){let y=m.parent;if(((d=(u=y.parent)===null||u===void 0?void 0:u.lastChild)===null||d===void 0?void 0:d.name)!="CloseTag"&&(v=Xj(i.doc,y.parent,h))&&!V8e.has(v)){let b=h+(i.doc.sliceString(h,h+1)===">"?1:0),x=`</${v}>`;return{range:c,changes:{from:h,to:b,insert:x}}}}else if(p&&r=="/"&&m.name=="IncompleteCloseTag"){let y=m.parent;if(m.from==h-2&&((f=y.lastChild)===null||f===void 0?void 0:f.name)!="CloseTag"&&(v=Xj(i.doc,y,h))&&!V8e.has(v)){let b=h+(i.doc.sliceString(h,h+1)===">"?1:0),x=`${v}>`;return{range:wt.cursor(h+x.length,-1),changes:{from:h,to:b,insert:x}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,i.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),NSt=YH({commentTokens:{block:{open:"<!--",close:"-->"}}}),ISt=new Pr,ASt=a7n.configure({props:[eC.add(e=>!e.is("Block")||e.is("Document")||Jge(e)!=null||$Un(e)?void 0:(t,n)=>({from:n.doc.lineAt(t.from).to,to:t.to})),ISt.add(Jge),J_.add({Document:()=>null}),Iw.add({Document:NSt})]});function Jge(e){let t=/^(?:ATX|Setext)Heading(\d)$/.exec(e.name);return t?+t[1]:void 0}function $Un(e){return e.name=="OrderedList"||e.name=="BulletList"}function MUn(e,t){let n=e;for(;;){let r=n.nextSibling,s;if(!r||(s=Jge(r.type))!=null&&s<=t)break;n=r}return n.to}const DUn=Jwt.of((e,t,n)=>{for(let r=pi(e).resolveInner(n,-1);r&&!(r.from<t);r=r.parent){let s=r.type.prop(ISt);if(s==null)continue;let a=MUn(r,s);if(a>n)return{from:n,to:a}}return null});function Kke(e){return new jp(NSt,e,[],"markdown")}const RSt=Kke(ASt),LUn=ASt.configure([g7n,y7n,v7n,b7n,{props:[eC.add({Table:(e,t)=>({from:t.doc.lineAt(e.from).to,to:e.to})})]}]),ZO=Kke(LUn);function FUn(e,t){return n=>{if(n&&e){let r=null;if(n=/\S*/.exec(n)[0],typeof e=="function"?r=e(n):r=dg.matchLanguageName(e,n,!0),r instanceof dg)return r.support?r.support.language.parser:qO.getSkippingParser(r.load());if(r)return r.parser}return t?t.parser:null}}class Zee{constructor(t,n,r,s,a,i,l){this.node=t,this.from=n,this.to=r,this.spaceBefore=s,this.spaceAfter=a,this.type=i,this.item=l}blank(t,n=!0){let r=this.spaceBefore+(this.node.name=="Blockquote"?">":"");if(t!=null){for(;r.length<t;)r+=" ";return r}else{for(let s=this.to-this.from-r.length-this.spaceAfter.length;s>0;s--)r+=" ";return r+(n?this.spaceAfter:"")}}marker(t,n){let r=this.node.name=="OrderedList"?String(+$St(this.item,t)[2]+n):"";return this.spaceBefore+r+this.type+this.spaceAfter}}function PSt(e,t){let n=[],r=[];for(let s=e;s;s=s.parent){if(s.name=="FencedCode")return r;(s.name=="ListItem"||s.name=="Blockquote")&&n.push(s)}for(let s=n.length-1;s>=0;s--){let a=n[s],i,l=t.lineAt(a.from),c=a.from-l.from;if(a.name=="Blockquote"&&(i=/^ *>( ?)/.exec(l.text.slice(c))))r.push(new Zee(a,c,c+i[0].length,"",i[1],">",null));else if(a.name=="ListItem"&&a.parent.name=="OrderedList"&&(i=/^( *)\d+([.)])( *)/.exec(l.text.slice(c)))){let u=i[3],d=i[0].length;u.length>=4&&(u=u.slice(0,u.length-4),d-=4),r.push(new Zee(a.parent,c,c+d,i[1],u,i[2],a))}else if(a.name=="ListItem"&&a.parent.name=="BulletList"&&(i=/^( *)([-+*])( {1,4}\[[ xX]\])?( +)/.exec(l.text.slice(c)))){let u=i[4],d=i[0].length;u.length>4&&(u=u.slice(0,u.length-4),d-=4);let f=i[2];i[3]&&(f+=i[3].replace(/[xX]/," ")),r.push(new Zee(a.parent,c,c+d,i[1],u,f,a))}}return r}function $St(e,t){return/^(\s*)(\d+)(?=[.)])/.exec(t.sliceString(e.from,e.from+10))}function Gee(e,t,n,r=0){for(let s=-1,a=e;;){if(a.name=="ListItem"){let l=$St(a,t),c=+l[2];if(s>=0){if(c!=s+1)return;n.push({from:a.from+l[1].length,to:a.from+l[0].length,insert:String(s+2+r)})}s=c}let i=a.nextSibling;if(!i)break;a=i}}function Xke(e,t){let n=/^[ \t]*/.exec(e)[0].length;if(!n||t.facet(wI)!=" ")return e;let r=qg(e,4,n),s="";for(let a=r;a>0;)a>=4?(s+=" ",a-=4):(s+=" ",a--);return s+e.slice(n)}const MSt=(e={})=>({state:t,dispatch:n})=>{let r=pi(t),{doc:s}=t,a=null,i=t.changeByRange(l=>{if(!l.empty||!ZO.isActiveAt(t,l.from,-1)&&!ZO.isActiveAt(t,l.from,1))return a={range:l};let c=l.from,u=s.lineAt(c),d=PSt(r.resolveInner(c,-1),s);for(;d.length&&d[d.length-1].from>c-u.from;)d.pop();if(!d.length)return a={range:l};let f=d[d.length-1];if(f.to-f.spaceAfter.length>c-u.from)return a={range:l};let p=c>=f.to-f.spaceAfter.length&&!/\S/.test(u.text.slice(f.to));if(f.item&&p){let b=f.node.firstChild,x=f.node.getChild("ListItem","ListItem");if(b.to>=c||x&&x.to<c||u.from>0&&!/[^\s>]/.test(s.lineAt(u.from-1).text)||e.nonTightLists===!1){let S=d.length>1?d[d.length-2]:null,k,_="";S&&S.item?(k=u.from+S.from,_=S.marker(s,1)):k=u.from+(S?S.to:0);let C=[{from:k,to:c,insert:_}];return f.node.name=="OrderedList"&&Gee(f.item,s,C,-2),S&&S.node.name=="OrderedList"&&Gee(S.item,s,C),{range:wt.cursor(k+_.length),changes:C}}else{let S=W8e(d,t,u);return{range:wt.cursor(c+S.length+1),changes:{from:u.from,insert:S+t.lineBreak}}}}if(f.node.name=="Blockquote"&&p&&u.from){let b=s.lineAt(u.from-1),x=/>\s*$/.exec(b.text);if(x&&x.index==f.from){let S=t.changes([{from:b.from+x.index,to:b.to},{from:u.from+f.from,to:u.to}]);return{range:l.map(S),changes:S}}}let h=[];f.node.name=="OrderedList"&&Gee(f.item,s,h);let m=f.item&&f.item.from<u.from,v="";if(!m||/^[\s\d.)\-+*>]*/.exec(u.text)[0].length>=f.to)for(let b=0,x=d.length-1;b<=x;b++)v+=b==x&&!m?d[b].marker(s,1):d[b].blank(b<x?qg(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=Xke(v,t),zUn(f.node,t.doc)&&(v=W8e(d,t,u)+t.lineBreak+v),h.push({from:y,to:c,insert:t.lineBreak+v}),{range:wt.cursor(y+v.length+1),changes:h}});return a?!1:(n(t.update(i,{scrollIntoView:!0,userEvent:"input"})),!0)},DSt=MSt();function H8e(e){return e.name=="QuoteMark"||e.name=="ListMark"}function zUn(e,t){if(e.name!="OrderedList"&&e.name!="BulletList")return!1;let n=e.firstChild,r=e.getChild("ListItem","ListItem");if(!r)return!1;let s=t.lineAt(n.to),a=t.lineAt(r.from),i=/^[\s>]*$/.test(s.text);return s.number+(i?0:1)<a.number}function W8e(e,t,n){let r="";for(let s=0,a=e.length-2;s<=a;s++)r+=e[s].blank(s<a?qg(n.text,4,e[s+1].from)-r.length:null,s<a);return Xke(r,t)}function BUn(e,t){let n=e.resolveInner(t,-1),r=t;H8e(n)&&(r=n.from,n=n.parent);for(let s;s=n.childBefore(r);)if(H8e(s))r=s.from;else if(s.name=="OrderedList"||s.name=="BulletList")n=s.lastChild,r=n.to;else break;return n}const LSt=({state:e,dispatch:t})=>{let n=pi(e),r=null,s=e.changeByRange(a=>{let i=a.from,{doc:l}=e;if(a.empty&&ZO.isActiveAt(e,a.from)){let c=l.lineAt(i),u=PSt(BUn(n,i),l);if(u.length){let d=u[u.length-1],f=d.to-d.spaceAfter.length+(d.spaceAfter?1:0);if(i-c.from>f&&!/\S/.test(c.text.slice(f,i-c.from)))return{range:wt.cursor(c.from+f),changes:{from:c.from+f,to:i}};if(i-c.from==f&&(!d.item||c.from<=d.item.from||!/\S/.test(c.text.slice(0,d.to)))){let p=c.from+d.from;if(d.item&&d.node.from<d.item.from&&/\S/.test(c.text.slice(d.from,d.to))){let h=d.blank(qg(c.text,4,d.to)-qg(c.text,4,d.from));return p==c.from&&(h=Xke(h,e)),{range:wt.cursor(p+h.length),changes:{from:p,to:c.from+d.to,insert:h}}}if(p<i)return{range:wt.cursor(p),changes:{from:p,to:i}}}}}return r={range:a}});return r?!1:(t(e.update(s,{scrollIntoView:!0,userEvent:"delete"})),!0)},FSt=[{key:"Enter",run:DSt},{key:"Backspace",run:LSt}],zSt=RUn({matchClosingTags:!1});function Jke(e={}){let{codeLanguages:t,defaultCodeLanguage:n,addKeymap:r=!0,base:{parser:s}=RSt,completeHTMLTags:a=!0,pasteURLAsLink:i=!0,htmlTagLanguage:l=zSt}=e;if(!(s instanceof eW))throw new RangeError("Base parser provided to `markdown` should be a Markdown parser");let c=e.extensions?[e.extensions]:[],u=[l.support,DUn],d;i&&u.push(BSt),n instanceof VO?(u.push(n.support),d=n.language):n&&(d=n);let f=t||d?FUn(t,d):void 0;c.push(o7n({codeParser:f,htmlParser:l.language.parser})),r&&u.push(th.high(xI.of(FSt)));let p=Kke(s.configure(c));return a&&u.push(p.data.of({autocomplete:UUn})),new VO(p,u)}function UUn(e){let{state:t,pos:n}=e,r=/<[:\-\.\w\u00b7-\uffff]*$/.exec(t.sliceDoc(n-25,n));if(!r)return null;let s=pi(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:qUn(),validFor:/^<[:\-\.\w\u00b7-\uffff]*$/}}let Qee=null;function qUn(){if(Qee)return Qee;let e=NUn(new jke(gs.create({extensions:zSt}),0,!0));return Qee=e?e.options:[]}const VUn=/code|horizontalrule|html|link|comment|processing|escape|entity|image|mark|url/i,BSt=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),!ZO.isActiveAt(t.state,r.from,1)))return!1;let a=pi(t.state),i=!1;return a.iterate({from:r.from,to:r.to,enter:l=>{(l.from>r.from||VUn.test(l.name))&&(i=!0)},leave:l=>{l.to<r.to&&(i=!0)}}),i?!1:(t.dispatch({changes:[{from:r.from,insert:"["},{from:r.to,insert:`](${s})`}],userEvent:"input.paste",scrollIntoView:!0}),!0)}}),HUn=Object.freeze(Object.defineProperty({__proto__:null,commonmarkLanguage:RSt,deleteMarkupBackward:LSt,insertNewlineContinueMarkup:DSt,insertNewlineContinueMarkupCommand:MSt,markdown:Jke,markdownKeymap:FSt,markdownLanguage:ZO,pasteURLAsLink:BSt},Symbol.toStringTag,{value:"Module"}));function GO(){return GO=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},GO.apply(null,arguments)}var WUn=e=>{var t=e.theme,n=e.settings,r=n===void 0?{}:n,s=e.styles,a=s===void 0?[]:s,i={".cm-gutters":{}},l={};r.background&&(l.backgroundColor=r.background),r.backgroundImage&&(l.backgroundImage=r.backgroundImage),r.foreground&&(l.color=r.foreground),r.fontSize&&(l.fontSize=r.fontSize),(r.background||r.foreground)&&(i["&"]=l),r.fontFamily&&(i["&.cm-editor .cm-scroller"]={fontFamily:r.fontFamily}),r.gutterBackground&&(i[".cm-gutters"].backgroundColor=r.gutterBackground),r.gutterForeground&&(i[".cm-gutters"].color=r.gutterForeground),r.gutterBorder&&(i[".cm-gutters"].borderRightColor=r.gutterBorder),r.caret&&(i[".cm-content"]={caretColor:r.caret},i[".cm-cursor, .cm-dropCursor"]={borderLeftColor:r.caret});var c={};r.gutterActiveForeground&&(c.color=r.gutterActiveForeground),r.lineHighlight&&(i[".cm-activeLine"]={backgroundColor:r.lineHighlight},c.backgroundColor=r.lineHighlight),i[".cm-activeLineGutter"]=c,r.selection&&(i["&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection"]={background:r.selection+" !important"}),r.selectionMatch&&(i["& .cm-selectionMatch"]={backgroundColor:r.selectionMatch});var u=Rt.theme(i,{dark:t==="dark"}),d=Kg.define(a),f=[u,rS(d)];return f},ZUn={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)"},GUn=[{tag:de.comment,color:"#6272a4"},{tag:de.string,color:"#f1fa8c"},{tag:de.atom,color:"#bd93f9"},{tag:de.meta,color:"#f8f8f2"},{tag:[de.keyword,de.operator,de.tagName],color:"#ff79c6"},{tag:[de.function(de.propertyName),de.propertyName],color:"#66d9ef"},{tag:[de.definition(de.variableName),de.function(de.variableName),de.className,de.attributeName],color:"#50fa7b"},{tag:de.atom,color:"#bd93f9"}],kI=e=>{var t=e||{},n=t.theme,r=n===void 0?"dark":n,s=t.settings,a=s===void 0?{}:s,i=t.styles,l=i===void 0?[]:i;return WUn({theme:r,settings:GO({},ZUn,a),styles:[...GUn,...l]})};kI();function USt(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 QUn=e=>{let{state:t}=e,n=t.doc.lineAt(t.selection.main.from),r=tOe(e.state,n.from);return r.line?YUn(e):r.block?XUn(e):!1};function eOe(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 YUn=eOe(tqn,0),KUn=eOe(qSt,0),XUn=eOe((e,t)=>qSt(e,t,eqn(t)),0);function tOe(e,t){let n=e.languageDataAt("commentTokens",t,1);return n.length?n[0]:{}}const AR=50;function JUn(e,{open:t,close:n},r,s){let a=e.sliceDoc(r-AR,r),i=e.sliceDoc(s,s+AR),l=/\s*$/.exec(a)[0].length,c=/^\s*/.exec(i)[0].length,u=a.length-l;if(a.slice(u-t.length,u)==t&&i.slice(c,c+n.length)==n)return{open:{pos:r-l,margin:l&&1},close:{pos:s+c,margin:c&&1}};let d,f;s-r<=2*AR?d=f=e.sliceDoc(r,s):(d=e.sliceDoc(r,r+AR),f=e.sliceDoc(s-AR,s));let p=/^\s*/.exec(d)[0].length,h=/\s*$/.exec(f)[0].length,m=f.length-h-n.length;return d.slice(p,p+t.length)==t&&f.slice(m,m+n.length)==n?{open:{pos:r+p+t.length,margin:/\s/.test(d.charAt(p+t.length))?1:0},close:{pos:s-h-n.length,margin:/\s/.test(f.charAt(m-1))?1:0}}:null}function eqn(e){let t=[];for(let n of e.selection.ranges){let r=e.doc.lineAt(n.from),s=n.to<=r.to?r:e.doc.lineAt(n.to);s.from>r.from&&s.from==n.to&&(s=n.to==r.to+1?r:e.doc.lineAt(n.to-1));let a=t.length-1;a>=0&&t[a].to>r.from?t[a].to=s.to:t.push({from:r.from+/^\s*/.exec(r.text)[0].length,to:s.to})}return t}function qSt(e,t,n=t.selection.ranges){let r=n.map(a=>tOe(t,a.from).block);if(!r.every(a=>a))return null;let s=n.map((a,i)=>JUn(t,r[i],a.from,a.to));if(e!=2&&!s.every(a=>a))return{changes:t.changes(n.map((a,i)=>s[i]?[]:[{from:a.from,insert:r[i].open+" "},{from:a.to,insert:" "+r[i].close}]))};if(e!=1&&s.some(a=>a)){let a=[];for(let i=0,l;i<s.length;i++)if(l=s[i]){let c=r[i],{open:u,close:d}=l;a.push({from:u.pos-c.open.length,to:u.pos+u.margin},{from:d.pos-d.margin,to:d.pos+c.close.length})}return{changes:a}}return null}function tqn(e,t,n=t.selection.ranges){let r=[],s=-1;e:for(let{from:a,to:i}of n){let l=r.length,c=1e9,u;for(let d=a;d<=i;){let f=t.doc.lineAt(d);if(u==null&&(u=tOe(t,f.from).line,!u))continue e;if(f.from>s&&(a==i||i>f.from)){s=f.from;let p=/^\s*/.exec(f.text)[0].length,h=p==f.length,m=f.text.slice(p,p+u.length)==u?p:-1;p<f.text.length&&p<c&&(c=p),r.push({line:f,comment:m,token:u,indent:p,empty:h,single:!1})}d=f.to+1}if(c<1e9)for(let d=l;d<r.length;d++)r[d].indent<r[d].line.text.length&&(r[d].indent=c);r.length==l+1&&(r[l].single=!0)}if(e!=2&&r.some(a=>a.comment<0&&(!a.empty||a.single))){let a=[];for(let{line:l,token:c,indent:u,empty:d,single:f}of r)(f||!d)&&a.push({from:l.from+u,insert:c+" "});let i=t.changes(a);return{changes:i,selection:t.selection.map(i,1)}}else if(e!=1&&r.some(a=>a.comment>=0)){let a=[];for(let{line:i,comment:l,token:c}of r)if(l>=0){let u=i.from+l,d=u+c.length;i.text[d-i.from]==" "&&d++,a.push({from:u,to:d})}return{changes:a}}return null}const eve=Ly.define(),nqn=Ly.define(),rqn=wn.define(),VSt=wn.define({combine(e){return Fy(e,{minDepth:100,newGroupDelay:500,joinToEvent:(t,n)=>n},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(t,n)=>(r,s)=>t(r,s)||n(r,s)})}}),HSt=vl.define({create(){return Jv.empty},update(e,t){let n=t.state.facet(VSt),r=t.annotation(eve);if(r){let c=Cf.fromTransaction(t,r.selection),u=r.side,d=u==0?e.undone:e.done;return c?d=BB(d,d.length,n.minDepth,c):d=GSt(d,t.startState.selection),new Jv(u==0?r.rest:d,u==0?d:r.rest)}let s=t.annotation(nqn);if((s=="full"||s=="before")&&(e=e.isolate()),t.annotation(jl.addToHistory)===!1)return t.changes.empty?e:e.addMapping(t.changes.desc);let a=Cf.fromTransaction(t),i=t.annotation(jl.time),l=t.annotation(jl.userEvent);return a?e=e.addChanges(a,i,l,n,t):t.selection&&(e=e.addSelection(t.startState.selection,i,l,n.newGroupDelay)),(s=="full"||s=="after")&&(e=e.isolate()),e},toJSON(e){return{done:e.done.map(t=>t.toJSON()),undone:e.undone.map(t=>t.toJSON())}},fromJSON(e){return new Jv(e.done.map(Cf.fromJSON),e.undone.map(Cf.fromJSON))}});function sqn(e={}){return[HSt,VSt.of(e),Rt.domEventHandlers({beforeinput(t,n){let r=t.inputType=="historyUndo"?WSt:t.inputType=="historyRedo"?tve:null;return r?(t.preventDefault(),r(n)):!1}})]}function tW(e,t){return function({state:n,dispatch:r}){if(!t&&n.readOnly)return!1;let s=n.field(HSt,!1);if(!s)return!1;let a=s.pop(e,n,t);return a?(r(a),!0):!1}}const WSt=tW(0,!1),tve=tW(1,!1),aqn=tW(0,!0),iqn=tW(1,!0);class Cf{constructor(t,n,r,s,a){this.changes=t,this.effects=n,this.mapped=r,this.startSelection=s,this.selectionsAfter=a}setSelAfter(t){return new Cf(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 Cf(t.changes&&El.fromJSON(t.changes),[],t.mapped&&uy.fromJSON(t.mapped),t.startSelection&&wt.fromJSON(t.startSelection),t.selectionsAfter.map(wt.fromJSON))}static fromTransaction(t,n){let r=Wh;for(let s of t.startState.facet(rqn)){let a=s(t);a.length&&(r=r.concat(a))}return!r.length&&t.changes.empty?null:new Cf(t.changes.invert(t.startState.doc),r,void 0,n||t.startState.selection,Wh)}static selection(t){return new Cf(void 0,Wh,void 0,void 0,t)}}function BB(e,t,n,r){let s=t+1>n+20?t-n-1:0,a=e.slice(s,t);return a.push(r),a}function oqn(e,t){let n=[],r=!1;return e.iterChangedRanges((s,a)=>n.push(s,a)),t.iterChangedRanges((s,a,i,l)=>{for(let c=0;c<n.length;){let u=n[c++],d=n[c++];l>=u&&i<=d&&(r=!0)}}),r}function lqn(e,t){return e.ranges.length==t.ranges.length&&e.ranges.filter((n,r)=>n.empty!=t.ranges[r].empty).length===0}function ZSt(e,t){return e.length?t.length?e.concat(t):e:t}const Wh=[],cqn=200;function GSt(e,t){if(e.length){let n=e[e.length-1],r=n.selectionsAfter.slice(Math.max(0,n.selectionsAfter.length-cqn));return r.length&&r[r.length-1].eq(t)?e:(r.push(t),BB(e,e.length-1,1e9,n.setSelAfter(r)))}else return[Cf.selection([t])]}function uqn(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 Yee(e,t){if(!e.length)return e;let n=e.length,r=Wh;for(;n;){let s=dqn(e[n-1],t,r);if(s.changes&&!s.changes.empty||s.effects.length){let a=e.slice(0,n);return a[n-1]=s,a}else t=s.mapped,n--,r=s.selectionsAfter}return r.length?[Cf.selection(r)]:Wh}function dqn(e,t,n){let r=ZSt(e.selectionsAfter.length?e.selectionsAfter.map(l=>l.map(t)):Wh,n);if(!e.changes)return Cf.selection(r);let s=e.changes.map(t),a=t.mapDesc(e.changes,!0),i=e.mapped?e.mapped.composeDesc(a):a;return new Cf(s,dr.mapEffects(e.effects,t),i,e.startSelection.map(a),r)}const fqn=/^(input\.type|delete)($|\.)/;class Jv{constructor(t,n,r=0,s=void 0){this.done=t,this.undone=n,this.prevTime=r,this.prevUserEvent=s}isolate(){return this.prevTime?new Jv(this.done,this.undone):this}addChanges(t,n,r,s,a){let i=this.done,l=i[i.length-1];return l&&l.changes&&!l.changes.empty&&t.changes&&(!r||fqn.test(r))&&(!l.selectionsAfter.length&&n-this.prevTime<s.newGroupDelay&&s.joinToEvent(a,oqn(l.changes,t.changes))||r=="input.type.compose")?i=BB(i,i.length-1,s.minDepth,new Cf(t.changes.compose(l.changes),ZSt(dr.mapEffects(t.effects,l.changes),l.effects),l.mapped,l.startSelection,Wh)):i=BB(i,i.length,s.minDepth,t),new Jv(i,Wh,n,r)}addSelection(t,n,r,s){let a=this.done.length?this.done[this.done.length-1].selectionsAfter:Wh;return a.length>0&&n-this.prevTime<s&&r==this.prevUserEvent&&r&&/^select($|\.)/.test(r)&&lqn(a[a.length-1],t)?this:new Jv(GSt(this.done,t),this.undone,n,r)}addMapping(t){return new Jv(Yee(this.done,t),Yee(this.undone,t),this.prevTime,this.prevUserEvent)}pop(t,n,r){let s=t==0?this.done:this.undone;if(s.length==0)return null;let a=s[s.length-1],i=a.selectionsAfter[0]||(a.startSelection?a.startSelection.map(a.changes.invertedDesc,1):n.selection);if(r&&a.selectionsAfter.length)return n.update({selection:a.selectionsAfter[a.selectionsAfter.length-1],annotations:eve.of({side:t,rest:uqn(s),selection:i}),userEvent:t==0?"select.undo":"select.redo",scrollIntoView:!0});if(a.changes){let l=s.length==1?Wh:s.slice(0,s.length-1);return a.mapped&&(l=Yee(l,a.mapped)),n.update({changes:a.changes,selection:a.startSelection,effects:a.effects,annotations:eve.of({side:t,rest:l,selection:i}),filter:!1,userEvent:t==0?"undo":"redo",scrollIntoView:!0})}else return null}}Jv.empty=new Jv(Wh,Wh);const pqn=[{key:"Mod-z",run:WSt,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:tve,preventDefault:!0},{linux:"Ctrl-Shift-z",run:tve,preventDefault:!0},{key:"Mod-u",run:aqn,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:iqn,preventDefault:!0}];function OI(e,t){return wt.create(e.ranges.map(t),e.mainIndex)}function Xg(e,t){return e.update({selection:t,scrollIntoView:!0,userEvent:"select"})}function Jg({state:e,dispatch:t},n){let r=OI(e.selection,n);return r.eq(e.selection,!0)?!1:(t(Xg(e,r)),!0)}function nW(e,t){return wt.cursor(t?e.to:e.from)}function QSt(e,t){return Jg(e,n=>n.empty?e.moveByChar(n,t):nW(n,t))}function id(e){return e.textDirectionAt(e.state.selection.main.head)==Si.LTR}const YSt=e=>QSt(e,!id(e)),KSt=e=>QSt(e,id(e));function XSt(e,t){return Jg(e,n=>n.empty?e.moveByGroup(n,t):nW(n,t))}const hqn=e=>XSt(e,!id(e)),mqn=e=>XSt(e,id(e));function gqn(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 rW(e,t,n){let r=pi(e).resolveInner(t.head),s=n?Pr.closedBy:Pr.openedBy;for(let c=t.head;;){let u=n?r.childAfter(c):r.childBefore(c);if(!u)break;gqn(e,u,s)?r=u:c=n?u.to:u.from}let a=r.type.prop(s),i,l;return a&&(i=n?Xv(e,r.from,1):Xv(e,r.to,-1))&&i.matched?l=n?i.end.to:i.end.from:l=n?r.to:r.from,wt.cursor(l,n?-1:1)}const vqn=e=>Jg(e,t=>rW(e.state,t,!id(e))),yqn=e=>Jg(e,t=>rW(e.state,t,id(e)));function JSt(e,t){return Jg(e,n=>{if(!n.empty)return nW(n,t);let r=e.moveVertically(n,t);return r.head!=n.head?r:e.moveToLineBoundary(n,t)})}const ekt=e=>JSt(e,!1),tkt=e=>JSt(e,!0);function nkt(e){let t=e.scrollDOM.clientHeight<e.scrollDOM.scrollHeight-2,n=0,r=0,s;if(t){for(let a of e.state.facet(Rt.scrollMargins)){let i=a(e);i?.top&&(n=Math.max(i?.top,n)),i?.bottom&&(r=Math.max(i?.bottom,r))}s=e.scrollDOM.clientHeight-n-r}else s=(e.dom.ownerDocument.defaultView||window).innerHeight;return{marginTop:n,marginBottom:r,selfScroll:t,height:Math.max(e.defaultLineHeight,s-5)}}function rkt(e,t){let n=nkt(e),{state:r}=e,s=OI(r.selection,i=>i.empty?e.moveVertically(i,t,n.height):nW(i,t));if(s.eq(r.selection))return!1;let a;if(n.selfScroll){let i=e.coordsAtPos(r.selection.main.head),l=e.scrollDOM.getBoundingClientRect(),c=l.top+n.marginTop,u=l.bottom-n.marginBottom;i&&i.top>c&&i.bottom<u&&(a=Rt.scrollIntoView(s.main.head,{y:"start",yMargin:i.top-c}))}return e.dispatch(Xg(r,s),{effects:a}),!0}const Z8e=e=>rkt(e,!1),nve=e=>rkt(e,!0);function sS(e,t,n){let r=e.lineBlockAt(t.head),s=e.moveToLineBoundary(t,n);if(s.head==t.head&&s.head!=(n?r.to:r.from)&&(s=e.moveToLineBoundary(t,n,!1)),!n&&s.head==r.from&&r.length){let a=/^\s*/.exec(e.state.sliceDoc(r.from,Math.min(r.from+100,r.to)))[0].length;a&&t.head!=r.from+a&&(s=wt.cursor(r.from+a))}return s}const bqn=e=>Jg(e,t=>sS(e,t,!0)),xqn=e=>Jg(e,t=>sS(e,t,!1)),wqn=e=>Jg(e,t=>sS(e,t,!id(e))),Sqn=e=>Jg(e,t=>sS(e,t,id(e))),kqn=e=>Jg(e,t=>wt.cursor(e.lineBlockAt(t.head).from,1)),Oqn=e=>Jg(e,t=>wt.cursor(e.lineBlockAt(t.head).to,-1));function _qn(e,t,n){let r=!1,s=OI(e.selection,a=>{let i=Xv(e,a.head,-1)||Xv(e,a.head,1)||a.head>0&&Xv(e,a.head-1,1)||a.head<e.doc.length&&Xv(e,a.head+1,-1);if(!i||!i.end)return a;r=!0;let l=i.start.from==a.head?i.end.to:i.end.from;return wt.cursor(l)});return r?(t(Xg(e,s)),!0):!1}const Cqn=({state:e,dispatch:t})=>_qn(e,t);function Pm(e,t,n){let r=OI(e.state.selection,s=>{s.undirectional&&s.head>=s.anchor!=t&&(s=wt.range(s.head,s.anchor));let a=n(s);return wt.range(s.anchor,a.head,a.goalColumn,a.bidiLevel||void 0,a.assoc)});return r.eq(e.state.selection)?!1:(e.dispatch(Xg(e.state,r)),!0)}function skt(e,t){return Pm(e,t,n=>e.moveByChar(n,t))}const akt=e=>skt(e,!id(e)),ikt=e=>skt(e,id(e));function okt(e,t){return Pm(e,t,n=>e.moveByGroup(n,t))}const Eqn=e=>okt(e,!id(e)),Tqn=e=>okt(e,id(e)),jqn=e=>{let t=!id(e);return Pm(e,t,n=>rW(e.state,n,t))},Nqn=e=>{let t=id(e);return Pm(e,t,n=>rW(e.state,n,t))};function lkt(e,t){return Pm(e,t,n=>e.moveVertically(n,t))}const ckt=e=>lkt(e,!1),ukt=e=>lkt(e,!0);function dkt(e,t){return Pm(e,t,n=>e.moveVertically(n,t,nkt(e).height))}const G8e=e=>dkt(e,!1),Q8e=e=>dkt(e,!0),Iqn=e=>Pm(e,!0,t=>sS(e,t,!0)),Aqn=e=>Pm(e,!1,t=>sS(e,t,!1)),Rqn=e=>{let t=!id(e);return Pm(e,t,n=>sS(e,n,t))},Pqn=e=>{let t=id(e);return Pm(e,t,n=>sS(e,n,t))},$qn=e=>Pm(e,!1,t=>wt.cursor(e.lineBlockAt(t.head).from)),Mqn=e=>Pm(e,!0,t=>wt.cursor(e.lineBlockAt(t.head).to)),Y8e=({state:e,dispatch:t})=>(t(Xg(e,{anchor:0})),!0),K8e=({state:e,dispatch:t})=>(t(Xg(e,{anchor:e.doc.length})),!0),X8e=({state:e,dispatch:t})=>(t(Xg(e,{anchor:e.selection.main.anchor,head:0})),!0),J8e=({state:e,dispatch:t})=>(t(Xg(e,{anchor:e.selection.main.anchor,head:e.doc.length})),!0),Dqn=({state:e,dispatch:t})=>(t(e.update({selection:{anchor:0,head:e.doc.length},userEvent:"select"})),!0),Lqn=({state:e,dispatch:t})=>{let n=sW(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},Fqn=({state:e,dispatch:t})=>{let n=OI(e.selection,r=>{let s=pi(e),a=s.resolveStack(r.from,1);if(r.empty){let i=s.resolveStack(r.from,-1);i.node.from>=a.node.from&&i.node.to<=a.node.to&&(a=i)}for(let i=a;i;i=i.next){let{node:l}=i;if((l.from<r.from&&l.to>=r.to||l.to>r.to&&l.from<=r.from)&&i.next)return wt.range(l.to,l.from)}return r});return n.eq(e.selection)?!1:(t(Xg(e,n)),!0)};function fkt(e,t){let{state:n}=e,r=n.selection,s=n.selection.ranges.slice();for(let a of n.selection.ranges){let i=n.doc.lineAt(a.head);if(t?i.to<e.state.doc.length:i.from>0)for(let l=a;;){let c=e.moveVertically(l,t);if(c.head<i.from||c.head>i.to){s.some(u=>u.head==c.head)||s.push(c);break}else{if(c.head==l.head)break;l=c}}}return s.length==r.ranges.length?!1:(e.dispatch(Xg(n,wt.create(s,s.length-1))),!0)}const zqn=e=>fkt(e,!1),Bqn=e=>fkt(e,!0),Uqn=({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(Xg(e,r)),!0):!1};function G3(e,t){if(e.state.readOnly)return!1;let n="delete.selection",{state:r}=e,s=r.changeByRange(a=>{let{from:i,to:l}=a;if(i==l){let c=t(a);c<i?(n="delete.backward",c=dF(e,c,!1)):c>i&&(n="delete.forward",c=dF(e,c,!0)),i=Math.min(i,c),l=Math.max(l,c)}else i=dF(e,i,!1),l=dF(e,l,!0);return i==l?{range:a}:{changes:{from:i,to:l},range:wt.cursor(i,i<a.head?-1:1)}});return s.changes.empty?!1:(e.dispatch(r.update(s,{scrollIntoView:!0,userEvent:n,effects:n=="delete.selection"?Rt.announce.of(r.phrase("Selection deleted")):void 0})),!0)}function dF(e,t,n){if(e instanceof Rt)for(let r of e.state.facet(Rt.atomicRanges).map(s=>s(e)))r.between(t,t,(s,a)=>{s<t&&a>t&&(t=n?a:s)});return t}const pkt=(e,t,n)=>G3(e,r=>{let s=r.from,{state:a}=e,i=a.doc.lineAt(s),l,c;if(n&&!t&&s>i.from&&s<i.from+200&&!/[^ \t]/.test(l=i.text.slice(0,s-i.from))){if(l[l.length-1]==" ")return s-1;let u=qg(l,a.tabSize),d=u%HO(a)||HO(a);for(let f=0;f<d&&l[l.length-1-f]==" ";f++)s--;c=s}else c=Ic(i.text,s-i.from,t,t)+i.from,c==s&&i.number!=(t?a.doc.lines:1)?c+=t?1:-1:!t&&/[\ufe00-\ufe0f]/.test(i.text.slice(c-i.from,s-i.from))&&(c=Ic(i.text,c-i.from,!1,!1)+i.from);return c}),rve=e=>pkt(e,!1,!0),hkt=e=>pkt(e,!0,!1),mkt=(e,t)=>G3(e,n=>{let r=n.head,{state:s}=e,a=s.doc.lineAt(r),i=s.charCategorizer(r);for(let l=null;;){if(r==(t?a.to:a.from)){r==n.head&&a.number!=(t?s.doc.lines:1)&&(r+=t?1:-1);break}let c=Ic(a.text,r-a.from,t)+a.from,u=a.text.slice(Math.min(r,c)-a.from,Math.max(r,c)-a.from),d=i(u);if(l!=null&&d!=l)break;(u!=" "||r!=n.head)&&(l=d),r=c}return r}),gkt=e=>mkt(e,!1),qqn=e=>mkt(e,!0),Vqn=e=>G3(e,t=>{let n=e.lineBlockAt(t.head).to;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),Hqn=e=>G3(e,t=>{let n=e.moveToLineBoundary(t,!1).head;return t.head>n?n:Math.max(0,t.head-1)}),Wqn=e=>G3(e,t=>{let n=e.moveToLineBoundary(t,!0).head;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),Zqn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(r=>({changes:{from:r.from,to:r.to,insert:wa.of(["",""])},range:wt.cursor(r.from)}));return t(e.update(n,{scrollIntoView:!0,userEvent:"input"})),!0},Gqn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(r=>{if(!r.empty||r.from==0||r.from==e.doc.length)return{range:r};let s=r.from,a=e.doc.lineAt(s),i=s==a.from?s-1:Ic(a.text,s-a.from,!1)+a.from,l=s==a.to?s+1:Ic(a.text,s-a.from,!0)+a.from;return{changes:{from:i,to:l,insert:e.doc.slice(s,l).append(e.doc.slice(i,s))},range:wt.cursor(l)}});return n.changes.empty?!1:(t(e.update(n,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function sW(e){let t=[],n=-1;for(let r of e.selection.ranges){let s=e.doc.lineAt(r.from),a=e.doc.lineAt(r.to);if(!r.empty&&r.to==a.from&&(a=e.doc.lineAt(r.to-1)),n>=s.number){let i=t[t.length-1];i.to=a.to,i.ranges.push(r)}else t.push({from:s.from,to:a.to,ranges:[r]});n=a.number+1}return t}function vkt(e,t,n){if(e.readOnly)return!1;let r=[],s=[];for(let a of sW(e)){if(n?a.to==e.doc.length:a.from==0)continue;let i=e.doc.lineAt(n?a.to+1:a.from-1),l=i.length+1;if(n){r.push({from:a.to,to:i.to},{from:a.from,insert:i.text+e.lineBreak});for(let c of a.ranges)s.push(wt.range(Math.min(e.doc.length,c.anchor+l),Math.min(e.doc.length,c.head+l)))}else{r.push({from:i.from,to:a.from},{from:a.to,insert:e.lineBreak+i.text});for(let c of a.ranges)s.push(wt.range(c.anchor-l,c.head-l))}}return r.length?(t(e.update({changes:r,scrollIntoView:!0,selection:wt.create(s,e.selection.mainIndex),userEvent:"move.line"})),!0):!1}const Qqn=({state:e,dispatch:t})=>vkt(e,t,!1),Yqn=({state:e,dispatch:t})=>vkt(e,t,!0);function ykt(e,t,n){if(e.readOnly)return!1;let r=[];for(let a of sW(e))n?r.push({from:a.from,insert:e.doc.slice(a.from,a.to)+e.lineBreak}):r.push({from:a.to,insert:e.lineBreak+e.doc.slice(a.from,a.to)});let s=e.changes(r);return t(e.update({changes:s,selection:e.selection.map(s,n?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}const Kqn=({state:e,dispatch:t})=>ykt(e,t,!1),Xqn=({state:e,dispatch:t})=>ykt(e,t,!0),Jqn=e=>{if(e.state.readOnly)return!1;let{state:t}=e,n=t.changes(sW(t).map(({from:s,to:a})=>(s>0?s--:a<t.doc.length&&a++,{from:s,to:a}))),r=OI(t.selection,s=>{let a;if(e.lineWrapping){let i=e.lineBlockAt(s.head),l=e.coordsAtPos(s.head,s.assoc||1);l&&(a=i.bottom+e.documentTop-l.bottom+e.defaultLineHeight/2)}return e.moveVertically(s,!0,a)}).map(n);return e.dispatch({changes:n,selection:r,scrollIntoView:!0,userEvent:"delete.line"}),!0};function eVn(e,t){if(/\(\)|\[\]|\{\}/.test(e.sliceDoc(t-1,t+1)))return{from:t,to:t};let n=pi(e).resolveInner(t),r=n.childBefore(t),s=n.childAfter(t),a;return r&&s&&r.to<=t&&s.from>=t&&(a=r.type.prop(Pr.closedBy))&&a.indexOf(s.name)>-1&&e.doc.lineAt(r.to).from==e.doc.lineAt(s.from).from&&!/\S/.test(e.sliceDoc(r.to,s.from))?{from:r.to,to:s.from}:null}const e9e=bkt(!1),tVn=bkt(!0);function bkt(e){return({state:t,dispatch:n})=>{if(t.readOnly)return!1;let r=t.changeByRange(s=>{let{from:a,to:i}=s,l=t.doc.lineAt(a),c=!e&&a==i&&eVn(t,a);e&&(a=i=(i<=l.to?l:t.doc.lineAt(i)).to);let u=new KH(t,{simulateBreak:a,simulateDoubleBreak:!!c}),d=kke(u,a);for(d==null&&(d=qg(/^\s*/.exec(t.doc.lineAt(a).text)[0],t.tabSize));i<l.to&&/\s/.test(l.text[i-l.from]);)i++;c?{from:a,to:i}=c:a>l.from&&a<l.from+100&&!/\S/.test(l.text.slice(0,a))&&(a=l.from);let f=["",bM(t,d)];return c&&f.push(bM(t,u.lineIndent(l.from,-1))),{changes:{from:a,to:i,insert:wa.of(f)},range:wt.cursor(a+1+f[1].length)}});return n(t.update(r,{scrollIntoView:!0,userEvent:"input"})),!0}}function nOe(e,t){let n=-1;return e.changeByRange(r=>{let s=[];for(let i=r.from;i<=r.to;){let l=e.doc.lineAt(i);l.number>n&&(r.empty||r.to>l.from)&&(t(l,s,r),n=l.number),i=l.to+1}let a=e.changes(s);return{changes:s,range:wt.range(a.mapPos(r.anchor,1),a.mapPos(r.head,1))}})}const nVn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=Object.create(null),r=new KH(e,{overrideIndentation:a=>{let i=n[a];return i??-1}}),s=nOe(e,(a,i,l)=>{let c=kke(r,a.from);if(c==null)return;/\S/.test(a.text)||(c=0);let u=/^\s*/.exec(a.text)[0],d=bM(e,c);(u!=d||l.from<a.from+u.length)&&(n[a.from]=c,i.push({from:a.from,to:a.from+u.length,insert:d}))});return s.changes.empty||t(e.update(s,{userEvent:"indent"})),!0},xkt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(nOe(e,(n,r)=>{r.push({from:n.from,insert:e.facet(wI)})}),{userEvent:"input.indent"})),!0),wkt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(nOe(e,(n,r)=>{let s=/^\s*/.exec(n.text)[0];if(!s)return;let a=qg(s,e.tabSize),i=0,l=bM(e,Math.max(0,a-HO(e)));for(;i<s.length&&i<l.length&&s.charCodeAt(i)==l.charCodeAt(i);)i++;r.push({from:n.from+i,to:n.from+s.length,insert:l.slice(i)})}),{userEvent:"delete.dedent"})),!0),rVn=e=>(e.setTabFocusMode(),!0),sVn=[{key:"Ctrl-b",run:YSt,shift:akt,preventDefault:!0},{key:"Ctrl-f",run:KSt,shift:ikt},{key:"Ctrl-p",run:ekt,shift:ckt},{key:"Ctrl-n",run:tkt,shift:ukt},{key:"Ctrl-a",run:kqn,shift:$qn},{key:"Ctrl-e",run:Oqn,shift:Mqn},{key:"Ctrl-d",run:hkt},{key:"Ctrl-h",run:rve},{key:"Ctrl-k",run:Vqn},{key:"Ctrl-Alt-h",run:gkt},{key:"Ctrl-o",run:Zqn},{key:"Ctrl-t",run:Gqn},{key:"Ctrl-v",run:nve}],aVn=[{key:"ArrowLeft",run:YSt,shift:akt,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:hqn,shift:Eqn,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:wqn,shift:Rqn,preventDefault:!0},{key:"ArrowRight",run:KSt,shift:ikt,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:mqn,shift:Tqn,preventDefault:!0},{mac:"Cmd-ArrowRight",run:Sqn,shift:Pqn,preventDefault:!0},{key:"ArrowUp",run:ekt,shift:ckt,preventDefault:!0},{mac:"Cmd-ArrowUp",run:Y8e,shift:X8e},{mac:"Ctrl-ArrowUp",run:Z8e,shift:G8e},{key:"ArrowDown",run:tkt,shift:ukt,preventDefault:!0},{mac:"Cmd-ArrowDown",run:K8e,shift:J8e},{mac:"Ctrl-ArrowDown",run:nve,shift:Q8e},{key:"PageUp",run:Z8e,shift:G8e},{key:"PageDown",run:nve,shift:Q8e},{key:"Home",run:xqn,shift:Aqn,preventDefault:!0},{key:"Mod-Home",run:Y8e,shift:X8e},{key:"End",run:bqn,shift:Iqn,preventDefault:!0},{key:"Mod-End",run:K8e,shift:J8e},{key:"Enter",run:e9e,shift:e9e},{key:"Mod-a",run:Dqn},{key:"Backspace",run:rve,shift:rve,preventDefault:!0},{key:"Delete",run:hkt,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:gkt,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:qqn,preventDefault:!0},{mac:"Mod-Backspace",run:Hqn,preventDefault:!0},{mac:"Mod-Delete",run:Wqn,preventDefault:!0}].concat(sVn.map(e=>({mac:e.key,run:e.run,shift:e.shift}))),iVn=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:vqn,shift:jqn},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:yqn,shift:Nqn},{key:"Alt-ArrowUp",run:Qqn},{key:"Shift-Alt-ArrowUp",run:Kqn},{key:"Alt-ArrowDown",run:Yqn},{key:"Shift-Alt-ArrowDown",run:Xqn},{key:"Mod-Alt-ArrowUp",run:zqn},{key:"Mod-Alt-ArrowDown",run:Bqn},{key:"Escape",run:Uqn},{key:"Mod-Enter",run:tVn},{key:"Alt-l",mac:"Ctrl-l",run:Lqn},{key:"Mod-i",run:Fqn,preventDefault:!0},{key:"Mod-[",run:wkt},{key:"Mod-]",run:xkt},{key:"Mod-Alt-\\",run:nVn},{key:"Shift-Mod-k",run:Jqn},{key:"Shift-Mod-\\",run:Cqn},{key:"Mod-/",run:QUn},{key:"Alt-A",run:KUn},{key:"Ctrl-m",mac:"Shift-Alt-m",run:rVn}].concat(aVn),oVn={key:"Tab",run:xkt,shift:wkt},t9e=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class $x{constructor(t,n,r=0,s=t.length,a,i){this.test=i,this.value={from:0,to:0,precise:!1},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=t.iterRange(r,s),this.bufferStart=r,this.normalize=a?l=>a(t9e(l)):t9e,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 gf(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let t=this.peek();if(t<0)return this.done=!0,this;let n=ske(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=Uv(t);let s=this.normalize(n);if(s.length)for(let a=0,i=r,l=!0;;a++){let c=s.charCodeAt(a),u=this.match(c,i,l,this.bufferPos+this.bufferStart,a==s.length-1);if(u)return this.value=u,this;if(a==s.length-1)break;l&&a<n.length&&n.charCodeAt(a)==c?i++:l=!1}}}match(t,n,r,s,a){let i=null;for(let l=0;l<this.matches.length;){let c=this.matches[l],u=!1;this.query.charCodeAt(c.index)==t&&(c.index==this.query.length-1?i={from:c.from,to:s,precise:a&&c.precise}:(c.index++,u=!0)),u?l++:this.matches.splice(l,1)}return this.query.charCodeAt(0)==t&&(this.query.length==1?i={from:n,to:s,precise:r&&a}:this.matches.push({from:n,index:1,precise:r})),i&&this.test&&!this.test(i.from,i.to,this.buffer,this.bufferStart)&&(i=null),i}}typeof Symbol<"u"&&($x.prototype[Symbol.iterator]=function(){return this});const Skt={from:-1,to:-1,match:/.*/.exec(""),precise:!0},rOe="gm"+(/x/.unicode==null?"":"u");class kkt{constructor(t,n,r,s=0,a=t.length){if(this.text=t,this.to=a,this.curLine="",this.done=!1,this.value=Skt,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new Okt(t,n,r,s,a);this.re=new RegExp(n,rOe+(r?.ignoreCase?"i":"")),this.test=r?.test,this.iter=t.iter();let i=t.lineAt(s);this.curLineStart=i.from,this.matchPos=UB(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=UB(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 Kee=new WeakMap;class sj{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let s=Kee.get(t);if(!s||s.from>=r||s.to<=n){let l=new sj(n,t.sliceString(n,r));return Kee.set(t,l),l}if(s.from==n&&s.to==r)return s;let{text:a,from:i}=s;return i>n&&(a=t.sliceString(n,i)+a,i=n),s.to<r&&(a+=t.sliceString(s.to,r)),Kee.set(t,new sj(i,a)),new sj(n,a.slice(n-i,r-i))}}class Okt{constructor(t,n,r,s,a){this.text=t,this.to=a,this.done=!1,this.value=Skt,this.matchPos=UB(t,s),this.re=new RegExp(n,rOe+(r?.ignoreCase?"i":"")),this.test=r?.test,this.flat=sj.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=UB(this.text,s+(r==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=sj.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(kkt.prototype[Symbol.iterator]=Okt.prototype[Symbol.iterator]=function(){return this});function lVn(e){try{return new RegExp(e,rOe),!0}catch{return!1}}function UB(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 cVn=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:s}=Vzn(e,{label:t.phrase("Go to line"),input:{type:"text",name:"line",value:n},focus:!0,submitLabel:t.phrase("go")});return s.then(a=>{let i=a&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(a.elements.line.value);if(!i){e.dispatch({effects:r});return}let l=t.doc.lineAt(t.selection.main.head),[,c,u,d,f]=i,p=d?+d.slice(1):0,h=u?+u:l.number;if(u&&f){let y=h/100;c&&(y=y*(c=="-"?-1:1)+l.number/t.doc.lines),h=Math.round(t.doc.lines*y)}else u&&c&&(h=h*(c=="-"?-1:1)+l.number);let m=t.doc.line(Math.max(1,Math.min(t.doc.lines,h))),v=wt.cursor(m.from+Math.max(0,Math.min(p,m.length)));e.dispatch({effects:[r,Rt.scrollIntoView(v.from,{y:"center"})],selection:v})}),!0},uVn={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},dVn=wn.define({combine(e){return Fy(e,uVn,{highlightWordAroundCursor:(t,n)=>t||n,minSelectionLength:Math.min,maxMatches:Math.min})}});function fVn(e){return[vVn,gVn]}const pVn=Tn.mark({class:"cm-selectionMatch"}),hVn=Tn.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function n9e(e,t,n,r){return(n==0||e(t.sliceDoc(n-1,n))!=yo.Word)&&(r==t.doc.length||e(t.sliceDoc(r,r+1))!=yo.Word)}function mVn(e,t,n,r){return e(t.sliceDoc(n,n+1))==yo.Word&&e(t.sliceDoc(r-1,r))==yo.Word}const gVn=ko.fromClass(class{constructor(e){this.decorations=this.getDeco(e)}update(e){(e.selectionSet||e.docChanged||e.viewportChanged)&&(this.decorations=this.getDeco(e.view))}getDeco(e){let t=e.state.facet(dVn),{state:n}=e,r=n.selection;if(r.ranges.length>1)return Tn.none;let s=r.main,a,i=null;if(s.empty){if(!t.highlightWordAroundCursor)return Tn.none;let c=n.wordAt(s.head);if(!c)return Tn.none;i=n.charCategorizer(s.head),a=n.sliceDoc(c.from,c.to)}else{let c=s.to-s.from;if(c<t.minSelectionLength||c>200)return Tn.none;if(t.wholeWords){if(a=n.sliceDoc(s.from,s.to),i=n.charCategorizer(s.head),!(n9e(i,n,s.from,s.to)&&mVn(i,n,s.from,s.to)))return Tn.none}else if(a=n.sliceDoc(s.from,s.to),!a)return Tn.none}let l=[];for(let c of e.visibleRanges){let u=new $x(n.doc,a,c.from,c.to);for(;!u.next().done;){let{from:d,to:f}=u.value;if((!i||n9e(i,n,d,f))&&(s.empty&&d<=s.from&&f>=s.to?l.push(hVn.range(d,f)):(d>=s.to||f<=s.from)&&l.push(pVn.range(d,f)),l.length>t.maxMatches))return Tn.none}}return Tn.set(l)}},{decorations:e=>e.decorations}),vVn=Rt.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),yVn=({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 bVn(e,t){let{main:n,ranges:r}=e.selection,s=e.wordAt(n.head),a=s&&s.from==n.from&&s.to==n.to;for(let i=!1,l=new $x(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(i)return null;l=new $x(e.doc,t,0,Math.max(0,r[r.length-1].from-1)),i=!0}else{if(i&&r.some(c=>c.from==l.value.from))continue;if(a){let c=e.wordAt(l.value.from);if(!c||c.from!=l.value.from||c.to!=l.value.to)continue}return l.value}}const xVn=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(a=>a.from===a.to))return yVn({state:e,dispatch:t});let r=e.sliceDoc(n[0].from,n[0].to);if(e.selection.ranges.some(a=>e.sliceDoc(a.from,a.to)!=r))return!1;let s=bVn(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},_I=wn.define({combine(e){return Fy(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new PVn(t),scrollToMatch:t=>Rt.scrollIntoView(t)})}});class _kt{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||lVn(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!t.wholeWord,this.test=t.test}unquote(t){return this.literal?t:t.replace(/\\([nrt\\])/g,(n,r)=>r=="n"?`
|
|
234
|
-
`:r=="r"?"\r":r=="t"?" ":"\\")}eq(t){return this.search==t.search&&this.replace==t.replace&&this.caseSensitive==t.caseSensitive&&this.regexp==t.regexp&&this.wholeWord==t.wholeWord&&this.test==t.test}create(){return this.regexp?new CVn(this):new kVn(this)}getCursor(t,n=0,r){let s=t.doc?t:gs.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?eT(this,s,n,r):JE(this,s,n,r)}}class Ckt{constructor(t){this.spec=t}}function wVn(e,t,n){return(r,s,a,i)=>{if(n&&!n(r,s,a,i))return!1;let l=r>=i&&s<=i+a.length?a.slice(r-i,s-i):t.doc.sliceString(r,s);return e(l,t,r,s)}}function JE(e,t,n,r){let s;return e.wholeWord&&(s=SVn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=wVn(e.test,t,s)),new $x(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function SVn(e,t){return(n,r,s,a)=>((a>n||a+s.length<r)&&(a=Math.max(0,n-2),s=e.sliceString(a,Math.min(e.length,r+2))),(t(qB(s,n-a))!=yo.Word||t(VB(s,n-a))!=yo.Word)&&(t(VB(s,r-a))!=yo.Word||t(qB(s,r-a))!=yo.Word))}class kVn extends Ckt{constructor(t){super(t)}nextMatch(t,n,r){let s=JE(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=JE(this.spec,t,0,a).nextOverlapping()}return s.done||s.value.from==n&&s.value.to==r?null:s.value}prevMatchInRange(t,n,r){for(let s=r;;){let a=Math.max(n,s-1e4-this.spec.unquoted.length),i=JE(this.spec,t,a,s),l=null;for(;!i.nextOverlapping().done;)l=i.value;if(l)return l;if(a==n)return null;s-=1e4}}prevMatch(t,n,r){let s=this.prevMatchInRange(t,0,n);return s||(s=this.prevMatchInRange(t,Math.max(0,r-this.spec.unquoted.length),t.doc.length)),s&&(s.from!=n||s.to!=r)?s:null}getReplacement(t){return this.spec.unquote(this.spec.replace)}matchAll(t,n){let r=JE(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=JE(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}function OVn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function eT(e,t,n,r){let s;return e.wholeWord&&(s=_Vn(t.charCategorizer(t.selection.main.head))),e.test&&(s=OVn(e.test,t,s)),new kkt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function qB(e,t){return e.slice(Ic(e,t,!1),t)}function VB(e,t){return e.slice(t,Ic(e,t))}function _Vn(e){return(t,n,r)=>!r[0].length||(e(qB(r.input,r.index))!=yo.Word||e(VB(r.input,r.index))!=yo.Word)&&(e(VB(r.input,r.index+r[0].length))!=yo.Word||e(qB(r.input,r.index+r[0].length))!=yo.Word)}class CVn extends Ckt{nextMatch(t,n,r){let s=eT(this.spec,t,r,t.doc.length).next();return s.done&&(s=eT(this.spec,t,0,n).next()),s.done?null:s.value}prevMatchInRange(t,n,r){for(let s=1;;s++){let a=Math.max(n,r-s*1e4),i=eT(this.spec,t,a,r),l=null;for(;!i.next().done;)l=i.value;if(l&&(a==n||l.from>a+10))return l;if(a==n)return null}}prevMatch(t,n,r){return this.prevMatchInRange(t,0,n)||this.prevMatchInRange(t,r,t.doc.length)}getReplacement(t){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(n,r)=>{if(r=="&")return t.match[0];if(r=="$")return"$";for(let s=r.length;s>0;s--){let a=+r.slice(0,s);if(a>0&&a<t.match.length)return t.match[a]+r.slice(s)}return n})}matchAll(t,n){let r=eT(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=eT(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}const TM=dr.define(),sOe=dr.define(),Yw=vl.define({create(e){return new Xee(sve(e).create(),null)},update(e,t){for(let n of t.effects)n.is(TM)?e=new Xee(n.value.create(),e.panel):n.is(sOe)&&(e=new Xee(e.query,n.value?aOe:null));return e},provide:e=>yM.from(e,t=>t.panel)});class Xee{constructor(t,n){this.query=t,this.panel=n}}const EVn=Tn.mark({class:"cm-searchMatch"}),TVn=Tn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),jVn=ko.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Yw))}update(e){let t=e.state.field(Yw);(t!=e.startState.field(Yw)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return Tn.none;let{view:n}=this,r=new Hd;for(let s=0,a=n.visibleRanges,i=a.length;s<i;s++){let{from:l,to:c}=a[s];for(;s<i-1&&c>a[s+1].from-500;)c=a[++s].to;e.highlight(n.state,l,c,(u,d)=>{let f=n.state.selection.ranges.some(p=>p.from==u&&p.to==d);r.add(u,d,f?TVn:EVn)})}return r.finish()}},{decorations:e=>e.decorations});function Q3(e){return t=>{let n=t.state.field(Yw,!1);return n&&n.query.spec.valid?e(t,n):jkt(t)}}const HB=Q3((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=wt.single(r.from,r.to),a=e.state.facet(_I);return e.dispatch({selection:s,effects:[iOe(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),Tkt(e),!0}),WB=Q3((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let a=wt.single(s.from,s.to),i=e.state.facet(_I);return e.dispatch({selection:a,effects:[iOe(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),Tkt(e),!0}),NVn=Q3((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)}),IVn=({state:e,dispatch:t})=>{let n=e.selection;if(n.ranges.length>1||n.main.empty)return!1;let{from:r,to:s}=n.main,a=[],i=0;for(let l=new $x(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(i=a.length),a.push(wt.range(l.value.from,l.value.to))}return t(e.update({selection:wt.create(a,i),userEvent:"select.search.matches"})),!0},r9e=Q3((e,{query:t})=>{let{state:n}=e,{from:r,to:s}=n.selection.main;if(n.readOnly)return!1;let a=t.nextMatch(n,r,r);if(!a)return!1;let i=a,l=[],c,u,d=[];i.precise?i.from==r&&i.to==s&&(u=n.toText(t.getReplacement(i)),l.push({from:i.from,to:i.to,insert:u}),i=t.nextMatch(n,i.from,i.to),d.push(Rt.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+"."))):i=t.nextMatch(n,i.from,i.to);let f=e.state.changes(l);return i&&(c=wt.single(i.from,i.to).map(f),d.push(iOe(e,i)),d.push(n.facet(_I).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),AVn=Q3((e,{query:t})=>{if(e.state.readOnly)return!1;let n=[];for(let s of t.matchAll(e.state,1e9)){let{from:a,to:i,precise:l}=s;l&&n.push({from:a,to:i,insert:t.getReplacement(s)})}if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:Rt.announce.of(r),userEvent:"input.replace.all"}),!0});function aOe(e){return e.state.facet(_I).createPanel(e)}function sve(e,t){var n,r,s,a,i;let l=e.selection.main,c=l.empty||l.to>l.from+100?"":e.sliceDoc(l.from,l.to);if(t&&!c)return t;let u=e.facet(_I);return new _kt({search:((n=t?.literal)!==null&&n!==void 0?n:u.literal)?c:c.replace(/\n/g,"\\n"),caseSensitive:(r=t?.caseSensitive)!==null&&r!==void 0?r:u.caseSensitive,literal:(s=t?.literal)!==null&&s!==void 0?s:u.literal,regexp:(a=t?.regexp)!==null&&a!==void 0?a:u.regexp,wholeWord:(i=t?.wholeWord)!==null&&i!==void 0?i:u.wholeWord})}function Ekt(e){let t=wke(e,aOe);return t&&t.dom.querySelector("[main-field]")}function Tkt(e){let t=Ekt(e);t&&t==e.root.activeElement&&t.select()}const jkt=e=>{let t=e.state.field(Yw,!1);if(t&&t.panel){let n=Ekt(e);if(n&&n!=e.root.activeElement){let r=sve(e.state,t.query.spec);r.valid&&e.dispatch({effects:TM.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[sOe.of(!0),t?TM.of(sve(e.state,t.query.spec)):dr.appendConfig.of(MVn)]});return!0},Nkt=e=>{let t=e.state.field(Yw,!1);if(!t||!t.panel)return!1;let n=wke(e,aOe);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:sOe.of(!1)}),!0},RVn=[{key:"Mod-f",run:jkt,scope:"editor search-panel"},{key:"F3",run:HB,shift:WB,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:HB,shift:WB,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:Nkt,scope:"editor search-panel"},{key:"Mod-Shift-l",run:IVn},{key:"Mod-Alt-g",run:cVn},{key:"Mod-d",run:xVn,preventDefault:!0}];class PVn{constructor(t){this.view=t;let n=this.query=t.state.field(Yw).query.spec;this.commit=this.commit.bind(this),this.searchField=oi("input",{value:n.search,placeholder:up(t,"Find"),"aria-label":up(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=oi("input",{value:n.replace,placeholder:up(t,"Replace"),"aria-label":up(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=oi("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=oi("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=oi("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return oi("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=oi("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>HB(t),[up(t,"next")]),r("prev",()=>WB(t),[up(t,"previous")]),r("select",()=>NVn(t),[up(t,"all")]),oi("label",null,[this.caseField,up(t,"match case")]),oi("label",null,[this.reField,up(t,"regexp")]),oi("label",null,[this.wordField,up(t,"by word")]),...t.state.readOnly?[]:[oi("br"),this.replaceField,r("replace",()=>r9e(t),[up(t,"replace")]),r("replaceAll",()=>AVn(t),[up(t,"replace all")])],oi("button",{name:"close",onclick:()=>Nkt(t),"aria-label":up(t,"close"),type:"button"},["×"])])}commit(){let t=new _kt({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:TM.of(t)}))}keydown(t){ezn(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?WB:HB)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),r9e(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(TM)&&!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(_I).top}}function up(e,t){return e.state.phrase(t)}const fF=30,pF=/[\s\.,:;?!]/;function iOe(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),s=e.state.doc.lineAt(n).to,a=Math.max(r.from,t-fF),i=Math.min(s,n+fF),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<fF;c++)if(!pF.test(l[c+1])&&pF.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-fF;c--)if(!pF.test(l[c-1])&&pF.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 $Vn=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"}}),MVn=[Yw,th.low(jVn),$Vn];class s9e{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class _k{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(jM).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new Hd,l=[],c=0;for(let d=0;;){let f=d==a.length?null:a[d];if(!f&&!l.length)break;let p,h;for(l.length?(p=c,h=l.reduce((v,y)=>Math.min(v,y.to),f&&f.from>p?f.from:1e8)):(p=f.from,h=f.to,l.push(f),d++);d<a.length;){let v=a[d];if(v.from==p&&(v.to>v.from||v.to==p))l.push(v),d++,h=Math.min(v.to,h);else{h=Math.min(v.from,h);break}}let m=QVn(l);if(l.some(v=>v.from==v.to||v.from==v.to-1&&r.doc.lineAt(v.from).to==v.from))i.add(p,p,Tn.widget({widget:new HVn(m),diagnostics:l.slice()}));else{let v=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(p,h,Tn.mark({class:"cm-lintRange cm-lintRange-"+m+v,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>h)}))}c=h;for(let v=0;v<l.length;v++)l[v].to<=c&&l.splice(v--,1)}let u=i.finish();return new _k(u,n,eN(u))}}function eN(e,t=null,n=0){let r=null;return e.between(n,1e9,(s,a,{spec:i})=>{if(!(t&&i.diagnostics.indexOf(t)<0))if(!r)r=new s9e(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new s9e(r.from,a,r.diagnostic)}}),r}function DVn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(jM).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(Ikt))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function LVn(e,t){return e.field(Np,!1)?t:t.concat(dr.appendConfig.of(YVn))}const Ikt=dr.define(),oOe=dr.define(),Akt=dr.define(),Np=vl.define({create(){return new _k(Tn.none,null,null)},update(e,t){if(t.docChanged&&e.diagnostics.size){let n=e.diagnostics.map(t.changes),r=null,s=e.panel;if(e.selected){let a=t.changes.mapPos(e.selected.from,1);r=eN(n,e.selected.diagnostic,a)||eN(n,null,a)}!n.size&&s&&t.state.facet(jM).autoPanel&&(s=null),e=new _k(n,s,r)}for(let n of t.effects)if(n.is(Ikt)){let r=t.state.facet(jM).autoPanel?n.value.length?NM.open:null:e.panel;e=_k.init(n.value,r,t.state)}else n.is(oOe)?e=new _k(e.diagnostics,n.value?NM.open:null,e.selected):n.is(Akt)&&(e=new _k(e.diagnostics,e.panel,n.value));return e},provide:e=>[yM.from(e,t=>t.panel),Rt.decorations.from(e,t=>t.diagnostics)]}),FVn=Tn.mark({class:"cm-lintRange cm-lintRange-active"});function zVn(e,t,n){let{diagnostics:r}=e.state.field(Np),s,a=-1,i=-1;r.between(t-(n<0?1:0),t+(n>0?1:0),(c,u,{spec:d})=>{if(t>=c&&t<=u&&(c==u||(t>c||n>0)&&(t<u||n<0)))return s=d.diagnostics,a=c,i=u,!1});let l=e.state.facet(jM).tooltipFilter;return s&&l&&(s=l(s,e.state)),s?{pos:a,end:i,above:e.state.doc.lineAt(a).to<i,create(){return{dom:BVn(e,s)}}}:null}function BVn(e,t){return oi("ul",{class:"cm-tooltip-lint"},t.map(n=>Pkt(e,n,!1)))}const UVn=e=>{let t=e.state.field(Np,!1);(!t||!t.panel)&&e.dispatch({effects:LVn(e.state,[oOe.of(!0)])});let n=wke(e,NM.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},a9e=e=>{let t=e.state.field(Np,!1);return!t||!t.panel?!1:(e.dispatch({effects:oOe.of(!1)}),!0)},qVn=e=>{let t=e.state.field(Np,!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)},VVn=[{key:"Mod-Shift-m",run:UVn,preventDefault:!0},{key:"F8",run:qVn}],jM=wn.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...Fy(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:i9e,tooltipFilter:i9e,needsRefresh:(t,n)=>t?n?r=>t(r)||n(r):t:n,hideOn:(t,n)=>t?n?(r,s,a)=>t(r,s,a)||n(r,s,a):t:n,autoPanel:(t,n)=>t||n})}}});function i9e(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function Rkt(e){let t=[];if(e)e:for(let{name:n}of e){for(let r=0;r<n.length;r++){let s=n[r];if(/[a-zA-Z]/.test(s)&&!t.some(a=>a.toLowerCase()==s.toLowerCase())){t.push(s);continue e}}t.push("")}return t}function Pkt(e,t,n){var r;let s=n?Rkt(t.actions):[];return oi("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},oi("span",{class:"cm-diagnosticText"},t.renderMessage?t.renderMessage(e):t.message),(r=t.actions)===null||r===void 0?void 0:r.map((a,i)=>{let l=!1,c=h=>{if(h.preventDefault(),l)return;l=!0;let m=eN(e.state.field(Np).diagnostics,t);m&&a.apply(e,m.from,m.to)},{name:u}=a,d=s[i]?u.indexOf(s[i]):-1,f=d<0?u:[u.slice(0,d),oi("u",u.slice(d,d+1)),u.slice(d+1)],p=a.markClass?" "+a.markClass:"";return oi("button",{type:"button",class:"cm-diagnosticAction"+p,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&oi("div",{class:"cm-diagnosticSource"},t.source))}class HVn extends nh{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return oi("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class o9e{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=Pkt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class NM{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)a9e(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:a}=this.items[this.selectedIndex],i=Rkt(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=eN(this.view.state.field(Np).diagnostics,a);c&&a.actions[l].apply(t,c.from,c.to)}}else return;s.preventDefault()},r=s=>{for(let a=0;a<this.items.length;a++)this.items[a].dom.contains(s.target)&&this.moveSelection(a)};this.list=oi("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=oi("div",{class:"cm-panel-lint"},this.list,oi("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>a9e(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Np).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(Np),r=0,s=!1,a=null,i=new Set;for(t.between(0,this.view.state.doc.length,(l,c,{spec:u})=>{for(let d of u.diagnostics){if(i.has(d))continue;i.add(d);let f=-1,p;for(let h=r;h<this.items.length;h++)if(this.items[h].diagnostic==d){f=h;break}f<0?(p=new o9e(this.view,d),this.items.splice(r,0,p),s=!0):(p=this.items[f],f>r&&(this.items.splice(r,f-r),s=!0)),n&&p.diagnostic==n.diagnostic?p.dom.hasAttribute("aria-selected")||(p.dom.setAttribute("aria-selected","true"),a=p):p.dom.hasAttribute("aria-selected")&&p.dom.removeAttribute("aria-selected"),r++}});r<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0);)s=!0,this.items.pop();this.items.length==0&&(this.items.push(new o9e(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),s=!0),a?(this.list.setAttribute("aria-activedescendant",a.id),this.view.requestMeasure({key:this,read:()=>({sel:a.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:l,panel:c})=>{let u=c.height/this.list.offsetHeight;l.top<c.top?this.list.scrollTop-=(c.top-l.top)/u:l.bottom>c.bottom&&(this.list.scrollTop+=(l.bottom-c.bottom)/u)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let t=this.list.firstChild;function n(){let r=t;t=r.nextSibling,r.remove()}for(let r of this.items)if(r.dom.parentNode==this.list){for(;t!=r.dom;)n();t=r.dom.nextSibling}else this.list.insertBefore(r.dom,t);for(;t;)n()}moveSelection(t){if(this.selectedIndex<0)return;let n=this.view.state.field(Np),r=eN(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:Akt.of(r)})}static open(t){return new NM(t)}}function WVn(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 hF(e){return WVn(`<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 ZVn=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:hF("#d11")},".cm-lintRange-warning":{backgroundImage:hF("orange")},".cm-lintRange-info":{backgroundImage:hF("#999")},".cm-lintRange-hint":{backgroundImage:hF("#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 GVn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function QVn(e){let t="hint",n=1;for(let r of e){let s=GVn(r.severity);s>n&&(n=s,t=r.severity)}return t}const YVn=[Np,Rt.decorations.compute([Np],e=>{let{selected:t,panel:n}=e.field(Np);return!t||!n||t.from==t.to?Tn.none:Tn.set([FVn.range(t.from,t.to)])}),Uzn(zVn,{hideOn:DVn}),ZVn];var l9e=function(t){t===void 0&&(t={});var n=t,r=n.crosshairCursor,s=r===void 0?!1:r,a=[];t.closeBracketsKeymap!==!1&&(a=a.concat(F9n)),t.defaultKeymap!==!1&&(a=a.concat(iVn)),t.searchKeymap!==!1&&(a=a.concat(RVn)),t.historyKeymap!==!1&&(a=a.concat(pqn)),t.foldKeymap!==!1&&(a=a.concat(O8n)),t.completionKeymap!==!1&&(a=a.concat(T1t)),t.lintKeymap!==!1&&(a=a.concat(VVn));var i=[];return t.lineNumbers!==!1&&i.push(e8n()),t.highlightActiveLineGutter!==!1&&i.push(r8n()),t.highlightSpecialChars!==!1&&i.push(gzn()),t.history!==!1&&i.push(sqn()),t.foldGutter!==!1&&i.push(T8n()),t.drawSelection!==!1&&i.push(izn()),t.dropCursor!==!1&&i.push(dzn()),t.allowMultipleSelections!==!1&&i.push(gs.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(g8n()),t.syntaxHighlighting!==!1&&i.push(rS(A8n,{fallback:!0})),t.bracketMatching!==!1&&i.push(F8n()),t.closeBrackets!==!1&&i.push($9n()),t.autocompletion!==!1&&i.push(E1t()),t.rectangularSelection!==!1&&i.push(Nzn()),s!==!1&&i.push(Rzn()),t.highlightActiveLine!==!1&&i.push(Szn()),t.highlightSelectionMatches!==!1&&i.push(fVn()),t.tabSize&&typeof t.tabSize=="number"&&i.push(wI.of(" ".repeat(t.tabSize))),i.concat([xI.of(a.flat())]).filter(Boolean)};const KVn="#e5c07b",c9e="#e06c75",XVn="#56b6c2",JVn="#ffffff",V8="#abb2bf",ave="#7d8799",eHn="#61afef",tHn="#98c379",u9e="#d19a66",nHn="#c678dd",rHn="#21252b",d9e="#2c313a",f9e="#282c34",Jee="#353a42",sHn="#3E4451",p9e="#528bff",aHn=Rt.theme({"&":{color:V8,backgroundColor:f9e},".cm-content":{caretColor:p9e},".cm-cursor, .cm-dropCursor":{borderLeftColor:p9e},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:sHn},".cm-panels":{backgroundColor:rHn,color:V8},".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:f9e,color:ave,border:"none"},".cm-activeLineGutter":{backgroundColor:d9e},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:Jee},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:Jee,borderBottomColor:Jee},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:d9e,color:V8}}},{dark:!0}),iHn=Kg.define([{tag:de.keyword,color:nHn},{tag:[de.name,de.deleted,de.character,de.propertyName,de.macroName],color:c9e},{tag:[de.function(de.variableName),de.labelName],color:eHn},{tag:[de.color,de.constant(de.name),de.standard(de.name)],color:u9e},{tag:[de.definition(de.name),de.separator],color:V8},{tag:[de.typeName,de.className,de.number,de.changed,de.annotation,de.modifier,de.self,de.namespace],color:KVn},{tag:[de.operator,de.operatorKeyword,de.url,de.escape,de.regexp,de.link,de.special(de.string)],color:XVn},{tag:[de.meta,de.comment],color:ave},{tag:de.strong,fontWeight:"bold"},{tag:de.emphasis,fontStyle:"italic"},{tag:de.strikethrough,textDecoration:"line-through"},{tag:de.link,color:ave,textDecoration:"underline"},{tag:de.heading,fontWeight:"bold",color:c9e},{tag:[de.atom,de.bool,de.special(de.variableName)],color:u9e},{tag:[de.processingInstruction,de.string,de.inserted],color:tHn},{tag:de.invalid,color:JVn}]),oHn=[aHn,rS(iHn)];var lHn=Rt.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),cHn=function(t){t===void 0&&(t={});var n=t,r=n.indentWithTab,s=r===void 0?!0:r,a=n.editable,i=a===void 0?!0:a,l=n.readOnly,c=l===void 0?!1:l,u=n.theme,d=u===void 0?"light":u,f=n.placeholder,p=f===void 0?"":f,h=n.basicSetup,m=h===void 0?!0:h,v=[];switch(s&&v.unshift(xI.of([oVn])),m&&(typeof m=="boolean"?v.unshift(l9e()):v.unshift(l9e(m))),p&&v.unshift(Czn(p)),d){case"light":v.push(lHn);break;case"dark":v.push(oHn);break;case"none":break;default:v.push(d);break}return i===!1&&v.push(Rt.editable.of(!1)),c&&v.push(gs.readOnly.of(!0)),[...v]},uHn=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 dHn{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 h9e{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 ete=null,fHn=()=>typeof window>"u"?new h9e:(ete||(ete=new h9e),ete),pHn=Rt.theme({"& .cm-scroller":{height:"100% !important"}}),m9e=null,tte=null;function hHn(e,t,n,r,s,a){if(!e&&!t&&!n&&!r&&!s&&!a)return null;var i=JSON.stringify({height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a});return i===m9e||(m9e=i,tte=Rt.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a}})),tte}var g9e=Ly.define(),mHn=200,gHn=[];function vHn(e){var t=e.value,n=e.selection,r=e.onChange,s=e.onStatistics,a=e.onCreateEditor,i=e.onUpdate,l=e.extensions,c=l===void 0?gHn:l,u=e.autoFocus,d=e.theme,f=d===void 0?"light":d,p=e.height,h=p===void 0?null:p,m=e.minHeight,v=m===void 0?null:m,y=e.maxHeight,b=y===void 0?null:y,x=e.width,S=x===void 0?null:x,k=e.minWidth,_=k===void 0?null:k,C=e.maxWidth,T=C===void 0?null:C,E=e.placeholder,N=E===void 0?"":E,I=e.editable,A=I===void 0?!0:I,R=e.readOnly,L=R===void 0?!1:R,D=e.indentWithTab,F=D===void 0?!0:D,H=e.basicSetup,B=H===void 0?!0:H,z=e.root,V=e.initialState,M=g.useState(),G=M[0],U=M[1],$=g.useState(),q=$[0],Z=$[1],Y=g.useState(),ne=Y[0],J=Y[1],ee=g.useState(()=>({current:null}))[0],re=g.useState(()=>({current:null}))[0],le=hHn(h,v,b,S,_,T),X=Rt.updateListener.of(pe=>{if(pe.docChanged&&typeof r=="function"&&!pe.transactions.some(ve=>ve.annotation(g9e))){ee.current?ee.current.reset():(ee.current=new dHn(()=>{if(re.current){var ve=re.current;re.current=null,ve()}ee.current=null},mHn),fHn().add(ee.current));var ce=pe.state.doc,Se=ce.toString();r(Se,pe)}s&&s(uHn(pe))}),te=cHn({theme:f,editable:A,readOnly:L,placeholder:N,indentWithTab:F,basicSetup:B}),se=[X,...le?[le]:[],pHn,...te];return i&&typeof i=="function"&&se.push(Rt.updateListener.of(i)),se=se.concat(c),g.useLayoutEffect(()=>{if(G&&!ne){var pe={doc:t,selection:n,extensions:se},ce=V?gs.fromJSON(V.json,pe,V.fields):gs.create(pe);if(J(ce),!q){var Se=new Rt({state:ce,parent:G,root:z});Z(Se),a&&a(Se,ce)}}return()=>{q&&(J(void 0),Z(void 0))}},[G,ne]),g.useEffect(()=>{e.container&&U(e.container)},[e.container]),g.useEffect(()=>()=>{q&&(q.destroy(),Z(void 0)),ee.current&&(ee.current.cancel(),ee.current=null)},[q]),g.useEffect(()=>{u&&q&&q.focus()},[u,q]),g.useEffect(()=>{q&&q.dispatch({effects:dr.reconfigure.of(se)})},[f,c,h,v,b,S,_,T,N,A,L,F,B,r,i]),g.useEffect(()=>{if(t!==void 0){var pe=q?q.state.doc.toString():"";if(q&&t!==pe){var ce=ee.current&&!ee.current.isDone,Se=()=>{q&&t!==q.state.doc.toString()&&q.dispatch({changes:{from:0,to:q.state.doc.toString().length,insert:t||""},annotations:[g9e.of(!0)]})};ce?re.current=Se:Se()}}},[t,q]),{state:ne,setState:J,view:q,setView:Z,container:G,setContainer:U}}var yHn=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],rd=g.forwardRef((e,t)=>{var n=e.className,r=e.value,s=r===void 0?"":r,a=e.selection,i=e.extensions,l=i===void 0?[]:i,c=e.onChange,u=e.onStatistics,d=e.onCreateEditor,f=e.onUpdate,p=e.autoFocus,h=e.theme,m=h===void 0?"light":h,v=e.height,y=e.minHeight,b=e.maxHeight,x=e.width,S=e.minWidth,k=e.maxWidth,_=e.basicSetup,C=e.placeholder,T=e.indentWithTab,E=e.editable,N=e.readOnly,I=e.root,A=e.initialState,R=USt(e,yHn),L=g.useRef(null),D=vHn({root:I,value:s,autoFocus:p,theme:m,height:v,minHeight:y,maxHeight:b,width:x,minWidth:S,maxWidth:k,basicSetup:_,placeholder:C,indentWithTab:T,editable:E,readOnly:N,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),F=D.state,H=D.view,B=D.container,z=D.setContainer;g.useImperativeHandle(t,()=>({editor:L.current,state:F,view:H}),[L,B,F,H]);var V=g.useCallback(G=>{L.current=G,z(G)},[z]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var M=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",GO({ref:V,className:""+M+(n?" "+n:"")},R))});rd.displayName="CodeMirror";const bHn={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 nte=null;function xHn(){return nte||(nte=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Ma(()=>import("./core-lanFcZkL.js"),__vite__mapDeps([0,1,2]),import.meta.url),Ma(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[Ma(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Ma(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Ma(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Ma(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Ma(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Ma(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Ma(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Ma(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Ma(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Ma(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Ma(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Ma(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Ma(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Ma(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([4,5,6]),import.meta.url),Ma(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Ma(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),nte}async function wHn(e,t){const n=bHn[t?.toLowerCase()];if(!n)return null;const r=await xHn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function SHn(e){return new VO(Cke.define(e))}const $kt=[dg.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return Ma(()=>Promise.resolve().then(()=>uF),void 0,import.meta.url).then(e=>e.javascript())}}),dg.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return Ma(()=>Promise.resolve().then(()=>K8n),void 0,import.meta.url).then(e=>e.json())}}),dg.of({name:"JSX",extensions:["jsx"],load(){return Ma(()=>Promise.resolve().then(()=>uF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),dg.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return Ma(()=>Promise.resolve().then(()=>HUn),void 0,import.meta.url).then(e=>e.markdown())}}),dg.of({name:"TSX",extensions:["tsx"],load(){return Ma(()=>Promise.resolve().then(()=>uF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),dg.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return Ma(()=>Promise.resolve().then(()=>uF),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),dg.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return Ma(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>SHn(e.shell))}})];function kHn(e,t=5){if(!e?.properties)return[];const n=[];function r(s,a,i){if(i>t)return;const l=Array.isArray(s.type)?s.type.join(" | "):s.type;if(n.push({path:a,label:a,description:s.description??s.title,type:l}),s.properties)for(const[c,u]of Object.entries(s.properties))r(u,`${a}.${c}`,i+1);if(s.items?.properties)for(const[c,u]of Object.entries(s.items.properties))r(u,`${a}[].${c}`,i+1)}for(const[s,a]of Object.entries(e.properties))r(a,s,1);return n}function OHn(e){const t=kHn(e);return E1t({override:[_Hn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function _Hn(e){return t=>{const r=t.state.sliceDoc(Math.max(0,t.pos-50),t.pos).match(/\{\{([a-zA-Z0-9_.\[\]]*)?$/);if(!r)return null;const s=r[1]??"",a=t.pos-s.length,i=s?e.filter(c=>c.path.toLowerCase().startsWith(s.toLowerCase())):e;if(i.length===0)return null;const l=i.map(c=>({label:c.path,displayLabel:c.path,detail:c.type,info:c.description,apply:(u,d,f,p)=>{const v=u.state.sliceDoc(p,p+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:p,insert:v},selection:{anchor:f+v.length}})}}));return{from:a,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const CHn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,EHn=Tn.mark({class:"cm-variable-highlight"}),v9e=new Bwt({regexp:CHn,decoration:()=>EHn}),THn=ko.fromClass(class{decorations;constructor(e){this.decorations=v9e.createDeco(e)}update(e){this.decorations=v9e.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),jHn=THn;function NHn(){const e=kI({settings:{fontFamily:"var(--font-mono)",fontSize:"0.8rem",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"var(--neutral2)",background:"transparent",foreground:"var(--neutral6)",caret:"var(--neutral6)"},styles:[{tag:[de.className,de.propertyName],color:"var(--neutral6)"},{tag:de.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[de.heading1,de.heading2,de.heading3,de.heading4,de.heading5,de.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:de.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:de.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:de.link,color:"var(--accent3)",textDecoration:"underline"},{tag:de.url,color:"var(--accent3)"},{tag:de.monospace,color:"var(--neutral6)"},{tag:de.strikethrough,textDecoration:"line-through"},{tag:de.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=Rt.theme({".cm-editor":{backgroundColor:"transparent"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{color:"var(--neutral3)"},".cm-cursor":{borderLeftColor:"var(--neutral6)"},".cm-selectionBackground, .cm-content ::selection":{backgroundColor:"color-mix(in srgb, var(--accent3) 22%, transparent)"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}});return[e,t]}function IHn(){const e=Rt.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"0.8rem"},"&.cm-editor .cm-scroller":{fontFamily:"var(--font-mono)"},".cm-gutters":{backgroundColor:"transparent",color:"var(--neutral2)",borderRight:"none"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-activeLine":{backgroundColor:"transparent"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{backgroundColor:"transparent",color:"var(--neutral3)"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"var(--neutral6)"},"&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection":{background:"color-mix(in srgb, var(--accent3) 22%, transparent) !important"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}}),t=Kg.define([{tag:[de.comment,de.bracket],color:"var(--neutral2)"},{tag:[de.string,de.meta,de.regexp],color:"var(--accent1)"},{tag:[de.atom,de.bool,de.special(de.variableName)],color:"var(--accent6)"},{tag:[de.keyword,de.operator,de.tagName],color:"var(--accent2)"},{tag:[de.function(de.propertyName),de.propertyName],color:"var(--accent5)"},{tag:[de.definition(de.variableName),de.function(de.variableName),de.className,de.attributeName],color:"var(--accent3)"},{tag:[de.variableName,de.number],color:"var(--accent5)"},{tag:[de.name,de.quote],color:"var(--accent1)"},{tag:de.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[de.heading1,de.heading2,de.heading3,de.heading4,de.heading5,de.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[de.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[de.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:de.link,color:"var(--accent3)",textDecoration:"underline"},{tag:de.url,color:"var(--accent3)"},{tag:de.monospace,color:"var(--neutral6)"},{tag:de.strikethrough,textDecoration:"line-through"},{tag:[de.deleted],color:"var(--accent2)"},{tag:de.invalid,color:"var(--error)"},{tag:[de.standard(de.tagName)],color:"var(--accent1)"}]);return[e,rS(t)]}const s0=()=>{const e=K_().resolvedTheme==="dark";return g.useMemo(()=>e?NHn():IHn(),[e])},AHn=Ii(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"}}),RHn=th.highest(Rt.editorAttributes.of({style:"outline: none"})),PHn=th.highest(Rt.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),$Hn=[RHn,PHn],Zr=g.forwardRef(({data:e,value:t,onChange:n,showCopyButton:r=!0,className:s,language:a="json",highlightVariables:i=!1,placeholder:l,schema:c,autoFocus:u,lineNumbers:d=!0,lineWrapping:f=!0,editable:p,variant:h,...m},v)=>{const y=s0(),b=e?JSON.stringify(e,null,2):t??"",x=g.useMemo(()=>{const S=[...$Hn];return f&&S.push(Rt.lineWrapping),a==="json"?S.push(Dp):a==="markdown"&&S.push(Jke({base:ZO,codeLanguages:$kt})),i&&a==="markdown"&&S.push(jHn),c&&a==="markdown"&&S.push(OHn(c)),p===!1&&S.push(gs.readOnly.of(!0)),S},[a,i,c,p,f]);return o.jsxs("div",{className:K(AHn({variant:h}),s),...m,children:[r&&o.jsx(ka,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(rd,{ref:v,value:b,theme:y,extensions:x,onChange:n,editable:p,"aria-label":"Code editor",placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),MHn=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},DHn=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=s0(),{settings:r,setSettings:s}=NH(),a=r?.tracingOptions,i=g.useMemo(()=>MHn(a),[a]),[l,c]=g.useState(()=>i),u=g.useRef(!1);g.useEffect(()=>{u.current||c(i)},[i]);const d=p=>{u.current=!0,c(p)},f=()=>{if(!l){s({...r,tracingOptions:void 0}),t?.();return}try{const p=JSON.parse(l);typeof p=="object"&&p!==null&&s({...r,tracingOptions:p})}catch{return}t?.()};return o.jsxs("div",{className:"space-y-2 px-5 py-2",children:[o.jsx(me,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),o.jsx(rd,{value:l,onChange:d,theme:n,extensions:[Dp],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(oe,{type:"button",onClick:f,children:"Save"})})]})},LHn=()=>{const[e,t]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:o.jsx(oe,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(He,{children:o.jsx(g0e,{})})})}),o.jsx(vn,{children:"Run Options"})]}),o.jsx(vr,{open:e,onOpenChange:t,children:o.jsxs(yr,{children:[o.jsxs(br,{children:[o.jsx(pr,{children:"Run Options"}),o.jsx(Ps,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx(Mr,{children:o.jsx(DHn,{onSaved:()=>t(!1)})})]})})]})};function FHn({status:e}){switch(e){case"running":return o.jsx(Ut,{});case"failed":return o.jsx(or,{className:"text-accent2"});case"canceled":return o.jsx(Mc,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(r1,{className:"text-neutral3"});case"suspended":return o.jsx(mV,{className:"text-accent3"});case"success":return o.jsx(Qr,{className:"text-accent1"});default:return o.jsx(r1,{className:"text-neutral3"})}}function Mkt({status:e}){return o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:o.jsx(He,{"aria-label":e,className:"shrink-0",children:o.jsx(FHn,{status:e})})}),o.jsx(vn,{children:e})]})}var rte,y9e;function lOe(){if(y9e)return rte;y9e=1;var e="\0",t="\0",n="";class r{_isDirected=!0;_isMultigraph=!1;_isCompound=!1;_label;_defaultNodeLabelFn=()=>{};_defaultEdgeLabelFn=()=>{};_nodes={};_in={};_preds={};_out={};_sucs={};_edgeObjs={};_edgeLabels={};_nodeCount=0;_edgeCount=0;_parent;_children;constructor(d){d&&(this._isDirected=Object.hasOwn(d,"directed")?d.directed:!0,this._isMultigraph=Object.hasOwn(d,"multigraph")?d.multigraph:!1,this._isCompound=Object.hasOwn(d,"compound")?d.compound:!1),this._isCompound&&(this._parent={},this._children={},this._children[t]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(d){return this._label=d,this}graph(){return this._label}setDefaultNodeLabel(d){return this._defaultNodeLabelFn=d,typeof d!="function"&&(this._defaultNodeLabelFn=()=>d),this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){var d=this;return this.nodes().filter(f=>Object.keys(d._in[f]).length===0)}sinks(){var d=this;return this.nodes().filter(f=>Object.keys(d._out[f]).length===0)}setNodes(d,f){var p=arguments,h=this;return d.forEach(function(m){p.length>1?h.setNode(m,f):h.setNode(m)}),this}setNode(d,f){return Object.hasOwn(this._nodes,d)?(arguments.length>1&&(this._nodes[d]=f),this):(this._nodes[d]=arguments.length>1?f:this._defaultNodeLabelFn(d),this._isCompound&&(this._parent[d]=t,this._children[d]={},this._children[t][d]=!0),this._in[d]={},this._preds[d]={},this._out[d]={},this._sucs[d]={},++this._nodeCount,this)}node(d){return this._nodes[d]}hasNode(d){return Object.hasOwn(this._nodes,d)}removeNode(d){var f=this;if(Object.hasOwn(this._nodes,d)){var p=h=>f.removeEdge(f._edgeObjs[h]);delete this._nodes[d],this._isCompound&&(this._removeFromParentsChildList(d),delete this._parent[d],this.children(d).forEach(function(h){f.setParent(h)}),delete this._children[d]),Object.keys(this._in[d]).forEach(p),delete this._in[d],delete this._preds[d],Object.keys(this._out[d]).forEach(p),delete this._out[d],delete this._sucs[d],--this._nodeCount}return this}setParent(d,f){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(f===void 0)f=t;else{f+="";for(var p=f;p!==void 0;p=this.parent(p))if(p===d)throw new Error("Setting "+f+" as parent of "+d+" would create a cycle");this.setNode(f)}return this.setNode(d),this._removeFromParentsChildList(d),this._parent[d]=f,this._children[f][d]=!0,this}_removeFromParentsChildList(d){delete this._children[this._parent[d]][d]}parent(d){if(this._isCompound){var f=this._parent[d];if(f!==t)return f}}children(d=t){if(this._isCompound){var f=this._children[d];if(f)return Object.keys(f)}else{if(d===t)return this.nodes();if(this.hasNode(d))return[]}}predecessors(d){var f=this._preds[d];if(f)return Object.keys(f)}successors(d){var f=this._sucs[d];if(f)return Object.keys(f)}neighbors(d){var f=this.predecessors(d);if(f){const h=new Set(f);for(var p of this.successors(d))h.add(p);return Array.from(h.values())}}isLeaf(d){var f;return this.isDirected()?f=this.successors(d):f=this.neighbors(d),f.length===0}filterNodes(d){var f=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});f.setGraph(this.graph());var p=this;Object.entries(this._nodes).forEach(function([v,y]){d(v)&&f.setNode(v,y)}),Object.values(this._edgeObjs).forEach(function(v){f.hasNode(v.v)&&f.hasNode(v.w)&&f.setEdge(v,p.edge(v))});var h={};function m(v){var y=p.parent(v);return y===void 0||f.hasNode(y)?(h[v]=y,y):y in h?h[y]:m(y)}return this._isCompound&&f.nodes().forEach(v=>f.setParent(v,m(v))),f}setDefaultEdgeLabel(d){return this._defaultEdgeLabelFn=d,typeof d!="function"&&(this._defaultEdgeLabelFn=()=>d),this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(d,f){var p=this,h=arguments;return d.reduce(function(m,v){return h.length>1?p.setEdge(m,v,f):p.setEdge(m,v),v}),this}setEdge(){var d,f,p,h,m=!1,v=arguments[0];typeof v=="object"&&v!==null&&"v"in v?(d=v.v,f=v.w,p=v.name,arguments.length===2&&(h=arguments[1],m=!0)):(d=v,f=arguments[1],p=arguments[3],arguments.length>2&&(h=arguments[2],m=!0)),d=""+d,f=""+f,p!==void 0&&(p=""+p);var y=i(this._isDirected,d,f,p);if(Object.hasOwn(this._edgeLabels,y))return m&&(this._edgeLabels[y]=h),this;if(p!==void 0&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(d),this.setNode(f),this._edgeLabels[y]=m?h:this._defaultEdgeLabelFn(d,f,p);var b=l(this._isDirected,d,f,p);return d=b.v,f=b.w,Object.freeze(b),this._edgeObjs[y]=b,s(this._preds[f],d),s(this._sucs[d],f),this._in[f][y]=b,this._out[d][y]=b,this._edgeCount++,this}edge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return this._edgeLabels[h]}edgeAsObj(){const d=this.edge(...arguments);return typeof d!="object"?{label:d}:d}hasEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return Object.hasOwn(this._edgeLabels,h)}removeEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p),m=this._edgeObjs[h];return m&&(d=m.v,f=m.w,delete this._edgeLabels[h],delete this._edgeObjs[h],a(this._preds[f],d),a(this._sucs[d],f),delete this._in[f][h],delete this._out[d][h],this._edgeCount--),this}inEdges(d,f){var p=this._in[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.v===f):h}}outEdges(d,f){var p=this._out[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.w===f):h}}nodeEdges(d,f){var p=this.inEdges(d,f);if(p)return p.concat(this.outEdges(d,f))}}function s(u,d){u[d]?u[d]++:u[d]=1}function a(u,d){--u[d]||delete u[d]}function i(u,d,f,p){var h=""+d,m=""+f;if(!u&&h>m){var v=h;h=m,m=v}return h+n+m+n+(p===void 0?e:p)}function l(u,d,f,p){var h=""+d,m=""+f;if(!u&&h>m){var v=h;h=m,m=v}var y={v:h,w:m};return p&&(y.name=p),y}function c(u,d){return i(u,d.v,d.w,d.name)}return rte=r,rte}var ste,b9e;function zHn(){return b9e||(b9e=1,ste="2.2.4"),ste}var ate,x9e;function BHn(){return x9e||(x9e=1,ate={Graph:lOe(),version:zHn()}),ate}var ite,w9e;function UHn(){if(w9e)return ite;w9e=1;var e=lOe();ite={write:t,read:s};function t(a){var i={options:{directed:a.isDirected(),multigraph:a.isMultigraph(),compound:a.isCompound()},nodes:n(a),edges:r(a)};return a.graph()!==void 0&&(i.value=structuredClone(a.graph())),i}function n(a){return a.nodes().map(function(i){var l=a.node(i),c=a.parent(i),u={v:i};return l!==void 0&&(u.value=l),c!==void 0&&(u.parent=c),u})}function r(a){return a.edges().map(function(i){var l=a.edge(i),c={v:i.v,w:i.w};return i.name!==void 0&&(c.name=i.name),l!==void 0&&(c.value=l),c})}function s(a){var i=new e(a.options).setGraph(a.value);return a.nodes.forEach(function(l){i.setNode(l.v,l.value),l.parent&&i.setParent(l.v,l.parent)}),a.edges.forEach(function(l){i.setEdge({v:l.v,w:l.w,name:l.name},l.value)}),i}return ite}var ote,S9e;function qHn(){if(S9e)return ote;S9e=1,ote=e;function e(t){var n={},r=[],s;function a(i){Object.hasOwn(n,i)||(n[i]=!0,s.push(i),t.successors(i).forEach(a),t.predecessors(i).forEach(a))}return t.nodes().forEach(function(i){s=[],a(i),s.length&&r.push(s)}),r}return ote}var lte,k9e;function Dkt(){if(k9e)return lte;k9e=1;class e{_arr=[];_keyIndices={};size(){return this._arr.length}keys(){return this._arr.map(function(n){return n.key})}has(n){return Object.hasOwn(this._keyIndices,n)}priority(n){var r=this._keyIndices[n];if(r!==void 0)return this._arr[r].priority}min(){if(this.size()===0)throw new Error("Queue underflow");return this._arr[0].key}add(n,r){var s=this._keyIndices;if(n=String(n),!Object.hasOwn(s,n)){var a=this._arr,i=a.length;return s[n]=i,a.push({key:n,priority:r}),this._decrease(i),!0}return!1}removeMin(){this._swap(0,this._arr.length-1);var n=this._arr.pop();return delete this._keyIndices[n.key],this._heapify(0),n.key}decrease(n,r){var s=this._keyIndices[n];if(r>this._arr[s].priority)throw new Error("New priority is greater than current priority. Key: "+n+" Old: "+this._arr[s].priority+" New: "+r);this._arr[s].priority=r,this._decrease(s)}_heapify(n){var r=this._arr,s=2*n,a=s+1,i=n;s<r.length&&(i=r[s].priority<r[i].priority?s:i,a<r.length&&(i=r[a].priority<r[i].priority?a:i),i!==n&&(this._swap(n,i),this._heapify(i)))}_decrease(n){for(var r=this._arr,s=r[n].priority,a;n!==0&&(a=n>>1,!(r[a].priority<s));)this._swap(n,a),n=a}_swap(n,r){var s=this._arr,a=this._keyIndices,i=s[n],l=s[r];s[n]=l,s[r]=i,a[l.key]=n,a[i.key]=r}}return lte=e,lte}var cte,O9e;function Lkt(){if(O9e)return cte;O9e=1;var e=Dkt();cte=n;var t=()=>1;function n(s,a,i,l){return r(s,String(a),i||t,l||function(c){return s.outEdges(c)})}function r(s,a,i,l){var c={},u=new e,d,f,p=function(h){var m=h.v!==d?h.v:h.w,v=c[m],y=i(h),b=f.distance+y;if(y<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+h+" Weight: "+y);b<v.distance&&(v.distance=b,v.predecessor=d,u.decrease(m,b))};for(s.nodes().forEach(function(h){var m=h===a?0:Number.POSITIVE_INFINITY;c[h]={distance:m},u.add(h,m)});u.size()>0&&(d=u.removeMin(),f=c[d],f.distance!==Number.POSITIVE_INFINITY);)l(d).forEach(p);return c}return cte}var ute,_9e;function VHn(){if(_9e)return ute;_9e=1;var e=Lkt();ute=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return ute}var dte,C9e;function Fkt(){if(C9e)return dte;C9e=1,dte=e;function e(t){var n=0,r=[],s={},a=[];function i(l){var c=s[l]={onStack:!0,lowlink:n,index:n++};if(r.push(l),t.successors(l).forEach(function(f){Object.hasOwn(s,f)?s[f].onStack&&(c.lowlink=Math.min(c.lowlink,s[f].index)):(i(f),c.lowlink=Math.min(c.lowlink,s[f].lowlink))}),c.lowlink===c.index){var u=[],d;do d=r.pop(),s[d].onStack=!1,u.push(d);while(l!==d);a.push(u)}}return t.nodes().forEach(function(l){Object.hasOwn(s,l)||i(l)}),a}return dte}var fte,E9e;function HHn(){if(E9e)return fte;E9e=1;var e=Fkt();fte=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return fte}var pte,T9e;function WHn(){if(T9e)return pte;T9e=1,pte=t;var e=()=>1;function t(r,s,a){return n(r,s||e,a||function(i){return r.outEdges(i)})}function n(r,s,a){var i={},l=r.nodes();return l.forEach(function(c){i[c]={},i[c][c]={distance:0},l.forEach(function(u){c!==u&&(i[c][u]={distance:Number.POSITIVE_INFINITY})}),a(c).forEach(function(u){var d=u.v===c?u.w:u.v,f=s(u);i[c][d]={distance:f,predecessor:c}})}),l.forEach(function(c){var u=i[c];l.forEach(function(d){var f=i[d];l.forEach(function(p){var h=f[c],m=u[p],v=f[p],y=h.distance+m.distance;y<v.distance&&(v.distance=y,v.predecessor=m.predecessor)})})}),i}return pte}var hte,j9e;function zkt(){if(j9e)return hte;j9e=1;function e(n){var r={},s={},a=[];function i(l){if(Object.hasOwn(s,l))throw new t;Object.hasOwn(r,l)||(s[l]=!0,r[l]=!0,n.predecessors(l).forEach(i),delete s[l],a.push(l))}if(n.sinks().forEach(i),Object.keys(r).length!==n.nodeCount())throw new t;return a}class t extends Error{constructor(){super(...arguments)}}return hte=e,e.CycleException=t,hte}var mte,N9e;function ZHn(){if(N9e)return mte;N9e=1;var e=zkt();mte=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return mte}var gte,I9e;function Bkt(){if(I9e)return gte;I9e=1,gte=e;function e(s,a,i){Array.isArray(a)||(a=[a]);var l=s.isDirected()?f=>s.successors(f):f=>s.neighbors(f),c=i==="post"?t:n,u=[],d={};return a.forEach(f=>{if(!s.hasNode(f))throw new Error("Graph does not have node: "+f);c(f,l,d,u)}),u}function t(s,a,i,l){for(var c=[[s,!1]];c.length>0;){var u=c.pop();u[1]?l.push(u[0]):Object.hasOwn(i,u[0])||(i[u[0]]=!0,c.push([u[0],!0]),r(a(u[0]),d=>c.push([d,!1])))}}function n(s,a,i,l){for(var c=[s];c.length>0;){var u=c.pop();Object.hasOwn(i,u)||(i[u]=!0,l.push(u),r(a(u),d=>c.push(d)))}}function r(s,a){for(var i=s.length;i--;)a(s[i],i,s);return s}return gte}var vte,A9e;function GHn(){if(A9e)return vte;A9e=1;var e=Bkt();vte=t;function t(n,r){return e(n,r,"post")}return vte}var yte,R9e;function QHn(){if(R9e)return yte;R9e=1;var e=Bkt();yte=t;function t(n,r){return e(n,r,"pre")}return yte}var bte,P9e;function YHn(){if(P9e)return bte;P9e=1;var e=lOe(),t=Dkt();bte=n;function n(r,s){var a=new e,i={},l=new t,c;function u(f){var p=f.v===c?f.w:f.v,h=l.priority(p);if(h!==void 0){var m=s(f);m<h&&(i[p]=c,l.decrease(p,m))}}if(r.nodeCount()===0)return a;r.nodes().forEach(function(f){l.add(f,Number.POSITIVE_INFINITY),a.setNode(f)}),l.decrease(r.nodes()[0],0);for(var d=!1;l.size()>0;){if(c=l.removeMin(),Object.hasOwn(i,c))a.setEdge(c,i[c]);else{if(d)throw new Error("Input graph is not connected: "+r);d=!0}r.nodeEdges(c).forEach(u)}return a}return bte}var xte,$9e;function KHn(){return $9e||($9e=1,xte={components:qHn(),dijkstra:Lkt(),dijkstraAll:VHn(),findCycles:HHn(),floydWarshall:WHn(),isAcyclic:ZHn(),postorder:GHn(),preorder:QHn(),prim:YHn(),tarjan:Fkt(),topsort:zkt()}),xte}var wte,M9e;function Hg(){if(M9e)return wte;M9e=1;var e=BHn();return wte={Graph:e.Graph,json:UHn(),alg:KHn(),version:e.version},wte}var Ste,D9e;function XHn(){if(D9e)return Ste;D9e=1;class e{constructor(){let s={};s._next=s._prev=s,this._sentinel=s}dequeue(){let s=this._sentinel,a=s._prev;if(a!==s)return t(a),a}enqueue(s){let a=this._sentinel;s._prev&&s._next&&t(s),s._next=a._next,a._next._prev=s,a._next=s,s._prev=a}toString(){let s=[],a=this._sentinel,i=a._prev;for(;i!==a;)s.push(JSON.stringify(i,n)),i=i._prev;return"["+s.join(", ")+"]"}}function t(r){r._prev._next=r._next,r._next._prev=r._prev,delete r._next,delete r._prev}function n(r,s){if(r!=="_next"&&r!=="_prev")return s}return Ste=e,Ste}var kte,L9e;function JHn(){if(L9e)return kte;L9e=1;let e=Hg().Graph,t=XHn();kte=r;let n=()=>1;function r(u,d){if(u.nodeCount()<=1)return[];let f=i(u,d||n);return s(f.graph,f.buckets,f.zeroIdx).flatMap(h=>u.outEdges(h.v,h.w))}function s(u,d,f){let p=[],h=d[d.length-1],m=d[0],v;for(;u.nodeCount();){for(;v=m.dequeue();)a(u,d,f,v);for(;v=h.dequeue();)a(u,d,f,v);if(u.nodeCount()){for(let y=d.length-2;y>0;--y)if(v=d[y].dequeue(),v){p=p.concat(a(u,d,f,v,!0));break}}}return p}function a(u,d,f,p,h){let m=h?[]:void 0;return u.inEdges(p.v).forEach(v=>{let y=u.edge(v),b=u.node(v.v);h&&m.push({v:v.v,w:v.w}),b.out-=y,l(d,f,b)}),u.outEdges(p.v).forEach(v=>{let y=u.edge(v),b=v.w,x=u.node(b);x.in-=y,l(d,f,x)}),u.removeNode(p.v),m}function i(u,d){let f=new e,p=0,h=0;u.nodes().forEach(y=>{f.setNode(y,{v:y,in:0,out:0})}),u.edges().forEach(y=>{let b=f.edge(y.v,y.w)||0,x=d(y),S=b+x;f.setEdge(y.v,y.w,S),h=Math.max(h,f.node(y.v).out+=x),p=Math.max(p,f.node(y.w).in+=x)});let m=c(h+p+3).map(()=>new t),v=p+1;return f.nodes().forEach(y=>{l(m,v,f.node(y))}),{graph:f,buckets:m,zeroIdx:v}}function l(u,d,f){f.out?f.in?u[f.out-f.in+d].enqueue(f):u[u.length-1].enqueue(f):u[0].enqueue(f)}function c(u){const d=[];for(let f=0;f<u;f++)d.push(f);return d}return kte}var Ote,F9e;function Al(){if(F9e)return Ote;F9e=1;let e=Hg().Graph;Ote={addBorderNode:d,addDummyNode:t,applyWithChunking:h,asNonCompoundGraph:r,buildLayerMatrix:l,intersectRect:i,mapValues:C,maxRank:m,normalizeRanks:c,notime:b,partition:v,pick:_,predecessorWeights:a,range:k,removeEmptyRanks:u,simplify:n,successorWeights:s,time:y,uniqueId:S,zipObject:T};function t(E,N,I,A){for(var R=A;E.hasNode(R);)R=S(A);return I.dummy=N,E.setNode(R,I),R}function n(E){let N=new e().setGraph(E.graph());return E.nodes().forEach(I=>N.setNode(I,E.node(I))),E.edges().forEach(I=>{let A=N.edge(I.v,I.w)||{weight:0,minlen:1},R=E.edge(I);N.setEdge(I.v,I.w,{weight:A.weight+R.weight,minlen:Math.max(A.minlen,R.minlen)})}),N}function r(E){let N=new e({multigraph:E.isMultigraph()}).setGraph(E.graph());return E.nodes().forEach(I=>{E.children(I).length||N.setNode(I,E.node(I))}),E.edges().forEach(I=>{N.setEdge(I,E.edge(I))}),N}function s(E){let N=E.nodes().map(I=>{let A={};return E.outEdges(I).forEach(R=>{A[R.w]=(A[R.w]||0)+E.edge(R).weight}),A});return T(E.nodes(),N)}function a(E){let N=E.nodes().map(I=>{let A={};return E.inEdges(I).forEach(R=>{A[R.v]=(A[R.v]||0)+E.edge(R).weight}),A});return T(E.nodes(),N)}function i(E,N){let I=E.x,A=E.y,R=N.x-I,L=N.y-A,D=E.width/2,F=E.height/2;if(!R&&!L)throw new Error("Not possible to find intersection inside of the rectangle");let H,B;return Math.abs(L)*D>Math.abs(R)*F?(L<0&&(F=-F),H=F*R/L,B=F):(R<0&&(D=-D),H=D,B=D*L/R),{x:I+H,y:A+B}}function l(E){let N=k(m(E)+1).map(()=>[]);return E.nodes().forEach(I=>{let A=E.node(I),R=A.rank;R!==void 0&&(N[R][A.order]=I)}),N}function c(E){let N=E.nodes().map(A=>{let R=E.node(A).rank;return R===void 0?Number.MAX_VALUE:R}),I=h(Math.min,N);E.nodes().forEach(A=>{let R=E.node(A);Object.hasOwn(R,"rank")&&(R.rank-=I)})}function u(E){let N=E.nodes().map(D=>E.node(D).rank),I=h(Math.min,N),A=[];E.nodes().forEach(D=>{let F=E.node(D).rank-I;A[F]||(A[F]=[]),A[F].push(D)});let R=0,L=E.graph().nodeRankFactor;Array.from(A).forEach((D,F)=>{D===void 0&&F%L!==0?--R:D!==void 0&&R&&D.forEach(H=>E.node(H).rank+=R)})}function d(E,N,I,A){let R={width:0,height:0};return arguments.length>=4&&(R.rank=I,R.order=A),t(E,"border",R,N)}function f(E,N=p){const I=[];for(let A=0;A<E.length;A+=N){const R=E.slice(A,A+N);I.push(R)}return I}const p=65535;function h(E,N){if(N.length>p){const I=f(N);return E.apply(null,I.map(A=>E.apply(null,A)))}else return E.apply(null,N)}function m(E){const I=E.nodes().map(A=>{let R=E.node(A).rank;return R===void 0?Number.MIN_VALUE:R});return h(Math.max,I)}function v(E,N){let I={lhs:[],rhs:[]};return E.forEach(A=>{N(A)?I.lhs.push(A):I.rhs.push(A)}),I}function y(E,N){let I=Date.now();try{return N()}finally{console.log(E+" time: "+(Date.now()-I)+"ms")}}function b(E,N){return N()}let x=0;function S(E){var N=++x;return E+(""+N)}function k(E,N,I=1){N==null&&(N=E,E=0);let A=L=>L<N;I<0&&(A=L=>N<L);const R=[];for(let L=E;A(L);L+=I)R.push(L);return R}function _(E,N){const I={};for(const A of N)E[A]!==void 0&&(I[A]=E[A]);return I}function C(E,N){let I=N;return typeof N=="string"&&(I=A=>A[N]),Object.entries(E).reduce((A,[R,L])=>(A[R]=I(L,R),A),{})}function T(E,N){return E.reduce((I,A,R)=>(I[A]=N[R],I),{})}return Ote}var _te,z9e;function eWn(){if(z9e)return _te;z9e=1;let e=JHn(),t=Al().uniqueId;_te={run:n,undo:s};function n(a){(a.graph().acyclicer==="greedy"?e(a,l(a)):r(a)).forEach(c=>{let u=a.edge(c);a.removeEdge(c),u.forwardName=c.name,u.reversed=!0,a.setEdge(c.w,c.v,u,t("rev"))});function l(c){return u=>c.edge(u).weight}}function r(a){let i=[],l={},c={};function u(d){Object.hasOwn(c,d)||(c[d]=!0,l[d]=!0,a.outEdges(d).forEach(f=>{Object.hasOwn(l,f.w)?i.push(f):u(f.w)}),delete l[d])}return a.nodes().forEach(u),i}function s(a){a.edges().forEach(i=>{let l=a.edge(i);if(l.reversed){a.removeEdge(i);let c=l.forwardName;delete l.reversed,delete l.forwardName,a.setEdge(i.w,i.v,l,c)}})}return _te}var Cte,B9e;function tWn(){if(B9e)return Cte;B9e=1;let e=Al();Cte={run:t,undo:r};function t(s){s.graph().dummyChains=[],s.edges().forEach(a=>n(s,a))}function n(s,a){let i=a.v,l=s.node(i).rank,c=a.w,u=s.node(c).rank,d=a.name,f=s.edge(a),p=f.labelRank;if(u===l+1)return;s.removeEdge(a);let h,m,v;for(v=0,++l;l<u;++v,++l)f.points=[],m={width:0,height:0,edgeLabel:f,edgeObj:a,rank:l},h=e.addDummyNode(s,"edge",m,"_d"),l===p&&(m.width=f.width,m.height=f.height,m.dummy="edge-label",m.labelpos=f.labelpos),s.setEdge(i,h,{weight:f.weight},d),v===0&&s.graph().dummyChains.push(h),i=h;s.setEdge(i,c,{weight:f.weight},d)}function r(s){s.graph().dummyChains.forEach(a=>{let i=s.node(a),l=i.edgeLabel,c;for(s.setEdge(i.edgeObj,l);i.dummy;)c=s.successors(a)[0],s.removeNode(a),l.points.push({x:i.x,y:i.y}),i.dummy==="edge-label"&&(l.x=i.x,l.y=i.y,l.width=i.width,l.height=i.height),a=c,i=s.node(a)})}return Cte}var Ete,U9e;function ZB(){if(U9e)return Ete;U9e=1;const{applyWithChunking:e}=Al();Ete={longestPath:t,slack:n};function t(r){var s={};function a(i){var l=r.node(i);if(Object.hasOwn(s,i))return l.rank;s[i]=!0;let c=r.outEdges(i).map(d=>d==null?Number.POSITIVE_INFINITY:a(d.w)-r.edge(d).minlen);var u=e(Math.min,c);return u===Number.POSITIVE_INFINITY&&(u=0),l.rank=u}r.sources().forEach(a)}function n(r,s){return r.node(s.w).rank-r.node(s.v).rank-r.edge(s).minlen}return Ete}var Tte,q9e;function Ukt(){if(q9e)return Tte;q9e=1;var e=Hg().Graph,t=ZB().slack;Tte=n;function n(i){var l=new e({directed:!1}),c=i.nodes()[0],u=i.nodeCount();l.setNode(c,{});for(var d,f;r(l,i)<u;)d=s(l,i),f=l.hasNode(d.v)?t(i,d):-t(i,d),a(l,i,f);return l}function r(i,l){function c(u){l.nodeEdges(u).forEach(d=>{var f=d.v,p=u===f?d.w:f;!i.hasNode(p)&&!t(l,d)&&(i.setNode(p,{}),i.setEdge(u,p,{}),c(p))})}return i.nodes().forEach(c),i.nodeCount()}function s(i,l){return l.edges().reduce((u,d)=>{let f=Number.POSITIVE_INFINITY;return i.hasNode(d.v)!==i.hasNode(d.w)&&(f=t(l,d)),f<u[0]?[f,d]:u},[Number.POSITIVE_INFINITY,null])[1]}function a(i,l,c){i.nodes().forEach(u=>l.node(u).rank+=c)}return Tte}var jte,V9e;function nWn(){if(V9e)return jte;V9e=1;var e=Ukt(),t=ZB().slack,n=ZB().longestPath,r=Hg().alg.preorder,s=Hg().alg.postorder,a=Al().simplify;jte=i,i.initLowLimValues=d,i.initCutValues=l,i.calcCutValue=u,i.leaveEdge=p,i.enterEdge=h,i.exchangeEdges=m;function i(x){x=a(x),n(x);var S=e(x);d(S),l(S,x);for(var k,_;k=p(S);)_=h(S,x,k),m(S,x,k,_)}function l(x,S){var k=s(x,x.nodes());k=k.slice(0,k.length-1),k.forEach(_=>c(x,S,_))}function c(x,S,k){var _=x.node(k),C=_.parent;x.edge(k,C).cutvalue=u(x,S,k)}function u(x,S,k){var _=x.node(k),C=_.parent,T=!0,E=S.edge(k,C),N=0;return E||(T=!1,E=S.edge(C,k)),N=E.weight,S.nodeEdges(k).forEach(I=>{var A=I.v===k,R=A?I.w:I.v;if(R!==C){var L=A===T,D=S.edge(I).weight;if(N+=L?D:-D,y(x,k,R)){var F=x.edge(k,R).cutvalue;N+=L?-F:F}}}),N}function d(x,S){arguments.length<2&&(S=x.nodes()[0]),f(x,{},1,S)}function f(x,S,k,_,C){var T=k,E=x.node(_);return S[_]=!0,x.neighbors(_).forEach(N=>{Object.hasOwn(S,N)||(k=f(x,S,k,N,_))}),E.low=T,E.lim=k++,C?E.parent=C:delete E.parent,k}function p(x){return x.edges().find(S=>x.edge(S).cutvalue<0)}function h(x,S,k){var _=k.v,C=k.w;S.hasEdge(_,C)||(_=k.w,C=k.v);var T=x.node(_),E=x.node(C),N=T,I=!1;T.lim>E.lim&&(N=E,I=!0);var A=S.edges().filter(R=>I===b(x,x.node(R.v),N)&&I!==b(x,x.node(R.w),N));return A.reduce((R,L)=>t(S,L)<t(S,R)?L:R)}function m(x,S,k,_){var C=k.v,T=k.w;x.removeEdge(C,T),x.setEdge(_.v,_.w,{}),d(x),l(x,S),v(x,S)}function v(x,S){var k=x.nodes().find(C=>!S.node(C).parent),_=r(x,k);_=_.slice(1),_.forEach(C=>{var T=x.node(C).parent,E=S.edge(C,T),N=!1;E||(E=S.edge(T,C),N=!0),S.node(C).rank=S.node(T).rank+(N?E.minlen:-E.minlen)})}function y(x,S,k){return x.hasEdge(S,k)}function b(x,S,k){return k.low<=S.lim&&S.lim<=k.lim}return jte}var Nte,H9e;function rWn(){if(H9e)return Nte;H9e=1;var e=ZB(),t=e.longestPath,n=Ukt(),r=nWn();Nte=s;function s(c){var u=c.graph().ranker;if(u instanceof Function)return u(c);switch(c.graph().ranker){case"network-simplex":l(c);break;case"tight-tree":i(c);break;case"longest-path":a(c);break;case"none":break;default:l(c)}}var a=t;function i(c){t(c),n(c)}function l(c){r(c)}return Nte}var Ite,W9e;function sWn(){if(W9e)return Ite;W9e=1,Ite=e;function e(r){let s=n(r);r.graph().dummyChains.forEach(a=>{let i=r.node(a),l=i.edgeObj,c=t(r,s,l.v,l.w),u=c.path,d=c.lca,f=0,p=u[f],h=!0;for(;a!==l.w;){if(i=r.node(a),h){for(;(p=u[f])!==d&&r.node(p).maxRank<i.rank;)f++;p===d&&(h=!1)}if(!h){for(;f<u.length-1&&r.node(p=u[f+1]).minRank<=i.rank;)f++;p=u[f]}r.setParent(a,p),a=r.successors(a)[0]}})}function t(r,s,a,i){let l=[],c=[],u=Math.min(s[a].low,s[i].low),d=Math.max(s[a].lim,s[i].lim),f,p;f=a;do f=r.parent(f),l.push(f);while(f&&(s[f].low>u||d>s[f].lim));for(p=f,f=i;(f=r.parent(f))!==p;)c.push(f);return{path:l.concat(c.reverse()),lca:p}}function n(r){let s={},a=0;function i(l){let c=a;r.children(l).forEach(i),s[l]={low:c,lim:a++}}return r.children().forEach(i),s}return Ite}var Ate,Z9e;function aWn(){if(Z9e)return Ate;Z9e=1;let e=Al();Ate={run:t,cleanup:a};function t(i){let l=e.addDummyNode(i,"root",{},"_root"),c=r(i),u=Object.values(c),d=e.applyWithChunking(Math.max,u)-1,f=2*d+1;i.graph().nestingRoot=l,i.edges().forEach(h=>i.edge(h).minlen*=f);let p=s(i)+1;i.children().forEach(h=>n(i,l,f,p,d,c,h)),i.graph().nodeRankFactor=f}function n(i,l,c,u,d,f,p){let h=i.children(p);if(!h.length){p!==l&&i.setEdge(l,p,{weight:0,minlen:c});return}let m=e.addBorderNode(i,"_bt"),v=e.addBorderNode(i,"_bb"),y=i.node(p);i.setParent(m,p),y.borderTop=m,i.setParent(v,p),y.borderBottom=v,h.forEach(b=>{n(i,l,c,u,d,f,b);let x=i.node(b),S=x.borderTop?x.borderTop:b,k=x.borderBottom?x.borderBottom:b,_=x.borderTop?u:2*u,C=S!==k?1:d-f[p]+1;i.setEdge(m,S,{weight:_,minlen:C,nestingEdge:!0}),i.setEdge(k,v,{weight:_,minlen:C,nestingEdge:!0})}),i.parent(p)||i.setEdge(l,m,{weight:0,minlen:d+f[p]})}function r(i){var l={};function c(u,d){var f=i.children(u);f&&f.length&&f.forEach(p=>c(p,d+1)),l[u]=d}return i.children().forEach(u=>c(u,1)),l}function s(i){return i.edges().reduce((l,c)=>l+i.edge(c).weight,0)}function a(i){var l=i.graph();i.removeNode(l.nestingRoot),delete l.nestingRoot,i.edges().forEach(c=>{var u=i.edge(c);u.nestingEdge&&i.removeEdge(c)})}return Ate}var Rte,G9e;function iWn(){if(G9e)return Rte;G9e=1;let e=Al();Rte=t;function t(r){function s(a){let i=r.children(a),l=r.node(a);if(i.length&&i.forEach(s),Object.hasOwn(l,"minRank")){l.borderLeft=[],l.borderRight=[];for(let c=l.minRank,u=l.maxRank+1;c<u;++c)n(r,"borderLeft","_bl",a,l,c),n(r,"borderRight","_br",a,l,c)}}r.children().forEach(s)}function n(r,s,a,i,l,c){let u={width:0,height:0,rank:c,borderType:s},d=l[s][c-1],f=e.addDummyNode(r,"border",u,a);l[s][c]=f,r.setParent(f,i),d&&r.setEdge(d,f,{weight:1})}return Rte}var Pte,Q9e;function oWn(){if(Q9e)return Pte;Q9e=1,Pte={adjust:e,undo:t};function e(c){let u=c.graph().rankdir.toLowerCase();(u==="lr"||u==="rl")&&n(c)}function t(c){let u=c.graph().rankdir.toLowerCase();(u==="bt"||u==="rl")&&s(c),(u==="lr"||u==="rl")&&(i(c),n(c))}function n(c){c.nodes().forEach(u=>r(c.node(u))),c.edges().forEach(u=>r(c.edge(u)))}function r(c){let u=c.width;c.width=c.height,c.height=u}function s(c){c.nodes().forEach(u=>a(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(a),Object.hasOwn(d,"y")&&a(d)})}function a(c){c.y=-c.y}function i(c){c.nodes().forEach(u=>l(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(l),Object.hasOwn(d,"x")&&l(d)})}function l(c){let u=c.x;c.x=c.y,c.y=u}return Pte}var $te,Y9e;function lWn(){if(Y9e)return $te;Y9e=1;let e=Al();$te=t;function t(n){let r={},s=n.nodes().filter(d=>!n.children(d).length),a=s.map(d=>n.node(d).rank),i=e.applyWithChunking(Math.max,a),l=e.range(i+1).map(()=>[]);function c(d){if(r[d])return;r[d]=!0;let f=n.node(d);l[f.rank].push(d),n.successors(d).forEach(c)}return s.sort((d,f)=>n.node(d).rank-n.node(f).rank).forEach(c),l}return $te}var Mte,K9e;function cWn(){if(K9e)return Mte;K9e=1;let e=Al().zipObject;Mte=t;function t(r,s){let a=0;for(let i=1;i<s.length;++i)a+=n(r,s[i-1],s[i]);return a}function n(r,s,a){let i=e(a,a.map((p,h)=>h)),l=s.flatMap(p=>r.outEdges(p).map(h=>({pos:i[h.w],weight:r.edge(h).weight})).sort((h,m)=>h.pos-m.pos)),c=1;for(;c<a.length;)c<<=1;let u=2*c-1;c-=1;let d=new Array(u).fill(0),f=0;return l.forEach(p=>{let h=p.pos+c;d[h]+=p.weight;let m=0;for(;h>0;)h%2&&(m+=d[h+1]),h=h-1>>1,d[h]+=p.weight;f+=p.weight*m}),f}return Mte}var Dte,X9e;function uWn(){if(X9e)return Dte;X9e=1,Dte=e;function e(t,n=[]){return n.map(r=>{let s=t.inEdges(r);if(s.length){let a=s.reduce((i,l)=>{let c=t.edge(l),u=t.node(l.v);return{sum:i.sum+c.weight*u.order,weight:i.weight+c.weight}},{sum:0,weight:0});return{v:r,barycenter:a.sum/a.weight,weight:a.weight}}else return{v:r}})}return Dte}var Lte,J9e;function dWn(){if(J9e)return Lte;J9e=1;let e=Al();Lte=t;function t(s,a){let i={};s.forEach((c,u)=>{let d=i[c.v]={indegree:0,in:[],out:[],vs:[c.v],i:u};c.barycenter!==void 0&&(d.barycenter=c.barycenter,d.weight=c.weight)}),a.edges().forEach(c=>{let u=i[c.v],d=i[c.w];u!==void 0&&d!==void 0&&(d.indegree++,u.out.push(i[c.w]))});let l=Object.values(i).filter(c=>!c.indegree);return n(l)}function n(s){let a=[];function i(c){return u=>{u.merged||(u.barycenter===void 0||c.barycenter===void 0||u.barycenter>=c.barycenter)&&r(c,u)}}function l(c){return u=>{u.in.push(c),--u.indegree===0&&s.push(u)}}for(;s.length;){let c=s.pop();a.push(c),c.in.reverse().forEach(i(c)),c.out.forEach(l(c))}return a.filter(c=>!c.merged).map(c=>e.pick(c,["vs","i","barycenter","weight"]))}function r(s,a){let i=0,l=0;s.weight&&(i+=s.barycenter*s.weight,l+=s.weight),a.weight&&(i+=a.barycenter*a.weight,l+=a.weight),s.vs=a.vs.concat(s.vs),s.barycenter=i/l,s.weight=l,s.i=Math.min(a.i,s.i),a.merged=!0}return Lte}var Fte,e7e;function fWn(){if(e7e)return Fte;e7e=1;let e=Al();Fte=t;function t(s,a){let i=e.partition(s,m=>Object.hasOwn(m,"barycenter")),l=i.lhs,c=i.rhs.sort((m,v)=>v.i-m.i),u=[],d=0,f=0,p=0;l.sort(r(!!a)),p=n(u,c,p),l.forEach(m=>{p+=m.vs.length,u.push(m.vs),d+=m.barycenter*m.weight,f+=m.weight,p=n(u,c,p)});let h={vs:u.flat(!0)};return f&&(h.barycenter=d/f,h.weight=f),h}function n(s,a,i){let l;for(;a.length&&(l=a[a.length-1]).i<=i;)a.pop(),s.push(l.vs),i++;return i}function r(s){return(a,i)=>a.barycenter<i.barycenter?-1:a.barycenter>i.barycenter?1:s?i.i-a.i:a.i-i.i}return Fte}var zte,t7e;function pWn(){if(t7e)return zte;t7e=1;let e=uWn(),t=dWn(),n=fWn();zte=r;function r(i,l,c,u){let d=i.children(l),f=i.node(l),p=f?f.borderLeft:void 0,h=f?f.borderRight:void 0,m={};p&&(d=d.filter(x=>x!==p&&x!==h));let v=e(i,d);v.forEach(x=>{if(i.children(x.v).length){let S=r(i,x.v,c,u);m[x.v]=S,Object.hasOwn(S,"barycenter")&&a(x,S)}});let y=t(v,c);s(y,m);let b=n(y,u);if(p&&(b.vs=[p,b.vs,h].flat(!0),i.predecessors(p).length)){let x=i.node(i.predecessors(p)[0]),S=i.node(i.predecessors(h)[0]);Object.hasOwn(b,"barycenter")||(b.barycenter=0,b.weight=0),b.barycenter=(b.barycenter*b.weight+x.order+S.order)/(b.weight+2),b.weight+=2}return b}function s(i,l){i.forEach(c=>{c.vs=c.vs.flatMap(u=>l[u]?l[u].vs:u)})}function a(i,l){i.barycenter!==void 0?(i.barycenter=(i.barycenter*i.weight+l.barycenter*l.weight)/(i.weight+l.weight),i.weight+=l.weight):(i.barycenter=l.barycenter,i.weight=l.weight)}return zte}var Bte,n7e;function hWn(){if(n7e)return Bte;n7e=1;let e=Hg().Graph,t=Al();Bte=n;function n(s,a,i,l){l||(l=s.nodes());let c=r(s),u=new e({compound:!0}).setGraph({root:c}).setDefaultNodeLabel(d=>s.node(d));return l.forEach(d=>{let f=s.node(d),p=s.parent(d);(f.rank===a||f.minRank<=a&&a<=f.maxRank)&&(u.setNode(d),u.setParent(d,p||c),s[i](d).forEach(h=>{let m=h.v===d?h.w:h.v,v=u.edge(m,d),y=v!==void 0?v.weight:0;u.setEdge(m,d,{weight:s.edge(h).weight+y})}),Object.hasOwn(f,"minRank")&&u.setNode(d,{borderLeft:f.borderLeft[a],borderRight:f.borderRight[a]}))}),u}function r(s){for(var a;s.hasNode(a=t.uniqueId("_root")););return a}return Bte}var Ute,r7e;function mWn(){if(r7e)return Ute;r7e=1,Ute=e;function e(t,n,r){let s={},a;r.forEach(i=>{let l=t.parent(i),c,u;for(;l;){if(c=t.parent(l),c?(u=s[c],s[c]=l):(u=a,a=l),u&&u!==l){n.setEdge(u,l);return}l=c}})}return Ute}var qte,s7e;function gWn(){if(s7e)return qte;s7e=1;let e=lWn(),t=cWn(),n=pWn(),r=hWn(),s=mWn(),a=Hg().Graph,i=Al();qte=l;function l(f,p){if(p&&typeof p.customOrder=="function"){p.customOrder(f,l);return}let h=i.maxRank(f),m=c(f,i.range(1,h+1),"inEdges"),v=c(f,i.range(h-1,-1,-1),"outEdges"),y=e(f);if(d(f,y),p&&p.disableOptimalOrderHeuristic)return;let b=Number.POSITIVE_INFINITY,x;for(let S=0,k=0;k<4;++S,++k){u(S%2?m:v,S%4>=2),y=i.buildLayerMatrix(f);let _=t(f,y);_<b&&(k=0,x=Object.assign({},y),b=_)}d(f,x)}function c(f,p,h){const m=new Map,v=(y,b)=>{m.has(y)||m.set(y,[]),m.get(y).push(b)};for(const y of f.nodes()){const b=f.node(y);if(typeof b.rank=="number"&&v(b.rank,y),typeof b.minRank=="number"&&typeof b.maxRank=="number")for(let x=b.minRank;x<=b.maxRank;x++)x!==b.rank&&v(x,y)}return p.map(function(y){return r(f,y,h,m.get(y)||[])})}function u(f,p){let h=new a;f.forEach(function(m){let v=m.graph().root,y=n(m,v,h,p);y.vs.forEach((b,x)=>m.node(b).order=x),s(m,h,y.vs)})}function d(f,p){Object.values(p).forEach(h=>h.forEach((m,v)=>f.node(m).order=v))}return qte}var Vte,a7e;function vWn(){if(a7e)return Vte;a7e=1;let e=Hg().Graph,t=Al();Vte={positionX:h,findType1Conflicts:n,findType2Conflicts:r,addConflict:a,hasConflict:i,verticalAlignment:l,horizontalCompaction:c,alignCoordinates:f,findSmallestWidthAlignment:d,balance:p};function n(y,b){let x={};function S(k,_){let C=0,T=0,E=k.length,N=_[_.length-1];return _.forEach((I,A)=>{let R=s(y,I),L=R?y.node(R).order:E;(R||I===N)&&(_.slice(T,A+1).forEach(D=>{y.predecessors(D).forEach(F=>{let H=y.node(F),B=H.order;(B<C||L<B)&&!(H.dummy&&y.node(D).dummy)&&a(x,F,D)})}),T=A+1,C=L)}),_}return b.length&&b.reduce(S),x}function r(y,b){let x={};function S(_,C,T,E,N){let I;t.range(C,T).forEach(A=>{I=_[A],y.node(I).dummy&&y.predecessors(I).forEach(R=>{let L=y.node(R);L.dummy&&(L.order<E||L.order>N)&&a(x,R,I)})})}function k(_,C){let T=-1,E,N=0;return C.forEach((I,A)=>{if(y.node(I).dummy==="border"){let R=y.predecessors(I);R.length&&(E=y.node(R[0]).order,S(C,N,A,T,E),N=A,T=E)}S(C,N,C.length,E,_.length)}),C}return b.length&&b.reduce(k),x}function s(y,b){if(y.node(b).dummy)return y.predecessors(b).find(x=>y.node(x).dummy)}function a(y,b,x){if(b>x){let k=b;b=x,x=k}let S=y[b];S||(y[b]=S={}),S[x]=!0}function i(y,b,x){if(b>x){let S=b;b=x,x=S}return!!y[b]&&Object.hasOwn(y[b],x)}function l(y,b,x,S){let k={},_={},C={};return b.forEach(T=>{T.forEach((E,N)=>{k[E]=E,_[E]=E,C[E]=N})}),b.forEach(T=>{let E=-1;T.forEach(N=>{let I=S(N);if(I.length){I=I.sort((R,L)=>C[R]-C[L]);let A=(I.length-1)/2;for(let R=Math.floor(A),L=Math.ceil(A);R<=L;++R){let D=I[R];_[N]===N&&E<C[D]&&!i(x,N,D)&&(_[D]=N,_[N]=k[N]=k[D],E=C[D])}}})}),{root:k,align:_}}function c(y,b,x,S,k){let _={},C=u(y,b,x,k),T=k?"borderLeft":"borderRight";function E(A,R){let L=C.nodes(),D=L.pop(),F={};for(;D;)F[D]?A(D):(F[D]=!0,L.push(D),L=L.concat(R(D))),D=L.pop()}function N(A){_[A]=C.inEdges(A).reduce((R,L)=>Math.max(R,_[L.v]+C.edge(L)),0)}function I(A){let R=C.outEdges(A).reduce((D,F)=>Math.min(D,_[F.w]-C.edge(F)),Number.POSITIVE_INFINITY),L=y.node(A);R!==Number.POSITIVE_INFINITY&&L.borderType!==T&&(_[A]=Math.max(_[A],R))}return E(N,C.predecessors.bind(C)),E(I,C.successors.bind(C)),Object.keys(S).forEach(A=>_[A]=_[x[A]]),_}function u(y,b,x,S){let k=new e,_=y.graph(),C=m(_.nodesep,_.edgesep,S);return b.forEach(T=>{let E;T.forEach(N=>{let I=x[N];if(k.setNode(I),E){var A=x[E],R=k.edge(A,I);k.setEdge(A,I,Math.max(C(y,N,E),R||0))}E=N})}),k}function d(y,b){return Object.values(b).reduce((x,S)=>{let k=Number.NEGATIVE_INFINITY,_=Number.POSITIVE_INFINITY;Object.entries(S).forEach(([T,E])=>{let N=v(y,T)/2;k=Math.max(E+N,k),_=Math.min(E-N,_)});const C=k-_;return C<x[0]&&(x=[C,S]),x},[Number.POSITIVE_INFINITY,null])[1]}function f(y,b){let x=Object.values(b),S=t.applyWithChunking(Math.min,x),k=t.applyWithChunking(Math.max,x);["u","d"].forEach(_=>{["l","r"].forEach(C=>{let T=_+C,E=y[T];if(E===b)return;let N=Object.values(E),I=S-t.applyWithChunking(Math.min,N);C!=="l"&&(I=k-t.applyWithChunking(Math.max,N)),I&&(y[T]=t.mapValues(E,A=>A+I))})})}function p(y,b){return t.mapValues(y.ul,(x,S)=>{if(b)return y[b.toLowerCase()][S];{let k=Object.values(y).map(_=>_[S]).sort((_,C)=>_-C);return(k[1]+k[2])/2}})}function h(y){let b=t.buildLayerMatrix(y),x=Object.assign(n(y,b),r(y,b)),S={},k;["u","d"].forEach(C=>{k=C==="u"?b:Object.values(b).reverse(),["l","r"].forEach(T=>{T==="r"&&(k=k.map(A=>Object.values(A).reverse()));let E=(C==="u"?y.predecessors:y.successors).bind(y),N=l(y,k,x,E),I=c(y,k,N.root,N.align,T==="r");T==="r"&&(I=t.mapValues(I,A=>-A)),S[C+T]=I})});let _=d(y,S);return f(S,_),p(S,y.graph().align)}function m(y,b,x){return(S,k,_)=>{let C=S.node(k),T=S.node(_),E=0,N;if(E+=C.width/2,Object.hasOwn(C,"labelpos"))switch(C.labelpos.toLowerCase()){case"l":N=-C.width/2;break;case"r":N=C.width/2;break}if(N&&(E+=x?N:-N),N=0,E+=(C.dummy?b:y)/2,E+=(T.dummy?b:y)/2,E+=T.width/2,Object.hasOwn(T,"labelpos"))switch(T.labelpos.toLowerCase()){case"l":N=T.width/2;break;case"r":N=-T.width/2;break}return N&&(E+=x?N:-N),N=0,E}}function v(y,b){return y.node(b).width}return Vte}var Hte,i7e;function yWn(){if(i7e)return Hte;i7e=1;let e=Al(),t=vWn().positionX;Hte=n;function n(s){s=e.asNonCompoundGraph(s),r(s),Object.entries(t(s)).forEach(([a,i])=>s.node(a).x=i)}function r(s){let a=e.buildLayerMatrix(s),i=s.graph().ranksep,l=0;a.forEach(c=>{const u=c.reduce((d,f)=>{const p=s.node(f).height;return d>p?d:p},0);c.forEach(d=>s.node(d).y=l+u/2),l+=u+i})}return Hte}var Wte,o7e;function bWn(){if(o7e)return Wte;o7e=1;let e=eWn(),t=tWn(),n=rWn(),r=Al().normalizeRanks,s=sWn(),a=Al().removeEmptyRanks,i=aWn(),l=iWn(),c=oWn(),u=gWn(),d=yWn(),f=Al(),p=Hg().Graph;Wte=h;function h($,q){let Z=q&&q.debugTiming?f.time:f.notime;Z("layout",()=>{let Y=Z(" buildLayoutGraph",()=>E($));Z(" runLayout",()=>m(Y,Z,q)),Z(" updateInputGraph",()=>v($,Y))})}function m($,q,Z){q(" makeSpaceForEdgeLabels",()=>N($)),q(" removeSelfEdges",()=>z($)),q(" acyclic",()=>e.run($)),q(" nestingGraph.run",()=>i.run($)),q(" rank",()=>n(f.asNonCompoundGraph($))),q(" injectEdgeLabelProxies",()=>I($)),q(" removeEmptyRanks",()=>a($)),q(" nestingGraph.cleanup",()=>i.cleanup($)),q(" normalizeRanks",()=>r($)),q(" assignRankMinMax",()=>A($)),q(" removeEdgeLabelProxies",()=>R($)),q(" normalize.run",()=>t.run($)),q(" parentDummyChains",()=>s($)),q(" addBorderSegments",()=>l($)),q(" order",()=>u($,Z)),q(" insertSelfEdges",()=>V($)),q(" adjustCoordinateSystem",()=>c.adjust($)),q(" position",()=>d($)),q(" positionSelfEdges",()=>M($)),q(" removeBorderNodes",()=>B($)),q(" normalize.undo",()=>t.undo($)),q(" fixupEdgeLabelCoords",()=>F($)),q(" undoCoordinateSystem",()=>c.undo($)),q(" translateGraph",()=>L($)),q(" assignNodeIntersects",()=>D($)),q(" reversePoints",()=>H($)),q(" acyclic.undo",()=>e.undo($))}function v($,q){$.nodes().forEach(Z=>{let Y=$.node(Z),ne=q.node(Z);Y&&(Y.x=ne.x,Y.y=ne.y,Y.rank=ne.rank,q.children(Z).length&&(Y.width=ne.width,Y.height=ne.height))}),$.edges().forEach(Z=>{let Y=$.edge(Z),ne=q.edge(Z);Y.points=ne.points,Object.hasOwn(ne,"x")&&(Y.x=ne.x,Y.y=ne.y)}),$.graph().width=q.graph().width,$.graph().height=q.graph().height}let y=["nodesep","edgesep","ranksep","marginx","marginy"],b={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},x=["acyclicer","ranker","rankdir","align"],S=["width","height","rank"],k={width:0,height:0},_=["minlen","weight","width","height","labeloffset"],C={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},T=["labelpos"];function E($){let q=new p({multigraph:!0,compound:!0}),Z=U($.graph());return q.setGraph(Object.assign({},b,G(Z,y),f.pick(Z,x))),$.nodes().forEach(Y=>{let ne=U($.node(Y));const J=G(ne,S);Object.keys(k).forEach(ee=>{J[ee]===void 0&&(J[ee]=k[ee])}),q.setNode(Y,J),q.setParent(Y,$.parent(Y))}),$.edges().forEach(Y=>{let ne=U($.edge(Y));q.setEdge(Y,Object.assign({},C,G(ne,_),f.pick(ne,T)))}),q}function N($){let q=$.graph();q.ranksep/=2,$.edges().forEach(Z=>{let Y=$.edge(Z);Y.minlen*=2,Y.labelpos.toLowerCase()!=="c"&&(q.rankdir==="TB"||q.rankdir==="BT"?Y.width+=Y.labeloffset:Y.height+=Y.labeloffset)})}function I($){$.edges().forEach(q=>{let Z=$.edge(q);if(Z.width&&Z.height){let Y=$.node(q.v),J={rank:($.node(q.w).rank-Y.rank)/2+Y.rank,e:q};f.addDummyNode($,"edge-proxy",J,"_ep")}})}function A($){let q=0;$.nodes().forEach(Z=>{let Y=$.node(Z);Y.borderTop&&(Y.minRank=$.node(Y.borderTop).rank,Y.maxRank=$.node(Y.borderBottom).rank,q=Math.max(q,Y.maxRank))}),$.graph().maxRank=q}function R($){$.nodes().forEach(q=>{let Z=$.node(q);Z.dummy==="edge-proxy"&&($.edge(Z.e).labelRank=Z.rank,$.removeNode(q))})}function L($){let q=Number.POSITIVE_INFINITY,Z=0,Y=Number.POSITIVE_INFINITY,ne=0,J=$.graph(),ee=J.marginx||0,re=J.marginy||0;function le(X){let te=X.x,se=X.y,pe=X.width,ce=X.height;q=Math.min(q,te-pe/2),Z=Math.max(Z,te+pe/2),Y=Math.min(Y,se-ce/2),ne=Math.max(ne,se+ce/2)}$.nodes().forEach(X=>le($.node(X))),$.edges().forEach(X=>{let te=$.edge(X);Object.hasOwn(te,"x")&&le(te)}),q-=ee,Y-=re,$.nodes().forEach(X=>{let te=$.node(X);te.x-=q,te.y-=Y}),$.edges().forEach(X=>{let te=$.edge(X);te.points.forEach(se=>{se.x-=q,se.y-=Y}),Object.hasOwn(te,"x")&&(te.x-=q),Object.hasOwn(te,"y")&&(te.y-=Y)}),J.width=Z-q+ee,J.height=ne-Y+re}function D($){$.edges().forEach(q=>{let Z=$.edge(q),Y=$.node(q.v),ne=$.node(q.w),J,ee;Z.points?(J=Z.points[0],ee=Z.points[Z.points.length-1]):(Z.points=[],J=ne,ee=Y),Z.points.unshift(f.intersectRect(Y,J)),Z.points.push(f.intersectRect(ne,ee))})}function F($){$.edges().forEach(q=>{let Z=$.edge(q);if(Object.hasOwn(Z,"x"))switch((Z.labelpos==="l"||Z.labelpos==="r")&&(Z.width-=Z.labeloffset),Z.labelpos){case"l":Z.x-=Z.width/2+Z.labeloffset;break;case"r":Z.x+=Z.width/2+Z.labeloffset;break}})}function H($){$.edges().forEach(q=>{let Z=$.edge(q);Z.reversed&&Z.points.reverse()})}function B($){$.nodes().forEach(q=>{if($.children(q).length){let Z=$.node(q),Y=$.node(Z.borderTop),ne=$.node(Z.borderBottom),J=$.node(Z.borderLeft[Z.borderLeft.length-1]),ee=$.node(Z.borderRight[Z.borderRight.length-1]);Z.width=Math.abs(ee.x-J.x),Z.height=Math.abs(ne.y-Y.y),Z.x=J.x+Z.width/2,Z.y=Y.y+Z.height/2}}),$.nodes().forEach(q=>{$.node(q).dummy==="border"&&$.removeNode(q)})}function z($){$.edges().forEach(q=>{if(q.v===q.w){var Z=$.node(q.v);Z.selfEdges||(Z.selfEdges=[]),Z.selfEdges.push({e:q,label:$.edge(q)}),$.removeEdge(q)}})}function V($){var q=f.buildLayerMatrix($);q.forEach(Z=>{var Y=0;Z.forEach((ne,J)=>{var ee=$.node(ne);ee.order=J+Y,(ee.selfEdges||[]).forEach(re=>{f.addDummyNode($,"selfedge",{width:re.label.width,height:re.label.height,rank:ee.rank,order:J+ ++Y,e:re.e,label:re.label},"_se")}),delete ee.selfEdges})})}function M($){$.nodes().forEach(q=>{var Z=$.node(q);if(Z.dummy==="selfedge"){var Y=$.node(Z.e.v),ne=Y.x+Y.width/2,J=Y.y,ee=Z.x-ne,re=Y.height/2;$.setEdge(Z.e,Z.label),$.removeNode(q),Z.label.points=[{x:ne+2*ee/3,y:J-re},{x:ne+5*ee/6,y:J-re},{x:ne+ee,y:J},{x:ne+5*ee/6,y:J+re},{x:ne+2*ee/3,y:J+re}],Z.label.x=Z.x,Z.label.y=Z.y}})}function G($,q){return f.mapValues(f.pick($,q),Number)}function U($){var q={};return $&&Object.entries($).forEach(([Z,Y])=>{typeof Z=="string"&&(Z=Z.toLowerCase()),q[Z]=Y}),q}return Wte}var Zte,l7e;function xWn(){if(l7e)return Zte;l7e=1;let e=Al(),t=Hg().Graph;Zte={debugOrdering:n};function n(r){let s=e.buildLayerMatrix(r),a=new t({compound:!0,multigraph:!0}).setGraph({});return r.nodes().forEach(i=>{a.setNode(i,{label:i}),a.setParent(i,"layer"+r.node(i).rank)}),r.edges().forEach(i=>a.setEdge(i.v,i.w,{},i.name)),s.forEach((i,l)=>{let c="layer"+l;a.setNode(c,{rank:"same"}),i.reduce((u,d)=>(a.setEdge(u,d,{style:"invis"}),d))}),a}return Zte}var Gte,c7e;function wWn(){return c7e||(c7e=1,Gte="1.1.8"),Gte}var Qte,u7e;function SWn(){return u7e||(u7e=1,Qte={graphlib:Hg(),layout:bWn(),debug:xWn(),util:{time:Al().time,notime:Al().notime},version:wWn()}),Qte}var kWn=SWn();const d7e=Fl(kWn);function ql(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,r;n<e.length;n++)(r=ql(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var OWn={value:()=>{}};function aW(){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 H8(n)}function H8(e){this._=e}function _Wn(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}})}H8.prototype=aW.prototype={constructor:H8,on:function(e,t){var n=this._,r=_Wn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=CWn(n[s],e.name)))return s;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++a<i;)if(s=(e=r[a]).type)n[s]=f7e(n[s],e.name,t);else if(t==null)for(s in n)n[s]=f7e(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 H8(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),r=0,s,a;r<s;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(a=this._[e],r=0,s=a.length;r<s;++r)a[r].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],s=0,a=r.length;s<a;++s)r[s].value.apply(t,n)}};function CWn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function f7e(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=OWn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var ive="http://www.w3.org/1999/xhtml";const p7e={svg:"http://www.w3.org/2000/svg",xhtml:ive,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function iW(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),p7e.hasOwnProperty(t)?{space:p7e[t],local:e}:e}function EWn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===ive&&t.documentElement.namespaceURI===ive?t.createElement(e):t.createElementNS(n,e)}}function TWn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function qkt(e){var t=iW(e);return(t.local?TWn:EWn)(t)}function jWn(){}function cOe(e){return e==null?jWn:function(){return this.querySelector(e)}}function NWn(e){typeof e!="function"&&(e=cOe(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=new Array(i),c,u,d=0;d<i;++d)(c=a[d])&&(u=e.call(c,c.__data__,d,a))&&("__data__"in c&&(u.__data__=c.__data__),l[d]=u);return new Yp(r,this._parents)}function IWn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function AWn(){return[]}function Vkt(e){return e==null?AWn:function(){return this.querySelectorAll(e)}}function RWn(e){return function(){return IWn(e.apply(this,arguments))}}function PWn(e){typeof e=="function"?e=RWn(e):e=Vkt(e);for(var t=this._groups,n=t.length,r=[],s=[],a=0;a<n;++a)for(var i=t[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&(r.push(e.call(c,c.__data__,u,i)),s.push(c));return new Yp(r,s)}function Hkt(e){return function(){return this.matches(e)}}function Wkt(e){return function(t){return t.matches(e)}}var $Wn=Array.prototype.find;function MWn(e){return function(){return $Wn.call(this.children,e)}}function DWn(){return this.firstElementChild}function LWn(e){return this.select(e==null?DWn:MWn(typeof e=="function"?e:Wkt(e)))}var FWn=Array.prototype.filter;function zWn(){return Array.from(this.children)}function BWn(e){return function(){return FWn.call(this.children,e)}}function UWn(e){return this.selectAll(e==null?zWn:BWn(typeof e=="function"?e:Wkt(e)))}function qWn(e){typeof e!="function"&&(e=Hkt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new Yp(r,this._parents)}function Zkt(e){return new Array(e.length)}function VWn(){return new Yp(this._enter||this._groups.map(Zkt),this._parents)}function GB(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}GB.prototype={constructor:GB,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 HWn(e){return function(){return e}}function WWn(e,t,n,r,s,a){for(var i=0,l,c=t.length,u=a.length;i<u;++i)(l=t[i])?(l.__data__=a[i],r[i]=l):n[i]=new GB(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function ZWn(e,t,n,r,s,a,i){var l,c,u=new Map,d=t.length,f=a.length,p=new Array(d),h;for(l=0;l<d;++l)(c=t[l])&&(p[l]=h=i.call(c,c.__data__,l,t)+"",u.has(h)?s[l]=c:u.set(h,c));for(l=0;l<f;++l)h=i.call(e,a[l],l,a)+"",(c=u.get(h))?(r[l]=c,c.__data__=a[l],u.delete(h)):n[l]=new GB(e,a[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(p[l])===c&&(s[l]=c)}function GWn(e){return e.__data__}function QWn(e,t){if(!arguments.length)return Array.from(this,GWn);var n=t?ZWn:WWn,r=this._parents,s=this._groups;typeof e!="function"&&(e=HWn(e));for(var a=s.length,i=new Array(a),l=new Array(a),c=new Array(a),u=0;u<a;++u){var d=r[u],f=s[u],p=f.length,h=YWn(e.call(d,d&&d.__data__,u,r)),m=h.length,v=l[u]=new Array(m),y=i[u]=new Array(m),b=c[u]=new Array(p);n(d,f,v,y,b,h,t);for(var x=0,S=0,k,_;x<m;++x)if(k=v[x]){for(x>=S&&(S=x+1);!(_=y[S])&&++S<m;);k._next=_||null}}return i=new Yp(i,r),i._enter=l,i._exit=c,i}function YWn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function KWn(){return new Yp(this._exit||this._groups.map(Zkt),this._parents)}function XWn(e,t,n){var r=this.enter(),s=this,a=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(s=t(s),s&&(s=s.selection())),n==null?a.remove():n(a),r&&s?r.merge(s).order():s}function JWn(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,s=n.length,a=r.length,i=Math.min(s,a),l=new Array(s),c=0;c<i;++c)for(var u=n[c],d=r[c],f=u.length,p=l[c]=new Array(f),h,m=0;m<f;++m)(h=u[m]||d[m])&&(p[m]=h);for(;c<s;++c)l[c]=n[c];return new Yp(l,this._parents)}function eZn(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],s=r.length-1,a=r[s],i;--s>=0;)(i=r[s])&&(a&&i.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(i,a),a=i);return this}function tZn(e){e||(e=nZn);function t(f,p){return f&&p?e(f.__data__,p.__data__):!f-!p}for(var n=this._groups,r=n.length,s=new Array(r),a=0;a<r;++a){for(var i=n[a],l=i.length,c=s[a]=new Array(l),u,d=0;d<l;++d)(u=i[d])&&(c[d]=u);c.sort(t)}return new Yp(s,this._parents).order()}function nZn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function rZn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function sZn(){return Array.from(this)}function aZn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length;s<a;++s){var i=r[s];if(i)return i}return null}function iZn(){let e=0;for(const t of this)++e;return e}function oZn(){return!this.node()}function lZn(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var s=t[n],a=0,i=s.length,l;a<i;++a)(l=s[a])&&e.call(l,l.__data__,a,s);return this}function cZn(e){return function(){this.removeAttribute(e)}}function uZn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function dZn(e,t){return function(){this.setAttribute(e,t)}}function fZn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function pZn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function hZn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function mZn(e,t){var n=iW(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?uZn:cZn:typeof t=="function"?n.local?hZn:pZn:n.local?fZn:dZn)(n,t))}function Gkt(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function gZn(e){return function(){this.style.removeProperty(e)}}function vZn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function yZn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function bZn(e,t,n){return arguments.length>1?this.each((t==null?gZn:typeof t=="function"?yZn:vZn)(e,t,n??"")):tN(this.node(),e)}function tN(e,t){return e.style.getPropertyValue(t)||Gkt(e).getComputedStyle(e,null).getPropertyValue(t)}function xZn(e){return function(){delete this[e]}}function wZn(e,t){return function(){this[e]=t}}function SZn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function kZn(e,t){return arguments.length>1?this.each((t==null?xZn:typeof t=="function"?SZn:wZn)(e,t)):this.node()[e]}function Qkt(e){return e.trim().split(/^|\s+/)}function uOe(e){return e.classList||new Ykt(e)}function Ykt(e){this._node=e,this._names=Qkt(e.getAttribute("class")||"")}Ykt.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 Kkt(e,t){for(var n=uOe(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function Xkt(e,t){for(var n=uOe(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function OZn(e){return function(){Kkt(this,e)}}function _Zn(e){return function(){Xkt(this,e)}}function CZn(e,t){return function(){(t.apply(this,arguments)?Kkt:Xkt)(this,e)}}function EZn(e,t){var n=Qkt(e+"");if(arguments.length<2){for(var r=uOe(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?CZn:t?OZn:_Zn)(n,t))}function TZn(){this.textContent=""}function jZn(e){return function(){this.textContent=e}}function NZn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function IZn(e){return arguments.length?this.each(e==null?TZn:(typeof e=="function"?NZn:jZn)(e)):this.node().textContent}function AZn(){this.innerHTML=""}function RZn(e){return function(){this.innerHTML=e}}function PZn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function $Zn(e){return arguments.length?this.each(e==null?AZn:(typeof e=="function"?PZn:RZn)(e)):this.node().innerHTML}function MZn(){this.nextSibling&&this.parentNode.appendChild(this)}function DZn(){return this.each(MZn)}function LZn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function FZn(){return this.each(LZn)}function zZn(e){var t=typeof e=="function"?e:qkt(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function BZn(){return null}function UZn(e,t){var n=typeof e=="function"?e:qkt(e),r=t==null?BZn:typeof t=="function"?t:cOe(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function qZn(){var e=this.parentNode;e&&e.removeChild(this)}function VZn(){return this.each(qZn)}function HZn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function WZn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function ZZn(e){return this.select(e?WZn:HZn)}function GZn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function QZn(e){return function(t){e.call(this,t,this.__data__)}}function YZn(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 KZn(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,s=t.length,a;n<s;++n)a=t[n],(!e.type||a.type===e.type)&&a.name===e.name?this.removeEventListener(a.type,a.listener,a.options):t[++r]=a;++r?t.length=r:delete this.__on}}}function XZn(e,t,n){return function(){var r=this.__on,s,a=QZn(t);if(r){for(var i=0,l=r.length;i<l;++i)if((s=r[i]).type===e.type&&s.name===e.name){this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=a,s.options=n),s.value=t;return}}this.addEventListener(e.type,a,n),s={type:e.type,name:e.name,value:t,listener:a,options:n},r?r.push(s):this.__on=[s]}}function JZn(e,t,n){var r=YZn(e+""),s,a=r.length,i;if(arguments.length<2){var l=this.node().__on;if(l){for(var c=0,u=l.length,d;c<u;++c)for(s=0,d=l[c];s<a;++s)if((i=r[s]).type===d.type&&i.name===d.name)return d.value}return}for(l=t?XZn:KZn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function Jkt(e,t,n){var r=Gkt(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 eGn(e,t){return function(){return Jkt(this,e,t)}}function tGn(e,t){return function(){return Jkt(this,e,t.apply(this,arguments))}}function nGn(e,t){return this.each((typeof t=="function"?tGn:eGn)(e,t))}function*rGn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length,i;s<a;++s)(i=r[s])&&(yield i)}var eOt=[null];function Yp(e,t){this._groups=e,this._parents=t}function Y3(){return new Yp([[document.documentElement]],eOt)}function sGn(){return this}Yp.prototype=Y3.prototype={constructor:Yp,select:NWn,selectAll:PWn,selectChild:LWn,selectChildren:UWn,filter:qWn,data:QWn,enter:VWn,exit:KWn,join:XWn,merge:JWn,selection:sGn,order:eZn,sort:tZn,call:rZn,nodes:sZn,node:aZn,size:iZn,empty:oZn,each:lZn,attr:mZn,style:bZn,property:kZn,classed:EZn,text:IZn,html:$Zn,raise:DZn,lower:FZn,append:zZn,insert:UZn,remove:VZn,clone:ZZn,datum:GZn,on:JZn,dispatch:nGn,[Symbol.iterator]:rGn};function Cp(e){return typeof e=="string"?new Yp([[document.querySelector(e)]],[document.documentElement]):new Yp([[e]],eOt)}function aGn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function fg(e,t){if(e=aGn(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 iGn={passive:!1},IM={capture:!0,passive:!1};function Yte(e){e.stopImmediatePropagation()}function aj(e){e.preventDefault(),e.stopImmediatePropagation()}function tOt(e){var t=e.document.documentElement,n=Cp(e).on("dragstart.drag",aj,IM);"onselectstart"in t?n.on("selectstart.drag",aj,IM):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function nOt(e,t){var n=e.document.documentElement,r=Cp(e).on("dragstart.drag",null);t&&(r.on("click.drag",aj,IM),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 mF=e=>()=>e;function ove(e,{sourceEvent:t,subject:n,target:r,identifier:s,active:a,x:i,y:l,dx:c,dy:u,dispatch:d}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:s,enumerable:!0,configurable:!0},active:{value:a,enumerable:!0,configurable:!0},x:{value:i,enumerable:!0,configurable:!0},y:{value:l,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:u,enumerable:!0,configurable:!0},_:{value:d}})}ove.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function oGn(e){return!e.ctrlKey&&!e.button}function lGn(){return this.parentNode}function cGn(e,t){return t??{x:e.x,y:e.y}}function uGn(){return navigator.maxTouchPoints||"ontouchstart"in this}function rOt(){var e=oGn,t=lGn,n=cGn,r=uGn,s={},a=aW("start","drag","end"),i=0,l,c,u,d,f=0;function p(k){k.on("mousedown.drag",h).filter(r).on("touchstart.drag",y).on("touchmove.drag",b,iGn).on("touchend.drag touchcancel.drag",x).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function h(k,_){if(!(d||!e.call(this,k,_))){var C=S(this,t.call(this,k,_),k,_,"mouse");C&&(Cp(k.view).on("mousemove.drag",m,IM).on("mouseup.drag",v,IM),tOt(k.view),Yte(k),u=!1,l=k.clientX,c=k.clientY,C("start",k))}}function m(k){if(aj(k),!u){var _=k.clientX-l,C=k.clientY-c;u=_*_+C*C>f}s.mouse("drag",k)}function v(k){Cp(k.view).on("mousemove.drag mouseup.drag",null),nOt(k.view,u),aj(k),s.mouse("end",k)}function y(k,_){if(e.call(this,k,_)){var C=k.changedTouches,T=t.call(this,k,_),E=C.length,N,I;for(N=0;N<E;++N)(I=S(this,T,k,_,C[N].identifier,C[N]))&&(Yte(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])&&(aj(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])&&(Yte(k),E("end",k,_[T]))}function S(k,_,C,T,E,N){var I=a.copy(),A=fg(N||C,_),R,L,D;if((D=n.call(k,new ove("beforestart",{sourceEvent:C,target:p,identifier:E,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),T))!=null)return R=D.x-A[0]||0,L=D.y-A[1]||0,function F(H,B,z){var V=A,M;switch(H){case"start":s[E]=F,M=i++;break;case"end":delete s[E],--i;case"drag":A=fg(z||B,_),M=i;break}I.call(H,k,new ove(H,{sourceEvent:B,subject:D,target:p,identifier:E,active:M,x:A[0]+R,y:A[1]+L,dx:A[0]-V[0],dy:A[1]-V[1],dispatch:I}),T)}}return p.filter=function(k){return arguments.length?(e=typeof k=="function"?k:mF(!!k),p):e},p.container=function(k){return arguments.length?(t=typeof k=="function"?k:mF(k),p):t},p.subject=function(k){return arguments.length?(n=typeof k=="function"?k:mF(k),p):n},p.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:mF(!!k),p):r},p.on=function(){var k=a.on.apply(a,arguments);return k===a?p:k},p.clickDistance=function(k){return arguments.length?(f=(k=+k)*k,p):Math.sqrt(f)},p}function dOe(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function sOt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function K3(){}var AM=.7,QB=1/AM,ij="\\s*([+-]?\\d+)\\s*",RM="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",dy="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",dGn=/^#([0-9a-f]{3,8})$/,fGn=new RegExp(`^rgb\\(${ij},${ij},${ij}\\)$`),pGn=new RegExp(`^rgb\\(${dy},${dy},${dy}\\)$`),hGn=new RegExp(`^rgba\\(${ij},${ij},${ij},${RM}\\)$`),mGn=new RegExp(`^rgba\\(${dy},${dy},${dy},${RM}\\)$`),gGn=new RegExp(`^hsl\\(${RM},${dy},${dy}\\)$`),vGn=new RegExp(`^hsla\\(${RM},${dy},${dy},${RM}\\)$`),h7e={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};dOe(K3,QO,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:m7e,formatHex:m7e,formatHex8:yGn,formatHsl:bGn,formatRgb:g7e,toString:g7e});function m7e(){return this.rgb().formatHex()}function yGn(){return this.rgb().formatHex8()}function bGn(){return aOt(this).formatHsl()}function g7e(){return this.rgb().formatRgb()}function QO(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=dGn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?v7e(t):n===3?new Ef(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?gF(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?gF(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=fGn.exec(e))?new Ef(t[1],t[2],t[3],1):(t=pGn.exec(e))?new Ef(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=hGn.exec(e))?gF(t[1],t[2],t[3],t[4]):(t=mGn.exec(e))?gF(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=gGn.exec(e))?x7e(t[1],t[2]/100,t[3]/100,1):(t=vGn.exec(e))?x7e(t[1],t[2]/100,t[3]/100,t[4]):h7e.hasOwnProperty(e)?v7e(h7e[e]):e==="transparent"?new Ef(NaN,NaN,NaN,0):null}function v7e(e){return new Ef(e>>16&255,e>>8&255,e&255,1)}function gF(e,t,n,r){return r<=0&&(e=t=n=NaN),new Ef(e,t,n,r)}function xGn(e){return e instanceof K3||(e=QO(e)),e?(e=e.rgb(),new Ef(e.r,e.g,e.b,e.opacity)):new Ef}function lve(e,t,n,r){return arguments.length===1?xGn(e):new Ef(e,t,n,r??1)}function Ef(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}dOe(Ef,lve,sOt(K3,{brighter(e){return e=e==null?QB:Math.pow(QB,e),new Ef(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?AM:Math.pow(AM,e),new Ef(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Ef(nO(this.r),nO(this.g),nO(this.b),YB(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:y7e,formatHex:y7e,formatHex8:wGn,formatRgb:b7e,toString:b7e}));function y7e(){return`#${Mk(this.r)}${Mk(this.g)}${Mk(this.b)}`}function wGn(){return`#${Mk(this.r)}${Mk(this.g)}${Mk(this.b)}${Mk((isNaN(this.opacity)?1:this.opacity)*255)}`}function b7e(){const e=YB(this.opacity);return`${e===1?"rgb(":"rgba("}${nO(this.r)}, ${nO(this.g)}, ${nO(this.b)}${e===1?")":`, ${e})`}`}function YB(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function nO(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Mk(e){return e=nO(e),(e<16?"0":"")+e.toString(16)}function x7e(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new bg(e,t,n,r)}function aOt(e){if(e instanceof bg)return new bg(e.h,e.s,e.l,e.opacity);if(e instanceof K3||(e=QO(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),a=Math.max(t,n,r),i=NaN,l=a-s,c=(a+s)/2;return l?(t===a?i=(n-r)/l+(n<r)*6:n===a?i=(r-t)/l+2:i=(t-n)/l+4,l/=c<.5?a+s:2-a-s,i*=60):l=c>0&&c<1?0:i,new bg(i,l,c,e.opacity)}function SGn(e,t,n,r){return arguments.length===1?aOt(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}dOe(bg,SGn,sOt(K3,{brighter(e){return e=e==null?QB:Math.pow(QB,e),new bg(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?AM:Math.pow(AM,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 Ef(Kte(e>=240?e-240:e+120,s,r),Kte(e,s,r),Kte(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new bg(w7e(this.h),vF(this.s),vF(this.l),YB(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=YB(this.opacity);return`${e===1?"hsl(":"hsla("}${w7e(this.h)}, ${vF(this.s)*100}%, ${vF(this.l)*100}%${e===1?")":`, ${e})`}`}}));function w7e(e){return e=(e||0)%360,e<0?e+360:e}function vF(e){return Math.max(0,Math.min(1,e||0))}function Kte(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 fOe=e=>()=>e;function kGn(e,t){return function(n){return e+n*t}}function OGn(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 _Gn(e){return(e=+e)==1?iOt:function(t,n){return n-t?OGn(t,n,e):fOe(isNaN(t)?n:t)}}function iOt(e,t){var n=t-e;return n?kGn(e,n):fOe(isNaN(e)?t:e)}const KB=(function e(t){var n=_Gn(t);function r(s,a){var i=n((s=lve(s)).r,(a=lve(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=iOt(s.opacity,a.opacity);return function(d){return s.r=i(d),s.g=l(d),s.b=c(d),s.opacity=u(d),s+""}}return r.gamma=e,r})(1);function CGn(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),s;return function(a){for(s=0;s<n;++s)r[s]=e[s]*(1-a)+t[s]*a;return r}}function EGn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function TGn(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,s=new Array(r),a=new Array(n),i;for(i=0;i<r;++i)s[i]=hx(e[i],t[i]);for(;i<n;++i)a[i]=t[i];return function(l){for(i=0;i<r;++i)a[i]=s[i](l);return a}}function jGn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function hg(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function NGn(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]=hx(e[s],t[s]):r[s]=t[s];return function(a){for(s in n)r[s]=n[s](a);return r}}var cve=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Xte=new RegExp(cve.source,"g");function IGn(e){return function(){return e}}function AGn(e){return function(t){return e(t)+""}}function oOt(e,t){var n=cve.lastIndex=Xte.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=cve.exec(e))&&(s=Xte.exec(t));)(a=s.index)>n&&(a=t.slice(n,a),l[i]?l[i]+=a:l[++i]=a),(r=r[0])===(s=s[0])?l[i]?l[i]+=s:l[++i]=s:(l[++i]=null,c.push({i,x:hg(r,s)})),n=Xte.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?AGn(c[0].x):IGn(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 hx(e,t){var n=typeof t,r;return t==null||n==="boolean"?fOe(t):(n==="number"?hg:n==="string"?(r=QO(t))?(t=r,KB):oOt:t instanceof QO?KB:t instanceof Date?jGn:EGn(t)?CGn:Array.isArray(t)?TGn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?NGn:hg)(e,t)}function pOe(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var S7e=180/Math.PI,uve={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function lOt(e,t,n,r,s,a){var i,l,c;return(i=Math.sqrt(e*e+t*t))&&(e/=i,t/=i),(c=e*n+t*r)&&(n-=e*c,r-=t*c),(l=Math.sqrt(n*n+r*r))&&(n/=l,r/=l,c/=l),e*r<t*n&&(e=-e,t=-t,c=-c,i=-i),{translateX:s,translateY:a,rotate:Math.atan2(t,e)*S7e,skewX:Math.atan(c)*S7e,scaleX:i,scaleY:l}}var yF;function RGn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?uve:lOt(t.a,t.b,t.c,t.d,t.e,t.f)}function PGn(e){return e==null||(yF||(yF=document.createElementNS("http://www.w3.org/2000/svg","g")),yF.setAttribute("transform",e),!(e=yF.transform.baseVal.consolidate()))?uve:(e=e.matrix,lOt(e.a,e.b,e.c,e.d,e.e,e.f))}function cOt(e,t,n,r){function s(u){return u.length?u.pop()+" ":""}function a(u,d,f,p,h,m){if(u!==f||d!==p){var v=h.push("translate(",null,t,null,n);m.push({i:v-4,x:hg(u,f)},{i:v-2,x:hg(d,p)})}else(f||p)&&h.push("translate("+f+t+p+n)}function i(u,d,f,p){u!==d?(u-d>180?d+=360:d-u>180&&(u+=360),p.push({i:f.push(s(f)+"rotate(",null,r)-2,x:hg(u,d)})):d&&f.push(s(f)+"rotate("+d+r)}function l(u,d,f,p){u!==d?p.push({i:f.push(s(f)+"skewX(",null,r)-2,x:hg(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,p,h,m){if(u!==f||d!==p){var v=h.push(s(h)+"scale(",null,",",null,")");m.push({i:v-4,x:hg(u,f)},{i:v-2,x:hg(d,p)})}else(f!==1||p!==1)&&h.push(s(h)+"scale("+f+","+p+")")}return function(u,d){var f=[],p=[];return u=e(u),d=e(d),a(u.translateX,u.translateY,d.translateX,d.translateY,f,p),i(u.rotate,d.rotate,f,p),l(u.skewX,d.skewX,f,p),c(u.scaleX,u.scaleY,d.scaleX,d.scaleY,f,p),u=d=null,function(h){for(var m=-1,v=p.length,y;++m<v;)f[(y=p[m]).i]=y.x(h);return f.join("")}}}var $Gn=cOt(RGn,"px, ","px)","deg)"),MGn=cOt(PGn,", ",")",")"),DGn=1e-12;function k7e(e){return((e=Math.exp(e))+1/e)/2}function LGn(e){return((e=Math.exp(e))-1/e)/2}function FGn(e){return((e=Math.exp(2*e))-1)/(e+1)}const W8=(function e(t,n,r){function s(a,i){var l=a[0],c=a[1],u=a[2],d=i[0],f=i[1],p=i[2],h=d-l,m=f-c,v=h*h+m*m,y,b;if(v<DGn)b=Math.log(p/u)/t,y=function(T){return[l+T*h,c+T*m,u*Math.exp(t*T*b)]};else{var x=Math.sqrt(v),S=(p*p-u*u+r*v)/(2*u*n*x),k=(p*p-u*u-r*v)/(2*p*n*x),_=Math.log(Math.sqrt(S*S+1)-S),C=Math.log(Math.sqrt(k*k+1)-k);b=(C-_)/t,y=function(T){var E=T*b,N=k7e(_),I=u/(n*x)*(N*FGn(t*E+_)-LGn(_));return[l+I*h,c+I*m,u*N/k7e(t*E+_)]}}return y.duration=b*1e3*t/Math.SQRT2,y}return s.rho=function(a){var i=Math.max(.001,+a),l=i*i,c=l*l;return e(i,l,c)},s})(Math.SQRT2,2,4);function zGn(e,t){t===void 0&&(t=e,e=hx);for(var n=0,r=t.length-1,s=t[0],a=new Array(r<0?0:r);n<r;)a[n]=e(s,s=t[++n]);return function(i){var l=Math.max(0,Math.min(r-1,Math.floor(i*=r)));return a[l](i-l)}}var nN=0,QP=0,RR=0,uOt=1e3,XB,YP,JB=0,YO=0,oW=0,PM=typeof performance=="object"&&performance.now?performance:Date,dOt=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function hOe(){return YO||(dOt(BGn),YO=PM.now()+oW)}function BGn(){YO=0}function eU(){this._call=this._time=this._next=null}eU.prototype=fOt.prototype={constructor:eU,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?hOe():+n)+(t==null?0:+t),!this._next&&YP!==this&&(YP?YP._next=this:XB=this,YP=this),this._call=e,this._time=n,dve()},stop:function(){this._call&&(this._call=null,this._time=1/0,dve())}};function fOt(e,t,n){var r=new eU;return r.restart(e,t,n),r}function UGn(){hOe(),++nN;for(var e=XB,t;e;)(t=YO-e._time)>=0&&e._call.call(void 0,t),e=e._next;--nN}function O7e(){YO=(JB=PM.now())+oW,nN=QP=0;try{UGn()}finally{nN=0,VGn(),YO=0}}function qGn(){var e=PM.now(),t=e-JB;t>uOt&&(oW-=t,JB=e)}function VGn(){for(var e,t=XB,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:XB=n);YP=e,dve(r)}function dve(e){if(!nN){QP&&(QP=clearTimeout(QP));var t=e-YO;t>24?(e<1/0&&(QP=setTimeout(O7e,e-PM.now()-oW)),RR&&(RR=clearInterval(RR))):(RR||(JB=PM.now(),RR=setInterval(qGn,uOt)),nN=1,dOt(O7e))}}function _7e(e,t,n){var r=new eU;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var HGn=aW("start","end","cancel","interrupt"),WGn=[],pOt=0,C7e=1,fve=2,Z8=3,E7e=4,pve=5,G8=6;function lW(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;ZGn(e,n,{name:t,index:r,group:s,on:HGn,tween:WGn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:pOt})}function mOe(e,t){var n=ev(e,t);if(n.state>pOt)throw new Error("too late; already scheduled");return n}function zy(e,t){var n=ev(e,t);if(n.state>Z8)throw new Error("too late; already running");return n}function ev(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function ZGn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=fOt(a,0,n.time);function a(u){n.state=C7e,n.timer.restart(i,n.delay,n.time),n.delay<=u&&i(u-n.delay)}function i(u){var d,f,p,h;if(n.state!==C7e)return c();for(d in r)if(h=r[d],h.name===n.name){if(h.state===Z8)return _7e(i);h.state===E7e?(h.state=G8,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete r[d]):+d<t&&(h.state=G8,h.timer.stop(),h.on.call("cancel",e,e.__data__,h.index,h.group),delete r[d])}if(_7e(function(){n.state===Z8&&(n.state=E7e,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=fve,n.on.call("start",e,e.__data__,n.index,n.group),n.state===fve){for(n.state=Z8,s=new Array(p=n.tween.length),d=0,f=-1;d<p;++d)(h=n.tween[d].value.call(e,e.__data__,n.index,n.group))&&(s[++f]=h);s.length=f+1}}function l(u){for(var d=u<n.duration?n.ease.call(null,u/n.duration):(n.timer.restart(c),n.state=pve,1),f=-1,p=s.length;++f<p;)s[f].call(e,d);n.state===pve&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=G8,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function Q8(e,t){var n=e.__transition,r,s,a=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((r=n[i]).name!==t){a=!1;continue}s=r.state>fve&&r.state<pve,r.state=G8,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function GGn(e){return this.each(function(){Q8(this,e)})}function QGn(e,t){var n,r;return function(){var s=zy(this,e),a=s.tween;if(a!==n){r=n=a;for(var i=0,l=r.length;i<l;++i)if(r[i].name===t){r=r.slice(),r.splice(i,1);break}}s.tween=r}}function YGn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=zy(this,e),i=a.tween;if(i!==r){s=(r=i).slice();for(var l={name:t,value:n},c=0,u=s.length;c<u;++c)if(s[c].name===t){s[c]=l;break}c===u&&s.push(l)}a.tween=s}}function KGn(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=ev(this.node(),n).tween,s=0,a=r.length,i;s<a;++s)if((i=r[s]).name===e)return i.value;return null}return this.each((t==null?QGn:YGn)(n,e,t))}function gOe(e,t,n){var r=e._id;return e.each(function(){var s=zy(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return ev(s,r).value[t]}}function hOt(e,t){var n;return(typeof t=="number"?hg:t instanceof QO?KB:(n=QO(t))?(t=n,KB):oOt)(e,t)}function XGn(e){return function(){this.removeAttribute(e)}}function JGn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function eQn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttribute(e);return i===s?null:i===r?a:a=t(r=i,n)}}function tQn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttributeNS(e.space,e.local);return i===s?null:i===r?a:a=t(r=i,n)}}function nQn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttribute(e):(i=this.getAttribute(e),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function rQn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttributeNS(e.space,e.local):(i=this.getAttributeNS(e.space,e.local),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function sQn(e,t){var n=iW(e),r=n==="transform"?MGn:hOt;return this.attrTween(e,typeof t=="function"?(n.local?rQn:nQn)(n,r,gOe(this,"attr."+e,t)):t==null?(n.local?JGn:XGn)(n):(n.local?tQn:eQn)(n,r,t))}function aQn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function iQn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function oQn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&iQn(e,a)),n}return s._value=t,s}function lQn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&aQn(e,a)),n}return s._value=t,s}function cQn(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=iW(e);return this.tween(n,(r.local?oQn:lQn)(r,t))}function uQn(e,t){return function(){mOe(this,e).delay=+t.apply(this,arguments)}}function dQn(e,t){return t=+t,function(){mOe(this,e).delay=t}}function fQn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?uQn:dQn)(t,e)):ev(this.node(),t).delay}function pQn(e,t){return function(){zy(this,e).duration=+t.apply(this,arguments)}}function hQn(e,t){return t=+t,function(){zy(this,e).duration=t}}function mQn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?pQn:hQn)(t,e)):ev(this.node(),t).duration}function gQn(e,t){if(typeof t!="function")throw new Error;return function(){zy(this,e).ease=t}}function vQn(e){var t=this._id;return arguments.length?this.each(gQn(t,e)):ev(this.node(),t).ease}function yQn(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;zy(this,e).ease=n}}function bQn(e){if(typeof e!="function")throw new Error;return this.each(yQn(this._id,e))}function xQn(e){typeof e!="function"&&(e=Hkt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new Mx(r,this._parents,this._name,this._id)}function wQn(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,s=n.length,a=Math.min(r,s),i=new Array(r),l=0;l<a;++l)for(var c=t[l],u=n[l],d=c.length,f=i[l]=new Array(d),p,h=0;h<d;++h)(p=c[h]||u[h])&&(f[h]=p);for(;l<r;++l)i[l]=t[l];return new Mx(i,this._parents,this._name,this._id)}function SQn(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 kQn(e,t,n){var r,s,a=SQn(t)?mOe:zy;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function OQn(e,t){var n=this._id;return arguments.length<2?ev(this.node(),n).on.on(e):this.each(kQn(n,e,t))}function _Qn(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function CQn(){return this.on("end.remove",_Qn(this._id))}function EQn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=cOe(e));for(var r=this._groups,s=r.length,a=new Array(s),i=0;i<s;++i)for(var l=r[i],c=l.length,u=a[i]=new Array(c),d,f,p=0;p<c;++p)(d=l[p])&&(f=e.call(d,d.__data__,p,l))&&("__data__"in d&&(f.__data__=d.__data__),u[p]=f,lW(u[p],t,n,p,u,ev(d,n)));return new Mx(a,this._parents,t,n)}function TQn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Vkt(e));for(var r=this._groups,s=r.length,a=[],i=[],l=0;l<s;++l)for(var c=r[l],u=c.length,d,f=0;f<u;++f)if(d=c[f]){for(var p=e.call(d,d.__data__,f,c),h,m=ev(d,n),v=0,y=p.length;v<y;++v)(h=p[v])&&lW(h,t,n,v,p,m);a.push(p),i.push(d)}return new Mx(a,i,t,n)}var jQn=Y3.prototype.constructor;function NQn(){return new jQn(this._groups,this._parents)}function IQn(e,t){var n,r,s;return function(){var a=tN(this,e),i=(this.style.removeProperty(e),tN(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function mOt(e){return function(){this.style.removeProperty(e)}}function AQn(e,t,n){var r,s=n+"",a;return function(){var i=tN(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function RQn(e,t,n){var r,s,a;return function(){var i=tN(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),tN(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function PQn(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=zy(this,e),u=c.on,d=c.value[a]==null?l||(l=mOt(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function $Qn(e,t,n){var r=(e+="")=="transform"?$Gn:hOt;return t==null?this.styleTween(e,IQn(e,r)).on("end.style."+e,mOt(e)):typeof t=="function"?this.styleTween(e,RQn(e,r,gOe(this,"style."+e,t))).each(PQn(this._id,e)):this.styleTween(e,AQn(e,r,t),n).on("end.style."+e,null)}function MQn(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function DQn(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&MQn(e,i,n)),r}return a._value=t,a}function LQn(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,DQn(e,t,n??""))}function FQn(e){return function(){this.textContent=e}}function zQn(e){return function(){var t=e(this);this.textContent=t??""}}function BQn(e){return this.tween("text",typeof e=="function"?zQn(gOe(this,"text",e)):FQn(e==null?"":e+""))}function UQn(e){return function(t){this.textContent=e.call(this,t)}}function qQn(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&UQn(s)),t}return r._value=e,r}function VQn(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,qQn(e))}function HQn(){for(var e=this._name,t=this._id,n=gOt(),r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)if(c=i[u]){var d=ev(c,t);lW(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new Mx(r,this._parents,e,n)}function WQn(){var e,t,n=this,r=n._id,s=n.size();return new Promise(function(a,i){var l={value:i},c={value:function(){--s===0&&a()}};n.each(function(){var u=zy(this,r),d=u.on;d!==e&&(t=(e=d).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(c)),u.on=t}),s===0&&a()})}var ZQn=0;function Mx(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function gOt(){return++ZQn}var Sb=Y3.prototype;Mx.prototype={constructor:Mx,select:EQn,selectAll:TQn,selectChild:Sb.selectChild,selectChildren:Sb.selectChildren,filter:xQn,merge:wQn,selection:NQn,transition:HQn,call:Sb.call,nodes:Sb.nodes,node:Sb.node,size:Sb.size,empty:Sb.empty,each:Sb.each,on:OQn,attr:sQn,attrTween:cQn,style:$Qn,styleTween:LQn,text:BQn,textTween:VQn,remove:CQn,tween:KGn,delay:fQn,duration:mQn,ease:vQn,easeVarying:bQn,end:WQn,[Symbol.iterator]:Sb[Symbol.iterator]};function GQn(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var QQn={time:null,delay:0,duration:250,ease:GQn};function YQn(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 KQn(e){var t,n;e instanceof Mx?(t=e._id,e=e._name):(t=gOt(),(n=QQn).time=hOe(),e=e==null?null:e+"");for(var r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&lW(c,e,t,u,i,n||YQn(c,t));return new Mx(r,this._parents,e,t)}Y3.prototype.interrupt=GGn;Y3.prototype.transition=KQn;const bF=e=>()=>e;function XQn(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 nx(e,t,n){this.k=e,this.x=t,this.y=n}nx.prototype={constructor:nx,scale:function(e){return e===1?this:new nx(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new nx(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 cW=new nx(1,0,0);vOt.prototype=nx.prototype;function vOt(e){for(;!e.__zoom;)if(!(e=e.parentNode))return cW;return e.__zoom}function Jte(e){e.stopImmediatePropagation()}function PR(e){e.preventDefault(),e.stopImmediatePropagation()}function JQn(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function eYn(){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 T7e(){return this.__zoom||cW}function tYn(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function nYn(){return navigator.maxTouchPoints||"ontouchstart"in this}function rYn(e,t,n){var r=e.invertX(t[0][0])-n[0][0],s=e.invertX(t[1][0])-n[1][0],a=e.invertY(t[0][1])-n[0][1],i=e.invertY(t[1][1])-n[1][1];return e.translate(s>r?(r+s)/2:Math.min(0,r)||Math.max(0,s),i>a?(a+i)/2:Math.min(0,a)||Math.max(0,i))}function yOt(){var e=JQn,t=eYn,n=rYn,r=tYn,s=nYn,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=W8,u=aW("start","zoom","end"),d,f,p,h=500,m=150,v=0,y=10;function b(D){D.property("__zoom",T7e).on("wheel.zoom",E,{passive:!1}).on("mousedown.zoom",N).on("dblclick.zoom",I).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",R).on("touchend.zoom touchcancel.zoom",L).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(D,F,H,B){var z=D.selection?D.selection():D;z.property("__zoom",T7e),D!==z?_(D,F,H,B):z.interrupt().each(function(){C(this,arguments).event(B).start().zoom(null,typeof F=="function"?F.apply(this,arguments):F).end()})},b.scaleBy=function(D,F,H,B){b.scaleTo(D,function(){var z=this.__zoom.k,V=typeof F=="function"?F.apply(this,arguments):F;return z*V},H,B)},b.scaleTo=function(D,F,H,B){b.transform(D,function(){var z=t.apply(this,arguments),V=this.__zoom,M=H==null?k(z):typeof H=="function"?H.apply(this,arguments):H,G=V.invert(M),U=typeof F=="function"?F.apply(this,arguments):F;return n(S(x(V,U),M,G),z,i)},H,B)},b.translateBy=function(D,F,H,B){b.transform(D,function(){return n(this.__zoom.translate(typeof F=="function"?F.apply(this,arguments):F,typeof H=="function"?H.apply(this,arguments):H),t.apply(this,arguments),i)},null,B)},b.translateTo=function(D,F,H,B,z){b.transform(D,function(){var V=t.apply(this,arguments),M=this.__zoom,G=B==null?k(V):typeof B=="function"?B.apply(this,arguments):B;return n(cW.translate(G[0],G[1]).scale(M.k).translate(typeof F=="function"?-F.apply(this,arguments):-F,typeof H=="function"?-H.apply(this,arguments):-H),V,i)},B,z)};function x(D,F){return F=Math.max(a[0],Math.min(a[1],F)),F===D.k?D:new nx(F,D.x,D.y)}function S(D,F,H){var B=F[0]-H[0]*D.k,z=F[1]-H[1]*D.k;return B===D.x&&z===D.y?D:new nx(D.k,B,z)}function k(D){return[(+D[0][0]+ +D[1][0])/2,(+D[0][1]+ +D[1][1])/2]}function _(D,F,H,B){D.on("start.zoom",function(){C(this,arguments).event(B).start()}).on("interrupt.zoom end.zoom",function(){C(this,arguments).event(B).end()}).tween("zoom",function(){var z=this,V=arguments,M=C(z,V).event(B),G=t.apply(z,V),U=H==null?k(G):typeof H=="function"?H.apply(z,V):H,$=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),q=z.__zoom,Z=typeof F=="function"?F.apply(z,V):F,Y=c(q.invert(U).concat($/q.k),Z.invert(U).concat($/Z.k));return function(ne){if(ne===1)ne=Z;else{var J=Y(ne),ee=$/J[2];ne=new nx(ee,U[0]-J[0]*ee,U[1]-J[1]*ee)}M.zoom(null,ne)}})}function C(D,F,H){return!H&&D.__zooming||new T(D,F)}function T(D,F){this.that=D,this.args=F,this.active=0,this.sourceEvent=null,this.extent=t.apply(D,F),this.taps=0}T.prototype={event:function(D){return D&&(this.sourceEvent=D),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(D,F){return this.mouse&&D!=="mouse"&&(this.mouse[1]=F.invert(this.mouse[0])),this.touch0&&D!=="touch"&&(this.touch0[1]=F.invert(this.touch0[0])),this.touch1&&D!=="touch"&&(this.touch1[1]=F.invert(this.touch1[0])),this.that.__zoom=F,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(D){var F=Cp(this.that).datum();u.call(D,this.that,new XQn(D,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),F)}};function E(D,...F){if(!e.apply(this,arguments))return;var H=C(this,F).event(D),B=this.__zoom,z=Math.max(a[0],Math.min(a[1],B.k*Math.pow(2,r.apply(this,arguments)))),V=fg(D);if(H.wheel)(H.mouse[0][0]!==V[0]||H.mouse[0][1]!==V[1])&&(H.mouse[1]=B.invert(H.mouse[0]=V)),clearTimeout(H.wheel);else{if(B.k===z)return;H.mouse=[V,B.invert(V)],Q8(this),H.start()}PR(D),H.wheel=setTimeout(M,m),H.zoom("mouse",n(S(x(B,z),H.mouse[0],H.mouse[1]),H.extent,i));function M(){H.wheel=null,H.end()}}function N(D,...F){if(p||!e.apply(this,arguments))return;var H=D.currentTarget,B=C(this,F,!0).event(D),z=Cp(D.view).on("mousemove.zoom",U,!0).on("mouseup.zoom",$,!0),V=fg(D,H),M=D.clientX,G=D.clientY;tOt(D.view),Jte(D),B.mouse=[V,this.__zoom.invert(V)],Q8(this),B.start();function U(q){if(PR(q),!B.moved){var Z=q.clientX-M,Y=q.clientY-G;B.moved=Z*Z+Y*Y>v}B.event(q).zoom("mouse",n(S(B.that.__zoom,B.mouse[0]=fg(q,H),B.mouse[1]),B.extent,i))}function $(q){z.on("mousemove.zoom mouseup.zoom",null),nOt(q.view,B.moved),PR(q),B.event(q).end()}}function I(D,...F){if(e.apply(this,arguments)){var H=this.__zoom,B=fg(D.changedTouches?D.changedTouches[0]:D,this),z=H.invert(B),V=H.k*(D.shiftKey?.5:2),M=n(S(x(H,V),B,z),t.apply(this,F),i);PR(D),l>0?Cp(this).transition().duration(l).call(_,M,B,D):Cp(this).call(b.transform,M,B,D)}}function A(D,...F){if(e.apply(this,arguments)){var H=D.touches,B=H.length,z=C(this,F,D.changedTouches.length===B).event(D),V,M,G,U;for(Jte(D),M=0;M<B;++M)G=H[M],U=fg(G,this),U=[U,this.__zoom.invert(U),G.identifier],z.touch0?!z.touch1&&z.touch0[2]!==U[2]&&(z.touch1=U,z.taps=0):(z.touch0=U,V=!0,z.taps=1+!!d);d&&(d=clearTimeout(d)),V&&(z.taps<2&&(f=U[0],d=setTimeout(function(){d=null},h)),Q8(this),z.start())}}function R(D,...F){if(this.__zooming){var H=C(this,F).event(D),B=D.changedTouches,z=B.length,V,M,G,U;for(PR(D),V=0;V<z;++V)M=B[V],G=fg(M,this),H.touch0&&H.touch0[2]===M.identifier?H.touch0[0]=G:H.touch1&&H.touch1[2]===M.identifier&&(H.touch1[0]=G);if(M=H.that.__zoom,H.touch1){var $=H.touch0[0],q=H.touch0[1],Z=H.touch1[0],Y=H.touch1[1],ne=(ne=Z[0]-$[0])*ne+(ne=Z[1]-$[1])*ne,J=(J=Y[0]-q[0])*J+(J=Y[1]-q[1])*J;M=x(M,Math.sqrt(ne/J)),G=[($[0]+Z[0])/2,($[1]+Z[1])/2],U=[(q[0]+Y[0])/2,(q[1]+Y[1])/2]}else if(H.touch0)G=H.touch0[0],U=H.touch0[1];else return;H.zoom("touch",n(S(M,G,U),H.extent,i))}}function L(D,...F){if(this.__zooming){var H=C(this,F).event(D),B=D.changedTouches,z=B.length,V,M;for(Jte(D),p&&clearTimeout(p),p=setTimeout(function(){p=null},h),V=0;V<z;++V)M=B[V],H.touch0&&H.touch0[2]===M.identifier?delete H.touch0:H.touch1&&H.touch1[2]===M.identifier&&delete H.touch1;if(H.touch1&&!H.touch0&&(H.touch0=H.touch1,delete H.touch1),H.touch0)H.touch0[1]=this.__zoom.invert(H.touch0[0]);else if(H.end(),H.taps===2&&(M=fg(M,this),Math.hypot(f[0]-M[0],f[1]-M[1])<y)){var G=Cp(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(D){return arguments.length?(r=typeof D=="function"?D:bF(+D),b):r},b.filter=function(D){return arguments.length?(e=typeof D=="function"?D:bF(!!D),b):e},b.touchable=function(D){return arguments.length?(s=typeof D=="function"?D:bF(!!D),b):s},b.extent=function(D){return arguments.length?(t=typeof D=="function"?D:bF([[+D[0][0],+D[0][1]],[+D[1][0],+D[1][1]]]),b):t},b.scaleExtent=function(D){return arguments.length?(a[0]=+D[0],a[1]=+D[1],b):[a[0],a[1]]},b.translateExtent=function(D){return arguments.length?(i[0][0]=+D[0][0],i[1][0]=+D[1][0],i[0][1]=+D[0][1],i[1][1]=+D[1][1],b):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},b.constrain=function(D){return arguments.length?(n=D,b):n},b.duration=function(D){return arguments.length?(l=+D,b):l},b.interpolate=function(D){return arguments.length?(c=D,b):c},b.on=function(){var D=u.on.apply(u,arguments);return D===u?b:D},b.clickDistance=function(D){return arguments.length?(v=(D=+D)*D,b):Math.sqrt(v)},b.tapDistance=function(D){return arguments.length?(y=+D,b):y},b}const ky={error001:()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>"The React Flow parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,{id:t,sourceHandle:n,targetHandle:r})=>`Couldn't create edge for ${e} handle id: "${e==="source"?n:r}", edge id: ${t}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(e="react")=>`It seems that you haven't loaded the styles. Please import '@xyflow/${e}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>"useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.",error015:()=>"It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs."},$M=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],bOt=["Enter"," ","Escape"],xOt={"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 rN;(function(e){e.Strict="strict",e.Loose="loose"})(rN||(rN={}));var rO;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(rO||(rO={}));var MM;(function(e){e.Partial="partial",e.Full="full"})(MM||(MM={}));const wOt={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var kw;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(kw||(kw={}));var DM;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(DM||(DM={}));var tr;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(tr||(tr={}));const j7e={[tr.Left]:tr.Right,[tr.Right]:tr.Left,[tr.Top]:tr.Bottom,[tr.Bottom]:tr.Top};function SOt(e){return e===null?null:e?"valid":"invalid"}const kOt=e=>"id"in e&&"source"in e&&"target"in e,sYn=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),vOe=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),X3=(e,t=[0,0])=>{const{width:n,height:r}=a0(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},aYn=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,s)=>{const a=typeof s=="string";let i=!t.nodeLookup&&!a?s:void 0;t.nodeLookup&&(i=a?t.nodeLookup.get(s):vOe(s)?s:t.nodeLookup.get(s.id));const l=i?tU(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return uW(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return dW(n)},J3=(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=uW(n,tU(s)),r=!0)}),r?dW(n):{x:0,y:0,width:0,height:0}},yOe=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...t4(t,[n,r,s]),width:t.width/s,height:t.height/s},c=[];for(const u of e.values()){const{measured:d,selectable:f=!0,hidden:p=!1}=u;if(i&&!f||p)continue;const h=d.width??u.width??u.initialWidth??null,m=d.height??u.height??u.initialHeight??null,v=LM(l,aN(u)),y=(h??0)*(m??0),b=a&&v>0;(!u.internals.handleBounds||b||v>=y||u.dragging)&&c.push(u)}return c},iYn=(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 oYn(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 lYn({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=oYn(e,i),c=J3(l),u=bOe(c,t,n,i?.minZoom??s,i?.maxZoom??a,i?.padding??.1);return await r.setViewport(u,{duration:i?.duration,ease:i?.ease,interpolate:i?.interpolate}),Promise.resolve(!0)}function OOt({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:s,onError:a}){const i=n.get(e),l=i.parentId?n.get(i.parentId):void 0,{x:c,y:u}=l?l.internals.positionAbsolute:{x:0,y:0},d=i.origin??r;let f=i.extent||s;if(i.extent==="parent"&&!i.expandParent)if(!l)a?.("005",ky.error005());else{const h=l.measured.width,m=l.measured.height;h&&m&&(f=[[c,u],[c+h,u+m]])}else l&&iN(i.extent)&&(f=[[i.extent[0][0]+c,i.extent[0][1]+u],[i.extent[1][0]+c,i.extent[1][1]+u]]);const p=iN(f)?KO(t,f,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&a?.("015",ky.error015()),{position:{x:p.x-c+(i.measured.width??0)*d[0],y:p.y-u+(i.measured.height??0)*d[1]},positionAbsolute:p}}async function cYn({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const a=new Set(e.map(p=>p.id)),i=[];for(const p of n){if(p.deletable===!1)continue;const h=a.has(p.id),m=!h&&p.parentId&&i.find(v=>v.id===p.parentId);(h||m)&&i.push(p)}const l=new Set(t.map(p=>p.id)),c=r.filter(p=>p.deletable!==!1),d=iYn(i,c);for(const p of c)l.has(p.id)&&!d.find(m=>m.id===p.id)&&d.push(p);if(!s)return{edges:d,nodes:i};const f=await s({nodes:i,edges:d});return typeof f=="boolean"?f?{edges:d,nodes:i}:{edges:[],nodes:[]}:f}const sN=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),KO=(e={x:0,y:0},t,n)=>({x:sN(e.x,t[0][0],t[1][0]-(n?.width??0)),y:sN(e.y,t[0][1],t[1][1]-(n?.height??0))});function _Ot(e,t,n){const{width:r,height:s}=a0(n),{x:a,y:i}=n.internals.positionAbsolute;return KO(e,[[a,i],[a+r,i+s]],t)}const N7e=(e,t,n)=>e<t?sN(Math.abs(e-t),1,t)/t:e>n?-sN(Math.abs(e-n),1,t)/t:0,COt=(e,t,n=15,r=40)=>{const s=N7e(e.x,r,t.width-r)*n,a=N7e(e.y,r,t.height-r)*n;return[s,a]},uW=(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)}),hve=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),dW=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),aN=(e,t=[0,0])=>{const{x:n,y:r}=vOe(e)?e.internals.positionAbsolute:X3(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}},tU=(e,t=[0,0])=>{const{x:n,y:r}=vOe(e)?e.internals.positionAbsolute:X3(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)}},EOt=(e,t)=>dW(uW(hve(e),hve(t))),LM=(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)},I7e=e=>_g(e.width)&&_g(e.height)&&_g(e.x)&&_g(e.y),_g=e=>!isNaN(e)&&isFinite(e),uYn=(e,t)=>{},e4=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),t4=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?e4(l,i):l},nU=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function vE(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 dYn(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=vE(e,n),s=vE(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=vE(e.top??e.y??0,n),s=vE(e.bottom??e.y??0,n),a=vE(e.left??e.x??0,t),i=vE(e.right??e.x??0,t);return{top:r,right:i,bottom:s,left:a,x:a+i,y:r+s}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function fYn(e,t,n,r,s,a){const{x:i,y:l}=nU(e,[t,n,r]),{x:c,y:u}=nU({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=s-c,f=a-u;return{left:Math.floor(i),top:Math.floor(l),right:Math.floor(d),bottom:Math.floor(f)}}const bOe=(e,t,n,r,s,a)=>{const i=dYn(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=sN(u,r,s),f=e.x+e.width/2,p=e.y+e.height/2,h=t/2-f*d,m=n/2-p*d,v=fYn(e,h,m,d,t,n),y={left:Math.min(v.left-i.left,0),top:Math.min(v.top-i.top,0),right:Math.min(v.right-i.right,0),bottom:Math.min(v.bottom-i.bottom,0)};return{x:h-y.left+y.right,y:m-y.top+y.bottom,zoom:d}},FM=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function iN(e){return e!=null&&e!=="parent"}function a0(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function TOt(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function jOt(e,t={width:0,height:0},n,r,s){const a={...e},i=r.get(n);if(i){const l=i.origin||s;a.x+=i.internals.positionAbsolute.x-(t.width??0)*l[0],a.y+=i.internals.positionAbsolute.y-(t.height??0)*l[1]}return a}function A7e(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function pYn(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function hYn(e){return{...xOt,...e||{}}}function R$(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=Cg(e),l=t4({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?e4(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const xOe=e=>({width:e.offsetWidth,height:e.offsetHeight}),NOt=e=>e?.getRootNode?.()||window?.document,mYn=["INPUT","SELECT","TEXTAREA"];function IOt(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:mYn.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const AOt=e=>"clientX"in e,Cg=(e,t)=>{const n=AOt(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)}},R7e=(e,t,n,r,s)=>{const a=t.querySelectorAll(`.${e}`);return!a||!a.length?null:Array.from(a).map(i=>{const l=i.getBoundingClientRect();return{id:i.getAttribute("data-handleid"),type:e,nodeId:s,position:i.getAttribute("data-handlepos"),x:(l.left-n.left)/r,y:(l.top-n.top)/r,...xOe(i)}})};function ROt({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:s,sourceControlY:a,targetControlX:i,targetControlY:l}){const c=e*.125+s*.375+i*.375+n*.125,u=t*.125+a*.375+l*.375+r*.125,d=Math.abs(c-e),f=Math.abs(u-t);return[c,u,d,f]}function xF(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function P7e({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case tr.Left:return[t-xF(t-r,a),n];case tr.Right:return[t+xF(r-t,a),n];case tr.Top:return[t,n-xF(n-s,a)];case tr.Bottom:return[t,n+xF(s-n,a)]}}function wOe({sourceX:e,sourceY:t,sourcePosition:n=tr.Bottom,targetX:r,targetY:s,targetPosition:a=tr.Top,curvature:i=.25}){const[l,c]=P7e({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=P7e({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,p,h,m]=ROt({sourceX:e,sourceY:t,targetX:r,targetY:s,sourceControlX:l,sourceControlY:c,targetControlX:u,targetControlY:d});return[`M${e},${t} C${l},${c} ${u},${d} ${r},${s}`,f,p,h,m]}function POt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const s=Math.abs(n-e)/2,a=n<e?n+s:n-s,i=Math.abs(r-t)/2,l=r<t?r+i:r-i;return[a,l,s,i]}function gYn({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:s=!1,zIndexMode:a="basic"}){if(a==="manual")return r;const i=s&&n?r+1e3:r,l=Math.max(e.parentId||s&&e.selected?e.internals.z:0,t.parentId||s&&t.selected?t.internals.z:0);return i+l}function vYn({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=uW(tU(e),tU(t));a.x===a.x2&&(a.x2+=1),a.y===a.y2&&(a.y2+=1);const i={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:r/s[2]};return LM(i,dW(a))>0}const yYn=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,bYn=(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)),xYn=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||yYn;let s;return kOt(e)?s={...e}:s={...e,id:r(e)},bYn(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function $Ot({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=POt({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const $7e={[tr.Left]:{x:-1,y:0},[tr.Right]:{x:1,y:0},[tr.Top]:{x:0,y:-1},[tr.Bottom]:{x:0,y:1}},wYn=({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},M7e=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function SYn({source:e,sourcePosition:t=tr.Bottom,target:n,targetPosition:r=tr.Top,center:s,offset:a,stepPosition:i}){const l=$7e[t],c=$7e[r],u={x:e.x+l.x*a,y:e.y+l.y*a},d={x:n.x+c.x*a,y:n.y+c.y*a},f=wYn({source:u,sourcePosition:t,target:d}),p=f.x!==0?"x":"y",h=f[p];let m=[],v,y;const b={x:0,y:0},x={x:0,y:0},[,,S,k]=POt({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[p]*c[p]===-1){p==="x"?(v=s.x??u.x+(d.x-u.x)*i,y=s.y??(u.y+d.y)/2):(v=s.x??(u.x+d.x)/2,y=s.y??u.y+(d.y-u.y)*i);const E=[{x:v,y:u.y},{x:v,y:d.y}],N=[{x:u.x,y},{x:d.x,y}];l[p]===h?m=p==="x"?E:N:m=p==="x"?N:E}else{const E=[{x:u.x,y:d.y}],N=[{x:d.x,y:u.y}];if(p==="x"?m=l.x===h?N:E:m=l.y===h?E:N,t===r){const D=Math.abs(e[p]-n[p]);if(D<=a){const F=Math.min(a-1,a-D);l[p]===h?b[p]=(u[p]>e[p]?-1:1)*F:x[p]=(d[p]>n[p]?-1:1)*F}}if(t!==r){const D=p==="x"?"y":"x",F=l[p]===c[D],H=u[D]>d[D],B=u[D]<d[D];(l[p]===1&&(!F&&H||F&&B)||l[p]!==1&&(!F&&B||F&&H))&&(m=p==="x"?E:N)}const I={x:u.x+b.x,y:u.y+b.y},A={x:d.x+x.x,y:d.y+x.y},R=Math.max(Math.abs(I.x-m[0].x),Math.abs(A.x-m[0].x)),L=Math.max(Math.abs(I.y-m[0].y),Math.abs(A.y-m[0].y));R>=L?(v=(I.x+A.x)/2,y=m[0].y):(v=m[0].x,y=(I.y+A.y)/2)}const _={x:u.x+b.x,y:u.y+b.y},C={x:d.x+x.x,y:d.y+x.y};return[[e,..._.x!==m[0].x||_.y!==m[0].y?[_]:[],...m,...C.x!==m[m.length-1].x||C.y!==m[m.length-1].y?[C]:[],n],v,y,S,k]}function kYn(e,t,n,r){const s=Math.min(M7e(e,t)/2,M7e(t,n)/2,r),{x:a,y:i}=t;if(e.x===a&&a===n.x||e.y===i&&i===n.y)return`L${a} ${i}`;if(e.y===i){const u=e.x<n.x?-1:1,d=e.y<n.y?1:-1;return`L ${a+s*u},${i}Q ${a},${i} ${a},${i+s*d}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${a},${i+s*c}Q ${a},${i} ${a+s*l},${i}`}function mve({sourceX:e,sourceY:t,sourcePosition:n=tr.Bottom,targetX:r,targetY:s,targetPosition:a=tr.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,p,h,m,v]=SYn({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:s},targetPosition:a,center:{x:l,y:c},offset:u,stepPosition:d});let y=`M${f[0].x} ${f[0].y}`;for(let b=1;b<f.length-1;b++)y+=kYn(f[b-1],f[b],f[b+1],i);return y+=`L${f[f.length-1].x} ${f[f.length-1].y}`,[y,p,h,m,v]}function D7e(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function OYn(e){const{sourceNode:t,targetNode:n}=e;if(!D7e(t)||!D7e(n))return null;const r=t.internals.handleBounds||L7e(t.handles),s=n.internals.handleBounds||L7e(n.handles),a=F7e(r?.source??[],e.sourceHandle),i=F7e(e.connectionMode===rN.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!a||!i)return e.onError?.("008",ky.error008(a?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=a?.position||tr.Bottom,c=i?.position||tr.Top,u=XO(t,a,l),d=XO(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function L7e(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 XO(e,t,n=tr.Left,r=!1){const s=(t?.x??0)+e.internals.positionAbsolute.x,a=(t?.y??0)+e.internals.positionAbsolute.y,{width:i,height:l}=t??a0(e);if(r)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case tr.Top:return{x:s+i/2,y:a};case tr.Right:return{x:s+i,y:a+l/2};case tr.Bottom:return{x:s+i/2,y:a+l};case tr.Left:return{x:s,y:a+l/2}}}function F7e(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function gve(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function _Yn(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:s}){const a=new Set;return e.reduce((i,l)=>([l.markerStart||r,l.markerEnd||s].forEach(c=>{if(c&&typeof c=="object"){const u=gve(c,t);a.has(u)||(i.push({id:u,color:c.color||n,...c}),a.add(u))}}),i),[]).sort((i,l)=>i.id.localeCompare(l.id))}const MOt=1e3,CYn=10,SOe={nodeOrigin:[0,0],nodeExtent:$M,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},EYn={...SOe,checkEquality:!0};function kOe(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function TYn(e,t,n){const r=kOe(SOe,n);for(const s of e.values())if(s.parentId)_Oe(s,e,t,r);else{const a=X3(s,r.nodeOrigin),i=iN(s.extent)?s.extent:r.nodeExtent,l=KO(a,i,a0(s));s.internals.positionAbsolute=l}}function jYn(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;const n=[],r=[];for(const s of e.handles){const a={id:s.id,width:s.width??1,height:s.height??1,nodeId:e.id,x:s.x,y:s.y,position:s.position,type:s.type};s.type==="source"?n.push(a):s.type==="target"&&r.push(a)}return{source:n,target:r}}function OOe(e){return e==="manual"}function vve(e,t,n,r={}){const s=kOe(EYn,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!OOe(s.zIndexMode)?MOt:0;let c=e.length>0,u=!1;t.clear(),n.clear();for(const d of e){let f=i.get(d.id);if(s.checkEquality&&d===f?.internals.userNode)t.set(d.id,f);else{const p=X3(d,s.nodeOrigin),h=iN(d.extent)?d.extent:s.nodeExtent,m=KO(p,h,a0(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:jYn(d,f),z:DOt(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&&_Oe(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function NYn(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 _Oe(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=kOe(SOe,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}NYn(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*CYn),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!OOe(c)?MOt:0,{x:p,y:h,z:m}=IYn(e,d,i,l,f,c),{positionAbsolute:v}=e.internals,y=p!==v.x||h!==v.y;(y||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:p,y:h}:v,z:m}})}function DOt(e,t,n){const r=_g(e.zIndex)?e.zIndex:0;return OOe(n)?r:r+(e.selected?t:0)}function IYn(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=a0(e),u=X3(e,n),d=iN(e.extent)?KO(u,e.extent,c):u;let f=KO({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=_Ot(f,c,t));const p=DOt(e,s,a),h=t.internals.z??0;return{x:f.x,y:f.y,z:h>=p?h+1:p}}function COe(e,t,n,r=[0,0]){const s=[],a=new Map;for(const i of e){const l=t.get(i.parentId);if(!l)continue;const c=a.get(i.parentId)?.expandedRect??aN(l),u=EOt(c,i.rect);a.set(i.parentId,{expandedRect:u,parent:l})}return a.size>0&&a.forEach(({expandedRect:i,parent:l},c)=>{const u=l.internals.positionAbsolute,d=a0(l),f=l.origin??r,p=i.x<u.x?Math.round(Math.abs(u.x-i.x)):0,h=i.y<u.y?Math.round(Math.abs(u.y-i.y)):0,m=Math.max(d.width,Math.round(i.width)),v=Math.max(d.height,Math.round(i.height)),y=(m-d.width)*f[0],b=(v-d.height)*f[1];(p>0||h>0||y||b)&&(s.push({id:c,type:"position",position:{x:l.position.x-p+y,y:l.position.y-h+b}}),n.get(c)?.forEach(x=>{e.some(S=>S.id===x.id)||s.push({id:x.id,type:"position",position:{x:x.position.x+p,y:x.position.y+h}})})),(d.width<i.width||d.height<i.height||p||h)&&s.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:m+(p?f[0]*p-y:0),height:v+(h?f[1]*h-b:0)}})}),s}function AYn(e,t,n,r,s,a,i){const l=r?.querySelector(".xyflow__viewport");let c=!1;if(!l)return{changes:[],updatedInternals:c};const u=[],d=window.getComputedStyle(l),{m22:f}=new window.DOMMatrixReadOnly(d.transform),p=[];for(const h of e.values()){const m=t.get(h.id);if(!m)continue;if(m.hidden){t.set(m.id,{...m,internals:{...m.internals,handleBounds:void 0}}),c=!0;continue}const v=xOe(h.nodeElement),y=m.measured.width!==v.width||m.measured.height!==v.height;if(!!(v.width&&v.height&&(y||!m.internals.handleBounds||h.force))){const x=h.nodeElement.getBoundingClientRect(),S=iN(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=_Ot(k,v,t.get(m.parentId)):S&&(k=KO(k,S,v));const _={...m,measured:v,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:R7e("source",h.nodeElement,x,f,m.id),target:R7e("target",h.nodeElement,x,f,m.id)}}};t.set(m.id,_),m.parentId&&_Oe(_,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,y&&(u.push({id:m.id,type:"dimensions",dimensions:v}),m.expandParent&&m.parentId&&p.push({id:m.id,parentId:m.parentId,rect:aN(_,s)}))}}if(p.length>0){const h=COe(p,t,n,s);u.push(...h)}return{changes:u,updatedInternals:c}}async function RYn({delta:e,panZoom:t,transform:n,translateExtent:r,width:s,height:a}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const i=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[s,a]],r),l=!!i&&(i.x!==n[0]||i.y!==n[1]||i.k!==n[2]);return Promise.resolve(l)}function z7e(e,t,n,r,s,a){let i=s;const l=r.get(i)||new Map;r.set(i,l.set(n,t)),i=`${s}-${e}`;const c=r.get(i)||new Map;if(r.set(i,c.set(n,t)),a){i=`${s}-${e}-${a}`;const u=r.get(i)||new Map;r.set(i,u.set(n,t))}}function LOt(e,t,n){e.clear(),t.clear();for(const r of n){const{source:s,target:a,sourceHandle:i=null,targetHandle:l=null}=r,c={edgeId:r.id,source:s,target:a,sourceHandle:i,targetHandle:l},u=`${s}-${i}--${a}-${l}`,d=`${a}-${l}--${s}-${i}`;z7e("source",c,d,e,s,i),z7e("target",c,u,e,a,l),t.set(r.id,r)}}function FOt(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:FOt(n,t):!1}function B7e(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 PYn(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!FOt(i,e))&&(i.draggable||t&&typeof i.draggable>"u")){const l=e.get(a);l&&s.set(a,{id:a,position:l.position||{x:0,y:0},distance:{x:n.x-l.internals.positionAbsolute.x,y:n.y-l.internals.positionAbsolute.y},extent:l.extent,parentId:l.parentId,origin:l.origin,expandParent:l.expandParent,internals:{positionAbsolute:l.internals.positionAbsolute||{x:0,y:0}},measured:{width:l.measured.width??0,height:l.measured.height??0}})}return s}function ene({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){const s=[];for(const[i,l]of t){const c=n.get(i)?.internals.userNode;c&&s.push({...c,position:l.position,dragging:r})}if(!e)return[s[0],s];const a=n.get(e)?.internals.userNode;return[a?{...a,position:t.get(e)?.position||a.position,dragging:r}:s[0],s]}function $Yn({dragItems:e,snapGrid:t,x:n,y:r}){const s=e.values().next().value;if(!s)return null;const a={x:n-s.distance.x,y:r-s.distance.y},i=e4(a,t);return{x:i.x-a.x,y:i.y-a.y}}function MYn({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:s}){let a={x:null,y:null},i=0,l=new Map,c=!1,u={x:0,y:0},d=null,f=!1,p=null,h=!1,m=!1,v=null;function y({noDragClassName:x,handleSelector:S,domNode:k,isSelectable:_,nodeId:C,nodeClickDistance:T=0}){p=Cp(k);function E({x:R,y:L}){const{nodeLookup:D,nodeExtent:F,snapGrid:H,snapToGrid:B,nodeOrigin:z,onNodeDrag:V,onSelectionDrag:M,onError:G,updateNodePositions:U}=t();a={x:R,y:L};let $=!1;const q=l.size>1,Z=q&&F?hve(J3(l)):null,Y=q&&B?$Yn({dragItems:l,snapGrid:H,x:R,y:L}):null;for(const[ne,J]of l){if(!D.has(ne))continue;let ee={x:R-J.distance.x,y:L-J.distance.y};B&&(ee=Y?{x:Math.round(ee.x+Y.x),y:Math.round(ee.y+Y.y)}:e4(ee,H));let re=null;if(q&&F&&!J.extent&&Z){const{positionAbsolute:te}=J.internals,se=te.x-Z.x+F[0][0],pe=te.x+J.measured.width-Z.x2+F[1][0],ce=te.y-Z.y+F[0][1],Se=te.y+J.measured.height-Z.y2+F[1][1];re=[[se,ce],[pe,Se]]}const{position:le,positionAbsolute:X}=OOt({nodeId:ne,nextPosition:ee,nodeLookup:D,nodeExtent:re||F,nodeOrigin:z,onError:G});$=$||J.position.x!==le.x||J.position.y!==le.y,J.position=le,J.internals.positionAbsolute=X}if(m=m||$,!!$&&(U(l,!0),v&&(r||V||!C&&M))){const[ne,J]=ene({nodeId:C,dragItems:l,nodeLookup:D});r?.(v,l,ne,J),V?.(v,ne,J),C||M?.(v,J)}}async function N(){if(!d)return;const{transform:R,panBy:L,autoPanSpeed:D,autoPanOnNodeDrag:F}=t();if(!F){c=!1,cancelAnimationFrame(i);return}const[H,B]=COt(u,d,D);(H!==0||B!==0)&&(a.x=(a.x??0)-H/R[2],a.y=(a.y??0)-B/R[2],await L({x:H,y:B})&&E(a)),i=requestAnimationFrame(N)}function I(R){const{nodeLookup:L,multiSelectionActive:D,nodesDraggable:F,transform:H,snapGrid:B,snapToGrid:z,selectNodesOnDrag:V,onNodeDragStart:M,onSelectionDragStart:G,unselectNodesAndEdges:U}=t();f=!0,(!V||!_)&&!D&&C&&(L.get(C)?.selected||U()),_&&V&&C&&e?.(C);const $=R$(R.sourceEvent,{transform:H,snapGrid:B,snapToGrid:z,containerBounds:d});if(a=$,l=PYn(L,F,$,C),l.size>0&&(n||M||!C&&G)){const[q,Z]=ene({nodeId:C,dragItems:l,nodeLookup:L});n?.(R.sourceEvent,l,q,Z),M?.(R.sourceEvent,q,Z),C||G?.(R.sourceEvent,Z)}}const A=rOt().clickDistance(T).on("start",R=>{const{domNode:L,nodeDragThreshold:D,transform:F,snapGrid:H,snapToGrid:B}=t();d=L?.getBoundingClientRect()||null,h=!1,m=!1,v=R.sourceEvent,D===0&&I(R),a=R$(R.sourceEvent,{transform:F,snapGrid:H,snapToGrid:B,containerBounds:d}),u=Cg(R.sourceEvent,d)}).on("drag",R=>{const{autoPanOnNodeDrag:L,transform:D,snapGrid:F,snapToGrid:H,nodeDragThreshold:B,nodeLookup:z}=t(),V=R$(R.sourceEvent,{transform:D,snapGrid:F,snapToGrid:H,containerBounds:d});if(v=R.sourceEvent,(R.sourceEvent.type==="touchmove"&&R.sourceEvent.touches.length>1||C&&!z.has(C))&&(h=!0),!h){if(!c&&L&&f&&(c=!0,N()),!f){const M=Cg(R.sourceEvent,d),G=M.x-u.x,U=M.y-u.y;Math.sqrt(G*G+U*U)>B&&I(R)}(a.x!==V.xSnapped||a.y!==V.ySnapped)&&l&&f&&(u=Cg(R.sourceEvent,d),E(V))}}).on("end",R=>{if(!(!f||h)&&(c=!1,f=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:L,updateNodePositions:D,onNodeDragStop:F,onSelectionDragStop:H}=t();if(m&&(D(l,!1),m=!1),s||F||!C&&H){const[B,z]=ene({nodeId:C,dragItems:l,nodeLookup:L,dragging:!1});s?.(R.sourceEvent,l,B,z),F?.(R.sourceEvent,B,z),C||H?.(R.sourceEvent,z)}}}).filter(R=>{const L=R.target;return!R.button&&(!x||!B7e(L,`.${x}`,k))&&(!S||B7e(L,S,k))});p.call(A)}function b(){p?.on(".drag",null)}return{update:y,destroy:b}}function DYn(e,t,n){const r=[],s={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const a of t.values())LM(s,aN(a))>0&&r.push(a);return r}const LYn=250;function FYn(e,t,n,r){let s=[],a=1/0;const i=DYn(e,n,t+LYn);for(const l of i){const c=[...l.internals.handleBounds?.source??[],...l.internals.handleBounds?.target??[]];for(const u of c){if(r.nodeId===u.nodeId&&r.type===u.type&&r.id===u.id)continue;const{x:d,y:f}=XO(l,u,u.position,!0),p=Math.sqrt(Math.pow(d-e.x,2)+Math.pow(f-e.y,2));p>t||(p<a?(s=[{...u,x:d,y:f}],a=p):p===a&&s.push({...u,x:d,y:f}))}}if(!s.length)return null;if(s.length>1){const l=r.type==="source"?"target":"source";return s.find(c=>c.type===l)??s[0]}return s[0]}function zOt(e,t,n,r,s,a=!1){const i=r.get(e);if(!i)return null;const l=s==="strict"?i.internals.handleBounds?.[t]:[...i.internals.handleBounds?.source??[],...i.internals.handleBounds?.target??[]],c=(n?l?.find(u=>u.id===n):l?.[0])??null;return c&&a?{...c,...XO(i,c,c.position,!0)}:c}function BOt(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function zYn(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const UOt=()=>!0;function BYn(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:a,isTarget:i,domNode:l,nodeLookup:c,lib:u,autoPanOnConnect:d,flowId:f,panBy:p,cancelConnection:h,onConnectStart:m,onConnect:v,onConnectEnd:y,isValidConnection:b=UOt,onReconnectEnd:x,updateConnection:S,getTransform:k,getFromHandle:_,autoPanSpeed:C,dragThreshold:T=1,handleDomNode:E}){const N=NOt(e.target);let I=0,A;const{x:R,y:L}=Cg(e),D=BOt(a,E),F=l?.getBoundingClientRect();let H=!1;if(!F||!D)return;const B=zOt(s,D,r,c,t);if(!B)return;let z=Cg(e,F),V=!1,M=null,G=!1,U=null;function $(){if(!d||!F)return;const[le,X]=COt(z,F,C);p({x:le,y:X}),I=requestAnimationFrame($)}const q={...B,nodeId:s,type:D,position:B.position},Z=c.get(s);let ne={inProgress:!0,isValid:null,from:XO(Z,q,tr.Left,!0),fromHandle:q,fromPosition:q.position,fromNode:Z,to:z,toHandle:null,toPosition:j7e[q.position],toNode:null,pointer:z};function J(){H=!0,S(ne),m?.(e,{nodeId:s,handleId:r,handleType:D})}T===0&&J();function ee(le){if(!H){const{x:Se,y:ve}=Cg(le),ke=Se-R,Ne=ve-L;if(!(ke*ke+Ne*Ne>T*T))return;J()}if(!_()||!q){re(le);return}const X=k();z=Cg(le,F),A=FYn(t4(z,X,!1,[1,1]),n,c,q),V||($(),V=!0);const te=qOt(le,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});U=te.handleDomNode,M=te.connection,G=zYn(!!A,te.isValid);const se=c.get(s),pe=se?XO(se,q,tr.Left,!0):ne.from,ce={...ne,from:pe,isValid:G,to:te.toHandle&&G?nU({x:te.toHandle.x,y:te.toHandle.y},X):z,toHandle:te.toHandle,toPosition:G&&te.toHandle?te.toHandle.position:j7e[q.position],toNode:te.toHandle?c.get(te.toHandle.nodeId):null,pointer:z};S(ce),ne=ce}function re(le){if(!("touches"in le&&le.touches.length>0)){if(H){(A||U)&&M&&G&&v?.(M);const{inProgress:X,...te}=ne,se={...te,toPosition:ne.toHandle?ne.toPosition:null};y?.(le,se),a&&x?.(le,se)}h(),cancelAnimationFrame(I),V=!1,G=!1,M=null,U=null,N.removeEventListener("mousemove",ee),N.removeEventListener("mouseup",re),N.removeEventListener("touchmove",ee),N.removeEventListener("touchend",re)}}N.addEventListener("mousemove",ee),N.addEventListener("mouseup",re),N.addEventListener("touchmove",ee),N.addEventListener("touchend",re)}function qOt(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=UOt,nodeLookup:d}){const f=a==="target",p=t?i.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:h,y:m}=Cg(e),v=i.elementFromPoint(h,m),y=v?.classList.contains(`${l}-flow__handle`)?v:p,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){const x=BOt(void 0,y),S=y.getAttribute("data-nodeid"),k=y.getAttribute("data-handleid"),_=y.classList.contains("connectable"),C=y.classList.contains("connectableend");if(!S||!x)return b;const T={source:f?S:r,sourceHandle:f?k:s,target:f?r:S,targetHandle:f?s:k};b.connection=T;const N=_&&C&&(n===rN.Strict?f&&x==="source"||!f&&x==="target":S!==r||k!==s);b.isValid=N&&u(T),b.toHandle=zOt(S,x,k,d,n,!0)}return b}const yve={onPointerDown:BYn,isValid:qOt};function UYn({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Cp(e);function a({translateExtent:l,width:c,height:u,zoomStep:d=1,pannable:f=!0,zoomable:p=!0,inversePan:h=!1}){const m=S=>{if(S.sourceEvent.type!=="wheel"||!t)return;const k=n(),_=S.sourceEvent.ctrlKey&&FM()?10:1,C=-S.sourceEvent.deltaY*(S.sourceEvent.deltaMode===1?.05:S.sourceEvent.deltaMode?1:.002)*d,T=k[2]*Math.pow(2,C*_);t.scaleTo(T)};let v=[0,0];const y=S=>{(S.sourceEvent.type==="mousedown"||S.sourceEvent.type==="touchstart")&&(v=[S.sourceEvent.clientX??S.sourceEvent.touches[0].clientX,S.sourceEvent.clientY??S.sourceEvent.touches[0].clientY])},b=S=>{const k=n();if(S.sourceEvent.type!=="mousemove"&&S.sourceEvent.type!=="touchmove"||!t)return;const _=[S.sourceEvent.clientX??S.sourceEvent.touches[0].clientX,S.sourceEvent.clientY??S.sourceEvent.touches[0].clientY],C=[_[0]-v[0],_[1]-v[1]];v=_;const T=r()*Math.max(k[2],Math.log(k[2]))*(h?-1:1),E={x:k[0]-C[0]*T,y:k[1]-C[1]*T},N=[[0,0],[c,u]];t.setViewportConstrained({x:E.x,y:E.y,zoom:k[2]},N,l)},x=yOt().on("start",y).on("zoom",f?b:null).on("zoom.wheel",p?m:null);s.call(x,{})}function i(){s.on("zoom",null)}return{update:a,destroy:i,pointer:fg}}const fW=e=>({x:e.x,y:e.y,zoom:e.k}),tne=({x:e,y:t,zoom:n})=>cW.translate(e,t).scale(n),xT=(e,t)=>e.target.closest(`.${t}`),VOt=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),qYn=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,nne=(e,t=0,n=qYn,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},HOt=e=>{const t=e.ctrlKey&&FM()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function VYn({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(xT(d,t))return d.ctrlKey&&d.preventDefault(),!1;d.preventDefault(),d.stopImmediatePropagation();const f=n.property("__zoom").k||1;if(d.ctrlKey&&i){const y=fg(d),b=HOt(d),x=f*Math.pow(2,b);r.scaleTo(n,x,y,d);return}const p=d.deltaMode===1?20:1;let h=s===rO.Vertical?0:d.deltaX*p,m=s===rO.Horizontal?0:d.deltaY*p;!FM()&&d.shiftKey&&s!==rO.Vertical&&(h=d.deltaY*p,m=0),r.translateBy(n,-(h/f)*a,-(m/f)*a,{internal:!0});const v=fW(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 HYn({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=xT(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function WYn({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=fW(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 ZYn({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&VOt(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,fW(a.transform))}}function GYn({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&VOt(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=fW(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function QYn({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:s,zoomOnDoubleClick:a,userSelectionActive:i,noWheelClassName:l,noPanClassName:c,lib:u,connectionInProgress:d}){return f=>{const p=e||t,h=n&&f.ctrlKey,m=f.type==="wheel";if(f.button===1&&f.type==="mousedown"&&(xT(f,`${u}-flow__node`)||xT(f,`${u}-flow__edge`)))return!0;if(!r&&!p&&!s&&!a&&!n||i||d&&!m||xT(f,l)&&m||xT(f,c)&&(!m||s&&m&&!e)||!n&&f.ctrlKey&&m)return!1;if(!n&&f.type==="touchstart"&&f.touches?.length>1)return f.preventDefault(),!1;if(!p&&!s&&!h&&m||!r&&(f.type==="mousedown"||f.type==="touchstart")||Array.isArray(r)&&!r.includes(f.button)&&f.type==="mousedown")return!1;const v=Array.isArray(r)&&r.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||m)&&v}}function YYn({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:s,onPanZoom:a,onPanZoomStart:i,onPanZoomEnd:l,onDraggingChange:c}){const u={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},d=e.getBoundingClientRect(),f=yOt().scaleExtent([t,n]).translateExtent(r),p=Cp(e).call(f);x({x:s.x,y:s.y,zoom:sN(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const h=p.on("wheel.zoom"),m=p.on("dblclick.zoom");f.wheelDelta(HOt);function v(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?hx:W8).transform(nne(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:R,onPaneContextMenu:L,userSelectionActive:D,panOnScroll:F,panOnDrag:H,panOnScrollMode:B,panOnScrollSpeed:z,preventScrolling:V,zoomOnPinch:M,zoomOnScroll:G,zoomOnDoubleClick:U,zoomActivationKeyPressed:$,lib:q,onTransformChange:Z,connectionInProgress:Y,paneClickDistance:ne,selectionOnDrag:J}){D&&!u.isZoomingOrPanning&&b();const ee=F&&!$&&!D;f.clickDistance(J?1/0:!_g(ne)||ne<0?0:ne);const re=ee?VYn({zoomPanValues:u,noWheelClassName:A,d3Selection:p,d3Zoom:f,panOnScrollMode:B,panOnScrollSpeed:z,zoomOnPinch:M,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):HYn({noWheelClassName:A,preventScrolling:V,d3ZoomHandler:h});if(p.on("wheel.zoom",re,{passive:!1}),!D){const X=WYn({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",X);const te=ZYn({zoomPanValues:u,panOnDrag:H,onPaneContextMenu:!!L,onPanZoom:a,onTransformChange:Z});f.on("zoom",te);const se=GYn({zoomPanValues:u,panOnDrag:H,panOnScroll:F,onPaneContextMenu:L,onPanZoomEnd:l,onDraggingChange:c});f.on("end",se)}const le=QYn({zoomActivationKeyPressed:$,panOnDrag:H,zoomOnScroll:G,panOnScroll:F,zoomOnDoubleClick:U,zoomOnPinch:M,userSelectionActive:D,noPanClassName:R,noWheelClassName:A,lib:q,connectionInProgress:Y});f.filter(le),U?p.on("dblclick.zoom",m):p.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,R,L){const D=tne(A),F=f?.constrain()(D,R,L);return F&&await v(F),new Promise(H=>H(F))}async function S(A,R){const L=tne(A);return await v(L,R),new Promise(D=>D(L))}function k(A){if(p){const R=tne(A),L=p.property("__zoom");(L.k!==A.zoom||L.x!==A.x||L.y!==A.y)&&f?.transform(p,R,null,{sync:!0})}}function _(){const A=p?vOt(p.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function C(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?hx:W8).scaleTo(nne(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function T(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?hx:W8).scaleBy(nne(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function E(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const R=!_g(A)||A<0?0:A;f?.clickDistance(R)}return{update:y,destroy:b,setViewport:S,setViewportConstrained:x,getViewport:_,scaleTo:C,scaleBy:T,setScaleExtent:E,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var oN;(function(e){e.Line="line",e.Handle="handle"})(oN||(oN={}));function KYn({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:s,affectsY:a}){const i=e-t,l=n-r,c=[i>0?1:i<0?-1:0,l>0?1:l<0?-1:0];return i&&s&&(c[0]=c[0]*-1),l&&a&&(c[1]=c[1]*-1),c}function U7e(e){const t=e.includes("right")||e.includes("left"),n=e.includes("bottom")||e.includes("top"),r=e.includes("left"),s=e.includes("top");return{isHorizontal:t,isVertical:n,affectsX:r,affectsY:s}}function X0(e,t){return Math.max(0,t-e)}function J0(e,t){return Math.max(0,e-t)}function wF(e,t,n){return Math.max(0,t-e,e-n)}function q7e(e,t){return e?!t:t}function XYn(e,t,n,r,s,a,i,l){let{affectsX:c,affectsY:u}=t;const{isHorizontal:d,isVertical:f}=t,p=d&&f,{xSnapped:h,ySnapped:m}=n,{minWidth:v,maxWidth:y,minHeight:b,maxHeight:x}=r,{x:S,y:k,width:_,height:C,aspectRatio:T}=e;let E=Math.floor(d?h-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=_+(c?-E:E),A=C+(u?-N:N),R=-a[0]*_,L=-a[1]*C;let D=wF(I,v,y),F=wF(A,b,x);if(i){let z=0,V=0;c&&E<0?z=X0(S+E+R,i[0][0]):!c&&E>0&&(z=J0(S+I+R,i[1][0])),u&&N<0?V=X0(k+N+L,i[0][1]):!u&&N>0&&(V=J0(k+A+L,i[1][1])),D=Math.max(D,z),F=Math.max(F,V)}if(l){let z=0,V=0;c&&E>0?z=J0(S+E,l[0][0]):!c&&E<0&&(z=X0(S+I,l[1][0])),u&&N>0?V=J0(k+N,l[0][1]):!u&&N<0&&(V=X0(k+A,l[1][1])),D=Math.max(D,z),F=Math.max(F,V)}if(s){if(d){const z=wF(I/T,b,x)*T;if(D=Math.max(D,z),i){let V=0;!c&&!u||c&&!u&&p?V=J0(k+L+I/T,i[1][1])*T:V=X0(k+L+(c?E:-E)/T,i[0][1])*T,D=Math.max(D,V)}if(l){let V=0;!c&&!u||c&&!u&&p?V=X0(k+I/T,l[1][1])*T:V=J0(k+(c?E:-E)/T,l[0][1])*T,D=Math.max(D,V)}}if(f){const z=wF(A*T,v,y)/T;if(F=Math.max(F,z),i){let V=0;!c&&!u||u&&!c&&p?V=J0(S+A*T+R,i[1][0])/T:V=X0(S+(u?N:-N)*T+R,i[0][0])/T,F=Math.max(F,V)}if(l){let V=0;!c&&!u||u&&!c&&p?V=X0(S+A*T,l[1][0])/T:V=J0(S+(u?N:-N)*T,l[0][0])/T,F=Math.max(F,V)}}}N=N+(N<0?F:-F),E=E+(E<0?D:-D),s&&(p?I>A*T?N=(q7e(c,u)?-E:E)/T:E=(q7e(c,u)?-N:N)*T:d?(N=E/T,u=c):(E=N*T,c=u));const H=c?S+E:S,B=u?k+N:k;return{width:_+(c?-E:E),height:C+(u?-N:N),x:a[0]*E*(c?-1:1)+H,y:a[1]*N*(u?-1:1)+B}}const WOt={width:0,height:0,x:0,y:0},JYn={...WOt,pointerX:0,pointerY:0,aspectRatio:1};function eKn(e){return[[0,0],[e.measured.width,e.measured.height]]}function tKn(e,t,n){const r=t.position.x+e.position.x,s=t.position.y+e.position.y,a=e.measured.width??0,i=e.measured.height??0,l=n[0]*a,c=n[1]*i;return[[r-l,s-c],[r+a-l,s+i-c]]}function nKn({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=Cp(e);let i={controlDirection:U7e("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:u,boundaries:d,keepAspectRatio:f,resizeDirection:p,onResizeStart:h,onResize:m,onResizeEnd:v,shouldResize:y}){let b={...WOt},x={...JYn};i={boundaries:d,resizeDirection:p,keepAspectRatio:f,controlDirection:U7e(u)};let S,k=null,_=[],C,T,E,N=!1;const I=rOt().on("start",A=>{const{nodeLookup:R,transform:L,snapGrid:D,snapToGrid:F,nodeOrigin:H,paneDomNode:B}=n();if(S=R.get(t),!S)return;k=B?.getBoundingClientRect()??null;const{xSnapped:z,ySnapped:V}=R$(A.sourceEvent,{transform:L,snapGrid:D,snapToGrid:F,containerBounds:k});b={width:S.measured.width??0,height:S.measured.height??0,x:S.position.x??0,y:S.position.y??0},x={...b,pointerX:z,pointerY:V,aspectRatio:b.width/b.height},C=void 0,S.parentId&&(S.extent==="parent"||S.expandParent)&&(C=R.get(S.parentId),T=C&&S.extent==="parent"?eKn(C):void 0),_=[],E=void 0;for(const[M,G]of R)if(G.parentId===t&&(_.push({id:M,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const U=tKn(G,S,G.origin??H);E?E=[[Math.min(U[0][0],E[0][0]),Math.min(U[0][1],E[0][1])],[Math.max(U[1][0],E[1][0]),Math.max(U[1][1],E[1][1])]]:E=U}h?.(A,{...b})}).on("drag",A=>{const{transform:R,snapGrid:L,snapToGrid:D,nodeOrigin:F}=n(),H=R$(A.sourceEvent,{transform:R,snapGrid:L,snapToGrid:D,containerBounds:k}),B=[];if(!S)return;const{x:z,y:V,width:M,height:G}=b,U={},$=S.origin??F,{width:q,height:Z,x:Y,y:ne}=XYn(x,i.controlDirection,H,i.boundaries,i.keepAspectRatio,$,T,E),J=q!==M,ee=Z!==G,re=Y!==z&&J,le=ne!==V&ⅇif(!re&&!le&&!J&&!ee)return;if((re||le||$[0]===1||$[1]===1)&&(U.x=re?Y:b.x,U.y=le?ne:b.y,b.x=U.x,b.y=U.y,_.length>0)){const pe=Y-z,ce=ne-V;for(const Se of _)Se.position={x:Se.position.x-pe+$[0]*(q-M),y:Se.position.y-ce+$[1]*(Z-G)},B.push(Se)}if((J||ee)&&(U.width=J&&(!i.resizeDirection||i.resizeDirection==="horizontal")?q:b.width,U.height=ee&&(!i.resizeDirection||i.resizeDirection==="vertical")?Z:b.height,b.width=U.width,b.height=U.height),C&&S.expandParent){const pe=$[0]*(U.width??0);U.x&&U.x<pe&&(b.x=pe,x.x=x.x-(U.x-pe));const ce=$[1]*(U.height??0);U.y&&U.y<ce&&(b.y=ce,x.y=x.y-(U.y-ce))}const X=KYn({width:b.width,prevWidth:M,height:b.height,prevHeight:G,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),te={...b,direction:X};y?.(A,te)!==!1&&(N=!0,m?.(A,te),r(U,B))}).on("end",A=>{N&&(v?.(A,{...b}),s?.({...b}),N=!1)});a.call(I)}function c(){a.on(".drag",null)}return{update:l,destroy:c}}const rKn={},V7e=e=>{let t;const n=new Set,r=(d,f)=>{const p=typeof d=="function"?d(t):d;if(!Object.is(p,t)){const h=t;t=f??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(m=>m(t,h))}},s=()=>t,c={setState:r,getState:s,getInitialState:()=>u,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(rKn?"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},sKn=e=>e?V7e(e):V7e,{useDebugValue:aKn}=ze,{useSyncExternalStoreWithSelector:iKn}=Njn,oKn=e=>e;function ZOt(e,t=oKn,n){const r=iKn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return aKn(r),r}const H7e=(e,t)=>{const n=sKn(e),r=(s,a=t)=>ZOt(n,s,a);return Object.assign(r,n),r},lKn=(e,t)=>e?H7e(e,t):H7e;function ao(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 pW=g.createContext(null),cKn=pW.Provider,GOt=ky.error001();function Hs(e,t){const n=g.useContext(pW);if(n===null)throw new Error(GOt);return ZOt(n,e,t)}function Co(){const e=g.useContext(pW);if(e===null)throw new Error(GOt);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const W7e={display:"none"},uKn={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},QOt="react-flow__node-desc",YOt="react-flow__edge-desc",dKn="react-flow__aria-live",fKn=e=>e.ariaLiveMessage,pKn=e=>e.ariaLabelConfig;function hKn({rfId:e}){const t=Hs(fKn);return o.jsx("div",{id:`${dKn}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:uKn,children:t})}function mKn({rfId:e,disableKeyboardA11y:t}){const n=Hs(pKn);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${QOt}-${e}`,style:W7e,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${YOt}-${e}`,style:W7e,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(hKn,{rfId:e})]})}const n4=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:ql(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});n4.displayName="Panel";function gKn({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(n4,{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 vKn=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}},SF=e=>e.id;function yKn(e,t){return ao(e.selectedNodes.map(SF),t.selectedNodes.map(SF))&&ao(e.selectedEdges.map(SF),t.selectedEdges.map(SF))}function bKn({onSelectionChange:e}){const t=Co(),{selectedNodes:n,selectedEdges:r}=Hs(vKn,yKn);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const xKn=e=>!!e.onSelectionChangeHandlers;function wKn({onSelectionChange:e}){const t=Hs(xKn);return e||t?o.jsx(bKn,{onSelectionChange:e}):null}const bve=typeof window<"u"?g.useLayoutEffect:g.useEffect,KOt=[0,0],SKn={x:0,y:0,zoom:1},kKn=["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"],Z7e=[...kKn,"rfId"],OKn=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}),G7e={translateExtent:$M,nodeOrigin:KOt,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function _Kn(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Hs(OKn,ao),u=Co();bve(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=G7e,l()}),[]);const d=g.useRef(G7e);return bve(()=>{for(const f of Z7e){const p=e[f],h=d.current[f];p!==h&&(typeof e[f]>"u"||(f==="nodes"?t(p):f==="edges"?n(p):f==="minZoom"?r(p):f==="maxZoom"?s(p):f==="translateExtent"?a(p):f==="nodeExtent"?i(p):f==="ariaLabelConfig"?u.setState({ariaLabelConfig:hYn(p)}):f==="fitView"?u.setState({fitViewQueued:p}):f==="fitViewOptions"?u.setState({fitViewOptions:p}):u.setState({[f]:p})))}d.current=e},Z7e.map(f=>e[f])),null}function Q7e(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function CKn(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=Q7e(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:Q7e()?.matches?"dark":"light"}const Y7e=typeof document<"u"?document:null;function zM(e=null,t={target:Y7e,actInsideInputWithModifier:!0}){const[n,r]=g.useState(!1),s=g.useRef(!1),a=g.useRef(new Set([])),[i,l]=g.useMemo(()=>{if(e!==null){const u=(Array.isArray(e)?e:[e]).filter(f=>typeof f=="string").map(f=>f.replace("+",`
|
|
234
|
+
`:r=="r"?"\r":r=="t"?" ":"\\")}eq(t){return this.search==t.search&&this.replace==t.replace&&this.caseSensitive==t.caseSensitive&&this.regexp==t.regexp&&this.wholeWord==t.wholeWord&&this.test==t.test}create(){return this.regexp?new CVn(this):new kVn(this)}getCursor(t,n=0,r){let s=t.doc?t:gs.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?eT(this,s,n,r):JE(this,s,n,r)}}class Ckt{constructor(t){this.spec=t}}function wVn(e,t,n){return(r,s,a,i)=>{if(n&&!n(r,s,a,i))return!1;let l=r>=i&&s<=i+a.length?a.slice(r-i,s-i):t.doc.sliceString(r,s);return e(l,t,r,s)}}function JE(e,t,n,r){let s;return e.wholeWord&&(s=SVn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=wVn(e.test,t,s)),new $x(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function SVn(e,t){return(n,r,s,a)=>((a>n||a+s.length<r)&&(a=Math.max(0,n-2),s=e.sliceString(a,Math.min(e.length,r+2))),(t(qB(s,n-a))!=yo.Word||t(VB(s,n-a))!=yo.Word)&&(t(VB(s,r-a))!=yo.Word||t(qB(s,r-a))!=yo.Word))}class kVn extends Ckt{constructor(t){super(t)}nextMatch(t,n,r){let s=JE(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=JE(this.spec,t,0,a).nextOverlapping()}return s.done||s.value.from==n&&s.value.to==r?null:s.value}prevMatchInRange(t,n,r){for(let s=r;;){let a=Math.max(n,s-1e4-this.spec.unquoted.length),i=JE(this.spec,t,a,s),l=null;for(;!i.nextOverlapping().done;)l=i.value;if(l)return l;if(a==n)return null;s-=1e4}}prevMatch(t,n,r){let s=this.prevMatchInRange(t,0,n);return s||(s=this.prevMatchInRange(t,Math.max(0,r-this.spec.unquoted.length),t.doc.length)),s&&(s.from!=n||s.to!=r)?s:null}getReplacement(t){return this.spec.unquote(this.spec.replace)}matchAll(t,n){let r=JE(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=JE(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}function OVn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function eT(e,t,n,r){let s;return e.wholeWord&&(s=_Vn(t.charCategorizer(t.selection.main.head))),e.test&&(s=OVn(e.test,t,s)),new kkt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function qB(e,t){return e.slice(Ic(e,t,!1),t)}function VB(e,t){return e.slice(t,Ic(e,t))}function _Vn(e){return(t,n,r)=>!r[0].length||(e(qB(r.input,r.index))!=yo.Word||e(VB(r.input,r.index))!=yo.Word)&&(e(VB(r.input,r.index+r[0].length))!=yo.Word||e(qB(r.input,r.index+r[0].length))!=yo.Word)}class CVn extends Ckt{nextMatch(t,n,r){let s=eT(this.spec,t,r,t.doc.length).next();return s.done&&(s=eT(this.spec,t,0,n).next()),s.done?null:s.value}prevMatchInRange(t,n,r){for(let s=1;;s++){let a=Math.max(n,r-s*1e4),i=eT(this.spec,t,a,r),l=null;for(;!i.next().done;)l=i.value;if(l&&(a==n||l.from>a+10))return l;if(a==n)return null}}prevMatch(t,n,r){return this.prevMatchInRange(t,0,n)||this.prevMatchInRange(t,r,t.doc.length)}getReplacement(t){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(n,r)=>{if(r=="&")return t.match[0];if(r=="$")return"$";for(let s=r.length;s>0;s--){let a=+r.slice(0,s);if(a>0&&a<t.match.length)return t.match[a]+r.slice(s)}return n})}matchAll(t,n){let r=eT(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=eT(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}const TM=dr.define(),sOe=dr.define(),Yw=vl.define({create(e){return new Xee(sve(e).create(),null)},update(e,t){for(let n of t.effects)n.is(TM)?e=new Xee(n.value.create(),e.panel):n.is(sOe)&&(e=new Xee(e.query,n.value?aOe:null));return e},provide:e=>yM.from(e,t=>t.panel)});class Xee{constructor(t,n){this.query=t,this.panel=n}}const EVn=Tn.mark({class:"cm-searchMatch"}),TVn=Tn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),jVn=ko.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Yw))}update(e){let t=e.state.field(Yw);(t!=e.startState.field(Yw)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return Tn.none;let{view:n}=this,r=new Hd;for(let s=0,a=n.visibleRanges,i=a.length;s<i;s++){let{from:l,to:c}=a[s];for(;s<i-1&&c>a[s+1].from-500;)c=a[++s].to;e.highlight(n.state,l,c,(u,d)=>{let f=n.state.selection.ranges.some(p=>p.from==u&&p.to==d);r.add(u,d,f?TVn:EVn)})}return r.finish()}},{decorations:e=>e.decorations});function Q3(e){return t=>{let n=t.state.field(Yw,!1);return n&&n.query.spec.valid?e(t,n):jkt(t)}}const HB=Q3((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=wt.single(r.from,r.to),a=e.state.facet(_I);return e.dispatch({selection:s,effects:[iOe(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),Tkt(e),!0}),WB=Q3((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let a=wt.single(s.from,s.to),i=e.state.facet(_I);return e.dispatch({selection:a,effects:[iOe(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),Tkt(e),!0}),NVn=Q3((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)}),IVn=({state:e,dispatch:t})=>{let n=e.selection;if(n.ranges.length>1||n.main.empty)return!1;let{from:r,to:s}=n.main,a=[],i=0;for(let l=new $x(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(i=a.length),a.push(wt.range(l.value.from,l.value.to))}return t(e.update({selection:wt.create(a,i),userEvent:"select.search.matches"})),!0},r9e=Q3((e,{query:t})=>{let{state:n}=e,{from:r,to:s}=n.selection.main;if(n.readOnly)return!1;let a=t.nextMatch(n,r,r);if(!a)return!1;let i=a,l=[],c,u,d=[];i.precise?i.from==r&&i.to==s&&(u=n.toText(t.getReplacement(i)),l.push({from:i.from,to:i.to,insert:u}),i=t.nextMatch(n,i.from,i.to),d.push(Rt.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+"."))):i=t.nextMatch(n,i.from,i.to);let f=e.state.changes(l);return i&&(c=wt.single(i.from,i.to).map(f),d.push(iOe(e,i)),d.push(n.facet(_I).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),AVn=Q3((e,{query:t})=>{if(e.state.readOnly)return!1;let n=[];for(let s of t.matchAll(e.state,1e9)){let{from:a,to:i,precise:l}=s;l&&n.push({from:a,to:i,insert:t.getReplacement(s)})}if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:Rt.announce.of(r),userEvent:"input.replace.all"}),!0});function aOe(e){return e.state.facet(_I).createPanel(e)}function sve(e,t){var n,r,s,a,i;let l=e.selection.main,c=l.empty||l.to>l.from+100?"":e.sliceDoc(l.from,l.to);if(t&&!c)return t;let u=e.facet(_I);return new _kt({search:((n=t?.literal)!==null&&n!==void 0?n:u.literal)?c:c.replace(/\n/g,"\\n"),caseSensitive:(r=t?.caseSensitive)!==null&&r!==void 0?r:u.caseSensitive,literal:(s=t?.literal)!==null&&s!==void 0?s:u.literal,regexp:(a=t?.regexp)!==null&&a!==void 0?a:u.regexp,wholeWord:(i=t?.wholeWord)!==null&&i!==void 0?i:u.wholeWord})}function Ekt(e){let t=wke(e,aOe);return t&&t.dom.querySelector("[main-field]")}function Tkt(e){let t=Ekt(e);t&&t==e.root.activeElement&&t.select()}const jkt=e=>{let t=e.state.field(Yw,!1);if(t&&t.panel){let n=Ekt(e);if(n&&n!=e.root.activeElement){let r=sve(e.state,t.query.spec);r.valid&&e.dispatch({effects:TM.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[sOe.of(!0),t?TM.of(sve(e.state,t.query.spec)):dr.appendConfig.of(MVn)]});return!0},Nkt=e=>{let t=e.state.field(Yw,!1);if(!t||!t.panel)return!1;let n=wke(e,aOe);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:sOe.of(!1)}),!0},RVn=[{key:"Mod-f",run:jkt,scope:"editor search-panel"},{key:"F3",run:HB,shift:WB,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:HB,shift:WB,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:Nkt,scope:"editor search-panel"},{key:"Mod-Shift-l",run:IVn},{key:"Mod-Alt-g",run:cVn},{key:"Mod-d",run:xVn,preventDefault:!0}];class PVn{constructor(t){this.view=t;let n=this.query=t.state.field(Yw).query.spec;this.commit=this.commit.bind(this),this.searchField=oi("input",{value:n.search,placeholder:up(t,"Find"),"aria-label":up(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=oi("input",{value:n.replace,placeholder:up(t,"Replace"),"aria-label":up(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=oi("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=oi("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=oi("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return oi("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=oi("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>HB(t),[up(t,"next")]),r("prev",()=>WB(t),[up(t,"previous")]),r("select",()=>NVn(t),[up(t,"all")]),oi("label",null,[this.caseField,up(t,"match case")]),oi("label",null,[this.reField,up(t,"regexp")]),oi("label",null,[this.wordField,up(t,"by word")]),...t.state.readOnly?[]:[oi("br"),this.replaceField,r("replace",()=>r9e(t),[up(t,"replace")]),r("replaceAll",()=>AVn(t),[up(t,"replace all")])],oi("button",{name:"close",onclick:()=>Nkt(t),"aria-label":up(t,"close"),type:"button"},["×"])])}commit(){let t=new _kt({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:TM.of(t)}))}keydown(t){ezn(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?WB:HB)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),r9e(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(TM)&&!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(_I).top}}function up(e,t){return e.state.phrase(t)}const fF=30,pF=/[\s\.,:;?!]/;function iOe(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),s=e.state.doc.lineAt(n).to,a=Math.max(r.from,t-fF),i=Math.min(s,n+fF),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<fF;c++)if(!pF.test(l[c+1])&&pF.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-fF;c--)if(!pF.test(l[c-1])&&pF.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 $Vn=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"}}),MVn=[Yw,th.low(jVn),$Vn];class s9e{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class _k{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(jM).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new Hd,l=[],c=0;for(let d=0;;){let f=d==a.length?null:a[d];if(!f&&!l.length)break;let p,h;for(l.length?(p=c,h=l.reduce((v,y)=>Math.min(v,y.to),f&&f.from>p?f.from:1e8)):(p=f.from,h=f.to,l.push(f),d++);d<a.length;){let v=a[d];if(v.from==p&&(v.to>v.from||v.to==p))l.push(v),d++,h=Math.min(v.to,h);else{h=Math.min(v.from,h);break}}let m=QVn(l);if(l.some(v=>v.from==v.to||v.from==v.to-1&&r.doc.lineAt(v.from).to==v.from))i.add(p,p,Tn.widget({widget:new HVn(m),diagnostics:l.slice()}));else{let v=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(p,h,Tn.mark({class:"cm-lintRange cm-lintRange-"+m+v,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>h)}))}c=h;for(let v=0;v<l.length;v++)l[v].to<=c&&l.splice(v--,1)}let u=i.finish();return new _k(u,n,eN(u))}}function eN(e,t=null,n=0){let r=null;return e.between(n,1e9,(s,a,{spec:i})=>{if(!(t&&i.diagnostics.indexOf(t)<0))if(!r)r=new s9e(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new s9e(r.from,a,r.diagnostic)}}),r}function DVn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(jM).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(Ikt))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function LVn(e,t){return e.field(Np,!1)?t:t.concat(dr.appendConfig.of(YVn))}const Ikt=dr.define(),oOe=dr.define(),Akt=dr.define(),Np=vl.define({create(){return new _k(Tn.none,null,null)},update(e,t){if(t.docChanged&&e.diagnostics.size){let n=e.diagnostics.map(t.changes),r=null,s=e.panel;if(e.selected){let a=t.changes.mapPos(e.selected.from,1);r=eN(n,e.selected.diagnostic,a)||eN(n,null,a)}!n.size&&s&&t.state.facet(jM).autoPanel&&(s=null),e=new _k(n,s,r)}for(let n of t.effects)if(n.is(Ikt)){let r=t.state.facet(jM).autoPanel?n.value.length?NM.open:null:e.panel;e=_k.init(n.value,r,t.state)}else n.is(oOe)?e=new _k(e.diagnostics,n.value?NM.open:null,e.selected):n.is(Akt)&&(e=new _k(e.diagnostics,e.panel,n.value));return e},provide:e=>[yM.from(e,t=>t.panel),Rt.decorations.from(e,t=>t.diagnostics)]}),FVn=Tn.mark({class:"cm-lintRange cm-lintRange-active"});function zVn(e,t,n){let{diagnostics:r}=e.state.field(Np),s,a=-1,i=-1;r.between(t-(n<0?1:0),t+(n>0?1:0),(c,u,{spec:d})=>{if(t>=c&&t<=u&&(c==u||(t>c||n>0)&&(t<u||n<0)))return s=d.diagnostics,a=c,i=u,!1});let l=e.state.facet(jM).tooltipFilter;return s&&l&&(s=l(s,e.state)),s?{pos:a,end:i,above:e.state.doc.lineAt(a).to<i,create(){return{dom:BVn(e,s)}}}:null}function BVn(e,t){return oi("ul",{class:"cm-tooltip-lint"},t.map(n=>Pkt(e,n,!1)))}const UVn=e=>{let t=e.state.field(Np,!1);(!t||!t.panel)&&e.dispatch({effects:LVn(e.state,[oOe.of(!0)])});let n=wke(e,NM.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},a9e=e=>{let t=e.state.field(Np,!1);return!t||!t.panel?!1:(e.dispatch({effects:oOe.of(!1)}),!0)},qVn=e=>{let t=e.state.field(Np,!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)},VVn=[{key:"Mod-Shift-m",run:UVn,preventDefault:!0},{key:"F8",run:qVn}],jM=wn.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...Fy(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:i9e,tooltipFilter:i9e,needsRefresh:(t,n)=>t?n?r=>t(r)||n(r):t:n,hideOn:(t,n)=>t?n?(r,s,a)=>t(r,s,a)||n(r,s,a):t:n,autoPanel:(t,n)=>t||n})}}});function i9e(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function Rkt(e){let t=[];if(e)e:for(let{name:n}of e){for(let r=0;r<n.length;r++){let s=n[r];if(/[a-zA-Z]/.test(s)&&!t.some(a=>a.toLowerCase()==s.toLowerCase())){t.push(s);continue e}}t.push("")}return t}function Pkt(e,t,n){var r;let s=n?Rkt(t.actions):[];return oi("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},oi("span",{class:"cm-diagnosticText"},t.renderMessage?t.renderMessage(e):t.message),(r=t.actions)===null||r===void 0?void 0:r.map((a,i)=>{let l=!1,c=h=>{if(h.preventDefault(),l)return;l=!0;let m=eN(e.state.field(Np).diagnostics,t);m&&a.apply(e,m.from,m.to)},{name:u}=a,d=s[i]?u.indexOf(s[i]):-1,f=d<0?u:[u.slice(0,d),oi("u",u.slice(d,d+1)),u.slice(d+1)],p=a.markClass?" "+a.markClass:"";return oi("button",{type:"button",class:"cm-diagnosticAction"+p,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&oi("div",{class:"cm-diagnosticSource"},t.source))}class HVn extends nh{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return oi("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class o9e{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=Pkt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class NM{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)a9e(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:a}=this.items[this.selectedIndex],i=Rkt(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=eN(this.view.state.field(Np).diagnostics,a);c&&a.actions[l].apply(t,c.from,c.to)}}else return;s.preventDefault()},r=s=>{for(let a=0;a<this.items.length;a++)this.items[a].dom.contains(s.target)&&this.moveSelection(a)};this.list=oi("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=oi("div",{class:"cm-panel-lint"},this.list,oi("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>a9e(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Np).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(Np),r=0,s=!1,a=null,i=new Set;for(t.between(0,this.view.state.doc.length,(l,c,{spec:u})=>{for(let d of u.diagnostics){if(i.has(d))continue;i.add(d);let f=-1,p;for(let h=r;h<this.items.length;h++)if(this.items[h].diagnostic==d){f=h;break}f<0?(p=new o9e(this.view,d),this.items.splice(r,0,p),s=!0):(p=this.items[f],f>r&&(this.items.splice(r,f-r),s=!0)),n&&p.diagnostic==n.diagnostic?p.dom.hasAttribute("aria-selected")||(p.dom.setAttribute("aria-selected","true"),a=p):p.dom.hasAttribute("aria-selected")&&p.dom.removeAttribute("aria-selected"),r++}});r<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0);)s=!0,this.items.pop();this.items.length==0&&(this.items.push(new o9e(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),s=!0),a?(this.list.setAttribute("aria-activedescendant",a.id),this.view.requestMeasure({key:this,read:()=>({sel:a.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:l,panel:c})=>{let u=c.height/this.list.offsetHeight;l.top<c.top?this.list.scrollTop-=(c.top-l.top)/u:l.bottom>c.bottom&&(this.list.scrollTop+=(l.bottom-c.bottom)/u)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let t=this.list.firstChild;function n(){let r=t;t=r.nextSibling,r.remove()}for(let r of this.items)if(r.dom.parentNode==this.list){for(;t!=r.dom;)n();t=r.dom.nextSibling}else this.list.insertBefore(r.dom,t);for(;t;)n()}moveSelection(t){if(this.selectedIndex<0)return;let n=this.view.state.field(Np),r=eN(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:Akt.of(r)})}static open(t){return new NM(t)}}function WVn(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 hF(e){return WVn(`<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 ZVn=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:hF("#d11")},".cm-lintRange-warning":{backgroundImage:hF("orange")},".cm-lintRange-info":{backgroundImage:hF("#999")},".cm-lintRange-hint":{backgroundImage:hF("#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 GVn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function QVn(e){let t="hint",n=1;for(let r of e){let s=GVn(r.severity);s>n&&(n=s,t=r.severity)}return t}const YVn=[Np,Rt.decorations.compute([Np],e=>{let{selected:t,panel:n}=e.field(Np);return!t||!n||t.from==t.to?Tn.none:Tn.set([FVn.range(t.from,t.to)])}),Uzn(zVn,{hideOn:DVn}),ZVn];var l9e=function(t){t===void 0&&(t={});var n=t,r=n.crosshairCursor,s=r===void 0?!1:r,a=[];t.closeBracketsKeymap!==!1&&(a=a.concat(F9n)),t.defaultKeymap!==!1&&(a=a.concat(iVn)),t.searchKeymap!==!1&&(a=a.concat(RVn)),t.historyKeymap!==!1&&(a=a.concat(pqn)),t.foldKeymap!==!1&&(a=a.concat(O8n)),t.completionKeymap!==!1&&(a=a.concat(T1t)),t.lintKeymap!==!1&&(a=a.concat(VVn));var i=[];return t.lineNumbers!==!1&&i.push(e8n()),t.highlightActiveLineGutter!==!1&&i.push(r8n()),t.highlightSpecialChars!==!1&&i.push(gzn()),t.history!==!1&&i.push(sqn()),t.foldGutter!==!1&&i.push(T8n()),t.drawSelection!==!1&&i.push(izn()),t.dropCursor!==!1&&i.push(dzn()),t.allowMultipleSelections!==!1&&i.push(gs.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(g8n()),t.syntaxHighlighting!==!1&&i.push(rS(A8n,{fallback:!0})),t.bracketMatching!==!1&&i.push(F8n()),t.closeBrackets!==!1&&i.push($9n()),t.autocompletion!==!1&&i.push(E1t()),t.rectangularSelection!==!1&&i.push(Nzn()),s!==!1&&i.push(Rzn()),t.highlightActiveLine!==!1&&i.push(Szn()),t.highlightSelectionMatches!==!1&&i.push(fVn()),t.tabSize&&typeof t.tabSize=="number"&&i.push(wI.of(" ".repeat(t.tabSize))),i.concat([xI.of(a.flat())]).filter(Boolean)};const KVn="#e5c07b",c9e="#e06c75",XVn="#56b6c2",JVn="#ffffff",V8="#abb2bf",ave="#7d8799",eHn="#61afef",tHn="#98c379",u9e="#d19a66",nHn="#c678dd",rHn="#21252b",d9e="#2c313a",f9e="#282c34",Jee="#353a42",sHn="#3E4451",p9e="#528bff",aHn=Rt.theme({"&":{color:V8,backgroundColor:f9e},".cm-content":{caretColor:p9e},".cm-cursor, .cm-dropCursor":{borderLeftColor:p9e},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:sHn},".cm-panels":{backgroundColor:rHn,color:V8},".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:f9e,color:ave,border:"none"},".cm-activeLineGutter":{backgroundColor:d9e},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:Jee},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:Jee,borderBottomColor:Jee},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:d9e,color:V8}}},{dark:!0}),iHn=Kg.define([{tag:de.keyword,color:nHn},{tag:[de.name,de.deleted,de.character,de.propertyName,de.macroName],color:c9e},{tag:[de.function(de.variableName),de.labelName],color:eHn},{tag:[de.color,de.constant(de.name),de.standard(de.name)],color:u9e},{tag:[de.definition(de.name),de.separator],color:V8},{tag:[de.typeName,de.className,de.number,de.changed,de.annotation,de.modifier,de.self,de.namespace],color:KVn},{tag:[de.operator,de.operatorKeyword,de.url,de.escape,de.regexp,de.link,de.special(de.string)],color:XVn},{tag:[de.meta,de.comment],color:ave},{tag:de.strong,fontWeight:"bold"},{tag:de.emphasis,fontStyle:"italic"},{tag:de.strikethrough,textDecoration:"line-through"},{tag:de.link,color:ave,textDecoration:"underline"},{tag:de.heading,fontWeight:"bold",color:c9e},{tag:[de.atom,de.bool,de.special(de.variableName)],color:u9e},{tag:[de.processingInstruction,de.string,de.inserted],color:tHn},{tag:de.invalid,color:JVn}]),oHn=[aHn,rS(iHn)];var lHn=Rt.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),cHn=function(t){t===void 0&&(t={});var n=t,r=n.indentWithTab,s=r===void 0?!0:r,a=n.editable,i=a===void 0?!0:a,l=n.readOnly,c=l===void 0?!1:l,u=n.theme,d=u===void 0?"light":u,f=n.placeholder,p=f===void 0?"":f,h=n.basicSetup,m=h===void 0?!0:h,v=[];switch(s&&v.unshift(xI.of([oVn])),m&&(typeof m=="boolean"?v.unshift(l9e()):v.unshift(l9e(m))),p&&v.unshift(Czn(p)),d){case"light":v.push(lHn);break;case"dark":v.push(oHn);break;case"none":break;default:v.push(d);break}return i===!1&&v.push(Rt.editable.of(!1)),c&&v.push(gs.readOnly.of(!0)),[...v]},uHn=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 dHn{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 h9e{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 ete=null,fHn=()=>typeof window>"u"?new h9e:(ete||(ete=new h9e),ete),pHn=Rt.theme({"& .cm-scroller":{height:"100% !important"}}),m9e=null,tte=null;function hHn(e,t,n,r,s,a){if(!e&&!t&&!n&&!r&&!s&&!a)return null;var i=JSON.stringify({height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a});return i===m9e||(m9e=i,tte=Rt.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a}})),tte}var g9e=Ly.define(),mHn=200,gHn=[];function vHn(e){var t=e.value,n=e.selection,r=e.onChange,s=e.onStatistics,a=e.onCreateEditor,i=e.onUpdate,l=e.extensions,c=l===void 0?gHn:l,u=e.autoFocus,d=e.theme,f=d===void 0?"light":d,p=e.height,h=p===void 0?null:p,m=e.minHeight,v=m===void 0?null:m,y=e.maxHeight,b=y===void 0?null:y,x=e.width,S=x===void 0?null:x,k=e.minWidth,_=k===void 0?null:k,C=e.maxWidth,T=C===void 0?null:C,E=e.placeholder,N=E===void 0?"":E,I=e.editable,A=I===void 0?!0:I,R=e.readOnly,L=R===void 0?!1:R,D=e.indentWithTab,F=D===void 0?!0:D,H=e.basicSetup,B=H===void 0?!0:H,z=e.root,V=e.initialState,M=g.useState(),G=M[0],U=M[1],$=g.useState(),q=$[0],Z=$[1],Y=g.useState(),ne=Y[0],J=Y[1],ee=g.useState(()=>({current:null}))[0],re=g.useState(()=>({current:null}))[0],le=hHn(h,v,b,S,_,T),X=Rt.updateListener.of(pe=>{if(pe.docChanged&&typeof r=="function"&&!pe.transactions.some(ve=>ve.annotation(g9e))){ee.current?ee.current.reset():(ee.current=new dHn(()=>{if(re.current){var ve=re.current;re.current=null,ve()}ee.current=null},mHn),fHn().add(ee.current));var ce=pe.state.doc,Se=ce.toString();r(Se,pe)}s&&s(uHn(pe))}),te=cHn({theme:f,editable:A,readOnly:L,placeholder:N,indentWithTab:F,basicSetup:B}),se=[X,...le?[le]:[],pHn,...te];return i&&typeof i=="function"&&se.push(Rt.updateListener.of(i)),se=se.concat(c),g.useLayoutEffect(()=>{if(G&&!ne){var pe={doc:t,selection:n,extensions:se},ce=V?gs.fromJSON(V.json,pe,V.fields):gs.create(pe);if(J(ce),!q){var Se=new Rt({state:ce,parent:G,root:z});Z(Se),a&&a(Se,ce)}}return()=>{q&&(J(void 0),Z(void 0))}},[G,ne]),g.useEffect(()=>{e.container&&U(e.container)},[e.container]),g.useEffect(()=>()=>{q&&(q.destroy(),Z(void 0)),ee.current&&(ee.current.cancel(),ee.current=null)},[q]),g.useEffect(()=>{u&&q&&q.focus()},[u,q]),g.useEffect(()=>{q&&q.dispatch({effects:dr.reconfigure.of(se)})},[f,c,h,v,b,S,_,T,N,A,L,F,B,r,i]),g.useEffect(()=>{if(t!==void 0){var pe=q?q.state.doc.toString():"";if(q&&t!==pe){var ce=ee.current&&!ee.current.isDone,Se=()=>{q&&t!==q.state.doc.toString()&&q.dispatch({changes:{from:0,to:q.state.doc.toString().length,insert:t||""},annotations:[g9e.of(!0)]})};ce?re.current=Se:Se()}}},[t,q]),{state:ne,setState:J,view:q,setView:Z,container:G,setContainer:U}}var yHn=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],rd=g.forwardRef((e,t)=>{var n=e.className,r=e.value,s=r===void 0?"":r,a=e.selection,i=e.extensions,l=i===void 0?[]:i,c=e.onChange,u=e.onStatistics,d=e.onCreateEditor,f=e.onUpdate,p=e.autoFocus,h=e.theme,m=h===void 0?"light":h,v=e.height,y=e.minHeight,b=e.maxHeight,x=e.width,S=e.minWidth,k=e.maxWidth,_=e.basicSetup,C=e.placeholder,T=e.indentWithTab,E=e.editable,N=e.readOnly,I=e.root,A=e.initialState,R=USt(e,yHn),L=g.useRef(null),D=vHn({root:I,value:s,autoFocus:p,theme:m,height:v,minHeight:y,maxHeight:b,width:x,minWidth:S,maxWidth:k,basicSetup:_,placeholder:C,indentWithTab:T,editable:E,readOnly:N,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),F=D.state,H=D.view,B=D.container,z=D.setContainer;g.useImperativeHandle(t,()=>({editor:L.current,state:F,view:H}),[L,B,F,H]);var V=g.useCallback(G=>{L.current=G,z(G)},[z]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var M=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",GO({ref:V,className:""+M+(n?" "+n:"")},R))});rd.displayName="CodeMirror";const bHn={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 nte=null;function xHn(){return nte||(nte=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Ma(()=>import("./core-gZ7e9rsY.js"),__vite__mapDeps([0,1,2]),import.meta.url),Ma(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[Ma(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Ma(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Ma(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Ma(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Ma(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Ma(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Ma(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Ma(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Ma(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Ma(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Ma(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Ma(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Ma(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Ma(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([4,5,6]),import.meta.url),Ma(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Ma(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),nte}async function wHn(e,t){const n=bHn[t?.toLowerCase()];if(!n)return null;const r=await xHn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function SHn(e){return new VO(Cke.define(e))}const $kt=[dg.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return Ma(()=>Promise.resolve().then(()=>uF),void 0,import.meta.url).then(e=>e.javascript())}}),dg.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return Ma(()=>Promise.resolve().then(()=>K8n),void 0,import.meta.url).then(e=>e.json())}}),dg.of({name:"JSX",extensions:["jsx"],load(){return Ma(()=>Promise.resolve().then(()=>uF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),dg.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return Ma(()=>Promise.resolve().then(()=>HUn),void 0,import.meta.url).then(e=>e.markdown())}}),dg.of({name:"TSX",extensions:["tsx"],load(){return Ma(()=>Promise.resolve().then(()=>uF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),dg.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return Ma(()=>Promise.resolve().then(()=>uF),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),dg.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return Ma(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>SHn(e.shell))}})];function kHn(e,t=5){if(!e?.properties)return[];const n=[];function r(s,a,i){if(i>t)return;const l=Array.isArray(s.type)?s.type.join(" | "):s.type;if(n.push({path:a,label:a,description:s.description??s.title,type:l}),s.properties)for(const[c,u]of Object.entries(s.properties))r(u,`${a}.${c}`,i+1);if(s.items?.properties)for(const[c,u]of Object.entries(s.items.properties))r(u,`${a}[].${c}`,i+1)}for(const[s,a]of Object.entries(e.properties))r(a,s,1);return n}function OHn(e){const t=kHn(e);return E1t({override:[_Hn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function _Hn(e){return t=>{const r=t.state.sliceDoc(Math.max(0,t.pos-50),t.pos).match(/\{\{([a-zA-Z0-9_.\[\]]*)?$/);if(!r)return null;const s=r[1]??"",a=t.pos-s.length,i=s?e.filter(c=>c.path.toLowerCase().startsWith(s.toLowerCase())):e;if(i.length===0)return null;const l=i.map(c=>({label:c.path,displayLabel:c.path,detail:c.type,info:c.description,apply:(u,d,f,p)=>{const v=u.state.sliceDoc(p,p+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:p,insert:v},selection:{anchor:f+v.length}})}}));return{from:a,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const CHn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,EHn=Tn.mark({class:"cm-variable-highlight"}),v9e=new Bwt({regexp:CHn,decoration:()=>EHn}),THn=ko.fromClass(class{decorations;constructor(e){this.decorations=v9e.createDeco(e)}update(e){this.decorations=v9e.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),jHn=THn;function NHn(){const e=kI({settings:{fontFamily:"var(--font-mono)",fontSize:"0.8rem",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"var(--neutral2)",background:"transparent",foreground:"var(--neutral6)",caret:"var(--neutral6)"},styles:[{tag:[de.className,de.propertyName],color:"var(--neutral6)"},{tag:de.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[de.heading1,de.heading2,de.heading3,de.heading4,de.heading5,de.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:de.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:de.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:de.link,color:"var(--accent3)",textDecoration:"underline"},{tag:de.url,color:"var(--accent3)"},{tag:de.monospace,color:"var(--neutral6)"},{tag:de.strikethrough,textDecoration:"line-through"},{tag:de.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=Rt.theme({".cm-editor":{backgroundColor:"transparent"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{color:"var(--neutral3)"},".cm-cursor":{borderLeftColor:"var(--neutral6)"},".cm-selectionBackground, .cm-content ::selection":{backgroundColor:"color-mix(in srgb, var(--accent3) 22%, transparent)"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}});return[e,t]}function IHn(){const e=Rt.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"0.8rem"},"&.cm-editor .cm-scroller":{fontFamily:"var(--font-mono)"},".cm-gutters":{backgroundColor:"transparent",color:"var(--neutral2)",borderRight:"none"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-activeLine":{backgroundColor:"transparent"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{backgroundColor:"transparent",color:"var(--neutral3)"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"var(--neutral6)"},"&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection":{background:"color-mix(in srgb, var(--accent3) 22%, transparent) !important"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"0.7rem",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}}),t=Kg.define([{tag:[de.comment,de.bracket],color:"var(--neutral2)"},{tag:[de.string,de.meta,de.regexp],color:"var(--accent1)"},{tag:[de.atom,de.bool,de.special(de.variableName)],color:"var(--accent6)"},{tag:[de.keyword,de.operator,de.tagName],color:"var(--accent2)"},{tag:[de.function(de.propertyName),de.propertyName],color:"var(--accent5)"},{tag:[de.definition(de.variableName),de.function(de.variableName),de.className,de.attributeName],color:"var(--accent3)"},{tag:[de.variableName,de.number],color:"var(--accent5)"},{tag:[de.name,de.quote],color:"var(--accent1)"},{tag:de.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[de.heading1,de.heading2,de.heading3,de.heading4,de.heading5,de.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[de.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[de.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:de.link,color:"var(--accent3)",textDecoration:"underline"},{tag:de.url,color:"var(--accent3)"},{tag:de.monospace,color:"var(--neutral6)"},{tag:de.strikethrough,textDecoration:"line-through"},{tag:[de.deleted],color:"var(--accent2)"},{tag:de.invalid,color:"var(--error)"},{tag:[de.standard(de.tagName)],color:"var(--accent1)"}]);return[e,rS(t)]}const s0=()=>{const e=K_().resolvedTheme==="dark";return g.useMemo(()=>e?NHn():IHn(),[e])},AHn=Ii(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"}}),RHn=th.highest(Rt.editorAttributes.of({style:"outline: none"})),PHn=th.highest(Rt.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),$Hn=[RHn,PHn],Zr=g.forwardRef(({data:e,value:t,onChange:n,showCopyButton:r=!0,className:s,language:a="json",highlightVariables:i=!1,placeholder:l,schema:c,autoFocus:u,lineNumbers:d=!0,lineWrapping:f=!0,editable:p,variant:h,...m},v)=>{const y=s0(),b=e?JSON.stringify(e,null,2):t??"",x=g.useMemo(()=>{const S=[...$Hn];return f&&S.push(Rt.lineWrapping),a==="json"?S.push(Dp):a==="markdown"&&S.push(Jke({base:ZO,codeLanguages:$kt})),i&&a==="markdown"&&S.push(jHn),c&&a==="markdown"&&S.push(OHn(c)),p===!1&&S.push(gs.readOnly.of(!0)),S},[a,i,c,p,f]);return o.jsxs("div",{className:K(AHn({variant:h}),s),...m,children:[r&&o.jsx(ka,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(rd,{ref:v,value:b,theme:y,extensions:x,onChange:n,editable:p,"aria-label":"Code editor",placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),MHn=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},DHn=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=s0(),{settings:r,setSettings:s}=NH(),a=r?.tracingOptions,i=g.useMemo(()=>MHn(a),[a]),[l,c]=g.useState(()=>i),u=g.useRef(!1);g.useEffect(()=>{u.current||c(i)},[i]);const d=p=>{u.current=!0,c(p)},f=()=>{if(!l){s({...r,tracingOptions:void 0}),t?.();return}try{const p=JSON.parse(l);typeof p=="object"&&p!==null&&s({...r,tracingOptions:p})}catch{return}t?.()};return o.jsxs("div",{className:"space-y-2 px-5 py-2",children:[o.jsx(me,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),o.jsx(rd,{value:l,onChange:d,theme:n,extensions:[Dp],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(oe,{type:"button",onClick:f,children:"Save"})})]})},LHn=()=>{const[e,t]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:o.jsx(oe,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(He,{children:o.jsx(g0e,{})})})}),o.jsx(vn,{children:"Run Options"})]}),o.jsx(vr,{open:e,onOpenChange:t,children:o.jsxs(yr,{children:[o.jsxs(br,{children:[o.jsx(pr,{children:"Run Options"}),o.jsx(Ps,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx(Mr,{children:o.jsx(DHn,{onSaved:()=>t(!1)})})]})})]})};function FHn({status:e}){switch(e){case"running":return o.jsx(Ut,{});case"failed":return o.jsx(or,{className:"text-accent2"});case"canceled":return o.jsx(Mc,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(r1,{className:"text-neutral3"});case"suspended":return o.jsx(mV,{className:"text-accent3"});case"success":return o.jsx(Qr,{className:"text-accent1"});default:return o.jsx(r1,{className:"text-neutral3"})}}function Mkt({status:e}){return o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:o.jsx(He,{"aria-label":e,className:"shrink-0",children:o.jsx(FHn,{status:e})})}),o.jsx(vn,{children:e})]})}var rte,y9e;function lOe(){if(y9e)return rte;y9e=1;var e="\0",t="\0",n="";class r{_isDirected=!0;_isMultigraph=!1;_isCompound=!1;_label;_defaultNodeLabelFn=()=>{};_defaultEdgeLabelFn=()=>{};_nodes={};_in={};_preds={};_out={};_sucs={};_edgeObjs={};_edgeLabels={};_nodeCount=0;_edgeCount=0;_parent;_children;constructor(d){d&&(this._isDirected=Object.hasOwn(d,"directed")?d.directed:!0,this._isMultigraph=Object.hasOwn(d,"multigraph")?d.multigraph:!1,this._isCompound=Object.hasOwn(d,"compound")?d.compound:!1),this._isCompound&&(this._parent={},this._children={},this._children[t]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(d){return this._label=d,this}graph(){return this._label}setDefaultNodeLabel(d){return this._defaultNodeLabelFn=d,typeof d!="function"&&(this._defaultNodeLabelFn=()=>d),this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){var d=this;return this.nodes().filter(f=>Object.keys(d._in[f]).length===0)}sinks(){var d=this;return this.nodes().filter(f=>Object.keys(d._out[f]).length===0)}setNodes(d,f){var p=arguments,h=this;return d.forEach(function(m){p.length>1?h.setNode(m,f):h.setNode(m)}),this}setNode(d,f){return Object.hasOwn(this._nodes,d)?(arguments.length>1&&(this._nodes[d]=f),this):(this._nodes[d]=arguments.length>1?f:this._defaultNodeLabelFn(d),this._isCompound&&(this._parent[d]=t,this._children[d]={},this._children[t][d]=!0),this._in[d]={},this._preds[d]={},this._out[d]={},this._sucs[d]={},++this._nodeCount,this)}node(d){return this._nodes[d]}hasNode(d){return Object.hasOwn(this._nodes,d)}removeNode(d){var f=this;if(Object.hasOwn(this._nodes,d)){var p=h=>f.removeEdge(f._edgeObjs[h]);delete this._nodes[d],this._isCompound&&(this._removeFromParentsChildList(d),delete this._parent[d],this.children(d).forEach(function(h){f.setParent(h)}),delete this._children[d]),Object.keys(this._in[d]).forEach(p),delete this._in[d],delete this._preds[d],Object.keys(this._out[d]).forEach(p),delete this._out[d],delete this._sucs[d],--this._nodeCount}return this}setParent(d,f){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(f===void 0)f=t;else{f+="";for(var p=f;p!==void 0;p=this.parent(p))if(p===d)throw new Error("Setting "+f+" as parent of "+d+" would create a cycle");this.setNode(f)}return this.setNode(d),this._removeFromParentsChildList(d),this._parent[d]=f,this._children[f][d]=!0,this}_removeFromParentsChildList(d){delete this._children[this._parent[d]][d]}parent(d){if(this._isCompound){var f=this._parent[d];if(f!==t)return f}}children(d=t){if(this._isCompound){var f=this._children[d];if(f)return Object.keys(f)}else{if(d===t)return this.nodes();if(this.hasNode(d))return[]}}predecessors(d){var f=this._preds[d];if(f)return Object.keys(f)}successors(d){var f=this._sucs[d];if(f)return Object.keys(f)}neighbors(d){var f=this.predecessors(d);if(f){const h=new Set(f);for(var p of this.successors(d))h.add(p);return Array.from(h.values())}}isLeaf(d){var f;return this.isDirected()?f=this.successors(d):f=this.neighbors(d),f.length===0}filterNodes(d){var f=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});f.setGraph(this.graph());var p=this;Object.entries(this._nodes).forEach(function([v,y]){d(v)&&f.setNode(v,y)}),Object.values(this._edgeObjs).forEach(function(v){f.hasNode(v.v)&&f.hasNode(v.w)&&f.setEdge(v,p.edge(v))});var h={};function m(v){var y=p.parent(v);return y===void 0||f.hasNode(y)?(h[v]=y,y):y in h?h[y]:m(y)}return this._isCompound&&f.nodes().forEach(v=>f.setParent(v,m(v))),f}setDefaultEdgeLabel(d){return this._defaultEdgeLabelFn=d,typeof d!="function"&&(this._defaultEdgeLabelFn=()=>d),this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(d,f){var p=this,h=arguments;return d.reduce(function(m,v){return h.length>1?p.setEdge(m,v,f):p.setEdge(m,v),v}),this}setEdge(){var d,f,p,h,m=!1,v=arguments[0];typeof v=="object"&&v!==null&&"v"in v?(d=v.v,f=v.w,p=v.name,arguments.length===2&&(h=arguments[1],m=!0)):(d=v,f=arguments[1],p=arguments[3],arguments.length>2&&(h=arguments[2],m=!0)),d=""+d,f=""+f,p!==void 0&&(p=""+p);var y=i(this._isDirected,d,f,p);if(Object.hasOwn(this._edgeLabels,y))return m&&(this._edgeLabels[y]=h),this;if(p!==void 0&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(d),this.setNode(f),this._edgeLabels[y]=m?h:this._defaultEdgeLabelFn(d,f,p);var b=l(this._isDirected,d,f,p);return d=b.v,f=b.w,Object.freeze(b),this._edgeObjs[y]=b,s(this._preds[f],d),s(this._sucs[d],f),this._in[f][y]=b,this._out[d][y]=b,this._edgeCount++,this}edge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return this._edgeLabels[h]}edgeAsObj(){const d=this.edge(...arguments);return typeof d!="object"?{label:d}:d}hasEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return Object.hasOwn(this._edgeLabels,h)}removeEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p),m=this._edgeObjs[h];return m&&(d=m.v,f=m.w,delete this._edgeLabels[h],delete this._edgeObjs[h],a(this._preds[f],d),a(this._sucs[d],f),delete this._in[f][h],delete this._out[d][h],this._edgeCount--),this}inEdges(d,f){var p=this._in[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.v===f):h}}outEdges(d,f){var p=this._out[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.w===f):h}}nodeEdges(d,f){var p=this.inEdges(d,f);if(p)return p.concat(this.outEdges(d,f))}}function s(u,d){u[d]?u[d]++:u[d]=1}function a(u,d){--u[d]||delete u[d]}function i(u,d,f,p){var h=""+d,m=""+f;if(!u&&h>m){var v=h;h=m,m=v}return h+n+m+n+(p===void 0?e:p)}function l(u,d,f,p){var h=""+d,m=""+f;if(!u&&h>m){var v=h;h=m,m=v}var y={v:h,w:m};return p&&(y.name=p),y}function c(u,d){return i(u,d.v,d.w,d.name)}return rte=r,rte}var ste,b9e;function zHn(){return b9e||(b9e=1,ste="2.2.4"),ste}var ate,x9e;function BHn(){return x9e||(x9e=1,ate={Graph:lOe(),version:zHn()}),ate}var ite,w9e;function UHn(){if(w9e)return ite;w9e=1;var e=lOe();ite={write:t,read:s};function t(a){var i={options:{directed:a.isDirected(),multigraph:a.isMultigraph(),compound:a.isCompound()},nodes:n(a),edges:r(a)};return a.graph()!==void 0&&(i.value=structuredClone(a.graph())),i}function n(a){return a.nodes().map(function(i){var l=a.node(i),c=a.parent(i),u={v:i};return l!==void 0&&(u.value=l),c!==void 0&&(u.parent=c),u})}function r(a){return a.edges().map(function(i){var l=a.edge(i),c={v:i.v,w:i.w};return i.name!==void 0&&(c.name=i.name),l!==void 0&&(c.value=l),c})}function s(a){var i=new e(a.options).setGraph(a.value);return a.nodes.forEach(function(l){i.setNode(l.v,l.value),l.parent&&i.setParent(l.v,l.parent)}),a.edges.forEach(function(l){i.setEdge({v:l.v,w:l.w,name:l.name},l.value)}),i}return ite}var ote,S9e;function qHn(){if(S9e)return ote;S9e=1,ote=e;function e(t){var n={},r=[],s;function a(i){Object.hasOwn(n,i)||(n[i]=!0,s.push(i),t.successors(i).forEach(a),t.predecessors(i).forEach(a))}return t.nodes().forEach(function(i){s=[],a(i),s.length&&r.push(s)}),r}return ote}var lte,k9e;function Dkt(){if(k9e)return lte;k9e=1;class e{_arr=[];_keyIndices={};size(){return this._arr.length}keys(){return this._arr.map(function(n){return n.key})}has(n){return Object.hasOwn(this._keyIndices,n)}priority(n){var r=this._keyIndices[n];if(r!==void 0)return this._arr[r].priority}min(){if(this.size()===0)throw new Error("Queue underflow");return this._arr[0].key}add(n,r){var s=this._keyIndices;if(n=String(n),!Object.hasOwn(s,n)){var a=this._arr,i=a.length;return s[n]=i,a.push({key:n,priority:r}),this._decrease(i),!0}return!1}removeMin(){this._swap(0,this._arr.length-1);var n=this._arr.pop();return delete this._keyIndices[n.key],this._heapify(0),n.key}decrease(n,r){var s=this._keyIndices[n];if(r>this._arr[s].priority)throw new Error("New priority is greater than current priority. Key: "+n+" Old: "+this._arr[s].priority+" New: "+r);this._arr[s].priority=r,this._decrease(s)}_heapify(n){var r=this._arr,s=2*n,a=s+1,i=n;s<r.length&&(i=r[s].priority<r[i].priority?s:i,a<r.length&&(i=r[a].priority<r[i].priority?a:i),i!==n&&(this._swap(n,i),this._heapify(i)))}_decrease(n){for(var r=this._arr,s=r[n].priority,a;n!==0&&(a=n>>1,!(r[a].priority<s));)this._swap(n,a),n=a}_swap(n,r){var s=this._arr,a=this._keyIndices,i=s[n],l=s[r];s[n]=l,s[r]=i,a[l.key]=n,a[i.key]=r}}return lte=e,lte}var cte,O9e;function Lkt(){if(O9e)return cte;O9e=1;var e=Dkt();cte=n;var t=()=>1;function n(s,a,i,l){return r(s,String(a),i||t,l||function(c){return s.outEdges(c)})}function r(s,a,i,l){var c={},u=new e,d,f,p=function(h){var m=h.v!==d?h.v:h.w,v=c[m],y=i(h),b=f.distance+y;if(y<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+h+" Weight: "+y);b<v.distance&&(v.distance=b,v.predecessor=d,u.decrease(m,b))};for(s.nodes().forEach(function(h){var m=h===a?0:Number.POSITIVE_INFINITY;c[h]={distance:m},u.add(h,m)});u.size()>0&&(d=u.removeMin(),f=c[d],f.distance!==Number.POSITIVE_INFINITY);)l(d).forEach(p);return c}return cte}var ute,_9e;function VHn(){if(_9e)return ute;_9e=1;var e=Lkt();ute=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return ute}var dte,C9e;function Fkt(){if(C9e)return dte;C9e=1,dte=e;function e(t){var n=0,r=[],s={},a=[];function i(l){var c=s[l]={onStack:!0,lowlink:n,index:n++};if(r.push(l),t.successors(l).forEach(function(f){Object.hasOwn(s,f)?s[f].onStack&&(c.lowlink=Math.min(c.lowlink,s[f].index)):(i(f),c.lowlink=Math.min(c.lowlink,s[f].lowlink))}),c.lowlink===c.index){var u=[],d;do d=r.pop(),s[d].onStack=!1,u.push(d);while(l!==d);a.push(u)}}return t.nodes().forEach(function(l){Object.hasOwn(s,l)||i(l)}),a}return dte}var fte,E9e;function HHn(){if(E9e)return fte;E9e=1;var e=Fkt();fte=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return fte}var pte,T9e;function WHn(){if(T9e)return pte;T9e=1,pte=t;var e=()=>1;function t(r,s,a){return n(r,s||e,a||function(i){return r.outEdges(i)})}function n(r,s,a){var i={},l=r.nodes();return l.forEach(function(c){i[c]={},i[c][c]={distance:0},l.forEach(function(u){c!==u&&(i[c][u]={distance:Number.POSITIVE_INFINITY})}),a(c).forEach(function(u){var d=u.v===c?u.w:u.v,f=s(u);i[c][d]={distance:f,predecessor:c}})}),l.forEach(function(c){var u=i[c];l.forEach(function(d){var f=i[d];l.forEach(function(p){var h=f[c],m=u[p],v=f[p],y=h.distance+m.distance;y<v.distance&&(v.distance=y,v.predecessor=m.predecessor)})})}),i}return pte}var hte,j9e;function zkt(){if(j9e)return hte;j9e=1;function e(n){var r={},s={},a=[];function i(l){if(Object.hasOwn(s,l))throw new t;Object.hasOwn(r,l)||(s[l]=!0,r[l]=!0,n.predecessors(l).forEach(i),delete s[l],a.push(l))}if(n.sinks().forEach(i),Object.keys(r).length!==n.nodeCount())throw new t;return a}class t extends Error{constructor(){super(...arguments)}}return hte=e,e.CycleException=t,hte}var mte,N9e;function ZHn(){if(N9e)return mte;N9e=1;var e=zkt();mte=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return mte}var gte,I9e;function Bkt(){if(I9e)return gte;I9e=1,gte=e;function e(s,a,i){Array.isArray(a)||(a=[a]);var l=s.isDirected()?f=>s.successors(f):f=>s.neighbors(f),c=i==="post"?t:n,u=[],d={};return a.forEach(f=>{if(!s.hasNode(f))throw new Error("Graph does not have node: "+f);c(f,l,d,u)}),u}function t(s,a,i,l){for(var c=[[s,!1]];c.length>0;){var u=c.pop();u[1]?l.push(u[0]):Object.hasOwn(i,u[0])||(i[u[0]]=!0,c.push([u[0],!0]),r(a(u[0]),d=>c.push([d,!1])))}}function n(s,a,i,l){for(var c=[s];c.length>0;){var u=c.pop();Object.hasOwn(i,u)||(i[u]=!0,l.push(u),r(a(u),d=>c.push(d)))}}function r(s,a){for(var i=s.length;i--;)a(s[i],i,s);return s}return gte}var vte,A9e;function GHn(){if(A9e)return vte;A9e=1;var e=Bkt();vte=t;function t(n,r){return e(n,r,"post")}return vte}var yte,R9e;function QHn(){if(R9e)return yte;R9e=1;var e=Bkt();yte=t;function t(n,r){return e(n,r,"pre")}return yte}var bte,P9e;function YHn(){if(P9e)return bte;P9e=1;var e=lOe(),t=Dkt();bte=n;function n(r,s){var a=new e,i={},l=new t,c;function u(f){var p=f.v===c?f.w:f.v,h=l.priority(p);if(h!==void 0){var m=s(f);m<h&&(i[p]=c,l.decrease(p,m))}}if(r.nodeCount()===0)return a;r.nodes().forEach(function(f){l.add(f,Number.POSITIVE_INFINITY),a.setNode(f)}),l.decrease(r.nodes()[0],0);for(var d=!1;l.size()>0;){if(c=l.removeMin(),Object.hasOwn(i,c))a.setEdge(c,i[c]);else{if(d)throw new Error("Input graph is not connected: "+r);d=!0}r.nodeEdges(c).forEach(u)}return a}return bte}var xte,$9e;function KHn(){return $9e||($9e=1,xte={components:qHn(),dijkstra:Lkt(),dijkstraAll:VHn(),findCycles:HHn(),floydWarshall:WHn(),isAcyclic:ZHn(),postorder:GHn(),preorder:QHn(),prim:YHn(),tarjan:Fkt(),topsort:zkt()}),xte}var wte,M9e;function Hg(){if(M9e)return wte;M9e=1;var e=BHn();return wte={Graph:e.Graph,json:UHn(),alg:KHn(),version:e.version},wte}var Ste,D9e;function XHn(){if(D9e)return Ste;D9e=1;class e{constructor(){let s={};s._next=s._prev=s,this._sentinel=s}dequeue(){let s=this._sentinel,a=s._prev;if(a!==s)return t(a),a}enqueue(s){let a=this._sentinel;s._prev&&s._next&&t(s),s._next=a._next,a._next._prev=s,a._next=s,s._prev=a}toString(){let s=[],a=this._sentinel,i=a._prev;for(;i!==a;)s.push(JSON.stringify(i,n)),i=i._prev;return"["+s.join(", ")+"]"}}function t(r){r._prev._next=r._next,r._next._prev=r._prev,delete r._next,delete r._prev}function n(r,s){if(r!=="_next"&&r!=="_prev")return s}return Ste=e,Ste}var kte,L9e;function JHn(){if(L9e)return kte;L9e=1;let e=Hg().Graph,t=XHn();kte=r;let n=()=>1;function r(u,d){if(u.nodeCount()<=1)return[];let f=i(u,d||n);return s(f.graph,f.buckets,f.zeroIdx).flatMap(h=>u.outEdges(h.v,h.w))}function s(u,d,f){let p=[],h=d[d.length-1],m=d[0],v;for(;u.nodeCount();){for(;v=m.dequeue();)a(u,d,f,v);for(;v=h.dequeue();)a(u,d,f,v);if(u.nodeCount()){for(let y=d.length-2;y>0;--y)if(v=d[y].dequeue(),v){p=p.concat(a(u,d,f,v,!0));break}}}return p}function a(u,d,f,p,h){let m=h?[]:void 0;return u.inEdges(p.v).forEach(v=>{let y=u.edge(v),b=u.node(v.v);h&&m.push({v:v.v,w:v.w}),b.out-=y,l(d,f,b)}),u.outEdges(p.v).forEach(v=>{let y=u.edge(v),b=v.w,x=u.node(b);x.in-=y,l(d,f,x)}),u.removeNode(p.v),m}function i(u,d){let f=new e,p=0,h=0;u.nodes().forEach(y=>{f.setNode(y,{v:y,in:0,out:0})}),u.edges().forEach(y=>{let b=f.edge(y.v,y.w)||0,x=d(y),S=b+x;f.setEdge(y.v,y.w,S),h=Math.max(h,f.node(y.v).out+=x),p=Math.max(p,f.node(y.w).in+=x)});let m=c(h+p+3).map(()=>new t),v=p+1;return f.nodes().forEach(y=>{l(m,v,f.node(y))}),{graph:f,buckets:m,zeroIdx:v}}function l(u,d,f){f.out?f.in?u[f.out-f.in+d].enqueue(f):u[u.length-1].enqueue(f):u[0].enqueue(f)}function c(u){const d=[];for(let f=0;f<u;f++)d.push(f);return d}return kte}var Ote,F9e;function Al(){if(F9e)return Ote;F9e=1;let e=Hg().Graph;Ote={addBorderNode:d,addDummyNode:t,applyWithChunking:h,asNonCompoundGraph:r,buildLayerMatrix:l,intersectRect:i,mapValues:C,maxRank:m,normalizeRanks:c,notime:b,partition:v,pick:_,predecessorWeights:a,range:k,removeEmptyRanks:u,simplify:n,successorWeights:s,time:y,uniqueId:S,zipObject:T};function t(E,N,I,A){for(var R=A;E.hasNode(R);)R=S(A);return I.dummy=N,E.setNode(R,I),R}function n(E){let N=new e().setGraph(E.graph());return E.nodes().forEach(I=>N.setNode(I,E.node(I))),E.edges().forEach(I=>{let A=N.edge(I.v,I.w)||{weight:0,minlen:1},R=E.edge(I);N.setEdge(I.v,I.w,{weight:A.weight+R.weight,minlen:Math.max(A.minlen,R.minlen)})}),N}function r(E){let N=new e({multigraph:E.isMultigraph()}).setGraph(E.graph());return E.nodes().forEach(I=>{E.children(I).length||N.setNode(I,E.node(I))}),E.edges().forEach(I=>{N.setEdge(I,E.edge(I))}),N}function s(E){let N=E.nodes().map(I=>{let A={};return E.outEdges(I).forEach(R=>{A[R.w]=(A[R.w]||0)+E.edge(R).weight}),A});return T(E.nodes(),N)}function a(E){let N=E.nodes().map(I=>{let A={};return E.inEdges(I).forEach(R=>{A[R.v]=(A[R.v]||0)+E.edge(R).weight}),A});return T(E.nodes(),N)}function i(E,N){let I=E.x,A=E.y,R=N.x-I,L=N.y-A,D=E.width/2,F=E.height/2;if(!R&&!L)throw new Error("Not possible to find intersection inside of the rectangle");let H,B;return Math.abs(L)*D>Math.abs(R)*F?(L<0&&(F=-F),H=F*R/L,B=F):(R<0&&(D=-D),H=D,B=D*L/R),{x:I+H,y:A+B}}function l(E){let N=k(m(E)+1).map(()=>[]);return E.nodes().forEach(I=>{let A=E.node(I),R=A.rank;R!==void 0&&(N[R][A.order]=I)}),N}function c(E){let N=E.nodes().map(A=>{let R=E.node(A).rank;return R===void 0?Number.MAX_VALUE:R}),I=h(Math.min,N);E.nodes().forEach(A=>{let R=E.node(A);Object.hasOwn(R,"rank")&&(R.rank-=I)})}function u(E){let N=E.nodes().map(D=>E.node(D).rank),I=h(Math.min,N),A=[];E.nodes().forEach(D=>{let F=E.node(D).rank-I;A[F]||(A[F]=[]),A[F].push(D)});let R=0,L=E.graph().nodeRankFactor;Array.from(A).forEach((D,F)=>{D===void 0&&F%L!==0?--R:D!==void 0&&R&&D.forEach(H=>E.node(H).rank+=R)})}function d(E,N,I,A){let R={width:0,height:0};return arguments.length>=4&&(R.rank=I,R.order=A),t(E,"border",R,N)}function f(E,N=p){const I=[];for(let A=0;A<E.length;A+=N){const R=E.slice(A,A+N);I.push(R)}return I}const p=65535;function h(E,N){if(N.length>p){const I=f(N);return E.apply(null,I.map(A=>E.apply(null,A)))}else return E.apply(null,N)}function m(E){const I=E.nodes().map(A=>{let R=E.node(A).rank;return R===void 0?Number.MIN_VALUE:R});return h(Math.max,I)}function v(E,N){let I={lhs:[],rhs:[]};return E.forEach(A=>{N(A)?I.lhs.push(A):I.rhs.push(A)}),I}function y(E,N){let I=Date.now();try{return N()}finally{console.log(E+" time: "+(Date.now()-I)+"ms")}}function b(E,N){return N()}let x=0;function S(E){var N=++x;return E+(""+N)}function k(E,N,I=1){N==null&&(N=E,E=0);let A=L=>L<N;I<0&&(A=L=>N<L);const R=[];for(let L=E;A(L);L+=I)R.push(L);return R}function _(E,N){const I={};for(const A of N)E[A]!==void 0&&(I[A]=E[A]);return I}function C(E,N){let I=N;return typeof N=="string"&&(I=A=>A[N]),Object.entries(E).reduce((A,[R,L])=>(A[R]=I(L,R),A),{})}function T(E,N){return E.reduce((I,A,R)=>(I[A]=N[R],I),{})}return Ote}var _te,z9e;function eWn(){if(z9e)return _te;z9e=1;let e=JHn(),t=Al().uniqueId;_te={run:n,undo:s};function n(a){(a.graph().acyclicer==="greedy"?e(a,l(a)):r(a)).forEach(c=>{let u=a.edge(c);a.removeEdge(c),u.forwardName=c.name,u.reversed=!0,a.setEdge(c.w,c.v,u,t("rev"))});function l(c){return u=>c.edge(u).weight}}function r(a){let i=[],l={},c={};function u(d){Object.hasOwn(c,d)||(c[d]=!0,l[d]=!0,a.outEdges(d).forEach(f=>{Object.hasOwn(l,f.w)?i.push(f):u(f.w)}),delete l[d])}return a.nodes().forEach(u),i}function s(a){a.edges().forEach(i=>{let l=a.edge(i);if(l.reversed){a.removeEdge(i);let c=l.forwardName;delete l.reversed,delete l.forwardName,a.setEdge(i.w,i.v,l,c)}})}return _te}var Cte,B9e;function tWn(){if(B9e)return Cte;B9e=1;let e=Al();Cte={run:t,undo:r};function t(s){s.graph().dummyChains=[],s.edges().forEach(a=>n(s,a))}function n(s,a){let i=a.v,l=s.node(i).rank,c=a.w,u=s.node(c).rank,d=a.name,f=s.edge(a),p=f.labelRank;if(u===l+1)return;s.removeEdge(a);let h,m,v;for(v=0,++l;l<u;++v,++l)f.points=[],m={width:0,height:0,edgeLabel:f,edgeObj:a,rank:l},h=e.addDummyNode(s,"edge",m,"_d"),l===p&&(m.width=f.width,m.height=f.height,m.dummy="edge-label",m.labelpos=f.labelpos),s.setEdge(i,h,{weight:f.weight},d),v===0&&s.graph().dummyChains.push(h),i=h;s.setEdge(i,c,{weight:f.weight},d)}function r(s){s.graph().dummyChains.forEach(a=>{let i=s.node(a),l=i.edgeLabel,c;for(s.setEdge(i.edgeObj,l);i.dummy;)c=s.successors(a)[0],s.removeNode(a),l.points.push({x:i.x,y:i.y}),i.dummy==="edge-label"&&(l.x=i.x,l.y=i.y,l.width=i.width,l.height=i.height),a=c,i=s.node(a)})}return Cte}var Ete,U9e;function ZB(){if(U9e)return Ete;U9e=1;const{applyWithChunking:e}=Al();Ete={longestPath:t,slack:n};function t(r){var s={};function a(i){var l=r.node(i);if(Object.hasOwn(s,i))return l.rank;s[i]=!0;let c=r.outEdges(i).map(d=>d==null?Number.POSITIVE_INFINITY:a(d.w)-r.edge(d).minlen);var u=e(Math.min,c);return u===Number.POSITIVE_INFINITY&&(u=0),l.rank=u}r.sources().forEach(a)}function n(r,s){return r.node(s.w).rank-r.node(s.v).rank-r.edge(s).minlen}return Ete}var Tte,q9e;function Ukt(){if(q9e)return Tte;q9e=1;var e=Hg().Graph,t=ZB().slack;Tte=n;function n(i){var l=new e({directed:!1}),c=i.nodes()[0],u=i.nodeCount();l.setNode(c,{});for(var d,f;r(l,i)<u;)d=s(l,i),f=l.hasNode(d.v)?t(i,d):-t(i,d),a(l,i,f);return l}function r(i,l){function c(u){l.nodeEdges(u).forEach(d=>{var f=d.v,p=u===f?d.w:f;!i.hasNode(p)&&!t(l,d)&&(i.setNode(p,{}),i.setEdge(u,p,{}),c(p))})}return i.nodes().forEach(c),i.nodeCount()}function s(i,l){return l.edges().reduce((u,d)=>{let f=Number.POSITIVE_INFINITY;return i.hasNode(d.v)!==i.hasNode(d.w)&&(f=t(l,d)),f<u[0]?[f,d]:u},[Number.POSITIVE_INFINITY,null])[1]}function a(i,l,c){i.nodes().forEach(u=>l.node(u).rank+=c)}return Tte}var jte,V9e;function nWn(){if(V9e)return jte;V9e=1;var e=Ukt(),t=ZB().slack,n=ZB().longestPath,r=Hg().alg.preorder,s=Hg().alg.postorder,a=Al().simplify;jte=i,i.initLowLimValues=d,i.initCutValues=l,i.calcCutValue=u,i.leaveEdge=p,i.enterEdge=h,i.exchangeEdges=m;function i(x){x=a(x),n(x);var S=e(x);d(S),l(S,x);for(var k,_;k=p(S);)_=h(S,x,k),m(S,x,k,_)}function l(x,S){var k=s(x,x.nodes());k=k.slice(0,k.length-1),k.forEach(_=>c(x,S,_))}function c(x,S,k){var _=x.node(k),C=_.parent;x.edge(k,C).cutvalue=u(x,S,k)}function u(x,S,k){var _=x.node(k),C=_.parent,T=!0,E=S.edge(k,C),N=0;return E||(T=!1,E=S.edge(C,k)),N=E.weight,S.nodeEdges(k).forEach(I=>{var A=I.v===k,R=A?I.w:I.v;if(R!==C){var L=A===T,D=S.edge(I).weight;if(N+=L?D:-D,y(x,k,R)){var F=x.edge(k,R).cutvalue;N+=L?-F:F}}}),N}function d(x,S){arguments.length<2&&(S=x.nodes()[0]),f(x,{},1,S)}function f(x,S,k,_,C){var T=k,E=x.node(_);return S[_]=!0,x.neighbors(_).forEach(N=>{Object.hasOwn(S,N)||(k=f(x,S,k,N,_))}),E.low=T,E.lim=k++,C?E.parent=C:delete E.parent,k}function p(x){return x.edges().find(S=>x.edge(S).cutvalue<0)}function h(x,S,k){var _=k.v,C=k.w;S.hasEdge(_,C)||(_=k.w,C=k.v);var T=x.node(_),E=x.node(C),N=T,I=!1;T.lim>E.lim&&(N=E,I=!0);var A=S.edges().filter(R=>I===b(x,x.node(R.v),N)&&I!==b(x,x.node(R.w),N));return A.reduce((R,L)=>t(S,L)<t(S,R)?L:R)}function m(x,S,k,_){var C=k.v,T=k.w;x.removeEdge(C,T),x.setEdge(_.v,_.w,{}),d(x),l(x,S),v(x,S)}function v(x,S){var k=x.nodes().find(C=>!S.node(C).parent),_=r(x,k);_=_.slice(1),_.forEach(C=>{var T=x.node(C).parent,E=S.edge(C,T),N=!1;E||(E=S.edge(T,C),N=!0),S.node(C).rank=S.node(T).rank+(N?E.minlen:-E.minlen)})}function y(x,S,k){return x.hasEdge(S,k)}function b(x,S,k){return k.low<=S.lim&&S.lim<=k.lim}return jte}var Nte,H9e;function rWn(){if(H9e)return Nte;H9e=1;var e=ZB(),t=e.longestPath,n=Ukt(),r=nWn();Nte=s;function s(c){var u=c.graph().ranker;if(u instanceof Function)return u(c);switch(c.graph().ranker){case"network-simplex":l(c);break;case"tight-tree":i(c);break;case"longest-path":a(c);break;case"none":break;default:l(c)}}var a=t;function i(c){t(c),n(c)}function l(c){r(c)}return Nte}var Ite,W9e;function sWn(){if(W9e)return Ite;W9e=1,Ite=e;function e(r){let s=n(r);r.graph().dummyChains.forEach(a=>{let i=r.node(a),l=i.edgeObj,c=t(r,s,l.v,l.w),u=c.path,d=c.lca,f=0,p=u[f],h=!0;for(;a!==l.w;){if(i=r.node(a),h){for(;(p=u[f])!==d&&r.node(p).maxRank<i.rank;)f++;p===d&&(h=!1)}if(!h){for(;f<u.length-1&&r.node(p=u[f+1]).minRank<=i.rank;)f++;p=u[f]}r.setParent(a,p),a=r.successors(a)[0]}})}function t(r,s,a,i){let l=[],c=[],u=Math.min(s[a].low,s[i].low),d=Math.max(s[a].lim,s[i].lim),f,p;f=a;do f=r.parent(f),l.push(f);while(f&&(s[f].low>u||d>s[f].lim));for(p=f,f=i;(f=r.parent(f))!==p;)c.push(f);return{path:l.concat(c.reverse()),lca:p}}function n(r){let s={},a=0;function i(l){let c=a;r.children(l).forEach(i),s[l]={low:c,lim:a++}}return r.children().forEach(i),s}return Ite}var Ate,Z9e;function aWn(){if(Z9e)return Ate;Z9e=1;let e=Al();Ate={run:t,cleanup:a};function t(i){let l=e.addDummyNode(i,"root",{},"_root"),c=r(i),u=Object.values(c),d=e.applyWithChunking(Math.max,u)-1,f=2*d+1;i.graph().nestingRoot=l,i.edges().forEach(h=>i.edge(h).minlen*=f);let p=s(i)+1;i.children().forEach(h=>n(i,l,f,p,d,c,h)),i.graph().nodeRankFactor=f}function n(i,l,c,u,d,f,p){let h=i.children(p);if(!h.length){p!==l&&i.setEdge(l,p,{weight:0,minlen:c});return}let m=e.addBorderNode(i,"_bt"),v=e.addBorderNode(i,"_bb"),y=i.node(p);i.setParent(m,p),y.borderTop=m,i.setParent(v,p),y.borderBottom=v,h.forEach(b=>{n(i,l,c,u,d,f,b);let x=i.node(b),S=x.borderTop?x.borderTop:b,k=x.borderBottom?x.borderBottom:b,_=x.borderTop?u:2*u,C=S!==k?1:d-f[p]+1;i.setEdge(m,S,{weight:_,minlen:C,nestingEdge:!0}),i.setEdge(k,v,{weight:_,minlen:C,nestingEdge:!0})}),i.parent(p)||i.setEdge(l,m,{weight:0,minlen:d+f[p]})}function r(i){var l={};function c(u,d){var f=i.children(u);f&&f.length&&f.forEach(p=>c(p,d+1)),l[u]=d}return i.children().forEach(u=>c(u,1)),l}function s(i){return i.edges().reduce((l,c)=>l+i.edge(c).weight,0)}function a(i){var l=i.graph();i.removeNode(l.nestingRoot),delete l.nestingRoot,i.edges().forEach(c=>{var u=i.edge(c);u.nestingEdge&&i.removeEdge(c)})}return Ate}var Rte,G9e;function iWn(){if(G9e)return Rte;G9e=1;let e=Al();Rte=t;function t(r){function s(a){let i=r.children(a),l=r.node(a);if(i.length&&i.forEach(s),Object.hasOwn(l,"minRank")){l.borderLeft=[],l.borderRight=[];for(let c=l.minRank,u=l.maxRank+1;c<u;++c)n(r,"borderLeft","_bl",a,l,c),n(r,"borderRight","_br",a,l,c)}}r.children().forEach(s)}function n(r,s,a,i,l,c){let u={width:0,height:0,rank:c,borderType:s},d=l[s][c-1],f=e.addDummyNode(r,"border",u,a);l[s][c]=f,r.setParent(f,i),d&&r.setEdge(d,f,{weight:1})}return Rte}var Pte,Q9e;function oWn(){if(Q9e)return Pte;Q9e=1,Pte={adjust:e,undo:t};function e(c){let u=c.graph().rankdir.toLowerCase();(u==="lr"||u==="rl")&&n(c)}function t(c){let u=c.graph().rankdir.toLowerCase();(u==="bt"||u==="rl")&&s(c),(u==="lr"||u==="rl")&&(i(c),n(c))}function n(c){c.nodes().forEach(u=>r(c.node(u))),c.edges().forEach(u=>r(c.edge(u)))}function r(c){let u=c.width;c.width=c.height,c.height=u}function s(c){c.nodes().forEach(u=>a(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(a),Object.hasOwn(d,"y")&&a(d)})}function a(c){c.y=-c.y}function i(c){c.nodes().forEach(u=>l(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(l),Object.hasOwn(d,"x")&&l(d)})}function l(c){let u=c.x;c.x=c.y,c.y=u}return Pte}var $te,Y9e;function lWn(){if(Y9e)return $te;Y9e=1;let e=Al();$te=t;function t(n){let r={},s=n.nodes().filter(d=>!n.children(d).length),a=s.map(d=>n.node(d).rank),i=e.applyWithChunking(Math.max,a),l=e.range(i+1).map(()=>[]);function c(d){if(r[d])return;r[d]=!0;let f=n.node(d);l[f.rank].push(d),n.successors(d).forEach(c)}return s.sort((d,f)=>n.node(d).rank-n.node(f).rank).forEach(c),l}return $te}var Mte,K9e;function cWn(){if(K9e)return Mte;K9e=1;let e=Al().zipObject;Mte=t;function t(r,s){let a=0;for(let i=1;i<s.length;++i)a+=n(r,s[i-1],s[i]);return a}function n(r,s,a){let i=e(a,a.map((p,h)=>h)),l=s.flatMap(p=>r.outEdges(p).map(h=>({pos:i[h.w],weight:r.edge(h).weight})).sort((h,m)=>h.pos-m.pos)),c=1;for(;c<a.length;)c<<=1;let u=2*c-1;c-=1;let d=new Array(u).fill(0),f=0;return l.forEach(p=>{let h=p.pos+c;d[h]+=p.weight;let m=0;for(;h>0;)h%2&&(m+=d[h+1]),h=h-1>>1,d[h]+=p.weight;f+=p.weight*m}),f}return Mte}var Dte,X9e;function uWn(){if(X9e)return Dte;X9e=1,Dte=e;function e(t,n=[]){return n.map(r=>{let s=t.inEdges(r);if(s.length){let a=s.reduce((i,l)=>{let c=t.edge(l),u=t.node(l.v);return{sum:i.sum+c.weight*u.order,weight:i.weight+c.weight}},{sum:0,weight:0});return{v:r,barycenter:a.sum/a.weight,weight:a.weight}}else return{v:r}})}return Dte}var Lte,J9e;function dWn(){if(J9e)return Lte;J9e=1;let e=Al();Lte=t;function t(s,a){let i={};s.forEach((c,u)=>{let d=i[c.v]={indegree:0,in:[],out:[],vs:[c.v],i:u};c.barycenter!==void 0&&(d.barycenter=c.barycenter,d.weight=c.weight)}),a.edges().forEach(c=>{let u=i[c.v],d=i[c.w];u!==void 0&&d!==void 0&&(d.indegree++,u.out.push(i[c.w]))});let l=Object.values(i).filter(c=>!c.indegree);return n(l)}function n(s){let a=[];function i(c){return u=>{u.merged||(u.barycenter===void 0||c.barycenter===void 0||u.barycenter>=c.barycenter)&&r(c,u)}}function l(c){return u=>{u.in.push(c),--u.indegree===0&&s.push(u)}}for(;s.length;){let c=s.pop();a.push(c),c.in.reverse().forEach(i(c)),c.out.forEach(l(c))}return a.filter(c=>!c.merged).map(c=>e.pick(c,["vs","i","barycenter","weight"]))}function r(s,a){let i=0,l=0;s.weight&&(i+=s.barycenter*s.weight,l+=s.weight),a.weight&&(i+=a.barycenter*a.weight,l+=a.weight),s.vs=a.vs.concat(s.vs),s.barycenter=i/l,s.weight=l,s.i=Math.min(a.i,s.i),a.merged=!0}return Lte}var Fte,e7e;function fWn(){if(e7e)return Fte;e7e=1;let e=Al();Fte=t;function t(s,a){let i=e.partition(s,m=>Object.hasOwn(m,"barycenter")),l=i.lhs,c=i.rhs.sort((m,v)=>v.i-m.i),u=[],d=0,f=0,p=0;l.sort(r(!!a)),p=n(u,c,p),l.forEach(m=>{p+=m.vs.length,u.push(m.vs),d+=m.barycenter*m.weight,f+=m.weight,p=n(u,c,p)});let h={vs:u.flat(!0)};return f&&(h.barycenter=d/f,h.weight=f),h}function n(s,a,i){let l;for(;a.length&&(l=a[a.length-1]).i<=i;)a.pop(),s.push(l.vs),i++;return i}function r(s){return(a,i)=>a.barycenter<i.barycenter?-1:a.barycenter>i.barycenter?1:s?i.i-a.i:a.i-i.i}return Fte}var zte,t7e;function pWn(){if(t7e)return zte;t7e=1;let e=uWn(),t=dWn(),n=fWn();zte=r;function r(i,l,c,u){let d=i.children(l),f=i.node(l),p=f?f.borderLeft:void 0,h=f?f.borderRight:void 0,m={};p&&(d=d.filter(x=>x!==p&&x!==h));let v=e(i,d);v.forEach(x=>{if(i.children(x.v).length){let S=r(i,x.v,c,u);m[x.v]=S,Object.hasOwn(S,"barycenter")&&a(x,S)}});let y=t(v,c);s(y,m);let b=n(y,u);if(p&&(b.vs=[p,b.vs,h].flat(!0),i.predecessors(p).length)){let x=i.node(i.predecessors(p)[0]),S=i.node(i.predecessors(h)[0]);Object.hasOwn(b,"barycenter")||(b.barycenter=0,b.weight=0),b.barycenter=(b.barycenter*b.weight+x.order+S.order)/(b.weight+2),b.weight+=2}return b}function s(i,l){i.forEach(c=>{c.vs=c.vs.flatMap(u=>l[u]?l[u].vs:u)})}function a(i,l){i.barycenter!==void 0?(i.barycenter=(i.barycenter*i.weight+l.barycenter*l.weight)/(i.weight+l.weight),i.weight+=l.weight):(i.barycenter=l.barycenter,i.weight=l.weight)}return zte}var Bte,n7e;function hWn(){if(n7e)return Bte;n7e=1;let e=Hg().Graph,t=Al();Bte=n;function n(s,a,i,l){l||(l=s.nodes());let c=r(s),u=new e({compound:!0}).setGraph({root:c}).setDefaultNodeLabel(d=>s.node(d));return l.forEach(d=>{let f=s.node(d),p=s.parent(d);(f.rank===a||f.minRank<=a&&a<=f.maxRank)&&(u.setNode(d),u.setParent(d,p||c),s[i](d).forEach(h=>{let m=h.v===d?h.w:h.v,v=u.edge(m,d),y=v!==void 0?v.weight:0;u.setEdge(m,d,{weight:s.edge(h).weight+y})}),Object.hasOwn(f,"minRank")&&u.setNode(d,{borderLeft:f.borderLeft[a],borderRight:f.borderRight[a]}))}),u}function r(s){for(var a;s.hasNode(a=t.uniqueId("_root")););return a}return Bte}var Ute,r7e;function mWn(){if(r7e)return Ute;r7e=1,Ute=e;function e(t,n,r){let s={},a;r.forEach(i=>{let l=t.parent(i),c,u;for(;l;){if(c=t.parent(l),c?(u=s[c],s[c]=l):(u=a,a=l),u&&u!==l){n.setEdge(u,l);return}l=c}})}return Ute}var qte,s7e;function gWn(){if(s7e)return qte;s7e=1;let e=lWn(),t=cWn(),n=pWn(),r=hWn(),s=mWn(),a=Hg().Graph,i=Al();qte=l;function l(f,p){if(p&&typeof p.customOrder=="function"){p.customOrder(f,l);return}let h=i.maxRank(f),m=c(f,i.range(1,h+1),"inEdges"),v=c(f,i.range(h-1,-1,-1),"outEdges"),y=e(f);if(d(f,y),p&&p.disableOptimalOrderHeuristic)return;let b=Number.POSITIVE_INFINITY,x;for(let S=0,k=0;k<4;++S,++k){u(S%2?m:v,S%4>=2),y=i.buildLayerMatrix(f);let _=t(f,y);_<b&&(k=0,x=Object.assign({},y),b=_)}d(f,x)}function c(f,p,h){const m=new Map,v=(y,b)=>{m.has(y)||m.set(y,[]),m.get(y).push(b)};for(const y of f.nodes()){const b=f.node(y);if(typeof b.rank=="number"&&v(b.rank,y),typeof b.minRank=="number"&&typeof b.maxRank=="number")for(let x=b.minRank;x<=b.maxRank;x++)x!==b.rank&&v(x,y)}return p.map(function(y){return r(f,y,h,m.get(y)||[])})}function u(f,p){let h=new a;f.forEach(function(m){let v=m.graph().root,y=n(m,v,h,p);y.vs.forEach((b,x)=>m.node(b).order=x),s(m,h,y.vs)})}function d(f,p){Object.values(p).forEach(h=>h.forEach((m,v)=>f.node(m).order=v))}return qte}var Vte,a7e;function vWn(){if(a7e)return Vte;a7e=1;let e=Hg().Graph,t=Al();Vte={positionX:h,findType1Conflicts:n,findType2Conflicts:r,addConflict:a,hasConflict:i,verticalAlignment:l,horizontalCompaction:c,alignCoordinates:f,findSmallestWidthAlignment:d,balance:p};function n(y,b){let x={};function S(k,_){let C=0,T=0,E=k.length,N=_[_.length-1];return _.forEach((I,A)=>{let R=s(y,I),L=R?y.node(R).order:E;(R||I===N)&&(_.slice(T,A+1).forEach(D=>{y.predecessors(D).forEach(F=>{let H=y.node(F),B=H.order;(B<C||L<B)&&!(H.dummy&&y.node(D).dummy)&&a(x,F,D)})}),T=A+1,C=L)}),_}return b.length&&b.reduce(S),x}function r(y,b){let x={};function S(_,C,T,E,N){let I;t.range(C,T).forEach(A=>{I=_[A],y.node(I).dummy&&y.predecessors(I).forEach(R=>{let L=y.node(R);L.dummy&&(L.order<E||L.order>N)&&a(x,R,I)})})}function k(_,C){let T=-1,E,N=0;return C.forEach((I,A)=>{if(y.node(I).dummy==="border"){let R=y.predecessors(I);R.length&&(E=y.node(R[0]).order,S(C,N,A,T,E),N=A,T=E)}S(C,N,C.length,E,_.length)}),C}return b.length&&b.reduce(k),x}function s(y,b){if(y.node(b).dummy)return y.predecessors(b).find(x=>y.node(x).dummy)}function a(y,b,x){if(b>x){let k=b;b=x,x=k}let S=y[b];S||(y[b]=S={}),S[x]=!0}function i(y,b,x){if(b>x){let S=b;b=x,x=S}return!!y[b]&&Object.hasOwn(y[b],x)}function l(y,b,x,S){let k={},_={},C={};return b.forEach(T=>{T.forEach((E,N)=>{k[E]=E,_[E]=E,C[E]=N})}),b.forEach(T=>{let E=-1;T.forEach(N=>{let I=S(N);if(I.length){I=I.sort((R,L)=>C[R]-C[L]);let A=(I.length-1)/2;for(let R=Math.floor(A),L=Math.ceil(A);R<=L;++R){let D=I[R];_[N]===N&&E<C[D]&&!i(x,N,D)&&(_[D]=N,_[N]=k[N]=k[D],E=C[D])}}})}),{root:k,align:_}}function c(y,b,x,S,k){let _={},C=u(y,b,x,k),T=k?"borderLeft":"borderRight";function E(A,R){let L=C.nodes(),D=L.pop(),F={};for(;D;)F[D]?A(D):(F[D]=!0,L.push(D),L=L.concat(R(D))),D=L.pop()}function N(A){_[A]=C.inEdges(A).reduce((R,L)=>Math.max(R,_[L.v]+C.edge(L)),0)}function I(A){let R=C.outEdges(A).reduce((D,F)=>Math.min(D,_[F.w]-C.edge(F)),Number.POSITIVE_INFINITY),L=y.node(A);R!==Number.POSITIVE_INFINITY&&L.borderType!==T&&(_[A]=Math.max(_[A],R))}return E(N,C.predecessors.bind(C)),E(I,C.successors.bind(C)),Object.keys(S).forEach(A=>_[A]=_[x[A]]),_}function u(y,b,x,S){let k=new e,_=y.graph(),C=m(_.nodesep,_.edgesep,S);return b.forEach(T=>{let E;T.forEach(N=>{let I=x[N];if(k.setNode(I),E){var A=x[E],R=k.edge(A,I);k.setEdge(A,I,Math.max(C(y,N,E),R||0))}E=N})}),k}function d(y,b){return Object.values(b).reduce((x,S)=>{let k=Number.NEGATIVE_INFINITY,_=Number.POSITIVE_INFINITY;Object.entries(S).forEach(([T,E])=>{let N=v(y,T)/2;k=Math.max(E+N,k),_=Math.min(E-N,_)});const C=k-_;return C<x[0]&&(x=[C,S]),x},[Number.POSITIVE_INFINITY,null])[1]}function f(y,b){let x=Object.values(b),S=t.applyWithChunking(Math.min,x),k=t.applyWithChunking(Math.max,x);["u","d"].forEach(_=>{["l","r"].forEach(C=>{let T=_+C,E=y[T];if(E===b)return;let N=Object.values(E),I=S-t.applyWithChunking(Math.min,N);C!=="l"&&(I=k-t.applyWithChunking(Math.max,N)),I&&(y[T]=t.mapValues(E,A=>A+I))})})}function p(y,b){return t.mapValues(y.ul,(x,S)=>{if(b)return y[b.toLowerCase()][S];{let k=Object.values(y).map(_=>_[S]).sort((_,C)=>_-C);return(k[1]+k[2])/2}})}function h(y){let b=t.buildLayerMatrix(y),x=Object.assign(n(y,b),r(y,b)),S={},k;["u","d"].forEach(C=>{k=C==="u"?b:Object.values(b).reverse(),["l","r"].forEach(T=>{T==="r"&&(k=k.map(A=>Object.values(A).reverse()));let E=(C==="u"?y.predecessors:y.successors).bind(y),N=l(y,k,x,E),I=c(y,k,N.root,N.align,T==="r");T==="r"&&(I=t.mapValues(I,A=>-A)),S[C+T]=I})});let _=d(y,S);return f(S,_),p(S,y.graph().align)}function m(y,b,x){return(S,k,_)=>{let C=S.node(k),T=S.node(_),E=0,N;if(E+=C.width/2,Object.hasOwn(C,"labelpos"))switch(C.labelpos.toLowerCase()){case"l":N=-C.width/2;break;case"r":N=C.width/2;break}if(N&&(E+=x?N:-N),N=0,E+=(C.dummy?b:y)/2,E+=(T.dummy?b:y)/2,E+=T.width/2,Object.hasOwn(T,"labelpos"))switch(T.labelpos.toLowerCase()){case"l":N=T.width/2;break;case"r":N=-T.width/2;break}return N&&(E+=x?N:-N),N=0,E}}function v(y,b){return y.node(b).width}return Vte}var Hte,i7e;function yWn(){if(i7e)return Hte;i7e=1;let e=Al(),t=vWn().positionX;Hte=n;function n(s){s=e.asNonCompoundGraph(s),r(s),Object.entries(t(s)).forEach(([a,i])=>s.node(a).x=i)}function r(s){let a=e.buildLayerMatrix(s),i=s.graph().ranksep,l=0;a.forEach(c=>{const u=c.reduce((d,f)=>{const p=s.node(f).height;return d>p?d:p},0);c.forEach(d=>s.node(d).y=l+u/2),l+=u+i})}return Hte}var Wte,o7e;function bWn(){if(o7e)return Wte;o7e=1;let e=eWn(),t=tWn(),n=rWn(),r=Al().normalizeRanks,s=sWn(),a=Al().removeEmptyRanks,i=aWn(),l=iWn(),c=oWn(),u=gWn(),d=yWn(),f=Al(),p=Hg().Graph;Wte=h;function h($,q){let Z=q&&q.debugTiming?f.time:f.notime;Z("layout",()=>{let Y=Z(" buildLayoutGraph",()=>E($));Z(" runLayout",()=>m(Y,Z,q)),Z(" updateInputGraph",()=>v($,Y))})}function m($,q,Z){q(" makeSpaceForEdgeLabels",()=>N($)),q(" removeSelfEdges",()=>z($)),q(" acyclic",()=>e.run($)),q(" nestingGraph.run",()=>i.run($)),q(" rank",()=>n(f.asNonCompoundGraph($))),q(" injectEdgeLabelProxies",()=>I($)),q(" removeEmptyRanks",()=>a($)),q(" nestingGraph.cleanup",()=>i.cleanup($)),q(" normalizeRanks",()=>r($)),q(" assignRankMinMax",()=>A($)),q(" removeEdgeLabelProxies",()=>R($)),q(" normalize.run",()=>t.run($)),q(" parentDummyChains",()=>s($)),q(" addBorderSegments",()=>l($)),q(" order",()=>u($,Z)),q(" insertSelfEdges",()=>V($)),q(" adjustCoordinateSystem",()=>c.adjust($)),q(" position",()=>d($)),q(" positionSelfEdges",()=>M($)),q(" removeBorderNodes",()=>B($)),q(" normalize.undo",()=>t.undo($)),q(" fixupEdgeLabelCoords",()=>F($)),q(" undoCoordinateSystem",()=>c.undo($)),q(" translateGraph",()=>L($)),q(" assignNodeIntersects",()=>D($)),q(" reversePoints",()=>H($)),q(" acyclic.undo",()=>e.undo($))}function v($,q){$.nodes().forEach(Z=>{let Y=$.node(Z),ne=q.node(Z);Y&&(Y.x=ne.x,Y.y=ne.y,Y.rank=ne.rank,q.children(Z).length&&(Y.width=ne.width,Y.height=ne.height))}),$.edges().forEach(Z=>{let Y=$.edge(Z),ne=q.edge(Z);Y.points=ne.points,Object.hasOwn(ne,"x")&&(Y.x=ne.x,Y.y=ne.y)}),$.graph().width=q.graph().width,$.graph().height=q.graph().height}let y=["nodesep","edgesep","ranksep","marginx","marginy"],b={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},x=["acyclicer","ranker","rankdir","align"],S=["width","height","rank"],k={width:0,height:0},_=["minlen","weight","width","height","labeloffset"],C={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},T=["labelpos"];function E($){let q=new p({multigraph:!0,compound:!0}),Z=U($.graph());return q.setGraph(Object.assign({},b,G(Z,y),f.pick(Z,x))),$.nodes().forEach(Y=>{let ne=U($.node(Y));const J=G(ne,S);Object.keys(k).forEach(ee=>{J[ee]===void 0&&(J[ee]=k[ee])}),q.setNode(Y,J),q.setParent(Y,$.parent(Y))}),$.edges().forEach(Y=>{let ne=U($.edge(Y));q.setEdge(Y,Object.assign({},C,G(ne,_),f.pick(ne,T)))}),q}function N($){let q=$.graph();q.ranksep/=2,$.edges().forEach(Z=>{let Y=$.edge(Z);Y.minlen*=2,Y.labelpos.toLowerCase()!=="c"&&(q.rankdir==="TB"||q.rankdir==="BT"?Y.width+=Y.labeloffset:Y.height+=Y.labeloffset)})}function I($){$.edges().forEach(q=>{let Z=$.edge(q);if(Z.width&&Z.height){let Y=$.node(q.v),J={rank:($.node(q.w).rank-Y.rank)/2+Y.rank,e:q};f.addDummyNode($,"edge-proxy",J,"_ep")}})}function A($){let q=0;$.nodes().forEach(Z=>{let Y=$.node(Z);Y.borderTop&&(Y.minRank=$.node(Y.borderTop).rank,Y.maxRank=$.node(Y.borderBottom).rank,q=Math.max(q,Y.maxRank))}),$.graph().maxRank=q}function R($){$.nodes().forEach(q=>{let Z=$.node(q);Z.dummy==="edge-proxy"&&($.edge(Z.e).labelRank=Z.rank,$.removeNode(q))})}function L($){let q=Number.POSITIVE_INFINITY,Z=0,Y=Number.POSITIVE_INFINITY,ne=0,J=$.graph(),ee=J.marginx||0,re=J.marginy||0;function le(X){let te=X.x,se=X.y,pe=X.width,ce=X.height;q=Math.min(q,te-pe/2),Z=Math.max(Z,te+pe/2),Y=Math.min(Y,se-ce/2),ne=Math.max(ne,se+ce/2)}$.nodes().forEach(X=>le($.node(X))),$.edges().forEach(X=>{let te=$.edge(X);Object.hasOwn(te,"x")&&le(te)}),q-=ee,Y-=re,$.nodes().forEach(X=>{let te=$.node(X);te.x-=q,te.y-=Y}),$.edges().forEach(X=>{let te=$.edge(X);te.points.forEach(se=>{se.x-=q,se.y-=Y}),Object.hasOwn(te,"x")&&(te.x-=q),Object.hasOwn(te,"y")&&(te.y-=Y)}),J.width=Z-q+ee,J.height=ne-Y+re}function D($){$.edges().forEach(q=>{let Z=$.edge(q),Y=$.node(q.v),ne=$.node(q.w),J,ee;Z.points?(J=Z.points[0],ee=Z.points[Z.points.length-1]):(Z.points=[],J=ne,ee=Y),Z.points.unshift(f.intersectRect(Y,J)),Z.points.push(f.intersectRect(ne,ee))})}function F($){$.edges().forEach(q=>{let Z=$.edge(q);if(Object.hasOwn(Z,"x"))switch((Z.labelpos==="l"||Z.labelpos==="r")&&(Z.width-=Z.labeloffset),Z.labelpos){case"l":Z.x-=Z.width/2+Z.labeloffset;break;case"r":Z.x+=Z.width/2+Z.labeloffset;break}})}function H($){$.edges().forEach(q=>{let Z=$.edge(q);Z.reversed&&Z.points.reverse()})}function B($){$.nodes().forEach(q=>{if($.children(q).length){let Z=$.node(q),Y=$.node(Z.borderTop),ne=$.node(Z.borderBottom),J=$.node(Z.borderLeft[Z.borderLeft.length-1]),ee=$.node(Z.borderRight[Z.borderRight.length-1]);Z.width=Math.abs(ee.x-J.x),Z.height=Math.abs(ne.y-Y.y),Z.x=J.x+Z.width/2,Z.y=Y.y+Z.height/2}}),$.nodes().forEach(q=>{$.node(q).dummy==="border"&&$.removeNode(q)})}function z($){$.edges().forEach(q=>{if(q.v===q.w){var Z=$.node(q.v);Z.selfEdges||(Z.selfEdges=[]),Z.selfEdges.push({e:q,label:$.edge(q)}),$.removeEdge(q)}})}function V($){var q=f.buildLayerMatrix($);q.forEach(Z=>{var Y=0;Z.forEach((ne,J)=>{var ee=$.node(ne);ee.order=J+Y,(ee.selfEdges||[]).forEach(re=>{f.addDummyNode($,"selfedge",{width:re.label.width,height:re.label.height,rank:ee.rank,order:J+ ++Y,e:re.e,label:re.label},"_se")}),delete ee.selfEdges})})}function M($){$.nodes().forEach(q=>{var Z=$.node(q);if(Z.dummy==="selfedge"){var Y=$.node(Z.e.v),ne=Y.x+Y.width/2,J=Y.y,ee=Z.x-ne,re=Y.height/2;$.setEdge(Z.e,Z.label),$.removeNode(q),Z.label.points=[{x:ne+2*ee/3,y:J-re},{x:ne+5*ee/6,y:J-re},{x:ne+ee,y:J},{x:ne+5*ee/6,y:J+re},{x:ne+2*ee/3,y:J+re}],Z.label.x=Z.x,Z.label.y=Z.y}})}function G($,q){return f.mapValues(f.pick($,q),Number)}function U($){var q={};return $&&Object.entries($).forEach(([Z,Y])=>{typeof Z=="string"&&(Z=Z.toLowerCase()),q[Z]=Y}),q}return Wte}var Zte,l7e;function xWn(){if(l7e)return Zte;l7e=1;let e=Al(),t=Hg().Graph;Zte={debugOrdering:n};function n(r){let s=e.buildLayerMatrix(r),a=new t({compound:!0,multigraph:!0}).setGraph({});return r.nodes().forEach(i=>{a.setNode(i,{label:i}),a.setParent(i,"layer"+r.node(i).rank)}),r.edges().forEach(i=>a.setEdge(i.v,i.w,{},i.name)),s.forEach((i,l)=>{let c="layer"+l;a.setNode(c,{rank:"same"}),i.reduce((u,d)=>(a.setEdge(u,d,{style:"invis"}),d))}),a}return Zte}var Gte,c7e;function wWn(){return c7e||(c7e=1,Gte="1.1.8"),Gte}var Qte,u7e;function SWn(){return u7e||(u7e=1,Qte={graphlib:Hg(),layout:bWn(),debug:xWn(),util:{time:Al().time,notime:Al().notime},version:wWn()}),Qte}var kWn=SWn();const d7e=Fl(kWn);function ql(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,r;n<e.length;n++)(r=ql(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var OWn={value:()=>{}};function aW(){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 H8(n)}function H8(e){this._=e}function _Wn(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}})}H8.prototype=aW.prototype={constructor:H8,on:function(e,t){var n=this._,r=_Wn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=CWn(n[s],e.name)))return s;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++a<i;)if(s=(e=r[a]).type)n[s]=f7e(n[s],e.name,t);else if(t==null)for(s in n)n[s]=f7e(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 H8(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),r=0,s,a;r<s;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(a=this._[e],r=0,s=a.length;r<s;++r)a[r].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],s=0,a=r.length;s<a;++s)r[s].value.apply(t,n)}};function CWn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function f7e(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=OWn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var ive="http://www.w3.org/1999/xhtml";const p7e={svg:"http://www.w3.org/2000/svg",xhtml:ive,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function iW(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),p7e.hasOwnProperty(t)?{space:p7e[t],local:e}:e}function EWn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===ive&&t.documentElement.namespaceURI===ive?t.createElement(e):t.createElementNS(n,e)}}function TWn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function qkt(e){var t=iW(e);return(t.local?TWn:EWn)(t)}function jWn(){}function cOe(e){return e==null?jWn:function(){return this.querySelector(e)}}function NWn(e){typeof e!="function"&&(e=cOe(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=new Array(i),c,u,d=0;d<i;++d)(c=a[d])&&(u=e.call(c,c.__data__,d,a))&&("__data__"in c&&(u.__data__=c.__data__),l[d]=u);return new Yp(r,this._parents)}function IWn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function AWn(){return[]}function Vkt(e){return e==null?AWn:function(){return this.querySelectorAll(e)}}function RWn(e){return function(){return IWn(e.apply(this,arguments))}}function PWn(e){typeof e=="function"?e=RWn(e):e=Vkt(e);for(var t=this._groups,n=t.length,r=[],s=[],a=0;a<n;++a)for(var i=t[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&(r.push(e.call(c,c.__data__,u,i)),s.push(c));return new Yp(r,s)}function Hkt(e){return function(){return this.matches(e)}}function Wkt(e){return function(t){return t.matches(e)}}var $Wn=Array.prototype.find;function MWn(e){return function(){return $Wn.call(this.children,e)}}function DWn(){return this.firstElementChild}function LWn(e){return this.select(e==null?DWn:MWn(typeof e=="function"?e:Wkt(e)))}var FWn=Array.prototype.filter;function zWn(){return Array.from(this.children)}function BWn(e){return function(){return FWn.call(this.children,e)}}function UWn(e){return this.selectAll(e==null?zWn:BWn(typeof e=="function"?e:Wkt(e)))}function qWn(e){typeof e!="function"&&(e=Hkt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new Yp(r,this._parents)}function Zkt(e){return new Array(e.length)}function VWn(){return new Yp(this._enter||this._groups.map(Zkt),this._parents)}function GB(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}GB.prototype={constructor:GB,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 HWn(e){return function(){return e}}function WWn(e,t,n,r,s,a){for(var i=0,l,c=t.length,u=a.length;i<u;++i)(l=t[i])?(l.__data__=a[i],r[i]=l):n[i]=new GB(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function ZWn(e,t,n,r,s,a,i){var l,c,u=new Map,d=t.length,f=a.length,p=new Array(d),h;for(l=0;l<d;++l)(c=t[l])&&(p[l]=h=i.call(c,c.__data__,l,t)+"",u.has(h)?s[l]=c:u.set(h,c));for(l=0;l<f;++l)h=i.call(e,a[l],l,a)+"",(c=u.get(h))?(r[l]=c,c.__data__=a[l],u.delete(h)):n[l]=new GB(e,a[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(p[l])===c&&(s[l]=c)}function GWn(e){return e.__data__}function QWn(e,t){if(!arguments.length)return Array.from(this,GWn);var n=t?ZWn:WWn,r=this._parents,s=this._groups;typeof e!="function"&&(e=HWn(e));for(var a=s.length,i=new Array(a),l=new Array(a),c=new Array(a),u=0;u<a;++u){var d=r[u],f=s[u],p=f.length,h=YWn(e.call(d,d&&d.__data__,u,r)),m=h.length,v=l[u]=new Array(m),y=i[u]=new Array(m),b=c[u]=new Array(p);n(d,f,v,y,b,h,t);for(var x=0,S=0,k,_;x<m;++x)if(k=v[x]){for(x>=S&&(S=x+1);!(_=y[S])&&++S<m;);k._next=_||null}}return i=new Yp(i,r),i._enter=l,i._exit=c,i}function YWn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function KWn(){return new Yp(this._exit||this._groups.map(Zkt),this._parents)}function XWn(e,t,n){var r=this.enter(),s=this,a=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(s=t(s),s&&(s=s.selection())),n==null?a.remove():n(a),r&&s?r.merge(s).order():s}function JWn(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,s=n.length,a=r.length,i=Math.min(s,a),l=new Array(s),c=0;c<i;++c)for(var u=n[c],d=r[c],f=u.length,p=l[c]=new Array(f),h,m=0;m<f;++m)(h=u[m]||d[m])&&(p[m]=h);for(;c<s;++c)l[c]=n[c];return new Yp(l,this._parents)}function eZn(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],s=r.length-1,a=r[s],i;--s>=0;)(i=r[s])&&(a&&i.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(i,a),a=i);return this}function tZn(e){e||(e=nZn);function t(f,p){return f&&p?e(f.__data__,p.__data__):!f-!p}for(var n=this._groups,r=n.length,s=new Array(r),a=0;a<r;++a){for(var i=n[a],l=i.length,c=s[a]=new Array(l),u,d=0;d<l;++d)(u=i[d])&&(c[d]=u);c.sort(t)}return new Yp(s,this._parents).order()}function nZn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function rZn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function sZn(){return Array.from(this)}function aZn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length;s<a;++s){var i=r[s];if(i)return i}return null}function iZn(){let e=0;for(const t of this)++e;return e}function oZn(){return!this.node()}function lZn(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var s=t[n],a=0,i=s.length,l;a<i;++a)(l=s[a])&&e.call(l,l.__data__,a,s);return this}function cZn(e){return function(){this.removeAttribute(e)}}function uZn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function dZn(e,t){return function(){this.setAttribute(e,t)}}function fZn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function pZn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function hZn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function mZn(e,t){var n=iW(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?uZn:cZn:typeof t=="function"?n.local?hZn:pZn:n.local?fZn:dZn)(n,t))}function Gkt(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function gZn(e){return function(){this.style.removeProperty(e)}}function vZn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function yZn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function bZn(e,t,n){return arguments.length>1?this.each((t==null?gZn:typeof t=="function"?yZn:vZn)(e,t,n??"")):tN(this.node(),e)}function tN(e,t){return e.style.getPropertyValue(t)||Gkt(e).getComputedStyle(e,null).getPropertyValue(t)}function xZn(e){return function(){delete this[e]}}function wZn(e,t){return function(){this[e]=t}}function SZn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function kZn(e,t){return arguments.length>1?this.each((t==null?xZn:typeof t=="function"?SZn:wZn)(e,t)):this.node()[e]}function Qkt(e){return e.trim().split(/^|\s+/)}function uOe(e){return e.classList||new Ykt(e)}function Ykt(e){this._node=e,this._names=Qkt(e.getAttribute("class")||"")}Ykt.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 Kkt(e,t){for(var n=uOe(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function Xkt(e,t){for(var n=uOe(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function OZn(e){return function(){Kkt(this,e)}}function _Zn(e){return function(){Xkt(this,e)}}function CZn(e,t){return function(){(t.apply(this,arguments)?Kkt:Xkt)(this,e)}}function EZn(e,t){var n=Qkt(e+"");if(arguments.length<2){for(var r=uOe(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?CZn:t?OZn:_Zn)(n,t))}function TZn(){this.textContent=""}function jZn(e){return function(){this.textContent=e}}function NZn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function IZn(e){return arguments.length?this.each(e==null?TZn:(typeof e=="function"?NZn:jZn)(e)):this.node().textContent}function AZn(){this.innerHTML=""}function RZn(e){return function(){this.innerHTML=e}}function PZn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function $Zn(e){return arguments.length?this.each(e==null?AZn:(typeof e=="function"?PZn:RZn)(e)):this.node().innerHTML}function MZn(){this.nextSibling&&this.parentNode.appendChild(this)}function DZn(){return this.each(MZn)}function LZn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function FZn(){return this.each(LZn)}function zZn(e){var t=typeof e=="function"?e:qkt(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function BZn(){return null}function UZn(e,t){var n=typeof e=="function"?e:qkt(e),r=t==null?BZn:typeof t=="function"?t:cOe(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function qZn(){var e=this.parentNode;e&&e.removeChild(this)}function VZn(){return this.each(qZn)}function HZn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function WZn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function ZZn(e){return this.select(e?WZn:HZn)}function GZn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function QZn(e){return function(t){e.call(this,t,this.__data__)}}function YZn(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 KZn(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,s=t.length,a;n<s;++n)a=t[n],(!e.type||a.type===e.type)&&a.name===e.name?this.removeEventListener(a.type,a.listener,a.options):t[++r]=a;++r?t.length=r:delete this.__on}}}function XZn(e,t,n){return function(){var r=this.__on,s,a=QZn(t);if(r){for(var i=0,l=r.length;i<l;++i)if((s=r[i]).type===e.type&&s.name===e.name){this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=a,s.options=n),s.value=t;return}}this.addEventListener(e.type,a,n),s={type:e.type,name:e.name,value:t,listener:a,options:n},r?r.push(s):this.__on=[s]}}function JZn(e,t,n){var r=YZn(e+""),s,a=r.length,i;if(arguments.length<2){var l=this.node().__on;if(l){for(var c=0,u=l.length,d;c<u;++c)for(s=0,d=l[c];s<a;++s)if((i=r[s]).type===d.type&&i.name===d.name)return d.value}return}for(l=t?XZn:KZn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function Jkt(e,t,n){var r=Gkt(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 eGn(e,t){return function(){return Jkt(this,e,t)}}function tGn(e,t){return function(){return Jkt(this,e,t.apply(this,arguments))}}function nGn(e,t){return this.each((typeof t=="function"?tGn:eGn)(e,t))}function*rGn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length,i;s<a;++s)(i=r[s])&&(yield i)}var eOt=[null];function Yp(e,t){this._groups=e,this._parents=t}function Y3(){return new Yp([[document.documentElement]],eOt)}function sGn(){return this}Yp.prototype=Y3.prototype={constructor:Yp,select:NWn,selectAll:PWn,selectChild:LWn,selectChildren:UWn,filter:qWn,data:QWn,enter:VWn,exit:KWn,join:XWn,merge:JWn,selection:sGn,order:eZn,sort:tZn,call:rZn,nodes:sZn,node:aZn,size:iZn,empty:oZn,each:lZn,attr:mZn,style:bZn,property:kZn,classed:EZn,text:IZn,html:$Zn,raise:DZn,lower:FZn,append:zZn,insert:UZn,remove:VZn,clone:ZZn,datum:GZn,on:JZn,dispatch:nGn,[Symbol.iterator]:rGn};function Cp(e){return typeof e=="string"?new Yp([[document.querySelector(e)]],[document.documentElement]):new Yp([[e]],eOt)}function aGn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function fg(e,t){if(e=aGn(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 iGn={passive:!1},IM={capture:!0,passive:!1};function Yte(e){e.stopImmediatePropagation()}function aj(e){e.preventDefault(),e.stopImmediatePropagation()}function tOt(e){var t=e.document.documentElement,n=Cp(e).on("dragstart.drag",aj,IM);"onselectstart"in t?n.on("selectstart.drag",aj,IM):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function nOt(e,t){var n=e.document.documentElement,r=Cp(e).on("dragstart.drag",null);t&&(r.on("click.drag",aj,IM),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 mF=e=>()=>e;function ove(e,{sourceEvent:t,subject:n,target:r,identifier:s,active:a,x:i,y:l,dx:c,dy:u,dispatch:d}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:s,enumerable:!0,configurable:!0},active:{value:a,enumerable:!0,configurable:!0},x:{value:i,enumerable:!0,configurable:!0},y:{value:l,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:u,enumerable:!0,configurable:!0},_:{value:d}})}ove.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function oGn(e){return!e.ctrlKey&&!e.button}function lGn(){return this.parentNode}function cGn(e,t){return t??{x:e.x,y:e.y}}function uGn(){return navigator.maxTouchPoints||"ontouchstart"in this}function rOt(){var e=oGn,t=lGn,n=cGn,r=uGn,s={},a=aW("start","drag","end"),i=0,l,c,u,d,f=0;function p(k){k.on("mousedown.drag",h).filter(r).on("touchstart.drag",y).on("touchmove.drag",b,iGn).on("touchend.drag touchcancel.drag",x).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function h(k,_){if(!(d||!e.call(this,k,_))){var C=S(this,t.call(this,k,_),k,_,"mouse");C&&(Cp(k.view).on("mousemove.drag",m,IM).on("mouseup.drag",v,IM),tOt(k.view),Yte(k),u=!1,l=k.clientX,c=k.clientY,C("start",k))}}function m(k){if(aj(k),!u){var _=k.clientX-l,C=k.clientY-c;u=_*_+C*C>f}s.mouse("drag",k)}function v(k){Cp(k.view).on("mousemove.drag mouseup.drag",null),nOt(k.view,u),aj(k),s.mouse("end",k)}function y(k,_){if(e.call(this,k,_)){var C=k.changedTouches,T=t.call(this,k,_),E=C.length,N,I;for(N=0;N<E;++N)(I=S(this,T,k,_,C[N].identifier,C[N]))&&(Yte(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])&&(aj(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])&&(Yte(k),E("end",k,_[T]))}function S(k,_,C,T,E,N){var I=a.copy(),A=fg(N||C,_),R,L,D;if((D=n.call(k,new ove("beforestart",{sourceEvent:C,target:p,identifier:E,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),T))!=null)return R=D.x-A[0]||0,L=D.y-A[1]||0,function F(H,B,z){var V=A,M;switch(H){case"start":s[E]=F,M=i++;break;case"end":delete s[E],--i;case"drag":A=fg(z||B,_),M=i;break}I.call(H,k,new ove(H,{sourceEvent:B,subject:D,target:p,identifier:E,active:M,x:A[0]+R,y:A[1]+L,dx:A[0]-V[0],dy:A[1]-V[1],dispatch:I}),T)}}return p.filter=function(k){return arguments.length?(e=typeof k=="function"?k:mF(!!k),p):e},p.container=function(k){return arguments.length?(t=typeof k=="function"?k:mF(k),p):t},p.subject=function(k){return arguments.length?(n=typeof k=="function"?k:mF(k),p):n},p.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:mF(!!k),p):r},p.on=function(){var k=a.on.apply(a,arguments);return k===a?p:k},p.clickDistance=function(k){return arguments.length?(f=(k=+k)*k,p):Math.sqrt(f)},p}function dOe(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function sOt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function K3(){}var AM=.7,QB=1/AM,ij="\\s*([+-]?\\d+)\\s*",RM="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",dy="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",dGn=/^#([0-9a-f]{3,8})$/,fGn=new RegExp(`^rgb\\(${ij},${ij},${ij}\\)$`),pGn=new RegExp(`^rgb\\(${dy},${dy},${dy}\\)$`),hGn=new RegExp(`^rgba\\(${ij},${ij},${ij},${RM}\\)$`),mGn=new RegExp(`^rgba\\(${dy},${dy},${dy},${RM}\\)$`),gGn=new RegExp(`^hsl\\(${RM},${dy},${dy}\\)$`),vGn=new RegExp(`^hsla\\(${RM},${dy},${dy},${RM}\\)$`),h7e={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};dOe(K3,QO,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:m7e,formatHex:m7e,formatHex8:yGn,formatHsl:bGn,formatRgb:g7e,toString:g7e});function m7e(){return this.rgb().formatHex()}function yGn(){return this.rgb().formatHex8()}function bGn(){return aOt(this).formatHsl()}function g7e(){return this.rgb().formatRgb()}function QO(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=dGn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?v7e(t):n===3?new Ef(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?gF(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?gF(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=fGn.exec(e))?new Ef(t[1],t[2],t[3],1):(t=pGn.exec(e))?new Ef(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=hGn.exec(e))?gF(t[1],t[2],t[3],t[4]):(t=mGn.exec(e))?gF(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=gGn.exec(e))?x7e(t[1],t[2]/100,t[3]/100,1):(t=vGn.exec(e))?x7e(t[1],t[2]/100,t[3]/100,t[4]):h7e.hasOwnProperty(e)?v7e(h7e[e]):e==="transparent"?new Ef(NaN,NaN,NaN,0):null}function v7e(e){return new Ef(e>>16&255,e>>8&255,e&255,1)}function gF(e,t,n,r){return r<=0&&(e=t=n=NaN),new Ef(e,t,n,r)}function xGn(e){return e instanceof K3||(e=QO(e)),e?(e=e.rgb(),new Ef(e.r,e.g,e.b,e.opacity)):new Ef}function lve(e,t,n,r){return arguments.length===1?xGn(e):new Ef(e,t,n,r??1)}function Ef(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}dOe(Ef,lve,sOt(K3,{brighter(e){return e=e==null?QB:Math.pow(QB,e),new Ef(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?AM:Math.pow(AM,e),new Ef(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Ef(nO(this.r),nO(this.g),nO(this.b),YB(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:y7e,formatHex:y7e,formatHex8:wGn,formatRgb:b7e,toString:b7e}));function y7e(){return`#${Mk(this.r)}${Mk(this.g)}${Mk(this.b)}`}function wGn(){return`#${Mk(this.r)}${Mk(this.g)}${Mk(this.b)}${Mk((isNaN(this.opacity)?1:this.opacity)*255)}`}function b7e(){const e=YB(this.opacity);return`${e===1?"rgb(":"rgba("}${nO(this.r)}, ${nO(this.g)}, ${nO(this.b)}${e===1?")":`, ${e})`}`}function YB(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function nO(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Mk(e){return e=nO(e),(e<16?"0":"")+e.toString(16)}function x7e(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new bg(e,t,n,r)}function aOt(e){if(e instanceof bg)return new bg(e.h,e.s,e.l,e.opacity);if(e instanceof K3||(e=QO(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),a=Math.max(t,n,r),i=NaN,l=a-s,c=(a+s)/2;return l?(t===a?i=(n-r)/l+(n<r)*6:n===a?i=(r-t)/l+2:i=(t-n)/l+4,l/=c<.5?a+s:2-a-s,i*=60):l=c>0&&c<1?0:i,new bg(i,l,c,e.opacity)}function SGn(e,t,n,r){return arguments.length===1?aOt(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}dOe(bg,SGn,sOt(K3,{brighter(e){return e=e==null?QB:Math.pow(QB,e),new bg(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?AM:Math.pow(AM,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 Ef(Kte(e>=240?e-240:e+120,s,r),Kte(e,s,r),Kte(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new bg(w7e(this.h),vF(this.s),vF(this.l),YB(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=YB(this.opacity);return`${e===1?"hsl(":"hsla("}${w7e(this.h)}, ${vF(this.s)*100}%, ${vF(this.l)*100}%${e===1?")":`, ${e})`}`}}));function w7e(e){return e=(e||0)%360,e<0?e+360:e}function vF(e){return Math.max(0,Math.min(1,e||0))}function Kte(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 fOe=e=>()=>e;function kGn(e,t){return function(n){return e+n*t}}function OGn(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 _Gn(e){return(e=+e)==1?iOt:function(t,n){return n-t?OGn(t,n,e):fOe(isNaN(t)?n:t)}}function iOt(e,t){var n=t-e;return n?kGn(e,n):fOe(isNaN(e)?t:e)}const KB=(function e(t){var n=_Gn(t);function r(s,a){var i=n((s=lve(s)).r,(a=lve(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=iOt(s.opacity,a.opacity);return function(d){return s.r=i(d),s.g=l(d),s.b=c(d),s.opacity=u(d),s+""}}return r.gamma=e,r})(1);function CGn(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),s;return function(a){for(s=0;s<n;++s)r[s]=e[s]*(1-a)+t[s]*a;return r}}function EGn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function TGn(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,s=new Array(r),a=new Array(n),i;for(i=0;i<r;++i)s[i]=hx(e[i],t[i]);for(;i<n;++i)a[i]=t[i];return function(l){for(i=0;i<r;++i)a[i]=s[i](l);return a}}function jGn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function hg(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function NGn(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]=hx(e[s],t[s]):r[s]=t[s];return function(a){for(s in n)r[s]=n[s](a);return r}}var cve=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Xte=new RegExp(cve.source,"g");function IGn(e){return function(){return e}}function AGn(e){return function(t){return e(t)+""}}function oOt(e,t){var n=cve.lastIndex=Xte.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=cve.exec(e))&&(s=Xte.exec(t));)(a=s.index)>n&&(a=t.slice(n,a),l[i]?l[i]+=a:l[++i]=a),(r=r[0])===(s=s[0])?l[i]?l[i]+=s:l[++i]=s:(l[++i]=null,c.push({i,x:hg(r,s)})),n=Xte.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?AGn(c[0].x):IGn(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 hx(e,t){var n=typeof t,r;return t==null||n==="boolean"?fOe(t):(n==="number"?hg:n==="string"?(r=QO(t))?(t=r,KB):oOt:t instanceof QO?KB:t instanceof Date?jGn:EGn(t)?CGn:Array.isArray(t)?TGn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?NGn:hg)(e,t)}function pOe(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var S7e=180/Math.PI,uve={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function lOt(e,t,n,r,s,a){var i,l,c;return(i=Math.sqrt(e*e+t*t))&&(e/=i,t/=i),(c=e*n+t*r)&&(n-=e*c,r-=t*c),(l=Math.sqrt(n*n+r*r))&&(n/=l,r/=l,c/=l),e*r<t*n&&(e=-e,t=-t,c=-c,i=-i),{translateX:s,translateY:a,rotate:Math.atan2(t,e)*S7e,skewX:Math.atan(c)*S7e,scaleX:i,scaleY:l}}var yF;function RGn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?uve:lOt(t.a,t.b,t.c,t.d,t.e,t.f)}function PGn(e){return e==null||(yF||(yF=document.createElementNS("http://www.w3.org/2000/svg","g")),yF.setAttribute("transform",e),!(e=yF.transform.baseVal.consolidate()))?uve:(e=e.matrix,lOt(e.a,e.b,e.c,e.d,e.e,e.f))}function cOt(e,t,n,r){function s(u){return u.length?u.pop()+" ":""}function a(u,d,f,p,h,m){if(u!==f||d!==p){var v=h.push("translate(",null,t,null,n);m.push({i:v-4,x:hg(u,f)},{i:v-2,x:hg(d,p)})}else(f||p)&&h.push("translate("+f+t+p+n)}function i(u,d,f,p){u!==d?(u-d>180?d+=360:d-u>180&&(u+=360),p.push({i:f.push(s(f)+"rotate(",null,r)-2,x:hg(u,d)})):d&&f.push(s(f)+"rotate("+d+r)}function l(u,d,f,p){u!==d?p.push({i:f.push(s(f)+"skewX(",null,r)-2,x:hg(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,p,h,m){if(u!==f||d!==p){var v=h.push(s(h)+"scale(",null,",",null,")");m.push({i:v-4,x:hg(u,f)},{i:v-2,x:hg(d,p)})}else(f!==1||p!==1)&&h.push(s(h)+"scale("+f+","+p+")")}return function(u,d){var f=[],p=[];return u=e(u),d=e(d),a(u.translateX,u.translateY,d.translateX,d.translateY,f,p),i(u.rotate,d.rotate,f,p),l(u.skewX,d.skewX,f,p),c(u.scaleX,u.scaleY,d.scaleX,d.scaleY,f,p),u=d=null,function(h){for(var m=-1,v=p.length,y;++m<v;)f[(y=p[m]).i]=y.x(h);return f.join("")}}}var $Gn=cOt(RGn,"px, ","px)","deg)"),MGn=cOt(PGn,", ",")",")"),DGn=1e-12;function k7e(e){return((e=Math.exp(e))+1/e)/2}function LGn(e){return((e=Math.exp(e))-1/e)/2}function FGn(e){return((e=Math.exp(2*e))-1)/(e+1)}const W8=(function e(t,n,r){function s(a,i){var l=a[0],c=a[1],u=a[2],d=i[0],f=i[1],p=i[2],h=d-l,m=f-c,v=h*h+m*m,y,b;if(v<DGn)b=Math.log(p/u)/t,y=function(T){return[l+T*h,c+T*m,u*Math.exp(t*T*b)]};else{var x=Math.sqrt(v),S=(p*p-u*u+r*v)/(2*u*n*x),k=(p*p-u*u-r*v)/(2*p*n*x),_=Math.log(Math.sqrt(S*S+1)-S),C=Math.log(Math.sqrt(k*k+1)-k);b=(C-_)/t,y=function(T){var E=T*b,N=k7e(_),I=u/(n*x)*(N*FGn(t*E+_)-LGn(_));return[l+I*h,c+I*m,u*N/k7e(t*E+_)]}}return y.duration=b*1e3*t/Math.SQRT2,y}return s.rho=function(a){var i=Math.max(.001,+a),l=i*i,c=l*l;return e(i,l,c)},s})(Math.SQRT2,2,4);function zGn(e,t){t===void 0&&(t=e,e=hx);for(var n=0,r=t.length-1,s=t[0],a=new Array(r<0?0:r);n<r;)a[n]=e(s,s=t[++n]);return function(i){var l=Math.max(0,Math.min(r-1,Math.floor(i*=r)));return a[l](i-l)}}var nN=0,QP=0,RR=0,uOt=1e3,XB,YP,JB=0,YO=0,oW=0,PM=typeof performance=="object"&&performance.now?performance:Date,dOt=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function hOe(){return YO||(dOt(BGn),YO=PM.now()+oW)}function BGn(){YO=0}function eU(){this._call=this._time=this._next=null}eU.prototype=fOt.prototype={constructor:eU,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?hOe():+n)+(t==null?0:+t),!this._next&&YP!==this&&(YP?YP._next=this:XB=this,YP=this),this._call=e,this._time=n,dve()},stop:function(){this._call&&(this._call=null,this._time=1/0,dve())}};function fOt(e,t,n){var r=new eU;return r.restart(e,t,n),r}function UGn(){hOe(),++nN;for(var e=XB,t;e;)(t=YO-e._time)>=0&&e._call.call(void 0,t),e=e._next;--nN}function O7e(){YO=(JB=PM.now())+oW,nN=QP=0;try{UGn()}finally{nN=0,VGn(),YO=0}}function qGn(){var e=PM.now(),t=e-JB;t>uOt&&(oW-=t,JB=e)}function VGn(){for(var e,t=XB,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:XB=n);YP=e,dve(r)}function dve(e){if(!nN){QP&&(QP=clearTimeout(QP));var t=e-YO;t>24?(e<1/0&&(QP=setTimeout(O7e,e-PM.now()-oW)),RR&&(RR=clearInterval(RR))):(RR||(JB=PM.now(),RR=setInterval(qGn,uOt)),nN=1,dOt(O7e))}}function _7e(e,t,n){var r=new eU;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var HGn=aW("start","end","cancel","interrupt"),WGn=[],pOt=0,C7e=1,fve=2,Z8=3,E7e=4,pve=5,G8=6;function lW(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;ZGn(e,n,{name:t,index:r,group:s,on:HGn,tween:WGn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:pOt})}function mOe(e,t){var n=ev(e,t);if(n.state>pOt)throw new Error("too late; already scheduled");return n}function zy(e,t){var n=ev(e,t);if(n.state>Z8)throw new Error("too late; already running");return n}function ev(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function ZGn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=fOt(a,0,n.time);function a(u){n.state=C7e,n.timer.restart(i,n.delay,n.time),n.delay<=u&&i(u-n.delay)}function i(u){var d,f,p,h;if(n.state!==C7e)return c();for(d in r)if(h=r[d],h.name===n.name){if(h.state===Z8)return _7e(i);h.state===E7e?(h.state=G8,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete r[d]):+d<t&&(h.state=G8,h.timer.stop(),h.on.call("cancel",e,e.__data__,h.index,h.group),delete r[d])}if(_7e(function(){n.state===Z8&&(n.state=E7e,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=fve,n.on.call("start",e,e.__data__,n.index,n.group),n.state===fve){for(n.state=Z8,s=new Array(p=n.tween.length),d=0,f=-1;d<p;++d)(h=n.tween[d].value.call(e,e.__data__,n.index,n.group))&&(s[++f]=h);s.length=f+1}}function l(u){for(var d=u<n.duration?n.ease.call(null,u/n.duration):(n.timer.restart(c),n.state=pve,1),f=-1,p=s.length;++f<p;)s[f].call(e,d);n.state===pve&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=G8,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function Q8(e,t){var n=e.__transition,r,s,a=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((r=n[i]).name!==t){a=!1;continue}s=r.state>fve&&r.state<pve,r.state=G8,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function GGn(e){return this.each(function(){Q8(this,e)})}function QGn(e,t){var n,r;return function(){var s=zy(this,e),a=s.tween;if(a!==n){r=n=a;for(var i=0,l=r.length;i<l;++i)if(r[i].name===t){r=r.slice(),r.splice(i,1);break}}s.tween=r}}function YGn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=zy(this,e),i=a.tween;if(i!==r){s=(r=i).slice();for(var l={name:t,value:n},c=0,u=s.length;c<u;++c)if(s[c].name===t){s[c]=l;break}c===u&&s.push(l)}a.tween=s}}function KGn(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=ev(this.node(),n).tween,s=0,a=r.length,i;s<a;++s)if((i=r[s]).name===e)return i.value;return null}return this.each((t==null?QGn:YGn)(n,e,t))}function gOe(e,t,n){var r=e._id;return e.each(function(){var s=zy(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return ev(s,r).value[t]}}function hOt(e,t){var n;return(typeof t=="number"?hg:t instanceof QO?KB:(n=QO(t))?(t=n,KB):oOt)(e,t)}function XGn(e){return function(){this.removeAttribute(e)}}function JGn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function eQn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttribute(e);return i===s?null:i===r?a:a=t(r=i,n)}}function tQn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttributeNS(e.space,e.local);return i===s?null:i===r?a:a=t(r=i,n)}}function nQn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttribute(e):(i=this.getAttribute(e),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function rQn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttributeNS(e.space,e.local):(i=this.getAttributeNS(e.space,e.local),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function sQn(e,t){var n=iW(e),r=n==="transform"?MGn:hOt;return this.attrTween(e,typeof t=="function"?(n.local?rQn:nQn)(n,r,gOe(this,"attr."+e,t)):t==null?(n.local?JGn:XGn)(n):(n.local?tQn:eQn)(n,r,t))}function aQn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function iQn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function oQn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&iQn(e,a)),n}return s._value=t,s}function lQn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&aQn(e,a)),n}return s._value=t,s}function cQn(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=iW(e);return this.tween(n,(r.local?oQn:lQn)(r,t))}function uQn(e,t){return function(){mOe(this,e).delay=+t.apply(this,arguments)}}function dQn(e,t){return t=+t,function(){mOe(this,e).delay=t}}function fQn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?uQn:dQn)(t,e)):ev(this.node(),t).delay}function pQn(e,t){return function(){zy(this,e).duration=+t.apply(this,arguments)}}function hQn(e,t){return t=+t,function(){zy(this,e).duration=t}}function mQn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?pQn:hQn)(t,e)):ev(this.node(),t).duration}function gQn(e,t){if(typeof t!="function")throw new Error;return function(){zy(this,e).ease=t}}function vQn(e){var t=this._id;return arguments.length?this.each(gQn(t,e)):ev(this.node(),t).ease}function yQn(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;zy(this,e).ease=n}}function bQn(e){if(typeof e!="function")throw new Error;return this.each(yQn(this._id,e))}function xQn(e){typeof e!="function"&&(e=Hkt(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new Mx(r,this._parents,this._name,this._id)}function wQn(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,s=n.length,a=Math.min(r,s),i=new Array(r),l=0;l<a;++l)for(var c=t[l],u=n[l],d=c.length,f=i[l]=new Array(d),p,h=0;h<d;++h)(p=c[h]||u[h])&&(f[h]=p);for(;l<r;++l)i[l]=t[l];return new Mx(i,this._parents,this._name,this._id)}function SQn(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 kQn(e,t,n){var r,s,a=SQn(t)?mOe:zy;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function OQn(e,t){var n=this._id;return arguments.length<2?ev(this.node(),n).on.on(e):this.each(kQn(n,e,t))}function _Qn(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function CQn(){return this.on("end.remove",_Qn(this._id))}function EQn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=cOe(e));for(var r=this._groups,s=r.length,a=new Array(s),i=0;i<s;++i)for(var l=r[i],c=l.length,u=a[i]=new Array(c),d,f,p=0;p<c;++p)(d=l[p])&&(f=e.call(d,d.__data__,p,l))&&("__data__"in d&&(f.__data__=d.__data__),u[p]=f,lW(u[p],t,n,p,u,ev(d,n)));return new Mx(a,this._parents,t,n)}function TQn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Vkt(e));for(var r=this._groups,s=r.length,a=[],i=[],l=0;l<s;++l)for(var c=r[l],u=c.length,d,f=0;f<u;++f)if(d=c[f]){for(var p=e.call(d,d.__data__,f,c),h,m=ev(d,n),v=0,y=p.length;v<y;++v)(h=p[v])&&lW(h,t,n,v,p,m);a.push(p),i.push(d)}return new Mx(a,i,t,n)}var jQn=Y3.prototype.constructor;function NQn(){return new jQn(this._groups,this._parents)}function IQn(e,t){var n,r,s;return function(){var a=tN(this,e),i=(this.style.removeProperty(e),tN(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function mOt(e){return function(){this.style.removeProperty(e)}}function AQn(e,t,n){var r,s=n+"",a;return function(){var i=tN(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function RQn(e,t,n){var r,s,a;return function(){var i=tN(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),tN(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function PQn(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=zy(this,e),u=c.on,d=c.value[a]==null?l||(l=mOt(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function $Qn(e,t,n){var r=(e+="")=="transform"?$Gn:hOt;return t==null?this.styleTween(e,IQn(e,r)).on("end.style."+e,mOt(e)):typeof t=="function"?this.styleTween(e,RQn(e,r,gOe(this,"style."+e,t))).each(PQn(this._id,e)):this.styleTween(e,AQn(e,r,t),n).on("end.style."+e,null)}function MQn(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function DQn(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&MQn(e,i,n)),r}return a._value=t,a}function LQn(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,DQn(e,t,n??""))}function FQn(e){return function(){this.textContent=e}}function zQn(e){return function(){var t=e(this);this.textContent=t??""}}function BQn(e){return this.tween("text",typeof e=="function"?zQn(gOe(this,"text",e)):FQn(e==null?"":e+""))}function UQn(e){return function(t){this.textContent=e.call(this,t)}}function qQn(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&UQn(s)),t}return r._value=e,r}function VQn(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,qQn(e))}function HQn(){for(var e=this._name,t=this._id,n=gOt(),r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)if(c=i[u]){var d=ev(c,t);lW(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new Mx(r,this._parents,e,n)}function WQn(){var e,t,n=this,r=n._id,s=n.size();return new Promise(function(a,i){var l={value:i},c={value:function(){--s===0&&a()}};n.each(function(){var u=zy(this,r),d=u.on;d!==e&&(t=(e=d).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(c)),u.on=t}),s===0&&a()})}var ZQn=0;function Mx(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function gOt(){return++ZQn}var Sb=Y3.prototype;Mx.prototype={constructor:Mx,select:EQn,selectAll:TQn,selectChild:Sb.selectChild,selectChildren:Sb.selectChildren,filter:xQn,merge:wQn,selection:NQn,transition:HQn,call:Sb.call,nodes:Sb.nodes,node:Sb.node,size:Sb.size,empty:Sb.empty,each:Sb.each,on:OQn,attr:sQn,attrTween:cQn,style:$Qn,styleTween:LQn,text:BQn,textTween:VQn,remove:CQn,tween:KGn,delay:fQn,duration:mQn,ease:vQn,easeVarying:bQn,end:WQn,[Symbol.iterator]:Sb[Symbol.iterator]};function GQn(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var QQn={time:null,delay:0,duration:250,ease:GQn};function YQn(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 KQn(e){var t,n;e instanceof Mx?(t=e._id,e=e._name):(t=gOt(),(n=QQn).time=hOe(),e=e==null?null:e+"");for(var r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&lW(c,e,t,u,i,n||YQn(c,t));return new Mx(r,this._parents,e,t)}Y3.prototype.interrupt=GGn;Y3.prototype.transition=KQn;const bF=e=>()=>e;function XQn(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 nx(e,t,n){this.k=e,this.x=t,this.y=n}nx.prototype={constructor:nx,scale:function(e){return e===1?this:new nx(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new nx(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 cW=new nx(1,0,0);vOt.prototype=nx.prototype;function vOt(e){for(;!e.__zoom;)if(!(e=e.parentNode))return cW;return e.__zoom}function Jte(e){e.stopImmediatePropagation()}function PR(e){e.preventDefault(),e.stopImmediatePropagation()}function JQn(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function eYn(){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 T7e(){return this.__zoom||cW}function tYn(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function nYn(){return navigator.maxTouchPoints||"ontouchstart"in this}function rYn(e,t,n){var r=e.invertX(t[0][0])-n[0][0],s=e.invertX(t[1][0])-n[1][0],a=e.invertY(t[0][1])-n[0][1],i=e.invertY(t[1][1])-n[1][1];return e.translate(s>r?(r+s)/2:Math.min(0,r)||Math.max(0,s),i>a?(a+i)/2:Math.min(0,a)||Math.max(0,i))}function yOt(){var e=JQn,t=eYn,n=rYn,r=tYn,s=nYn,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=W8,u=aW("start","zoom","end"),d,f,p,h=500,m=150,v=0,y=10;function b(D){D.property("__zoom",T7e).on("wheel.zoom",E,{passive:!1}).on("mousedown.zoom",N).on("dblclick.zoom",I).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",R).on("touchend.zoom touchcancel.zoom",L).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(D,F,H,B){var z=D.selection?D.selection():D;z.property("__zoom",T7e),D!==z?_(D,F,H,B):z.interrupt().each(function(){C(this,arguments).event(B).start().zoom(null,typeof F=="function"?F.apply(this,arguments):F).end()})},b.scaleBy=function(D,F,H,B){b.scaleTo(D,function(){var z=this.__zoom.k,V=typeof F=="function"?F.apply(this,arguments):F;return z*V},H,B)},b.scaleTo=function(D,F,H,B){b.transform(D,function(){var z=t.apply(this,arguments),V=this.__zoom,M=H==null?k(z):typeof H=="function"?H.apply(this,arguments):H,G=V.invert(M),U=typeof F=="function"?F.apply(this,arguments):F;return n(S(x(V,U),M,G),z,i)},H,B)},b.translateBy=function(D,F,H,B){b.transform(D,function(){return n(this.__zoom.translate(typeof F=="function"?F.apply(this,arguments):F,typeof H=="function"?H.apply(this,arguments):H),t.apply(this,arguments),i)},null,B)},b.translateTo=function(D,F,H,B,z){b.transform(D,function(){var V=t.apply(this,arguments),M=this.__zoom,G=B==null?k(V):typeof B=="function"?B.apply(this,arguments):B;return n(cW.translate(G[0],G[1]).scale(M.k).translate(typeof F=="function"?-F.apply(this,arguments):-F,typeof H=="function"?-H.apply(this,arguments):-H),V,i)},B,z)};function x(D,F){return F=Math.max(a[0],Math.min(a[1],F)),F===D.k?D:new nx(F,D.x,D.y)}function S(D,F,H){var B=F[0]-H[0]*D.k,z=F[1]-H[1]*D.k;return B===D.x&&z===D.y?D:new nx(D.k,B,z)}function k(D){return[(+D[0][0]+ +D[1][0])/2,(+D[0][1]+ +D[1][1])/2]}function _(D,F,H,B){D.on("start.zoom",function(){C(this,arguments).event(B).start()}).on("interrupt.zoom end.zoom",function(){C(this,arguments).event(B).end()}).tween("zoom",function(){var z=this,V=arguments,M=C(z,V).event(B),G=t.apply(z,V),U=H==null?k(G):typeof H=="function"?H.apply(z,V):H,$=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),q=z.__zoom,Z=typeof F=="function"?F.apply(z,V):F,Y=c(q.invert(U).concat($/q.k),Z.invert(U).concat($/Z.k));return function(ne){if(ne===1)ne=Z;else{var J=Y(ne),ee=$/J[2];ne=new nx(ee,U[0]-J[0]*ee,U[1]-J[1]*ee)}M.zoom(null,ne)}})}function C(D,F,H){return!H&&D.__zooming||new T(D,F)}function T(D,F){this.that=D,this.args=F,this.active=0,this.sourceEvent=null,this.extent=t.apply(D,F),this.taps=0}T.prototype={event:function(D){return D&&(this.sourceEvent=D),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(D,F){return this.mouse&&D!=="mouse"&&(this.mouse[1]=F.invert(this.mouse[0])),this.touch0&&D!=="touch"&&(this.touch0[1]=F.invert(this.touch0[0])),this.touch1&&D!=="touch"&&(this.touch1[1]=F.invert(this.touch1[0])),this.that.__zoom=F,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(D){var F=Cp(this.that).datum();u.call(D,this.that,new XQn(D,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),F)}};function E(D,...F){if(!e.apply(this,arguments))return;var H=C(this,F).event(D),B=this.__zoom,z=Math.max(a[0],Math.min(a[1],B.k*Math.pow(2,r.apply(this,arguments)))),V=fg(D);if(H.wheel)(H.mouse[0][0]!==V[0]||H.mouse[0][1]!==V[1])&&(H.mouse[1]=B.invert(H.mouse[0]=V)),clearTimeout(H.wheel);else{if(B.k===z)return;H.mouse=[V,B.invert(V)],Q8(this),H.start()}PR(D),H.wheel=setTimeout(M,m),H.zoom("mouse",n(S(x(B,z),H.mouse[0],H.mouse[1]),H.extent,i));function M(){H.wheel=null,H.end()}}function N(D,...F){if(p||!e.apply(this,arguments))return;var H=D.currentTarget,B=C(this,F,!0).event(D),z=Cp(D.view).on("mousemove.zoom",U,!0).on("mouseup.zoom",$,!0),V=fg(D,H),M=D.clientX,G=D.clientY;tOt(D.view),Jte(D),B.mouse=[V,this.__zoom.invert(V)],Q8(this),B.start();function U(q){if(PR(q),!B.moved){var Z=q.clientX-M,Y=q.clientY-G;B.moved=Z*Z+Y*Y>v}B.event(q).zoom("mouse",n(S(B.that.__zoom,B.mouse[0]=fg(q,H),B.mouse[1]),B.extent,i))}function $(q){z.on("mousemove.zoom mouseup.zoom",null),nOt(q.view,B.moved),PR(q),B.event(q).end()}}function I(D,...F){if(e.apply(this,arguments)){var H=this.__zoom,B=fg(D.changedTouches?D.changedTouches[0]:D,this),z=H.invert(B),V=H.k*(D.shiftKey?.5:2),M=n(S(x(H,V),B,z),t.apply(this,F),i);PR(D),l>0?Cp(this).transition().duration(l).call(_,M,B,D):Cp(this).call(b.transform,M,B,D)}}function A(D,...F){if(e.apply(this,arguments)){var H=D.touches,B=H.length,z=C(this,F,D.changedTouches.length===B).event(D),V,M,G,U;for(Jte(D),M=0;M<B;++M)G=H[M],U=fg(G,this),U=[U,this.__zoom.invert(U),G.identifier],z.touch0?!z.touch1&&z.touch0[2]!==U[2]&&(z.touch1=U,z.taps=0):(z.touch0=U,V=!0,z.taps=1+!!d);d&&(d=clearTimeout(d)),V&&(z.taps<2&&(f=U[0],d=setTimeout(function(){d=null},h)),Q8(this),z.start())}}function R(D,...F){if(this.__zooming){var H=C(this,F).event(D),B=D.changedTouches,z=B.length,V,M,G,U;for(PR(D),V=0;V<z;++V)M=B[V],G=fg(M,this),H.touch0&&H.touch0[2]===M.identifier?H.touch0[0]=G:H.touch1&&H.touch1[2]===M.identifier&&(H.touch1[0]=G);if(M=H.that.__zoom,H.touch1){var $=H.touch0[0],q=H.touch0[1],Z=H.touch1[0],Y=H.touch1[1],ne=(ne=Z[0]-$[0])*ne+(ne=Z[1]-$[1])*ne,J=(J=Y[0]-q[0])*J+(J=Y[1]-q[1])*J;M=x(M,Math.sqrt(ne/J)),G=[($[0]+Z[0])/2,($[1]+Z[1])/2],U=[(q[0]+Y[0])/2,(q[1]+Y[1])/2]}else if(H.touch0)G=H.touch0[0],U=H.touch0[1];else return;H.zoom("touch",n(S(M,G,U),H.extent,i))}}function L(D,...F){if(this.__zooming){var H=C(this,F).event(D),B=D.changedTouches,z=B.length,V,M;for(Jte(D),p&&clearTimeout(p),p=setTimeout(function(){p=null},h),V=0;V<z;++V)M=B[V],H.touch0&&H.touch0[2]===M.identifier?delete H.touch0:H.touch1&&H.touch1[2]===M.identifier&&delete H.touch1;if(H.touch1&&!H.touch0&&(H.touch0=H.touch1,delete H.touch1),H.touch0)H.touch0[1]=this.__zoom.invert(H.touch0[0]);else if(H.end(),H.taps===2&&(M=fg(M,this),Math.hypot(f[0]-M[0],f[1]-M[1])<y)){var G=Cp(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(D){return arguments.length?(r=typeof D=="function"?D:bF(+D),b):r},b.filter=function(D){return arguments.length?(e=typeof D=="function"?D:bF(!!D),b):e},b.touchable=function(D){return arguments.length?(s=typeof D=="function"?D:bF(!!D),b):s},b.extent=function(D){return arguments.length?(t=typeof D=="function"?D:bF([[+D[0][0],+D[0][1]],[+D[1][0],+D[1][1]]]),b):t},b.scaleExtent=function(D){return arguments.length?(a[0]=+D[0],a[1]=+D[1],b):[a[0],a[1]]},b.translateExtent=function(D){return arguments.length?(i[0][0]=+D[0][0],i[1][0]=+D[1][0],i[0][1]=+D[0][1],i[1][1]=+D[1][1],b):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},b.constrain=function(D){return arguments.length?(n=D,b):n},b.duration=function(D){return arguments.length?(l=+D,b):l},b.interpolate=function(D){return arguments.length?(c=D,b):c},b.on=function(){var D=u.on.apply(u,arguments);return D===u?b:D},b.clickDistance=function(D){return arguments.length?(v=(D=+D)*D,b):Math.sqrt(v)},b.tapDistance=function(D){return arguments.length?(y=+D,b):y},b}const ky={error001:()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>"The React Flow parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,{id:t,sourceHandle:n,targetHandle:r})=>`Couldn't create edge for ${e} handle id: "${e==="source"?n:r}", edge id: ${t}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(e="react")=>`It seems that you haven't loaded the styles. Please import '@xyflow/${e}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>"useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.",error015:()=>"It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs."},$M=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],bOt=["Enter"," ","Escape"],xOt={"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 rN;(function(e){e.Strict="strict",e.Loose="loose"})(rN||(rN={}));var rO;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(rO||(rO={}));var MM;(function(e){e.Partial="partial",e.Full="full"})(MM||(MM={}));const wOt={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var kw;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(kw||(kw={}));var DM;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(DM||(DM={}));var tr;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(tr||(tr={}));const j7e={[tr.Left]:tr.Right,[tr.Right]:tr.Left,[tr.Top]:tr.Bottom,[tr.Bottom]:tr.Top};function SOt(e){return e===null?null:e?"valid":"invalid"}const kOt=e=>"id"in e&&"source"in e&&"target"in e,sYn=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),vOe=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),X3=(e,t=[0,0])=>{const{width:n,height:r}=a0(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},aYn=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,s)=>{const a=typeof s=="string";let i=!t.nodeLookup&&!a?s:void 0;t.nodeLookup&&(i=a?t.nodeLookup.get(s):vOe(s)?s:t.nodeLookup.get(s.id));const l=i?tU(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return uW(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return dW(n)},J3=(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=uW(n,tU(s)),r=!0)}),r?dW(n):{x:0,y:0,width:0,height:0}},yOe=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...t4(t,[n,r,s]),width:t.width/s,height:t.height/s},c=[];for(const u of e.values()){const{measured:d,selectable:f=!0,hidden:p=!1}=u;if(i&&!f||p)continue;const h=d.width??u.width??u.initialWidth??null,m=d.height??u.height??u.initialHeight??null,v=LM(l,aN(u)),y=(h??0)*(m??0),b=a&&v>0;(!u.internals.handleBounds||b||v>=y||u.dragging)&&c.push(u)}return c},iYn=(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 oYn(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 lYn({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=oYn(e,i),c=J3(l),u=bOe(c,t,n,i?.minZoom??s,i?.maxZoom??a,i?.padding??.1);return await r.setViewport(u,{duration:i?.duration,ease:i?.ease,interpolate:i?.interpolate}),Promise.resolve(!0)}function OOt({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:s,onError:a}){const i=n.get(e),l=i.parentId?n.get(i.parentId):void 0,{x:c,y:u}=l?l.internals.positionAbsolute:{x:0,y:0},d=i.origin??r;let f=i.extent||s;if(i.extent==="parent"&&!i.expandParent)if(!l)a?.("005",ky.error005());else{const h=l.measured.width,m=l.measured.height;h&&m&&(f=[[c,u],[c+h,u+m]])}else l&&iN(i.extent)&&(f=[[i.extent[0][0]+c,i.extent[0][1]+u],[i.extent[1][0]+c,i.extent[1][1]+u]]);const p=iN(f)?KO(t,f,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&a?.("015",ky.error015()),{position:{x:p.x-c+(i.measured.width??0)*d[0],y:p.y-u+(i.measured.height??0)*d[1]},positionAbsolute:p}}async function cYn({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const a=new Set(e.map(p=>p.id)),i=[];for(const p of n){if(p.deletable===!1)continue;const h=a.has(p.id),m=!h&&p.parentId&&i.find(v=>v.id===p.parentId);(h||m)&&i.push(p)}const l=new Set(t.map(p=>p.id)),c=r.filter(p=>p.deletable!==!1),d=iYn(i,c);for(const p of c)l.has(p.id)&&!d.find(m=>m.id===p.id)&&d.push(p);if(!s)return{edges:d,nodes:i};const f=await s({nodes:i,edges:d});return typeof f=="boolean"?f?{edges:d,nodes:i}:{edges:[],nodes:[]}:f}const sN=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),KO=(e={x:0,y:0},t,n)=>({x:sN(e.x,t[0][0],t[1][0]-(n?.width??0)),y:sN(e.y,t[0][1],t[1][1]-(n?.height??0))});function _Ot(e,t,n){const{width:r,height:s}=a0(n),{x:a,y:i}=n.internals.positionAbsolute;return KO(e,[[a,i],[a+r,i+s]],t)}const N7e=(e,t,n)=>e<t?sN(Math.abs(e-t),1,t)/t:e>n?-sN(Math.abs(e-n),1,t)/t:0,COt=(e,t,n=15,r=40)=>{const s=N7e(e.x,r,t.width-r)*n,a=N7e(e.y,r,t.height-r)*n;return[s,a]},uW=(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)}),hve=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),dW=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),aN=(e,t=[0,0])=>{const{x:n,y:r}=vOe(e)?e.internals.positionAbsolute:X3(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}},tU=(e,t=[0,0])=>{const{x:n,y:r}=vOe(e)?e.internals.positionAbsolute:X3(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)}},EOt=(e,t)=>dW(uW(hve(e),hve(t))),LM=(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)},I7e=e=>_g(e.width)&&_g(e.height)&&_g(e.x)&&_g(e.y),_g=e=>!isNaN(e)&&isFinite(e),uYn=(e,t)=>{},e4=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),t4=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?e4(l,i):l},nU=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function vE(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 dYn(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=vE(e,n),s=vE(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=vE(e.top??e.y??0,n),s=vE(e.bottom??e.y??0,n),a=vE(e.left??e.x??0,t),i=vE(e.right??e.x??0,t);return{top:r,right:i,bottom:s,left:a,x:a+i,y:r+s}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function fYn(e,t,n,r,s,a){const{x:i,y:l}=nU(e,[t,n,r]),{x:c,y:u}=nU({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=s-c,f=a-u;return{left:Math.floor(i),top:Math.floor(l),right:Math.floor(d),bottom:Math.floor(f)}}const bOe=(e,t,n,r,s,a)=>{const i=dYn(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=sN(u,r,s),f=e.x+e.width/2,p=e.y+e.height/2,h=t/2-f*d,m=n/2-p*d,v=fYn(e,h,m,d,t,n),y={left:Math.min(v.left-i.left,0),top:Math.min(v.top-i.top,0),right:Math.min(v.right-i.right,0),bottom:Math.min(v.bottom-i.bottom,0)};return{x:h-y.left+y.right,y:m-y.top+y.bottom,zoom:d}},FM=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function iN(e){return e!=null&&e!=="parent"}function a0(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function TOt(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function jOt(e,t={width:0,height:0},n,r,s){const a={...e},i=r.get(n);if(i){const l=i.origin||s;a.x+=i.internals.positionAbsolute.x-(t.width??0)*l[0],a.y+=i.internals.positionAbsolute.y-(t.height??0)*l[1]}return a}function A7e(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function pYn(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function hYn(e){return{...xOt,...e||{}}}function R$(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=Cg(e),l=t4({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?e4(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const xOe=e=>({width:e.offsetWidth,height:e.offsetHeight}),NOt=e=>e?.getRootNode?.()||window?.document,mYn=["INPUT","SELECT","TEXTAREA"];function IOt(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:mYn.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const AOt=e=>"clientX"in e,Cg=(e,t)=>{const n=AOt(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)}},R7e=(e,t,n,r,s)=>{const a=t.querySelectorAll(`.${e}`);return!a||!a.length?null:Array.from(a).map(i=>{const l=i.getBoundingClientRect();return{id:i.getAttribute("data-handleid"),type:e,nodeId:s,position:i.getAttribute("data-handlepos"),x:(l.left-n.left)/r,y:(l.top-n.top)/r,...xOe(i)}})};function ROt({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:s,sourceControlY:a,targetControlX:i,targetControlY:l}){const c=e*.125+s*.375+i*.375+n*.125,u=t*.125+a*.375+l*.375+r*.125,d=Math.abs(c-e),f=Math.abs(u-t);return[c,u,d,f]}function xF(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function P7e({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case tr.Left:return[t-xF(t-r,a),n];case tr.Right:return[t+xF(r-t,a),n];case tr.Top:return[t,n-xF(n-s,a)];case tr.Bottom:return[t,n+xF(s-n,a)]}}function wOe({sourceX:e,sourceY:t,sourcePosition:n=tr.Bottom,targetX:r,targetY:s,targetPosition:a=tr.Top,curvature:i=.25}){const[l,c]=P7e({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=P7e({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,p,h,m]=ROt({sourceX:e,sourceY:t,targetX:r,targetY:s,sourceControlX:l,sourceControlY:c,targetControlX:u,targetControlY:d});return[`M${e},${t} C${l},${c} ${u},${d} ${r},${s}`,f,p,h,m]}function POt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const s=Math.abs(n-e)/2,a=n<e?n+s:n-s,i=Math.abs(r-t)/2,l=r<t?r+i:r-i;return[a,l,s,i]}function gYn({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:s=!1,zIndexMode:a="basic"}){if(a==="manual")return r;const i=s&&n?r+1e3:r,l=Math.max(e.parentId||s&&e.selected?e.internals.z:0,t.parentId||s&&t.selected?t.internals.z:0);return i+l}function vYn({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=uW(tU(e),tU(t));a.x===a.x2&&(a.x2+=1),a.y===a.y2&&(a.y2+=1);const i={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:r/s[2]};return LM(i,dW(a))>0}const yYn=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,bYn=(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)),xYn=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||yYn;let s;return kOt(e)?s={...e}:s={...e,id:r(e)},bYn(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function $Ot({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=POt({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const $7e={[tr.Left]:{x:-1,y:0},[tr.Right]:{x:1,y:0},[tr.Top]:{x:0,y:-1},[tr.Bottom]:{x:0,y:1}},wYn=({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},M7e=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function SYn({source:e,sourcePosition:t=tr.Bottom,target:n,targetPosition:r=tr.Top,center:s,offset:a,stepPosition:i}){const l=$7e[t],c=$7e[r],u={x:e.x+l.x*a,y:e.y+l.y*a},d={x:n.x+c.x*a,y:n.y+c.y*a},f=wYn({source:u,sourcePosition:t,target:d}),p=f.x!==0?"x":"y",h=f[p];let m=[],v,y;const b={x:0,y:0},x={x:0,y:0},[,,S,k]=POt({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[p]*c[p]===-1){p==="x"?(v=s.x??u.x+(d.x-u.x)*i,y=s.y??(u.y+d.y)/2):(v=s.x??(u.x+d.x)/2,y=s.y??u.y+(d.y-u.y)*i);const E=[{x:v,y:u.y},{x:v,y:d.y}],N=[{x:u.x,y},{x:d.x,y}];l[p]===h?m=p==="x"?E:N:m=p==="x"?N:E}else{const E=[{x:u.x,y:d.y}],N=[{x:d.x,y:u.y}];if(p==="x"?m=l.x===h?N:E:m=l.y===h?E:N,t===r){const D=Math.abs(e[p]-n[p]);if(D<=a){const F=Math.min(a-1,a-D);l[p]===h?b[p]=(u[p]>e[p]?-1:1)*F:x[p]=(d[p]>n[p]?-1:1)*F}}if(t!==r){const D=p==="x"?"y":"x",F=l[p]===c[D],H=u[D]>d[D],B=u[D]<d[D];(l[p]===1&&(!F&&H||F&&B)||l[p]!==1&&(!F&&B||F&&H))&&(m=p==="x"?E:N)}const I={x:u.x+b.x,y:u.y+b.y},A={x:d.x+x.x,y:d.y+x.y},R=Math.max(Math.abs(I.x-m[0].x),Math.abs(A.x-m[0].x)),L=Math.max(Math.abs(I.y-m[0].y),Math.abs(A.y-m[0].y));R>=L?(v=(I.x+A.x)/2,y=m[0].y):(v=m[0].x,y=(I.y+A.y)/2)}const _={x:u.x+b.x,y:u.y+b.y},C={x:d.x+x.x,y:d.y+x.y};return[[e,..._.x!==m[0].x||_.y!==m[0].y?[_]:[],...m,...C.x!==m[m.length-1].x||C.y!==m[m.length-1].y?[C]:[],n],v,y,S,k]}function kYn(e,t,n,r){const s=Math.min(M7e(e,t)/2,M7e(t,n)/2,r),{x:a,y:i}=t;if(e.x===a&&a===n.x||e.y===i&&i===n.y)return`L${a} ${i}`;if(e.y===i){const u=e.x<n.x?-1:1,d=e.y<n.y?1:-1;return`L ${a+s*u},${i}Q ${a},${i} ${a},${i+s*d}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${a},${i+s*c}Q ${a},${i} ${a+s*l},${i}`}function mve({sourceX:e,sourceY:t,sourcePosition:n=tr.Bottom,targetX:r,targetY:s,targetPosition:a=tr.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,p,h,m,v]=SYn({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:s},targetPosition:a,center:{x:l,y:c},offset:u,stepPosition:d});let y=`M${f[0].x} ${f[0].y}`;for(let b=1;b<f.length-1;b++)y+=kYn(f[b-1],f[b],f[b+1],i);return y+=`L${f[f.length-1].x} ${f[f.length-1].y}`,[y,p,h,m,v]}function D7e(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function OYn(e){const{sourceNode:t,targetNode:n}=e;if(!D7e(t)||!D7e(n))return null;const r=t.internals.handleBounds||L7e(t.handles),s=n.internals.handleBounds||L7e(n.handles),a=F7e(r?.source??[],e.sourceHandle),i=F7e(e.connectionMode===rN.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!a||!i)return e.onError?.("008",ky.error008(a?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=a?.position||tr.Bottom,c=i?.position||tr.Top,u=XO(t,a,l),d=XO(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function L7e(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 XO(e,t,n=tr.Left,r=!1){const s=(t?.x??0)+e.internals.positionAbsolute.x,a=(t?.y??0)+e.internals.positionAbsolute.y,{width:i,height:l}=t??a0(e);if(r)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case tr.Top:return{x:s+i/2,y:a};case tr.Right:return{x:s+i,y:a+l/2};case tr.Bottom:return{x:s+i/2,y:a+l};case tr.Left:return{x:s,y:a+l/2}}}function F7e(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function gve(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function _Yn(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:s}){const a=new Set;return e.reduce((i,l)=>([l.markerStart||r,l.markerEnd||s].forEach(c=>{if(c&&typeof c=="object"){const u=gve(c,t);a.has(u)||(i.push({id:u,color:c.color||n,...c}),a.add(u))}}),i),[]).sort((i,l)=>i.id.localeCompare(l.id))}const MOt=1e3,CYn=10,SOe={nodeOrigin:[0,0],nodeExtent:$M,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},EYn={...SOe,checkEquality:!0};function kOe(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function TYn(e,t,n){const r=kOe(SOe,n);for(const s of e.values())if(s.parentId)_Oe(s,e,t,r);else{const a=X3(s,r.nodeOrigin),i=iN(s.extent)?s.extent:r.nodeExtent,l=KO(a,i,a0(s));s.internals.positionAbsolute=l}}function jYn(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;const n=[],r=[];for(const s of e.handles){const a={id:s.id,width:s.width??1,height:s.height??1,nodeId:e.id,x:s.x,y:s.y,position:s.position,type:s.type};s.type==="source"?n.push(a):s.type==="target"&&r.push(a)}return{source:n,target:r}}function OOe(e){return e==="manual"}function vve(e,t,n,r={}){const s=kOe(EYn,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!OOe(s.zIndexMode)?MOt:0;let c=e.length>0,u=!1;t.clear(),n.clear();for(const d of e){let f=i.get(d.id);if(s.checkEquality&&d===f?.internals.userNode)t.set(d.id,f);else{const p=X3(d,s.nodeOrigin),h=iN(d.extent)?d.extent:s.nodeExtent,m=KO(p,h,a0(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:jYn(d,f),z:DOt(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&&_Oe(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function NYn(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 _Oe(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=kOe(SOe,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}NYn(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*CYn),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!OOe(c)?MOt:0,{x:p,y:h,z:m}=IYn(e,d,i,l,f,c),{positionAbsolute:v}=e.internals,y=p!==v.x||h!==v.y;(y||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:p,y:h}:v,z:m}})}function DOt(e,t,n){const r=_g(e.zIndex)?e.zIndex:0;return OOe(n)?r:r+(e.selected?t:0)}function IYn(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=a0(e),u=X3(e,n),d=iN(e.extent)?KO(u,e.extent,c):u;let f=KO({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=_Ot(f,c,t));const p=DOt(e,s,a),h=t.internals.z??0;return{x:f.x,y:f.y,z:h>=p?h+1:p}}function COe(e,t,n,r=[0,0]){const s=[],a=new Map;for(const i of e){const l=t.get(i.parentId);if(!l)continue;const c=a.get(i.parentId)?.expandedRect??aN(l),u=EOt(c,i.rect);a.set(i.parentId,{expandedRect:u,parent:l})}return a.size>0&&a.forEach(({expandedRect:i,parent:l},c)=>{const u=l.internals.positionAbsolute,d=a0(l),f=l.origin??r,p=i.x<u.x?Math.round(Math.abs(u.x-i.x)):0,h=i.y<u.y?Math.round(Math.abs(u.y-i.y)):0,m=Math.max(d.width,Math.round(i.width)),v=Math.max(d.height,Math.round(i.height)),y=(m-d.width)*f[0],b=(v-d.height)*f[1];(p>0||h>0||y||b)&&(s.push({id:c,type:"position",position:{x:l.position.x-p+y,y:l.position.y-h+b}}),n.get(c)?.forEach(x=>{e.some(S=>S.id===x.id)||s.push({id:x.id,type:"position",position:{x:x.position.x+p,y:x.position.y+h}})})),(d.width<i.width||d.height<i.height||p||h)&&s.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:m+(p?f[0]*p-y:0),height:v+(h?f[1]*h-b:0)}})}),s}function AYn(e,t,n,r,s,a,i){const l=r?.querySelector(".xyflow__viewport");let c=!1;if(!l)return{changes:[],updatedInternals:c};const u=[],d=window.getComputedStyle(l),{m22:f}=new window.DOMMatrixReadOnly(d.transform),p=[];for(const h of e.values()){const m=t.get(h.id);if(!m)continue;if(m.hidden){t.set(m.id,{...m,internals:{...m.internals,handleBounds:void 0}}),c=!0;continue}const v=xOe(h.nodeElement),y=m.measured.width!==v.width||m.measured.height!==v.height;if(!!(v.width&&v.height&&(y||!m.internals.handleBounds||h.force))){const x=h.nodeElement.getBoundingClientRect(),S=iN(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=_Ot(k,v,t.get(m.parentId)):S&&(k=KO(k,S,v));const _={...m,measured:v,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:R7e("source",h.nodeElement,x,f,m.id),target:R7e("target",h.nodeElement,x,f,m.id)}}};t.set(m.id,_),m.parentId&&_Oe(_,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,y&&(u.push({id:m.id,type:"dimensions",dimensions:v}),m.expandParent&&m.parentId&&p.push({id:m.id,parentId:m.parentId,rect:aN(_,s)}))}}if(p.length>0){const h=COe(p,t,n,s);u.push(...h)}return{changes:u,updatedInternals:c}}async function RYn({delta:e,panZoom:t,transform:n,translateExtent:r,width:s,height:a}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const i=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[s,a]],r),l=!!i&&(i.x!==n[0]||i.y!==n[1]||i.k!==n[2]);return Promise.resolve(l)}function z7e(e,t,n,r,s,a){let i=s;const l=r.get(i)||new Map;r.set(i,l.set(n,t)),i=`${s}-${e}`;const c=r.get(i)||new Map;if(r.set(i,c.set(n,t)),a){i=`${s}-${e}-${a}`;const u=r.get(i)||new Map;r.set(i,u.set(n,t))}}function LOt(e,t,n){e.clear(),t.clear();for(const r of n){const{source:s,target:a,sourceHandle:i=null,targetHandle:l=null}=r,c={edgeId:r.id,source:s,target:a,sourceHandle:i,targetHandle:l},u=`${s}-${i}--${a}-${l}`,d=`${a}-${l}--${s}-${i}`;z7e("source",c,d,e,s,i),z7e("target",c,u,e,a,l),t.set(r.id,r)}}function FOt(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:FOt(n,t):!1}function B7e(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 PYn(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!FOt(i,e))&&(i.draggable||t&&typeof i.draggable>"u")){const l=e.get(a);l&&s.set(a,{id:a,position:l.position||{x:0,y:0},distance:{x:n.x-l.internals.positionAbsolute.x,y:n.y-l.internals.positionAbsolute.y},extent:l.extent,parentId:l.parentId,origin:l.origin,expandParent:l.expandParent,internals:{positionAbsolute:l.internals.positionAbsolute||{x:0,y:0}},measured:{width:l.measured.width??0,height:l.measured.height??0}})}return s}function ene({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){const s=[];for(const[i,l]of t){const c=n.get(i)?.internals.userNode;c&&s.push({...c,position:l.position,dragging:r})}if(!e)return[s[0],s];const a=n.get(e)?.internals.userNode;return[a?{...a,position:t.get(e)?.position||a.position,dragging:r}:s[0],s]}function $Yn({dragItems:e,snapGrid:t,x:n,y:r}){const s=e.values().next().value;if(!s)return null;const a={x:n-s.distance.x,y:r-s.distance.y},i=e4(a,t);return{x:i.x-a.x,y:i.y-a.y}}function MYn({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:s}){let a={x:null,y:null},i=0,l=new Map,c=!1,u={x:0,y:0},d=null,f=!1,p=null,h=!1,m=!1,v=null;function y({noDragClassName:x,handleSelector:S,domNode:k,isSelectable:_,nodeId:C,nodeClickDistance:T=0}){p=Cp(k);function E({x:R,y:L}){const{nodeLookup:D,nodeExtent:F,snapGrid:H,snapToGrid:B,nodeOrigin:z,onNodeDrag:V,onSelectionDrag:M,onError:G,updateNodePositions:U}=t();a={x:R,y:L};let $=!1;const q=l.size>1,Z=q&&F?hve(J3(l)):null,Y=q&&B?$Yn({dragItems:l,snapGrid:H,x:R,y:L}):null;for(const[ne,J]of l){if(!D.has(ne))continue;let ee={x:R-J.distance.x,y:L-J.distance.y};B&&(ee=Y?{x:Math.round(ee.x+Y.x),y:Math.round(ee.y+Y.y)}:e4(ee,H));let re=null;if(q&&F&&!J.extent&&Z){const{positionAbsolute:te}=J.internals,se=te.x-Z.x+F[0][0],pe=te.x+J.measured.width-Z.x2+F[1][0],ce=te.y-Z.y+F[0][1],Se=te.y+J.measured.height-Z.y2+F[1][1];re=[[se,ce],[pe,Se]]}const{position:le,positionAbsolute:X}=OOt({nodeId:ne,nextPosition:ee,nodeLookup:D,nodeExtent:re||F,nodeOrigin:z,onError:G});$=$||J.position.x!==le.x||J.position.y!==le.y,J.position=le,J.internals.positionAbsolute=X}if(m=m||$,!!$&&(U(l,!0),v&&(r||V||!C&&M))){const[ne,J]=ene({nodeId:C,dragItems:l,nodeLookup:D});r?.(v,l,ne,J),V?.(v,ne,J),C||M?.(v,J)}}async function N(){if(!d)return;const{transform:R,panBy:L,autoPanSpeed:D,autoPanOnNodeDrag:F}=t();if(!F){c=!1,cancelAnimationFrame(i);return}const[H,B]=COt(u,d,D);(H!==0||B!==0)&&(a.x=(a.x??0)-H/R[2],a.y=(a.y??0)-B/R[2],await L({x:H,y:B})&&E(a)),i=requestAnimationFrame(N)}function I(R){const{nodeLookup:L,multiSelectionActive:D,nodesDraggable:F,transform:H,snapGrid:B,snapToGrid:z,selectNodesOnDrag:V,onNodeDragStart:M,onSelectionDragStart:G,unselectNodesAndEdges:U}=t();f=!0,(!V||!_)&&!D&&C&&(L.get(C)?.selected||U()),_&&V&&C&&e?.(C);const $=R$(R.sourceEvent,{transform:H,snapGrid:B,snapToGrid:z,containerBounds:d});if(a=$,l=PYn(L,F,$,C),l.size>0&&(n||M||!C&&G)){const[q,Z]=ene({nodeId:C,dragItems:l,nodeLookup:L});n?.(R.sourceEvent,l,q,Z),M?.(R.sourceEvent,q,Z),C||G?.(R.sourceEvent,Z)}}const A=rOt().clickDistance(T).on("start",R=>{const{domNode:L,nodeDragThreshold:D,transform:F,snapGrid:H,snapToGrid:B}=t();d=L?.getBoundingClientRect()||null,h=!1,m=!1,v=R.sourceEvent,D===0&&I(R),a=R$(R.sourceEvent,{transform:F,snapGrid:H,snapToGrid:B,containerBounds:d}),u=Cg(R.sourceEvent,d)}).on("drag",R=>{const{autoPanOnNodeDrag:L,transform:D,snapGrid:F,snapToGrid:H,nodeDragThreshold:B,nodeLookup:z}=t(),V=R$(R.sourceEvent,{transform:D,snapGrid:F,snapToGrid:H,containerBounds:d});if(v=R.sourceEvent,(R.sourceEvent.type==="touchmove"&&R.sourceEvent.touches.length>1||C&&!z.has(C))&&(h=!0),!h){if(!c&&L&&f&&(c=!0,N()),!f){const M=Cg(R.sourceEvent,d),G=M.x-u.x,U=M.y-u.y;Math.sqrt(G*G+U*U)>B&&I(R)}(a.x!==V.xSnapped||a.y!==V.ySnapped)&&l&&f&&(u=Cg(R.sourceEvent,d),E(V))}}).on("end",R=>{if(!(!f||h)&&(c=!1,f=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:L,updateNodePositions:D,onNodeDragStop:F,onSelectionDragStop:H}=t();if(m&&(D(l,!1),m=!1),s||F||!C&&H){const[B,z]=ene({nodeId:C,dragItems:l,nodeLookup:L,dragging:!1});s?.(R.sourceEvent,l,B,z),F?.(R.sourceEvent,B,z),C||H?.(R.sourceEvent,z)}}}).filter(R=>{const L=R.target;return!R.button&&(!x||!B7e(L,`.${x}`,k))&&(!S||B7e(L,S,k))});p.call(A)}function b(){p?.on(".drag",null)}return{update:y,destroy:b}}function DYn(e,t,n){const r=[],s={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const a of t.values())LM(s,aN(a))>0&&r.push(a);return r}const LYn=250;function FYn(e,t,n,r){let s=[],a=1/0;const i=DYn(e,n,t+LYn);for(const l of i){const c=[...l.internals.handleBounds?.source??[],...l.internals.handleBounds?.target??[]];for(const u of c){if(r.nodeId===u.nodeId&&r.type===u.type&&r.id===u.id)continue;const{x:d,y:f}=XO(l,u,u.position,!0),p=Math.sqrt(Math.pow(d-e.x,2)+Math.pow(f-e.y,2));p>t||(p<a?(s=[{...u,x:d,y:f}],a=p):p===a&&s.push({...u,x:d,y:f}))}}if(!s.length)return null;if(s.length>1){const l=r.type==="source"?"target":"source";return s.find(c=>c.type===l)??s[0]}return s[0]}function zOt(e,t,n,r,s,a=!1){const i=r.get(e);if(!i)return null;const l=s==="strict"?i.internals.handleBounds?.[t]:[...i.internals.handleBounds?.source??[],...i.internals.handleBounds?.target??[]],c=(n?l?.find(u=>u.id===n):l?.[0])??null;return c&&a?{...c,...XO(i,c,c.position,!0)}:c}function BOt(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function zYn(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const UOt=()=>!0;function BYn(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:a,isTarget:i,domNode:l,nodeLookup:c,lib:u,autoPanOnConnect:d,flowId:f,panBy:p,cancelConnection:h,onConnectStart:m,onConnect:v,onConnectEnd:y,isValidConnection:b=UOt,onReconnectEnd:x,updateConnection:S,getTransform:k,getFromHandle:_,autoPanSpeed:C,dragThreshold:T=1,handleDomNode:E}){const N=NOt(e.target);let I=0,A;const{x:R,y:L}=Cg(e),D=BOt(a,E),F=l?.getBoundingClientRect();let H=!1;if(!F||!D)return;const B=zOt(s,D,r,c,t);if(!B)return;let z=Cg(e,F),V=!1,M=null,G=!1,U=null;function $(){if(!d||!F)return;const[le,X]=COt(z,F,C);p({x:le,y:X}),I=requestAnimationFrame($)}const q={...B,nodeId:s,type:D,position:B.position},Z=c.get(s);let ne={inProgress:!0,isValid:null,from:XO(Z,q,tr.Left,!0),fromHandle:q,fromPosition:q.position,fromNode:Z,to:z,toHandle:null,toPosition:j7e[q.position],toNode:null,pointer:z};function J(){H=!0,S(ne),m?.(e,{nodeId:s,handleId:r,handleType:D})}T===0&&J();function ee(le){if(!H){const{x:Se,y:ve}=Cg(le),ke=Se-R,Ne=ve-L;if(!(ke*ke+Ne*Ne>T*T))return;J()}if(!_()||!q){re(le);return}const X=k();z=Cg(le,F),A=FYn(t4(z,X,!1,[1,1]),n,c,q),V||($(),V=!0);const te=qOt(le,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});U=te.handleDomNode,M=te.connection,G=zYn(!!A,te.isValid);const se=c.get(s),pe=se?XO(se,q,tr.Left,!0):ne.from,ce={...ne,from:pe,isValid:G,to:te.toHandle&&G?nU({x:te.toHandle.x,y:te.toHandle.y},X):z,toHandle:te.toHandle,toPosition:G&&te.toHandle?te.toHandle.position:j7e[q.position],toNode:te.toHandle?c.get(te.toHandle.nodeId):null,pointer:z};S(ce),ne=ce}function re(le){if(!("touches"in le&&le.touches.length>0)){if(H){(A||U)&&M&&G&&v?.(M);const{inProgress:X,...te}=ne,se={...te,toPosition:ne.toHandle?ne.toPosition:null};y?.(le,se),a&&x?.(le,se)}h(),cancelAnimationFrame(I),V=!1,G=!1,M=null,U=null,N.removeEventListener("mousemove",ee),N.removeEventListener("mouseup",re),N.removeEventListener("touchmove",ee),N.removeEventListener("touchend",re)}}N.addEventListener("mousemove",ee),N.addEventListener("mouseup",re),N.addEventListener("touchmove",ee),N.addEventListener("touchend",re)}function qOt(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=UOt,nodeLookup:d}){const f=a==="target",p=t?i.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:h,y:m}=Cg(e),v=i.elementFromPoint(h,m),y=v?.classList.contains(`${l}-flow__handle`)?v:p,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){const x=BOt(void 0,y),S=y.getAttribute("data-nodeid"),k=y.getAttribute("data-handleid"),_=y.classList.contains("connectable"),C=y.classList.contains("connectableend");if(!S||!x)return b;const T={source:f?S:r,sourceHandle:f?k:s,target:f?r:S,targetHandle:f?s:k};b.connection=T;const N=_&&C&&(n===rN.Strict?f&&x==="source"||!f&&x==="target":S!==r||k!==s);b.isValid=N&&u(T),b.toHandle=zOt(S,x,k,d,n,!0)}return b}const yve={onPointerDown:BYn,isValid:qOt};function UYn({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Cp(e);function a({translateExtent:l,width:c,height:u,zoomStep:d=1,pannable:f=!0,zoomable:p=!0,inversePan:h=!1}){const m=S=>{if(S.sourceEvent.type!=="wheel"||!t)return;const k=n(),_=S.sourceEvent.ctrlKey&&FM()?10:1,C=-S.sourceEvent.deltaY*(S.sourceEvent.deltaMode===1?.05:S.sourceEvent.deltaMode?1:.002)*d,T=k[2]*Math.pow(2,C*_);t.scaleTo(T)};let v=[0,0];const y=S=>{(S.sourceEvent.type==="mousedown"||S.sourceEvent.type==="touchstart")&&(v=[S.sourceEvent.clientX??S.sourceEvent.touches[0].clientX,S.sourceEvent.clientY??S.sourceEvent.touches[0].clientY])},b=S=>{const k=n();if(S.sourceEvent.type!=="mousemove"&&S.sourceEvent.type!=="touchmove"||!t)return;const _=[S.sourceEvent.clientX??S.sourceEvent.touches[0].clientX,S.sourceEvent.clientY??S.sourceEvent.touches[0].clientY],C=[_[0]-v[0],_[1]-v[1]];v=_;const T=r()*Math.max(k[2],Math.log(k[2]))*(h?-1:1),E={x:k[0]-C[0]*T,y:k[1]-C[1]*T},N=[[0,0],[c,u]];t.setViewportConstrained({x:E.x,y:E.y,zoom:k[2]},N,l)},x=yOt().on("start",y).on("zoom",f?b:null).on("zoom.wheel",p?m:null);s.call(x,{})}function i(){s.on("zoom",null)}return{update:a,destroy:i,pointer:fg}}const fW=e=>({x:e.x,y:e.y,zoom:e.k}),tne=({x:e,y:t,zoom:n})=>cW.translate(e,t).scale(n),xT=(e,t)=>e.target.closest(`.${t}`),VOt=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),qYn=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,nne=(e,t=0,n=qYn,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},HOt=e=>{const t=e.ctrlKey&&FM()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function VYn({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(xT(d,t))return d.ctrlKey&&d.preventDefault(),!1;d.preventDefault(),d.stopImmediatePropagation();const f=n.property("__zoom").k||1;if(d.ctrlKey&&i){const y=fg(d),b=HOt(d),x=f*Math.pow(2,b);r.scaleTo(n,x,y,d);return}const p=d.deltaMode===1?20:1;let h=s===rO.Vertical?0:d.deltaX*p,m=s===rO.Horizontal?0:d.deltaY*p;!FM()&&d.shiftKey&&s!==rO.Vertical&&(h=d.deltaY*p,m=0),r.translateBy(n,-(h/f)*a,-(m/f)*a,{internal:!0});const v=fW(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 HYn({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=xT(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function WYn({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=fW(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 ZYn({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&VOt(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,fW(a.transform))}}function GYn({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&VOt(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=fW(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function QYn({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:s,zoomOnDoubleClick:a,userSelectionActive:i,noWheelClassName:l,noPanClassName:c,lib:u,connectionInProgress:d}){return f=>{const p=e||t,h=n&&f.ctrlKey,m=f.type==="wheel";if(f.button===1&&f.type==="mousedown"&&(xT(f,`${u}-flow__node`)||xT(f,`${u}-flow__edge`)))return!0;if(!r&&!p&&!s&&!a&&!n||i||d&&!m||xT(f,l)&&m||xT(f,c)&&(!m||s&&m&&!e)||!n&&f.ctrlKey&&m)return!1;if(!n&&f.type==="touchstart"&&f.touches?.length>1)return f.preventDefault(),!1;if(!p&&!s&&!h&&m||!r&&(f.type==="mousedown"||f.type==="touchstart")||Array.isArray(r)&&!r.includes(f.button)&&f.type==="mousedown")return!1;const v=Array.isArray(r)&&r.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||m)&&v}}function YYn({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:s,onPanZoom:a,onPanZoomStart:i,onPanZoomEnd:l,onDraggingChange:c}){const u={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},d=e.getBoundingClientRect(),f=yOt().scaleExtent([t,n]).translateExtent(r),p=Cp(e).call(f);x({x:s.x,y:s.y,zoom:sN(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const h=p.on("wheel.zoom"),m=p.on("dblclick.zoom");f.wheelDelta(HOt);function v(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?hx:W8).transform(nne(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:R,onPaneContextMenu:L,userSelectionActive:D,panOnScroll:F,panOnDrag:H,panOnScrollMode:B,panOnScrollSpeed:z,preventScrolling:V,zoomOnPinch:M,zoomOnScroll:G,zoomOnDoubleClick:U,zoomActivationKeyPressed:$,lib:q,onTransformChange:Z,connectionInProgress:Y,paneClickDistance:ne,selectionOnDrag:J}){D&&!u.isZoomingOrPanning&&b();const ee=F&&!$&&!D;f.clickDistance(J?1/0:!_g(ne)||ne<0?0:ne);const re=ee?VYn({zoomPanValues:u,noWheelClassName:A,d3Selection:p,d3Zoom:f,panOnScrollMode:B,panOnScrollSpeed:z,zoomOnPinch:M,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):HYn({noWheelClassName:A,preventScrolling:V,d3ZoomHandler:h});if(p.on("wheel.zoom",re,{passive:!1}),!D){const X=WYn({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",X);const te=ZYn({zoomPanValues:u,panOnDrag:H,onPaneContextMenu:!!L,onPanZoom:a,onTransformChange:Z});f.on("zoom",te);const se=GYn({zoomPanValues:u,panOnDrag:H,panOnScroll:F,onPaneContextMenu:L,onPanZoomEnd:l,onDraggingChange:c});f.on("end",se)}const le=QYn({zoomActivationKeyPressed:$,panOnDrag:H,zoomOnScroll:G,panOnScroll:F,zoomOnDoubleClick:U,zoomOnPinch:M,userSelectionActive:D,noPanClassName:R,noWheelClassName:A,lib:q,connectionInProgress:Y});f.filter(le),U?p.on("dblclick.zoom",m):p.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,R,L){const D=tne(A),F=f?.constrain()(D,R,L);return F&&await v(F),new Promise(H=>H(F))}async function S(A,R){const L=tne(A);return await v(L,R),new Promise(D=>D(L))}function k(A){if(p){const R=tne(A),L=p.property("__zoom");(L.k!==A.zoom||L.x!==A.x||L.y!==A.y)&&f?.transform(p,R,null,{sync:!0})}}function _(){const A=p?vOt(p.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function C(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?hx:W8).scaleTo(nne(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function T(A,R){return p?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?hx:W8).scaleBy(nne(p,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function E(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const R=!_g(A)||A<0?0:A;f?.clickDistance(R)}return{update:y,destroy:b,setViewport:S,setViewportConstrained:x,getViewport:_,scaleTo:C,scaleBy:T,setScaleExtent:E,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var oN;(function(e){e.Line="line",e.Handle="handle"})(oN||(oN={}));function KYn({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:s,affectsY:a}){const i=e-t,l=n-r,c=[i>0?1:i<0?-1:0,l>0?1:l<0?-1:0];return i&&s&&(c[0]=c[0]*-1),l&&a&&(c[1]=c[1]*-1),c}function U7e(e){const t=e.includes("right")||e.includes("left"),n=e.includes("bottom")||e.includes("top"),r=e.includes("left"),s=e.includes("top");return{isHorizontal:t,isVertical:n,affectsX:r,affectsY:s}}function X0(e,t){return Math.max(0,t-e)}function J0(e,t){return Math.max(0,e-t)}function wF(e,t,n){return Math.max(0,t-e,e-n)}function q7e(e,t){return e?!t:t}function XYn(e,t,n,r,s,a,i,l){let{affectsX:c,affectsY:u}=t;const{isHorizontal:d,isVertical:f}=t,p=d&&f,{xSnapped:h,ySnapped:m}=n,{minWidth:v,maxWidth:y,minHeight:b,maxHeight:x}=r,{x:S,y:k,width:_,height:C,aspectRatio:T}=e;let E=Math.floor(d?h-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=_+(c?-E:E),A=C+(u?-N:N),R=-a[0]*_,L=-a[1]*C;let D=wF(I,v,y),F=wF(A,b,x);if(i){let z=0,V=0;c&&E<0?z=X0(S+E+R,i[0][0]):!c&&E>0&&(z=J0(S+I+R,i[1][0])),u&&N<0?V=X0(k+N+L,i[0][1]):!u&&N>0&&(V=J0(k+A+L,i[1][1])),D=Math.max(D,z),F=Math.max(F,V)}if(l){let z=0,V=0;c&&E>0?z=J0(S+E,l[0][0]):!c&&E<0&&(z=X0(S+I,l[1][0])),u&&N>0?V=J0(k+N,l[0][1]):!u&&N<0&&(V=X0(k+A,l[1][1])),D=Math.max(D,z),F=Math.max(F,V)}if(s){if(d){const z=wF(I/T,b,x)*T;if(D=Math.max(D,z),i){let V=0;!c&&!u||c&&!u&&p?V=J0(k+L+I/T,i[1][1])*T:V=X0(k+L+(c?E:-E)/T,i[0][1])*T,D=Math.max(D,V)}if(l){let V=0;!c&&!u||c&&!u&&p?V=X0(k+I/T,l[1][1])*T:V=J0(k+(c?E:-E)/T,l[0][1])*T,D=Math.max(D,V)}}if(f){const z=wF(A*T,v,y)/T;if(F=Math.max(F,z),i){let V=0;!c&&!u||u&&!c&&p?V=J0(S+A*T+R,i[1][0])/T:V=X0(S+(u?N:-N)*T+R,i[0][0])/T,F=Math.max(F,V)}if(l){let V=0;!c&&!u||u&&!c&&p?V=X0(S+A*T,l[1][0])/T:V=J0(S+(u?N:-N)*T,l[0][0])/T,F=Math.max(F,V)}}}N=N+(N<0?F:-F),E=E+(E<0?D:-D),s&&(p?I>A*T?N=(q7e(c,u)?-E:E)/T:E=(q7e(c,u)?-N:N)*T:d?(N=E/T,u=c):(E=N*T,c=u));const H=c?S+E:S,B=u?k+N:k;return{width:_+(c?-E:E),height:C+(u?-N:N),x:a[0]*E*(c?-1:1)+H,y:a[1]*N*(u?-1:1)+B}}const WOt={width:0,height:0,x:0,y:0},JYn={...WOt,pointerX:0,pointerY:0,aspectRatio:1};function eKn(e){return[[0,0],[e.measured.width,e.measured.height]]}function tKn(e,t,n){const r=t.position.x+e.position.x,s=t.position.y+e.position.y,a=e.measured.width??0,i=e.measured.height??0,l=n[0]*a,c=n[1]*i;return[[r-l,s-c],[r+a-l,s+i-c]]}function nKn({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=Cp(e);let i={controlDirection:U7e("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:u,boundaries:d,keepAspectRatio:f,resizeDirection:p,onResizeStart:h,onResize:m,onResizeEnd:v,shouldResize:y}){let b={...WOt},x={...JYn};i={boundaries:d,resizeDirection:p,keepAspectRatio:f,controlDirection:U7e(u)};let S,k=null,_=[],C,T,E,N=!1;const I=rOt().on("start",A=>{const{nodeLookup:R,transform:L,snapGrid:D,snapToGrid:F,nodeOrigin:H,paneDomNode:B}=n();if(S=R.get(t),!S)return;k=B?.getBoundingClientRect()??null;const{xSnapped:z,ySnapped:V}=R$(A.sourceEvent,{transform:L,snapGrid:D,snapToGrid:F,containerBounds:k});b={width:S.measured.width??0,height:S.measured.height??0,x:S.position.x??0,y:S.position.y??0},x={...b,pointerX:z,pointerY:V,aspectRatio:b.width/b.height},C=void 0,S.parentId&&(S.extent==="parent"||S.expandParent)&&(C=R.get(S.parentId),T=C&&S.extent==="parent"?eKn(C):void 0),_=[],E=void 0;for(const[M,G]of R)if(G.parentId===t&&(_.push({id:M,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const U=tKn(G,S,G.origin??H);E?E=[[Math.min(U[0][0],E[0][0]),Math.min(U[0][1],E[0][1])],[Math.max(U[1][0],E[1][0]),Math.max(U[1][1],E[1][1])]]:E=U}h?.(A,{...b})}).on("drag",A=>{const{transform:R,snapGrid:L,snapToGrid:D,nodeOrigin:F}=n(),H=R$(A.sourceEvent,{transform:R,snapGrid:L,snapToGrid:D,containerBounds:k}),B=[];if(!S)return;const{x:z,y:V,width:M,height:G}=b,U={},$=S.origin??F,{width:q,height:Z,x:Y,y:ne}=XYn(x,i.controlDirection,H,i.boundaries,i.keepAspectRatio,$,T,E),J=q!==M,ee=Z!==G,re=Y!==z&&J,le=ne!==V&ⅇif(!re&&!le&&!J&&!ee)return;if((re||le||$[0]===1||$[1]===1)&&(U.x=re?Y:b.x,U.y=le?ne:b.y,b.x=U.x,b.y=U.y,_.length>0)){const pe=Y-z,ce=ne-V;for(const Se of _)Se.position={x:Se.position.x-pe+$[0]*(q-M),y:Se.position.y-ce+$[1]*(Z-G)},B.push(Se)}if((J||ee)&&(U.width=J&&(!i.resizeDirection||i.resizeDirection==="horizontal")?q:b.width,U.height=ee&&(!i.resizeDirection||i.resizeDirection==="vertical")?Z:b.height,b.width=U.width,b.height=U.height),C&&S.expandParent){const pe=$[0]*(U.width??0);U.x&&U.x<pe&&(b.x=pe,x.x=x.x-(U.x-pe));const ce=$[1]*(U.height??0);U.y&&U.y<ce&&(b.y=ce,x.y=x.y-(U.y-ce))}const X=KYn({width:b.width,prevWidth:M,height:b.height,prevHeight:G,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),te={...b,direction:X};y?.(A,te)!==!1&&(N=!0,m?.(A,te),r(U,B))}).on("end",A=>{N&&(v?.(A,{...b}),s?.({...b}),N=!1)});a.call(I)}function c(){a.on(".drag",null)}return{update:l,destroy:c}}const rKn={},V7e=e=>{let t;const n=new Set,r=(d,f)=>{const p=typeof d=="function"?d(t):d;if(!Object.is(p,t)){const h=t;t=f??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(m=>m(t,h))}},s=()=>t,c={setState:r,getState:s,getInitialState:()=>u,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(rKn?"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},sKn=e=>e?V7e(e):V7e,{useDebugValue:aKn}=ze,{useSyncExternalStoreWithSelector:iKn}=Njn,oKn=e=>e;function ZOt(e,t=oKn,n){const r=iKn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return aKn(r),r}const H7e=(e,t)=>{const n=sKn(e),r=(s,a=t)=>ZOt(n,s,a);return Object.assign(r,n),r},lKn=(e,t)=>e?H7e(e,t):H7e;function ao(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 pW=g.createContext(null),cKn=pW.Provider,GOt=ky.error001();function Hs(e,t){const n=g.useContext(pW);if(n===null)throw new Error(GOt);return ZOt(n,e,t)}function Co(){const e=g.useContext(pW);if(e===null)throw new Error(GOt);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const W7e={display:"none"},uKn={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},QOt="react-flow__node-desc",YOt="react-flow__edge-desc",dKn="react-flow__aria-live",fKn=e=>e.ariaLiveMessage,pKn=e=>e.ariaLabelConfig;function hKn({rfId:e}){const t=Hs(fKn);return o.jsx("div",{id:`${dKn}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:uKn,children:t})}function mKn({rfId:e,disableKeyboardA11y:t}){const n=Hs(pKn);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${QOt}-${e}`,style:W7e,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${YOt}-${e}`,style:W7e,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(hKn,{rfId:e})]})}const n4=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:ql(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});n4.displayName="Panel";function gKn({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(n4,{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 vKn=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}},SF=e=>e.id;function yKn(e,t){return ao(e.selectedNodes.map(SF),t.selectedNodes.map(SF))&&ao(e.selectedEdges.map(SF),t.selectedEdges.map(SF))}function bKn({onSelectionChange:e}){const t=Co(),{selectedNodes:n,selectedEdges:r}=Hs(vKn,yKn);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const xKn=e=>!!e.onSelectionChangeHandlers;function wKn({onSelectionChange:e}){const t=Hs(xKn);return e||t?o.jsx(bKn,{onSelectionChange:e}):null}const bve=typeof window<"u"?g.useLayoutEffect:g.useEffect,KOt=[0,0],SKn={x:0,y:0,zoom:1},kKn=["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"],Z7e=[...kKn,"rfId"],OKn=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}),G7e={translateExtent:$M,nodeOrigin:KOt,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function _Kn(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Hs(OKn,ao),u=Co();bve(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=G7e,l()}),[]);const d=g.useRef(G7e);return bve(()=>{for(const f of Z7e){const p=e[f],h=d.current[f];p!==h&&(typeof e[f]>"u"||(f==="nodes"?t(p):f==="edges"?n(p):f==="minZoom"?r(p):f==="maxZoom"?s(p):f==="translateExtent"?a(p):f==="nodeExtent"?i(p):f==="ariaLabelConfig"?u.setState({ariaLabelConfig:hYn(p)}):f==="fitView"?u.setState({fitViewQueued:p}):f==="fitViewOptions"?u.setState({fitViewOptions:p}):u.setState({[f]:p})))}d.current=e},Z7e.map(f=>e[f])),null}function Q7e(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function CKn(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=Q7e(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:Q7e()?.matches?"dark":"light"}const Y7e=typeof document<"u"?document:null;function zM(e=null,t={target:Y7e,actInsideInputWithModifier:!0}){const[n,r]=g.useState(!1),s=g.useRef(!1),a=g.useRef(new Set([])),[i,l]=g.useMemo(()=>{if(e!==null){const u=(Array.isArray(e)?e:[e]).filter(f=>typeof f=="string").map(f=>f.replace("+",`
|
|
235
235
|
`).replace(`
|
|
236
236
|
|
|
237
237
|
`,`
|
|
@@ -624,7 +624,7 @@ window.parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/sandbox-proxy-
|
|
|
624
624
|
`),s=n.length,a=r.length,i=Array.from({length:s+1},()=>new Array(a+1).fill(0));for(let d=1;d<=s;d++)for(let f=1;f<=a;f++)n[d-1]===r[f-1]?i[d][f]=i[d-1][f-1]+1:i[d][f]=Math.max(i[d-1][f],i[d][f-1]);const l=[];let c=s,u=a;for(;c>0||u>0;)c>0&&u>0&&n[c-1]===r[u-1]?(l.push({type:"equal",text:n[c-1]}),c--,u--):u>0&&(c===0||i[c][u-1]>=i[c-1][u])?(l.push({type:"added",text:r[u-1]}),u--):(l.push({type:"removed",text:n[c-1]}),c--);return l.reverse()}function Cxe(e){return e.type==="prompt_block"&&typeof e.content=="string"?e.content:null}function Gas({promptBlockId:e}){const{data:t}=AL(e),n=t?.content??"";return n?o.jsx(ka,{content:n,tooltip:"Copy prompt block text",size:"sm"}):null}function vP({block:e}){const t=Cxe(e);return t?o.jsx(ka,{content:t,tooltip:"Copy prompt text",size:"sm"}):e.type==="prompt_block_ref"&&(typeof e.promptBlockId=="string"||typeof e.id=="string")?o.jsx(Gas,{promptBlockId:e.promptBlockId??e.id}):null}function Qas({previousBlocks:e,currentBlocks:t}){const n=Array.isArray(e)?e:[],r=Array.isArray(t)?t:[],s=r.map(l=>Cxe(l)??""),a=n.map(l=>Cxe(l)??"");if(n.length<=1&&r.length<=1){const l=a[0]??"",c=s[0]??"",u=n[0];if(l===c)return o.jsxs("div",{className:"border-border1 bg-surface2 relative rounded-md border p-3",children:[u&&o.jsx("div",{className:"absolute top-2 right-2",children:o.jsx(vP,{block:u})}),o.jsx(me,{variant:"ui-sm",className:"text-neutral4 font-mono whitespace-pre-wrap",children:l||"(empty)"})]});const d=uJe(l,c);return o.jsxs("div",{className:"border-border1 relative overflow-hidden rounded-md border font-mono text-sm",children:[u&&o.jsx("div",{className:"absolute top-2 right-2 z-10",children:o.jsx(vP,{block:u})}),d.map((f,p)=>o.jsxs("div",{className:K("px-3 py-0.5 whitespace-pre-wrap wrap-break-word",f.type==="removed"&&"bg-red-950/20 text-red-300",f.type==="added"&&"bg-green-950/20 text-green-300",f.type==="equal"&&"text-neutral4"),children:[o.jsx("span",{className:"text-neutral3/50 mr-2 inline-block w-4 shrink-0 select-none",children:f.type==="removed"?"−":f.type==="added"?"+":" "}),f.text||" "]},p))]})}const i=Math.max(n.length,r.length);return o.jsx("div",{className:"flex flex-col gap-2",children:Array.from({length:i},(l,c)=>{const u=n[c],d=r[c],f=a[c]??"",p=s[c]??"";if(!u&&d)return o.jsxs("div",{className:"rounded-md border border-green-900/30 bg-green-950/10 p-3 font-mono text-sm",children:[o.jsx(me,{variant:"ui-xs",className:"mb-1 text-green-400",children:"+ Added block"}),o.jsx(me,{variant:"ui-sm",className:"whitespace-pre-wrap text-green-300",children:p})]},c);if(u&&!d)return o.jsxs("div",{className:"relative rounded-md border border-red-900/30 bg-red-950/10 p-3 font-mono text-sm",children:[o.jsx("div",{className:"absolute top-2 right-2",children:o.jsx(vP,{block:u})}),o.jsx(me,{variant:"ui-xs",className:"mb-1 text-red-400",children:"− Removed in latest"}),o.jsx(me,{variant:"ui-sm",className:"whitespace-pre-wrap text-red-300",children:f})]},c);if(f===p)return o.jsxs("div",{className:"border-border1 bg-surface2 relative rounded-md border p-3",children:[u&&o.jsx("div",{className:"absolute top-2 right-2",children:o.jsx(vP,{block:u})}),o.jsx(me,{variant:"ui-sm",className:"text-neutral4 font-mono whitespace-pre-wrap",children:f||"(empty)"})]},c);const h=uJe(f,p);return o.jsxs("div",{className:"border-border1 relative overflow-hidden rounded-md border font-mono text-sm",children:[u&&o.jsx("div",{className:"absolute top-2 right-2 z-10",children:o.jsx(vP,{block:u})}),h.map((m,v)=>o.jsxs("div",{className:K("px-3 py-0.5 whitespace-pre-wrap wrap-break-word",m.type==="removed"&&"bg-red-950/20 text-red-300",m.type==="added"&&"bg-green-950/20 text-green-300",m.type==="equal"&&"text-neutral4"),children:[o.jsx("span",{className:"text-neutral3/50 mr-2 inline-block w-4 shrink-0 select-none",children:m.type==="removed"?"−":m.type==="added"?"+":" "}),m.text||" "]},v))]},c)})})}function Yas({promptBlockId:e}){const{data:t,isLoading:n}=AL(e);if(n)return o.jsx("div",{className:"flex items-center justify-center py-4",children:o.jsx(Ut,{className:"h-4 w-4"})});const r=t?.content??"";return o.jsxs("div",{className:"border-border1 bg-surface2 relative rounded-md border p-3",children:[r&&o.jsx("div",{className:"absolute top-2 right-2",children:o.jsx(ka,{content:r,tooltip:"Copy prompt block text",size:"sm"})}),t?.name&&o.jsx(me,{variant:"ui-xs",className:"text-neutral3 mb-1 font-medium",children:t.name}),o.jsx(me,{variant:"ui-sm",className:"text-neutral4 font-mono whitespace-pre-wrap",children:r||"(empty)"})]})}function tUt({blocks:e}){const t=Array.isArray(e)?e:[];return t.length===0?o.jsx(me,{variant:"ui-sm",className:"text-neutral3 py-2",children:"No instruction blocks configured"}):o.jsx("div",{className:"flex flex-col gap-2",children:t.map((n,r)=>{if(n.type==="prompt_block_ref"){const a=n.promptBlockId??n.id;return o.jsx(Yas,{promptBlockId:a},a??r)}const s=typeof n.content=="string"?n.content:"";return o.jsxs("div",{className:"border-border1 bg-surface2 relative rounded-md border p-3",children:[s&&o.jsx("div",{className:"absolute top-2 right-2",children:o.jsx(ka,{content:s,tooltip:"Copy prompt text",size:"sm"})}),o.jsx(me,{variant:"ui-sm",className:"text-neutral4 font-mono whitespace-pre-wrap",children:s||"(empty)"})]},n.id??r)})})}function Kas({previousTools:e,currentTools:t}){const n=new Set(e?Object.keys(e):[]),r=new Set(t?Object.keys(t):[]),s=[...new Set([...n,...r])].sort();return o.jsx("div",{className:"flex flex-col gap-1.5",children:s.map(a=>{const i=n.has(a),l=r.has(a);let c;return i&&l?c="same":i?c="removed":c="added",o.jsxs("div",{className:K("flex items-center gap-2 rounded-md border px-3 py-1.5",c==="removed"&&"border-red-900/30 bg-red-950/10",c==="added"&&"border-green-900/30 bg-green-950/10",c==="same"&&"border-border1 bg-surface2"),children:[o.jsx(me,{variant:"ui-sm",className:K("font-mono",c==="removed"&&"text-red-300 line-through",c==="added"&&"text-green-300",c==="same"&&"text-neutral5"),children:a}),c==="removed"&&o.jsx(St,{variant:"red",className:"ml-auto",children:"removed in latest"}),c==="added"&&o.jsx(St,{variant:"green",className:"ml-auto",children:"added in latest"})]},a)})})}function Xas({tools:e}){const t=e?Object.entries(e):[];return t.length===0?o.jsx(me,{variant:"ui-sm",className:"text-neutral3 py-2",children:"No tools configured"}):o.jsx("div",{className:"flex flex-col gap-1.5",children:t.map(([n,r])=>o.jsxs("div",{className:"border-border1 bg-surface2 rounded-md border px-3 py-1.5",children:[o.jsx(me,{variant:"ui-sm",className:"text-neutral5 font-mono",children:n}),r?.description?o.jsx(me,{variant:"ui-xs",className:"text-neutral3 mt-0.5",children:String(r.description)}):null]},n))})}function Jas({previousVars:e,currentVars:t}){const n=e?.properties??{},r=t?.properties??{},s=new Set(Object.keys(n)),a=new Set(Object.keys(r)),i=[...new Set([...s,...a])].sort();return i.length===0?o.jsx(me,{variant:"ui-sm",className:"text-neutral3 py-2",children:"No variables configured"}):o.jsx("div",{className:"flex flex-col gap-1.5",children:i.map(l=>{const c=s.has(l),u=a.has(l);let d;return c&&u?d="same":c?d="removed":d="added",o.jsxs("div",{className:K("flex items-center gap-2 rounded-md border px-3 py-1.5",d==="removed"&&"border-red-900/30 bg-red-950/10",d==="added"&&"border-green-900/30 bg-green-950/10",d==="same"&&"border-border1 bg-surface2"),children:[o.jsx(me,{variant:"ui-sm",className:K("font-mono",d==="removed"&&"text-red-300 line-through",d==="added"&&"text-green-300",d==="same"&&"text-neutral5"),children:`{{${l}}}`}),d==="removed"&&o.jsx(St,{variant:"red",className:"ml-auto",children:"removed in latest"}),d==="added"&&o.jsx(St,{variant:"green",className:"ml-auto",children:"added in latest"})]},l)})})}function eis({variables:e}){const t=e?.properties??{},n=Object.entries(t);return n.length===0?o.jsx(me,{variant:"ui-sm",className:"text-neutral3 py-2",children:"No variables configured"}):o.jsx("div",{className:"flex flex-col gap-1.5",children:n.map(([r,s])=>o.jsxs("div",{className:"border-border1 bg-surface2 flex items-center gap-2 rounded-md border px-3 py-1.5",children:[o.jsx(me,{variant:"ui-sm",className:"text-neutral5 font-mono",children:`{{${r}}}`}),s?.type?o.jsx(St,{children:String(s.type)}):null]},r))})}function tis({agentId:e,selectedVersionId:t,latestVersionId:n}){const{form:r}=Bo(),s=r.watch("tools"),a=r.watch("variables"),i=r.watch("instructionBlocks"),l=s?Object.keys(s).length:0,{data:c,isLoading:u}=brs({agentId:e,fromVersionId:t,toVersionId:n}),d=g.useMemo(()=>{const b=new Map;if(c?.diffs)for(const x of c.diffs)b.set(x.field,{previousValue:x.previousValue,currentValue:x.currentValue});return b},[c]),f=d.get("instructions"),p=d.get("tools"),h=d.get("requestContextSchema"),m=f?o.jsx(St,{variant:"yellow",size:"sm",children:"modified"}):null,v=p?o.jsx(St,{variant:"yellow",size:"sm",children:"modified"}):l>0?o.jsx(St,{size:"sm",children:`${l}`}):null,y=h?o.jsx(St,{variant:"yellow",size:"sm",children:"modified"}):null;return u?o.jsx("div",{className:"flex items-center justify-center py-8",children:o.jsx(Ut,{className:"h-5 w-5"})}):o.jsxs(yc,{defaultTab:"variables",className:"flex min-h-full flex-col overflow-visible",children:[o.jsxs(vc,{variant:"pill-ghost",className:"shrink-0",children:[o.jsx(Ar,{value:"variables",children:o.jsx(yj,{title:"Variables",icon:o.jsx(Jl,{}),badge:y})}),o.jsx(Ar,{value:"instructions",children:o.jsx(yj,{title:"System Prompt",icon:o.jsx(gV,{}),badge:m})}),o.jsx(Ar,{value:"tools",children:o.jsx(yj,{title:"Tools",icon:o.jsx(Ud,{}),badge:v})})]}),o.jsx(fs,{value:"variables",className:"px-4 py-4",children:h?o.jsx(Jas,{previousVars:h.previousValue,currentVars:h.currentValue}):o.jsx(eis,{variables:a})}),o.jsx(fs,{value:"instructions",className:"px-4 py-4",children:f?o.jsx(Qas,{previousBlocks:f.previousValue,currentBlocks:f.currentValue}):o.jsx(tUt,{blocks:i})}),o.jsx(fs,{value:"tools",className:"px-4 py-4",children:p?o.jsx(Kas,{previousTools:p.previousValue,currentTools:p.currentValue}):o.jsx(Xas,{tools:s})})]})}function nis({agentId:e,selectedVersionId:t,latestVersionId:n}){const{form:r,readOnly:s,isCodeAgentOverride:a,editorConfig:i}=Bo(),{isInstructionsLocked:l}=kC(a,i),c=r.watch("tools"),u=r.watch("instructionBlocks"),d=r.watch("variables"),f=c?Object.keys(c).length:0,p=g.useMemo(()=>Object.entries(d?.properties??{}),[d]),h=s&&!!t&&!!n&&t!==n;return o.jsxs("div",{className:K("flex flex-col h-full"),children:[o.jsx("div",{className:"border-border1 border-b px-4 py-3"}),o.jsx(Dr,{className:"min-h-0 flex-1",children:h?o.jsx(tis,{agentId:e,selectedVersionId:t,latestVersionId:n}):o.jsxs(yc,{defaultTab:"variables",className:"flex min-h-full flex-col overflow-visible",children:[o.jsxs(vc,{variant:"pill-ghost",className:"shrink-0",children:[o.jsx(Ar,{value:"variables",children:o.jsx(yj,{title:"Variables",icon:o.jsx(Jl,{})})}),o.jsx(Ar,{value:"instructions",children:o.jsx(yj,{title:"System Prompt",icon:o.jsx(gV,{})})}),o.jsx(Ar,{value:"tools",children:o.jsx(yj,{title:"Tools",icon:o.jsx(Ud,{}),badge:f>0?o.jsx(St,{size:"sm",children:`${f}`}):void 0})})]}),o.jsx(fs,{value:"variables",className:"py-0",children:o.jsxs("div",{className:"flex flex-col gap-1 px-4 py-4",children:[p.length>0?o.jsx("div",{className:"flex flex-col",children:p.map(([m,v])=>o.jsx(eUt,{name:m,prop:v,depth:0},m))}):null,o.jsx(me,{variant:"ui-xs",className:"text-neutral3 mt-1",children:p.length>0?"Defined via requestContextSchema in code.":"No variables defined. Add a requestContextSchema to your agent to define variables."})]})}),o.jsxs(fs,{value:"instructions",className:"px-4 py-0 pb-4",children:[o.jsx("div",{className:"flex flex-col gap-3 pt-4 pb-2",children:o.jsxs(me,{variant:"ui-sm",className:"text-neutral3 font-normal",children:["Add instruction blocks to your agent. Blocks are combined in order to form the system prompt. You can"," ",o.jsxs(yn,{children:[o.jsx(gn,{className:"text-neutral3 hover:text-neutral5 inline cursor-pointer underline decoration-dotted",children:"use variables"}),o.jsx(vn,{side:"bottom",align:"start",className:"max-w-72",children:o.jsxs("span",{children:["Use ",o.jsx("code",{className:"text-accent1 font-medium",children:"{{variableName}}"})," syntax to insert dynamic values into your instruction blocks."]})})]})," ","as part of your instruction blocks."]})}),s||l?o.jsx(tUt,{blocks:u}):o.jsx(EBt,{})]}),o.jsx(fs,{value:"tools",className:"px-4 py-0 pb-4",children:o.jsx(jBt,{})})]})})]})}function aie(e){return typeof e=="object"&&e!==null}function ris(e){if(!aie(e))return{};const t={};return typeof e.maxSteps=="number"&&(t.maxSteps=e.maxSteps),aie(e.modelSettings)&&(t.modelSettings=e.modelSettings),aie(e.providerOptions)&&(t.providerOptions=e.providerOptions),t}function KIe(e){if(!e)return{modelSettings:{}};const t=ris(e.defaultOptions),{maxOutputTokens:n,...r}=t.modelSettings??{};return{modelSettings:{...r,...n!==void 0&&{maxTokens:n},...t.maxSteps!==void 0&&{maxSteps:t.maxSteps},...t.providerOptions!==void 0&&{providerOptions:t.providerOptions}}}}function sis(e){const t=e?.properties;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)}function ais({labelTooltip:e,variablesSchema:t}){const{setSchemaValues:n,schemaValues:r}=uSe(),s=JSON.stringify(r),a=g.useMemo(()=>{try{return vm(t)}catch(i){return console.error("Failed to parse variables schema:",i),null}},[t]);return a?o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx(xSe,{tooltip:e,children:"Request Context"}),o.jsx(ka,{content:s})]}),o.jsx(U3,{schema:a,onSubmit:n,submitButtonLabel:"Save",defaultValues:r})]}):o.jsx("div",{className:"p-4",children:o.jsx(me,{variant:"ui-sm",className:"text-red-400",children:"Failed to parse request context schema"})})}function iis({mode:e,onModeChange:t}){return o.jsxs("div",{className:"border-border1 flex items-center gap-1 rounded-md border p-0.5",children:[o.jsxs("button",{type:"button","aria-pressed":e==="form",onClick:()=>t("form"),className:K("flex items-center gap-1.5 px-2 py-1 rounded text-xs transition-colors",e==="form"?"bg-surface3 text-neutral5":"text-neutral3 hover:text-neutral5"),children:[o.jsx(He,{size:"sm",children:o.jsx(d0e,{})}),"Form"]}),o.jsxs("button",{type:"button","aria-pressed":e==="json",onClick:()=>t("json"),className:K("flex items-center gap-1.5 px-2 py-1 rounded text-xs transition-colors",e==="json"?"bg-surface3 text-neutral5":"text-neutral3 hover:text-neutral5"),children:[o.jsx(He,{size:"sm",children:o.jsx(eI,{})}),"JSON"]})]})}function ois({requestContextSchema:e,freeformEditorClassName:t,requestContextTooltip:n}){const s=z4t()?.form.watch("variables"),[a,i]=g.useState("form"),l=sis(s),c=!!e||l;return o.jsx("div",{className:"space-y-4",children:c?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"flex items-center justify-end",children:o.jsx(iis,{mode:a,onModeChange:i})}),a==="form"?e?o.jsx(eke,{requestContextSchema:e,labelTooltip:n}):l?o.jsx(ais,{variablesSchema:s,labelTooltip:n}):null:o.jsx(gxe,{editorClassName:t,labelTooltip:n})]}):o.jsx(gxe,{editorClassName:t,labelTooltip:n})})}const lis=()=>{const{debugMode:e,setDebugMode:t}=g.useContext(Ul);return o.jsxs(o.Fragment,{children:[o.jsx(me,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Debug Mode"}),o.jsx(So,{checked:e,onCheckedChange:n=>t(n)})]})},cis=({className:e,editorClassName:t="h-[400px]",hideTitle:n=!1,showEditorHeader:r=!1}={})=>{const s=s0(),{settings:a,setSettings:i,entityType:l}=NH(),c=d=>{if(!d)return i({...a,tracingOptions:void 0});try{const f=JSON.parse(d);typeof f=="object"&&f!==null&&i({...a,tracingOptions:f})}catch{}};let u="{}";try{u=JSON.stringify(a?.tracingOptions,null,2)}catch{}return o.jsxs("div",{className:K("px-5 py-2",!n&&"space-y-2",e),children:[!n&&o.jsx(me,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),r&&o.jsxs("div",{className:"flex items-center justify-between pb-2",children:[o.jsx(me,{as:"label",variant:"ui-md",className:"text-neutral3",children:"Tracing Options (JSON)"}),o.jsx(me,{as:"span",variant:"ui-xs",className:"text-neutral3",children:"Auto-applied on valid JSON"})]}),o.jsx(rd,{value:u,onChange:c,theme:s,extensions:[Dp],className:K(t,"overflow-y-scroll rounded-lg border border-border1 bg-surface2 overflow-hidden p-3","[&_.cm-editor]:!bg-surface2 [&_.cm-gutters]:!bg-surface2")}),l==="workflow"&&o.jsx(lis,{})]})},dJe="h-[260px] md:h-[360px]";function nUt({requestContextSchema:e}){return o.jsx(Dr,{className:"w-full",maxHeight:"min(600px, calc(100dvh - 8rem))",children:o.jsxs("div",{className:"space-y-4 p-4",children:[o.jsx(me,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Run options"}),o.jsxs("div",{className:"grid gap-5 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]",children:[o.jsx("section",{className:"min-w-0",children:o.jsx(ois,{requestContextSchema:e,requestContextTooltip:"Request context values are passed into experiments and test chats.",freeformEditorClassName:dJe})}),o.jsx("section",{className:"min-w-0",children:o.jsx(cis,{className:"px-0 py-0",editorClassName:dJe,hideTitle:!0,showEditorHeader:!0})})]})]})})}const uis={align:"shift"};function dis({requestContextSchema:e}){return o.jsxs(Uf,{children:[o.jsx(Kd,{asChild:!0,children:o.jsx(oe,{variant:"default",size:"icon-md",type:"button",tooltip:"Run options","data-testid":"composer-run-options-trigger",children:o.jsx(h0e,{className:"text-neutral3 hover:text-neutral6 h-5 w-5"})})}),o.jsx(Xd,{align:"start",collisionAvoidance:uis,className:"w-[min(760px,calc(100vw-2rem))] p-0",children:o.jsx(nUt,{requestContextSchema:e})})]})}function fis({ctx:e}){const{isDirty:t}=VSe({control:e.form.control}),n=e.handleSaveDraft,r=e.isSavingDraft??!1,s=e.isCodeSourceAgent??!1;if(!t)return null;const a=s?"Save to filesystem":"Save draft",i=s?"You have unsaved changes to the agent configuration. Save to filesystem to ensure the chat uses your latest changes.":"You have unsaved changes to the agent configuration. Save your draft to ensure the chat uses your latest changes.";return o.jsx(Wn,{variant:"warning",title:"Unsaved changes",className:"mx-4 mt-3 mb-0",action:n&&o.jsxs(oe,{type:"button",variant:"default",size:"sm",onClick:()=>n(),disabled:r,children:[o.jsx(Gu,{className:"h-3.5 w-3.5"}),r?"Saving...":a]}),children:o.jsx(Wn.Message,{children:i})})}function pis({agentId:e,agentName:t,modelVersion:n,agentVersionId:r,hasMemory:s}){const a=g.useMemo(()=>vo(),[e]),i=Bl(),l=Object.keys(i).length>0,c=z4t(),{data:u}=Vl(e),d=g.useMemo(()=>KIe(u),[u]);return o.jsx(JTe,{agentId:e,defaultSettings:d,children:o.jsx(qZ,{children:o.jsxs(VZ,{agentId:e,threadId:a,enabled:!!(u?.hasBrowser??u?.browserTools?.length),children:[o.jsx(qIe,{children:o.jsx(JZ,{children:o.jsx(Sqr,{enabled:!0,threadId:a,agentId:e,requestContext:l?i:void 0,children:o.jsxs("div",{className:"flex h-full flex-col",children:[c&&o.jsx(fis,{ctx:c}),o.jsx("div",{className:"min-h-0 flex-1",children:o.jsx(eAe,{agentId:e,agentName:t,modelVersion:n,agentVersionId:r,supportsMemory:u?.supportsMemory,threadId:a,memory:s,modelList:u?.modelList,isNewThread:!0,runOptionsSlot:o.jsx(dis,{requestContextSchema:u?.requestContextSchema})},a)})]})})},a)}),o.jsx(KDt,{})]},`session-${e}-${a}`)},`browser-${e}-${a}`)})}function his(e){return new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})}function mis({agentId:e,activeVersionId:t,selectedVersionId:n,onVersionSelect:r,isDirty:s,isSavingDraft:a,isPublishing:i,hasDraft:l,readOnly:c,isCodeSourceAgent:u=!1,showCodeModeActions:d=!1,canOpenPr:f=!1,openPrTitle:p,onSaveDraft:h,onPublish:m,onDownloadJson:v,onOpenPr:y,isViewingPreviousVersion:b=!1}){const[x,S]=g.useState(!1),[k,_]=g.useState(""),{data:C}=vS({agentId:e,params:{orderBy:{direction:"DESC"}}}),T=g.useMemo(()=>C?.versions??[],[C?.versions]),E=T[0],I=(t?T.find(H=>H.id===t):void 0)?.versionNumber,A=g.useMemo(()=>T.map(H=>{const B=H.id===t,z=I!==void 0&&H.versionNumber>I;return{value:H.id,label:`${u?"Save":"v"}${H.versionNumber} - ${his(H.createdAt)}`,description:H.changeMessage||void 0,end:u?o.jsx(St,{variant:B?"green":"blue",children:B?"Current":"Saved"}):B?o.jsx(St,{variant:"green",children:"Published"}):z?o.jsx(St,{variant:"blue",children:"Draft"}):void 0}}),[T,t,I,u]),R=n??E?.id??"",L=c||!s||a||i,D=u?"Code mode saves write override JSON to filesystem-backed editor storage. This dropdown shows saved override snapshots for this agent.":"Changes are saved as draft versions. When you're ready, publish a version to make it the active configuration used in production.",F=g.useCallback(async()=>{if(a)return;const H=k.trim();await h(H||void 0),S(!1),_("")},[k,h,a]);return{versionSelector:o.jsxs("div",{className:"border-border1 bg-surface3 flex items-center gap-2 border-b px-4 py-3",children:[T.length>0?o.jsx(ml,{options:A,value:R,onValueChange:r,placeholder:"Select version...",variant:"ghost",className:"min-w-0 flex-1"}):o.jsx(me,{variant:"ui-xs",className:"text-neutral3",children:u?"No filesystem saves yet":"No versions yet"}),R&&o.jsx(ka,{content:R,tooltip:"Copy version ID",size:"sm"}),o.jsxs(yn,{children:[o.jsx(gn,{"aria-label":"Version information",className:"text-neutral3 hover:text-neutral5 shrink-0 rounded-sm transition-colors focus-visible:ring-1 focus-visible:ring-white/30 focus-visible:outline-hidden",children:o.jsx(He,{size:"sm",children:o.jsx(km,{})})}),o.jsx(vn,{side:"bottom",align:"start",className:"max-w-56",children:D})]}),o.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-2",children:[c&&o.jsx(St,{variant:"yellow",children:"Read-only"}),!c&&l&&!u&&o.jsx(St,{variant:"blue",children:"Unpublished"})]})]}),actionBar:o.jsxs("div",{className:"border-border1 bg-surface3 flex items-center justify-end border-t px-3 py-2",children:[d?o.jsxs(hs,{className:"flex-wrap justify-end",children:[o.jsxs(oe,{variant:"default",size:"md",onClick:()=>{v?.()},children:[o.jsx(He,{size:"sm",children:o.jsx(Pd,{})}),"Download JSON"]}),f?o.jsxs(oe,{variant:"primary",size:"md",onClick:()=>{y?.()},title:p,children:[o.jsx(He,{size:"sm",children:o.jsx(Flt,{})}),"Open PR"]}):o.jsx(oe,{variant:"primary",size:"md",onClick:()=>{h()},disabled:L,children:a?o.jsxs(o.Fragment,{children:[o.jsx(Ut,{className:"size-3.5"}),"Saving…"]}):o.jsxs(o.Fragment,{children:[o.jsx(He,{size:"sm",children:o.jsx(Gu,{})}),"Save to filesystem"]})})]}):c&&!b?null:o.jsxs(hs,{className:"flex-wrap justify-end",children:[o.jsxs(hs,{spacing:"close",children:[o.jsx(oe,{variant:"default",size:"md",onClick:()=>h(),disabled:L,children:a?o.jsxs(o.Fragment,{children:[o.jsx(Ut,{className:"size-3.5"}),"Saving…"]}):o.jsxs(o.Fragment,{children:[o.jsx(He,{size:"sm",children:o.jsx(Gu,{})}),"Save New Version"]})}),o.jsxs(rt,{children:[o.jsx(rt.Trigger,{asChild:!0,children:o.jsx(oe,{variant:"default",size:"md",disabled:L,"aria-label":"More save options",children:o.jsx(Xs,{className:"size-3.5"})})}),o.jsx(rt.Content,{align:"end",children:o.jsxs(rt.Item,{onSelect:()=>S(!0),children:[o.jsx(He,{size:"sm",children:o.jsx(u0e,{})}),"Save with message"]})})]})]}),o.jsx(oe,{variant:"primary",size:"md",onClick:m,disabled:b?n===t||i||a:c||!l||i||a,children:i?o.jsxs(o.Fragment,{children:[o.jsx(Ut,{className:"size-3.5"}),"Publishing…"]}):o.jsxs(o.Fragment,{children:[o.jsx(He,{size:"sm",children:o.jsx(Qr,{})}),b?"Publish This Version":"Publish"]})})]}),o.jsx(vr,{open:x,onOpenChange:S,children:o.jsxs(yr,{children:[o.jsxs(br,{children:[o.jsx(pr,{children:"Save New Version"}),o.jsx(Ps,{children:"Add a message to describe the changes in this version."})]}),o.jsx(Mr,{className:"py-1",children:o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{htmlFor:"change-message",children:"Change message"}),o.jsx(In,{id:"change-message",placeholder:"Describe what changed...",value:k,className:"focus:ring-white/50",onChange:H=>_(H.target.value),onKeyDown:H=>{H.key==="Enter"&&F()},disabled:a,autoFocus:!0})]})}),o.jsxs(lc,{className:"px-6",children:[o.jsx(oe,{variant:"default",size:"sm",onClick:()=>S(!1),children:"Cancel"}),o.jsxs(oe,{variant:"primary",size:"sm",onClick:F,disabled:a,children:[o.jsx(He,{size:"sm",children:o.jsx(Gu,{})}),"Save Version"]})]})]})})]})}}function gis({agentId:e,activeVersionId:t,selectedVersionId:n,latestVersionId:r,onVersionSelect:s,isDirty:a,isSavingDraft:i,isPublishing:l,hasDraft:c,readOnly:u,isCodeSourceAgent:d,showCodeModeActions:f,canOpenPr:p,openPrTitle:h,onSaveDraft:m,onPublish:v,onDownloadJson:y,onOpenPr:b,isViewingPreviousVersion:x}){const{versionSelector:S,actionBar:k}=mis({agentId:e,activeVersionId:t,selectedVersionId:n,onVersionSelect:s,isDirty:a,isSavingDraft:i,isPublishing:l,hasDraft:c,readOnly:u,isCodeSourceAgent:d,showCodeModeActions:f,canOpenPr:p,openPrTitle:h,onSaveDraft:m,onPublish:v,onDownloadJson:y,onOpenPr:b,isViewingPreviousVersion:x});return o.jsxs(zzr,{children:[S,o.jsx("div",{className:"px-4 pt-3",children:o.jsx(me,{variant:"ui-sm",className:"text-neutral3",children:"Edit your agent's system prompt, tools, and variables below."})}),o.jsx("div",{className:"min-h-0 flex-1",children:o.jsx(nis,{agentId:e,selectedVersionId:n,latestVersionId:r})}),k]})}function vis({agentId:e,agentName:t,modelVersion:n,agentVersionId:r,hasMemory:s,activeVersionId:a,selectedVersionId:i,latestVersionId:l,onVersionSelect:c,isDirty:u,isSavingDraft:d,isPublishing:f,hasDraft:p,readOnly:h,isCodeSourceAgent:m,showCodeModeActions:v,canOpenPr:y,openPrTitle:b,onSaveDraft:x,onPublish:S,onDownloadJson:k,onOpenPr:_,isViewingPreviousVersion:C}){return o.jsx(Urs,{agentId:e,leftDrawerLabel:"Open configuration",leftSlot:o.jsx(gis,{agentId:e,activeVersionId:a,selectedVersionId:i,latestVersionId:l,onVersionSelect:c,isDirty:u,isSavingDraft:d,isPublishing:f,hasDraft:p,readOnly:h,isCodeSourceAgent:m,showCodeModeActions:v,canOpenPr:y,openPrTitle:b,onSaveDraft:x,onPublish:S,onDownloadJson:k,onOpenPr:_,isViewingPreviousVersion:C}),children:o.jsx(pis,{agentId:e,agentName:t,modelVersion:n,agentVersionId:r,hasMemory:s})})}function zN(e,t){return typeof t=="number"||/^\d+(\.\d+)*$/.test(String(t))?`${e} v${t}`:`${e} ${t}`}const DD=(e,t,n)=>{const r=Qe();return yt({queryKey:["dataset-experiments",e,t,n],queryFn:()=>r.listDatasetExperiments(e,t),enabled:!!e,select:s=>{if(!n)return s;const a=s.experiments.filter(i=>!(n.status&&i.status!==n.status||n.targetType&&i.targetType!==n.targetType||n.targetId&&i.targetId!==n.targetId));return{...s,experiments:a}}})},Exe=(e,t)=>{const n=Qe();return yt({queryKey:["dataset-experiment",e,t],queryFn:()=>n.getDatasetExperiment(e,t),enabled:!!e&&!!t,gcTime:0,staleTime:0,refetchInterval:r=>{const s=r.state.data?.status;return s==="running"||s==="pending"?2e3:!1}})},fJe=100,LD=({datasetId:e,experimentId:t,experimentStatus:n})=>{const r=Qe(),{inView:s,setRef:a}=tC(),i=K1({queryKey:["dataset-experiment-results",e,t,n],queryFn:async({pageParam:l})=>r.listDatasetExperimentResults(e,t,{page:l,perPage:fJe}),initialPageParam:0,getNextPageParam:(l,c,u)=>{if(!l?.results?.length)return;const d=(u+1)*fJe,f=l?.pagination?.total??0;if(!(d>=f))return u+1},enabled:!!e&&!!t,refetchInterval:n==="running"||n==="pending"?2e3:!1,select:l=>l.pages.flatMap(c=>c?.results??[])});return g.useEffect(()=>{s&&i.hasNextPage&&!i.isFetchingNextPage&&i.fetchNextPage()},[s,i.hasNextPage,i.isFetchingNextPage]),{...i,setEndOfListElement:a}},w_=(e,t)=>{const n=Qe();return yt({queryKey:["dataset-experiment-scores",e,t],queryFn:async()=>{const r=[];let s=0;const a=100;for(;;){const l=await n.listScoresByRunId({runId:e,page:s,perPage:a});if(r.push(...l.scores),!l.pagination.hasMore)break;s++}const i={};for(const l of r)i[l.entityId]||(i[l.entityId]=[]),i[l.entityId].push(l);return i},enabled:!!e,refetchInterval:t==="running"||t==="pending"?2e3:!1})},rUt="minmax(9rem,1fr)",yis="1fr",sUt="auto auto auto auto auto auto auto",au={experiment:"Experiment",dataset:"Dataset",target:"Target",status:"Status",items:"Items",succeeded:"Processed",failed:"Errored",review:"Review",date:"Date"},aUt={completed:"neutral",running:"yellow",failed:"red",pending:"neutral"},RT={completed:"Run completed",running:"Run in progress",failed:"Run failed",pending:"Run queued"};function bis(e){return e?(typeof e=="string"?new Date(e):e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function xis(e){return new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function wis({status:e}){switch(e){case"completed":return o.jsx(St,{variant:"neutral",icon:o.jsx(mO,{}),children:RT.completed});case"failed":return o.jsx(St,{variant:"red",icon:o.jsx(gO,{}),children:RT.failed});case"running":return o.jsx(St,{variant:"blue",icon:o.jsx(qs,{className:"motion-safe:animate-spin motion-reduce:animate-none"}),children:RT.running});case"pending":return o.jsx(St,{variant:"neutral",icon:o.jsx(r1,{}),children:RT.pending});default:return o.jsx(St,{children:e})}}function Txe(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Sis(e){return Array.isArray(e)?e.flatMap(t=>{if(!t||typeof t!="object")return[];const n=t;return[{toolName:typeof n.toolName=="string"?n.toolName:"Unknown tool",args:n.args&&typeof n.args=="object"&&!Array.isArray(n.args)?n.args:{}}]}):[]}function kis(e){const t=e&&typeof e=="object"?e:{};return{text:typeof t.text=="string"?t.text:void 0,object:t.object&&typeof t.object=="object"?t.object:void 0,toolCalls:Sis(t.toolCalls),toolResults:Array.isArray(t.toolResults)?t.toolResults:[],usage:t.usage&&typeof t.usage=="object"?t.usage:void 0,traceId:typeof t.traceId=="string"?t.traceId:void 0,error:typeof t.error=="string"?t.error:t.error?String(t.error):void 0}}function Ois({traceId:e}){const t=Qe(),[n,r]=g.useState(!1),{data:s,isLoading:a,isError:i}=yt({queryKey:["trajectory",e],queryFn:()=>t.getTraceTrajectory(e),enabled:n});return o.jsxs(Fc,{open:n,onOpenChange:r,children:[o.jsxs(cc,{className:"flex items-center gap-1.5 text-xs font-medium text-purple-400 hover:text-purple-300",children:[o.jsx(Ur,{className:"h-3 w-3 shrink-0"}),"Trajectory Steps"]}),o.jsx(uc,{children:a?o.jsxs("div",{className:"mt-1 flex items-center gap-2 px-3 py-2",children:[o.jsx(Ut,{className:"h-3 w-3"}),o.jsx(me,{variant:"ui-xs",className:"text-neutral3",children:"Loading trajectory..."})]}):i?o.jsx(me,{variant:"ui-xs",className:"mt-1 px-3 py-2 text-red-400",children:"Failed to load trajectory steps"}):s?.steps&&s.steps.length>0?o.jsxs("div",{className:"mt-1 space-y-1",children:[s.steps.map((l,c)=>o.jsxs("div",{className:"bg-surface1 flex items-center gap-2 rounded px-3 py-1.5 text-xs",children:[o.jsx(St,{size:"xs",variant:"purple",children:String(l.stepType||"step")}),o.jsx("span",{className:"text-neutral5 font-mono font-medium",children:String(l.name||`Step ${c+1}`)}),typeof l.durationMs=="number"&&o.jsxs("span",{className:"text-neutral2 ml-auto",children:[l.durationMs,"ms"]})]},c)),typeof s.totalDurationMs=="number"&&o.jsxs(me,{variant:"ui-xs",className:"text-neutral3 px-3 py-1",children:["Total: ",s.totalDurationMs,"ms"]})]}):o.jsx(me,{variant:"ui-xs",className:"text-neutral2 mt-1 px-3 py-2",children:"No trajectory steps found"})})]})}function _is({output:e,traceId:t,onViewTrace:n}){const r=kis(e),s=t||r.traceId;return o.jsxs("div",{className:"space-y-2",children:[r.text?o.jsxs("div",{className:"space-y-1",children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Response"}),o.jsx("div",{className:"text-neutral5 bg-surface1 max-h-48 overflow-y-auto rounded px-3 py-2 text-sm wrap-break-word whitespace-pre-wrap",children:r.text})]}):null,r.object&&o.jsxs("div",{className:"space-y-1",children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Structured Output"}),o.jsx("pre",{className:"text-neutral4 bg-surface1 max-h-48 overflow-x-auto overflow-y-auto rounded px-3 py-2 text-xs wrap-break-word whitespace-pre-wrap",children:JSON.stringify(r.object,null,2)})]}),r.toolCalls.length>0&&o.jsxs("div",{className:"space-y-1",children:[o.jsxs(me,{variant:"ui-xs",className:"text-neutral3 font-medium",children:["Tool Calls (",r.toolCalls.length,")"]}),o.jsx("div",{className:"space-y-1",children:r.toolCalls.map((a,i)=>o.jsxs(Fc,{children:[o.jsxs(cc,{className:"text-neutral4 hover:text-neutral5 bg-surface1 flex w-full items-center gap-1.5 rounded px-2 py-1 text-left text-xs",children:[o.jsx(Ur,{className:"h-3 w-3 shrink-0"}),o.jsx("span",{className:"font-mono font-medium",children:a.toolName})]}),o.jsx(uc,{children:o.jsx("pre",{className:"text-neutral4 bg-surface2 mt-1 ml-4 max-h-32 overflow-x-auto overflow-y-auto rounded px-3 py-2 text-xs wrap-break-word whitespace-pre-wrap",children:JSON.stringify(a.args,null,2)})})]},i))})]}),r.toolResults.length>0&&o.jsxs("div",{className:"space-y-1",children:[o.jsxs(me,{variant:"ui-xs",className:"text-neutral3 font-medium",children:["Tool Results (",r.toolResults.length,")"]}),o.jsx("div",{className:"space-y-1",children:r.toolResults.map((a,i)=>o.jsxs(Fc,{children:[o.jsxs(cc,{className:"text-neutral4 hover:text-neutral5 bg-surface1 flex w-full items-center gap-1.5 rounded px-2 py-1 text-left text-xs",children:[o.jsx(Ur,{className:"h-3 w-3 shrink-0"}),o.jsxs("span",{className:"font-mono",children:["Result ",i+1]})]}),o.jsx(uc,{children:o.jsx("pre",{className:"text-neutral4 bg-surface2 mt-1 ml-4 max-h-32 overflow-x-auto overflow-y-auto rounded px-3 py-2 text-xs wrap-break-word whitespace-pre-wrap",children:JSON.stringify(a,null,2)})})]},i))})]}),r.usage&&o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Usage"}),o.jsxs(me,{variant:"ui-xs",className:"text-neutral2 font-mono",children:[r.usage.promptTokens," prompt · ",r.usage.completionTokens," completion · ",r.usage.totalTokens," ","total"]})]}),s&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Trace"}),o.jsx(me,{variant:"ui-xs",className:"text-neutral2 truncate font-mono",children:s}),o.jsx(ka,{content:s,tooltip:"Copy trace ID",size:"sm"}),n&&o.jsxs("button",{type:"button",onClick:()=>n(s),className:"text-accent1 hover:text-accent2 flex cursor-pointer items-center gap-1 text-xs transition-colors",children:[o.jsx(Yr,{className:"h-3 w-3"}),"View Trace"]})]}),!r.text&&!r.object&&r.toolCalls.length===0&&o.jsxs("div",{className:"space-y-1",children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Output"}),o.jsx("pre",{className:"text-neutral4 bg-surface1 max-h-48 overflow-x-auto overflow-y-auto rounded px-3 py-2 text-xs wrap-break-word whitespace-pre-wrap",children:Txe(e)})]})]})}function Cis({experiment:e,onBack:t,onSendToReview:n,onCreateScorer:r}){const[s,a]=g.useState(new Set),i=e.status,{data:l,isLoading:c,setEndOfListElement:u,isFetchingNextPage:d,hasNextPage:f}=LD({datasetId:e.datasetId,experimentId:e.id,experimentStatus:i}),{data:p}=w_(e.id,i),h=e.targetType==="agent"?e.targetId??void 0:void 0,{data:m}=vS({agentId:h}),v=m?.versions??[],{navigate:y}=cn(),b=_=>{a(C=>{const T=new Set(C);return T.has(_)?T.delete(_):T.add(_),T})},x=()=>{if(!l)return;const _=l.filter(C=>!!C.error).map(C=>C.id);a(new Set(_))},S=()=>a(new Set),k=l?.filter(_=>s.has(_.id))||[];return o.jsxs("div",{className:"flex h-full flex-col",children:[o.jsxs("div",{className:"border-border1 flex items-center gap-2 border-b px-4 py-3",children:[o.jsxs("button",{type:"button",onClick:t,className:"text-neutral3 hover:text-neutral5 flex cursor-pointer items-center gap-1 transition-colors",children:[o.jsx(He,{size:"sm",children:o.jsx(gl,{})}),o.jsx(me,{variant:"ui-xs",children:"Back"})]}),o.jsx("div",{className:"flex-1"}),o.jsx(wis,{status:e.status}),o.jsxs(me,{variant:"ui-xs",className:"text-neutral2",children:[e.datasetName,e.datasetVersion!=null&&` ${zN("Dataset",e.datasetVersion)}`,e.agentVersion&&(()=>{const _=v.find(T=>T.id===e.agentVersion),C=zN("Agent",_?_.versionNumber:e.agentVersion);return o.jsxs(o.Fragment,{children:[" · ",o.jsx("button",{type:"button",className:"hover:text-neutral5 cursor-pointer underline transition-colors",onClick:()=>y(`/agents/${h}/editor?version=${encodeURIComponent(e.agentVersion)}`),children:C})]})})()," · ",e.startedAt?xis(e.startedAt):"-"]})]}),s.size>0&&o.jsxs("div",{className:"bg-surface3 border-border1 flex items-center gap-2 border-b px-4 py-2",children:[o.jsxs(me,{variant:"ui-xs",className:"text-neutral5 font-medium",children:[s.size," selected"]}),o.jsx("div",{className:"flex-1"}),r&&o.jsxs(oe,{variant:"outline",size:"sm",onClick:()=>{r(k.map(_=>({input:_.input,output:_.output})))},children:[o.jsx(He,{size:"sm",children:o.jsx(WGt,{})}),"Create Scorer"]}),n&&o.jsxs(oe,{variant:"outline",size:"sm",onClick:()=>{n(k.map(_=>{const C=p?.[_.itemId],T={};if(C)for(const E of C)typeof E.score=="number"&&(T[E.scorerId||"unknown"]=E.score);return{id:_.id,input:_.input,output:_.output,error:_.error,itemId:_.itemId,datasetId:e.datasetId,scores:T,experimentId:e.id,traceId:_.traceId??void 0}}))},children:[o.jsx(He,{size:"sm",children:o.jsx(vO,{})}),"Send to Review"]}),o.jsx(oe,{variant:"ghost",size:"sm",onClick:S,children:"Clear"})]}),l&&l.length>0&&s.size===0&&o.jsx("div",{className:"border-border1 flex items-center gap-2 border-b px-4 py-2",children:o.jsx(oe,{variant:"ghost",size:"sm",onClick:x,children:"Select all failures"})}),o.jsx(Dr,{className:"min-h-0 flex-1",children:c?o.jsx("div",{className:"flex items-center justify-center py-8",children:o.jsx(Ut,{className:"h-5 w-5"})}):!l||l.length===0?o.jsx("div",{className:"px-4 py-8 text-center",children:o.jsx(me,{variant:"ui-sm",className:"text-neutral2",children:"No results yet"})}):o.jsxs("div",{children:[l.map(_=>{const C=!!_.error,T=p?.[_.itemId]??[],E=T.filter(A=>A.entityType!=="TRAJECTORY"),N=T.filter(A=>A.entityType==="TRAJECTORY"),I=s.has(_.id);return o.jsxs("div",{className:K("border-b border-border1 px-4 py-3 space-y-2",I&&"bg-surface3/50"),children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(So,{checked:I,onCheckedChange:()=>b(_.id)}),o.jsx(St,{variant:C?"red":"green",children:C?"Error":"Success"}),o.jsx(me,{variant:"ui-xs",className:"text-neutral2 font-mono",children:_.itemId.slice(0,8)}),T.length>0&&o.jsxs("div",{className:"ml-auto flex flex-wrap items-center gap-2",children:[E.map(A=>o.jsxs(St,{children:[A.scorerId,": ",A.score.toFixed(3)]},A.scorerId)),N.map(A=>o.jsxs(St,{size:"xs",variant:"purple",children:[A.scorerId,": ",A.score.toFixed(3)]},A.scorerId))]})]}),N.length>0&&o.jsxs(Fc,{children:[o.jsxs(cc,{className:"flex items-center gap-1.5 text-xs font-medium text-purple-400 hover:text-purple-300",children:[o.jsx(Ur,{className:"h-3 w-3 shrink-0"}),"Trajectory Score Details"]}),o.jsx(uc,{children:o.jsx("div",{className:"mt-1 space-y-2",children:N.map(A=>o.jsxs("div",{className:"bg-surface1 space-y-1 rounded px-3 py-2",children:[o.jsx(me,{variant:"ui-xs",className:"font-medium text-purple-400",children:A.scorerId}),A.reason&&o.jsx("p",{className:"text-neutral4 text-xs",children:A.reason}),A.preprocessStepResult&&o.jsx("pre",{className:"text-neutral3 max-h-48 overflow-x-auto overflow-y-auto text-xs break-words whitespace-pre-wrap",children:JSON.stringify(A.preprocessStepResult,null,2)})]},A.scorerId))})})]}),_.traceId&&N.length>0&&o.jsx(Ois,{traceId:_.traceId}),o.jsxs(Fc,{children:[o.jsxs(cc,{className:"text-neutral3 hover:text-neutral5 flex items-center gap-1.5 text-xs font-medium",children:[o.jsx(Ur,{className:"h-3 w-3 shrink-0"}),"Input"]}),o.jsx(uc,{children:o.jsx("pre",{className:"text-neutral4 bg-surface1 mt-1 max-h-32 overflow-x-auto overflow-y-auto rounded px-3 py-2 text-xs wrap-break-word whitespace-pre-wrap",children:Txe(_.input)})})]}),C?o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(me,{variant:"ui-xs",className:"font-medium text-red-400",children:"Error"}),o.jsx("pre",{className:"bg-surface1 max-h-32 overflow-x-auto overflow-y-auto rounded px-3 py-2 text-xs wrap-break-word whitespace-pre-wrap text-red-300",children:Txe(_.error)})]}),_.traceId&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Trace"}),o.jsx(me,{variant:"ui-xs",className:"text-neutral2 truncate font-mono",children:_.traceId}),o.jsx(ka,{content:_.traceId,tooltip:"Copy trace ID",size:"sm"}),o.jsxs("button",{type:"button",onClick:()=>y(`/traces?traceId=${encodeURIComponent(_.traceId??"")}`),className:"text-accent1 hover:text-accent2 flex cursor-pointer items-center gap-1 text-xs transition-colors",children:[o.jsx(Yr,{className:"h-3 w-3"}),"View Trace"]})]})]}):o.jsx(_is,{output:_.output,traceId:_.traceId,onViewTrace:A=>y(`/traces?traceId=${encodeURIComponent(A)}`)})]},_.id)}),o.jsxs("div",{ref:u,className:"h-1",children:[d&&o.jsx("div",{className:"flex items-center justify-center py-4",children:o.jsx(Ut,{className:"h-4 w-4"})}),!f&&l.length>0&&o.jsx("div",{className:"py-2 text-center",children:o.jsx(me,{variant:"ui-xs",className:"text-neutral2",children:"All results loaded"})})]})]})})]})}function Eis({children:e,className:t}){return o.jsx("div",{className:K("grid content-start gap-8 overflow-y-auto",t),children:e})}function Tis({children:e,className:t,withLeftSeparator:n,withRightSeparator:r}){return o.jsxs("div",{className:"flex w-full overflow-y-auto",children:[n&&o.jsx(pJe,{}),o.jsx("div",{className:K("grid w-full content-start gap-8 overflow-y-auto",t),children:e}),r&&o.jsx(pJe,{})]})}function pJe(){return o.jsx("div",{className:K("mx-[1.5vw] w-[3px] shrink-0 bg-surface5")})}function jis({children:e,className:t}){return o.jsx("div",{className:K("flex w-full flex-wrap items-center justify-between gap-4 gap-x-6",t),children:e})}const ta=Object.assign(Tis,{Content:Eis,Toolbar:jis});function vx({children:e,className:t}){return o.jsx("div",{className:K("grid size-full grid-cols-1 overflow-y-auto",t),children:e})}const XIe=(e,t=[])=>{const n=Qe(),{data:r}=Im(),s=r?.datasets??[];return yt({queryKey:["agent-experiments",e,t,s.map(a=>a.id)],queryFn:async()=>{if(s.length===0)return[];const a=new Set(t),i=await Promise.all(s.map(async c=>{try{return(await n.listDatasetExperiments(c.id)).experiments.filter(d=>d.targetType==="agent"&&d.targetId===e||d.targetType==="scorer"&&d.targetId!==null&&a.has(d.targetId)).map(d=>({...d,datasetId:c.id,datasetName:c.name}))}catch{return[]}})),l=c=>c?c instanceof Date?c.getTime():new Date(c).getTime():0;return i.flat().sort((c,u)=>l(u.startedAt)-l(c.startedAt))},enabled:!!e&&s.length>0,refetchInterval:a=>{const i=a.state.data;return i&&i.some(c=>c.status==="running"||c.status==="pending")?3e3:!1}})},FD=(e,t)=>{const n=Qe();return yt({queryKey:["dataset-item",e,t],queryFn:()=>n.getDatasetItem(e,t),enabled:!!e&&!!t,retry:!1})},hJe=10,Zx=(e,t,n)=>{const r=Qe(),{inView:s,setRef:a}=tC(),i=K1({queryKey:["dataset-items",e,t,n],queryFn:async({pageParam:u})=>await r.listDatasetItems(e,{page:u,perPage:hJe,search:t||void 0,version:n||void 0}),initialPageParam:0,getNextPageParam:(u,d,f)=>{if(!u?.items?.length)return;const p=(f+1)*hJe,h=u?.pagination?.total??0;if(!(p>=h))return f+1},enabled:!!e,retry:!1}),l=i.data?.pages.flatMap(u=>u?.items??[])??[],c=i.data?.pages[0]?.pagination?.total;return g.useEffect(()=>{s&&i.hasNextPage&&!i.isFetchingNextPage&&i.fetchNextPage()},[s,i.hasNextPage,i.isFetchingNextPage]),{...i,data:l,total:c,setEndOfListElement:a}},Nis=10,JIe=e=>{const t=Qe();return K1({queryKey:["dataset-versions",e],queryFn:async({pageParam:n})=>t.listDatasetVersions(e,{page:n,perPage:Nis}),initialPageParam:0,getNextPageParam:(n,r,s)=>{if(n?.pagination?.hasMore)return s+1},select:n=>n.pages.flatMap(r=>r?.versions??[]).map((r,s)=>({id:r.id,datasetId:r.datasetId,version:r.version,createdAt:r.createdAt,isCurrent:s===0})),enabled:!!e})};function Iis(e){const t=new Date(e);return t.toLocaleDateString("en-US",{month:"short",day:"numeric"})+", "+t.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"})}function Ais(e,t=120){if(e==null)return"-";const n=typeof e=="string"?e:JSON.stringify(e);return!n||n.length<=t?n||"-":n.slice(0,t)+"…"}function Ris(e){const t=e,n=Array.isArray(t?.steps)?t.steps.length:0;return n>0?`${n} expected steps`:"trajectory"}const mJe=["blue","green","purple","orange","cyan","pink","red","yellow"];function Pis(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return mJe[Math.abs(t)%mJe.length]}function $is({agentId:e,datasetId:t,datasetName:n,datasetDescription:r,datasetTags:s=[],datasetTargetType:a,datasetTargetIds:i,activeScorers:l=[],datasetScorerIds:c=[],onGenerate:u,onViewExperiment:d}){const[f,p]=g.useState(!1),h=g.useRef(!1),[m,v]=g.useState(null),[y,b]=g.useState(!1),[x,S]=g.useState(!1),[k,_]=g.useState(!1),[C,T]=g.useState(!1),[E,N]=g.useState(""),[I,A]=g.useState(""),[R,L]=g.useState(""),{data:D}=oh(),{updateDataset:F}=qi(),H=g.useMemo(()=>new Set(c??[]),[c]),B=g.useMemo(()=>D?Object.entries(D).filter(([ce])=>H.has(ce)):[],[D,H]),z=g.useMemo(()=>D?Object.entries(D).filter(([ce])=>!H.has(ce)):[],[D,H]),V=g.useCallback(async ce=>{const Se=[...c??[],ce];try{await F.mutateAsync({datasetId:t,scorerIds:Se})}catch(ve){throw Be.error("Failed to attach scorer"),ve}},[t,c,F]),M=g.useCallback(async ce=>{const Se=(c??[]).filter(ve=>ve!==ce);try{await F.mutateAsync({datasetId:t,scorerIds:Se})}catch{Be.error("Failed to detach scorer")}},[t,c,F]),{data:G=[],setEndOfListElement:U,isFetchingNextPage:$}=Zx(t),{data:q,refetch:Z}=DD(t),Y=q?.experiments??[],J=JIe(t).data??[],ee=!a||a==="agent",le=vS({agentId:e,enabled:ee}).data?.versions??[];g.useEffect(()=>{A("")},[t]),g.useEffect(()=>{L("")},[e]);const X=Bl(),te=Lr(),{triggerExperiment:se}=qi(),pe=g.useCallback(async()=>{if(!h.current){h.current=!0,p(!0);try{const ce=Object.keys(X).length>0,Se=a==="scorer"||a==="workflow"?a:"agent",ve=Array.isArray(i)?i:typeof i=="string"?(()=>{try{return JSON.parse(i)}catch{return[]}})():[],ke=Se!=="agent"&&ve[0]?ve[0]:e;await se.mutateAsync({datasetId:t,targetType:Se,targetId:ke,...l.length>0?{scorerIds:l}:{},...ce?{requestContext:X}:{},...I?{version:Number(I)}:{},...R?{agentVersion:R}:{}}),te.invalidateQueries({queryKey:["agent-experiments",e]}),Z();const Ne=setInterval(()=>Z(),3e3);setTimeout(()=>clearInterval(Ne),3e4),Be.success("Experiment started")}catch(ce){Be.error(`Failed to start experiment: ${ce instanceof Error?ce.message:"Unknown error"}`)}finally{h.current=!1,p(!1)}}},[t,l,e,a,i,se,X,te,Z,I,R]);return o.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[o.jsxs("div",{className:"border-border1 space-y-3 border-b p-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx(me,{variant:"ui-sm",className:"text-neutral5 block truncate font-medium",children:n}),r&&o.jsx(me,{variant:"ui-xs",className:"text-neutral3 mt-0.5 block truncate",children:r}),s.length>0&&o.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:s.map(ce=>o.jsx(St,{variant:Pis(ce),size:"xs",children:ce},ce))})]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[o.jsxs(oe,{variant:"ghost",size:"sm",onClick:u,children:[o.jsx(He,{size:"sm",children:o.jsx($g,{})}),"Generate"]}),o.jsx(oe,{variant:"primary",size:"sm",onClick:pe,disabled:G.length===0||f,children:f?o.jsxs(o.Fragment,{children:[o.jsx(Ut,{className:"h-3 w-3"})," Running..."]}):o.jsxs(o.Fragment,{children:[o.jsx(He,{size:"sm",children:o.jsx(Dc,{})})," ","Run Experiment"]})})]})]}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3 mb-1 block",children:"Dataset version"}),o.jsx(ml,{options:[{label:"Latest",value:""},...J.map(ce=>({label:`v${ce.version}`,value:String(ce.version),description:ce.isCurrent?"Current":void 0}))],value:I,onValueChange:A,placeholder:"Latest",size:"sm"})]}),ee&&o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3 mb-1 block",children:"Agent version"}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(ml,{options:[{label:"Current",value:""},...le.map(ce=>({label:`v${ce.versionNumber}`,value:ce.id,description:ce.changeMessage??void 0}))],value:R,onValueChange:L,placeholder:"Current",size:"sm"}),(R||le[0]?.id)&&o.jsx(ka,{content:R||le[0]?.id,tooltip:"Copy version ID",size:"sm"})]})]})]})]}),o.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:o.jsxs(Dr,{className:"min-h-0 flex-1",children:[o.jsxs("div",{className:"border-border1 border-b",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("button",{type:"button",onClick:()=>_(ce=>!ce),className:"hover:bg-surface3 flex flex-1 items-center gap-1 px-4 py-2 transition-colors",children:[o.jsx(He,{size:"sm",className:"text-neutral3",children:k?o.jsx(Ur,{}):o.jsx(Xs,{})}),o.jsxs(me,{variant:"ui-xs",className:"text-neutral3 font-semibold tracking-wider uppercase",children:["Scorers (",B.length,")"]})]}),z.length>0&&o.jsx("div",{className:"pr-2",children:o.jsx(oe,{variant:"ghost",size:"sm",onClick:()=>T(!0),children:"Attach"})})]}),!k&&(B.length===0?o.jsxs("div",{className:"px-4 py-4 text-center",children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3",children:"No scorers attached to this dataset."}),z.length>0&&o.jsx("div",{className:"mt-2",children:o.jsx(oe,{variant:"outline",size:"sm",onClick:()=>T(!0),children:"Attach a scorer"})})]}):o.jsx("div",{className:"divide-border1 divide-y",children:B.map(([ce,Se])=>{const ve=Se.scorer?.name||ce;return o.jsxs("div",{className:"hover:bg-surface3 group flex items-center justify-between px-4 py-1.5 transition-colors",children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral5 truncate",children:ve}),o.jsx("button",{type:"button",onClick:()=>M(ce),"aria-label":`Detach "${ve}" from this dataset`,className:"text-neutral3 p-0.5 opacity-0 transition-opacity group-hover:opacity-100 hover:text-red-500 focus-visible:opacity-100",title:"Detach scorer",children:o.jsx(He,{size:"sm",children:o.jsx(or,{})})})]},ce)})}))]}),o.jsxs("div",{className:"border-border1 border-b",children:[o.jsxs("button",{type:"button",onClick:()=>b(ce=>!ce),className:"hover:bg-surface3 flex w-full items-center gap-1 px-4 py-2 transition-colors",children:[o.jsx(He,{size:"sm",className:"text-neutral3",children:y?o.jsx(Ur,{}):o.jsx(Xs,{})}),o.jsxs(me,{variant:"ui-xs",className:"text-neutral3 font-semibold tracking-wider uppercase",children:["Items (",G.length,")"]})]}),!y&&(G.length===0?o.jsx("div",{className:"px-4 py-6 text-center",children:o.jsx(me,{variant:"ui-xs",className:"text-neutral3",children:"No items yet. Use Generate to create test data."})}):o.jsxs("div",{className:"divide-border1 divide-y",children:[G.map(ce=>{const Se=m===ce.id;return o.jsxs("div",{children:[o.jsxs("button",{type:"button",onClick:()=>v(Se?null:ce.id),className:"hover:bg-surface3 flex w-full items-start gap-2 px-4 py-2 text-left transition-colors",children:[o.jsx(He,{size:"sm",className:"text-neutral3 mt-0.5 shrink-0",children:Se?o.jsx(Xs,{}):o.jsx(Ur,{})}),o.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral5 block flex-1 truncate",children:Ais(ce.input)}),ce.expectedTrajectory!=null&&o.jsx(St,{size:"xs",variant:"purple",children:Ris(ce.expectedTrajectory)})]})]}),Se&&o.jsx(Mis,{datasetId:t,item:ce})]},ce.id)}),o.jsx("div",{ref:U}),$&&o.jsx("div",{className:"flex items-center justify-center py-2",children:o.jsx(Ut,{className:"h-3 w-3"})})]}))]}),o.jsxs("div",{children:[o.jsxs("button",{type:"button",onClick:()=>S(ce=>!ce),className:"hover:bg-surface3 flex w-full items-center gap-1 px-4 py-2 transition-colors",children:[o.jsx(He,{size:"sm",className:"text-neutral3",children:x?o.jsx(Ur,{}):o.jsx(Xs,{})}),o.jsx(He,{size:"sm",className:"text-neutral3",children:o.jsx(r1,{})}),o.jsxs(me,{variant:"ui-xs",className:"text-neutral3 font-semibold tracking-wider uppercase",children:["Past Runs (",Y.length,")"]})]}),!x&&(Y.length===0?o.jsx("div",{className:"px-4 py-4 text-center",children:o.jsx(me,{variant:"ui-xs",className:"text-neutral3",children:"No experiment runs yet"})}):o.jsx("div",{className:"divide-border1 divide-y",children:Y.map(ce=>o.jsxs("button",{type:"button",onClick:()=>d(ce.id),className:"hover:bg-surface3 flex w-full items-center gap-2 px-4 py-2 text-left transition-colors",children:[o.jsx(Dis,{status:ce.status}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral5 block",children:ce.startedAt?Iis(ce.startedAt):"Unknown"}),o.jsxs(me,{variant:"ui-xs",className:"text-neutral3",children:[ce.totalItems," items",ce.failedCount>0&&` · ${ce.failedCount} errored`,ce.datasetVersion!=null&&` · ${zN("Dataset",ce.datasetVersion)}`,ce.agentVersion&&(()=>{const Se=le.find(ve=>ve.id===ce.agentVersion);return` · ${zN("Agent",Se?Se.versionNumber:ce.agentVersion)}`})()]})]}),o.jsx(He,{size:"sm",className:"text-neutral3",children:o.jsx(Ur,{})})]},ce.id))}))]})]})}),o.jsx(vr,{open:C,onOpenChange:ce=>{T(ce),ce||N("")},children:o.jsxs(yr,{className:"max-w-md",children:[o.jsx(br,{children:o.jsx(pr,{children:"Attach Scorer to Dataset"})}),o.jsx(Mr,{className:"max-h-[50vh] overflow-y-auto",children:z.length===0?o.jsx(me,{variant:"ui-sm",className:"text-neutral3 py-4 text-center",children:"No scorers available to attach."}):o.jsxs("div",{className:"space-y-2",children:[o.jsx("input",{type:"text",placeholder:"Search scorers...",value:E,onChange:ce=>N(ce.target.value),className:"border-border1 bg-surface2 text-text1 placeholder:text-neutral3 focus:ring-accent1 w-full rounded border px-3 py-1.5 text-sm focus:ring-1 focus:outline-none"}),z.filter(([ce,Se])=>E?(Se.scorer?.name||ce).toLowerCase().includes(E.toLowerCase()):!0).map(([ce,Se])=>{const ve=Se.scorer?.name||ce;return o.jsx("button",{type:"button",className:"hover:bg-surface4 w-full rounded px-3 py-2 text-left transition-colors",onClick:async()=>{try{await V(ce),Be.success(`Attached "${ve}" to this dataset`),T(!1)}catch{}},children:o.jsx(me,{variant:"ui-sm",className:"font-medium",children:ve})},ce)})]})})]})})]})}function DE(e){return e==null?"":typeof e=="string"?e:JSON.stringify(e,null,2)}function Mis({datasetId:e,item:t}){const[n,r]=g.useState(!1),[s,a]=g.useState(!1),[i,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState(""),{updateItem:p,deleteItem:h}=qi(),m=g.useCallback(()=>{l(DE(t.input)),u(DE(t.groundTruth)),f(DE(t.expectedTrajectory)),r(!0)},[t.input,t.groundTruth,t.expectedTrajectory]),v=g.useCallback(()=>{r(!1)},[]),y=g.useCallback(async()=>{try{await h.mutateAsync({datasetId:e,itemId:t.id}),Be.success("Item deleted")}catch(x){Be.error(`Failed to delete: ${x instanceof Error?x.message:"Unknown error"}`)}},[h,e,t.id]),b=g.useCallback(async()=>{let x;try{x=JSON.parse(i)}catch{x=i}let S;if(c.trim())try{S=JSON.parse(c)}catch{S=c}let k;if(d.trim())try{k=JSON.parse(d)}catch{k=d}try{await p.mutateAsync({datasetId:e,itemId:t.id,input:x,groundTruth:S,expectedTrajectory:k}),Be.success("Item updated"),r(!1)}catch(_){Be.error(`Failed to update: ${_ instanceof Error?_.message:"Unknown error"}`)}},[i,c,d,e,t.id,p]);return n?o.jsxs("div",{className:"space-y-2 px-4 pb-3 pl-10",children:[o.jsxs("div",{children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Input"}),o.jsx(Il,{value:i,onChange:x=>l(x.target.value),className:"mt-1 font-mono text-xs",rows:4})]}),o.jsxs("div",{children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Ground Truth"}),o.jsx(Il,{value:c,onChange:x=>u(x.target.value),className:"mt-1 font-mono text-xs",rows:3,placeholder:"Optional"})]}),o.jsxs("div",{children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Expected Trajectory (JSON)"}),o.jsx(Il,{value:d,onChange:x=>f(x.target.value),className:"mt-1 font-mono text-xs",rows:3,placeholder:"Optional — JSON trajectory expectation"})]}),o.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[o.jsxs(oe,{variant:"primary",size:"sm",onClick:b,disabled:p.isPending,children:[p.isPending?o.jsx(Ut,{className:"h-3 w-3"}):o.jsx(He,{size:"sm",children:o.jsx(Gu,{})}),"Save"]}),o.jsxs(oe,{variant:"ghost",size:"sm",onClick:v,children:[o.jsx(He,{size:"sm",children:o.jsx(or,{})}),"Cancel"]})]})]}):o.jsxs("div",{className:"space-y-2 px-4 pb-3 pl-10",children:[o.jsxs("div",{children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Input"}),o.jsx("pre",{className:"text-neutral5 bg-surface1 mt-1 max-h-48 overflow-x-auto overflow-y-auto rounded px-2 py-1.5 text-xs wrap-break-word whitespace-pre-wrap",children:DE(t.input)})]}),t.groundTruth!==void 0&&t.groundTruth!==null&&o.jsxs("div",{children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Ground Truth"}),o.jsx("pre",{className:"text-neutral5 bg-surface1 mt-1 max-h-48 overflow-x-auto overflow-y-auto rounded px-2 py-1.5 text-xs wrap-break-word whitespace-pre-wrap",children:DE(t.groundTruth)})]}),t.expectedTrajectory!=null&&o.jsxs("div",{children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Expected Trajectory"}),o.jsx("pre",{className:"text-neutral5 bg-surface1 mt-1 max-h-48 overflow-x-auto overflow-y-auto rounded px-2 py-1.5 text-xs break-words whitespace-pre-wrap",children:DE(t.expectedTrajectory)})]}),o.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[o.jsxs(oe,{variant:"ghost",size:"sm",onClick:m,children:[o.jsx(He,{size:"sm",children:o.jsx(um,{})}),"Edit"]}),s?o.jsxs(o.Fragment,{children:[o.jsx(me,{variant:"ui-xs",className:"text-negative1 font-medium",children:"Delete this item?"}),o.jsx(oe,{variant:"ghost",size:"sm",onClick:y,disabled:h.isPending,className:"text-negative1 hover:text-negative1",children:h.isPending?o.jsx(Ut,{className:"h-3 w-3"}):"Yes"}),o.jsx(oe,{variant:"ghost",size:"sm",onClick:()=>a(!1),children:"No"})]}):o.jsxs(oe,{variant:"ghost",size:"sm",onClick:()=>a(!0),className:"text-neutral2 hover:text-negative1",children:[o.jsx(He,{size:"sm",children:o.jsx(Ml,{})}),"Delete"]}),t.source!=null&&o.jsxs(me,{variant:"ui-xs",className:"text-neutral2",children:["Source:"," ",typeof t.source=="object"&&t.source!==null&&"type"in t.source?String(t.source.type):"manual"]})]})]})}function Dis({status:e}){const t=e==="completed"?"bg-positive1":e==="running"?"bg-warning1":e==="failed"?"bg-negative1":"bg-neutral3";return o.jsx("div",{className:K("w-2 h-2 rounded-full shrink-0",t)})}function Lis({scorerId:e,scorerData:t,isAttached:n,onToggleAttach:r,onEdit:s,linkedDatasets:a,onViewDataset:i}){if(!t)return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(me,{variant:"ui-sm",className:"text-neutral3",children:"Scorer not found"})});const l=t.scorer?.name||e,c=t.scorer?.description,u=t.source==="code",d=t.scorer?.config?.type==="trajectory";return o.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[o.jsxs("div",{className:"border-border1 space-y-3 border-b p-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(me,{variant:"ui-sm",className:"text-neutral5 truncate font-medium",children:l}),d&&o.jsx(St,{size:"xs",variant:"purple",children:"trajectory"}),u&&o.jsx("span",{title:"Defined in code — cannot be edited in the UI",children:o.jsx(St,{children:"Code"})})]}),c&&o.jsx(me,{variant:"ui-xs",className:"text-neutral3 mt-1 block",children:c})]}),o.jsx("div",{className:"flex shrink-0 items-center gap-3",children:!u&&o.jsxs(oe,{variant:"ghost",size:"sm",onClick:s,children:[o.jsx(He,{size:"sm",children:o.jsx(um,{})}),"Edit"]})})]}),o.jsxs("div",{className:"bg-surface3 flex items-center justify-between rounded-md px-3 py-2",children:[o.jsxs("div",{children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral5 block",children:"Run in experiments"}),o.jsx(me,{variant:"ui-xs",className:"text-neutral3 mt-0.5 block",children:"When enabled, this scorer grades results for this agent"})]}),o.jsx(oc,{checked:n,onCheckedChange:r})]})]}),o.jsxs("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[o.jsxs("div",{children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3 mb-2 block font-medium tracking-wider uppercase",children:"Details"}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rz,{label:"ID",value:e}),o.jsx(Rz,{label:"Type",value:d?"Trajectory":"Agent"}),o.jsx(Rz,{label:"Source",value:u?"Code":"Stored"}),t.agentIds&&t.agentIds.length>0&&o.jsx(Rz,{label:"Used by agents",value:t.agentNames?.join(", ")||t.agentIds.join(", ")})]})]}),a&&a.length>0&&o.jsxs("div",{children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3 mb-2 block font-medium tracking-wider uppercase",children:"Datasets"}),o.jsx("div",{className:"space-y-1",children:a.map(f=>i?o.jsx("button",{onClick:()=>i(f.id),className:"bg-surface3 hover:bg-surface4 w-full cursor-pointer rounded-md px-3 py-2 text-left transition-colors",children:o.jsx(me,{variant:"ui-xs",className:"text-neutral5",children:f.name})},f.id):o.jsx("div",{className:"bg-surface3 rounded-md px-3 py-2",children:o.jsx(me,{variant:"ui-xs",className:"text-neutral5",children:f.name})},f.id))})]}),u&&o.jsx("div",{className:"bg-surface3 rounded-md p-3",children:o.jsx(me,{variant:"ui-xs",className:"text-neutral3",children:"This scorer is defined in code and cannot be edited in the UI. You can toggle whether it runs in experiments for this agent."})})]})]})}function Rz({label:e,value:t}){return o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3 w-24 shrink-0",children:e}),o.jsx(me,{variant:"ui-xs",className:"text-neutral5 break-all",children:t})]})}function gJe({onBack:e,onSaved:t,initialItems:n,prefillTestItems:r,editScorerId:s,editScorerData:a}){const i=!!s,l=Qe(),[c,u]=g.useState(""),[d,f]=g.useState(""),[p,h]=g.useState(0),[m,v]=g.useState(1),[y,b]=g.useState(""),[x,S]=g.useState(!1),[k,_]=g.useState(()=>n?n.map(le=>({input:le.input,output:le.error||le.output,expectedDirection:le.error?"low":"high",label:le.itemId.slice(0,8)})):r?r.map((le,X)=>({input:le.input,output:le.output,expectedDirection:le.expectedDirection==="high"?"high":"low",label:`failure-${X+1}`})):[]),[C,T]=g.useState(!1),[E,N]=g.useState(s||null),[I,A]=g.useState(null),[R,L]=g.useState(null),[D,F]=g.useState(!1);g.useEffect(()=>{s&&(S(!0),l.getStoredScorer(s).details(void 0,{status:"draft"}).then(async le=>{u(le.name||s),f(le.instructions||""),h(le.scoreRange?.min??0),v(le.scoreRange?.max??1),le.model&&b(`${le.model.provider}/${le.model.name}`);let X=null;try{const{datasets:te}=await l.listDatasets({perPage:200}),se=te.find(pe=>pe.targetType!=="scorer"?!1:(Array.isArray(pe.targetIds)?pe.targetIds:typeof pe.targetIds=="string"?(()=>{try{return JSON.parse(pe.targetIds)}catch{return[]}})():[]).includes(s));se&&(X=se.id)}catch{}if(X){A(X);try{const{items:te}=await l.listDatasetItems(X,{perPage:200}),se=te.map(pe=>{const ce=pe.input,Se=pe.groundTruth,ve=pe.metadata;return{input:ce?.input??"",output:ce?.output??"",expectedDirection:Se?.expectedDirection==="low"?"low":"high",label:ve?.label||void 0}});_(se)}catch{}}}).catch(()=>{const X=a?.scorer?.config,te=X?.judge;u(X?.name||a?.name||s),f(te?.instructions||X?.instructions||""),te?.model&&b(te.model)}).finally(()=>S(!1)))},[s]);const{provider:H,model:B}=oje(),{createStoredScorer:z,updateStoredScorer:V}=GTe(s||E||void 0),{form:M}=Bo(),{createDataset:G,batchInsertItems:U,batchDeleteItems:$,triggerExperiment:q}=qi(),{data:Z=[]}=LD({datasetId:I??"",experimentId:R??"",experimentStatus:D?"running":"completed"}),Y=()=>{_(le=>[...le,{input:"",output:"",expectedDirection:"high"}])},ne=le=>{_(X=>X.filter((te,se)=>se!==le))},J=(le,X,te)=>{_(se=>se.map((pe,ce)=>ce===le?{...pe,[X]:te}:pe))},ee=g.useCallback(async()=>{if(!c.trim()){Be.error("Please enter a scorer name");return}if(!d.trim()){Be.error("Please enter scorer instructions");return}let le=H,X=B;if(y){const se=y.split("/");se.length>=2&&(le=se[0],X=se.slice(1).join("/"))}if(!le||!X){Be.error("Please select a model");return}const te=s||E;T(!0);try{if(te){await V.mutateAsync({instructions:d.trim(),model:{provider:le,name:X},scoreRange:{min:p,max:m}});let se=I;if(!se&&k.length>0&&(se=(await G.mutateAsync({name:`${c.trim()} — Test Dataset`,description:`Test dataset for scorer "${c.trim()}". Items with known-good and known-bad examples to verify scoring accuracy.`,targetType:"scorer",targetIds:[te]})).id,A(se)),se){try{const{items:pe}=await l.listDatasetItems(se,{perPage:200});pe.length>0&&await $.mutateAsync({datasetId:se,itemIds:pe.map(ce=>ce.id)})}catch{}k.length>0&&await U.mutateAsync({datasetId:se,items:k.map(pe=>({input:{input:pe.input,output:pe.output},groundTruth:{expectedDirection:pe.expectedDirection},metadata:{label:pe.label},source:{type:"llm",referenceId:"scorer-editor"}}))})}t?.(te),Be.success("Scorer updated")}else{const pe=(await z.mutateAsync({name:c.trim(),type:"llm-judge",model:{provider:le,name:X},instructions:d.trim(),scoreRange:{min:p,max:m}}))?.id;if(pe){if(N(pe),k.length>0){const Se=await G.mutateAsync({name:`${c.trim()} — Test Dataset`,description:`Test dataset for scorer "${c.trim()}". Items with known-good and known-bad examples to verify scoring accuracy.`,targetType:"scorer",targetIds:[pe]});A(Se.id),await U.mutateAsync({datasetId:Se.id,items:k.map(ve=>({input:{input:ve.input,output:ve.output},groundTruth:{expectedDirection:ve.expectedDirection},metadata:{label:ve.label},source:{type:"llm",referenceId:"scorer-editor"}}))})}const ce=M.getValues("scorers")||{};M.setValue("scorers",{...ce,[pe]:{sampling:void 0}},{shouldDirty:!0}),t?.(pe)}Be.success(`Scorer saved${k.length>0?" with test dataset":""}. ${k.length>0?'Click "Run Test" to verify scoring.':""}`)}}catch(se){Be.error(`Failed to save scorer: ${se instanceof Error?se.message:"Unknown error"}`)}finally{T(!1)}},[c,d,H,B,y,p,m,k,I,s,E,z,V,G,U,$,l,M,t]),re=g.useCallback(async()=>{if(!E){Be.error("Save the scorer first before testing");return}if(!I){Be.error("No test dataset — add items and save first");return}F(!0),L(null);try{const X=(await q.mutateAsync({datasetId:I,targetType:"scorer",targetId:E}))?.experimentId;X&&(L(X),Be.success("Scorer test started — results will appear below"))}catch(le){Be.error(`Failed to run test: ${le instanceof Error?le.message:"Unknown error"}`)}finally{F(!1)}},[E,I,q]);return o.jsxs("div",{className:"flex h-full flex-col",children:[o.jsxs("div",{className:"border-border1 flex items-center gap-2 border-b px-4 py-3",children:[o.jsxs(oe,{variant:"ghost",size:"sm",onClick:e,children:[o.jsx(He,{children:o.jsx(gl,{})}),"Back"]}),o.jsx(me,{as:"h3",variant:"header-sm",className:"ml-2",children:i||E?"Edit Scorer":"New Scorer"}),(i||E)&&o.jsx(St,{variant:"green",className:"ml-2",children:"Saved"})]}),o.jsx(Dr,{className:"flex-1",children:x?o.jsxs("div",{className:"flex items-center justify-center p-8",children:[o.jsx(Ut,{className:"mr-2"})," Loading scorer..."]}):o.jsxs("div",{className:"space-y-6 p-4",children:[o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mt,{children:"Name"}),o.jsx(In,{placeholder:"e.g. Relevance Scorer",value:c,onChange:le=>u(le.target.value),disabled:i||!!E})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mt,{children:"Model"}),o.jsx(In,{placeholder:"e.g. openai/gpt-4o-mini",value:y||(H&&B?`${H}/${B}`:""),onChange:le=>b(le.target.value)}),o.jsx(me,{variant:"ui-sm",className:"text-icon3",children:"Format: provider/model (e.g. openai/gpt-4o-mini)"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mt,{children:"Instructions"}),o.jsx(Il,{placeholder:"Describe what this scorer should evaluate. Be specific about what constitutes a good vs bad response...",value:d,onChange:le=>f(le.target.value),rows:6})]}),o.jsxs("div",{className:"flex gap-4",children:[o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsx(Mt,{children:"Min Score"}),o.jsx(In,{type:"number",min:-1e3,max:1e3,step:"any",value:p,onChange:le=>h(Number(le.target.value))})]}),o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsx(Mt,{children:"Max Score"}),o.jsx(In,{type:"number",min:-1e3,max:1e3,step:"any",value:m,onChange:le=>v(Number(le.target.value))})]})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsx(me,{variant:"ui-md",className:"font-medium",children:"Test Items"}),o.jsx(me,{variant:"ui-sm",className:"text-icon3 mt-0.5",children:"Add known-good and known-bad examples to verify your scorer"}),I&&o.jsxs(me,{variant:"ui-xs",className:"text-icon3 mt-1",children:["Linked dataset · ",k.length," item",k.length!==1?"s":""]})]}),o.jsxs(oe,{variant:"outline",size:"sm",onClick:Y,children:[o.jsx(He,{children:o.jsx(Or,{})}),"Add Item"]})]}),k.length===0&&o.jsx("div",{className:"border-border1 rounded-lg border border-dashed p-6 text-center",children:o.jsx(me,{variant:"ui-sm",className:"text-icon3",children:"No test items yet. Add items with expected scoring direction to verify your scorer works correctly."})}),k.map((le,X)=>{const te=Z[X],se=te?.output?te.output?.score:null,pe=te?.output?te.output?.reason:null,ce=te?.error,Se=se!=null?le.expectedDirection==="high"?se>=(m-p)/2+p:se<(m-p)/2+p:null;return o.jsxs("div",{className:K("border border-border1 rounded-lg p-3 space-y-3",Se===!0&&"border-success/50 bg-success/5",Se===!1&&"border-error/50 bg-error/5"),children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(me,{variant:"ui-sm",className:"font-medium",children:["Item ",X+1]}),le.label&&o.jsx(St,{children:le.label}),o.jsxs("button",{className:K("px-2 py-0.5 rounded text-xs font-medium transition-colors",le.expectedDirection==="high"?"bg-success/20 text-success":"bg-error/20 text-error"),onClick:()=>J(X,"expectedDirection",le.expectedDirection==="high"?"low":"high"),children:["Should score ",le.expectedDirection]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[Se!==null&&o.jsx(He,{className:Se?"text-success":"text-error",children:Se?o.jsx(WD,{}):o.jsx(gO,{})}),o.jsx(oe,{variant:"ghost",size:"sm",onClick:()=>ne(X),children:o.jsx(He,{children:o.jsx(Ml,{})})})]})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(me,{variant:"ui-xs",className:"text-icon3 font-medium",children:"Input"}),o.jsx(Il,{placeholder:"The user's question/input...",value:typeof le.input=="string"?le.input:JSON.stringify(le.input,null,2),onChange:ve=>J(X,"input",ve.target.value),rows:3,className:"text-sm"})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(me,{variant:"ui-xs",className:"text-icon3 font-medium",children:"Output (agent response)"}),o.jsx(Il,{placeholder:"The agent's response...",value:typeof le.output=="string"?le.output:JSON.stringify(le.output,null,2),onChange:ve=>J(X,"output",ve.target.value),rows:3,className:"text-sm"})]})]}),(se!==null||ce)&&o.jsx("div",{className:"border-border1 flex items-center gap-3 border-t pt-2",children:ce?o.jsxs("div",{className:"text-error flex items-center gap-1.5",children:[o.jsx(He,{size:"sm",children:o.jsx(hO,{})}),o.jsxs(me,{variant:"ui-xs",children:["Error: ",String(ce)]})]}):o.jsxs(o.Fragment,{children:[o.jsxs(me,{variant:"ui-sm",className:"font-mono font-medium",children:["Score: ",se?.toFixed(3)]}),pe&&o.jsx(me,{variant:"ui-xs",className:"text-icon3 flex-1 truncate",children:pe})]})})]},X)})]}),Z.length>0&&o.jsxs("div",{className:"border-border1 rounded-lg border p-3",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(me,{variant:"ui-sm",className:"font-medium",children:"Test Results:"}),(()=>{let le=0,X=0,te=0;return Z.forEach((se,pe)=>{const ce=k[pe];if(!ce)return;if(se.error){te++;return}const Se=se.output?.score;if(Se==null)return;const ve=(m-p)/2+p;(ce.expectedDirection==="high"?Se>=ve:Se<ve)?le++:X++}),o.jsxs(o.Fragment,{children:[le>0&&o.jsxs(St,{variant:"green",children:[le," correct"]}),X>0&&o.jsxs(St,{variant:"red",children:[X," incorrect"]}),te>0&&o.jsxs(St,{children:[te," errors"]})]})})()]}),o.jsx(me,{variant:"ui-xs",className:"text-icon3 mt-1",children:Z.length<k.length?"Still processing...":"All items scored. Tweak instructions and re-run to improve accuracy."})]})]})}),o.jsxs("div",{className:"border-border1 flex items-center gap-2 border-t px-4 py-3",children:[i?o.jsxs(o.Fragment,{children:[o.jsxs(oe,{variant:"default",size:"sm",onClick:ee,disabled:C||!d.trim(),children:[C?o.jsx(Ut,{className:"mr-1.5"}):o.jsx(He,{children:o.jsx(Gu,{})}),"Save Changes"]}),o.jsxs(oe,{variant:"default",size:"sm",onClick:re,disabled:D||k.length===0,children:[D?o.jsx(Ut,{className:"mr-1.5"}):o.jsx(He,{children:o.jsx(Dc,{})}),"Run Test"]})]}):E?o.jsxs(o.Fragment,{children:[o.jsxs(oe,{variant:"default",size:"sm",onClick:re,disabled:D||k.length===0,children:[D?o.jsx(Ut,{className:"mr-1.5"}):o.jsx(He,{children:o.jsx(Dc,{})}),"Run Test"]}),o.jsxs(oe,{variant:"outline",size:"sm",onClick:ee,disabled:C,children:[C?o.jsx(Ut,{className:"mr-1.5"}):null,"Update & Re-save"]})]}):o.jsxs(oe,{variant:"default",size:"sm",onClick:ee,disabled:C||!c.trim()||!d.trim(),children:[C?o.jsx(Ut,{className:"mr-1.5"}):o.jsx(He,{children:o.jsx(Gu,{})}),k.length>0?"Save with Test Dataset":"Save & Attach"]}),o.jsx(oe,{variant:"ghost",size:"sm",onClick:e,className:"ml-auto",children:i||E?"Done":"Cancel"})]})]})}const iUt=g.createContext(null);function Fis({children:e}){const[t,n]=g.useState({}),r=g.useRef(t);r.current=t;const s=g.useCallback(({datasetId:l,modelId:c,prompt:u,count:d,agentContext:f,generateFn:p})=>{n(h=>({...h,[l]:{datasetId:l,modelId:c,count:d,status:"generating",startedAt:Date.now()}})),p({datasetId:l,modelId:c,prompt:u,count:d,agentContext:f}).then(h=>{const m=h.items??[];n(v=>{const y=v[l];if(!y||y.status!=="generating")return v;if(m.length===0){Be.info("Generation complete — no items were produced.");const{[l]:b,...x}=v;return x}return Be.success(`Generated ${m.length} item${m.length>1?"s":""}. Click the dataset to review.`),{...v,[l]:{...y,status:"review-ready",items:m}}})}).catch(h=>{const m=h instanceof Error?h.message:"Unknown error";Be.error(`Generation failed: ${m}`),n(v=>{const y=v[l];return y?{...v,[l]:{...y,status:"error",error:m}}:v})})},[]),a=g.useCallback(l=>{n(c=>{const{[l]:u,...d}=c;return d})},[]),i=g.useCallback(l=>{const c=r.current[l];if(!c||c.status!=="review-ready"||!c.items)return null;const u=c.items;return n(d=>{const{[l]:f,...p}=d;return p}),u},[]);return o.jsx(iUt.Provider,{value:{tasks:t,startGeneration:s,dismissTask:a,consumeReviewItems:i},children:e})}function oUt(){const e=g.useContext(iUt);if(!e)throw new Error("useGenerationTasks must be used within GenerationProvider");return e}function vJe(e){const t=[];return e?.description?t.push(`Generate diverse test inputs for an agent that ${e.description.toLowerCase()}.`):t.push("Generate diverse test inputs for this agent."),e?.instructions&&t.push(`Agent instructions: ${e.instructions}`),e?.tools?.length&&t.push(`The agent has these tools: ${e.tools.join(", ")}.`),t.push("Include edge cases, typical usage, and adversarial inputs."),t.join(" ")}function zis({datasetId:e,agentContext:t,onDismiss:n}){const{provider:r,model:s}=oje(),[a,i]=g.useState(r),[l,c]=g.useState(s),u=a&&l?`${a}/${l}`:"",[d,f]=g.useState(()=>vJe(t)),[p,h]=g.useState(5),m=g.useRef(null),{generateItems:v}=qi(),{startGeneration:y}=oUt(),b=g.useCallback(()=>{if(!u){Be.error("Please select a provider and model");return}const S=d.trim()||vJe(t);y({datasetId:e,modelId:u,prompt:S,count:p,agentContext:t,generateFn:async k=>({items:(await v.mutateAsync(k)).items??[]})}),n()},[d,p,u,e,v,t,n,y]),x=g.useCallback(S=>{S||n()},[n]);return o.jsx(vr,{open:!0,onOpenChange:x,children:o.jsxs(yr,{ref:m,className:"max-w-2xl",children:[o.jsx(br,{children:o.jsx(pr,{children:"Generate Test Data"})}),o.jsx(Mr,{children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(Mt,{children:"Model"}),o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("div",{className:"w-[160px]",children:o.jsx(Vy,{value:a,onValueChange:S=>{const k=di(S);i(k),c("")},size:"sm",container:m})}),o.jsx("div",{className:"flex-1",children:o.jsx(Hy,{llmId:a,value:l,onValueChange:c,size:"sm",container:m})})]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mt,{children:"Instructions (optional)"}),o.jsx(Il,{value:d,onChange:S=>f(S.target.value),placeholder:"e.g., Generate diverse recipe queries covering different cuisines, dietary restrictions, and skill levels...",rows:4})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mt,{children:"Number of items"}),o.jsx(In,{type:"number",min:1,max:50,value:p,onChange:S=>h(Math.max(1,Math.min(50,parseInt(S.target.value)||1)))})]}),!u&&o.jsx(me,{variant:"ui-xs",className:"text-amber-400",children:"Select a provider and model above to generate items."})]})}),o.jsx(lc,{className:"px-6",children:o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(oe,{onClick:()=>x(!1),children:"Cancel"}),o.jsxs(oe,{variant:"primary",onClick:b,disabled:!u,children:[o.jsx(He,{children:o.jsx($g,{})}),"Generate"]})]})})]})})}function Bis({datasetId:e,items:t,modelId:n,onDismiss:r,onStartOver:s}){const[a,i]=g.useState(t),[l,c]=g.useState(new Set(t.map((S,k)=>k))),[u,d]=g.useState(new Set([0])),f=a.length,{batchInsertItems:p}=qi(),h=g.useCallback(async()=>{const S=a.filter((k,_)=>l.has(_)).map(k=>({input:k.input,groundTruth:k.groundTruth,source:{type:"llm",referenceId:n}}));if(S.length===0){Be.error("No items selected");return}try{await p.mutateAsync({datasetId:e,items:S}),Be.success(`Added ${S.length} item${S.length>1?"s":""} to dataset`),r()}catch(k){Be.error(`Failed to add items: ${k instanceof Error?k.message:"Unknown error"}`)}},[a,l,n,e,p,r]),m=g.useCallback(S=>{S||r()},[r]),v=g.useCallback(S=>{c(k=>{const _=new Set(k);return _.has(S)?_.delete(S):_.add(S),_})},[]),y=g.useCallback(S=>{d(k=>{const _=new Set(k);return _.has(S)?_.delete(S):_.add(S),_})},[]),b=g.useCallback(()=>{l.size===f?c(new Set):c(new Set(Array.from({length:f},(S,k)=>k)))},[l.size,f]),x=g.useCallback(S=>{i(k=>k.filter((_,C)=>C!==S)),c(k=>{const _=new Set;for(const C of k)C<S?_.add(C):C>S&&_.add(C-1);return _}),d(k=>{const _=new Set;for(const C of k)C<S?_.add(C):C>S&&_.add(C-1);return _})},[]);return o.jsx(vr,{open:!0,onOpenChange:m,children:o.jsxs(yr,{className:"max-w-2xl",children:[o.jsx(br,{children:o.jsx(pr,{children:"Review Generated Items"})}),o.jsx(Mr,{className:"flex max-h-[70vh] flex-col",children:o.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(So,{checked:l.size===a.length,onCheckedChange:b}),o.jsxs(me,{variant:"ui-sm",className:"text-neutral4",children:[l.size," of ",a.length," selected"]})]}),s&&o.jsx(oe,{variant:"ghost",size:"sm",onClick:s,children:"Start over"})]}),o.jsx(Dr,{className:"min-h-0 flex-1",children:o.jsx("div",{className:"space-y-2",children:a.map((S,k)=>o.jsxs("div",{className:"border-border1 rounded-lg border",children:[o.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[o.jsx(So,{checked:l.has(k),onCheckedChange:()=>v(k)}),o.jsx("button",{type:"button",className:"flex-1 text-left",onClick:()=>y(k),children:o.jsxs(me,{variant:"ui-sm",className:"text-neutral5 truncate",children:["Item ",k+1,": ",Uis(S.input)]})}),o.jsx(oe,{variant:"ghost",size:"sm",onClick:()=>x(k),children:o.jsx(He,{size:"sm",children:o.jsx(Ml,{})})})]}),u.has(k)&&o.jsxs("div",{className:"border-border1 space-y-2 border-t px-3 py-2",children:[o.jsxs("div",{children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Input"}),o.jsx("pre",{className:"text-neutral5 bg-surface1 mt-1 max-h-32 overflow-x-auto overflow-y-auto rounded px-2 py-1.5 text-xs wrap-break-word whitespace-pre-wrap",children:JSON.stringify(S.input,null,2)})]}),S.groundTruth!==void 0&&o.jsxs("div",{children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3 font-medium",children:"Ground Truth"}),o.jsx("pre",{className:"text-neutral5 bg-surface1 mt-1 max-h-32 overflow-x-auto overflow-y-auto rounded px-2 py-1.5 text-xs wrap-break-word whitespace-pre-wrap",children:JSON.stringify(S.groundTruth,null,2)})]})]})]},k))})})]})}),o.jsx(lc,{className:"px-6",children:o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(oe,{onClick:()=>m(!1),children:"Cancel"}),o.jsx(oe,{variant:"primary",onClick:h,disabled:l.size===0||p.isPending,children:p.isPending?o.jsxs(o.Fragment,{children:[o.jsx(Ut,{className:"h-4 w-4"}),"Adding..."]}):o.jsxs(o.Fragment,{children:[o.jsx(He,{children:o.jsx(Or,{})}),"Add ",l.size," Item",l.size!==1?"s":""]})})]})})]})})}function Uis(e){if(typeof e=="string")return e.slice(0,80);if(typeof e=="object"&&e!==null){const n=Object.values(e)[0];return typeof n=="string"?n.slice(0,80):JSON.stringify(e).slice(0,80)}return String(e).slice(0,80)}function Pz(e){if(Array.isArray(e))return e;if(typeof e=="string"){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return[]}function yJe(e){return e?(typeof e=="string"?new Date(e):e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function $z(e){return e?e instanceof Date?e.getTime():new Date(e).getTime():0}function qis({agentId:e,onSwitchToReview:t,pendingScorerItems:n,onPendingScorerItemsConsumed:r}){const s=es(),[a,i]=g.useState("experiments"),[l,c]=g.useState(null),[u,d]=g.useState(!1),[f,p]=g.useState(""),[h,m]=g.useState(!1),[v,y]=g.useState(""),[b,x]=g.useState(null),[S,k]=g.useState(null),[_,C]=g.useState(""),[T,E]=g.useState(""),[N,I]=g.useState(""),{form:A,isCodeAgentOverride:R}=Bo(),{addItems:L}=U4t(),D=Pn({control:A.control,name:"scorers"})??{},F=Pn({control:A.control,name:"instructions"}),H=Pn({control:A.control,name:"description"}),B=Pn({control:A.control,name:"tools"}),{data:z,isLoading:V}=Im(),M=z?.datasets??[],{data:G,isLoading:U}=oh(),{data:$,isLoading:q}=XIe(e),{tasks:Z}=oUt(),{updateDataset:Y,updateExperimentResult:ne}=qi(),{createStoredAgent:J,updateStoredAgent:ee}=R1(e),re=g.useMemo(()=>({description:H||"",instructions:F||"",tools:B?Object.keys(B):[]}),[H,F,B]);g.useEffect(()=>{for(const[xe,Pe]of Object.entries(Z))if(Pe.status==="review-ready"&&Pe.items?.length){k(xe);break}},[Z]),g.useEffect(()=>{n?.length&&(i("scorers"),c({type:"new-scorer",prefillTestItems:n.map(xe=>({input:xe.input,output:xe.output,expectedDirection:"low"}))}),r?.())},[n,r]);const le=M.filter(xe=>Pz(xe.targetIds).includes(e)),X=M.filter(xe=>!Pz(xe.targetIds).includes(e)),te=($||[]).reduce((xe,Pe)=>{const tt=xe[Pe.datasetId];return(!tt||$z(Pe.startedAt)>$z(tt.startedAt))&&(xe[Pe.datasetId]=Pe),xe},{}),se=g.useMemo(()=>{const xe=new Map;return le.forEach(Pe=>xe.set(Pe.id,Pe)),xe},[le]),pe=Object.entries(G||{}),ce=pe.filter(([xe])=>!!D[xe]),Se=pe.filter(([xe])=>!D[xe]),ve=g.useCallback(async xe=>{A.setValue("scorers",xe,{shouldDirty:!1});const Pe={scorers:XBt(xe)};try{await ee.mutateAsync(Pe)}catch(tt){if(R)try{const nt=A.getValues();await J.mutateAsync({id:e,name:nt.name,instructions:_xe(nt.instructionBlocks),model:nt.model,...Pe})}catch(nt){console.error("Failed to persist scorer change:",nt),Be.error("Failed to save scorer changes")}else console.error("Failed to persist scorer change:",tt),Be.error("Failed to save scorer changes")}},[A,e,R,J,ee]),ke=g.useCallback(async(xe,Pe)=>{const nt={...A.getValues("scorers")||{},[xe]:{sampling:Pe.sampling}};await ve(nt)},[A,ve]),Ne=g.useCallback(async xe=>{const Pe=A.getValues("scorers")||{},{[xe]:tt,...nt}=Pe;await ve(nt)},[A,ve]),Me=g.useCallback(async xe=>{for(const Pe of xe)if(Pe.experimentId&&Pe.datasetId)try{await ne.mutateAsync({datasetId:Pe.datasetId,experimentId:Pe.experimentId,resultId:Pe.id,status:"needs-review"})}catch{}L(xe.map(Pe=>({id:Pe.id,itemId:Pe.itemId,input:Pe.input,output:Pe.output,error:Pe.error,scores:Pe.scores,experimentId:Pe.experimentId,datasetId:Pe.datasetId,traceId:Pe.traceId}))),t?.()},[L,t,ne]),Ae=g.useCallback(xe=>{i("scorers"),c({type:"new-scorer",prefillTestItems:xe.map(Pe=>({input:Pe.input,output:Pe.output,expectedDirection:"low"}))})},[]),Ie=g.useMemo(()=>{const xe=[...$||[]].sort((tt,nt)=>{const Dt=$z(tt.startedAt);return $z(nt.startedAt)-Dt});if(!_)return xe;const Pe=_.toLowerCase();return xe.filter(tt=>{const nt=se.get(tt.datasetId)?.name??"";return tt.id.toLowerCase().includes(Pe)||nt.toLowerCase().includes(Pe)||(tt.targetId??"").toLowerCase().includes(Pe)})},[$,_,se]),ae=g.useMemo(()=>{if(!T)return le;const xe=T.toLowerCase();return le.filter(Pe=>Pe.name.toLowerCase().includes(xe)||(Pe.description??"").toLowerCase().includes(xe))},[le,T]),fe=g.useMemo(()=>{if(!N)return ce;const xe=N.toLowerCase();return ce.filter(([Pe,tt])=>(tt.scorer?.name||Pe).toLowerCase().includes(xe))},[ce,N]),{containerRef:ue,getRowProps:we}=wo({count:Ie.length}),{containerRef:Ee,getRowProps:ge}=wo({count:ae.length}),{containerRef:Ce,getRowProps:Ue}=wo({count:fe.length}),Fe=g.useCallback(xe=>{i(xe),c(null)},[]);function Re(){if(!l)return null;const xe=(Pe,tt)=>o.jsx("div",{className:"border-border1 flex items-center gap-2 border-b px-4 py-2",children:o.jsxs(oe,{variant:"ghost",size:"sm",onClick:tt,children:[o.jsx(HD,{className:"size-4"}),Pe]})});if(l.type==="dataset")return o.jsxs(ta,{withLeftSeparator:!0,children:[xe("Back to Datasets",()=>c(null)),o.jsx(ta.Content,{children:o.jsx($is,{agentId:e,datasetId:l.id,datasetName:se.get(l.id)?.name??"",datasetDescription:se.get(l.id)?.description??void 0,datasetTags:se.get(l.id)?.tags??void 0,datasetTargetType:se.get(l.id)?.targetType,datasetTargetIds:Pz(se.get(l.id)?.targetIds),activeScorers:Object.keys(D),datasetScorerIds:se.get(l.id)?.scorerIds??null,onGenerate:()=>x(l.id),onViewExperiment:Pe=>c({type:"experiment",id:Pe,datasetId:l.id})})})]});if(l.type==="scorer")return o.jsxs(ta,{withLeftSeparator:!0,children:[xe("Back to Scorers",()=>c(null)),o.jsx(ta.Content,{children:o.jsx(Lis,{scorerId:l.id,scorerData:G?.[l.id],isAttached:!!D[l.id],onToggleAttach:async()=>{D[l.id]?await Ne(l.id):await ke(l.id,G?.[l.id]??{})},onEdit:()=>c({type:"edit-scorer",id:l.id,scorerData:G?.[l.id]??{}}),linkedDatasets:M.map(Pe=>({id:Pe.id,name:Pe.name})),onViewDataset:Pe=>{i("datasets"),c({type:"dataset",id:Pe})}})})]});if(l.type==="new-scorer")return o.jsxs(ta,{withLeftSeparator:!0,children:[xe("Back to Scorers",()=>c(null)),o.jsx(ta.Content,{children:o.jsx(gJe,{onBack:()=>c(null),prefillTestItems:l.prefillTestItems,onSaved:Pe=>{ke(Pe,{}),c({type:"scorer",id:Pe})}})})]});if(l.type==="edit-scorer")return o.jsxs(ta,{withLeftSeparator:!0,children:[xe("Back to Scorer",()=>c({type:"scorer",id:l.id})),o.jsx(ta.Content,{children:o.jsx(gJe,{onBack:()=>c({type:"scorer",id:l.id}),editScorerId:l.id,editScorerData:l.scorerData,onSaved:()=>c({type:"scorer",id:l.id})})})]});if(l.type==="experiment"){const Pe=$?.find(tt=>tt.id===l.id);return Pe?o.jsxs(ta,{withLeftSeparator:!0,children:[xe("Back to Experiments",()=>c(null)),o.jsx(ta.Content,{children:o.jsx(Cis,{experiment:Pe,onBack:()=>c(null),onSendToReview:Me,onCreateScorer:Ae})})]}):o.jsxs(ta,{withLeftSeparator:!0,children:[xe("Back to Experiments",()=>c(null)),o.jsx(ta.Content,{children:o.jsx("div",{className:"text-neutral3 p-4",children:"Experiment not found"})})]})}return null}function Ge(){return q?o.jsx(Pl,{columns:"auto minmax(15rem,1fr) auto auto auto auto auto"}):$?.length?o.jsxs(be,{columns:"auto minmax(15rem,1fr) auto auto auto auto auto",className:"min-w-0",scrollRef:ue,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"Experiment"}),o.jsx(be.TopCell,{children:"Dataset"}),o.jsx(be.TopCell,{children:"Status"}),o.jsx(be.TopCell,{className:"text-center",children:"Items"}),o.jsx(be.TopCell,{className:"text-center",children:"Processed"}),o.jsx(be.TopCell,{className:"text-center",children:"Errored"}),o.jsx(be.TopCell,{children:"Date"})]}),Ie.map((xe,Pe)=>{const tt=se.get(xe.datasetId)?.name??xe.datasetId.slice(0,8),nt=xe.status??"pending",Dt=xe.succeededCount??0,Te=xe.failedCount??0,Ke=xe.totalItems??0,pt=l?.type==="experiment"&&l.id===xe.id;return o.jsxs(be.RowButton,{featured:pt,onClick:()=>c({type:"experiment",id:xe.id,datasetId:xe.datasetId}),...we(Pe),children:[o.jsx(be.IdCell,{id:xe.id}),o.jsx(be.Cell,{className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:tt})}),o.jsx(be.Cell,{children:o.jsx(St,{variant:aUt[nt]??"neutral",indicator:"dot",children:RT[nt]??nt})}),o.jsx(be.Cell,{className:"text-center",children:Ke}),o.jsx(be.Cell,{className:"text-center",children:Dt}),o.jsx(be.Cell,{className:"text-center",children:o.jsx("span",{className:Te>0?"text-accent2":"",children:Te})}),o.jsx(be.Cell,{children:yJe(xe.startedAt)})]},xe.id)})]}):o.jsx("div",{className:"flex h-full items-center justify-center py-20",children:o.jsx(Er,{iconSlot:o.jsx(a0e,{className:"text-neutral3 size-10"}),titleSlot:"No Experiments Yet",descriptionSlot:"Run experiments against your datasets to see results here."})})}function st(){return V?o.jsx(Pl,{columns:"minmax(10rem,1fr) auto auto auto auto"}):le.length?o.jsxs(be,{columns:"minmax(10rem,1fr) auto auto auto auto",className:"min-w-0",scrollRef:Ee,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"Name"}),o.jsx(be.TopCell,{children:"Tags"}),o.jsx(be.TopCell,{children:"Latest Experiment"}),o.jsx(be.TopCell,{children:"Status"}),o.jsx(be.TopCell,{children:"Updated"})]}),ae.map((xe,Pe)=>{const tt=te[xe.id],nt=Z[xe.id],Dt=nt?.status==="generating",Te=l?.type==="dataset"&&l.id===xe.id;return o.jsxs(be.RowButton,{featured:Te,onClick:()=>c({type:"dataset",id:xe.id}),...ge(Pe),children:[o.jsx(be.Cell,{className:"text-neutral4 min-w-0",children:o.jsx("span",{className:"block truncate",children:xe.name})}),o.jsx(be.Cell,{children:xe.tags?.length?o.jsxs("div",{className:"flex gap-1",children:[xe.tags.slice(0,2).map(Ke=>o.jsx(St,{children:Ke},Ke)),xe.tags.length>2&&o.jsxs(St,{children:["+",xe.tags.length-2]})]}):o.jsx("span",{className:"text-neutral2",children:"—"})}),o.jsx(be.Cell,{children:tt?o.jsx(Vis,{experiment:tt}):o.jsx("span",{className:"text-neutral2",children:"No experiments"})}),o.jsx(be.Cell,{children:Dt?o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Ut,{className:"size-3"}),o.jsx(me,{variant:"ui-xs",className:"text-warning1",children:"Generating..."})]}):nt?.error?o.jsx(me,{variant:"ui-xs",className:"text-negative1",children:"Failed"}):o.jsx("span",{className:"text-neutral2",children:"—"})}),o.jsx(be.Cell,{children:yJe(xe.updatedAt)})]},xe.id)})]}):o.jsx("div",{className:"flex h-full items-center justify-center py-20",children:o.jsx(Er,{iconSlot:o.jsx(cm,{className:"text-neutral3 size-10"}),titleSlot:"No Datasets",descriptionSlot:"Create or attach a dataset to begin testing your agent."})})}function mt(){return U?o.jsx(Pl,{columns:"minmax(10rem,1fr) auto auto auto"}):ce.length?o.jsxs(be,{columns:"minmax(10rem,1fr) auto auto auto",className:"min-w-0",scrollRef:Ce,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"Name"}),o.jsx(be.TopCell,{children:"Source"}),o.jsx(be.TopCell,{children:"Description"}),o.jsx(be.TopCell,{children:"Datasets"})]}),fe.map(([xe,Pe],tt)=>{const nt=Pe.scorer?.name||xe,Dt=Pe.scorer?.description||"",Te=Pe.source??"stored",Ke=M.filter(Qt=>(Qt.scorerIds??[]).includes(xe)).length,pt=l?.type==="scorer"&&l.id===xe;return o.jsxs(be.RowButton,{featured:pt,onClick:()=>c({type:"scorer",id:xe}),...Ue(tt),children:[o.jsx(be.Cell,{className:"text-neutral4 min-w-0",children:o.jsx("span",{className:"block truncate",children:nt})}),o.jsx(be.Cell,{children:o.jsx(St,{variant:Te==="code"?"neutral":"green",children:Te})}),o.jsx(be.Cell,{className:"min-w-0",children:o.jsx("span",{className:"block max-w-[200px] truncate",children:Dt||o.jsx("span",{className:"text-neutral2",children:"—"})})}),o.jsx(be.Cell,{children:Ke>0?`${Ke} dataset${Ke>1?"s":""}`:"—"})]},xe)})]}):o.jsx("div",{className:"flex h-full items-center justify-center py-20",children:o.jsx(Er,{iconSlot:o.jsx(Wp,{className:"text-neutral3 size-10"}),titleSlot:"No Scorers Attached",descriptionSlot:"Attach or create a scorer to evaluate your agent's performance."})})}function $e(){return o.jsxs(o.Fragment,{children:[b&&o.jsx(zis,{datasetId:b,agentContext:re,onDismiss:()=>x(null)}),S&&Z[S]?.status==="review-ready"&&Z[S]?.items&&o.jsx(Bis,{datasetId:S,items:Z[S].items,modelId:Z[S].modelId,onDismiss:()=>k(null)}),o.jsx(vr,{open:u,onOpenChange:d,children:o.jsxs(yr,{children:[o.jsx(br,{children:o.jsx(pr,{children:"Attach Existing Dataset"})}),o.jsxs(Mr,{className:"max-h-[50vh] overflow-y-auto",children:[o.jsxs(uu,{variant:"outline",children:[o.jsx(Nc,{align:"inline-start",children:o.jsx(Ms,{})}),o.jsx(du,{type:"search","aria-label":"Search datasets",placeholder:"Search datasets...",onChange:xe=>p(xe.target.value)})]}),X.filter(xe=>!f||xe.name.toLowerCase().includes(f.toLowerCase())).map(xe=>o.jsx("button",{type:"button",className:"hover:bg-surface3 flex w-full items-center justify-between rounded-md px-3 py-2 text-left transition-colors",onClick:async()=>{try{await Y.mutateAsync({datasetId:xe.id,targetType:xe.targetType??"agent",targetIds:[...Pz(xe.targetIds),e]}),Be.success(`Dataset "${xe.name}" attached`),d(!1)}catch{Be.error("Failed to attach dataset")}},children:o.jsxs("div",{children:[o.jsx(me,{variant:"ui-sm",className:"font-medium",children:xe.name}),xe.description&&o.jsx(me,{variant:"ui-xs",className:"text-neutral3 block",children:xe.description})]})},xe.id)),X.filter(xe=>!f||xe.name.toLowerCase().includes(f.toLowerCase())).length===0&&o.jsx(me,{variant:"ui-sm",className:"text-neutral3 block py-4 text-center",children:"No datasets available to attach"})]})]})}),o.jsx(vr,{open:h,onOpenChange:m,children:o.jsxs(yr,{children:[o.jsx(br,{children:o.jsx(pr,{children:"Attach Existing Scorer"})}),o.jsxs(Mr,{className:"max-h-[50vh] overflow-y-auto",children:[o.jsxs(uu,{variant:"outline",children:[o.jsx(Nc,{align:"inline-start",children:o.jsx(Ms,{})}),o.jsx(du,{type:"search","aria-label":"Search scorers",placeholder:"Search scorers...",onChange:xe=>y(xe.target.value)})]}),Se.filter(([xe,Pe])=>v?(Pe.scorer?.name||xe).toLowerCase().includes(v.toLowerCase()):!0).map(([xe,Pe])=>o.jsx("button",{type:"button",className:"hover:bg-surface3 flex w-full items-center justify-between rounded-md px-3 py-2 text-left transition-colors",onClick:async()=>{try{await ke(xe,Pe),Be.success(`Scorer "${Pe.scorer?.name||xe}" attached`),m(!1)}catch{Be.error("Failed to attach scorer")}},children:o.jsxs("div",{children:[o.jsx(me,{variant:"ui-sm",className:"font-medium",children:Pe.scorer?.name||xe}),Pe.scorer?.description&&o.jsx(me,{variant:"ui-xs",className:"text-neutral3 block",children:Pe.scorer.description})]})},xe)),Se.filter(([xe,Pe])=>v?(Pe.scorer?.name||xe).toLowerCase().includes(v.toLowerCase()):!0).length===0&&o.jsx(me,{variant:"ui-sm",className:"text-neutral3 block py-4 text-center",children:"No scorers available to attach"})]})]})})]})}const ye=!!l;return o.jsxs("div",{className:"flex h-full flex-col overflow-hidden p-4",children:[o.jsxs(yc,{defaultTab:"experiments",value:a,onValueChange:Fe,className:"flex h-full flex-col overflow-hidden",children:[o.jsxs("div",{className:"border-border1 flex items-center justify-between border-b",children:[o.jsxs(vc,{className:"border-b-0",children:[o.jsx(Ar,{value:"experiments",children:"Experiments"}),o.jsx(Ar,{value:"datasets",children:"Datasets"}),o.jsx(Ar,{value:"scorers",children:"Scorers"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[a==="datasets"&&o.jsxs(o.Fragment,{children:[X.length>0&&o.jsxs(oe,{variant:"ghost",size:"sm",onClick:()=>d(!0),children:[o.jsx(J2e,{className:"mr-1 size-3.5"}),"Attach"]}),o.jsxs(oe,{variant:"ghost",size:"sm",onClick:()=>{s(`/datasets/new?targetType=agent&targetIds=${encodeURIComponent(e)}`)},children:[o.jsx(Or,{className:"mr-1 size-3.5"}),"Create"]})]}),a==="scorers"&&o.jsxs(o.Fragment,{children:[Se.length>0&&o.jsxs(oe,{variant:"ghost",size:"sm",onClick:()=>m(!0),children:[o.jsx(J2e,{className:"mr-1 size-3.5"}),"Attach"]}),o.jsxs(oe,{variant:"ghost",size:"sm",onClick:()=>c({type:"new-scorer"}),children:[o.jsx(Or,{className:"mr-1 size-3.5"}),"New"]})]})]})]}),o.jsxs("div",{className:"border-border1 border-b py-2",children:[a==="experiments"&&o.jsxs(uu,{variant:"outline",children:[o.jsx(Nc,{align:"inline-start",children:o.jsx(Ms,{})}),o.jsx(du,{type:"search","aria-label":"Search experiments",placeholder:"Search experiments...",onChange:xe=>C(xe.target.value)})]}),a==="datasets"&&o.jsxs(uu,{variant:"outline",children:[o.jsx(Nc,{align:"inline-start",children:o.jsx(Ms,{})}),o.jsx(du,{type:"search","aria-label":"Search datasets",placeholder:"Search datasets...",onChange:xe=>E(xe.target.value)})]}),a==="scorers"&&o.jsxs(uu,{variant:"outline",children:[o.jsx(Nc,{align:"inline-start",children:o.jsx(Ms,{})}),o.jsx(du,{type:"search","aria-label":"Search scorers",placeholder:"Search scorers...",onChange:xe=>I(xe.target.value)})]})]}),o.jsxs("div",{className:"flex-1 overflow-hidden",children:[o.jsx(fs,{value:"experiments",className:"h-full overflow-hidden",children:o.jsxs(vx,{className:ye&&l?.type==="experiment"?"grid-cols-[1fr_1fr]":"",children:[o.jsx(ta,{children:o.jsx(ta.Content,{children:Ge()})}),l?.type==="experiment"&&Re()]})}),o.jsx(fs,{value:"datasets",className:"h-full overflow-hidden",children:o.jsxs(vx,{className:ye&&l?.type==="dataset"?"grid-cols-[1fr_1fr]":"",children:[o.jsx(ta,{children:o.jsx(ta.Content,{children:st()})}),l?.type==="dataset"&&Re()]})}),o.jsx(fs,{value:"scorers",className:"h-full overflow-hidden",children:o.jsxs(vx,{className:ye&&(l?.type==="scorer"||l?.type==="new-scorer"||l?.type==="edit-scorer")?"grid-cols-[1fr_1fr]":"",children:[o.jsx(ta,{children:o.jsx(ta.Content,{children:mt()})}),(l?.type==="scorer"||l?.type==="new-scorer"||l?.type==="edit-scorer")&&Re()]})})]})]}),$e()]})}function Vis({experiment:e}){const{status:t,failedCount:n,totalItems:r}=e,s=[e.datasetVersion!=null?zN("Dataset",e.datasetVersion):null,e.agentVersion?zN("Agent",e.agentVersion):null].filter(Boolean),a=s.length>0?o.jsx(me,{variant:"ui-xs",className:"text-neutral3",children:s.join(" · ")}):null;return t==="running"||t==="pending"?o.jsxs("div",{className:"flex flex-col",children:[o.jsx(me,{variant:"ui-xs",className:"text-warning1",children:t==="running"?"Running...":"Pending..."}),a]}):r===0?o.jsxs("div",{className:"flex flex-col",children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3",children:"No results"}),a]}):o.jsxs("div",{className:"flex flex-col",children:[o.jsxs(me,{variant:"ui-xs",className:"text-neutral3",children:[r," items",n>0&&o.jsxs("span",{className:"text-error",children:[" · ",n," errored"]})]}),a]})}const His=e=>{const t=Qe(),{data:n}=XIe(e);return yt({queryKey:["completed-items",e,n?.map(r=>r.id)],queryFn:async()=>!n||n.length===0?[]:(await Promise.all(n.map(async s=>{try{const{results:a}=await t.listDatasetExperimentResults(s.datasetId,s.id);return a.filter(i=>i.status==="complete").map(i=>({id:i.id,input:i.input,output:i.output,error:i.error,itemId:i.itemId,experimentId:i.experimentId,datasetId:s.datasetId,traceId:i.traceId??void 0,scores:i.scores?Object.fromEntries(i.scores.map(l=>[l.scorerId,l.score??0])):{},tags:i.tags??[],comment:i.comment??""}))}catch{return[]}}))).flat(),enabled:!!e&&!!n&&n.length>0,refetchOnWindowFocus:!1})},Wis=e=>{const t=Qe(),{data:n}=XIe(e);return yt({queryKey:["review-items",e,n?.map(r=>r.id)],queryFn:async()=>!n||n.length===0?[]:(await Promise.all(n.map(async s=>{try{const{results:a}=await t.listDatasetExperimentResults(s.datasetId,s.id);return a.filter(i=>i.status==="needs-review").map(i=>({id:i.id,input:i.input,output:i.output,error:i.error,itemId:i.itemId,experimentId:i.experimentId,datasetId:s.datasetId,traceId:i.traceId??void 0,scores:i.scores?Object.fromEntries(i.scores.map(l=>[l.scorerId,l.score??0])):{},tags:i.tags??[],comment:i.comment??""}))}catch{return[]}}))).flat(),enabled:!!e&&!!n&&n.length>0,refetchOnWindowFocus:!1})};function Zis({tags:e,vocabulary:t,onSetTags:n}){const[r,s]=g.useState(!1),[a,i]=g.useState(""),l=g.useRef(null),c=t.filter(h=>!e.includes(h)&&h.toLowerCase().includes(a.toLowerCase())),u=a.trim()&&!t.includes(a.trim())&&!e.includes(a.trim()),d=h=>{n([...e,h]),i("")},f=h=>{n(e.filter(m=>m!==h))},p=h=>{h.key==="Enter"&&a.trim()&&(h.preventDefault(),d(a.trim()))};return o.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[e.map(h=>o.jsxs("span",{className:"bg-accent1/10 text-accent1 inline-flex items-center gap-0.5 rounded-md px-1.5 py-0.5 text-[10px] font-medium",children:[h,o.jsx("button",{type:"button",onClick:()=>f(h),className:"hover:text-accent1/70",children:o.jsx(or,{className:"h-2.5 w-2.5"})})]},h)),o.jsxs(Uf,{open:r,onOpenChange:s,children:[o.jsx(Kd,{asChild:!0,children:o.jsxs("button",{type:"button",className:"text-neutral3 hover:text-neutral5 hover:bg-surface3 inline-flex items-center gap-0.5 rounded px-1 py-0.5 text-[10px] transition-colors",children:[o.jsx(Or,{className:"h-3 w-3"}),"tag"]})}),o.jsxs(Xd,{className:"w-52 p-2",align:"start",children:[o.jsx(In,{ref:l,value:a,onChange:h=>i(h.target.value),onKeyDown:p,placeholder:"Search or create tag...",className:"mb-1 h-7 text-xs",autoFocus:!0}),o.jsxs("div",{className:"max-h-32 space-y-0.5 overflow-y-auto",children:[c.map(h=>o.jsx("button",{type:"button",onClick:()=>d(h),className:"hover:bg-surface3 text-neutral4 w-full rounded px-2 py-1 text-left text-xs",children:h},h)),u&&o.jsxs("button",{type:"button",onClick:()=>d(a.trim()),className:"hover:bg-surface3 text-accent1 w-full rounded px-2 py-1 text-left text-xs",children:['Create "',a.trim(),'"']}),c.length===0&&!u&&o.jsx(me,{variant:"ui-xs",className:"text-neutral3 block px-2 py-1",children:"No tags available"})]})]})]})]})}function iie(e){if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function lUt({item:e,className:t,isCompleted:n,tagVocabulary:r,onRate:s,onSetTags:a,onComment:i,onRemove:l,onComplete:c,onPrevious:u,onNext:d,onClose:f}){const[p,h]=g.useState(e.comment||""),[m,v]=g.useState(!1),[y,b]=g.useState(!1);g.useEffect(()=>{h(e.comment||""),v(!1),b(!1)},[e.id]);const x=g.useRef(void 0);g.useEffect(()=>()=>clearTimeout(x.current),[]);const S=()=>{p!==(e.comment||"")&&(i(p),v(!0),clearTimeout(x.current),x.current=setTimeout(()=>v(!1),1500))};return o.jsxs(o.Fragment,{children:[o.jsxs(fn,{className:t,children:[o.jsxs(fn.Header,{children:[o.jsx(fn.Heading,{children:"Review"}),o.jsxs(hs,{className:"ml-auto shrink-0",children:[o.jsx(fn.NextPrevNav,{onPrevious:u,onNext:d,previousLabel:"Previous item",nextLabel:"Next item"}),!n&&c&&o.jsxs(oe,{size:"md",onClick:c,"aria-label":"Mark as complete",children:[o.jsx(mO,{}),"Complete"]}),o.jsx(fn.CloseButton,{onClick:f,tooltip:"Close detail panel"})]})]}),o.jsxs(fn.Content,{children:[o.jsxs("div",{className:"mb-6 grid gap-4",children:[!n&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(me,{variant:"ui-sm",className:"text-neutral3",children:"Rating"}),o.jsxs(hs,{spacing:"close",children:[o.jsx(oe,{size:"md",onClick:()=>s(e.rating==="positive"?void 0:"positive"),"aria-label":"Rate positive",children:o.jsx(He,{size:"sm",className:e.rating==="positive"?"text-positive1":"",children:o.jsx(y0e,{})})}),o.jsx(oe,{size:"md",onClick:()=>s(e.rating==="negative"?void 0:"negative"),"aria-label":"Rate negative",children:o.jsx(He,{size:"sm",className:e.rating==="negative"?"text-negative1":"",children:o.jsx(v0e,{})})})]}),e.rating&&o.jsx(St,{variant:e.rating==="positive"?"green":"red",children:e.rating==="positive"?"Good":"Bad"})]}),n&&e.rating&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(me,{variant:"ui-sm",className:"text-neutral3",children:"Rating"}),o.jsx(St,{variant:e.rating==="positive"?"green":"red",children:e.rating==="positive"?"Good":"Bad"})]}),o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsx(me,{variant:"ui-sm",className:"text-neutral3 mt-0 block",children:"Tags"}),n?o.jsx("div",{className:"flex flex-wrap gap-1",children:e.tags.length>0?e.tags.map(k=>o.jsx(St,{children:k},k)):o.jsx(me,{variant:"ui-sm",className:"text-neutral2",children:"No tags"})}):o.jsx(Zis,{tags:e.tags,vocabulary:r,onSetTags:a})]}),e.scores&&Object.keys(e.scores).length>0&&o.jsxs("div",{children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3 mb-2 block",children:"Scores"}),o.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(e.scores).map(([k,_])=>o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(He,{size:"sm",className:"text-neutral3",children:o.jsx(Wp,{})}),o.jsxs(me,{variant:"ui-xs",className:"text-neutral4",children:[k,":"]}),o.jsx(St,{variant:_>=.5?"green":"red",children:_.toFixed(3)})]},k))})]}),e.experimentId&&o.jsxs(_n,{children:[o.jsx(_n.Key,{children:"Experiment Id"}),o.jsx(_n.ValueWithCopyBtn,{copyTooltip:"Copy Experiment Id to clipboard",copyValue:e.experimentId,children:e.experimentId})]})]}),o.jsxs("div",{className:"grid gap-3",children:[o.jsx(fn.CodeSection,{title:"Input",icon:o.jsx(xx,{}),codeStr:iie(e.input??null)}),o.jsx(fn.CodeSection,{title:"Output",icon:o.jsx(em,{}),codeStr:iie(e.output??null)})]}),e.error!=null&&o.jsxs("div",{children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral3 mb-1 block",children:"Error"}),o.jsx("pre",{className:"text-ui-xs text-negative1 bg-surface2 max-h-48 overflow-auto rounded-md p-3 wrap-break-word whitespace-pre-wrap",children:iie(e.error)})]}),o.jsxs("div",{className:"mt-4",children:[o.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[o.jsx(me,{variant:"ui-sm",className:"text-neutral2 tracking-widest uppercase",children:"Comment"}),m&&o.jsx(me,{variant:"ui-xs",className:"text-positive1",children:"Saved"})]}),n?o.jsx(me,{variant:"ui-xs",className:"text-neutral4 block",children:e.comment||"No comment"}):o.jsx(Il,{value:p,onChange:k=>h(k.target.value),onBlur:S,placeholder:"Add notes about this item...",rows:3,className:"text-xs"})]}),!n&&o.jsxs("div",{className:"border-border1 mt-4 flex items-center gap-2 border-t pt-4",children:[c&&o.jsxs(oe,{size:"md",onClick:c,children:[o.jsx(mO,{}),"Mark as complete"]}),o.jsxs(oe,{variant:"outline",size:"md",onClick:()=>b(!0),children:[o.jsx(Ml,{}),"Remove"]})]})]})]}),o.jsx(Pt,{open:y,onOpenChange:b,children:o.jsxs(Pt.Content,{children:[o.jsxs(Pt.Header,{children:[o.jsx(Pt.Title,{children:"Remove from Review"}),o.jsx(Pt.Description,{children:"This will remove the item from the review queue. The experiment result will remain but will no longer be flagged for review."})]}),o.jsxs(Pt.Footer,{children:[o.jsx(Pt.Cancel,{children:"Cancel"}),o.jsx(Pt.Action,{onClick:()=>{l(),b(!1)},children:"Remove"})]})]})})]})}function cUt({selectedCount:e,vocabulary:t,onApplyTag:n,onRemoveTag:r,onNewTag:s}){const[a,i]=g.useState(!1),[l,c]=g.useState(""),u=t.filter(f=>f.toLowerCase().includes(l.toLowerCase())),d=l.trim()&&!t.includes(l.trim());return o.jsxs(Uf,{open:a,onOpenChange:i,children:[o.jsx(Kd,{asChild:!0,children:o.jsxs(oe,{variant:"outline",size:"sm",children:[o.jsx(He,{size:"sm",children:o.jsx(sI,{})}),"Tag ",e," items"]})}),o.jsxs(Xd,{className:"w-56 p-2",align:"end",children:[o.jsx(In,{value:l,onChange:f=>c(f.target.value),onKeyDown:f=>{f.key==="Enter"&&l.trim()&&(f.preventDefault(),d?s(l.trim()):n(l.trim()),c(""))},placeholder:"Search or create tag...",className:"mb-1 h-7 text-xs",autoFocus:!0}),o.jsxs("div",{className:"max-h-40 space-y-0.5 overflow-y-auto",children:[u.map(f=>o.jsxs("div",{className:"hover:bg-surface3 flex items-center justify-between rounded px-2 py-1 text-xs",children:[o.jsx("button",{type:"button",onClick:()=>n(f),className:"text-neutral4 flex-1 text-left",children:f}),o.jsx("button",{type:"button",onClick:()=>r(f),className:"text-neutral2 hover:text-negative1 ml-2",children:o.jsx(or,{className:"h-3 w-3"})})]},f)),d&&o.jsxs("button",{type:"button",onClick:()=>{s(l.trim()),c("")},className:"hover:bg-surface3 text-accent1 w-full rounded px-2 py-1 text-left text-xs",children:['Create & apply "',l.trim(),'"']})]})]})]})}function uUt({tag:e,onRename:t,onRemove:n}){const[r,s]=g.useState(!1),[a,i]=g.useState(e),l=g.useRef(null);g.useEffect(()=>{r&&(l.current?.focus(),l.current?.select())},[r]);const c=()=>{const u=a.trim();u&&u!==e&&t(u),s(!1)};return r?o.jsxs("span",{className:"bg-surface3 border-border1 inline-flex items-center gap-0.5 rounded-md border px-1",children:[o.jsx("input",{ref:l,value:a,onChange:u=>i(u.target.value),onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),c()),u.key==="Escape"&&(i(e),s(!1))},onBlur:c,className:"text-neutral4 w-20 bg-transparent py-0.5 text-xs outline-hidden"}),o.jsx("button",{type:"button",onMouseDown:u=>{u.preventDefault(),c()},className:"text-positive1 hover:text-positive2 p-0.5",children:o.jsx(Qr,{className:"h-3 w-3"})})]}):o.jsxs("span",{className:"bg-surface3 border-border1 text-neutral4 group inline-flex items-center gap-0.5 rounded-md border px-1.5 py-0.5 text-xs",children:[e,o.jsx("button",{type:"button",onClick:()=>{i(e),s(!0)},className:"text-neutral2 hover:text-neutral4 p-0.5 opacity-0 transition-opacity group-hover:opacity-100",title:"Edit tag",children:o.jsx(um,{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(or,{className:"h-3 w-3"})})]})}function Gis(e,t){if(typeof e=="string")return e.length>t?e.slice(0,t)+"...":e;try{const n=JSON.stringify(e);return n.length>t?n.slice(0,t)+"...":n}catch{return String(e)}}function Qis({agentId:e,onCreateScorer:t}){const{items:n,setItemTags:r,rateItem:s,commentItem:a,removeItem:i,completeItem:l,loadPersistedItems:c}=U4t(),{data:u}=Wis(e),{data:d,refetch:f,isLoading:p}=His(e),h=Qe(),{provider:m,model:v}=oje(),{data:y}=Im(),{updateDataset:b}=qi();g.useEffect(()=>{u&&c(u)},[u,c]);const[x,S]=g.useState(null),[k,_]=g.useState(!1),[C,T]=g.useState(null),[E,N]=g.useState(new Set),[I,A]=g.useState(!1),R=g.useRef(null),[L,D]=g.useState(!1),[F,H]=g.useState("untagged"),[B,z]=g.useState(""),[V,M]=g.useState(m),[G,U]=g.useState(v),[$,q]=g.useState([]),[Z,Y]=g.useState(!1),[ne,J]=g.useState(null),ee=y?.datasets,re=g.useMemo(()=>{if(!ee)return[];const ye=new Set(n.map(Pe=>Pe.datasetId).filter(Boolean)),xe=new Set;for(const Pe of ee)if(ye.has(Pe.id)&&Array.isArray(Pe.tags))for(const tt of Pe.tags)xe.add(tt);for(const Pe of n)for(const tt of Pe.tags)xe.add(tt);return Array.from(xe).sort()},[ee,n]),le=g.useCallback(ye=>{if(!ee)return;const xe=new Set(n.map(Pe=>Pe.datasetId).filter(Boolean));for(const Pe of ee)if(xe.has(Pe.id)){const tt=Array.isArray(Pe.tags)?Pe.tags:[];tt.includes(ye)||b.mutate({datasetId:Pe.id,tags:[...tt,ye]})}},[ee,n,b]),X=g.useCallback(ye=>{H(ye),z(""),M(m),U(v),D(!0)},[m,v]),te=g.useCallback(async()=>{if(!V||!G)return;const ye=F==="untagged"?n.filter(xe=>xe.tags.length===0):n.filter(xe=>E.has(xe.id));if(ye.length!==0){D(!1),_(!0);try{const xe=`${V}/${G}`,tt=((await h.clusterFailures({modelId:xe,items:ye.map(nt=>({id:nt.id,input:nt.input,output:nt.output,error:typeof nt.error=="string"?nt.error:nt.error?JSON.stringify(nt.error):void 0,scores:nt.scores,existingTags:nt.tags.length>0?nt.tags:void 0})),availableTags:re.length>0?re:void 0,prompt:B.trim()||void 0})).proposedTags??[]).filter(nt=>nt.tags.length>0).map(nt=>({itemId:nt.itemId,tags:nt.tags,reason:nt.reason||"",accepted:!0}));tt.length>0?(J(xe),q(tt),Y(!0)):Be.success("Analysis complete — no new tags proposed.")}catch(xe){console.error("Failed to analyze failures:",xe),Be.error("Analysis failed. Please try again.")}finally{_(!1)}}},[n,V,G,h,E,re,F,B]),se=g.useCallback(()=>{const ye=$.filter(nt=>nt.accepted);for(const nt of ye){const Dt=n.find(Te=>Te.id===nt.itemId);if(Dt){const Te=Array.from(new Set([...Dt.tags,...nt.tags]));r(nt.itemId,Te)}}const xe=new Set(ye.flatMap(nt=>nt.tags));for(const nt of xe)le(nt);const Pe=xe.size,tt=ye.length;Be.success(`Applied ${Pe} tag${Pe!==1?"s":""} to ${tt} item${tt!==1?"s":""}`),Y(!1),q([])},[$,n,r,le]),pe=g.useMemo(()=>C?C==="__untagged__"?n.filter(ye=>ye.tags.length===0):n.filter(ye=>ye.tags.includes(C)):n,[n,C]),ce=g.useMemo(()=>{const ye=new Map;for(const xe of n)for(const Pe of xe.tags)ye.set(Pe,(ye.get(Pe)??0)+1);return[...ye.entries()].sort((xe,Pe)=>Pe[1]-xe[1])},[n]),Se=g.useMemo(()=>n.filter(ye=>ye.tags.length===0).length,[n]),ve=g.useMemo(()=>{let ye=0;return C&&ye++,I&&ye++,ye},[C,I]),ke=g.useMemo(()=>{const ye=I?d??[]:pe;return!I||!C?ye:C==="__untagged__"?ye.filter(xe=>xe.tags.length===0):ye.filter(xe=>xe.tags.includes(C))},[I,d,pe,C]),Ne=I?p:!1,Me=g.useMemo(()=>new Set(ke.map(ye=>ye.id)),[ke]),Ae=g.useMemo(()=>[...E].filter(ye=>Me.has(ye)).length,[E,Me]),Ie=ke.length>0&&Ae===ke.length,ae=Ae>0&&!Ie,fe=g.useCallback(ye=>{N(xe=>{const Pe=new Set(xe);return Pe.has(ye)?Pe.delete(ye):Pe.add(ye),Pe})},[]),ue=g.useCallback(()=>{N(Ie?new Set:new Set(ke.map(ye=>ye.id)))},[Ie,ke]),we=g.useCallback(ye=>{for(const xe of E){const Pe=n.find(tt=>tt.id===xe);Pe&&!Pe.tags.includes(ye)&&r(xe,[...Pe.tags,ye])}le(ye)},[E,n,r,le]),Ee=g.useCallback(ye=>{for(const xe of E){const Pe=n.find(tt=>tt.id===xe);Pe&&Pe.tags.includes(ye)&&r(xe,Pe.tags.filter(tt=>tt!==ye))}},[E,n,r]),ge=g.useCallback(async()=>{for(const ye of E)await l(ye);N(new Set),f()},[E,l,f]),Ce=g.useCallback(()=>{for(const ye of E)i(ye);N(new Set)},[E,i]),Ue=g.useCallback(ye=>{S(xe=>xe===ye?null:ye)},[]),Fe=g.useMemo(()=>x?ke.find(ye=>ye.id===x)??null:null,[x,ke]),Re=g.useCallback(()=>{if(!x||ke.length===0)return;const ye=ke.findIndex(xe=>xe.id===x);ye<ke.length-1&&S(ke[ye+1].id)},[x,ke]),Ge=g.useCallback(()=>{if(!x||ke.length===0)return;const ye=ke.findIndex(xe=>xe.id===x);ye>0&&S(ke[ye-1].id)},[x,ke]),st="auto minmax(15rem,1fr) 10rem 8rem 6rem 6rem",{containerRef:mt,getRowProps:$e}=wo({count:ke.length});return o.jsxs(o.Fragment,{children:[o.jsx(vr,{open:L,onOpenChange:D,children:o.jsxs(yr,{ref:R,className:"max-w-lg",children:[o.jsx(br,{children:o.jsxs(pr,{children:["Analyze ",F==="untagged"?"Untagged":"Selected"," Items"]})}),o.jsx(Mr,{children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(Mt,{children:"Model"}),o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("div",{className:"w-[160px]",children:o.jsx(Vy,{value:V,onValueChange:ye=>{const xe=di(ye);M(xe),U("")},size:"sm",container:R})}),o.jsx("div",{className:"flex-1",children:o.jsx(Hy,{llmId:V,value:G,onValueChange:U,size:"sm",container:R})})]})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(Mt,{children:"Items"}),o.jsx(me,{variant:"ui-sm",className:"text-neutral4",children:F==="untagged"?`${Se} untagged item${Se!==1?"s":""}`:`${E.size} selected item${E.size!==1?"s":""}`})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(Mt,{children:"Instructions (optional)"}),o.jsx(Il,{value:B,onChange:ye=>z(ye.target.value),placeholder:"e.g., Focus on tool usage failures, pay attention to whether the agent hallucinated...",rows:3,disabled:k}),o.jsx(me,{variant:"ui-xs",className:"text-neutral2",children:"Guide the LLM on what to look for when tagging items"})]})]})}),o.jsxs(lc,{className:"px-6",children:[o.jsx(oe,{variant:"ghost",onClick:()=>D(!1),disabled:k,children:"Cancel"}),o.jsx(oe,{variant:"default",onClick:te,disabled:k||!V||!G,children:k?o.jsxs(o.Fragment,{children:[o.jsx(Ut,{className:"mr-2"}),"Analyzing..."]}):"Analyze"})]})]})}),o.jsx(vr,{open:Z,onOpenChange:Y,children:o.jsxs(yr,{className:"max-w-xl",children:[o.jsxs(br,{children:[o.jsx(pr,{children:"Proposed Tag Assignments"}),ne&&o.jsxs(me,{variant:"ui-xs",className:"text-neutral3 mt-1",children:["Analyzed by ",o.jsx("span",{className:"text-neutral4 font-medium",children:ne})]})]}),o.jsx(Mr,{className:"max-h-[400px] space-y-2 overflow-y-auto",children:$.map((ye,xe)=>{const Pe=n.find(nt=>nt.id===ye.itemId),tt=typeof Pe?.input=="string"?Pe.input:Pe?.input?JSON.stringify(Pe.input):"";return o.jsxs("div",{className:K("flex items-start gap-2 p-2 rounded-md border border-border1",ye.accepted?"bg-surface1":"bg-surface1 opacity-50"),children:[o.jsx(So,{checked:ye.accepted,onCheckedChange:nt=>{q(Dt=>Dt.map((Te,Ke)=>Ke===xe?{...Te,accepted:!!nt}:Te))},className:"mt-1"}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral4 block truncate",children:tt||`Item ${ye.itemId.slice(0,8)}`}),o.jsx("div",{className:"mt-1 flex flex-wrap gap-1",children:ye.tags.map((nt,Dt)=>o.jsx(uUt,{tag:nt,onRename:Te=>q(Ke=>Ke.map((pt,Qt)=>Qt===xe?{...pt,tags:pt.tags.map((Yt,an)=>an===Dt?Te:Yt)}:pt)),onRemove:()=>q(Te=>Te.map((Ke,pt)=>pt===xe?{...Ke,tags:Ke.tags.filter((Qt,Yt)=>Yt!==Dt)}:Ke))},`${nt}-${Dt}`))}),ye.reason&&o.jsx(me,{variant:"ui-xs",className:"text-neutral3 mt-1 italic",children:ye.reason})]})]},ye.itemId)})}),o.jsxs(lc,{children:[o.jsx(oe,{variant:"ghost",onClick:()=>Y(!1),children:"Cancel"}),o.jsxs(oe,{variant:"default",onClick:se,disabled:$.filter(ye=>ye.accepted).length===0,children:["Accept ",$.filter(ye=>ye.accepted).length," proposals"]})]})]})}),o.jsxs(vx,{className:K("p-4",Fe?"grid-cols-[1fr_1fr]":""),children:[o.jsxs(ta,{children:[o.jsxs(ta.Toolbar,{children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs(rt,{children:[o.jsx(rt.Trigger,{asChild:!0,children:o.jsxs(oe,{variant:"outline",size:"md",children:[o.jsx(i0e,{}),"Filter",ve>0&&o.jsx("span",{className:K("ml-0.5 inline-flex items-center justify-center rounded-full bg-accent1/50 text-neutral5 text-ui-sm w-5 h-5"),children:ve})]})}),o.jsxs(rt.Content,{align:"start",className:K("min-w-48"),children:[o.jsxs(rt.Sub,{children:[o.jsxs(rt.SubTrigger,{children:["Status",I&&o.jsx("span",{className:K("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(rt.SubContent,{children:[o.jsx(rt.CheckboxItem,{checked:!I,onCheckedChange:()=>{A(!1),S(null)},onSelect:ye=>ye.preventDefault(),children:"Review Queue"}),o.jsx(rt.CheckboxItem,{checked:I,onCheckedChange:()=>{A(!0),S(null)},onSelect:ye=>ye.preventDefault(),children:"Completed"})]})]}),o.jsxs(rt.Sub,{children:[o.jsxs(rt.SubTrigger,{children:["Tags",C&&o.jsx("span",{className:K("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(rt.SubContent,{children:[o.jsx(rt.CheckboxItem,{checked:!C,onCheckedChange:()=>T(null),onSelect:ye=>ye.preventDefault(),children:"All tags"}),Se>0&&o.jsx(rt.CheckboxItem,{checked:C==="__untagged__",onCheckedChange:()=>T(C==="__untagged__"?null:"__untagged__"),onSelect:ye=>ye.preventDefault(),children:"Untagged"}),ce.map(([ye])=>o.jsx(rt.CheckboxItem,{checked:C===ye,onCheckedChange:()=>T(C===ye?null:ye),onSelect:xe=>xe.preventDefault(),children:ye},ye))]})]}),ve>0&&o.jsxs(o.Fragment,{children:[o.jsx(rt.Separator,{}),o.jsxs(rt.Item,{onSelect:()=>{T(null),A(!1),S(null)},children:[o.jsx(or,{}),"Clear all filters"]})]})]})]}),ve>0&&o.jsxs(oe,{variant:"outline",size:"md",onClick:()=>{T(null),A(!1),S(null)},children:[o.jsx(or,{}),"Reset"]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[!I&&E.size>0&&o.jsxs(o.Fragment,{children:[o.jsx(cUt,{selectedCount:E.size,vocabulary:re,onApplyTag:we,onRemoveTag:Ee,onNewTag:ye=>we(ye)}),o.jsxs(rt,{children:[o.jsx(rt.Trigger,{asChild:!0,children:o.jsxs(oe,{disabled:k,children:[k?o.jsx(Ut,{className:"h-4 w-4"}):o.jsx(He,{size:"sm",children:o.jsx(Xs,{})}),"Actions"]})}),o.jsxs(rt.Content,{align:"end",children:[o.jsxs(rt.Item,{onSelect:ge,children:[o.jsx(He,{size:"sm",children:o.jsx(mO,{})}),"Complete"]}),o.jsxs(rt.Item,{onSelect:Ce,children:[o.jsx(He,{size:"sm",children:o.jsx(Ml,{})}),"Remove"]}),o.jsx(rt.Separator,{}),o.jsxs(rt.Item,{disabled:E.size===0,onSelect:()=>X("selected"),children:[o.jsx(He,{size:"sm",children:o.jsx($g,{})}),"Analyze selected"]}),o.jsxs(rt.Item,{disabled:Se===0,onSelect:()=>X("untagged"),children:[o.jsx(He,{size:"sm",children:o.jsx($g,{})}),"Analyze untagged"]})]})]})]}),t&&pe.length>0&&!I&&o.jsxs(oe,{variant:"outline",size:"md",onClick:()=>{t(pe.map(ye=>({input:ye.input,output:ye.output})))},children:[o.jsx(He,{size:"sm",children:o.jsx(Wp,{})}),"Create Scorer"]})]})]}),Ne?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(Ut,{className:"h-4 w-4"})}):ke.length===0?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsxs("div",{className:"px-8 text-center",children:[o.jsx(me,{variant:"ui-sm",className:"text-neutral3 block",children:I?"No completed reviews yet":"No items to review"}),o.jsx(me,{variant:"ui-xs",className:"text-neutral3 mt-2 block",children:I?"Items marked as complete will appear here for auditing.":"When you identify failures in experiment results, send them here to annotate, cluster, and create scorers from failure patterns."})]})}):o.jsxs(be,{columns:st,className:"min-w-0",scrollRef:mt,children:[o.jsxs(be.Top,{hasLeadingCell:!0,children:[I?o.jsx(be.TopCell,{children:" "}):o.jsx(be.TopSelectCell,{checked:Ie?!0:ae?"indeterminate":!1,onToggle:()=>ue(),"aria-label":"Select all"}),o.jsxs(be.TopCells,{colStart:2,children:[o.jsx(be.TopCell,{children:"Input"}),o.jsx(be.TopCell,{children:"Comment"}),o.jsx(be.TopCell,{children:"Tags"}),o.jsx(be.TopCell,{children:"Rating"}),o.jsx(be.TopCell,{children:"Scores"})]})]}),ke.map((ye,xe)=>{const Pe=ye.scores?Object.entries(ye.scores):[],tt=x===ye.id,nt=o.jsxs(o.Fragment,{children:[o.jsx(be.Cell,{className:"text-neutral4 min-w-0",children:o.jsx("span",{className:"block truncate",children:Gis(ye.input,80)})}),o.jsx(be.Cell,{className:"min-w-0",children:ye.comment?o.jsx(me,{variant:"ui-xs",className:"text-neutral3 truncate",children:ye.comment}):o.jsx(me,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsx(be.Cell,{className:"min-w-0",children:ye.tags.length>0?o.jsx(me,{variant:"ui-xs",className:"text-neutral4 truncate",children:ye.tags.join(", ")}):o.jsx(me,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsxs(be.Cell,{children:[ye.rating==="positive"&&o.jsx(He,{size:"sm",className:"text-positive1",children:o.jsx(y0e,{})}),ye.rating==="negative"&&o.jsx(He,{size:"sm",className:"text-negative1",children:o.jsx(v0e,{})}),!ye.rating&&o.jsx(me,{variant:"ui-xs",className:"text-neutral2",children:"—"})]}),o.jsx(be.Cell,{children:Pe.length>0?o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx(He,{size:"sm",className:"text-neutral3",children:o.jsx(Wp,{})}),o.jsx(me,{variant:"ui-xs",className:"text-neutral4 font-mono",children:Pe[0][1].toFixed(2)}),Pe.length>1&&o.jsxs(St,{children:["+",Pe.length-1]})]}):o.jsx(me,{variant:"ui-xs",className:"text-neutral2",children:"—"})})]});return o.jsxs(be.RowWrapper,{children:[I?o.jsx(be.Cell,{className:"justify-items-center px-4",children:o.jsx("div",{role:"img","aria-label":ye.error?"Error":"Success",title:ye.error?"Error":"Success",className:K("w-2 h-2 rounded-full",ye.error?"bg-red-700":"bg-green-600")})}):o.jsx(be.SelectCell,{checked:E.has(ye.id),onToggle:()=>fe(ye.id),"aria-label":`Select item ${ye.id}`}),o.jsx(be.RowButton,{colStart:2,featured:tt,onClick:()=>Ue(ye.id),...$e(xe),children:nt})]},ye.id)})]})]}),Fe&&o.jsx(lUt,{item:Fe,isCompleted:I,tagVocabulary:re,onRate:ye=>s(Fe.id,ye),onSetTags:ye=>{r(Fe.id,ye);for(const xe of ye)re.includes(xe)||le(xe)},onComment:ye=>a(Fe.id,ye),onRemove:()=>i(Fe.id),onComplete:async()=>{await l(Fe.id),f()},onPrevious:Ge,onNext:Re,onClose:()=>S(null)})]})]})}function bJe({href:e,children:t}){return o.jsxs("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-inherit underline hover:text-white",children:[t,o.jsx(Yr,{className:"size-3"})]})}function yP({value:e,icon:t,label:n,badge:r,disabled:s,disabledReason:a}){const i=o.jsxs(o.Fragment,{children:[o.jsx(He,{size:"sm",children:t}),o.jsx(me,{variant:"ui-sm",className:"text-inherit",children:n}),r!==void 0&&r>0&&o.jsx("span",{className:"bg-accent1 ml-1 min-w-[18px] rounded-full px-1.5 py-0 text-center text-xs leading-[18px] font-medium text-white",children:r})]});return s?o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:o.jsx("span",{tabIndex:0,className:"inline-flex",children:o.jsx(Ar,{value:e,disabled:!0,className:"px-3 py-2.5",children:i})})}),a&&o.jsx(vn,{side:"bottom",children:a})]}):o.jsx(Ar,{value:e,className:"px-3 py-2.5",children:i})}function Yis({agentId:e,activeTab:t,showPlayground:n=!1,showObservability:r=!1,reviewBadge:s,rightSlot:a}){const{navigate:i}=cn(),l=n?void 0:o.jsxs("p",{children:["Configure ",o.jsx("code",{children:"@mastra/editor"})," to use the Editor."," ",o.jsx(bJe,{href:"https://mastra.ai/docs/editor/overview",children:"Learn more"})]}),c=r?void 0:o.jsxs("p",{children:["Add ",o.jsx("code",{children:"@mastra/observability"})," to enable this tab."," ",o.jsx(bJe,{href:"https://mastra.ai/docs/observability/overview",children:"Learn more"})]}),u={overview:`/agents/${e}/overview`,versions:`/agents/${e}/editor`,evaluate:`/agents/${e}/evaluate`,review:`/agents/${e}/review`,traces:`/agents/${e}/traces`},d=f=>{f!=="none"&&i(u[f])};return o.jsxs("div",{className:"flex min-w-0 items-center gap-2 p-1.5 max-lg:flex-wrap",children:[o.jsx(yc,{value:t,defaultTab:t,onValueChange:d,className:"min-w-0 flex-1 max-lg:flex-auto",children:o.jsxs(vc,{variant:"pill-ghost",children:[o.jsx(yP,{value:"overview",icon:o.jsx(TKt,{}),label:"Overview"}),o.jsx(yP,{value:"versions",icon:o.jsx(o0e,{}),label:"Editor",disabled:!n,disabledReason:l}),o.jsx(yP,{value:"evaluate",icon:o.jsx(a0e,{}),label:"Evaluate",disabled:!r,disabledReason:c}),o.jsx(yP,{value:"review",icon:o.jsx(vO,{}),label:"Review",badge:s,disabled:!r,disabledReason:c}),o.jsx(yP,{value:"traces",icon:o.jsx(ec,{}),label:"Traces",disabled:!r,disabledReason:c})]})}),a&&o.jsx("div",{className:"ml-auto flex items-center gap-2",children:a})]})}function Kis({requestContextSchema:e}){return o.jsxs(Uf,{children:[o.jsx(Kd,{asChild:!0,children:o.jsxs(oe,{variant:"ghost",size:"sm",type:"button",tooltip:"Run options","data-testid":"agent-top-bar-run-options-trigger",children:[o.jsx(h0e,{}),"Run options"]})}),o.jsx(Xd,{align:"end",className:"w-[min(760px,calc(100vw-2rem))] p-0",children:o.jsx(nUt,{requestContextSchema:e})})]})}const Mz=({label:e,children:t})=>o.jsxs("div",{className:"space-y-2",children:[o.jsx(me,{as:"p",variant:"ui-md",className:"text-neutral3",children:e}),t]});function Xis(e,t){if(!e||h3t(e).toLowerCase()!=="anthropic")return!1;if(!t)return!0;const r=t.toLowerCase();return/[^0-9]4[.-]5/.test(r)||/[^0-9][5-9][.-]\d/.test(r)}function Jis({provider:e,modelId:t,settings:n,setSettings:r}){const s=Xis(e,t),a=g.useEffectEvent(()=>{r({...n,modelSettings:{...n?.modelSettings,topP:void 0}})}),i=e&&t?`${e}-${t}`:void 0,l=n?.modelSettings?.topP,c=n?.modelSettings?.temperature;return g.useEffect(()=>{s&&i&&(l===void 0||c===void 0||a())},[s,i,l,c]),{hasSamplingRestriction:s}}const eos=({canEdit:e=!0})=>{const{settings:t,setSettings:n}=eje(),[r,s]=g.useState(""),[a,i]=g.useState(!1),[l,c]=g.useState(null),u=s0(),{handleCopy:d}=Df({text:r}),f=JSON.stringify(t?.modelSettings?.providerOptions??{});g.useEffect(()=>{(async()=>{if(!ED(f)){c("Invalid JSON");return}const y=await vj(f);s(y)})()},[f]);const p=async()=>{if(c(null),!ED(r)){c("Invalid JSON");return}const v=await vj(r);s(v)},h=async()=>{try{c(null);const v=JSON.parse(r);n({...t,modelSettings:{...t?.modelSettings,providerOptions:v}}),i(!0),setTimeout(()=>{i(!1)},1e3)}catch(v){console.error("error",v),c("Invalid JSON")}},m="text-neutral3 hover:text-neutral6";return o.jsx(zl,{children:o.jsxs("div",{className:"@container/advanced",children:[o.jsxs("div",{className:"grid grid-cols-1 gap-2 pb-2 @xs/advanced:grid-cols-2",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx(me,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"frequency-penalty",children:"Frequency Penalty"}),o.jsx(In,{id:"frequency-penalty",type:"number",step:"0.1",min:"-1",max:"1",readOnly:!e,value:t?.modelSettings?.frequencyPenalty??"",onChange:v=>n({...t,modelSettings:{...t?.modelSettings,frequencyPenalty:v.target.value?Number(v.target.value):void 0}})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(me,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"presence-penalty",children:"Presence Penalty"}),o.jsx(In,{id:"presence-penalty",type:"number",step:"0.1",min:"-1",max:"1",readOnly:!e,value:t?.modelSettings?.presencePenalty??"",onChange:v=>n({...t,modelSettings:{...t?.modelSettings,presencePenalty:v.target.value?Number(v.target.value):void 0}})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(me,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"top-k",children:"Top K"}),o.jsx(In,{id:"top-k",type:"number",readOnly:!e,value:t?.modelSettings?.topK||"",onChange:v=>n({...t,modelSettings:{...t?.modelSettings,topK:v.target.value?Number(v.target.value):void 0}})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(me,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"max-tokens",children:"Max Tokens"}),o.jsx(In,{id:"max-tokens",type:"number",readOnly:!e,value:t?.modelSettings?.maxTokens||"",onChange:v=>n({...t,modelSettings:{...t?.modelSettings,maxTokens:v.target.value?Number(v.target.value):void 0}})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(me,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"max-steps",children:"Max Steps"}),o.jsx(In,{id:"max-steps",type:"number",readOnly:!e,value:t?.modelSettings?.maxSteps||"",onChange:v=>n({...t,modelSettings:{...t?.modelSettings,maxSteps:v.target.value?Number(v.target.value):void 0}})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(me,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"max-retries",children:"Max Retries"}),o.jsx(In,{id:"max-retries",type:"number",readOnly:!e,value:t?.modelSettings?.maxRetries||"",onChange:v=>n({...t,modelSettings:{...t?.modelSettings,maxRetries:v.target.value?Number(v.target.value):void 0}})})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx(me,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"seed",children:"Seed"}),o.jsx(In,{id:"seed",type:"number",readOnly:!e,value:t?.modelSettings?.seed||"",onChange:v=>n({...t,modelSettings:{...t?.modelSettings,seed:v.target.value?Number(v.target.value):void 0}})})]})]}),o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx(me,{as:"label",className:"text-neutral3",variant:"ui-sm",htmlFor:"provider-options",children:"Provider Options"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:o.jsx("button",{type:"button",onClick:p,className:m,"aria-label":"Format Provider Options",children:o.jsx(He,{children:o.jsx(Jl,{})})})}),o.jsx(vn,{children:"Format the Provider Options JSON"})]}),o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:o.jsx("button",{type:"button",onClick:d,className:m,"aria-label":"Copy Provider Options",children:o.jsx(He,{children:o.jsx(zd,{})})})}),o.jsx(vn,{children:"Copy Provider Options"})]}),e&&o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:o.jsx("button",{type:"button",onClick:h,className:m,"aria-label":"Save Provider Options",children:o.jsx(He,{children:a?o.jsx(Qr,{}):o.jsx(Gu,{})})})}),o.jsx(vn,{children:a?"Saved":"Save Provider Options"})]})]})]}),o.jsx(rd,{value:r,onChange:s,theme:u,extensions:[Dp],readOnly:!e,className:"h-dropdown-max-height overflow-scroll rounded-lg border bg-transparent p-2 shadow-sm transition-colors"}),l&&o.jsx(me,{variant:"ui-md",className:"text-accent2",children:l})]})]})})},tos=({hasMemory:e,hasSubAgents:t,disabled:n})=>{const r=e&&t,s=n||!r,a=o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Pp,{value:"network",id:"network",className:"text-neutral6",disabled:s}),o.jsx(Mt,{className:K("text-neutral6 text-ui-md",!r&&"text-neutral3! cursor-not-allowed"),htmlFor:"network",children:"Network"})]});if(r)return a;const i=[];return e||i.push("memory enabled"),t||i.push("at least one sub-agent"),o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:a}),o.jsx(vn,{children:o.jsxs("p",{children:["Network is not available. Please make sure you have ",i.join(" and "),"."]})})]})},nos=({supported:e,disabled:t})=>{const n=t||!e,r=o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Pp,{value:"streamSubscription",id:"streamSubscription",className:"text-neutral6",disabled:n}),o.jsx(Mt,{className:K("text-neutral6 text-ui-md",!e&&"text-neutral3! cursor-not-allowed"),htmlFor:"streamSubscription",children:"Stream subscription (default)"})]});return e?r:o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:r}),o.jsx(vn,{children:o.jsx("p",{children:"Stream subscription is not supported for this agent."})})]})},ros=({agentId:e})=>{const{data:t,isLoading:n}=Vl(e),{data:r,isLoading:s}=yC(e),{settings:a,setSettings:i,resetAll:l}=eje(),{canEdit:c}=_o(),[u,d]=g.useState(!1),[f,p]=g.useState(!1),h=c("agents"),{hasSamplingRestriction:m}=Jis({provider:t?.provider,modelId:t?.modelId,settings:a,setSettings:i});if(!n&&!t)return null;const v=!!r?.result,y=!!(t&&Object.keys(t.agents||{}).length>0),b=t?.modelVersion,x=b==="v2"||b==="v3",S=t?.supportsMemory!==!1;let k;t&&(x?a?.modelSettings?.chatWithNetwork?k="network":a?.modelSettings?.chatWithGenerate?k="generate":a?.modelSettings?.chatWithLegacyStream||!S?k="stream":k="streamSubscription":k=a?.modelSettings?.chatWithGenerateLegacy?"generateLegacy":"streamLegacy");const _=m&&(a?.modelSettings?.temperature!==void 0||a?.modelSettings?.topP!==void 0);return o.jsxs(o.Fragment,{children:[o.jsxs(Uf,{open:f,onOpenChange:(C,T)=>{if(!C&&u){T?.cancel?.();return}p(C)},children:[o.jsx(Kd,{asChild:!0,children:o.jsx(oe,{variant:"default",size:"icon-md",type:"button",tooltip:"Model settings","data-testid":"composer-model-settings-trigger",children:o.jsx(_Jt,{className:"text-neutral3 hover:text-neutral6 h-5 w-5"})})}),o.jsx(Xd,{align:"start",className:"w-80 p-4",children:n||s?o.jsx(jt,{className:"h-40 w-full","data-testid":"composer-model-settings-skeleton"}):o.jsxs("section",{className:"@container space-y-5",children:[o.jsx(Mz,{label:"Chat Method",children:o.jsxs(G4,{value:k,disabled:!h,onValueChange:C=>h&&i({...a,modelSettings:{...a?.modelSettings,chatWithGenerateLegacy:C==="generateLegacy",chatWithGenerate:C==="generate",chatWithLegacyStream:C==="stream",chatWithNetwork:C==="network"}}),className:"flex flex-col gap-3",children:[!x&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Pp,{value:"generateLegacy",id:"generateLegacy",className:"text-neutral6",disabled:!h}),o.jsx(Mt,{className:"text-neutral6 text-ui-md",htmlFor:"generateLegacy",children:"Generate (Legacy)"})]}),x&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Pp,{value:"generate",id:"generate",className:"text-neutral6",disabled:!h}),o.jsx(Mt,{className:"text-neutral6 text-ui-md",htmlFor:"generate",children:"Generate"})]}),!x&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Pp,{value:"streamLegacy",id:"streamLegacy",className:"text-neutral6",disabled:!h}),o.jsx(Mt,{className:"text-neutral6 text-ui-md",htmlFor:"streamLegacy",children:"Stream (Legacy)"})]}),x&&o.jsx(nos,{supported:S,disabled:!h}),x&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Pp,{value:"stream",id:"stream",className:"text-neutral6",disabled:!h}),o.jsx(Mt,{className:"text-neutral6 text-ui-md",htmlFor:"stream",children:"Stream"})]}),x&&o.jsx(tos,{hasMemory:v,hasSubAgents:y,disabled:!h})]})}),o.jsx(Mz,{label:"Require Tool Approval",children:o.jsx(So,{checked:a?.modelSettings?.requireToolApproval,disabled:!h,onCheckedChange:C=>h&&i({...a,modelSettings:{...a?.modelSettings,requireToolApproval:C}})})}),_&&o.jsxs("div",{className:"text-neutral3 bg-surface3 flex items-center gap-2 rounded px-3 py-2 text-xs","data-testid":"sampling-restriction-banner",children:[o.jsx(km,{className:"h-3.5 w-3.5 shrink-0"}),o.jsx("span",{children:a?.modelSettings?.temperature!==void 0?"Claude 4.5+ models only accept Temperature OR Top P. Clear Temperature to use Top P.":"Claude 4.5+ models only accept Temperature OR Top P. Setting Temperature will clear Top P."})]}),o.jsx(Mz,{label:"Temperature",children:o.jsxs("div",{className:"flex flex-row items-center justify-between gap-2",children:[o.jsx(axe,{value:[a?.modelSettings?.temperature??-.1],max:1,min:-.1,step:.1,disabled:!h,onValueChange:C=>h&&i({...a,modelSettings:{...a?.modelSettings,temperature:C[0]<0?void 0:C[0]}})}),o.jsx(me,{as:"p",variant:"ui-sm",className:"text-neutral3",children:a?.modelSettings?.temperature??"n/a"})]})}),o.jsx(Mz,{label:"Top P",children:o.jsxs("div",{className:"flex flex-row items-center justify-between gap-2",children:[o.jsx(axe,{disabled:!h,onValueChange:C=>h&&i({...a,modelSettings:{...a?.modelSettings,topP:C[0]<0?void 0:C[0]}}),value:[a?.modelSettings?.topP??-.1],max:1,min:-.1,step:.1}),o.jsx(me,{as:"p",variant:"ui-sm",className:"text-neutral3",children:a?.modelSettings?.topP??"n/a"})]})}),o.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[o.jsx(oe,{variant:"ghost",size:"sm",type:"button",disabled:!h,onClick:()=>h&&l(),children:"Reset"}),o.jsx(oe,{variant:"default",size:"sm",type:"button",disabled:!h,onClick:()=>d(!0),children:"Advanced Settings"})]})]})})]}),o.jsx(vr,{open:u,onOpenChange:d,children:o.jsxs(yr,{className:"sm:max-w-xl",children:[o.jsx(br,{children:o.jsx(pr,{children:"Advanced model settings"})}),o.jsx(Mr,{children:o.jsx(eos,{canEdit:h})})]})})]})},xJe="lk.agent.state",sos="lk.transcription",aos="lk.transcription_final";function ios(e,t,n,r,s){return(e.find(l=>l.id===t)?e.map(l=>l.id===t?{...l,text:l.text+r,final:l.final||s}:l):[...e,{id:t,role:n,text:r,final:s}]).slice(-20)}const oos=({agentId:e,threadId:t,onCallStarted:n})=>{const{baseUrl:r,headers:s}=SH(),a=Lr(),i=g.useRef(n);g.useEffect(()=>{i.current=n},[n]);const[l,c]=g.useState("idle"),[u,d]=g.useState("initializing"),[f,p]=g.useState([]),h=g.useRef(null),m=g.useRef(null),v=g.useRef(null),y=g.useRef(0),b=g.useRef(null),x=g.useCallback(()=>{t&&a.invalidateQueries({queryKey:["memory","messages",t]}),e&&a.invalidateQueries({queryKey:["memory","threads",e,e]})},[e,a,t]),S=g.useCallback(()=>{v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{v.current=null,x()},600)},[x]),k=g.useCallback(()=>{y.current+=1,b.current?.abort(),b.current=null;const T=h.current;h.current=null,T&&T.disconnect(),v.current&&(clearTimeout(v.current),v.current=null),m.current=null,c("idle"),d("initializing")},[]);g.useEffect(()=>k,[k]);const _=g.useCallback(()=>{k(),p([]),x()},[k,x]),C=g.useCallback(async()=>{if(l!=="idle")return;const T=y.current+=1,E=new AbortController;b.current=E;const N=()=>y.current!==T;c("connecting"),p([]);try{const I=await fetch(`${r}/voice/livekit/connection-details`,{method:"POST",headers:{...s,"content-type":"application/json"},body:JSON.stringify({agentId:e,threadId:t,resourceId:e}),signal:E.signal});if(N())return;if(!I.ok){const B=await I.json().catch(()=>({}));throw new Error(B.error??"LiveKit voice is not configured for this server. Add liveKitConnectionRoute() to server.apiRoutes and run a voice worker.")}const A=await I.json();if(N())return;const{Room:R,RoomEvent:L,Track:D}=await Ma(async()=>{const{Room:B,RoomEvent:z,Track:V}=await import("./livekit-client.esm-CKIgC2IJ.js");return{Room:B,RoomEvent:z,Track:V}},[],import.meta.url);if(N())return;const F=new R;h.current=F;const H=new Audio;if(H.autoplay=!0,m.current=H,F.on(L.TrackSubscribed,B=>{B.kind===D.Kind.Audio&&m.current&&B.attach(m.current)}),F.on(L.ParticipantAttributesChanged,(B,z)=>{const V=B[xJe]??z.attributes[xJe];V&&z.identity!==A.participantName&&d(V)}),F.on(L.Disconnected,()=>{h.current===F&&k()}),F.registerTextStreamHandler(sos,async(B,z)=>{const V=z.identity===A.participantName?"user":"agent",M=B.info.attributes?.[aos]==="true";for await(const G of B)p(U=>ios(U,B.info.id,V,G,M));V==="agent"&&S()}),await F.connect(A.serverUrl,A.participantToken),N()){F.disconnect(),h.current===F&&(h.current=null);return}if(await F.localParticipant.setMicrophoneEnabled(!0),N()){F.disconnect(),h.current===F&&(h.current=null);return}c("active"),x(),await Promise.resolve(i.current?.()).catch(()=>{})}catch(I){if(E.signal.aborted||N())return;k(),gu.error(I instanceof Error?I.message:"Failed to start the voice call.")}},[e,r,k,s,x,S,l,t]);return{status:l,agentState:u,captions:f,start:()=>{C()},stop:_}},los=({voiceCall:e})=>e.status==="idle"?o.jsx(oe,{variant:"default",size:"icon-md",type:"button",tooltip:"Start voice call","data-testid":"voice-call-button",onClick:()=>e.start(),children:o.jsx(UXt,{className:"text-neutral3 hover:text-neutral6 h-5 w-5"})}):e.status==="connecting"?o.jsx(oe,{variant:"default",size:"icon-md",type:"button",tooltip:"Connecting…","data-testid":"voice-call-button",children:o.jsx(qs,{className:"text-neutral3 h-5 w-5 animate-spin"})}):o.jsx(oe,{variant:"default",size:"icon-md",type:"button",tooltip:"End voice call","data-testid":"voice-call-button",onClick:()=>e.stop(),children:o.jsx(zXt,{className:"h-5 w-5 text-red-500"})}),cos={initializing:"Connecting…",listening:"Listening…",thinking:"Thinking…",speaking:"Speaking…"},wJe=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(e[n]?.role===t)return e[n]},uos=({voiceCall:e})=>{if(e.status==="idle")return null;const t=wJe(e.captions,"user"),n=wJe(e.captions,"agent"),r=e.status==="connecting"?"Connecting…":cos[e.agentState];return o.jsxs("div",{"data-testid":"voice-call-panel",className:"border-border2/40 bg-surface3 mx-auto mb-2 w-full max-w-3xl rounded-[16px] border px-4 py-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:K("h-2 w-2 rounded-full",e.status==="connecting"&&"bg-neutral3",e.status==="active"&&e.agentState==="speaking"&&"bg-accent1 animate-pulse",e.status==="active"&&e.agentState!=="speaking"&&"bg-green-500")}),o.jsx("span",{className:"text-ui-sm text-neutral4",children:r})]}),t&&o.jsx("p",{className:"text-ui-sm text-neutral3 mt-2 truncate","data-testid":"voice-caption-user",children:t.text}),n&&o.jsx("p",{className:"text-ui-sm text-neutral6 mt-1","data-testid":"voice-caption-agent",children:n.text})]})},dos=300,fos=[],pos=(e,t)=>{const[n,r]=g.useState(!1);return g.useEffect(()=>{if(!e){r(!1);return}const s=setTimeout(()=>r(!0),t);return()=>clearTimeout(s)},[e,t]),n},hos=e=>e?e.content.parts.some(n=>{if(n.type==="reasoning"||n.type==="text")return"state"in n&&n.state==="streaming";if(n.type==="tool-invocation")return"toolInvocation"in n&&n.toolInvocation.state!=="result";if(n.type==="dynamic-tool"||n.type.startsWith("tool-")){const r="state"in n?n.state:void 0;return r!=="output-available"&&r!=="output-error"}return!1}):!1,mos=({turns:e})=>e.length===0?null:o.jsx("div",{"data-testid":"thread-rail-layer",className:"thread-rail-layer pointer-events-none absolute inset-y-0 left-4 z-20",children:o.jsx($Ur,{turns:e,className:"pointer-events-auto sticky top-1/2 -translate-y-1/2"})}),gos=({agentName:e,agentId:t,threadId:n,suggestedPrompts:r,hasModelList:s,hideModelSwitcher:a,runOptionsSlot:i,refreshThreadList:l})=>{const c=g.useRef(null),u=fBr(),{isRunning:d}=Q4(),{requestContext:f}=vs(),{isSpeaking:p,readAloud:h,stop:m}=vqr(t,f),{hasSession:v,viewMode:y}=B4(),b=v&&(y==="collapsed"||y==="expanded"),x=u.length===0,S=u[u.length-1],k=d&&(S?.role!=="assistant"||!hos(S)),_=pos(k,dos),C=g.useMemo(()=>GUr(u),[u]),T=g.useMemo(()=>new Set(C.map(N=>N.messageId)),[C]),E=[];for(const N of u)(T.has(N.id)||E.length===0)&&E.push({key:nxe(N),messages:[],opensTurn:T.has(N.id)}),E.at(-1)?.messages.push(N);return o.jsx(aqr,{children:o.jsx(jUr,{defaultScrollPosition:"last-anchor",children:o.jsxs("div",{className:"group/thread grid h-full grid-rows-[1fr_auto] overflow-y-auto","data-testid":"thread-wrapper",children:[o.jsxs(tLt,{children:[o.jsx(nLt,{className:"h-full overflow-y-scroll",style:{overflowAnchor:"none"},children:x?o.jsx(vos,{agentName:e,suggestedPrompts:r}):o.jsxs("div",{"data-testid":"thread-rail-container",className:"thread-rail-container relative min-h-full",children:[o.jsx(mos,{turns:C}),o.jsxs("div",{ref:c,"data-testid":"thread-message-column",className:"relative mx-auto w-full max-w-3xl px-4 pb-7 group-has-[[data-attachments-row]]/thread:pb-24",children:[o.jsx(yqr,{containerRef:c}),o.jsx(V4t,{children:o.jsx(rLt,{className:"flex flex-col gap-6 py-6",children:E.map((N,I)=>{const A=I===E.length-1;return o.jsxs("div",{className:K("flex flex-col gap-6",A&&N.opensTurn&&"min-h-[50cqh]"),children:[N.messages.map(R=>o.jsx(sLt,{messageId:R.id,scrollAnchor:T.has(R.id),children:o.jsx(tBt,{message:R,hasModelList:s,isSpeaking:p,onReadAloud:h,onStopSpeaking:m})},nxe(R))),A&&_&&o.jsx(G2t,{})]},N.key)})})}),!d&&o.jsx(_qr,{})]})]})}),o.jsx("div",{className:"pointer-events-none absolute inset-x-0 bottom-4 z-30 mx-auto flex w-full max-w-3xl px-4",children:o.jsx(aLt,{className:"pointer-events-auto static ms-auto translate-x-0 rtl:translate-x-0"})})]}),b&&t&&n&&o.jsx("div",{className:"mx-auto mb-2 w-full max-w-3xl px-4",children:o.jsx(YDt,{agentName:e})}),o.jsx(ors,{}),o.jsx(yos,{agentId:t,threadId:n,hasModelList:s,hideModelSwitcher:a,runOptionsSlot:i,refreshThreadList:l})]})})})},vos=({agentName:e,suggestedPrompts:t=fos})=>o.jsxs("div",{className:"flex w-full grow flex-col items-center pt-[15vh]",children:[o.jsx(g_,{name:e||"Agent",size:"lg"}),o.jsx("p",{className:"mt-4 font-medium",children:"How can I help you today?"}),o.jsx(Qns,{prompts:t})]}),yos=({agentId:e,threadId:t,hasModelList:n,hideModelSwitcher:r,runOptionsSlot:s,refreshThreadList:a})=>{const{threadInput:i,setThreadInput:l}=lBt(t),c=g.useRef(null),u=YTe(),{attachments:d,toCoreUserMessages:f,clear:p}=fG(),{isRunning:h,canSendWhileStreaming:m,cancelRun:v}=Q4(),[y,b]=g.useState(0),{canExecute:x}=_o(),S=x("agents"),k=oos({agentId:e,threadId:t,onCallStarted:a}),_=i.trim().length===0&&d.length===0,C=h&&!m,T=async()=>{if(_||C||!S)return;const E=d.length>0?await f():void 0,N=i;l(""),p(),b(I=>I+1),u({message:N,attachments:E})};return o.jsxs("div",{className:"relative",style:{viewTransitionName:"agent-chat-composer"},children:[o.jsx(uos,{voiceCall:k}),o.jsxs(H4t,{className:"relative px-2 pb-2",onSubmit:E=>{E.preventDefault(),T()},children:[o.jsx(G4t,{children:o.jsx(gqr,{})}),o.jsx(Z4t,{busy:h,children:o.jsxs(W4t,{sendingPulseKey:y,children:[o.jsx(Q4t,{ref:c,value:i,autoFocus:!1,placeholder:S?"Enter your message...":"You don't have permission to execute agents",onChange:E=>{l(E.target.value)},onKeyDown:E=>{if(!(E.nativeEvent.isComposing||E.keyCode===229)&&E.key==="Enter"&&!E.shiftKey){if(C)return;E.preventDefault(),E.stopPropagation(),T()}},disabled:!S}),e&&!n&&!r&&o.jsx(vrs,{}),o.jsx(Y4t,{children:o.jsx(xos,{canExecute:S,agentId:e,runOptionsSlot:s,showModelSwitcher:!!(e&&!n&&!r),isEmpty:_,isRunning:h,canSendWhileStreaming:m,onCancel:()=>{v()},onSetText:E=>{l(E)},voiceCall:k})})]})})]})]})},bos=({agentId:e,onTranscript:t})=>{const{requestContext:n}=vs(),{start:r,stop:s,isListening:a,transcript:i}=$On({agentId:e,requestContext:n});return g.useEffect(()=>{i&&g.startTransition(()=>t(i))},[t,i]),o.jsx(oe,{variant:"default",size:"icon-md",type:"button",tooltip:a?"Stop dictation":"Start dictation",onClick:()=>a?s():r(),children:a?o.jsx(jxe,{}):o.jsx(lXt,{className:"text-neutral3 hover:text-neutral6 h-5 w-5"})})},xos=({canExecute:e=!0,agentId:t,showModelSwitcher:n,runOptionsSlot:r,isEmpty:s,isRunning:a,canSendWhileStreaming:i,onCancel:l,onSetText:c,voiceCall:u})=>o.jsxs(o.Fragment,{children:[(n&&t||r)&&o.jsxs("div",{className:"flex max-w-full shrink-0 items-center gap-1.5",children:[n&&t&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"bg-surface3 border-border1 duration-normal focus-within:border-border2 rounded-full border transition-colors",children:o.jsx(grs,{})}),o.jsx(ros,{agentId:t})]}),r]}),o.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[o.jsxs(hs,{spacing:"close",children:[e&&o.jsx(iqr,{}),e&&o.jsx(bos,{agentId:t,onTranscript:c}),e&&t&&u&&o.jsx(los,{voiceCall:u})]}),o.jsx(wos,{canExecute:e,isEmpty:s,isRunning:a,canSendWhileStreaming:i,onCancel:l})]})]}),wos=({canExecute:e=!0,isEmpty:t,isRunning:n,canSendWhileStreaming:r,onCancel:s})=>n&&!r?o.jsx(oe,{variant:"default",size:"icon-md",type:"button",tooltip:"Cancel",onClick:s,children:o.jsx(jxe,{})}):o.jsxs(o.Fragment,{children:[o.jsx(oe,{type:"submit",variant:"default",size:"icon-md",tooltip:e?"Send":"No permission to execute",className:"border-border1 bg-surface5 rounded-full border",disabled:!e||t,children:o.jsx(q1,{className:"text-neutral3 hover:text-neutral6 h-6 w-6"})}),n&&o.jsx(oe,{variant:"default",size:"icon-md",type:"button",tooltip:"Cancel",onClick:s,children:o.jsx(jxe,{})})]}),jxe=()=>o.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-neutral3 hover:text-neutral6",children:[o.jsx("circle",{cx:"12",cy:"12",r:"10"}),o.jsx("rect",{width:"6",height:"6",x:"9",y:"9",rx:"1"})]}),Sos=({suggestedPrompts:e,isNewThread:t,isMessagesLoading:n})=>{if(t)return e;if(!n)return e},eAe=({agentId:e,agentName:t,threadId:n,memory:r,refreshThreadList:s,modelVersion:a,agentVersionId:i,supportsMemory:l,modelList:c,messageId:u,suggestedPrompts:d,isNewThread:f,hideModelSwitcher:p,runOptionsSlot:h})=>{const{settings:m}=eje(),v=Bl(),{data:y,isLoading:b}=wW({agentId:e,threadId:f?void 0:n,memory:r??!1});g.useEffect(()=>{u&&y&&!b&&setTimeout(()=>{const _=document.querySelector(`[data-message-id="${u}"]`);_&&(_.scrollIntoView({behavior:"smooth",block:"center"}),_.classList.add("bg-surface4"),setTimeout(()=>{_.classList.remove("bg-surface4")},2e3))},100)},[u,y,b]);const x=g.useRef({threadId:n,messages:[]});x.current.threadId!==n&&(x.current={threadId:n,messages:[]});const S=y?.messages??x.current.messages,k=Sos({suggestedPrompts:d,isNewThread:f,isMessagesLoading:b});return o.jsx(aUr,{agentId:e,agentName:t,modelVersion:a,agentVersionId:i,supportsMemory:l,threadId:n,initialMessages:S,refreshThreadList:s,settings:m,requestContext:v,children:o.jsx(gos,{agentName:t??"",agentId:e,threadId:n,suggestedPrompts:k,hasModelList:!!c,hideModelSwitcher:p,refreshThreadList:s,runOptionsSlot:h})})};function SJe(){const{agentId:e,threadId:t}=mr(),[n]=hi(),{data:r,isLoading:s}=Vl(e),{data:a}=yC(e),i=es(),l=t==="new",c=g.useMemo(()=>vo(),[t]),u=!!a?.result,{refetch:d}=k4t({resourceId:e,agentId:e,isMemoryEnabled:u});g.useEffect(()=>{u&&(t||i(`/agents/${e}/session/new`))},[u,t,e,i]);const f=n.get("messageId")??void 0,p=g.useMemo(()=>KIe(r),[r]);if(s)return o.jsx(kos,{});if(!r)return o.jsx("div",{className:"py-4 text-center",children:"Agent not found"});const h=l?c:t??c,m=async()=>{await d(),l&&i(`/agents/${e}/session/${c}`)};return o.jsx(jH,{entityId:e,entityType:"agent",children:o.jsx(JTe,{agentId:e,defaultSettings:p,children:o.jsx(I3,{children:o.jsx($4t,{agentId:e,threadId:h,resourceId:e,children:o.jsx(qZ,{children:o.jsx(VZ,{agentId:e,threadId:h,enabled:!!(r?.hasBrowser??r?.browserTools?.length),children:o.jsx(qIe,{children:o.jsx(L4t,{children:o.jsx(JZ,{children:o.jsxs(_s,{children:[o.jsx(E4t,{}),o.jsx("div",{className:"relative grid h-full overflow-y-auto pt-6",children:o.jsx(eAe,{agentId:e,agentName:r?.name,modelVersion:r?.modelVersion,supportsMemory:r?.supportsMemory,threadId:h,memory:u,refreshThreadList:m,modelList:r?.modelList,messageId:f,isNewThread:l,hideModelSwitcher:!0},h)})]})})})})},`session-${e}-${h}`)},`browser-${e}-${h}`)})})})})}const kos=()=>o.jsxs(_s,{children:[o.jsx(E4t,{}),o.jsx("div",{className:"relative grid h-full overflow-y-auto pt-6","data-testid":"agent-session-skeleton","aria-busy":"true",children:o.jsx($3t,{})})]});function Oos({className:e,children:t,...n}){return o.jsx("div",{className:K("mt-auto",e),...n,children:t})}const tAe=ze.createContext(null),dUt=ze.createContext(null);function SQ(){return ze.useContext(tAe)}function _C(){const e=ze.useContext(tAe),t=ze.useContext(dUt);if(!e||!t)throw new Error("useMainSidebar must be used within a MainSidebarProvider.");return{...e,...t}}function _os({className:e,icon:t,"aria-label":n="Open navigation menu",onClick:r,...s}){const{isMobile:a,setOpenMobile:i}=_C();return o.jsx("button",{type:"button","aria-label":n,"aria-hidden":!a,tabIndex:a?0:-1,"data-mobile-only":!0,...s,onClick:l=>{r?.(l),l.defaultPrevented||i(!0)},className:K("inline-flex size-10 items-center justify-center rounded-md","[[data-sidebar-mobile='false']_&]:hidden","text-neutral4 hover:bg-sidebar-nav-hover hover:text-neutral6","focus-visible:ring-1 focus-visible:ring-accent1 focus-visible:outline-hidden",e),children:t??o.jsx(JKt,{className:"size-5"})})}function Cos({"aria-label":e="Main",children:t,className:n,...r}){return o.jsx("nav",{"aria-label":e,className:K("flex min-h-0 flex-1 flex-col",n),...r,children:o.jsx(Dr,{className:"min-h-0 flex-1",viewPortClassName:"px-0.5",children:t})})}function fUt({children:e,className:t,state:n,href:r,isActive:s,LinkComponent:a,...i}){const l=SQ(),c=n??l?.state??"default",u=l?.isMobile??!1,d=a??l?.LinkComponent??"a",f=c==="default"&&!u;return o.jsx("div",{className:K("mt-2 mb-0.5 flex min-h-8 min-w-0 items-center",t),children:f?o.jsx("header",{...i,className:K("max-w-full min-w-0 truncate pl-3 text-ui-sm font-medium",{"text-neutral5":s,"text-neutral3/70":!s}),children:r?o.jsx(d,{href:r,className:K("duration-normal block min-w-0 truncate transition-colors",{"hover:text-neutral5":!s,"text-neutral5":s}),children:e}):e}):o.jsxs(o.Fragment,{children:[o.jsx(w1,{asChild:!0,children:o.jsx("header",{...i,children:e})}),o.jsx("div",{"aria-hidden":"true",className:"bg-border1 mx-3 h-px flex-1"})]})})}function pUt({children:e,className:t,state:n,...r}){const s=SQ();return(n??s?.state??"default")==="collapsed"?o.jsx(w1,{children:e}):o.jsx("span",{...r,className:K("min-w-0 flex-1 truncate text-left font-[450]",t),children:e})}const Eos=Ii("flex min-w-0 cursor-pointer items-center rounded-lg whitespace-nowrap",{variants:{size:{default:"h-8 text-ui-md",sm:"h-7 text-ui-sm",lg:"h-9 text-ui-md"}},defaultVariants:{size:"sm"}}),Tos=e=>e<=0?"w-full gap-2 py-1 px-3 justify-start":e===1?"w-full gap-2 py-1 pr-3 pl-8 justify-start text-ui-sm h-8":e===2?"w-full gap-2 py-1 pr-3 pl-10 justify-start text-ui-sm h-8":"w-full gap-2 py-1 pr-3 pl-12 justify-start text-ui-sm h-8",jos=K("rounded-lg text-neutral3 [&_svg]:text-neutral3/70","hover:bg-sidebar-nav-hover hover:text-neutral6 [&:hover_svg]:text-neutral5"),Nos="bg-sidebar-nav-active text-neutral6 hover:bg-sidebar-nav-active hover:text-neutral6 [&_svg]:text-neutral6 [&:hover_svg]:text-neutral6",Ios=K("my-2 border border-accent1/30 bg-accent1Dark text-accent1 hover:bg-accent1Darker hover:text-accent1","dark:border-transparent dark:bg-accent1 dark:text-black dark:hover:bg-accent1/90 dark:hover:text-black","[&_svg]:text-accent1 dark:[&_svg]:text-black/75 [&:hover_svg]:text-accent1 dark:[&:hover_svg]:text-black"),hUt=({isActive:e,isFeatured:t})=>K(jos,e&&Nos,t&&Ios),mUt=({isCollapsed:e,level:t=0,size:n})=>K(Eos({size:n}),"transition-all duration-normal ease-out-custom motion-reduce:transition-none","[&_svg]:size-4 [&_svg]:shrink-0 [&_svg]:transition-colors [&_svg]:duration-normal motion-reduce:[&_svg]:transition-none","focus-visible:shadow-focus-ring focus-visible:ring-1 focus-visible:ring-accent1 focus-visible:outline-hidden",!e&&Tos(t),e&&"w-full justify-center p-0"),Aos=({isActive:e,isCollapsed:t,isFeatured:n,level:r,size:s}={})=>K(mUt({isCollapsed:t,level:r,size:s}),hUt({isActive:e,isFeatured:n}),t&&!e&&"[&_svg]:text-neutral3");function gUt({link:e,state:t,children:n,isActive:r,size:s,render:a,action:i,className:l,LinkComponent:c,level:u,subItems:d,asChild:f=!1,...p}){if(a&&f)throw new Error("MainSidebarNavLink accepts either `render` or `asChild`, not both.");const h=SQ(),m=t??h?.state??"default",v=c??h?.LinkComponent??"a",y=m==="collapsed",b=e?.variant==="featured",x=u??(e?.indent?1:0),S=y?void 0:i,k=S?K(mUt({level:x,size:s}),"flex-1 pr-1"):Aos({isActive:r,isCollapsed:y,isFeatured:b,level:x,size:s});return o.jsxs("li",{...p,className:K("relative flex min-w-0 flex-col",l),children:[o.jsx(Mos,{action:S,surfaceClassName:hUt({isActive:r,isFeatured:b}),children:o.jsx($os,{label:Pos(e,y),children:Ros({render:a,asChild:f,children:n,link:e,state:m,Link:v,className:k})})}),!y&&d]})}function Ros({render:e,asChild:t,children:n,link:r,state:s,Link:a,className:i}){if(e)return ze.cloneElement(e,{className:K(i,e.props.className)});if(t){if(!ze.isValidElement(n))throw new Error("MainSidebarNavLink requires a valid React element child when `asChild` is true so it can apply `SlottedNavChildProps` and merge `itemClassName`.");return ze.cloneElement(n,{className:K(i,n.props.className)})}if(!r)return n;const l=/^(https?:)?\/\//.test(r.url)?{target:"_blank",rel:"noreferrer"}:{};return o.jsxs(a,{href:r.url,...l,className:i,children:[r.icon,o.jsx(pUt,{state:s,children:r.name}),n]})}function Pos(e,t){if(e)return e.tooltipMsg?t?`${e.name} | ${e.tooltipMsg}`:e.tooltipMsg:t?e.name:void 0}function $os({label:e,children:t}){return!e||!ze.isValidElement(t)?t:o.jsxs(yn,{children:[o.jsx(gn,{render:t}),o.jsx(vn,{side:"right",align:"center",sideOffset:16,children:e})]})}function Mos({action:e,surfaceClassName:t,children:n}){return e?o.jsxs("div",{className:K("flex min-w-0 items-center pr-1",t),children:[n,e]}):n}function nAe({className:e,children:t,...n}){return o.jsx("ul",{className:K("grid grid-cols-[minmax(0,1fr)] content-center items-start gap-0.5",e),...n,children:t})}function vUt({className:e,children:t,...n}){return o.jsx("section",{className:K("relative grid grid-cols-[minmax(0,1fr)] content-center items-start",e),...n,children:t})}function yUt({className:e,...t}){return o.jsx("div",{role:"separator","aria-orientation":"horizontal",className:K("relative min-h-5",'[&:after]:absolute [&:after]:inset-x-3 [&:after]:top-1/2 [&:after]:block [&:after]:h-0 [&:after]:border-t [&:after]:border-border1 [&:after]:content-[""]',e),...t})}const kJe=10,Dos=5;function Los({children:e,className:t}){const{state:n,width:r,minWidth:s,maxWidth:a,collapseBelow:i,collapsedWidth:l,isMobile:c,openMobile:u,setOpenMobile:d,setWidth:f,collapse:p,expand:h,commit:m,toggleSidebar:v,setGestureActive:y}=_C(),b=n==="collapsed",x=b&&l===0,S=g.useRef(!1),k=g.useRef(null);g.useEffect(()=>()=>{k.current?.(),k.current=null},[]);const _=g.useCallback(I=>{if(I.button!==0)return;I.preventDefault(),S.current=!1,y(!0);const A=I.clientX,R=I.currentTarget,L=I.pointerId;try{R.setPointerCapture(L)}catch{}const D=R.parentElement,F=D?D.getBoundingClientRect().left:0,H=document.body.style.cursor,B=document.body.style.userSelect,z=M=>{if(M.pointerId!==L)return;const G=M.clientX-A;if(!S.current){if(Math.abs(G)<=Dos)return;S.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none"}const U=M.clientX-F;if(i>0&&U<i){p();return}h(),f(U)},V=M=>{M&&M.pointerId!==L||(window.removeEventListener("pointermove",z),window.removeEventListener("pointerup",V),window.removeEventListener("pointercancel",V),document.body.style.cursor=H,document.body.style.userSelect=B,y(!1),m(),k.current=null)};k.current=()=>V(),window.addEventListener("pointermove",z),window.addEventListener("pointerup",V),window.addEventListener("pointercancel",V)},[i,f,h,p,m,y]),C=g.useCallback(()=>{if(S.current){S.current=!1;return}v()},[v]),T=g.useCallback(I=>{switch(I.key){case"Enter":case" ":{I.preventDefault(),v();return}case"ArrowLeft":{if(I.preventDefault(),b)return;f(r-kJe),m();return}case"ArrowRight":{if(I.preventDefault(),b){h(),m();return}f(r+kJe),m();return}case"Home":{I.preventDefault(),h(),f(s),m();return}case"End":{I.preventDefault(),h(),f(a),m();return}}},[b,r,s,a,f,h,m,v]),E=g.useCallback(I=>{const A=I.target.closest("a");!A||!A.hasAttribute("href")||I.button!==0||I.metaKey||I.ctrlKey||I.shiftKey||I.altKey||A.target==="_blank"||A.hasAttribute("download")||d(!1)},[d]);if(c)return o.jsx(CI,{side:"left",open:u,onOpenChange:d,children:o.jsxs(xW,{className:K("w-3/4 max-w-(--sidebar-width-mobile) overflow-hidden rounded-none border-0 bg-surface2 shadow-xl",t),children:[o.jsx(w1,{asChild:!0,children:o.jsx(EI,{children:"Navigation"})}),o.jsx(w1,{asChild:!0,children:o.jsx(i4,{children:"Primary site navigation drawer"})}),o.jsx("div",{onClick:E,className:"flex h-full min-h-0 flex-col overflow-hidden px-4 py-2",children:e})]})});const N=b?l:r;return o.jsxs("div",{className:K("sidebar-layout group/sidebar relative min-h-0 shrink-0 self-stretch","w-(--sidebar-width)","transition-[width] duration-220 ease-[cubic-bezier(0.32,0.72,0,1)]","motion-reduce:transition-none","in-data-[sidebar-gesture=active]:transition-none",t,x&&"border-r-0 border-transparent"),children:[o.jsx("div",{className:K("flex h-full min-h-0 flex-col overflow-hidden","transition-opacity duration-200 motion-reduce:transition-none","px-2",x&&"pointer-events-none px-0 opacity-0"),children:e}),o.jsx("div",{role:"separator","aria-orientation":"vertical","aria-valuenow":b?void 0:N,"aria-valuemin":b?void 0:s,"aria-valuemax":b?void 0:a,"aria-valuetext":b?"collapsed":`${N} pixels`,"aria-label":`Resize sidebar. Arrow keys to resize, Enter to ${b?"expand":"collapse"}.`,tabIndex:0,onPointerDown:_,onClick:C,onKeyDown:T,className:K("group absolute top-0 -right-1 z-10 h-full w-2 cursor-col-resize touch-none","flex items-center justify-center","focus-visible:outline-hidden"),children:o.jsx(VCt,{className:K("group-hover:opacity-100","group-focus-visible:via-accent1 group-focus-visible:opacity-100","in-data-[sidebar-gesture=active]:via-neutral6/45 in-data-[sidebar-gesture=active]:opacity-100")})})]})}function bUt(e){return`${e.url}:${e.name}`}function xUt({link:e,activeCandidates:t,level:n=0,isActive:r}){const s=e.children??[];return o.jsx(gUt,{link:e,isActive:r?.(e,t)??e.isActive,level:n,subItems:s.length>0?o.jsx(nAe,{className:"mt-0.5",children:s.map(a=>o.jsx(xUt,{link:a,activeCandidates:t,level:n+1,isActive:r},bUt(a)))}):null})}function Fos({sections:e,isActive:t,className:n}){const r=g.useId();return o.jsx(o.Fragment,{children:e.map(s=>{const a=s.links.length>0&&s.separator,i=s.title?`${r}-${s.key}`:void 0;return o.jsxs(vUt,{className:n,"aria-labelledby":i,"aria-label":i?void 0:s.key,children:[a?o.jsx(yUt,{}):null,s.title?o.jsx(fUt,{id:i,href:s.href,isActive:s.isHeaderActive,children:s.title}):null,o.jsx(nAe,{children:s.links.map(l=>o.jsx(xUt,{link:l,activeCandidates:s.links,isActive:t},bUt(l)))})]},s.key)})})}function zos({className:e,onClick:t,...n}){const{desktopState:r,toggleSidebar:s}=_C(),a=r==="collapsed";return o.jsxs(yn,{children:[o.jsx(gn,{render:o.jsx("button",{type:"button","aria-label":"Toggle sidebar","aria-expanded":!a,...n,onClick:i=>{t?.(i),i.defaultPrevented||s()},className:K("flex items-center justify-center rounded-md text-neutral3","size-7",a?"mx-auto":"ml-auto","hover:bg-sidebar-nav-hover hover:text-neutral6","duration-normal transition-all ease-out-custom","focus-visible:shadow-focus-ring focus-visible:ring-1 focus-visible:ring-accent1 focus-visible:outline-hidden","[&_svg]:duration-normal [&_svg]:size-4 [&_svg]:text-neutral3 [&_svg]:transition-transform [&:hover_svg]:text-neutral5",e),children:o.jsx(IXt,{className:K({"rotate-180":a})})})}),o.jsx(vn,{children:"Toggle Sidebar"})]})}const OJe="sidebar:state",_Je="sidebar:width",CJe="--sidebar-width",oie=(e,t,n)=>Math.min(n,Math.max(t,e)),Bos=typeof window<"u"?ze.useLayoutEffect:ze.useEffect;function rAe({children:e,defaultState:t="default",defaultWidth:n=240,minWidth:r=200,maxWidth:s=480,collapseBelow:a,collapsedWidth:i=64,disableKeyboardShortcut:l=!0,storageKey:c,mobileBreakpoint:u=1024,mobileWidth:d=360,LinkComponent:f}){const p=Math.max(0,Math.min(r,s)),h=Math.max(p,s),m=Math.max(0,Math.min(i,h)),v=oie(n,p,h),y=a??p,b=c?`${c}:${OJe}`:OJe,x=c?`${c}:${_Je}`:_Je,S=()=>{if(typeof window>"u")return{state:t,width:v};try{let ee=t,re=v;const le=window.localStorage.getItem(b);(le==="collapsed"||le==="default")&&(ee=le);const X=window.localStorage.getItem(x);if(X!==null){const te=Number(X);Number.isFinite(te)&&(re=oie(te,p,h))}return{state:ee,width:re}}catch{return{state:t,width:v}}},k=ze.useRef(null);k.current===null&&(k.current=S());const _=k.current,[C,T]=ze.useState(_.state),[E,N]=ze.useState(_.width),[I,A]=ze.useState(!1),[R,L]=ze.useState(!1),D=ze.useRef(_.width),F=ze.useRef(_.state);F.current=C;const H=ze.useRef(null);ze.useEffect(()=>{if(typeof window>"u")return;const ee=window.matchMedia(`(max-width: ${u-1}px)`),re=()=>A(ee.matches);return re(),ee.addEventListener("change",re),()=>ee.removeEventListener("change",re)},[u]),ze.useEffect(()=>{!I&&R&&L(!1)},[I,R]);const B=ze.useCallback(ee=>{const re=H.current;re&&re.style.setProperty(CJe,`${ee}px`)},[]);Bos(()=>{B(C==="collapsed"?m:D.current)},[C,m,B]);const z=ze.useCallback(ee=>{try{window.localStorage.setItem(b,ee)}catch{}},[b]),V=ze.useCallback(()=>{if(I){L(ee=>!ee);return}T(ee=>{const re=ee==="default"?"collapsed":"default";return F.current=re,z(re),re})},[I,z]),M=ze.useCallback(ee=>{const re=oie(ee,p,h);D.current=re,B(re)},[p,h,B]),G=ze.useCallback(()=>{F.current="collapsed",z("collapsed"),T("collapsed")},[z]),U=ze.useCallback(()=>{F.current="default",z("default"),T("default")},[z]),$=ze.useCallback(()=>{N(D.current);try{window.localStorage.setItem(b,F.current),window.localStorage.setItem(x,String(D.current))}catch{}},[b,x]),q=ze.useCallback(ee=>{const re=H.current;re&&(ee?re.setAttribute("data-sidebar-gesture","active"):re.removeAttribute("data-sidebar-gesture"))},[]);ze.useEffect(()=>{if(l)return;const ee=re=>{if(re.code!=="KeyB"||!(re.metaKey||re.ctrlKey)||re.altKey||re.shiftKey)return;const le=re.target;if(le){const X=le.tagName;if(X==="INPUT"||X==="TEXTAREA"||X==="SELECT"||le.isContentEditable)return}re.preventDefault(),V()};return window.addEventListener("keydown",ee),()=>window.removeEventListener("keydown",ee)},[l,V]);const Z=I?"default":C,Y=ze.useMemo(()=>({state:Z,desktopState:C,width:E,minWidth:p,maxWidth:h,collapseBelow:y,collapsedWidth:m,isMobile:I,toggleSidebar:V,setWidth:M,collapse:G,expand:U,commit:$,setGestureActive:q,LinkComponent:f}),[Z,C,E,p,h,y,m,I,V,M,G,U,$,q,f]),ne=ze.useMemo(()=>({openMobile:R,setOpenMobile:L}),[R]),J={[CJe]:`${_.state==="collapsed"?m:_.width}px`,"--sidebar-width-mobile":`${d}px`,display:"contents"};return o.jsx("div",{ref:H,"data-sidebar-scope":!0,"data-sidebar-state":C,"data-sidebar-mobile":I?"true":"false",style:J,suppressHydrationWarning:!0,children:o.jsx(tAe.Provider,{value:Y,children:o.jsx(dUt.Provider,{value:ne,children:e})})})}const ns=Object.assign(Los,{Bottom:Oos,Nav:Cos,NavSection:vUt,NavLink:gUt,NavLabel:pUt,NavHeader:fUt,NavList:nAe,NavSeparator:yUt,Sections:Fos,Trigger:zos,MobileTrigger:_os}),Uos={purple:{icon:"text-purple-700 dark:text-purple-300"},amber:{icon:"text-amber-700 dark:text-amber-300"},emerald:{icon:"text-emerald-700 dark:text-emerald-300"},sky:{icon:"text-sky-700 dark:text-sky-300"},cyan:{icon:"text-cyan-700 dark:text-cyan-300"},orange:{icon:"text-orange-700 dark:text-orange-300"}},bj=e=>e?Object.keys(e).length:0,kQ=e=>e>0?String(e):"Off",wUt=e=>(e?.inputProcessors?.length??0)+(e?.outputProcessors?.length??0),SUt=e=>!!e?.result,kUt=(e,t)=>!!(t&&e&&e.editor!==!1);function aA({view:e,label:t,status:n,description:r,docsHref:s,enabled:a,tone:i,icon:l}){const c=Uos[i].icon;return e==="chip"?o.jsx("span",{"aria-label":`${t}: ${n}`,className:K("pointer-events-none inline-flex h-5 min-w-5 items-center justify-center rounded-full px-1 text-neutral3",a?c:void 0),children:o.jsx("span",{className:"size-3 shrink-0 [&>svg]:size-3",children:l})}):o.jsxs("a",{"aria-label":`${t}: ${n}`,href:s,target:"_blank",rel:"noopener noreferrer",className:K("group/capability-row flex min-w-0 items-start gap-2 rounded-md px-2 py-1.5 text-ui-xs text-neutral4 transition-colors duration-normal","hover:bg-surface4/60 hover:text-neutral6 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-border2"),children:[o.jsx("span",{className:K("mt-0.5 size-3.5 shrink-0 text-neutral3 transition-colors duration-normal [&>svg]:size-3.5",a?c:"group-hover/capability-row:text-neutral5"),children:l}),o.jsxs("span",{className:"min-w-0 flex-1",children:[o.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[o.jsx("span",{className:"text-neutral5 min-w-0 truncate font-medium",children:t}),o.jsx("span",{className:"text-neutral3 shrink-0 tabular-nums",children:n})]}),o.jsx("span",{className:"text-neutral3 duration-normal group-hover/capability-row:text-neutral4 mt-0.5 block transition-colors",children:r})]}),o.jsx(Yr,{className:"text-neutral3 duration-normal group-hover/capability-row:text-neutral5 mt-0.5 size-3 shrink-0 transition-colors"})]})}function EJe({agentId:e,view:t}){const{data:n,isLoading:r}=yC(e),s=SUt(n),a=s?n?.memoryType==="gateway"?"Gateway":"On":"Off",i=r?"Checking":a;return o.jsx(aA,{view:t,label:"Memory",status:i,description:s?"Conversation history and configured memory features are available for this agent.":"This agent has no memory configured, so conversations are not saved as memory-backed threads.",docsHref:"https://mastra.ai/docs/memory/overview",enabled:s,tone:"purple",icon:o.jsx(RL,{})})}function TJe({agentId:e,view:t}){const{data:n,isLoading:r}=Vl(e),{isCmsAvailable:s,isLoading:a}=hS(),i=kUt(n,s),l=n?.editor===!1,c=vS({agentId:e,params:{orderBy:{field:"createdAt",direction:"DESC"}},enabled:i}),u=c.data?.total??c.data?.versions.length??0,d=r||a||i&&c.isLoading,f=u>0?String(u):"Ready",h=d?"Checking":i?f:l?"Locked":"Off",v=i?"Editor is available for versioned agent overrides.":l?"This code-defined agent explicitly disables editor overrides.":"Register MastraEditor to enable versioned agent overrides.";return o.jsx(aA,{view:t,label:"Editor",status:h,description:v,docsHref:"https://mastra.ai/docs/editor/overview",enabled:i,tone:"amber",icon:o.jsx(um,{})})}function jJe({agentId:e,view:t}){const{data:n,isLoading:r}=Vl(e),s=bj(n?.tools);return o.jsx(aA,{view:t,label:"Tools",status:r?"Checking":kQ(s),description:s>0?`${s} tool${s===1?"":"s"} available.`:"No tools are configured.",docsHref:"https://mastra.ai/docs/agents/using-tools-and-mcp",enabled:s>0,tone:"emerald",icon:o.jsx(Ud,{})})}function NJe({agentId:e,view:t}){const{data:n,isLoading:r}=Vl(e),s=bj(n?.workflows);return o.jsx(aA,{view:t,label:"Workflows",status:r?"Checking":kQ(s),description:s>0?`${s} workflow${s===1?"":"s"} available.`:"No workflows are attached to this agent.",docsHref:"https://mastra.ai/docs/workflows/overview",enabled:s>0,tone:"sky",icon:o.jsx(aI,{})})}function IJe({agentId:e,view:t}){const{data:n,isLoading:r}=Vl(e),s=bj(n?.agents);return o.jsx(aA,{view:t,label:"Sub-agents",status:r?"Checking":kQ(s),description:s>0?`${s} sub-agent${s===1?"":"s"} available.`:"No sub-agents are attached to this agent.",docsHref:"https://mastra.ai/docs/agents/supervisor-agents",enabled:s>0,tone:"cyan",icon:o.jsx(h8,{})})}function AJe({agentId:e,view:t}){const{data:n,isLoading:r}=Vl(e),s=wUt(n);return o.jsx(aA,{view:t,label:"Processors",status:r?"Checking":kQ(s),description:s>0?`${s} input/output processor${s===1?"":"s"} configured.`:"No input or output processors are configured.",docsHref:"https://mastra.ai/docs/agents/processors",enabled:s>0,tone:"orange",icon:o.jsx(g0e,{})})}function qos({agentId:e}){const{data:t}=yC(e),{data:n}=Vl(e),{isCmsAvailable:r}=hS(),s=[SUt(t),kUt(n,r),bj(n?.tools)>0,bj(n?.workflows)>0,bj(n?.agents)>0,wUt(n)>0],a=s.filter(Boolean).length;return o.jsxs(me,{as:"span",variant:"ui-xs",className:"text-neutral3 shrink-0",children:[a,"/",s.length]})}function Vos({agentId:e}){const[t,n]=g.useState(!1);return o.jsx(Fc,{open:t,onOpenChange:n,children:o.jsxs("div",{className:"border-border1/50 shrink-0 border-t",children:[o.jsx(cc,{asChild:!0,"aria-label":t?"Hide capability details":"Show capability details",children:o.jsxs("button",{type:"button","data-testid":"agent-capabilities-footer",className:"text-neutral4 duration-normal hover:!text-neutral4 hover:bg-surface4 focus-visible:!text-neutral4 focus-visible:bg-surface4 focus-visible:ring-border2 active:bg-surface5/80 aria-expanded:bg-surface4/70 data-[panel-open]:bg-surface4/70 flex w-full cursor-pointer items-center gap-1.5 px-2 py-2 text-left transition-colors focus-visible:ring-1 focus-visible:outline-none focus-visible:ring-inset",children:[o.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden",children:[o.jsx(EJe,{agentId:e,view:"chip"}),o.jsx(TJe,{agentId:e,view:"chip"}),o.jsx(jJe,{agentId:e,view:"chip"}),o.jsx(NJe,{agentId:e,view:"chip"}),o.jsx(IJe,{agentId:e,view:"chip"}),o.jsx(AJe,{agentId:e,view:"chip"})]}),o.jsx(qos,{agentId:e}),o.jsx(Ur,{className:K("size-3.5 shrink-0 text-neutral3 transition-transform duration-normal ease-out-custom",t?"rotate-90":void 0)})]})}),o.jsx(uc,{className:"px-2 pb-2",children:o.jsxs("div",{className:"grid gap-1",children:[o.jsx(EJe,{agentId:e,view:"row"}),o.jsx(TJe,{agentId:e,view:"row"}),o.jsx(jJe,{agentId:e,view:"row"}),o.jsx(NJe,{agentId:e,view:"row"}),o.jsx(IJe,{agentId:e,view:"row"}),o.jsx(AJe,{agentId:e,view:"row"})]})})]})})}function Hos(e){let t=e;for(let n=0;n<3&&typeof t=="string";n++)try{const r=JSON.parse(t);if(typeof r=="object"&&r!==null)return r;if(typeof r=="string"&&r!==t){t=r;continue}break}catch{break}return t}function Wos(e){return typeof e=="object"&&e!==null&&"parts"in e&&Array.isArray(e.parts)}function Zos(e){const t=e.type;return t==="data-om-status"||t==="data-om-observation-start"||t==="data-om-observation-end"||t==="data-om-buffering-start"||t==="data-om-buffering-end"||t==="data-om-activation"}function Gos(e,t){switch(e.type){case"data-om-status":return{type:"status",timestamp:t,pendingTokens:e.data.windows?.active?.messages?.tokens,observationTokens:e.data.windows?.active?.observations?.tokens,observationThreshold:e.data.windows?.active?.messages?.threshold,reflectionThreshold:e.data.windows?.active?.observations?.threshold};case"data-om-observation-start":return{type:"observation-start",timestamp:e.data.startedAt,pendingTokens:e.data.tokensToObserve,observationThreshold:e.data.config?.messageTokens,reflectionThreshold:e.data.config?.observationTokens};case"data-om-observation-end":return{type:"observation-end",timestamp:e.data.completedAt,observationTokens:e.data.observationTokens};case"data-om-buffering-start":return{type:"buffering-start",timestamp:e.data.startedAt,pendingTokens:e.data.tokensToBuffer,observationThreshold:e.data.config?.messageTokens,reflectionThreshold:e.data.config?.observationTokens};case"data-om-buffering-end":return{type:"buffering-end",timestamp:e.data.completedAt,observationTokens:e.data.bufferedTokens};case"data-om-activation":return{type:"activation",timestamp:e.data.activatedAt,pendingTokens:e.data.tokensActivated,observationTokens:e.data.observationTokens,observationThreshold:e.data.config?.messageTokens,reflectionThreshold:e.data.config?.observationTokens,generationCount:e.data.generationCount}}}function Qos(e){const t=[];for(const n of e){const r=Hos(n.content);if(Wos(r))for(const s of r.parts)Zos(s)&&t.push(Gos(s,new Date(n.createdAt).toISOString()))}return t.sort((n,r)=>n.timestamp.localeCompare(r.timestamp)),t}function BN(e){return/[Zz+-]\d{0,4}$/.test(e.trim())?new Date(e).getTime():new Date(e.trim().replace(" ","T")+"Z").getTime()}function Yos(e){if(e.length===0)return{tMin:0,tMax:1};let t=1/0,n=-1/0;for(const r of e){const s=BN(r);s<t&&(t=s),s>n&&(n=s)}return t===n?{tMin:t,tMax:t+1}:{tMin:t,tMax:n}}function $L(e,t){return(BN(e)-t.tMin)/(t.tMax-t.tMin)}function sAe(e,t){return new Date(t.tMin+e*(t.tMax-t.tMin))}function OUt(e){const t=String(e.getUTCDate()).padStart(2,"0"),n=String(e.getUTCMonth()+1).padStart(2,"0"),r=String(e.getUTCHours()).padStart(2,"0"),s=String(e.getUTCMinutes()).padStart(2,"0"),a=String(e.getUTCSeconds()).padStart(2,"0");return`${t}/${n} ${r}:${s}:${a}`}function Kos(e,t){return sAe(e,t).getTime()}function _Ut(e){const t=e.lastObservedAt??e.updatedAt;return typeof t=="string"?t:new Date(t).toISOString()}function Xos(e){return BN(_Ut(e))}function Jos(e,t){if(t==null)return null;const r=e.map(s=>({id:s.id,t:BN(_Ut(s))})).toSorted((s,a)=>s.t-a.t).findLast(s=>s.t<=t);return r?r.id:null}function RJe(e){const t=e.lastObservedAt??e.updatedAt;return typeof t=="string"?t:new Date(t).toISOString()}function els(e){return[...e].sort((t,n)=>BN(RJe(t))-BN(RJe(n)))}function tls({markers:e,omRecords:t,observationThreshold:n,reflectionThreshold:r}){const s=[...e].filter(i=>i.type==="status"&&(i.pendingTokens!=null||i.observationTokens!=null)).sort((i,l)=>i.timestamp.localeCompare(l.timestamp)).at(-1),a=els(t).at(-1);return{messageTokens:s?.pendingTokens??a?.pendingMessageTokens,messageThreshold:s?.observationThreshold??n,memoryTokens:s?.observationTokens??a?.observationTokenCount,memoryThreshold:s?.reflectionThreshold??r}}function r2(e){const t=e.lastObservedAt??e.updatedAt;return typeof t=="string"?t:new Date(t).toISOString()}function nls(e,t,n){const r=e.map(a=>({ts:String(r2(a)),pendingMessageTokens:a.pendingMessageTokens})),s=t.flatMap(a=>a.pendingTokens==null?[]:{ts:a.timestamp,pendingMessageTokens:a.pendingTokens});return[...r,...s].sort((a,i)=>a.ts.localeCompare(i.ts)).map(a=>({t:$L(a.ts,n),pendingMessageTokens:a.pendingMessageTokens}))}function rls(e,t,n){const r=[...e.map(a=>({ts:String(r2(a)),observationTokenCount:a.observationTokenCount})),...t.flatMap(a=>a.type!=="status"||a.observationTokens==null?[]:{ts:a.timestamp,observationTokenCount:a.observationTokens})].sort((a,i)=>a.ts.localeCompare(i.ts));let s=0;return r.map(a=>(s=Math.max(s,a.observationTokenCount),{t:$L(a.ts,n),observationTokenCount:s}))}function sls(e,t){const n=e.flatMap(s=>s.observationTokens==null||s.type!=="buffering-end"&&s.type!=="activation"?[]:{ts:s.timestamp,bufferedObservationTokenCount:s.type==="activation"?-s.observationTokens:s.observationTokens}).sort((s,a)=>s.ts.localeCompare(a.ts));let r=0;return n.map(s=>(r=Math.max(0,r+s.bufferedObservationTokenCount),{t:$L(s.ts,t),bufferedObservationTokenCount:r}))}function als(e,t){return[...e].sort((n,r)=>String(r2(n)).localeCompare(String(r2(r)))).map(n=>({t:$L(String(r2(n)),t),event:1}))}function ils(e,t){return[...e].sort((n,r)=>new Date(n.createdAt).getTime()-new Date(r.createdAt).getTime()).map(n=>({t:$L(new Date(n.createdAt).toISOString(),t),event:1,role:n.role}))}function ols(e,t,n){const r=new Map;for(const c of e)c.t!==void 0&&r.set(c.t,Number(c[t]??0));const s=n.reduce((c,u)=>{const d=c.get(u.t);return d?d.push(u):c.set(u.t,[u]),c},new Map),a=Array.from(new Set([...r.keys(),...s.keys()])).sort((c,u)=>c-u);let i=0;const l=[];for(const c of a){const u=r.get(c);u!=null&&(i=u);const d=s.get(c);if(d)for(const f of d)l.push({...f,t:c,[t]:i});else l.push({t:c,[t]:i})}return l}function lls(e,t,n){if(n==null)return;const r=Math.max(0,...e.map(s=>Number(s[t])||0));return Math.max(r,n)}function cls(e){return e==null?null:Number(e)}function uls(e){return!!e?.event}const dls="var(--color-green-500, #22c55e)",fls="#f59e0b",PJe="#ec4899";function pls({domain:e}){const t=[0,.25,.5,.75,1];return o.jsxs("div",{className:"grid grid-cols-[6rem_1fr] items-center",children:[o.jsx("p",{className:"text-icon3 border-border1/50 text-ui-xs flex items-center self-stretch border-r pl-3 font-medium",children:"Time"}),o.jsx("div",{className:"text-icon3 text-ui-xs flex justify-between px-1 py-1.5 font-mono",children:t.map(n=>o.jsx("span",{children:OUt(sAe(n,e))},n))})]})}function aAe({active:e,payload:t,domain:n,showValue:r}){if(!e||!t?.length)return null;const s=t[0]?.payload?.t,a=n!=null&&s!=null?OUt(sAe(s,n)):null,i=t.filter(l=>l.name!=="t"&&l.name!=="time"&&l.value!=null);return r?o.jsxs("div",{className:"border-border1 bg-surface3 text-ui-xs flex flex-col gap-0.5 rounded border px-2 py-1.5 font-mono shadow",children:[a&&o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx("span",{className:"text-icon3",children:"time"}),o.jsx("span",{className:"text-neutral6",children:a})]}),i.map(l=>o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx("span",{className:"text-icon3",children:l.name}),o.jsx("span",{className:"text-neutral6",children:typeof l.value=="number"?Math.round(l.value).toLocaleString():String(l.value)})]},l.name))]}):o.jsx("div",{className:"border-border1 bg-surface3 text-ui-xs rounded border px-2 py-1 font-mono shadow",children:a&&o.jsx("span",{className:"text-neutral6",children:a})})}function hls({label:e,data:t,dataKey:n,color:r,gradientId:s,domain:a,zoomDomain:i,threshold:l}){const c=lls(t,n,l);return o.jsxs("div",{className:"border-border1/50 relative grid grid-cols-[6rem_1fr] items-center border-b hover:z-10",children:[o.jsx("p",{className:"text-icon3 border-border1/50 text-ui-xs flex items-center self-stretch border-r pl-3 font-medium",children:e}),o.jsx("div",{children:o.jsx(h4,{width:"100%",height:32,children:o.jsxs(A_r,{data:t,margin:{top:0,right:0,bottom:0,left:0},children:[o.jsx("defs",{children:o.jsxs("linearGradient",{id:s,x1:"0",y1:"0",x2:"0",y2:"1",children:[o.jsx("stop",{offset:"0%",stopColor:r,stopOpacity:.35}),o.jsx("stop",{offset:"100%",stopColor:r,stopOpacity:.03})]})}),o.jsx(E4,{dataKey:"t",type:"number",domain:i,allowDataOverflow:!0,hide:!0}),o.jsx(T4,{type:"number",domain:c!=null?[0,c]:void 0,hide:!0}),o.jsx(xZ,{content:o.jsx(aAe,{domain:a,showValue:!0}),cursor:{stroke:"rgba(255,255,255,0.08)"}}),o.jsx(cEe,{type:"linear",dataKey:n,stroke:r,strokeWidth:1,strokeOpacity:.6,fill:`url(#${s})`,isAnimationActive:!1}),l!=null&&o.jsx(nEe,{y:l,stroke:r,strokeDasharray:"4 3",strokeOpacity:.4})]})})})]})}function mls({label:e,data:t,color:n,height:r=32,domain:s,zoomDomain:a}){return o.jsxs("div",{className:"border-border1/50 relative grid grid-cols-[6rem_1fr] items-center border-b hover:z-10",children:[o.jsx("p",{className:"text-icon3 border-border1/50 text-ui-xs flex items-center self-stretch border-r pl-3 font-medium",children:e}),o.jsx("div",{children:o.jsx(h4,{width:"100%",height:r,children:o.jsxs(N_r,{margin:{top:0,right:0,bottom:0,left:0},children:[o.jsx(E4,{dataKey:"t",type:"number",domain:a,allowDataOverflow:!0,hide:!0}),o.jsx(T4,{dataKey:"event",type:"number",domain:[0,2],hide:!0}),o.jsx(xZ,{content:o.jsx(aAe,{domain:s}),cursor:!1}),o.jsx(lRt,{data:t,fill:n,isAnimationActive:!1,shape:i=>{const l=i.cx;return o.jsxs("g",{children:[o.jsx("rect",{x:l-6,y:0,width:12,height:r,fill:"transparent"}),o.jsx("rect",{x:l-1.5,y:0,width:3,height:r,fill:n})]})}})]})})})]})}function $Je({label:e,areaData:t,areaDataKey:n,eventData:r,color:s,gradientId:a,domain:i,zoomDomain:l,threshold:c,height:u=44,onSelectT:d}){const f=ols(t,n,r);return o.jsxs("div",{className:"border-border1/50 relative grid grid-cols-[6rem_1fr] items-center border-b hover:z-10",children:[o.jsx("p",{className:"text-icon3 border-border1/50 text-ui-xs flex items-center self-stretch border-r pl-3 font-medium",children:e}),o.jsx("div",{children:o.jsx(h4,{width:"100%",height:u,children:o.jsxs(P_r,{margin:{top:0,right:0,bottom:0,left:0},onClick:p=>{const h=cls(p?.activeLabel);h!=null&&d&&d(h)},className:d?"cursor-pointer":void 0,children:[o.jsx("defs",{children:o.jsxs("linearGradient",{id:a,x1:"0",y1:"0",x2:"0",y2:"1",children:[o.jsx("stop",{offset:"0%",stopColor:s,stopOpacity:.35}),o.jsx("stop",{offset:"100%",stopColor:s,stopOpacity:.06})]})}),o.jsx(E4,{dataKey:"t",type:"number",domain:l,allowDataOverflow:!0,hide:!0}),o.jsx(T4,{yAxisId:"area",dataKey:n,type:"number",hide:!0,domain:[0,"dataMax"]}),o.jsx(xZ,{content:o.jsx(aAe,{domain:i,showValue:!0}),cursor:!1}),o.jsx(cEe,{yAxisId:"area",data:f,type:"linear",dataKey:n,stroke:s,strokeWidth:1,strokeOpacity:.6,fill:`url(#${a})`,isAnimationActive:!1,activeDot:{r:5,stroke:s,strokeWidth:2,fill:"#0a0a0a"},dot:p=>uls(p.payload)?o.jsx("circle",{cx:p.cx,cy:p.cy,r:4,fill:s}):o.jsx(o.Fragment,{})}),c!=null&&o.jsx(nEe,{yAxisId:"area",y:c,stroke:s,strokeDasharray:"4 3",strokeOpacity:.4})]})})})]})}function gls({tDomain:e,zoomLeft:t,zoomRight:n,onZoomLeftChange:r,onZoomRightChange:s,onReset:a}){const i=g.useRef(null),l=g.useRef(null),c=e.tMax-e.tMin,u=c>0?(t-e.tMin)/c*100:0,d=c>0?(n-e.tMin)/c*100:100,f=g.useCallback(p=>{const h=i.current;if(!h)return null;const m=h.getBoundingClientRect(),v=Math.max(0,Math.min(1,(p-m.left)/m.width));return e.tMin+v*(e.tMax-e.tMin)},[e.tMin,e.tMax]);return g.useEffect(()=>{const p=m=>{if(!l.current)return;const v=f(m.clientX);v!=null&&(l.current==="left"?r(Math.min(v,n)):s(Math.max(v,t)))},h=()=>{l.current=null};return window.addEventListener("mousemove",p),window.addEventListener("mouseup",h),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",h)}},[f,t,n,r,s]),o.jsxs("div",{className:"border-border1/50 grid grid-cols-[6rem_1fr] items-center border-b",children:[o.jsxs("div",{className:"border-border1/50 flex items-center gap-1 self-stretch border-r pl-3",children:[o.jsx("p",{className:"text-icon3 text-ui-xs font-medium",children:"Zoom"}),o.jsx(oe,{variant:"ghost",size:"icon-sm","aria-label":"Reset zoom",onClick:a,children:o.jsx(f0e,{className:"size-3"})})]}),o.jsxs("div",{ref:i,"data-zoom-track":"",className:"relative h-6 cursor-pointer select-none",onMouseDown:p=>{const h=f(p.clientX);if(h==null)return;p.preventDefault();const m=Math.abs(h-t),v=Math.abs(h-n);m<=v?(r(Math.min(h,n)),l.current="left"):(s(Math.max(h,t)),l.current="right")},children:[o.jsx("div",{"data-zoom-part":"before",className:"bg-surface2/60 absolute inset-y-0 left-0",style:{width:`${u}%`}}),o.jsx("div",{"data-zoom-part":"band",className:"border-border1/30 bg-neutral6/5 absolute inset-y-0 border-y",style:{left:`${u}%`,right:`${100-d}%`}}),o.jsx("div",{"data-zoom-part":"after",className:"bg-surface2/60 absolute inset-y-0 right-0",style:{width:`${100-d}%`}}),o.jsx("div",{"data-zoom-handle":"left",className:"bg-neutral6/50 hover:bg-neutral6 absolute inset-y-0 w-1 cursor-col-resize",style:{left:`${u}%`,transform:"translateX(-50%)"},onMouseDown:p=>{p.preventDefault(),p.stopPropagation(),l.current="left"}}),o.jsx("div",{"data-zoom-handle":"right",className:"bg-neutral6/50 hover:bg-neutral6 absolute inset-y-0 w-1 cursor-col-resize",style:{left:`${d}%`,transform:"translateX(-50%)"},onMouseDown:p=>{p.preventDefault(),p.stopPropagation(),l.current="right"}})]})]})}const vls={tMin:0,tMax:1};function yls({omRecords:e,markers:t,messages:n,tDomain:r,observationThreshold:s,reflectionThreshold:a,onSelectTimestamp:i,zoomRange:l,onZoomRangeChange:c}){const u=r??vls,d=g.useCallback(F=>{i?.(Kos(F,u))},[i,u]),f=l!=null&&c!=null,[p,h]=g.useState(u.tMin),[m,v]=g.useState(u.tMax);g.useEffect(()=>{f||(h(u.tMin),v(u.tMax))},[u.tMin,u.tMax,f]);const y=f?l.left:p,b=f?l.right:m,x=g.useCallback(F=>{f?c({left:F,right:b}):h(F)},[f,c,b]),S=g.useCallback(F=>{f?c({left:y,right:F}):v(F)},[f,c,y]),k=g.useCallback(()=>{f?c({left:u.tMin,right:u.tMax}):(h(u.tMin),v(u.tMax))},[f,c,u.tMin,u.tMax]),_=u.tMax-u.tMin,C=_>0?(y-u.tMin)/_:0,T=_>0?(b-u.tMin)/_:1,E=[C,T],N=g.useMemo(()=>ils(n,u),[n,u]),I=g.useMemo(()=>nls(e,t,u),[e,t,u]),A=g.useMemo(()=>rls(e,t,u),[e,t,u]),R=g.useMemo(()=>sls(t,u),[t,u]),L=g.useMemo(()=>als(e,u),[e,u]);return N.length>0||I.length>0||A.length>0||L.length>0?o.jsxs("div",{className:"flex flex-col pr-2 pb-2 [&_.recharts-surface]:outline-none",children:[o.jsx($Je,{label:"Messages",areaData:I,areaDataKey:"pendingMessageTokens",eventData:N,color:dls,gradientId:"grad-messages",domain:u,zoomDomain:E,threshold:s,onSelectT:i?d:void 0}),o.jsx($Je,{label:"Observations",areaData:A,areaDataKey:"observationTokenCount",eventData:L,color:fls,gradientId:"grad-observations",domain:u,zoomDomain:E,threshold:a,onSelectT:i?d:void 0}),R.length>0&&o.jsx(hls,{label:"Buffered obs",data:R,dataKey:"bufferedObservationTokenCount",color:PJe,gradientId:"grad-buffered-obs",domain:u,zoomDomain:E,threshold:a}),L.length>0&&o.jsx(mls,{label:"Events",data:L,color:PJe,domain:u,zoomDomain:E}),o.jsx(pls,{domain:u}),o.jsx(gls,{tDomain:u,zoomLeft:y,zoomRight:b,onZoomLeftChange:x,onZoomRightChange:S,onReset:k})]}):null}class Tl{constructor(t,n,r,s){this.fromA=t,this.toA=n,this.fromB=r,this.toB=s}offset(t,n=t){return new Tl(this.fromA+t,this.toA+t,this.fromB+n,this.toB+n)}}function S_(e,t,n,r,s,a){if(e==r)return[];let i=oAe(e,t,n,r,s,a),l=lAe(e,t+i,n,r,s+i,a);t+=i,n-=l,s+=i,a-=l;let c=n-t,u=a-s;if(!c||!u)return[new Tl(t,n,s,a)];if(c>u){let f=e.slice(t,n).indexOf(r.slice(s,a));if(f>-1)return[new Tl(t,t+f,s,s),new Tl(t+f+u,n,a,a)]}else if(u>c){let f=r.slice(s,a).indexOf(e.slice(t,n));if(f>-1)return[new Tl(t,t,s,s+f),new Tl(n,n,s+f+c,a)]}if(c==1||u==1)return[new Tl(t,n,s,a)];let d=TUt(e,t,n,r,s,a);if(d){let[f,p,h]=d;return S_(e,t,f,r,s,p).concat(S_(e,f+h,n,r,p+h,a))}return bls(e,t,n,r,s,a)}let c$=1e9,u$=0,iAe=!1;function bls(e,t,n,r,s,a){let i=n-t,l=a-s;if(c$<1e9&&Math.min(i,l)>c$*16||u$>0&&Date.now()>u$)return Math.min(i,l)>c$*64?[new Tl(t,n,s,a)]:MJe(e,t,n,r,s,a);let c=Math.ceil((i+l)/2);lie.reset(c),cie.reset(c);let u=(h,m)=>e.charCodeAt(t+h)==r.charCodeAt(s+m),d=(h,m)=>e.charCodeAt(n-h-1)==r.charCodeAt(a-m-1),f=(i-l)%2!=0?cie:null,p=f?null:lie;for(let h=0;h<c;h++){if(h>c$||u$>0&&!(h&63)&&Date.now()>u$)return MJe(e,t,n,r,s,a);let m=lie.advance(h,i,l,c,f,!1,u)||cie.advance(h,i,l,c,p,!0,d);if(m)return xls(e,t,n,t+m[0],r,s,a,s+m[1])}return[new Tl(t,n,s,a)]}class CUt{constructor(){this.vec=[]}reset(t){this.len=t<<1;for(let n=0;n<this.len;n++)this.vec[n]=-1;this.vec[t+1]=0,this.start=this.end=0}advance(t,n,r,s,a,i,l){for(let c=-t+this.start;c<=t-this.end;c+=2){let u=s+c,d=c==-t||c!=t&&this.vec[u-1]<this.vec[u+1]?this.vec[u+1]:this.vec[u-1]+1,f=d-c;for(;d<n&&f<r&&l(d,f);)d++,f++;if(this.vec[u]=d,d>n)this.end+=2;else if(f>r)this.start+=2;else if(a){let p=s+(n-r)-c;if(p>=0&&p<this.len&&a.vec[p]!=-1)if(i){let h=a.vec[p];if(h>=n-d)return[h,s+h-p]}else{let h=n-a.vec[p];if(d>=h)return[d,f]}}}return null}}const lie=new CUt,cie=new CUt;function xls(e,t,n,r,s,a,i,l){let c=!1;return!UN(e,r)&&++r==n&&(c=!0),!UN(s,l)&&++l==i&&(c=!0),c?[new Tl(t,n,a,i)]:S_(e,t,r,s,a,l).concat(S_(e,r,n,s,l,i))}function EUt(e,t){let n=1,r=Math.min(e,t);for(;n<r;)n=n<<1;return n}function oAe(e,t,n,r,s,a){if(t==n||t==a||e.charCodeAt(t)!=r.charCodeAt(s))return 0;let i=EUt(n-t,a-s);for(let l=t,c=s;;){let u=l+i,d=c+i;if(u>n||d>a||e.slice(l,u)!=r.slice(c,d)){if(i==1)return l-t-(UN(e,l)?0:1);i=i>>1}else{if(u==n||d==a)return u-t;l=u,c=d}}}function lAe(e,t,n,r,s,a){if(t==n||s==a||e.charCodeAt(n-1)!=r.charCodeAt(a-1))return 0;let i=EUt(n-t,a-s);for(let l=n,c=a;;){let u=l-i,d=c-i;if(u<t||d<s||e.slice(u,l)!=r.slice(d,c)){if(i==1)return n-l-(UN(e,l)?0:1);i=i>>1}else{if(u==t||d==s)return n-u;l=u,c=d}}}function Nxe(e,t,n,r,s,a,i,l){let c=r.slice(s,a),u=null;for(;;){if(u||i<l)return u;for(let d=t+i;;){UN(e,d)||d++;let f=d+i;if(UN(e,f)||(f+=f==d+1?1:-1),f>=n)break;let p=e.slice(d,f),h=-1;for(;(h=c.indexOf(p,h+1))!=-1;){let m=oAe(e,f,n,r,s+h+p.length,a),v=lAe(e,t,d,r,s,s+h),y=p.length+m+v;(!u||u[2]<y)&&(u=[d-v,s+h-v,y])}d=f}if(l<0)return u;i=i>>1}}function TUt(e,t,n,r,s,a){let i=n-t,l=a-s;if(i<l){let c=TUt(r,s,a,e,t,n);return c&&[c[1],c[0],c[2]]}return i<4||l*2<i?null:Nxe(e,t,n,r,s,a,Math.floor(i/4),-1)}function MJe(e,t,n,r,s,a){iAe=!0;let i=n-t,l=a-s,c;if(i<l){let p=Nxe(r,s,a,e,t,n,Math.floor(i/6),50);c=p&&[p[1],p[0],p[2]]}else c=Nxe(e,t,n,r,s,a,Math.floor(l/6),50);if(!c)return[new Tl(t,n,s,a)];let[u,d,f]=c;return S_(e,t,u,r,s,d).concat(S_(e,u+f,n,r,d+f,a))}function jUt(e,t){for(let n=1;n<e.length;n++){let r=e[n-1],s=e[n];r.toA>s.fromA-t&&r.toB>s.fromB-t&&(e[n-1]=new Tl(r.fromA,s.toA,r.fromB,s.toB),e.splice(n--,1))}}function wls(e,t,n){for(;;){jUt(n,1);let r=!1;for(let s=0;s<n.length;s++){let a=n[s],i,l;(i=oAe(e,a.fromA,a.toA,t,a.fromB,a.toB))&&(a=n[s]=new Tl(a.fromA+i,a.toA,a.fromB+i,a.toB)),(l=lAe(e,a.fromA,a.toA,t,a.fromB,a.toB))&&(a=n[s]=new Tl(a.fromA,a.toA-l,a.fromB,a.toB-l));let c=a.toA-a.fromA,u=a.toB-a.fromB;if(c&&u)continue;let d=a.fromA-(s?n[s-1].toA:0),f=(s<n.length-1?n[s+1].fromA:e.length)-a.toA;if(!d||!f)continue;let p=c?e.slice(a.fromA,a.toA):t.slice(a.fromB,a.toB);d<=p.length&&e.slice(a.fromA-d,a.fromA)==p.slice(p.length-d)?(n[s]=new Tl(a.fromA-d,a.toA-d,a.fromB-d,a.toB-d),r=!0):f<=p.length&&e.slice(a.toA,a.toA+f)==p.slice(0,f)&&(n[s]=new Tl(a.fromA+f,a.toA+f,a.fromB+f,a.toB+f),r=!0)}if(!r)break}return n}function Sls(e,t,n){for(let r=0,s=0;s<e.length;s++){let a=e[s],i=a.toA-a.fromA,l=a.toB-a.fromB;if(i&&l||i>3||l>3){let c=s==e.length-1?t.length:e[s+1].fromA,u=a.fromA-r,d=c-a.toA,f=LJe(t,a.fromA,u),p=DJe(t,a.toA,d),h=a.fromA-f,m=p-a.toA;if((!i||!l)&&h&&m){let v=Math.max(i,l),[y,b,x]=i?[t,a.fromA,a.toA]:[n,a.fromB,a.toB];v>h&&t.slice(f,a.fromA)==y.slice(x-h,x)?(a=e[s]=new Tl(f,f+i,a.fromB-h,a.toB-h),f=a.fromA,p=DJe(t,a.toA,c-a.toA)):v>m&&t.slice(a.toA,p)==y.slice(b,b+m)&&(a=e[s]=new Tl(p-i,p,a.fromB+m,a.toB+m),p=a.toA,f=LJe(t,a.fromA,a.fromA-r)),h=a.fromA-f,m=p-a.toA}if(h||m)a=e[s]=new Tl(a.fromA-h,a.toA+m,a.fromB-h,a.toB+m);else if(i){if(!l){let v=zJe(t,a.fromA,a.toA),y,b=v<0?-1:FJe(t,a.toA,a.fromA);v>-1&&(y=v-a.fromA)<=d&&t.slice(a.fromA,v)==t.slice(a.toA,a.toA+y)?a=e[s]=a.offset(y):b>-1&&(y=a.toA-b)<=u&&t.slice(a.fromA-y,a.fromA)==t.slice(b,a.toA)&&(a=e[s]=a.offset(-y))}}else{let v=zJe(n,a.fromB,a.toB),y,b=v<0?-1:FJe(n,a.toB,a.fromB);v>-1&&(y=v-a.fromB)<=d&&n.slice(a.fromB,v)==n.slice(a.toB,a.toB+y)?a=e[s]=a.offset(y):b>-1&&(y=a.toB-b)<=u&&n.slice(a.fromB-y,a.fromB)==n.slice(b,a.toB)&&(a=e[s]=a.offset(-y))}}r=a.toA}return jUt(e,3),e}let pO;try{pO=new RegExp("[\\p{Alphabetic}\\p{Number}]","u")}catch{}function NUt(e){return e>48&&e<58||e>64&&e<91||e>96&&e<123}function IUt(e,t){if(t==e.length)return 0;let n=e.charCodeAt(t);return n<192?NUt(n)?1:0:pO?!PUt(n)||t==e.length-1?pO.test(String.fromCharCode(n))?1:0:pO.test(e.slice(t,t+2))?2:0:0}function AUt(e,t){if(!t)return 0;let n=e.charCodeAt(t-1);return n<192?NUt(n)?1:0:pO?!$Ut(n)||t==1?pO.test(String.fromCharCode(n))?1:0:pO.test(e.slice(t-2,t))?2:0:0}const RUt=8;function DJe(e,t,n){if(t==e.length||!AUt(e,t))return t;for(let r=t,s=t+n,a=0;a<RUt;a++){let i=IUt(e,r);if(!i||r+i>s)return r;r+=i}return t}function LJe(e,t,n){if(!t||!IUt(e,t))return t;for(let r=t,s=t-n,a=0;a<RUt;a++){let i=AUt(e,r);if(!i||r-i<s)return r;r-=i}return t}function FJe(e,t,n){for(;t!=n;t--)if(e.charCodeAt(t-1)==10)return t;return-1}function zJe(e,t,n){for(;t!=n;t++)if(e.charCodeAt(t)==10)return t;return-1}const PUt=e=>e>=55296&&e<=56319,$Ut=e=>e>=56320&&e<=57343;function UN(e,t){return!t||t==e.length||!PUt(e.charCodeAt(t-1))||!$Ut(e.charCodeAt(t))}function kls(e,t,n){var r;let s=n?.override;return s?s(e,t):(c$=((r=n?.scanLimit)!==null&&r!==void 0?r:1e9)>>1,u$=n?.timeout?Date.now()+n.timeout:0,iAe=!1,wls(e,t,S_(e,0,e.length,t,0,t.length)))}function MUt(){return!iAe}function DUt(e,t,n){return Sls(kls(e,t,n),e,t)}const Sg=wn.define({combine:e=>e[0]}),Ixe=dr.define(),Ols=wn.define(),yx=vl.define({create(e){return null},update(e,t){for(let n of t.effects)n.is(Ixe)&&(e=n.value);for(let n of t.state.facet(Ols))e=n(e,t);return e}});class xj{constructor(t,n,r,s,a,i=!0){this.changes=t,this.fromA=n,this.toA=r,this.fromB=s,this.toB=a,this.precise=i}offset(t,n){return t||n?new xj(this.changes,this.fromA+t,this.toA+t,this.fromB+n,this.toB+n,this.precise):this}get endA(){return Math.max(this.fromA,this.toA-1)}get endB(){return Math.max(this.fromB,this.toB-1)}static build(t,n,r){let s=DUt(t.toString(),n.toString(),r);return LUt(s,t,n,0,0,MUt())}static updateA(t,n,r,s,a){return HJe(VJe(t,s,!0,r.length),t,n,r,a)}static updateB(t,n,r,s,a){return HJe(VJe(t,s,!1,n.length),t,n,r,a)}}function BJe(e,t,n,r){let s=n.lineAt(e),a=r.lineAt(t);return s.to==e&&a.to==t&&e<n.length&&t<r.length?[e+1,t+1]:[s.from,a.from]}function UJe(e,t,n,r){let s=n.lineAt(e),a=r.lineAt(t);return s.from==e&&a.from==t?[e,t]:[s.to+1,a.to+1]}function LUt(e,t,n,r,s,a){let i=[];for(let l=0;l<e.length;l++){let c=e[l],[u,d]=BJe(c.fromA+r,c.fromB+s,t,n),[f,p]=UJe(c.toA+r,c.toB+s,t,n),h=[c.offset(-u+r,-d+s)];for(;l<e.length-1;){let m=e[l+1],[v,y]=BJe(m.fromA+r,m.fromB+s,t,n);if(v>f+1&&y>p+1)break;h.push(m.offset(-u+r,-d+s)),[f,p]=UJe(m.toA+r,m.toB+s,t,n),l++}i.push(new xj(h,u,Math.max(u,f),d,Math.max(d,p),a))}return i}const Dz=1e3;function qJe(e,t,n,r){let s=0,a=e.length;for(;;){if(s==a){let d=0,f=0;s&&({toA:d,toB:f}=e[s-1]);let p=t-(n?d:f);return[d+p,f+p]}let i=s+a>>1,l=e[i],[c,u]=n?[l.fromA,l.toA]:[l.fromB,l.toB];if(c>t)a=i;else if(u<=t)s=i+1;else return r?[l.fromA,l.fromB]:[l.toA,l.toB]}}function VJe(e,t,n,r){let s=[];return t.iterChangedRanges((a,i,l,c)=>{let u=0,d=n?t.length:r,f=0,p=n?r:t.length;a>Dz&&([u,f]=qJe(e,a-Dz,n,!0)),i<t.length-Dz&&([d,p]=qJe(e,i+Dz,n,!1));let h=c-l-(i-a),m,[v,y]=n?[h,0]:[0,h];s.length&&(m=s[s.length-1]).toA>=u?s[s.length-1]={fromA:m.fromA,fromB:m.fromB,toA:d,toB:p,diffA:m.diffA+v,diffB:m.diffB+y}:s.push({fromA:u,toA:d,fromB:f,toB:p,diffA:v,diffB:y})}),s}function HJe(e,t,n,r,s){if(!e.length)return t;let a=[];for(let i=0,l=0,c=0,u=0;;i++){let d=i==e.length?null:e[i],f=d?d.fromA+l:n.length,p=d?d.fromB+c:r.length;for(;u<t.length;){let y=t[u];if(d&&(y.toA+l>f||y.toB+c>p))break;a.push(y.offset(l,c)),u++}if(!d)break;let h=d.toA+l+d.diffA,m=d.toB+c+d.diffB,v=DUt(n.sliceString(f,h),r.sliceString(p,m),s);for(let y of LUt(v,n,r,f,p,MUt()))a.push(y);for(l+=d.diffA,c+=d.diffB;u<t.length;){let y=t[u];if(y.fromA+l>h&&y.fromB+c>m)break;u++}}return a}const _ls={scanLimit:500},FUt=ko.fromClass(class{constructor(e){({deco:this.deco,gutter:this.gutter}=GJe(e))}update(e){(e.docChanged||e.viewportChanged||Cls(e.startState,e.state)||Els(e.startState,e.state))&&({deco:this.deco,gutter:this.gutter}=GJe(e.view))}},{decorations:e=>e.deco}),Lz=th.low(Zwt({class:"cm-changeGutter",markers:e=>{var t;return((t=e.plugin(FUt))===null||t===void 0?void 0:t.gutter)||Os.empty}}));function Cls(e,t){return e.field(yx,!1)!=t.field(yx,!1)}function Els(e,t){return e.facet(Sg)!=t.facet(Sg)}const WJe=Tn.line({class:"cm-changedLine"}),Tls=Tn.mark({class:"cm-changedText"}),jls=Tn.mark({tagName:"ins",class:"cm-insertedLine"}),Nls=Tn.mark({tagName:"del",class:"cm-deletedLine"}),ZJe=new class extends Sy{constructor(){super(...arguments),this.elementClass="cm-changedLineGutter"}};function Ils(e,t,n,r,s,a){let i=n?e.fromA:e.fromB,l=n?e.toA:e.toB,c=0;if(i!=l){s.add(i,i,WJe),s.add(i,l,n?Nls:jls),a&&a.add(i,i,ZJe);for(let u=t.iterRange(i,l-1),d=i;!u.next().done;){if(u.lineBreak){d++,s.add(d,d,WJe),a&&a.add(d,d,ZJe);continue}let f=d+u.value.length;if(r)for(;c<e.changes.length;){let p=e.changes[c],h=i+(n?p.fromA:p.fromB),m=i+(n?p.toA:p.toB),v=Math.max(d,h),y=Math.min(f,m);if(v<y&&s.add(v,y,Tls),m<f)c++;else break}d=f}}}function GJe(e){let t=e.state.field(yx),{side:n,highlightChanges:r,markGutter:s,overrideChunk:a}=e.state.facet(Sg),i=n=="a",l=new Hd,c=s?new Hd:null,{from:u,to:d}=e.viewport;for(let f of t){if((i?f.fromA:f.fromB)>=d)break;(i?f.toA:f.toB)>u&&(!a||!a(e.state,f,l,c))&&Ils(f,e.state.doc,i,r,l,c)}return{deco:l.finish(),gutter:c&&c.finish()}}class Fz extends nh{constructor(t){super(),this.height=t}eq(t){return this.height==t.height}toDOM(){let t=document.createElement("div");return t.className="cm-mergeSpacer",t.style.height=this.height+"px",t}updateDOM(t){return t.style.height=this.height+"px",!0}get estimatedHeight(){return this.height}ignoreEvent(){return!1}}const sV=dr.define({map:(e,t)=>e.map(t)}),d$=vl.define({create:()=>Tn.none,update:(e,t)=>{for(let n of t.effects)if(n.is(sV))return n.value;return e.map(t.changes)},provide:e=>Rt.decorations.from(e)}),zz=.01;function QJe(e,t){if(e.size!=t.size)return!1;let n=e.iter(),r=t.iter();for(;n.value;){if(n.from!=r.from||Math.abs(n.value.spec.widget.height-r.value.spec.widget.height)>1)return!1;n.next(),r.next()}return!0}function Als(e,t,n){let r=new Hd,s=new Hd,a=e.state.field(d$).iter(),i=t.state.field(d$).iter(),l=0,c=0,u=0,d=0,f=e.viewport,p=t.viewport;for(let y=0;;y++){let b=y<n.length?n[y]:null,x=b?b.fromA:e.state.doc.length,S=b?b.fromB:t.state.doc.length;if(l<x){let k=e.lineBlockAt(l).top+u,_=t.lineBlockAt(c).top+d,C=k-_;C<-zz?(u-=C,r.add(l,l,Tn.widget({widget:new Fz(-C),block:!0,side:-1}))):C>zz&&(d+=C,s.add(c,c,Tn.widget({widget:new Fz(C),block:!0,side:-1})))}if(x>l+1e3&&l<f.from&&x>f.from&&c<p.from&&S>p.from){let k=Math.min(f.from-l,p.from-c);l+=k,c+=k,y--}else if(b)l=b.toA,c=b.toB;else break;for(;a.value&&a.from<l;)u-=a.value.spec.widget.height,a.next();for(;i.value&&i.from<c;)d-=i.value.spec.widget.height,i.next()}for(;a.value;)u-=a.value.spec.widget.height,a.next();for(;i.value;)d-=i.value.spec.widget.height,i.next();let h=e.contentHeight+u-(t.contentHeight+d);h<zz?r.add(e.state.doc.length,e.state.doc.length,Tn.widget({widget:new Fz(-h),block:!0,side:1})):h>zz&&s.add(t.state.doc.length,t.state.doc.length,Tn.widget({widget:new Fz(h),block:!0,side:1}));let m=r.finish(),v=s.finish();QJe(m,e.state.field(d$))||e.dispatch({effects:sV.of(m)}),QJe(v,t.state.field(d$))||t.dispatch({effects:sV.of(v)})}const Axe=dr.define({map:(e,t)=>t.mapPos(e)});class Rls extends nh{constructor(t){super(),this.lines=t}eq(t){return this.lines==t.lines}toDOM(t){let n=document.createElement("div");return n.className="cm-collapsedLines",n.textContent=t.state.phrase("$ unchanged lines",this.lines),n.addEventListener("click",r=>{let s=t.posAtDOM(r.target);t.dispatch({effects:Axe.of(s)});let{side:a,sibling:i}=t.state.facet(Sg);i&&i().dispatch({effects:Axe.of(Pls(s,t.state.field(yx),a=="a"))})}),n}ignoreEvent(t){return t instanceof MouseEvent}get estimatedHeight(){return 27}get type(){return"collapsed-unchanged-code"}}function Pls(e,t,n){let r=0,s=0;for(let a=0;;a++){let i=a<t.length?t[a]:null;if(!i||(n?i.fromA:i.fromB)>=e)return s+(e-r);[r,s]=n?[i.toA,i.toB]:[i.toB,i.toA]}}const $ls=vl.define({create(e){return Tn.none},update(e,t){e=e.map(t.changes);for(let n of t.effects)n.is(Axe)&&(e=e.update({filter:r=>r!=n.value}));if(e.size&&t.state.field(yx)!=t.startState.field(yx,!1)){let n=t.state.facet(Sg).side=="a",r=[];for(let s of t.state.field(yx))e.between(n?s.fromA:s.fromB,n?s.toA:s.toB,a=>{r.push(a)});r.length&&(e=e.update({filter:s=>r.indexOf(s)<0}))}return e},provide:e=>Rt.decorations.from(e)});function YJe({margin:e=3,minSize:t=4}){return $ls.init(n=>Mls(n,e,t))}function Mls(e,t,n){let r=new Hd,s=e.facet(Sg).side=="a",a=e.field(yx),i=1;for(let l=0;;l++){let c=l<a.length?a[l]:null,u=l?i+t:1,d=c?e.doc.lineAt(s?c.fromA:c.fromB).number-1-t:e.doc.lines,f=d-u+1;if(f>=n&&r.add(e.doc.line(u).from,e.doc.line(d).to,Tn.replace({widget:new Rls(f),block:!0})),!c)break;i=e.doc.lineAt(Math.min(e.doc.length,s?c.toA:c.toB)).number}return r.finish()}const Dls=Rt.styleModule.of(new Rx({".cm-mergeView":{overflowY:"auto"},".cm-mergeViewEditors":{display:"flex",alignItems:"stretch"},".cm-mergeViewEditor":{flexGrow:1,flexBasis:0,overflow:"hidden"},".cm-merge-revert":{width:"1.6em",flexGrow:0,flexShrink:0,position:"relative"},".cm-merge-revert button":{position:"absolute",display:"block",width:"100%",boxSizing:"border-box",textAlign:"center",background:"none",border:"none",font:"inherit",cursor:"pointer"}})),Lls=Rt.baseTheme({".cm-mergeView & .cm-scroller, .cm-mergeView &":{height:"auto !important",overflowY:"visible !important"},"&.cm-merge-a .cm-changedLine, .cm-deletedChunk":{backgroundColor:"rgba(160, 128, 100, .08)"},"&.cm-merge-b .cm-changedLine, .cm-inlineChangedLine":{backgroundColor:"rgba(100, 160, 128, .08)"},"&light.cm-merge-a .cm-changedText, &light .cm-deletedChunk .cm-deletedText":{background:"linear-gradient(#ee443366, #ee443366) bottom/100% 2px no-repeat"},"&dark.cm-merge-a .cm-changedText, &dark .cm-deletedChunk .cm-deletedText":{background:"linear-gradient(#ffaa9966, #ffaa9966) bottom/100% 2px no-repeat"},"&light.cm-merge-b .cm-changedText":{background:"linear-gradient(#22bb22aa, #22bb22aa) bottom/100% 2px no-repeat"},"&dark.cm-merge-b .cm-changedText":{background:"linear-gradient(#88ff88aa, #88ff88aa) bottom/100% 2px no-repeat"},"&.cm-merge-b .cm-deletedText":{background:"#ff000033"},".cm-insertedLine, .cm-deletedLine, .cm-deletedLine del":{textDecoration:"none"},".cm-deletedChunk":{paddingLeft:"6px","& .cm-chunkButtons":{position:"absolute",insetInlineEnd:"5px"},"& button":{border:"none",cursor:"pointer",color:"white",margin:"0 2px",borderRadius:"3px","&[name=accept]":{background:"#2a2"},"&[name=reject]":{background:"#d43"}}},".cm-collapsedLines":{padding:"5px 5px 5px 10px",cursor:"pointer","&:before":{content:'"⦚"',marginInlineEnd:"7px"},"&:after":{content:'"⦚"',marginInlineStart:"7px"}},"&light .cm-collapsedLines":{color:"#444",background:"linear-gradient(to bottom, transparent 0, #f3f3f3 30%, #f3f3f3 70%, transparent 100%)"},"&dark .cm-collapsedLines":{color:"#ddd",background:"linear-gradient(to bottom, transparent 0, #222 30%, #222 70%, transparent 100%)"},".cm-changeGutter":{width:"3px",paddingLeft:"1px"},"&light.cm-merge-a .cm-changedLineGutter, &light .cm-deletedLineGutter":{background:"#e43"},"&dark.cm-merge-a .cm-changedLineGutter, &dark .cm-deletedLineGutter":{background:"#fa9"},"&light.cm-merge-b .cm-changedLineGutter":{background:"#2b2"},"&dark.cm-merge-b .cm-changedLineGutter":{background:"#8f8"},".cm-inlineChangedLineGutter":{background:"#75d"}}),KJe=new bI,Bz=new bI;class Fls{constructor(t){this.revertDOM=null,this.revertToA=!1,this.revertToLeft=!1,this.measuring=-1,this.diffConf=t.diffConfig||_ls;let n=[th.low(FUt),Lls,Dls,d$,Rt.updateListener.of(f=>{this.measuring<0&&(f.heightChanged||f.viewportChanged)&&!f.transactions.some(p=>p.effects.some(h=>h.is(sV)))&&this.measure()})],r=[Sg.of({side:"a",sibling:()=>this.b,highlightChanges:t.highlightChanges!==!1,markGutter:t.gutter!==!1})];t.gutter!==!1&&r.push(Lz);let s=gs.create({doc:t.a.doc,selection:t.a.selection,extensions:[t.a.extensions||[],Rt.editorAttributes.of({class:"cm-merge-a"}),Bz.of(r),n]}),a=[Sg.of({side:"b",sibling:()=>this.a,highlightChanges:t.highlightChanges!==!1,markGutter:t.gutter!==!1})];t.gutter!==!1&&a.push(Lz);let i=gs.create({doc:t.b.doc,selection:t.b.selection,extensions:[t.b.extensions||[],Rt.editorAttributes.of({class:"cm-merge-b"}),Bz.of(a),n]});this.chunks=xj.build(s.doc,i.doc,this.diffConf);let l=[yx.init(()=>this.chunks),KJe.of(t.collapseUnchanged?YJe(t.collapseUnchanged):[])];s=s.update({effects:dr.appendConfig.of(l)}).state,i=i.update({effects:dr.appendConfig.of(l)}).state,this.dom=document.createElement("div"),this.dom.className="cm-mergeView",this.editorDOM=this.dom.appendChild(document.createElement("div")),this.editorDOM.className="cm-mergeViewEditors";let c=t.orientation||"a-b",u=document.createElement("div");u.className="cm-mergeViewEditor";let d=document.createElement("div");d.className="cm-mergeViewEditor",this.editorDOM.appendChild(c=="a-b"?u:d),this.editorDOM.appendChild(c=="a-b"?d:u),this.a=new Rt({state:s,parent:u,root:t.root,dispatchTransactions:f=>this.dispatch(f,this.a)}),this.b=new Rt({state:i,parent:d,root:t.root,dispatchTransactions:f=>this.dispatch(f,this.b)}),this.setupRevertControls(!!t.revertControls,t.revertControls=="b-to-a",t.renderRevertControl),t.parent&&t.parent.appendChild(this.dom),this.scheduleMeasure()}dispatch(t,n){if(t.some(r=>r.docChanged)){let r=t[t.length-1],s=t.reduce((i,l)=>i.compose(l.changes),El.empty(t[0].startState.doc.length));this.chunks=n==this.a?xj.updateA(this.chunks,r.newDoc,this.b.state.doc,s,this.diffConf):xj.updateB(this.chunks,this.a.state.doc,r.newDoc,s,this.diffConf),n.update([...t,r.state.update({effects:Ixe.of(this.chunks)})]);let a=n==this.a?this.b:this.a;a.update([a.state.update({effects:Ixe.of(this.chunks)})]),this.scheduleMeasure()}else n.update(t)}reconfigure(t){if("diffConfig"in t&&(this.diffConf=t.diffConfig),"orientation"in t){let a=t.orientation!="b-a";if(a!=(this.editorDOM.firstChild==this.a.dom.parentNode)){let i=this.a.dom.parentNode,l=this.b.dom.parentNode;i.remove(),l.remove(),this.editorDOM.insertBefore(a?i:l,this.editorDOM.firstChild),this.editorDOM.appendChild(a?l:i),this.revertToLeft=!this.revertToLeft,this.revertDOM&&(this.revertDOM.textContent="")}}if("revertControls"in t||"renderRevertControl"in t){let a=!!this.revertDOM,i=this.revertToA,l=this.renderRevert;"revertControls"in t&&(a=!!t.revertControls,i=t.revertControls=="b-to-a"),"renderRevertControl"in t&&(l=t.renderRevertControl),this.setupRevertControls(a,i,l)}let n="highlightChanges"in t,r="gutter"in t,s="collapseUnchanged"in t;if(n||r||s){let a=[],i=[];if(n||r){let l=this.a.state.facet(Sg),c=r?t.gutter!==!1:l.markGutter,u=n?t.highlightChanges!==!1:l.highlightChanges;a.push(Bz.reconfigure([Sg.of({side:"a",sibling:()=>this.b,highlightChanges:u,markGutter:c}),c?Lz:[]])),i.push(Bz.reconfigure([Sg.of({side:"b",sibling:()=>this.a,highlightChanges:u,markGutter:c}),c?Lz:[]]))}if(s){let l=KJe.reconfigure(t.collapseUnchanged?YJe(t.collapseUnchanged):[]);a.push(l),i.push(l)}this.a.dispatch({effects:a}),this.b.dispatch({effects:i})}this.scheduleMeasure()}setupRevertControls(t,n,r){this.revertToA=n,this.revertToLeft=this.revertToA==(this.editorDOM.firstChild==this.a.dom.parentNode),this.renderRevert=r,!t&&this.revertDOM?(this.revertDOM.remove(),this.revertDOM=null):t&&!this.revertDOM?(this.revertDOM=this.editorDOM.insertBefore(document.createElement("div"),this.editorDOM.firstChild.nextSibling),this.revertDOM.addEventListener("mousedown",s=>this.revertClicked(s)),this.revertDOM.className="cm-merge-revert"):this.revertDOM&&(this.revertDOM.textContent="")}scheduleMeasure(){if(this.measuring<0){let t=this.dom.ownerDocument.defaultView||window;this.measuring=t.requestAnimationFrame(()=>{this.measuring=-1,this.measure()})}}measure(){Als(this.a,this.b,this.chunks),this.revertDOM&&this.updateRevertButtons()}updateRevertButtons(){let t=this.revertDOM,n=t.firstChild,r=this.a.viewport,s=this.b.viewport;for(let a=0;a<this.chunks.length;a++){let i=this.chunks[a];if(i.fromA>r.to||i.fromB>s.to)break;if(i.fromA<r.from||i.fromB<s.from)continue;let l=this.a.lineBlockAt(i.fromA).top+"px";for(;n&&+n.dataset.chunk<a;)n=XJe(n);n&&n.dataset.chunk==String(a)?(n.style.top!=l&&(n.style.top=l),n=n.nextSibling):t.insertBefore(this.renderRevertButton(l,a),n)}for(;n;)n=XJe(n)}renderRevertButton(t,n){let r;if(this.renderRevert)r=this.renderRevert();else{r=document.createElement("button");let s=this.a.state.phrase("Revert this chunk");r.setAttribute("aria-label",s),r.setAttribute("title",s),r.textContent=this.revertToLeft?"⇜":"⇝"}return r.style.top=t,r.setAttribute("data-chunk",String(n)),r}revertClicked(t){let n=t.target,r;for(;n&&n.parentNode!=this.revertDOM;)n=n.parentNode;if(n&&(r=this.chunks[n.dataset.chunk])){let[s,a,i,l,c,u]=this.revertToA?[this.b,this.a,r.fromB,r.toB,r.fromA,r.toA]:[this.a,this.b,r.fromA,r.toA,r.fromB,r.toB],d=s.state.sliceDoc(i,Math.max(i,l-1));i!=l&&u<=a.state.doc.length&&(d+=s.state.lineBreak),a.dispatch({changes:{from:c,to:Math.min(a.state.doc.length,u),insert:d},userEvent:"revert"}),t.preventDefault()}}destroy(){this.a.destroy(),this.b.destroy(),this.measuring>-1&&(this.dom.ownerDocument.defaultView||window).cancelAnimationFrame(this.measuring),this.dom.remove()}}function XJe(e){let t=e.nextSibling;return e.remove(),t}const zls=Rt.theme({"&.cm-editor .cm-changedLine":{backgroundColor:"transparent",backgroundImage:"none",borderLeft:"none"},"&.cm-editor .cm-changedText":{backgroundImage:"none",backgroundColor:"#880000",padding:"1px 5px",display:"inline-block",borderRadius:"4px"},"&.cm-editor .cm-changedText, &.cm-editor .cm-changedText *":{color:"white"},"&.cm-editor .cm-line":{lineHeight:"1.5",opacity:"0.5"},"&.cm-editor .cm-line.cm-changedLine":{opacity:"1"},"&.cm-editor .cm-gutters":{display:"none"}});function Bls(){return kI({settings:{fontFamily:"var(--font-mono)",fontSize:"0.8125rem",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"#939393",background:"transparent"},styles:[{tag:[de.className,de.propertyName]}]})}function Uls(){const e=Rt.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"0.8125rem"},"&.cm-editor .cm-scroller":{fontFamily:"var(--font-mono)"},".cm-gutters":{backgroundColor:"transparent",color:"var(--neutral2)",borderRight:"none"},".cm-content":{color:"var(--neutral6)"},".cm-activeLine":{backgroundColor:"transparent"},".cm-activeLineGutter":{backgroundColor:"transparent"}}),t=Kg.define([{tag:[de.comment,de.bracket],color:"var(--neutral2)"},{tag:[de.string,de.meta,de.regexp],color:"var(--accent1)"},{tag:[de.atom,de.bool,de.special(de.variableName)],color:"var(--accent6)"},{tag:[de.keyword,de.operator,de.tagName],color:"var(--accent2)"},{tag:[de.function(de.propertyName),de.propertyName],color:"var(--accent5)"},{tag:[de.definition(de.variableName),de.function(de.variableName),de.className,de.attributeName],color:"var(--accent3)"},{tag:[de.variableName,de.number],color:"var(--accent5)"},{tag:[de.name,de.quote],color:"var(--accent1)"}]);return[e,rS(t)]}function cAe({codeA:e,codeB:t}){const n=g.useRef(null),r=g.useRef(null),s=K_().resolvedTheme==="dark",a=g.useMemo(()=>s?Bls():Uls(),[s]);return g.useEffect(()=>{if(!n.current)return;r.current&&r.current.destroy();const i=[Yj(),a,zls,Rt.lineWrapping,gs.readOnly.of(!0)],l=new Fls({parent:n.current,a:{doc:e,extensions:i},b:{doc:t,extensions:i},collapseUnchanged:{margin:3,minSize:4}});return r.current=l,()=>{l.destroy(),r.current=null}},[e,t,a]),o.jsxs("div",{className:"border-border1 bg-surface3 relative overflow-auto rounded-xl border dark:border-white/10 dark:bg-black/20",children:[o.jsx("div",{className:"bg-border1 absolute top-0 left-1/2 z-10 h-full w-px dark:bg-white/10"}),o.jsx("div",{ref:n,className:"[&_.cm-editor]:bg-transparent [&_.cm-editor]:p-6 [&_.cm-gutters]:bg-transparent [&_.cm-mergeViewEditor]:flex-1"})]})}function qls(e){if(!e)return null;const t=e.match(/^(\d{1,2}):(\d{2})$/);if(!t)return e;const[,n,r]=t,s=Number(n),a=s>=12?"PM":"AM";return`${s%12||12}:${r} ${a}`}function Vls(e){return e==="🔴"?"high":e==="🟡"?"medium":e==="🟢"?"low":e==="✅"?"complete":null}function Hls(e,t){if(t)return{card:"bg-transparent border-transparent",text:"text-neutral3",time:"text-icon3"};switch(e){case"high":return{card:"border-purple-400/30 bg-purple-500/10",text:"text-neutral6",time:"text-purple-200/80"};case"medium":return{card:"border-blue-400/30 bg-blue-500/10",text:"text-neutral6",time:"text-blue-200/80"};case"low":return{card:"border-emerald-400/30 bg-emerald-500/10",text:"text-neutral6",time:"text-emerald-200/80"};case"complete":return{card:"border-green-400/30 bg-green-500/10",text:"text-neutral6",time:"text-green-200/80"};default:return{card:"border-border1 bg-surface2",text:"text-neutral6",time:"text-icon3"}}}function Wls(e){const t=e.trim();if(!t)return null;if(t.startsWith("* ->")||t.startsWith("->")){const n=t.replace(/^\*?\s*->\s*/,"").trim();return n?{text:n,time:null,priority:null,children:[]}:null}if(t.startsWith("-")){const n=t.replace(/^-\s*/,"").trim();return n?{text:n,time:null,priority:null,children:[]}:null}if(t.startsWith("*")){let n=t.slice(1).trimStart(),r=null;for(const i of["🔴","🟡","🟢","✅"])if(n.startsWith(i)){r=Vls(i),n=n.slice(i.length).trimStart();break}let s=null;const a=n.match(/^\((\d{1,2}:\d{2})\)/);if(a){const[i,l]=a;i!==void 0&&l!==void 0&&(s=l,n=n.slice(i.length).trimStart())}if(n)return{text:n,time:s,priority:r,children:[]}}return{text:t,time:null,priority:null,children:[]}}function Zls(e){const t="<observations>",n=e.indexOf(t),r=n===-1?-1:e.indexOf("</observations>",n+t.length),s=(r===-1?e:e.slice(n+t.length,r)).trim();if(!s)return[];const a=s.split(`
|
|
625
625
|
`),i=[];let l=null,c=null;for(const u of a){const d=u.trim();if(!d)continue;if(d.startsWith("Date:")){let m=d.slice(5).trim(),v=null;if(m.endsWith(")")){const y=m.lastIndexOf("("),b=y===-1?"":m.slice(y+1,-1);y>0&&b&&!b.includes(")")&&(v=b.trim(),m=m.slice(0,y).trim())}if(m){l={title:m,relativeTime:v,items:[]},i.push(l),c=null;continue}}l||(l={title:"Recent",relativeTime:null,items:[]},i.push(l));const p=(u.match(/^(\s*)/)?.[1]?.length??0)>=2&&(d.startsWith("* ->")||d.startsWith("->")||d.startsWith("-")),h=Wls(u);if(h){if(p&&c){c.children.push(h);continue}l.items.push(h),c=h}}return i}function zUt({items:e,nested:t=!1}){return o.jsx("div",{className:t?"border-border1 space-y-2 border-l pl-4":"space-y-3",children:e.map((n,r)=>{const s=Hls(n.priority,t);return o.jsx("div",{className:"space-y-2",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("div",{className:"w-12 shrink-0 pt-2 text-right",children:n.time&&o.jsx("span",{className:`text-ui-xs font-mono ${s.time}`,children:qls(n.time)})}),o.jsxs("div",{className:K("min-w-0 flex-1 rounded-md border px-3 py-2",s.card),children:[o.jsx("p",{className:K("text-sm leading-6 break-words whitespace-pre-wrap",s.text),children:n.text}),n.children.length>0&&o.jsx("div",{className:"mt-3",children:o.jsx(zUt,{items:n.children,nested:!0})})]})]})},`${n.text.slice(0,20)}-${r}`)})})}function Gls({observations:e}){const t=g.useMemo(()=>Zls(e),[e]);return t.length===0?o.jsx("p",{className:"text-icon3 text-xs italic",children:"Initialized"}):o.jsx("div",{className:"space-y-5",children:t.map((n,r)=>o.jsxs("section",{className:"space-y-3",children:[o.jsx("div",{className:"border-border1 flex items-baseline justify-between gap-3 border-b pb-2",children:o.jsxs("div",{className:"min-w-0",children:[o.jsx("h3",{className:"text-neutral6 text-xs font-medium",children:n.title}),n.relativeTime&&o.jsx("p",{className:"text-icon3 text-ui-xs",children:n.relativeTime})]})}),o.jsx(zUt,{items:n.items})]},`${n.title}-${r}`))})}function Qls({records:e,selectedRecordId:t,onSelectRecord:n}){return e.length<=1?null:o.jsxs("div",{className:"border-border1 flex w-50 min-w-45 flex-col overflow-hidden border-l",children:[o.jsx("div",{className:"border-border1 border-b px-4 py-2",children:o.jsx("p",{className:"text-neutral6 text-sm font-normal",children:"History"})}),o.jsx("div",{className:"flex-1 overflow-y-auto",children:e.map(r=>{const s=r.id===t;return o.jsx("button",{type:"button",className:K("text-icon3 w-full cursor-pointer truncate border-l-2 border-l-transparent px-3 py-2 text-left text-xs transition-all hover:bg-surface3/50",s&&"border-l-accent1 bg-surface3/50"),onClick:()=>n(r.id),children:r.activeObservations||o.jsx("span",{className:"text-icon3 italic",children:r.isObserving||r.isReflecting?"Processing…":"Initialized"})},r.id)})})]})}function Yls({records:e,selectedRecordId:t,onSelectRecord:n,isLoading:r}){const[s,a]=g.useState(!1),i=g.useMemo(()=>[...e].sort((f,p)=>new Date(f.createdAt).getTime()-new Date(p.createdAt).getTime()),[e]),l=t?i.find(f=>f.id===t):i[i.length-1],c=l?i.findIndex(f=>f.id===l.id):-1,u=c>0?i[c-1]:null;if(g.useEffect(()=>{const f=i.at(-1);!t&&f&&n(f.id)},[t,i,n]),r)return o.jsxs("div",{className:"space-y-4 p-4",children:[o.jsx(jt,{className:"h-6 w-40"}),o.jsx(jt,{className:"h-32 w-full"}),o.jsx(jt,{className:"h-32 w-full"})]});if(!l)return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Er,{iconSlot:o.jsx(kg,{className:"size-4"}),titleSlot:"No observations",descriptionSlot:"No observational memory snapshots available for this thread."})});const d=typeof l.activeObservations=="string"?l.activeObservations:"";return o.jsxs("div",{className:"flex size-full overflow-hidden",children:[o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col overflow-hidden",children:[u&&o.jsx("div",{className:"border-border1 border-b px-4 py-2",children:o.jsx("div",{className:"flex items-start justify-end gap-3",children:o.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5",children:[o.jsx(So,{checked:s,onCheckedChange:f=>a(f===!0)}),o.jsx("span",{className:"text-icon3 text-xs",children:"Show diff"})]})})}),o.jsx("div",{"data-testid":"observation-detail-body",className:"flex-1 overflow-y-auto p-4",children:s&&u?o.jsx(cAe,{codeA:typeof u.activeObservations=="string"?u.activeObservations:"",codeB:d}):d?o.jsx(Gls,{observations:d}):o.jsx("p",{className:"text-icon3 text-xs italic",children:l.isObserving||l.isReflecting?"Processing…":"Initialized"})})]}),o.jsx(Qls,{records:i,selectedRecordId:l.id,onSelectRecord:n})]})}function JJe(e){if(e===0)return"0";const t=e/1e3,n=t<.1?2:1;return t.toFixed(n).replace(/\.0+$/,"").replace(/(\.\d*[1-9])0$/,"$1")}const Kls={messages:"text-blue-500",memory:"text-violet-500",warning:"text-warning1"};function eet({label:e,value:t,max:n,tone:r}){const s=Math.max(0,Math.min(100,t/n*100));return o.jsxs("div",{className:K("min-w-0 flex-1",Kls[r]),children:[o.jsxs("div",{className:"text-icon3 text-ui-xs mb-1 flex items-center justify-between gap-2 font-mono",children:[o.jsx("span",{className:"text-icon6 tracking-wide uppercase",children:e}),o.jsxs("span",{className:"text-icon3 tabular-nums",children:[JJe(t),"/",JJe(n),"k"]})]}),o.jsx("div",{className:"h-1.5 overflow-hidden rounded-full bg-white/[0.08]",children:o.jsx("div",{className:"h-full rounded-full bg-current/80",style:{width:`${s}%`}})})]})}function Xls({messageTokens:e,messageThreshold:t,memoryTokens:n,memoryThreshold:r,memoryLabel:s="Memory"}){const a=e!=null&&t!=null&&t>0,i=n!=null&&r!=null&&r>0;return!a&&!i?null:o.jsx("div",{className:"border-border1 border-b px-3 py-2",children:o.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[a?o.jsx(eet,{label:"Messages",value:e,max:t,tone:"messages"}):null,i?o.jsx(eet,{label:s,value:n,max:r,tone:"memory"}):null]})})}function Jls({messages:e,omRecords:t,isLoading:n=!1,onClose:r,selectedTimestamp:s,onSelectTimestamp:a,contextWindow:i}){const[l,c]=g.useState(null),u=g.useMemo(()=>Qos(e),[e]),d=g.useMemo(()=>Yos(e.map(_=>new Date(_.createdAt).toISOString())),[e]),f=g.useMemo(()=>tls({markers:u,omRecords:t}),[u,t]),p=i?.memoryTokens??f.memoryTokens,h=i?.memoryThreshold??f.memoryThreshold,[m,v]=g.useState({left:d.tMin,right:d.tMax});g.useEffect(()=>{v({left:d.tMin,right:d.tMax})},[d.tMin,d.tMax]);const y=m.left<=d.tMin&&m.right>=d.tMax,b=g.useMemo(()=>y?t:t.filter(_=>{const C=Xos(_);return C>=m.left&&C<=m.right}),[t,y,m.left,m.right]),x=g.useMemo(()=>s!=null?Jos(b,s):null,[b,s]),S=l!=null&&b.some(_=>_.id===l)?l:null,k=x??S;return o.jsxs("div",{className:"flex size-full flex-col overflow-hidden",children:[o.jsxs("div",{className:"border-border1 flex shrink-0 items-center gap-2 border-b px-3 py-2.5",children:[o.jsx(oe,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"Back to memory",onClick:()=>r?.(),children:o.jsx(gl,{})}),o.jsxs("span",{className:"text-neutral6 flex min-w-0 items-center gap-1.5",children:[o.jsx(RL,{className:"size-4 shrink-0"}),o.jsx(me,{as:"span",variant:"ui-sm",className:"font-medium",children:"Observational memory"})]})]}),n?o.jsxs("div",{"data-testid":"memory-studio-loading",className:"flex flex-1 flex-col gap-3 p-4",children:[o.jsx(jt,{className:"h-6 w-40"}),o.jsx(jt,{className:"h-32 w-full"}),o.jsx(jt,{className:"h-16 w-full"})]}):o.jsxs("div",{className:"grid min-h-0 flex-1 grid-rows-[1fr_auto] overflow-hidden",children:[o.jsx("div",{className:"flex min-h-0 flex-col overflow-hidden",children:o.jsx(Yls,{records:b,selectedRecordId:k,onSelectRecord:c,isLoading:n})}),o.jsxs("div",{className:"border-border1 border-t",children:[o.jsx(Xls,{messageTokens:i?.messageTokens??f.messageTokens,messageThreshold:i?.messageThreshold??f.messageThreshold,memoryTokens:p,memoryThreshold:h,memoryLabel:"Observations"}),o.jsx(yls,{omRecords:t,markers:u,messages:e,tDomain:d,onSelectTimestamp:a,zoomRange:m,onZoomRangeChange:v})]})]})]})}const ecs=2e3;function tcs({agentId:e,threadId:t}){const{isPanelOpen:n,closePanel:r,selectedTimestamp:s,setSelectedTimestamp:a}=iG(),{isObservingFromStream:i,isReflectingFromStream:l,observationsUpdatedAt:c,streamProgress:u}=aG(),d=i||l,{data:f}=XTe({threadId:t,agentId:e}),p=f?.resourceId??e,{data:h}=mS(e),{data:m,isLoading:v,refetch:y}=j4t(n?e:void 0,n?t:void 0,p),{data:b,isLoading:x,refetch:S}=DBr(n?t:void 0);if(g.useEffect(()=>{!n||c===0||(y(),S())},[n,c,y,S]),g.useEffect(()=>{if(!n||!d)return;const T=setInterval(()=>{y(),S()},ecs);return()=>clearInterval(T)},[n,d,y,S]),!n)return null;const k=h?.config?.observationalMemory,_=u?.threadId===t?u:null,C=UIe({record:m?.record,liveProgress:_,agentConfig:k});return o.jsx("div",{"data-testid":"memory-sidebar-om-detail-subpanel",className:"bg-surface3 h-full min-h-0 min-w-0 overflow-hidden",children:o.jsx(Jls,{messages:b?.messages??[],omRecords:m?.history??[],isLoading:v||x,onClose:r,selectedTimestamp:s,onSelectTimestamp:a,contextWindow:{messageTokens:C.messageTokens,messageThreshold:C.messageThreshold,memoryTokens:C.observationTokens,memoryThreshold:C.observationThreshold}})})}function ncs(e){if(e!==!1)return e}function rcs(e){const{data:t}=mS(e),n=t?.config;return{lastMessages:ncs(n?.lastMessages),semanticRecallOn:!!n?.semanticRecall,workingMemoryOn:!!n?.workingMemory?.enabled,observationalOn:!!n?.observationalMemory?.enabled}}const tet="agent-memory-sidebar-tab-v2",scs=()=>{const[e,t]=g.useState(()=>{const r=sessionStorage.getItem(tet)||"threads";return r==="threads"||r==="memory"?r:"threads"}),n=g.useCallback(r=>{t(r),sessionStorage.setItem(tet,r)},[]);return{selectedTab:e,handleTabChange:n}},acs=e=>e>=85?"bg-orange-400":e>=60?"bg-blue-500":"bg-green-500";function Uz({icon:e,tooltip:t,enabled:n,value:r}){return o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:o.jsxs("span",{className:K("inline-flex items-center gap-1 rounded-full border px-1.5 py-0.5 transition-colors duration-normal",n?"border-border1 bg-surface4 text-neutral6":"border-border1/40 text-neutral3/50"),children:[o.jsx(e,{className:"h-3 w-3 shrink-0"}),r!==void 0&&o.jsx(me,{as:"span",variant:"ui-xs",className:"leading-none font-medium tabular-nums",children:r})]})}),o.jsx(vn,{children:t})]})}function ics(){return o.jsxs("div",{"data-testid":"memory-sidebar-skeleton",className:"flex h-full min-h-0 w-full flex-col gap-2.5 p-3",children:[o.jsx(jt,{className:"h-3 w-28"}),o.jsx(jt,{className:"h-3 w-20"}),o.jsx(jt,{className:"h-3 w-24"}),o.jsx(jt,{className:"h-3 w-16"})]})}function ocs({agentId:e,threadId:t,threads:n,onDelete:r,threadsSlot:s}){const{data:a,isLoading:i}=yC(e),l=!!a?.result,c=a?.memoryType,{selectedTab:u,handleTabChange:d}=scs(),{isPanelOpen:f}=iG(),{streamProgress:p}=aG(),{lastMessages:h,semanticRecallOn:m,workingMemoryOn:v,observationalOn:y}=rcs(e),b=u==="memory",x=g.useRef(null),S=g.useRef(null),[k,_]=g.useState({height:0,offset:0}),C=y&&f,T=p?.threadId===t?p:null,{data:E}=XTe({threadId:t,agentId:e}),{data:N}=mS(e),{data:I}=j4t(y?e:void 0,y?t:void 0,E?.resourceId??e),A=N?.config?.observationalMemory,{messageTokens:R,messageThreshold:L}=UIe({record:I?.record,liveProgress:T,agentConfig:A}),F=(!!T||!!I?.record)&&L>0?Math.min(100,Math.round(R/L*100)):void 0;return g.useLayoutEffect(()=>{if(b||C||!l)return;const H=x.current,B=S.current;if(!H||!B)return;const z=()=>{const M=getComputedStyle(H),G=Number.parseFloat(M.borderTopWidth)||0,U=Number.parseFloat(M.borderBottomWidth)||0,$=Number.parseFloat(M.marginTop)||0,q=Number.parseFloat(M.marginBottom)||0,Z=Math.ceil(B.getBoundingClientRect().height+G+U),Y=Math.ceil(Z+$+q);_(ne=>ne.height===Z&&ne.offset===Y?ne:{height:Z,offset:Y})};if(z(),typeof ResizeObserver>"u")return;const V=new ResizeObserver(z);return V.observe(B),()=>V.disconnect()},[l,h,F,y,m,b,C,v]),i?o.jsx(ics,{}):C?o.jsx("div",{"data-testid":"memory-sidebar-panel",className:"h-full min-h-0 min-w-0",children:o.jsx(tcs,{agentId:e,threadId:t})}):o.jsxs("div",{className:"flex h-full min-h-0 w-full flex-col overflow-hidden",children:[o.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden",children:[o.jsx("div",{"aria-hidden":b&&l,inert:b&&l?!0:void 0,"data-testid":"memory-sidebar-thread-layer",className:K("memory-sidebar-thread-layer absolute inset-0 flex min-h-0 flex-col overflow-hidden",b&&l?"pointer-events-none opacity-0":"opacity-100"),children:o.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",style:{paddingBottom:l&&k.offset||void 0},children:s||(l?o.jsx(urs,{resourceId:e,resourceType:"agent",threads:n??[],threadId:t,onDelete:r??(()=>{}),embedded:!0}):o.jsx(Er,{iconSlot:null,titleSlot:"Memory not enabled",descriptionSlot:"Conversations are only saved as threads when the agent has memory configured.",actionSlot:o.jsx(oe,{as:"a",href:"https://mastra.ai/docs/memory/overview",target:"_blank",rel:"noopener noreferrer",variant:"outline",children:"View documentation"})}))})}),l?o.jsxs("div",{ref:x,"data-testid":"memory-sidebar-overlay",className:K("memory-sidebar-overlay absolute inset-x-0 bottom-0 z-10 box-border flex min-h-0 flex-col overflow-hidden border",b?"top-1 m-1 rounded-xl border-border1/40 bg-surface3 shadow-none":"m-1 rounded-xl border-border1/40 bg-surface4 hover:bg-surface5 active:bg-surface4"),style:{height:b?void 0:k.height||void 0},children:[o.jsxs("button",{ref:S,type:"button",onClick:()=>d(b?"threads":"memory"),"aria-pressed":b,"data-testid":"memory-sidebar-card",className:"group/memory-card w-full shrink-0 cursor-pointer bg-transparent px-3 py-2.5 text-left",children:[o.jsxs("span",{className:"flex items-center justify-between gap-2",children:[o.jsxs("span",{className:"text-neutral6 flex min-w-0 items-center gap-1.5",children:[o.jsx(RL,{className:"h-4 w-4 shrink-0"}),o.jsx(me,{as:"span",variant:"ui-sm",className:"font-medium",children:"Memory"})]}),b?o.jsx(Xs,{className:"text-neutral3 h-4 w-4 shrink-0"}):o.jsx(O_,{className:"text-neutral3 h-4 w-4 shrink-0"})]}),b?null:o.jsx(zl,{delay:150,timeout:400,children:o.jsxs("span",{"data-testid":"memory-config-badges",className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[o.jsx(Uz,{icon:u0e,tooltip:h!==void 0?`Keeps the last ${h} messages in context`:"Recent message history is off",enabled:h!==void 0,value:h}),o.jsx(Uz,{icon:Ms,tooltip:m?"Semantic recall is on - retrieves relevant past messages":"Semantic recall is off",enabled:m}),o.jsx(Uz,{icon:wXt,tooltip:v?"Working memory is on - persists notes across the conversation":"Working memory is off",enabled:v}),o.jsx(Uz,{icon:ec,tooltip:y?"Observational memory is on - learns from the conversation":"Observational memory is off",enabled:y})]})}),F!==void 0?o.jsx("span",{"data-testid":"memory-card-observation-bar","data-percent":F,className:"bg-surface5 mt-2 block h-1 w-full overflow-hidden rounded-full",children:o.jsx("span",{className:K("block h-full rounded-full transition-all duration-normal",acs(F)),style:{width:`${F}%`}})}):null]}),b&&o.jsx("div",{className:"memory-card-content border-border1 min-h-0 flex-1 overflow-y-auto border-t",children:o.jsx(zrs,{agentId:e,threadId:t,memoryType:c})})]}):null]}),o.jsx(Vos,{agentId:e})]})}const lcs=3;function ccs(e){const t=e?.suggestedPrompts;if(!Array.isArray(t))return[];const n=[],r=new Set;for(const s of t){if(typeof s!="string")continue;const a=s.trim();if(!(!a||r.has(a))&&(n.push(a),r.add(a),n.length===lcs))break}return n}function ucs({title:e,onClose:t,children:n}){return o.jsxs(Yu,{as:"aside",appearance:"surface",elevation:"elevated",className:"border-border1 flex h-full min-h-0 w-full flex-col overflow-hidden rounded-2xl border",children:[e?o.jsxs(fn.Header,{children:[o.jsx(fn.Heading,{children:e}),t?o.jsx(fn.CloseButton,{onClick:t}):null]}):null,o.jsx("div",{className:"min-h-0 flex-1",children:n})]})}function BUt({error:e,resource:t,errorTitle:n}){if(Ss(e))return o.jsx(Gs,{});if(ks(e))return o.jsx(Fs,{resource:t});const r=e instanceof Error?GNr(e):void 0;return o.jsx(Ui,{title:n,message:r?.error??"Unknown error"})}function dcs(e,t,n){const r=new Array(e);return new Proxy(r,{get(s,a,i){if(typeof a=="string"){const l=a.charCodeAt(0);if(l>=48&&l<=57){const c=+a;if(Number.isInteger(c)&&c>=0&&c<e){let u=s[c];if(!u){const d=t[c*2];u=s[c]={index:c,key:n(c),start:d,size:t[c*2+1],end:d+t[c*2+1],lane:0}}return u}}if(a==="length")return e}return Reflect.get(s,a,i)}})}function LE(e,t,n){let r=n.initialDeps??[],s,a=!0;function i(){const l=e();return(l.length!==r.length||l.some((u,d)=>r[d]!==u))&&(r=l,s=t(...l),n?.onChange&&!(a&&n.skipInitialOnChange)&&n.onChange(s),a=!1),s}return i.updateDeps=l=>{r=l},i}function net(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const fcs=(e,t)=>Math.abs(e-t)<1.01,pcs=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}};let bP;const uie=()=>{if(bP!==void 0)return bP;if(typeof navigator>"u")return bP=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return bP=!0;const e=navigator.maxTouchPoints;return bP=navigator.platform==="MacIntel"&&e!==void 0&&e>0},ret=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},hcs=e=>e,mcs=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,s=new Array(r);for(let a=0;a<r;a++)s[a]=t+a;return s},gcs=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const s=i=>{const{width:l,height:c}=i;t({width:Math.round(l),height:Math.round(c)})};if(s(ret(n)),!r.ResizeObserver)return()=>{};const a=new r.ResizeObserver(i=>{const l=()=>{const c=i[0];if(c?.borderBoxSize){const u=c.borderBoxSize[0];if(u){s({width:u.inlineSize,height:u.blockSize});return}}s(ret(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return a.observe(n,{box:"border-box"}),()=>{a.unobserve(n)}},aV={passive:!0},vcs=typeof window>"u"?!0:"onscrollend"in window,ycs=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const s=e.targetWindow;if(!s)return;const a=e.options.useScrollendEvent&&vcs;let i=0;const l=a?null:pcs(s,()=>t(i,!1),e.options.isScrollingResetDelay),c=f=>()=>{i=n(r),l?.(),t(i,f)},u=c(!0),d=c(!1);return r.addEventListener("scroll",u,aV),a&&r.addEventListener("scrollend",d,aV),()=>{r.removeEventListener("scroll",u),a&&r.removeEventListener("scrollend",d)}},bcs=(e,t)=>ycs(e,t,n=>{const{horizontal:r,isRtl:s}=e.options;return r?n.scrollLeft*(s&&-1||1):n.scrollTop}),xcs=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),s=n.options.getItemKey(r);return n.itemSizeCache.get(s)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),s=n.options.getItemKey(r),a=n.itemSizeCache.get(s);if(a!==void 0)return a}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},wcs=(e,{adjustments:t=0,behavior:n},r)=>{var s,a;(a=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||a.call(s,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},Scs=wcs;class kcs{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,s;return((s=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:s.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(s=>{s.forEach(a=>{const i=()=>{const l=a.target,c=this.indexFromElement(l);if(!l.isConnected){this.observer.unobserve(l);for(const[u,d]of this.elementsCache)if(d===l){this.elementsCache.delete(u);break}return}this.shouldMeasureDuringScroll(c)&&this.resizeItem(c,this.options.measureElement(l,a,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var s;(s=r())==null||s.disconnect(),n=null},observe:s=>{var a;return(a=r())==null?void 0:a.observe(s,{box:"border-box"})},unobserve:s=>{var a;return(a=r())==null?void 0:a.unobserve(s)}}})(),this.range=null,this.setOptions=n=>{var r,s;const a={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:hcs,rangeExtractor:mcs,onChange:()=>{},measureElement:xcs,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const p in n){const h=n[p];h!==void 0&&(a[p]=h)}const i=this.options;let l=null,c=null,u=!1;if(i!==void 0&&i.enabled&&a.enabled&&a.anchorTo==="end"&&this.scrollElement!==null){const p=i.count,h=a.count,m=this.getMeasurements(),v=p>0?((r=m[0])==null?void 0:r.key)??i.getItemKey(0):null,y=p>0?((s=m[p-1])==null?void 0:s.key)??i.getItemKey(p-1):null;if(h!==p||p>0&&h>0&&(a.getItemKey(0)!==v||a.getItemKey(h-1)!==y)){u=!0;const S=p>0?this.getVirtualItemForOffset(this.getScrollOffset())??m[0]:null;S&&(l=[S.key,this.getScrollOffset()-S.start]);const k=a.followOnAppend===!0?"auto":a.followOnAppend||null;k&&h>p&&this.isAtEnd(i.scrollEndThreshold)&&(p===0||a.getItemKey(h-1)!==y)&&(c=k)}}this.options=a,u&&(this.pendingMin=0,this.itemSizeCacheVersion++);let d=!1,f=0;if(l&&this.scrollOffset!==null){const[p,h]=l,m=this.getMeasurements(),{count:v,getItemKey:y}=this.options;let b=0;for(;b<v&&y(b)!==p;)b++;if(b<v){const x=m[b];if(x){const S=x.start+h;S!==this.scrollOffset&&(f=S-this.scrollOffset,this.scrollOffset=S,d=!0)}}}(d||c)&&(this.pendingScrollAnchor=[d?l[0]:null,d?l[1]:0,c,f])},this.notify=n=>{var r,s;(s=(r=this.options).onChange)==null||s.call(r,this,n)},this.maybeNotify=LE(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(a=>{this.observer.observe(a)}),this.unsubs.push(this.options.observeElementRect(this,a=>{this.scrollRect=a,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(a,i)=>{if(i&&this._intendedScrollOffset===null&&a===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(a-this._intendedScrollOffset)<1.5&&(a=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const l=this.getScrollOffset();this.scrollDirection=i?l===a?this.scrollDirection:l<a?"forward":"backward":null,this.scrollOffset=a,this.isScrolling=i,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const a=this.scrollElement,i=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},l=()=>{this._iosTouching=!1,!(!uie()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};a.addEventListener("touchstart",i,aV),a.addEventListener("touchend",l,aV),this.unsubs.push(()=>{a.removeEventListener("touchstart",i),a.removeEventListener("touchend",l),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const s=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,s&&this.scrollElement&&this.options.enabled){const[a,i,l,c]=s;a!==null&&!l&&(uie()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?c!==0&&(this._iosDeferredAdjustment+=c):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),l&&this.scrollToEnd({behavior:l})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;const s=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=s,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(n,r)=>{const s=new Map,a=new Map;for(let i=r-1;i>=0;i--){const l=n[i];if(s.has(l.lane))continue;const c=a.get(l.lane);if(c==null||l.end>c.end?a.set(l.lane,l):l.end<c.end&&s.set(l.lane,!0),s.size===this.options.lanes)break}return a.size===this.options.lanes?Array.from(a.values()).sort((i,l)=>i.end===l.end?i.index-l.index:i.end-l.end)[0]:void 0},this.getMeasurementOptions=LE(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(n,r,s,a,i,l,c)=>(this.prevLanes!==void 0&&this.prevLanes!==l&&(this.lanesChangedFlag=!0),this.prevLanes=l,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:s,getItemKey:a,enabled:i,lanes:l,laneAssignmentMode:c}),{key:!1}),this.getMeasurements=LE(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:s,getItemKey:a,enabled:i,lanes:l,laneAssignmentMode:c},u)=>{const d=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const m of this.laneAssignments.keys())m>=n&&this.laneAssignments.delete(m);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(m=>{this.itemSizeCache.set(m.key,m.size)}));const f=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),l===1){const m=this.options.gap,v=n*2;let y=this._flatMeasurements;if(!y||y.length<v){const S=new Float64Array(v);y&&f>0&&S.set(y.subarray(0,f*2)),y=S,this._flatMeasurements=y}let b;if(f===0)b=r+s;else{const S=f-1;b=y[S*2]+y[S*2+1]+m}for(let S=f;S<n;S++){const k=a(S),_=d.get(k),C=typeof _=="number"?_:this.options.estimateSize(S);y[S*2]=b,y[S*2+1]=C,b+=C+m}const x=dcs(n,y,a);return this.measurementsCache=x,x}const p=this.measurementsCache.slice(0,f),h=new Array(l).fill(void 0);for(let m=0;m<f;m++){const v=p[m];v&&(h[v.lane]=m)}for(let m=f;m<n;m++){const v=a(m),y=this.laneAssignments.get(m);let b,x;const S=c==="estimate"||d.has(v);if(y!==void 0&&this.options.lanes>1){b=y;const T=h[b],E=T!==void 0?p[T]:void 0;x=E?E.end+this.options.gap:r+s}else{const T=this.options.lanes===1?p[m-1]:this.getFurthestMeasurement(p,m);x=T?T.end+this.options.gap:r+s,b=T?T.lane:m%this.options.lanes,this.options.lanes>1&&S&&this.laneAssignments.set(m,b)}const k=d.get(v),_=typeof k=="number"?k:this.options.estimateSize(m),C=x+_;p[m]={index:m,start:x,size:_,end:C,key:v,lane:b},h[b]=m}return this.measurementsCache=p,p},{key:!1,debug:()=>this.options.debug}),this.calculateRange=LE(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,a)=>n.length===0||r===0?(this.range=null,null):(this.range=_cs(n,r,s,a,a===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=LE(()=>{let n=null,r=null;const s=this.calculateRange();return s&&(n=s.startIndex,r=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,s,a,i)=>a===null||i===null?[]:n({startIndex:a,endIndex:i,overscan:r,count:s}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,s=n.getAttribute(r);return s?parseInt(s,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const s=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(s!==void 0&&this.range){const a=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,s-a),l=Math.min(this.options.count-1,s+a);return n>=i&&n<=l}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((i,l)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(l))});return}const r=this.indexFromElement(n),s=this.options.getItemKey(r),a=this.elementsCache.get(s);a!==n&&(a&&this.observer.unobserve(a),this.observer.observe(n),this.elementsCache.set(s,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var s,a;if(n<0||n>=this.options.count)return;let i,l,c;const u=this._flatMeasurements;if(this.options.lanes===1&&u!==null)c=this.options.getItemKey(n),l=u[n*2],i=u[n*2+1];else{const p=this.measurementsCache[n];if(!p)return;c=p.key,l=p.start,i=p.size}const d=this.itemSizeCache.get(c)??i,f=r-d;if(f!==0){const p=this.options.anchorTo==="end"&&((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,h=p?this.getTotalSize():0,m=((a=this.scrollState)==null?void 0:a.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:c,start:l,size:i,end:l+i,lane:0},f,this):l<this.getScrollOffset()+this.scrollAdjustments&&(!this.itemSizeCache.has(c)||this.scrollDirection!=="backward"));(this.pendingMin===null||n<this.pendingMin)&&(this.pendingMin=n),this.itemSizeCache.set(c,r),this.itemSizeCacheVersion++,p?this.applyScrollAdjustment(this.getTotalSize()-h):m&&this.applyScrollAdjustment(f),this.notify(!1)}},this.getVirtualItems=LE(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let a=0,i=n.length;a<i;a++){const l=n[a],c=r[l];s.push(c)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const s=this._flatMeasurements,a=this.options.lanes===1&&s!=null,i=UUt(0,r.length-1,a?l=>s[l*2]:l=>net(r[l]).start,n);return net(r[i])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,s=0)=>{if(!this.scrollElement)return 0;const a=this.getSize(),i=this.getScrollOffset();r==="auto"&&(r=n>=i+a?"end":"start"),r==="center"?n+=(s-a)/2:r==="end"&&(n-=a);const l=this.getMaxScrollOffset();return Math.max(Math.min(l,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const s=this.getSize(),a=this.getScrollOffset(),i=this.measurementsCache[n];if(!i)return;if(r==="auto")if(i.end>=a+s-this.options.scrollPaddingEnd)r="end";else if(i.start<=a+this.options.scrollPaddingStart)r="start";else return[a,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const l=r==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,r,i.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:s="auto"}={})=>{const a=this.getOffsetForAlignment(n,r),i=this.now();this.scrollState={index:null,align:r,behavior:s,startedAt:i,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:s="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const a=this.getOffsetForIndex(n,r);if(!a)return;const[i,l]=a,c=this.now();this.scrollState={index:n,align:l,behavior:s,startedAt:c,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const s=this.getScrollOffset()+n,a=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:a,lastTargetOffset:s,stableFrames:0},this._scrollToOffset(s,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let s;if(r.length===0)s=this.options.paddingStart;else if(this.options.lanes===1){const a=r.length-1,i=this._flatMeasurements;i!=null?s=i[a*2]+i[a*2+1]:s=((n=r[a])==null?void 0:n.end)??0}else{const a=Array(this.options.lanes).fill(null);let i=r.length-1;for(;i>=0&&a.some(l=>l===null);){const l=r[i];a[l.lane]===null&&(a[l.lane]=l.end),i--}s=Math.max(...a.filter(l=>l!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const s of r)s&&this.itemSizeCache.has(s.key)&&n.push({index:s.index,key:s.key,start:s.start,size:s.size,end:s.end,lane:s.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:s})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:s,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(uie()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,s=r?r[0]:this.scrollState.lastTargetOffset,a=1,i=s!==this.scrollState.lastTargetOffset;if(!i&&fcs(s,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=a){this.getScrollOffset()!==s&&this._scrollToOffset(s,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,i){const l=this.getSize()||600,c=Math.abs(s-this.getScrollOffset()),u=this.scrollState.behavior==="smooth"&&c>l;this.scrollState.lastTargetOffset=s,u||(this.scrollState.behavior="auto"),this._scrollToOffset(s,{adjustments:void 0,behavior:u?"smooth":"auto"})}this.scheduleScrollReconcile()}}const UUt=(e,t,n,r)=>{for(;e<=t;){const s=(e+t)/2|0,a=n(s);if(a<r)e=s+1;else if(a>r)t=s-1;else return s}return e>0?e-1:0};function Ocs(e,t,n){let r=0;for(;r<=t;){const s=(r+t)/2|0,a=e[s*2];if(a<n)r=s+1;else if(a>n)t=s-1;else return s}return r>0?r-1:0}function _cs(e,t,n,r,s){const a=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:a};if(r===1&&s!==null){const u=Ocs(s,a,n);let d=u;const f=n+t;for(;d<a&&s[d*2]+s[d*2+1]<f;)d++;return{startIndex:u,endIndex:d}}let l=UUt(0,a,u=>e[u].start,n),c=l;if(r===1)for(;c<a&&e[c].end<n+t;)c++;else if(r>1){const u=Array(r).fill(0);for(;c<a&&u.some(f=>f<n+t);){const f=e[c];u[f.lane]=f.end,c++}const d=Array(r).fill(n+t);for(;l>=0&&d.some(f=>f>=n);){const f=e[l];d[f.lane]=f.start,l--}l=Math.max(0,l-l%r),c=Math.min(a,c+(r-1-c%r))}return{startIndex:l,endIndex:c}}const die=typeof document<"u"?g.useLayoutEffect:g.useEffect;function Ccs({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const s=g.useReducer(u=>u+1,0)[1],a=g.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});a.current.enabled=t,a.current.mode=n;const i=u=>{const d=a.current;if(!d.enabled||!d.container)return;const f=u.getTotalSize();if(f!==d.lastSize){d.lastSize=f;const b=u.options.horizontal?"width":"height";d.container.style[b]=`${f}px`}const p=!!u.options.horizontal,h=d.mode==="transform",m=p?"left":"top",v=u.options.scrollMargin,y=u.getVirtualItems();for(const b of y){const x=b.start-v,S=u.elementsCache.get(b.key);S&&d.lastPositions.get(S)!==x&&(d.lastPositions.set(S,x),h?S.style.transform=p?`translate3d(${x}px, 0, 0)`:`translate3d(0, ${x}px, 0)`:S.style[m]=`${x}px`)}},l={...r,onChange:(u,d)=>{var f;const p=a.current;let h=!0;if(p.enabled){i(u);const m=u.range,v=p.prevRange;h=!v||v.isScrolling!==u.isScrolling||v.startIndex!==m?.startIndex||v.endIndex!==m?.endIndex,h&&(p.prevRange=m?{startIndex:m.startIndex,endIndex:m.endIndex,isScrolling:u.isScrolling}:null)}h&&(e&&d?Ei.flushSync(s):s()),(f=r.onChange)==null||f.call(r,u,d)}},[c]=g.useState(()=>{const u=new kcs(l);return Object.assign(u,{containerRef:d=>{const f=a.current;if(f.container=d,f.lastSize=null,d&&f.enabled){const p=u.getTotalSize();f.lastSize=p;const h=u.options.horizontal?"width":"height";d.style[h]=`${p}px`}}})});return c.setOptions(l),die(()=>c._didMount(),[]),die(()=>c._willUpdate()),die(()=>{i(c)}),c}function qUt(e){return Ccs({observeElementRect:gcs,observeElementOffset:bcs,scrollToFn:Scs,...e})}const Ecs=["input","entity","duration","inputTokens","outputTokens","estimatedCost"],VUt=["inputTokens","outputTokens","estimatedCost"],$w={visibleColumns:["input","entity"],metadataKeys:[]},HUt=1,Tcs=new Set(Ecs),jcs=new Set(VUt);function Ncs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ics(e){return typeof e=="string"&&Tcs.has(e)}function Acs(e){if(!Array.isArray(e))return[];const t=e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);return[...new Set(t)]}function Rcs(e){if(!e)return $w;try{const t=JSON.parse(e);return!Ncs(t)||t.version!==HUt?$w:{visibleColumns:Array.isArray(t.visibleColumns)?[...new Set(t.visibleColumns.filter(Ics))]:[...$w.visibleColumns],metadataKeys:Acs(t.metadataKeys)}}catch{return $w}}function Pcs(e){return JSON.stringify({version:HUt,visibleColumns:e.visibleColumns,metadataKeys:e.metadataKeys})}function $cs(e){const t=new Set(e.visibleColumns),n=["11rem",t.has("input")?"14rem":"minmax(8rem,1fr)"];t.has("input")&&n.push("minmax(8rem,1fr)"),t.has("entity")&&n.push("14rem"),n.push("6rem"),t.has("duration")&&n.push("7rem"),t.has("inputTokens")&&n.push("8rem"),t.has("outputTokens")&&n.push("8rem"),t.has("estimatedCost")&&n.push("8rem");for(const r of e.metadataKeys)n.push("minmax(8rem,14rem)");return n.join(" ")}function Mcs(e,t){if(!e||!Object.prototype.hasOwnProperty.call(e,t))return;const n=e[t];if(n!=null){if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean"||typeof n=="bigint")return String(n);try{return JSON.stringify(n)??void 0}catch{return}}}function Th(e,t){return e.visibleColumns.includes(t)}function Dcs(e){return e.visibleColumns.some(WUt)}function WUt(e){return jcs.has(e)}function zD(e){if(e==null)return;const t=e instanceof Date?e.getTime():new Date(e).getTime();return Number.isFinite(t)?t:void 0}function ZUt(e,t){const n=zD(e),r=zD(t);if(!(n===void 0||r===void 0||r<n))return r-n}function OQ(e,t){const n=ZUt(e,t);if(n!==void 0)return n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`}function Lcs(e,t){const n=ZUt(e,t);if(n!==void 0)return n<1e3?`${n}ms`:`${n/1e3}s`}function Fcs(e){const t=zD(e);return t===void 0?void 0:hr(new Date(t),"h:mm:ss a")}function zcs(e){const t=zD(e);return t===void 0?void 0:hr(new Date(t),"MMM d, yyyy, h:mm:ss.SSS a")}function iV(e){const t=zD(e);return t===void 0?void 0:hr(new Date(t),"MMM dd, h:mm:ss.SSS aaa")}function Bcs(e,t=100){if(e==null)return"";const n=Array.isArray(e)?e:e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.messages)?e.messages:null;if(n){const i=n.filter(l=>l?.role==="user").map(l=>typeof l.content=="string"?l.content:Array.isArray(l.content)?l.content.map(c=>typeof c=="string"?c:c?.type==="text"&&typeof c.text=="string"?c.text:"").filter(Boolean).join(" "):"").filter(Boolean).join(" | ");return i.length>t?i.slice(0,t)+"…":i}if(typeof e=="string")return e.length>t?e.slice(0,t)+"…":e;const r=JSON.stringify(e);return r.length>t?r.slice(0,t)+"…":r}function Ucs(e){return e?.attributes?.finishReason==="length"}function qcs(e){const t=e?.attributes?.usage;if(!t)return"The model stopped generating because it reached the maximum token limit. The response was truncated and may be incomplete.";const n=t.inputTokens??0,r=t.outputTokens??0,s=t.totalTokens??n+r;return n>0||r>0?`The model stopped generating because it reached the maximum token limit. The response was truncated and may be incomplete.
|
|
626
626
|
|
|
627
|
-
Token usage: ${n} input + ${r} output = ${s} total`:`The model stopped generating because it reached the maximum token limit (${s} tokens). The response was truncated and may be incomplete.`}function nl(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString()}function Vp(e,t){return t?.toLowerCase()==="usd"||!t?`$${e<.01&&e>0?e.toFixed(4):e.toFixed(2)}`:`${e.toFixed(4)} ${t}`}const Rxe={className:"max-h-80",mask:{left:!1},stickyHeaderBackground:"tinted"},Hp={orange:"#fb923c",pink:"#f472b6",purple:"#8b5cf6",blue:"#4f83f1",blueDark:"#2b5cd9",yellow:"#facc15"},Vcs=36,Hcs=8;function GUt({traces:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,filtersApplied:a,featuredTraceId:i,featuredSpanId:l,isBranchesMode:c,recentlyAddedKeys:u,columnPreferences:d=$w,usageByTraceId:f,onTraceClick:p}){const h=g.useRef(null),m=$cs(d),v=qUt({count:e.length,getScrollElement:()=>h.current,estimateSize:()=>Vcs,overscan:Hcs}),{getRowProps:y}=wo({count:e.length,containerRef:h,onNavigate:C=>v.scrollToIndex(C)}),b=g.useRef(t);if(g.useEffect(()=>{b.current&&!t&&h.current?.dispatchEvent(new Event("scroll")),b.current=t},[t]),t)return o.jsx(Pl,{columns:m,fit:"container"});const x=v.getVirtualItems(),S=v.getTotalSize(),k=x[0]?.start??0,_=x.length>0?Math.max(0,S-(x[x.length-1]?.end??0)):0;return o.jsxs(Go,{columns:m,variant:"striped",fit:"container",scrollRef:h,className:"min-w-0",children:[o.jsxs(Go.Top,{children:[o.jsx(Go.TopCell,{children:"Created"}),o.jsx(Go.TopCell,{children:"Name"}),Th(d,"input")&&o.jsx(Go.TopCell,{children:"Input"}),Th(d,"entity")&&o.jsx(Go.TopCell,{children:"Entity"}),o.jsx(Go.TopCell,{children:"Status"}),Th(d,"duration")&&o.jsx(Go.TopCell,{className:"justify-end text-right",children:"Duration"}),Th(d,"inputTokens")&&o.jsx(Go.TopCell,{className:"justify-end text-right",children:"Input tokens"}),Th(d,"outputTokens")&&o.jsx(Go.TopCell,{className:"justify-end text-right",children:"Output tokens"}),Th(d,"estimatedCost")&&o.jsx(Go.TopCell,{className:"justify-end text-right",children:"Est. cost"}),d.metadataKeys.map(C=>o.jsx(Go.TopCellWithTooltip,{tooltip:C,children:C},C))]}),e.length===0?o.jsx(Go.NoMatch,{message:a?"No traces found for applied filters":"No traces found yet"}):o.jsxs(o.Fragment,{children:[o.jsx(Go.Spacer,{height:k}),x.map(C=>{const T=e[C.index];if(!T)return null;const E=T.traceId===i&&(l==null||T.spanId===l),N=`${T.traceId}:${T.spanId??""}`,I=u?.has(N)??!1,A=T.startedAt??T.createdAt,R=T.entityName||T.entityId,L=f?.get(T.traceId);return o.jsxs(Go.RowButton,{ref:v.measureElement,"data-index":C.index,...y(C.index),onClick:()=>p(T),featured:E,className:K(I&&"animate-row-highlight"),children:[o.jsx(Go.CreatedCell,{timestamp:A}),o.jsx(Go.NameCell,{name:T.name,parentSpanId:T.parentSpanId,showLevelTooltip:c}),Th(d,"input")&&o.jsx(Go.InputCell,{input:T.inputPreview??Bcs(T.input)}),Th(d,"entity")&&o.jsx(Go.EntityCell,{entityType:T.entityType,entityName:R}),o.jsx(Go.StatusCell,{status:T.status}),Th(d,"duration")&&o.jsx(be.NumberCell,{children:OQ(T.startedAt,T.endedAt)}),Th(d,"inputTokens")&&o.jsx(be.NumberCell,{children:L?.inputTokens===void 0?void 0:nl(L.inputTokens)}),Th(d,"outputTokens")&&o.jsx(be.NumberCell,{children:L?.outputTokens===void 0?void 0:nl(L.outputTokens)}),Th(d,"estimatedCost")&&o.jsx(be.NumberCell,{children:L?.estimatedCost===void 0?void 0:Vp(L.estimatedCost,L.costUnit)}),d.metadataKeys.map(D=>{const F=Mcs(T.metadata,D);return o.jsx(be.TextCell,{font:"mono",children:F},D)})]},N)}),o.jsx(Go.Spacer,{height:_}),o.jsx(Go.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})]})}function QUt(e,t,n,r){const s=g.useMemo(()=>t?e.findIndex(u=>u.traceId===t&&(n==null||u.spanId===n)):-1,[e,t,n]),a=n!=null,i=u=>r(u.traceId,a?u.spanId??void 0:void 0),l=s>0?()=>{const u=e[s-1];u&&i(u)}:void 0,c=s>=0&&s<e.length-1?()=>{const u=e[s+1];u&&i(u)}:void 0;return{featuredTraceIdx:s,handlePreviousTrace:l,handleNextTrace:c}}function Wcs(e){const t=[];return lw(e,t,new Set),t.join(" ")}function lw(e,t,n){if(e==null)return;switch(typeof e){case"string":{const s=e.trim();s&&t.push(s);return}case"number":{Number.isFinite(e)&&t.push(String(e));return}case"boolean":case"bigint":t.push(String(e));return;case"function":case"symbol":return}const r=e;if(!n.has(r)){n.add(r);try{Zcs(r,t,n)}finally{n.delete(r)}}}function Zcs(e,t,n){if(e instanceof Date){const r=e.getTime();Number.isNaN(r)||t.push(e.toISOString());return}if(e instanceof Error){lw(e.message,t,n);return}if(Array.isArray(e)){for(const r of e)lw(r,t,n);return}if(e instanceof Map){for(const[r,s]of e)lw(r,t,n),lw(s,t,n);return}if(e instanceof Set){for(const r of e)lw(r,t,n);return}for(const r of Object.keys(e)){lw(r,t,n);let s;try{s=e[r]}catch{continue}lw(s,t,n)}}function Gcs(e){return e.map(t=>({...t,searchText:Wcs(t).toLowerCase()}))}function uAe(e){return e?{...e,spans:Gcs(e.spans)}:null}const Qcs=1e3*60*60*24*30;function Ycs({traceId:e,spanId:t,depth:n}){const r=Qe();return yt({queryKey:["branch",e,t,n],queryFn:async()=>{if(!e||!t)throw new Error("traceId and spanId are required");return r.getBranch({traceId:e,spanId:t,depth:n})},select:uAe,enabled:!!e&&!!t,staleTime:s=>s.state.data?.spans.every(l=>!!l.endedAt)?Qcs:0})}const Kcs=1e3*60*60*24*30;function YUt(e){const t=Qe();return yt({queryKey:["trace-spans",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return await t.getTrace(e)},select:uAe,enabled:!!e,staleTime:n=>n.state.data?.spans.every(a=>!!a.endedAt)?Kcs:0})}function KUt({traceId:e,anchorSpanId:t,listMode:n,depth:r}){const s=n==="branches",a=YUt(s?null:e),i=Ycs({traceId:s?e:null,spanId:s?t:null,depth:r});return s?{spans:i.data?.spans,anchorSpanId:t??void 0,isLoading:i.isLoading,isError:i.isError,error:i.error}:{spans:a.data?.spans,anchorSpanId:void 0,isLoading:a.isLoading,isError:a.isError,error:a.error}}const fie=new WeakMap,pie=new WeakMap,hie=new WeakMap,Xcs=1e4,sw={deltaPollIntervalMs:5e3,deltaChaseIntervalMs:100,deltaLimit:100,pageModeRefetchIntervalMs:1e4,page0StatusRefreshIntervalMs:6e4,idleGuardThresholdMs:15*6e4,minRefetchSpinMs:400,deltaHighlightMs:1e3};function Jcs(e,t,n){return e===0?!1:t-e>n}function eus(e){return e?.status===501}function tus(e){const t=e?.status;return t===404||t===500?t:void 0}function nus(e,t,n){return e===404?!0:e!==500||t===void 0?!1:n-t>=Xcs}const mie=async e=>{const{client:t,filters:n,listMode:r="traces"}=e,s=e.mode==="delta"?{mode:"delta",after:e.after,limit:e.limit,filters:n}:{pagination:{page:e.page,perPage:e.perPage},filters:n};if(r==="branches")return t.listBranches(s);if(pie.get(t)==="unsupported")return t.listTraces(s);try{const a=await t.listTracesLight(s);if(e.mode!=="delta"){const i=a.spans??[];if(i.length>0&&i.every(l=>l.status===void 0))return pie.set(t,"unsupported"),t.listTraces(s)}return hie.delete(t),a}catch(a){const i=tus(a);if(i===void 0)throw a;const l=Date.now(),c=hie.get(t);return i===500&&c===void 0&&hie.set(t,l),nus(i,c,l)&&pie.set(t,"unsupported"),t.listTraces(s)}},set=25;function rus(e,t,n){if(e?.pagination?.hasMore)return n+1}function sus(e){return"branches"in e?e.branches??[]:e.spans??[]}function aus(e){const t=new Set;return{spans:e.pages.flatMap(r=>sus(r)).filter(r=>{const s=`${r.traceId}:${r.spanId}`;return t.has(s)?!1:(t.add(s),!0)}),deltaCursor:e.pages[0]?.deltaCursor}}function Pxe(e){return`${e.traceId}:${e.spanId}`}function aet(e){return new Map(e.map(t=>[Pxe(t),t]))}function ius(e,t,n){if(!e||e.pages.length===0)return e;const[r,...s]=e.pages;if(!r)return e;let a;if(n==="branches"&&"branches"in r&&"branches"in t){const i=aet(t.branches??[]);if(i.size===0)return e;a={...r,branches:(r.branches??[]).map(l=>i.get(Pxe(l))??l)}}else if("spans"in r&&"spans"in t){const i=aet(t.spans??[]);if(i.size===0)return e;a={...r,spans:(r.spans??[]).map(l=>i.get(Pxe(l))??l)}}else return e;return{...e,pages:[a,...s]}}function iet(e){return[...e].sort((t,n)=>{const r=t.startedAt?new Date(t.startedAt).getTime():0;return(n.startedAt?new Date(n.startedAt).getTime():0)-r})}function ous(e,t,n){if(!e||e.pages.length===0)return e;const[r,...s]=e.pages;if(!r)return e;const a=t.deltaCursor??r.deltaCursor;let i;if(n==="branches"&&"branches"in r){const l=t.branches??[];i={...r,branches:iet([...l,...r.branches??[]]),deltaCursor:a}}else if("spans"in r){const l=t.spans??[];i={...r,spans:iet([...l,...r.spans??[]]),deltaCursor:a}}else return e;return{...e,pages:[i,...s]}}const XUt=({filters:e,listMode:t="traces",polling:n={}})=>{const{deltaPollIntervalMs:r=sw.deltaPollIntervalMs,deltaChaseIntervalMs:s=sw.deltaChaseIntervalMs,deltaLimit:a=sw.deltaLimit,pageModeRefetchIntervalMs:i=sw.pageModeRefetchIntervalMs,page0StatusRefreshIntervalMs:l=sw.page0StatusRefreshIntervalMs,idleGuardThresholdMs:c=sw.idleGuardThresholdMs,minRefetchSpinMs:u=sw.minRefetchSpinMs,deltaHighlightMs:d=sw.deltaHighlightMs}=n,f=Qe(),p=Lr(),{inView:h,setRef:m}=tC(),[v,y]=g.useState(()=>fie.get(f)??"unknown"),b=v==="unsupported",[x,S]=g.useState(!0),[k,_]=g.useState(()=>new Set);g.useEffect(()=>{_(new Set)},[t,e]);const C=["traces",t,e],T=K1({queryKey:C,queryFn:({pageParam:U})=>mie({client:f,page:U,perPage:set,filters:e,listMode:t}),initialPageParam:0,getNextPageParam:rus,select:aus,retry:!1,refetchInterval:U=>ks(U.state.error)||!x?!1:b?i:!1}),E=T.data?.deltaCursor;g.useEffect(()=>{T.isSuccess&&E===void 0&&v==="unknown"&&(fie.set(f,"unsupported"),y("unsupported"))},[T.isSuccess,E,v,f]);const N=yt({queryKey:["traces-delta",t,e],queryFn:()=>{const U=p.getQueryData(C)?.pages[0]?.deltaCursor;return U?mie({client:f,mode:"delta",after:U,limit:a,filters:e,listMode:t}):null},enabled:!!E&&!b&&x,retry:!1,refetchInterval:U=>U.state.error?!1:U.state.data?.delta?.hasMore?s:r});g.useEffect(()=>{const U=N.data;if(!U)return;p.setQueryData(C,Z=>ous(Z,U,t));const $=t==="branches"&&"branches"in U?U.branches??[]:"spans"in U?U.spans??[]:[];if($.length===0)return;const q=$.map(Z=>`${Z.traceId}:${Z.spanId??""}`);_(Z=>{const Y=new Set(Z);for(const ne of q)Y.add(ne);return Y}),setTimeout(()=>{_(Z=>{const Y=new Set(Z);for(const ne of q)Y.delete(ne);return Y})},d)},[N.data,p,t,e,d]),g.useEffect(()=>{eus(N.error)&&(fie.set(f,"unsupported"),y("unsupported"))},[N.error,f]);const I=yt({queryKey:["traces-status-refresh",t,e],queryFn:()=>mie({client:f,page:0,perPage:set,filters:e,listMode:t}),enabled:!!E&&!b&&x,refetchInterval:l,refetchOnMount:!1,retry:!1});g.useEffect(()=>{const U=I.data;U&&p.setQueryData(C,$=>ius($,U,t))},[I.data,p,t,e]);const A=g.useRef(0);g.useEffect(()=>{const U=Math.max(T.dataUpdatedAt,N.dataUpdatedAt,I.dataUpdatedAt);U>A.current&&(A.current=U)},[T.dataUpdatedAt,N.dataUpdatedAt,I.dataUpdatedAt]);const R=g.useRef(x);g.useEffect(()=>{R.current=x},[x]),g.useEffect(()=>{const U=()=>{document.visibilityState==="visible"&&R.current&&Jcs(A.current,Date.now(),c)&&p.resetQueries({queryKey:["traces",t,e]})};return document.addEventListener("visibilitychange",U),()=>document.removeEventListener("visibilitychange",U)},[p,t,e,c]);const{hasNextPage:L,isFetchingNextPage:D,fetchNextPage:F}=T;g.useEffect(()=>{h&&L&&!D&&F()},[h,L,D,F]);const H=T.isFetching||I.isFetching||N.isFetching,B=Math.max(T.dataUpdatedAt,T.errorUpdatedAt,N.dataUpdatedAt,N.errorUpdatedAt,I.dataUpdatedAt,I.errorUpdatedAt),[z,V]=g.useState(!1),M=g.useRef(B);return g.useEffect(()=>{if(B>M.current){M.current=B,V(!0);const U=setTimeout(()=>V(!1),u);return()=>clearTimeout(U)}},[B,u]),{...T,setEndOfListElement:m,isRefetching:H||z,autoRefetch:x,setAutoRefetch:S,recentlyAddedKeys:k}};function oet(e){return!!e&&Object.values(e).some(t=>typeof t=="number")}function lus(e){if(!e)return null;const t=typeof e.inputTokens=="number",n=typeof e.outputTokens=="number";if(!t&&!n)return null;const r=e.inputTokens??0,s=e.outputTokens??0,a=r+s,i=a>0;return{inputValue:r,outputValue:s,total:a,showSplit:i,inputPct:i?r/a*100:0,outputPct:i?s/a*100:0,inputDetails:t&&oet(e.inputDetails)?e.inputDetails:void 0,outputDetails:n&&oet(e.outputDetails)?e.outputDetails:void 0}}const cus={text:"Text",cacheRead:"Cache read",cacheWrite:"Cache write",audio:"Audio",image:"Image",reasoning:"Reasoning"},cet="oklch(0.78 0.16 320)",uet="oklch(0.55 0.18 320)";function uus({usage:e,className:t}){const n=lus(e);if(!n)return null;const{inputValue:r,outputValue:s,total:a,showSplit:i,inputPct:l,outputPct:c,inputDetails:u,outputDetails:d}=n;return o.jsxs("div",{className:K("mt-2 mb-8 grid grid-cols-1 border-b border-border1 pb-3 4xl:grid-cols-2 4xl:gap-12",t),children:[i&&o.jsxs("div",{className:"mb-2",children:[o.jsxs("div",{className:"text-neutral2 flex items-baseline gap-3",children:[o.jsx("span",{className:"text-ui-md",children:"Tokens Used"}),o.jsx("span",{className:"text-ui-md text-neutral4 font-semibold",children:a.toLocaleString()}),o.jsxs("span",{className:"text-ui-sm ml-auto",children:[Math.round(l),"% Input vs ",Math.round(c),"% Output"]})]}),o.jsx("div",{className:"bg-surface4 mt-2 rounded-md p-1.5",children:o.jsxs("div",{className:"relative h-1.5 w-full overflow-hidden rounded-sm",children:[o.jsx("div",{className:"absolute top-0 left-0 h-1.5",style:{width:`${l}%`,backgroundColor:cet}}),o.jsx("div",{className:"absolute top-0 h-1.5",style:{left:`${l}%`,width:`${c}%`,backgroundColor:uet}})]})})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[o.jsx(det,{label:"Input",color:cet,value:r,details:u}),o.jsx(det,{label:"Output",color:uet,value:s,details:d})]})]})}function det({label:e,color:t,value:n,details:r}){return o.jsxs("div",{children:[o.jsxs("div",{className:"text-neutral2 mb-2 flex items-baseline gap-3",children:[o.jsx("span",{className:"text-ui-md",children:e}),typeof n=="number"&&o.jsxs("span",{className:"flex items-baseline gap-1.5",children:[o.jsx("span",{className:"text-ui-md text-neutral4 font-semibold",children:n.toLocaleString()}),o.jsx("span",{className:"size-2 self-center rounded-full",style:{backgroundColor:t}})]})]}),r&&o.jsx(dus,{details:r})]})}function dus({details:e}){return o.jsx(_n,{density:"dense",children:Object.entries(e).map(([t,n])=>typeof n!="number"?null:o.jsxs(g.Fragment,{children:[o.jsx(_n.Key,{children:cus[t]||t}),o.jsx(_n.Value,{className:"text-right",children:n.toLocaleString()})]},t))})}function qz(e,t,n){return o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"text-neutral2 flex items-center gap-1.5 tracking-widest uppercase [&>svg]:size-3.5",children:[t,e]}),o.jsxs("span",{children:["› Span ",o.jsxs("b",{className:"text-neutral3",children:["#",n.spanId]})]}),o.jsxs("span",{children:["› Trace ",o.jsxs("b",{className:"text-neutral3",children:["#",n.traceId]})]})]})}function JUt({traceId:e,spanId:t,span:n,isLoading:r,onClose:s,onPrevious:a,onNext:i,activeTab:l,onTabChange:c,feedbackTabSlot:u,feedbackTabBadge:d,isAnchor:f,className:p}){return o.jsxs(fn,{className:p,children:[o.jsxs(fn.Header,{children:[o.jsxs(fn.Heading,{children:["Span ",o.jsxs("b",{children:["# ",t]})]}),o.jsxs(hs,{className:"ml-auto shrink-0",children:[o.jsx(fn.NextPrevNav,{onPrevious:a,onNext:i,previousLabel:"Previous span",nextLabel:"Next span"}),o.jsx(fn.CloseButton,{onClick:s})]})]}),r?o.jsx(fn.LoadingData,{children:"Loading span details..."}):n?o.jsx(fus,{span:n,traceId:e,spanId:t,activeTab:l,onTabChange:c,feedbackTabSlot:u,feedbackTabBadge:d,isAnchor:f}):o.jsx(fn.NoData,{children:"Span not found."})]})}function fus({span:e,traceId:t,spanId:n,activeTab:r,onTabChange:s,feedbackTabSlot:a,feedbackTabBadge:i,isAnchor:l}){const c=OQ(e.startedAt,e.endedAt),u=iV(e.startedAt),d=iV(e.endedAt),f=e.attributes?.usage,p=o.jsxs(o.Fragment,{children:[Ucs(e)&&o.jsx("div",{className:"mb-3",children:o.jsx(Wn,{variant:"warning",title:"Token Limit Exceeded",children:o.jsx(Wn.Message,{children:qcs(e)})})}),f&&o.jsx(uus,{usage:f,className:"mb-3"}),o.jsxs(_n,{children:[(l??e.parentSpanId==null)&&o.jsxs(o.Fragment,{children:[e.traceId&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Trace Id"}),o.jsx(_n.ValueWithCopyBtn,{copyTooltip:"Copy Trace Id to clipboard",copyValue:e.traceId,children:e.traceId})]}),e.tags&&e.tags.length>0&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Tags"}),o.jsx(_n.Value,{children:e.tags.join(", ")})]}),e.runId&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Run Id"}),o.jsx(_n.ValueWithCopyBtn,{copyTooltip:"Copy Run Id to clipboard",copyValue:e.runId,children:e.runId})]}),e.threadId&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Thread Id"}),o.jsx(_n.ValueWithCopyBtn,{copyTooltip:"Copy Thread Id to clipboard",copyValue:e.threadId,children:e.threadId})]}),e.sessionId&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Session Id"}),o.jsx(_n.ValueWithCopyBtn,{copyTooltip:"Copy Session Id to clipboard",copyValue:e.sessionId,children:e.sessionId})]}),e.requestId&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Request Id"}),o.jsx(_n.ValueWithCopyBtn,{copyTooltip:"Copy Request Id to clipboard",copyValue:e.requestId,children:e.requestId})]}),e.resourceId&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Resource Id"}),o.jsx(_n.ValueWithCopyBtn,{copyTooltip:"Copy Resource Id to clipboard",copyValue:e.resourceId,children:e.resourceId})]}),e.userId&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"User Id"}),o.jsx(_n.ValueWithCopyBtn,{copyTooltip:"Copy User Id to clipboard",copyValue:e.userId,children:e.userId})]}),e.organizationId&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Organization Id"}),o.jsx(_n.ValueWithCopyBtn,{copyTooltip:"Copy Organization Id to clipboard",copyValue:e.organizationId,children:e.organizationId})]}),e.experimentId&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Experiment Id"}),o.jsx(_n.ValueWithCopyBtn,{copyTooltip:"Copy Experiment Id to clipboard",copyValue:e.experimentId,children:e.experimentId})]})]}),e.name&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Name"}),o.jsx(_n.Value,{children:e.name})]}),e.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Type"}),o.jsx(_n.Value,{children:e.spanType})]}),u&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Started"}),o.jsx(_n.Value,{children:u})]}),d&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Ended"}),o.jsx(_n.Value,{children:d})]}),c&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Duration"}),o.jsx(_n.Value,{children:c})]})]}),o.jsxs("div",{className:"mt-3 grid gap-3",children:[o.jsx(fn.CodeSection,{title:"Input",dialogTitle:qz("Input",o.jsx(xx,{}),{spanId:n,traceId:t}),icon:o.jsx(xx,{}),codeStr:JSON.stringify(e.input??null,null,2)}),o.jsx(fn.CodeSection,{title:"Output",dialogTitle:qz("Output",o.jsx(em,{}),{spanId:n,traceId:t}),icon:o.jsx(em,{}),codeStr:JSON.stringify(e.output??null,null,2)}),o.jsx(fn.CodeSection,{title:"Metadata",dialogTitle:qz("Metadata",o.jsx(Jl,{}),{spanId:n,traceId:t}),icon:o.jsx(Jl,{}),codeStr:JSON.stringify(e.metadata??null,null,2)}),o.jsx(fn.CodeSection,{title:"Attributes",dialogTitle:qz("Attributes",o.jsx(Jl,{}),{spanId:n,traceId:t}),icon:o.jsx(Jl,{}),codeStr:JSON.stringify(e.attributes??null,null,2)})]})]});return a?o.jsx(fn.Content,{children:o.jsxs(yc,{defaultTab:"details",value:r,onValueChange:s,children:[o.jsxs(vc,{variant:"pill-ghost",className:"px-0",children:[o.jsx(Ar,{value:"details",children:"Details"}),o.jsxs(Ar,{value:"feedback",children:["Feedback ",i!=null&&o.jsxs(o.Fragment,{children:["(",i,")"]})]})]}),o.jsx(fs,{value:"details",children:p}),o.jsx(fs,{value:"feedback",children:a({span:e,traceId:t,spanId:n})})]})}):o.jsx(fn.Content,{children:p})}const pus=1e3*60*60*24*30;function _Q(e,t){const n=Qe();return yt({queryKey:["span-detail",e,t],queryFn:async()=>{if(!e||!t)throw new Error("Trace ID and Span ID are required");return n.getSpan(e,t)},enabled:!!e&&!!t,staleTime:r=>r.state.data?.span?.endedAt?pus:0})}const dAe=(e,t)=>{if(!e||e.length===0)return[];const n=e.reduce((u,d)=>{const f=d?.endedAt?new Date(d.endedAt):void 0;return f&&(!u||f>u)?f:u},null),r=new Map,s=[];e.forEach(u=>{const d=new Date(u.startedAt),f=u.endedAt?new Date(u.endedAt):void 0,p={id:u.spanId,name:u.name,type:u.spanType,latency:f?f.getTime()-d.getTime():0,startTime:d.toISOString(),endTime:f?f.toISOString():void 0,spans:[],parentSpanId:u.parentSpanId,matchedInPayloadOnly:u.matchedInPayloadOnly};r.set(u.spanId,p)});const a=u=>t?u.spanId===t:u?.parentSpanId==null;e.forEach(u=>{const d=r.get(u.spanId);if(d)if(a(u)){if(n&&d.endTime&&n>new Date(d.endTime)){d.endTime=n.toISOString();const f=new Date(n).getTime(),p=new Date(d.startTime).getTime();d.latency=f-p}s.push(d)}else{const f=u.parentSpanId?r.get(u.parentSpanId):void 0;f?(f.spans??=[],f.spans.push(d)):s.push(d)}});const i=u=>u.sort((d,f)=>new Date(d.startTime).getTime()-new Date(f.startTime).getTime()),l=i(s),c=u=>{u.forEach(d=>{d.spans&&d.spans.length>0&&(d.spans=i(d.spans),c(d.spans))})};return c(l),l};function oV(e){if(!e.spans||e.spans.length===0)return[];const t=[];return e.spans.forEach(n=>{t.push(n.id),t.push(...oV(n))}),t}function fAe(e){const t=[];for(const n of e)t.push(n.id),t.push(...oV(n));return t}function eqt(e,t,n){const r=g.useMemo(()=>fAe(dAe(e??[])),[e]),s=t?r.indexOf(t):-1,a=s>0?()=>{const l=r[s-1];l!==void 0&&n(l)}:void 0,i=s>=0&&s<r.length-1?()=>{const l=r[s+1];l!==void 0&&n(l)}:void 0;return{handlePreviousSpan:a,handleNextSpan:i,timelineSpanIds:r}}function hus(){const e=Qe(),[t,n]=g.useState(!1);return{download:s=>{if(t)return;n(!0);const a=e.getTrace(s).then(i=>QUr(`trace-${s}.json`,i)).finally(()=>n(!1));Be.promise({myPromise:a,loadingMessage:"Preparing trace download…",successMessage:"Trace downloaded",errorMessage:"Failed to download trace"})},isPending:t}}function mus(e,t){if(!e||e.length===0)return[];const n=new Map,r=new Map,s=[];for(const l of e)if(l){if(n.set(l.spanId,l),l.parentSpanId){const c=r.get(l.parentSpanId);c?c.push(l):r.set(l.parentSpanId,[l])}t(l)&&s.push(l)}if(s.length===0)return[];const a=new Set,i=[...s];for(;i.length>0;){const l=i.pop();if(!l||a.has(l.spanId))continue;a.add(l.spanId);const c=r.get(l.spanId);c&&i.push(...c)}for(const l of s){let c=l.parentSpanId;for(;c&&!a.has(c);){const u=n.get(c);if(!u)break;a.add(u.spanId),c=u.parentSpanId}}return e.filter(l=>l&&a.has(l.spanId))}function gus(e){const[t,n]=g.useState(""),r=g.useDeferredValue(t),{results:s,payloadOnlyMatchIds:a}=g.useMemo(()=>{const i=r.trim().toLowerCase();if(!i)return{results:e,payloadOnlyMatchIds:new Set};const l=new Set;return{results:mus(e,u=>u.searchText.includes(i)?(u.name.toLowerCase().includes(i)||l.add(u.spanId),!0):!1),payloadOnlyMatchIds:l}},[e,r]);return{query:t,setQuery:n,results:s,payloadOnlyMatchIds:a,isPending:t!==r}}function vus(e){return e.split("_").map(t=>`${t.charAt(0).toUpperCase()}${t.slice(1)}`).join(" ")}function xP({label:e,children:t}){return o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:o.jsx("span",{tabIndex:0,className:"flex shrink-0 cursor-help items-center gap-1 whitespace-nowrap","aria-label":e,children:t})}),o.jsx(vn,{children:e})]})}function yus({rootSpan:e,usage:t,entityHref:n,LinkComponent:r,className:s}){const a=e.startedAt?new Date(e.startedAt):null,i=e.endedAt?new Date(e.endedAt):null,l=OQ(a,i),c=Lcs(a,i),u=Fcs(a),d=zcs(a),f=e.entityName||e.entityId,p=e.entityType,h=p?vus(p):"Entity",m=p?.includes("workflow")?Uc:Ti,v=r??"a";return o.jsxs("div",{className:K("flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-ui-xs leading-ui-xs text-neutral3",s),children:[f&&o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:n?o.jsxs(v,{href:n,className:"text-neutral4 hover:text-neutral5 flex shrink-0 items-center gap-1 whitespace-nowrap hover:underline",children:[o.jsx(m,{className:"size-3.5 shrink-0","aria-hidden":"true"}),o.jsx("span",{children:f}),o.jsx(Yr,{className:"size-3 shrink-0","aria-hidden":"true"})]}):o.jsxs("span",{tabIndex:0,className:"flex shrink-0 cursor-help items-center gap-1 whitespace-nowrap",children:[o.jsx(m,{className:"size-3.5 shrink-0","aria-hidden":"true"}),o.jsx("span",{children:f})]})}),o.jsx(vn,{children:h})]}),u&&d&&o.jsxs(xP,{label:`Started at ${d}`,children:[o.jsx(KN,{className:"size-3.5 shrink-0","aria-hidden":"true"}),o.jsx("span",{children:u})]}),l&&c&&o.jsxs(xP,{label:`Duration ${c}`,children:[o.jsx(Ipe,{className:"size-3.5 shrink-0","aria-hidden":"true"}),o.jsx("span",{children:l})]}),t&&o.jsxs(o.Fragment,{children:[o.jsxs(xP,{label:"Input tokens",children:[o.jsx(RGt,{className:"size-3.5 shrink-0","aria-hidden":"true"}),o.jsx("span",{children:t.inputTokens===void 0?"—":nl(t.inputTokens)})]}),o.jsxs(xP,{label:"Output tokens",children:[o.jsx(FGt,{className:"size-3.5 shrink-0","aria-hidden":"true"}),o.jsx("span",{children:t.outputTokens===void 0?"—":nl(t.outputTokens)})]}),o.jsxs(xP,{label:"Estimated cost",children:[o.jsx(AQt,{className:"size-3.5 shrink-0","aria-hidden":"true"}),o.jsx("span",{children:t.estimatedCost===void 0?"—":Vp(t.estimatedCost,t.costUnit)})]})]})]})}const tqt=e=>o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:o.jsx("path",{d:"M1.5 8.5V8C1.5 7.60218 1.65804 7.22064 1.93934 6.93934C2.22064 6.65804 2.60218 6.5 3 6.5H13C13.3978 6.5 13.7794 6.65804 14.0607 6.93934C14.342 7.22064 14.5 7.60218 14.5 8V8.5M8.70667 4.20667L7.29333 2.79333C7.20048 2.70037 7.09022 2.62661 6.96886 2.57628C6.84749 2.52595 6.71739 2.50003 6.586 2.5H3C2.60218 2.5 2.22064 2.65804 1.93934 2.93934C1.65804 3.22064 1.5 3.60218 1.5 4V12C1.5 12.3978 1.65804 12.7794 1.93934 13.0607C2.22064 13.342 2.60218 13.5 3 13.5H13C13.3978 13.5 13.7794 13.342 14.0607 13.0607C14.342 12.7794 14.5 12.3978 14.5 12V6C14.5 5.60218 14.342 5.22064 14.0607 4.93934C13.7794 4.65804 13.3978 4.5 13 4.5H9.414C9.14887 4.49977 8.89402 4.39426 8.70667 4.20667Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})}),fet=["agent","workflow","model","mcp","tool","provider","memory","workspace","skill","scorer","other"],bus={agent:{icon:o.jsx(Ti,{}),color:"oklch(0.75 0.15 250)",label:"Agent",typePrefix:"agent"},workflow:{icon:o.jsx(Uc,{}),color:"oklch(0.75 0.15 200)",label:"Workflow",typePrefix:"workflow"},model:{icon:o.jsx(kg,{}),color:"oklch(0.75 0.15 320)",label:"Model",typePrefix:"model"},mcp:{icon:o.jsx(OC,{}),color:"oklch(0.75 0.15 160)",label:"MCP",typePrefix:"mcp"},tool:{icon:o.jsx(Ff,{}),color:"oklch(0.75 0.15 100)",label:"Tool",typePrefix:"tool"},provider:{icon:o.jsx(Ff,{}),color:"oklch(0.75 0.15 60)",label:"Provider Tool",typePrefix:"provider"},memory:{icon:o.jsx(RL,{}),color:"oklch(0.75 0.12 50)",label:"Memory",typePrefix:"memory"},workspace:{icon:o.jsx(tqt,{}),color:"oklch(0.75 0.15 40)",label:"Workspace",typePrefix:"workspace"},skill:{icon:o.jsx(fC,{}),color:"oklch(0.75 0.15 130)",label:"Skill",typePrefix:"skill"},scorer:{icon:o.jsx(Wp,{}),color:"oklch(0.75 0.15 280)",label:"Scorer",typePrefix:"scorer"}},xus={color:"oklch(0.65 0 0)",label:"Other",typePrefix:"other"};function nqt(e){const t=e?.toLowerCase().split("_")[0]??"";return bus[t]??xus}function wus({isSelected:e,isFaded:t,isExpanded:n,isRootSpan:r,toggleChildren:s,expandAllDescendants:a,collapseAllDescendants:i,collapseAll:l,totalDescendants:c=0,allDescendantsExpanded:u,numOfChildren:d=0,toggleSiblings:f,siblingsAllExpanded:p,siblingsWithChildrenCount:h=0}){const m=n?`Collapse children (${d})`:`Expand children (${d})`,v=!r&&!!d&&d>0,y=!r&&v&&c>d,b=!r&&h>=2,x=!!r&&!!d&&d>0,S=!!n&&!!u;return o.jsx("div",{className:K("flex h-full items-center justify-end px-1.5",{"opacity-30 [&:hover]:opacity-60":t,"bg-surface4":e}),children:o.jsxs("div",{className:"grid grid-cols-[1.625rem_1.625rem_1.625rem] gap-1",children:[o.jsx("div",{children:v&&o.jsx(Vz,{onClick:()=>s?.(),tooltip:m,children:n?o.jsx(O_,{}):o.jsx(Xs,{})})}),o.jsx("div",{children:y&&o.jsx(Vz,{onClick:()=>u?i?.():a?.(),tooltip:u?`Collapse all descendants (${c})`:`Expand all descendants (${c})`,children:u?o.jsx(EQt,{}):o.jsx(wQt,{})})}),o.jsxs("div",{children:[b&&o.jsx(Vz,{onClick:()=>f?.(),tooltip:p?"Collapse at this level":"Expand at this level",children:p?o.jsx(HYt,{}):o.jsx(nen,{})}),x&&o.jsx(Vz,{onClick:()=>S?l?.():a?.(),tooltip:S?"Collapse all":"Expand all",children:S?o.jsx(hV,{}):o.jsx(XN,{})})]})]})})}function Vz({onClick:e,children:t,className:n,tooltip:r}){return o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:o.jsx("button",{onClick:e,className:K("h-full shrink-0 cursor-pointer",n),"aria-label":r,children:o.jsx("div",{className:K("flex items-center gap-[0.1rem] rounded-md p-1 transition-all","hover:bg-surface5","[&:hover>svg]:opacity-100 [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:opacity-50 [&>svg]:transition-all"),children:t})})}),r&&o.jsx(vn,{children:r})]})}function Sus({isLastChild:e}){return o.jsx("div",{className:K("relative h-[1.8rem] w-2 shrink-0 opacity-100",'after:absolute after:inset-y-0 after:-left-px after:w-0 after:border-l-[1px] after:border-dashed after:border-neutral3 after:content-[""] ','before:absolute before:top-[50%] before:left-0 before:h-0 before:w-full before:border-b-[1px] before:border-dashed before:border-neutral3 before:content-[""]',{"after:bottom-[50%]":e})})}const kus=e=>{e?.scrollIntoView({block:"nearest"})};function Ous({span:e,spanUI:t,isFaded:n,depth:r=0,onSpanClick:s,selectedSpanId:a,isLastChild:i,hasChildren:l,isRootSpan:c,isExpanded:u}){const d=a===e.id;return o.jsxs("div",{ref:d?kus:void 0,"aria-label":`View details for span ${e.name}`,className:K("flex min-h-8 items-center rounded-md rounded-l-lg opacity-80",{"opacity-30 [&:hover]:opacity-60":n,"bg-surface4":d}),style:{paddingLeft:`${r*1}rem`},children:[!c&&o.jsx(Sus,{isLastChild:i}),o.jsxs("button",{onClick:()=>s?.(e.id),className:K("flex size-full min-w-0 items-center gap-1.5 rounded-md px-2 py-1 text-left text-ui-smd text-neutral6 transition-colors","[&>svg]:ml-auto [&>svg]:size-[1em] [&>svg]:shrink-0 [&>svg]:opacity-0 [&>svg]:transition-all","hover:bg-surface4 [&:hover>svg]:opacity-60","focus:outline-none focus-visible:ring-1 focus-visible:ring-accent1 focus-visible:ring-inset"),children:[t?.color&&o.jsx("span",{"aria-hidden":!0,title:t.label,className:"inline-block size-2 shrink-0 rounded-full",style:{backgroundColor:t.color}}),o.jsx("span",{"data-highlight":e.matchedInPayloadOnly?void 0:"","data-highlight-indirect":e.matchedInPayloadOnly?"":void 0,title:e.matchedInPayloadOnly?"Matches your search in this span’s details":void 0,className:"min-w-0 truncate",children:e.name})]})]})}function _us({span:e,selectedSpanId:t,isFaded:n,overallLatency:r,overallStartTime:s,color:a,chartWidth:i="default"}){const l=r?Math.ceil(e.latency/r*100):0,c=s?new Date(s):null,u=e.startTime?new Date(e.startTime):null,d=u&&c?u.getTime()-c.getTime():0,f=r&&Math.floor(d/r*100);return o.jsxs(XI,{children:[o.jsxs(pC,{className:K("grid h-8 cursor-help grid-cols-[1fr_auto] items-center gap-2 rounded-r-md p-1 pr-2",i==="wide"?"min-w-72":"min-w-32","[&:hover>div]:bg-surface5",{"opacity-30 [&:hover]:opacity-60":n,"bg-surface4":t===e.id}),children:[o.jsx("div",{className:K("w-full rounded-md bg-surface4 p-1.5 transition-colors duration-1000"),children:o.jsx("div",{className:"relative h-1.5 w-full overflow-hidden rounded-sm",children:o.jsx("div",{className:K("absolute top-0 h-1.5 rounded-sm bg-neutral1"),style:{width:l?`${l}%`:"2px",left:`${f||0}%`,backgroundColor:a}})})}),o.jsxs("div",{className:K("flex justify-end text-ui-xs text-neutral3"),children:[(e.latency/1e3).toFixed(3)," s"]})]}),o.jsxs(hC,{className:"bg-surface4 pr-6",children:[o.jsx("div",{className:K("mt-1 mb-2 flex items-center gap-2 text-ui-sm"),children:"Span Timing"}),o.jsxs(_n,{children:[o.jsx(_n.Key,{children:"Latency"}),o.jsxs(_n.Value,{children:[e.latency," ms"]}),o.jsx(_n.Key,{children:"Started at"}),o.jsx(_n.Value,{children:e.startTime?hr(new Date(e.startTime),"hh:mm:ss:SSS a"):"-"}),o.jsx(_n.Key,{children:"Ended at"}),o.jsx(_n.Value,{children:e.endTime?hr(new Date(e.endTime),"hh:mm:ss:SSS a"):"-"}),o.jsx(_n.Key,{children:"Start Shift"}),o.jsxs(_n.Value,{children:[d,"ms"]})]})]})]})}function rqt({span:e,siblings:t,depth:n=0,onSpanClick:r,selectedSpanId:s,isLastChild:a,overallLatency:i,overallStartTime:l,fadedTypes:c,searchPhrase:u,featuredSpanIds:d,expandedSpanIds:f,setExpandedSpanIds:p,chartWidth:h}){const m=e.spans&&e.spans.length>0,v=e.spans?e.spans.length:0,y=oV(e),b=y.length,x=n===0,S=nqt(e?.type),k=f?f.includes(e.id):!1,_=d&&d.length>0?!d.includes(e.id):!1,T=(c&&c.length>0?c.includes(S?.typePrefix||""):!1)||_;g.useEffect(()=>{if(!d||y.length===0||k)return;y.some(z=>d.includes(z))&&p&&p(z=>!z||z.includes(e.id)?z??[e.id]:[...z,e.id])},[d,y]);const E=()=>{p&&p(B=>B&&(k?B.filter(z=>z!==e.id):[...B,e.id]))},N=()=>{p&&p(B=>B&&Array.from(new Set([...B,e.id,...y])))},I=()=>{p&&p(B=>{if(!B)return B;const z=new Set(y);return B.filter(V=>!z.has(V))})},A=()=>{p&&p(B=>{if(!B)return B;const z=new Set([e.id,...y]);return B.filter(V=>!z.has(V))})},R=y.every(B=>f?.includes(B)),L=(t??[]).filter(B=>B.spans&&B.spans.length>0),D=L.length,F=D>0&&L.every(B=>f?.includes(B.id)),H=()=>{!p||D===0||p(B=>{if(!B)return B;if(F){const z=new Set;return L.forEach(V=>{z.add(V.id),oV(V).forEach(M=>z.add(M))}),B.filter(V=>!z.has(V))}return Array.from(new Set([...B,...L.map(z=>z.id)]))})};return o.jsxs(o.Fragment,{children:[o.jsx(Ous,{span:e,spanUI:S,isFaded:T,depth:n,onSpanClick:r,selectedSpanId:s,isLastChild:a,hasChildren:m,isRootSpan:x,isExpanded:k}),o.jsx(wus,{isSelected:s===e.id,isFaded:T,isExpanded:k,isRootSpan:x,toggleChildren:E,expandAllDescendants:N,collapseAllDescendants:I,collapseAll:A,totalDescendants:b,allDescendantsExpanded:R,numOfChildren:v,toggleSiblings:H,siblingsAllExpanded:F,siblingsWithChildrenCount:D}),o.jsx(_us,{span:e,selectedSpanId:s,isFaded:T,overallLatency:i,overallStartTime:l,color:S?.color,chartWidth:h}),m&&k&&e.spans?.map((B,z,V)=>{const M=z===V.length-1;return o.jsx(rqt,{span:B,siblings:V,depth:n+1,onSpanClick:r,selectedSpanId:s,isLastChild:M,overallLatency:i,overallStartTime:l,fadedTypes:c,searchPhrase:u,expandedSpanIds:f,setExpandedSpanIds:p,featuredSpanIds:d,chartWidth:h},B.id)})]})}function sqt({hierarchicalSpans:e=[],onSpanClick:t,selectedSpanId:n,isLoading:r,fadedTypes:s,expandedSpanIds:a,setExpandedSpanIds:i,featuredSpanIds:l,chartWidth:c="default",leadingSlot:u}){const d=e?.[0]?.latency||0,f=e?.[0]?.startTime||"",p=g.useMemo(()=>{const h=b=>{const x=new Set;for(const S of b){const k=S.type?.toLowerCase().split("_")[0];if(k&&x.add(k),S.spans)for(const _ of h(S.spans))x.add(_)}return x},m=h(e),v=[...m].some(b=>!fet.includes(b)),y=fet.filter(b=>b!=="other"&&m.has(b));return v&&y.push("other"),y},[e]);return o.jsx(o.Fragment,{children:r?o.jsxs("div",{className:K("flex items-center justify-center gap-3 rounded-md bg-surface3/50 p-3 text-ui-sm text-neutral3","[&_svg]:size-[1.25em] [&_svg]:opacity-50"),children:[o.jsx(Ut,{})," Loading Trace Timeline ..."]}):o.jsxs(o.Fragment,{children:[(p.length>0||u)&&o.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-3 px-2 py-1.5",children:[u&&o.jsx("div",{className:"min-w-0 flex-1",children:u}),p.map(h=>{const m=nqt(h);return o.jsxs("div",{className:"text-ui-sm text-neutral3 flex shrink-0 items-center gap-1",children:[o.jsx("span",{className:"inline-block size-1.5 shrink-0 rounded-full",style:{backgroundColor:m?.color}}),m?.label||h]},h)})]}),o.jsx("div",{className:"grid grid-cols-[minmax(0,1fr)_auto_auto] content-start items-start gap-y-px overflow-hidden py-1",children:e?.map(h=>o.jsx(rqt,{span:h,siblings:e,onSpanClick:t,selectedSpanId:n,overallLatency:d,overallStartTime:f,fadedTypes:s,featuredSpanIds:l,expandedSpanIds:a,setExpandedSpanIds:i,chartWidth:c},h.id))})]})})}const gie="search-result",vie="search-result-indirect",aqt=2,iqt="[data-highlight]",lV="[data-highlight-indirect]";function oqt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Cus(e,t){const n=new RegExp(oqt(t),"iu"),r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(s){return s.parentElement.closest(`${iqt}, ${lV}`)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}});for(;r.nextNode();){const s=r.currentNode;if(s.parentElement.closest(lV)){if(s.data.length>0)return s;continue}if(n.test(s.data))return s}return null}function Eus(e){const[t,n]=g.useState(null);return uG(()=>{if(!t||e.trim().length<aqt||typeof CSS>"u"||!("highlights"in CSS)||typeof StaticRange>"u"){CSS?.highlights?.delete(gie),CSS?.highlights?.delete(vie);return}let r=null;const s=()=>{const l=[],c=[],u=new RegExp(oqt(e),"giu"),d=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(f){return f.parentElement.closest(`${iqt}, ${lV}`)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}});for(;d.nextNode();){const f=d.currentNode;if(f.parentElement.closest(lV)){f.data.length>0&&c.push(new StaticRange({startContainer:f,startOffset:0,endContainer:f,endOffset:f.data.length}));continue}u.lastIndex=0;let h;for(;(h=u.exec(f.data))!==null;)l.push(new StaticRange({startContainer:f,startOffset:h.index,endContainer:f,endOffset:h.index+h[0].length}))}CSS.highlights.set(gie,new Highlight(...l)),CSS.highlights.set(vie,new Highlight(...c))},a=()=>{r!==null&&cancelAnimationFrame(r),r=requestAnimationFrame(()=>{r=null,s()})};s();const i=new MutationObserver(a);return i.observe(t,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:["data-highlight","data-highlight-indirect"]}),()=>{i.disconnect(),r!==null&&cancelAnimationFrame(r),CSS.highlights.delete(gie),CSS.highlights.delete(vie)}},[t,e]),{ref:n}}function Tus(e,t){const[n,r]=g.useState(null);return g.useEffect(()=>{if(!n||e.trim().length<aqt)return;let s=null,a=null,i="";const l=()=>{const d=Cus(n,e);if(!d)return;a=d,i=d.data;const f=d.parentElement;f&&typeof f.scrollIntoView=="function"&&f.scrollIntoView({block:"center"})},c=()=>a!==null&&a.isConnected&&a.data===i;l();const u=new MutationObserver(()=>{s===null&&(s=requestAnimationFrame(()=>{s=null,c()||l()}))});return u.observe(n,{subtree:!0,childList:!0,characterData:!0}),()=>{u.disconnect(),s!==null&&cancelAnimationFrame(s)}},[n,e,t]),{ref:r}}function lqt({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,onEvaluateTrace:a,onSaveAsDatasetItem:i,onAddTraceMocksToItem:l,initialSpanId:c,onPrevious:u,onNext:d,collapsed:f,onCollapsedChange:p,placement:h,timelineChartWidth:m="default",LinkComponent:v,traceHref:y,entityHref:b,usage:x,anchorSpanId:S,showUnavailableFeaturesMsg:k=!0,scoresTabSlot:_,scoresTabBadge:C,feedbackTabSlot:T,feedbackTabBadge:E,activeTab:N,onTabChange:I,spanPanelSlot:A,className:R}){const L=h==="trace-page",[D,F]=g.useState(!1),H=f??D,B=p??F,{download:z,isPending:V}=hus(),[M,G]=g.useState(c??void 0);g.useEffect(()=>{if(!c){G(void 0),s?.(void 0);return}if(n||!t)return;t.find(se=>se.spanId===c)?(G(c),s?.(c)):(G(void 0),s?.(void 0))},[c,t,n]);const U=g.useId(),{query:$,setQuery:q,results:Z,payloadOnlyMatchIds:Y}=gus(t??[]),ne=g.useMemo(()=>dAe(Z.map(te=>({...te,matchedInPayloadOnly:Y.has(te.spanId)})),S),[Z,Y,S]),[J,ee]=g.useState([]);g.useEffect(()=>{ne.length>0&&ee(fAe(ne))},[ne]);const re=g.useMemo(()=>S?t?.find(te=>te.spanId===S):t?.find(te=>te.parentSpanId==null),[t,S]),le=te=>{const se=M===te?void 0:te;G(se),s?.(se)},X=o.jsxs(rt,{children:[o.jsx(rt.Trigger,{render:o.jsx(oe,{size:"md",tooltip:"Trace actions","aria-label":"Trace actions",children:o.jsx(vYt,{})})}),o.jsxs(rt.Content,{align:"end",children:[!L&&p&&o.jsxs(rt.Item,{onSelect:()=>B(!H),children:[H?o.jsx(XN,{}):o.jsx(hV,{}),H?"Expand panel":"Collapse panel"]}),!L&&a&&o.jsxs(rt.Item,{onSelect:a,children:[o.jsx(Rlt,{}),"Evaluate trace"]}),!L&&i&&o.jsxs(rt.Item,{onSelect:()=>i({traceId:e,rootSpanId:re?.spanId}),children:[o.jsx(Gu,{}),"Add full trace to dataset"]}),!L&&l&&o.jsxs(rt.Item,{onSelect:()=>l({traceId:e}),children:[o.jsx(Ud,{}),"Add tool mocks to item"]}),!L&&v&&y&&o.jsxs(rt.Item,{render:o.jsx(v,{href:y}),children:[o.jsx(c0e,{}),"Open trace page"]}),o.jsxs(rt.Item,{disabled:V,onSelect:()=>z(e),children:[V?o.jsx(qs,{className:"animate-spin"}):o.jsx(Pd,{}),"Download trace JSON"]})]})]});return o.jsxs(fn,{collapsed:H,className:R,children:[o.jsx(fn.Header,{children:L?o.jsxs(o.Fragment,{children:[o.jsx(fn.Heading,{children:"Trace Timeline"}),o.jsx(hs,{className:"ml-auto shrink-0",children:X})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[o.jsxs(fn.Heading,{children:["Trace ",o.jsxs("b",{children:["# ",Xh(e,12)]})]}),!H&&re&&o.jsx(yus,{rootSpan:re,usage:x,entityHref:b,LinkComponent:v})]}),o.jsxs(hs,{className:"ml-auto shrink-0 self-start",children:[X,(u||d)&&o.jsx(fn.NextPrevNav,{onPrevious:u,onNext:d,previousLabel:"Previous trace",nextLabel:"Next trace"}),o.jsx(fn.CloseButton,{onClick:r})]})]})}),!H&&o.jsx(jus,{spanPanelSlot:A,highlightQuery:$,spanPanelKey:M,children:n?o.jsx(fn.LoadingData,{children:"Loading trace..."}):t?.length?o.jsx(fn.Content,{children:(()=>{const te=o.jsxs(o.Fragment,{children:[!L&&!a&&!i&&!l&&k&&o.jsx(Wn,{variant:"info",className:"mb-6",children:o.jsx(Wn.Message,{children:"Evaluating traces and saving them as dataset items is available in Mastra Studio (local or deployed)."})}),o.jsx(sqt,{hierarchicalSpans:ne,onSpanClick:le,selectedSpanId:M,expandedSpanIds:J,setExpandedSpanIds:ee,chartWidth:m,leadingSlot:o.jsx(m_,{name:U,label:"Search spans",labelIsHidden:!0,placeholder:"Search spans...",value:$,onChange:se=>q(se.target.value),onReset:()=>q(""),size:"sm",variant:"outline",className:"w-full"})}),ne.length===0&&o.jsx(fn.NoData,{children:"No spans match your search."})]});return!_&&!T?te:o.jsxs(yc,{defaultTab:"details",value:N,onValueChange:I,className:N==="scores"||N==="feedback"?"grid h-full min-h-0 grid-rows-[auto_1fr]":void 0,children:[o.jsxs(vc,{variant:"pill-ghost",className:"px-0",children:[o.jsx(Ar,{value:"details",children:"Spans"}),_&&o.jsxs(Ar,{value:"scores",children:["Evaluations ",C!=null&&o.jsxs(o.Fragment,{children:["(",C,")"]})]}),T&&o.jsxs(Ar,{value:"feedback",children:["Feedback ",E!=null&&o.jsxs(o.Fragment,{children:["(",E,")"]})]})]}),o.jsx(fs,{value:"details",children:te}),_&&o.jsx(fs,{value:"scores",className:"h-full min-h-0",children:_({traceId:e,rootSpanId:re?.spanId})}),T&&o.jsx(fs,{value:"feedback",className:"h-full min-h-0",children:T({traceId:e})})]})})()}):o.jsx(fn.NoData,{children:"No spans found for this trace."})})]})}function jus({spanPanelSlot:e,highlightQuery:t,spanPanelKey:n,children:r}){const{ref:s}=Eus(t),{ref:a}=Tus(t,n);return e?o.jsxs("div",{ref:s,className:"grid min-h-0 flex-1 grid-cols-[1fr_1fr]",children:[o.jsx("div",{className:"flex min-h-0 flex-col overflow-hidden",children:r}),o.jsx("div",{ref:a,"data-highlight":!0,className:"animate-in border-border1 fade-in-0 flex min-h-0 flex-col overflow-hidden border-l duration-300",children:e})]}):o.jsx("div",{ref:s,className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:r})}function Nus(e){const[t,n]=g.useState("details");return o.jsx(lqt,{...e,onEvaluateTrace:()=>n("scores"),activeTab:t,onTabChange:n})}function Ius(e,t){if(!t||!e)return;const n=e.toLowerCase();if(n.includes("workflow"))return`/workflows/${encodeURIComponent(t)}/graph`;if(n.includes("agent"))return`/agents/${encodeURIComponent(t)}/chat/new`}function cqt({traceId:e,spans:t,isLoadingSpans:n,selectedSpanId:r,onSpanSelect:s,onClose:a,onSpanClose:i,anchorSpanId:l,initialSpanId:c,onPrevious:u,onNext:d,onSaveAsDatasetItem:f,onAddTraceMocksToItem:p,feedbackTabBadge:h,feedbackTabSlot:m,scoresTabBadge:v,scoresTabSlot:y,usage:b,traceHref:x,className:S,spanActiveTab:k,onSpanTabChange:_,spanFeedbackTabBadge:C,spanFeedbackTabSlot:T,spanPanelClassName:E}){const{data:N,isLoading:I}=_Q(e,r??""),{handlePreviousSpan:A,handleNextSpan:R}=eqt(t,r,s),L=l?t?.find(F=>F.spanId===l):t?.find(F=>F.parentSpanId==null),D=Ius(L?.entityType,L?.entityId);return o.jsx(Nus,{className:S,traceId:e,spans:t,anchorSpanId:l,entityHref:D,usage:b,isLoading:n,onClose:a,onSpanSelect:s,onSaveAsDatasetItem:f,onAddTraceMocksToItem:p,initialSpanId:c??r,onPrevious:u,onNext:d,placement:"traces-list",LinkComponent:cy,traceHref:x,feedbackTabBadge:h,feedbackTabSlot:m,scoresTabBadge:v,scoresTabSlot:y,spanPanelSlot:r?o.jsx(JUt,{className:E,traceId:e,spanId:r,span:N?.span,isAnchor:l?r===l:void 0,isLoading:I,onClose:i??(()=>s(void 0)),onPrevious:A,onNext:R,activeTab:k,onTabChange:_,feedbackTabBadge:C,feedbackTabSlot:T}):null})}function Aus({threadId:e,onTraceOpenChange:t,onSpanOpenChange:n}){const r=g.useMemo(()=>({threadId:e}),[e]),{data:s,isLoading:a,isFetchingNextPage:i,hasNextPage:l,setEndOfListElement:c,error:u}=XUt({filters:r}),d=s?.spans??[],[f,p]=g.useState(null),[h,m]=g.useState(void 0),v=C=>{!!C!=!!h&&n?.(!!C),m(C)},y=C=>{p(C),t?.(!0)},b=()=>{v(void 0),p(null),t?.(!1)},{handlePreviousTrace:x,handleNextTrace:S}=QUt(d,f??void 0,null,C=>{v(void 0),p(C)}),{spans:k,isLoading:_}=KUt({traceId:f,anchorSpanId:null,listMode:"traces"});return u?o.jsx("div",{className:"flex h-full items-center justify-center p-4",children:o.jsx(BUt,{error:u,resource:"traces",errorTitle:"Failed to load traces"})}):f?o.jsx(cqt,{className:"h-full rounded-none border-0",spanPanelClassName:"rounded-none border-0",traceId:f,spans:k,isLoadingSpans:_,selectedSpanId:h??null,onClose:b,onSpanSelect:v,onPrevious:x,onNext:S,traceHref:`/traces?traceId=${encodeURIComponent(f)}`},f):a?o.jsx("div",{className:"flex flex-col gap-3 p-4","aria-hidden":"true",children:["80%","60%","90%","70%","65%"].map((C,T)=>o.jsx("div",{className:"bg-surface6 h-4 animate-pulse rounded-lg",style:{width:C}},T))}):o.jsx("div",{className:"h-full min-h-0 p-1.5",children:o.jsx(GUt,{traces:d,isLoading:a,isFetchingNextPage:i,hasNextPage:l,setEndOfListElement:c,onTraceClick:C=>y(C.traceId)})})}function Rus(){const{agentId:e,threadId:t}=mr(),[n]=hi(),{data:r,isLoading:s,error:a}=Vl(e),{data:i}=yC(e),l=es(),c=t==="new",u=g.useMemo(()=>vo(),[t]),d=!!i?.result,{data:f,isLoading:p,refetch:h}=k4t({agentId:e,isMemoryEnabled:d,resourceId:e}),m=g.useMemo(()=>(f||[]).map(k=>({...k,createdAt:new Date(k.createdAt),updatedAt:new Date(k.updatedAt)})),[f]),v=n.get("messageId")??void 0,y=ccs(r?.metadata),b=g.useMemo(()=>KIe(r),[r]);if(a&&Ss(a))return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Gs,{})});if(a&&ks(a))return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{resource:"agents"})});if(s)return o.jsx(zus,{});if(!r)return o.jsx("div",{className:"py-4 text-center",children:"Agent not found"});const x=c?u:t??u,S=async()=>{await h(),c&&l(`/agents/${e}/threads/${u}`)};return o.jsx(jH,{entityId:e,entityType:"agent",children:o.jsx(JTe,{agentId:e,defaultSettings:b,children:o.jsx(I3,{children:o.jsx($4t,{agentId:e,threadId:x,resourceId:e,children:o.jsx(qZ,{children:o.jsx(VZ,{agentId:e,threadId:x,enabled:!!(r?.hasBrowser??r?.browserTools?.length),children:o.jsx(qIe,{children:o.jsx(L4t,{children:o.jsx(eUr,{children:o.jsx(JZ,{children:o.jsx(rAe,{storageKey:"agent-thread",children:o.jsxs("div",{className:"bg-surface1 h-full lg:grid lg:grid-cols-[auto_1fr] lg:grid-rows-[1fr]",children:[o.jsx($us,{agentId:e,agentName:r.name,threads:m,threadId:x,isLoading:p}),o.jsxs("div",{className:"relative min-h-0",children:[o.jsx("div",{className:"rounded-studio-frame border-border1 bg-surface2 shadow-main-frame m-1.5 h-[calc(100%-0.75rem)] min-h-0 overflow-hidden border [--studio-frame-inset:0.5rem] [--studio-frame-radius:1.5rem] lg:m-2 lg:ml-0 lg:h-[calc(100%-1rem)]",children:o.jsx("div",{className:"relative grid h-full min-h-0 overflow-y-auto pt-6",children:o.jsx(eAe,{agentId:e,agentName:r?.name,modelVersion:r?.modelVersion,supportsMemory:r?.supportsMemory,threadId:x,memory:d,refreshThreadList:S,modelList:r?.modelList,messageId:v,suggestedPrompts:y,isNewThread:c},x)})}),!c&&o.jsx(Pus,{threadId:x},x)]})]})})},`${e}-${x}`)},`memory-timeline-${e}-${x}`)})})},`session-${e}-${x}`)},`browser-${e}-${x}`)})})})})}const Pus=({threadId:e})=>{const[t,n]=g.useState("closed"),[r,s]=g.useState(!1),[a,i]=g.useState(!1),l=()=>{n("closing"),s(!1),i(!1)};return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"absolute top-3 right-3 z-10 hidden lg:top-4 lg:right-4 lg:block",children:o.jsxs(oe,{variant:"outline",onClick:()=>t==="open"?l():n("open"),children:[o.jsx(Ilt,{}),"Traces"]})}),t!=="closed"&&o.jsx("div",{onAnimationEnd:c=>{c.target===c.currentTarget&&t==="closing"&&n("closed")},className:`absolute top-3 right-3 bottom-3 z-20 hidden transition-[width] duration-300 ease-out lg:top-4 lg:right-4 lg:bottom-4 lg:block ${t==="closing"?"animate-out fade-out-0 slide-out-to-right-full fill-mode-forwards":"animate-in fade-in-0 slide-in-from-right-full"} ${a?"w-[70%]":"w-[40%]"}`,children:o.jsx(ucs,{title:r?void 0:"Traces",onClose:l,children:o.jsx(Aus,{threadId:e,onTraceOpenChange:s,onSpanOpenChange:i})})})]})},$us=({agentId:e,agentName:t,threads:n,threadId:r,isLoading:s})=>{const{Link:a}=cn(),{state:i}=_C(),l=es(),{canDelete:c}=_o(),{mutateAsync:u}=OBr(),[d,f]=g.useState(null),p=c("memory"),h=async()=>{d&&(await u({threadId:d,agentId:e}),d===r&&l(`/agents/${e}/threads/new`),f(null))},m=o.jsx(ns.Nav,{children:o.jsxs(ns.NavSection,{children:[o.jsx(ns.NavHeader,{state:i,children:"Threads"}),s?o.jsx(Dus,{}):o.jsx(ns.NavList,{"data-testid":"thread-list",children:n.map(v=>o.jsx(ns.NavLink,{LinkComponent:a,state:i,isActive:v.id===r,link:{name:Fus(v),url:`/agents/${e}/threads/${v.id}`},className:"group/thread-row",action:p?o.jsx(oe,{variant:"ghost",size:"icon-sm",className:"shrink-0 opacity-0 transition-opacity group-focus-within/thread-row:opacity-100 group-hover/thread-row:opacity-100",onClick:()=>f(v.id),"aria-label":"Delete thread",children:o.jsx(or,{})}):void 0},v.id))})]})});return o.jsxs(o.Fragment,{children:[o.jsx(Mus,{open:!!d,onOpenChange:()=>f(null),onDelete:()=>{h()}}),o.jsxs(ns,{children:[o.jsx("div",{className:"mb-1.5 pt-2.5",children:o.jsxs("span",{className:"flex h-7 items-center gap-2 pr-2 pl-3",children:[o.jsx(qp,{className:"h-[1.5rem] w-[1.5rem] shrink-0"}),o.jsx("span",{className:"font-display truncate text-sm font-semibold tracking-tight whitespace-nowrap",children:"Mastra Studio"})]})}),o.jsx("div",{className:"mb-1",children:o.jsxs(ns.NavList,{children:[o.jsx(ns.NavLink,{state:i,asChild:!0,children:o.jsxs(a,{href:`/agents/${e}/overview`,"data-testid":"thread-sidebar-back",children:[o.jsx(gl,{}),o.jsxs(ns.NavLabel,{state:i,children:["Back to ",t??"agent"]})]})}),o.jsx(ns.NavLink,{state:i,asChild:!0,children:o.jsxs(a,{href:`/agents/${e}/threads/new`,"data-testid":"thread-sidebar-new-chat",children:[o.jsx(Or,{}),o.jsx(ns.NavLabel,{state:i,children:"New Chat"})]})})]})}),i==="collapsed"?m:o.jsx("div",{className:"min-h-0 flex-1",children:o.jsx(ocs,{agentId:e,threadId:r,threadsSlot:m})})]})]})},Mus=({open:e,onOpenChange:t,onDelete:n})=>o.jsx(Pt,{open:e,onOpenChange:t,children:o.jsxs(Pt.Content,{children:[o.jsxs(Pt.Header,{children:[o.jsx(Pt.Title,{children:"Are you absolutely sure?"}),o.jsx(Pt.Description,{children:"This action cannot be undone. This will permanently delete your chat and remove it from our servers."})]}),o.jsxs(Pt.Footer,{children:[o.jsx(Pt.Cancel,{children:"Cancel"}),o.jsx(Pt.Action,{onClick:n,children:"Continue"})]})]})}),Dus=()=>o.jsx("div",{className:"flex flex-col gap-px","data-testid":"thread-list-skeleton","aria-busy":"true",children:["w-32","w-24","w-36","w-28"].map(e=>o.jsx("div",{className:"flex h-9 items-center px-3",children:o.jsx(jt,{className:`h-3 ${e}`})},e))}),Lus=/^New Thread \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;function Fus(e){return e.title&&!Lus.test(e.title)?e.title:new Date(e.createdAt).toLocaleString("en-us",{month:"short",day:"numeric",hour:"numeric",minute:"numeric",hour12:!0}).replace(","," at")}const zus=()=>o.jsx(_s,{className:"grid-rows-[1fr]",children:o.jsx("div",{className:"relative grid h-full overflow-y-auto pt-6","data-testid":"agent-thread-skeleton","aria-busy":"true",children:o.jsx($3t,{})})}),pAe=()=>{const{data:e}=H4();return e?.editorSource==="code"?"code":"db"};function Bus(){const{agentId:e}=mr(),{navigate:t}=cn(),{data:n,isLoading:r,error:s}=Vl(e),{data:a}=vS({agentId:e,params:{orderBy:{direction:"DESC"}}}),i=(a?.versions?.length??0)>0,{data:l,isLoading:c}=A4(e,{status:"draft",enabled:i}),u=pAe(),d=n?.source==="code",f=d&&u==="code",p=r||i&&c,h=g.useMemo(()=>l||(n?YIe(n):{}),[l,n]),{form:m,handlePublish:v,handleSaveDraft:y,isSubmitting:b,isSavingDraft:x}=wQ({mode:"edit",agentId:e??"",dataSource:h,isCodeAgentOverride:d,hasStoredOverride:d&&!!l,editorConfig:n?.editor,onSuccess:()=>{}}),[S,k]=g.useState(()=>{const _=sessionStorage.getItem(`pending-scorer-items-${e}`);if(_){sessionStorage.removeItem(`pending-scorer-items-${e}`);try{return JSON.parse(_)}catch{return null}}return null});return s&&Ss(s)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Gs,{})}):s&&ks(s)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{resource:"agents"})}):p?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ut,{className:"h-6 w-6"})}):n?o.jsx(aje,{form:m,mode:"edit",agentId:e,isSubmitting:b,isSavingDraft:x,handlePublish:v,handleSaveDraft:y,isCodeAgentOverride:d,isCodeSourceAgent:f,readOnly:!1,children:o.jsx(qis,{agentId:e,onSwitchToReview:()=>t(`/agents/${e}/review`),pendingScorerItems:S,onPendingScorerItemsConsumed:()=>k(null)})}):o.jsx("div",{className:"py-4 text-center",children:"Agent not found"})}const CQ=()=>{const e=window.MASTRA_CLOUD_API_ENDPOINT,t=window.MASTRA_PLATFORM_PROJECT_ID,n=window.MASTRA_ORGANIZATION_ID,r=window.MASTRA_PLATFORM_OBSERVABILITY_ENDPOINT;return{isMastraPlatform:!!e,mastraPlatformEndpoint:e,mastraPlatformApiEndpoint:e,mastraPlatformProjectId:t,mastraOrganizationId:n,platformObservabilityEndpoint:r}};function Uus(){const{agentId:e}=mr(),[t,n]=g.useState(null),{data:r,isLoading:s,error:a}=Vl(e),{data:i}=yC(e),l=pAe(),{isMastraPlatform:c,mastraPlatformApiEndpoint:u,mastraPlatformProjectId:d}=CQ(),{data:f,isLoading:p}=vS({agentId:e,params:{orderBy:{direction:"DESC"}}}),h=(f?.versions?.length??0)>0,{data:m,isLoading:v}=A4(e,{status:"draft",enabled:h}),y=r?.source==="code",b=y&&l==="code",x=!kC(y,r?.editor).isFullyLocked,S=b&&x,k=S&&c&&!!u&&!!d,_=k?"Open a pull request for these JSON changes":void 0,C=s||p||h&&v,T=!!i?.result,{data:E}=aBt({agentId:e??"",versionId:t??""}),N=m?.activeVersionId,I=f?.versions?.[0],A=!!(I&&I.id!==N),R=!!t&&!!E,L=R&&t!==I?.id,D=g.useMemo(()=>R&&E?E:m||(r?YIe(r):{}),[R,E,m,r]),{form:F,handlePublish:H,handleSaveDraft:B,handleDownloadJson:z,handleOpenPr:V,isSubmitting:M,isSavingDraft:G,isDirty:U}=wQ({mode:"edit",agentId:e??"",dataSource:D,isCodeAgentOverride:y,hasStoredOverride:y&&!!m,editorConfig:r?.editor,saveSuccessMessage:b?"Saved to filesystem":void 0,onSuccess:()=>{}}),$=g.useCallback(async()=>{L&&t?await H(t):await H()},[H,L,t]),q=g.useCallback(async()=>{!u||!d||await V({platformApiEndpoint:u,projectId:d})},[V,u,d]),Z=g.useCallback(Y=>{Y===I?.id?n(null):n(Y)},[I?.id]);return a&&Ss(a)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Gs,{})}):a&&ks(a)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{resource:"agents"})}):C?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ut,{className:"h-6 w-6"})}):r?o.jsx(aje,{form:F,mode:"edit",agentId:e,isSubmitting:M,isSavingDraft:G,handlePublish:H,handleSaveDraft:B,isCodeAgentOverride:y,isCodeSourceAgent:b,readOnly:L||!x,editorConfig:r?.editor,children:o.jsx(vis,{agentId:e,agentName:r?.name,modelVersion:r?.modelVersion,agentVersionId:t??I?.id,hasMemory:T,activeVersionId:N,selectedVersionId:t??void 0,latestVersionId:I?.id,onVersionSelect:Z,isDirty:U,isSavingDraft:G,isPublishing:M,hasDraft:A,readOnly:L||!x,isCodeSourceAgent:b,showCodeModeActions:S,canOpenPr:k,openPrTitle:_,onSaveDraft:B,onPublish:$,onDownloadJson:z,onOpenPr:q,isViewingPreviousVersion:L})}):o.jsx("div",{className:"py-4 text-center",children:"Agent not found"})}function qus(){const{agentId:e}=mr(),{navigate:t}=cn(),{data:n,isLoading:r,error:s}=Vl(e);if(s&&Ss(s))return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Gs,{})});if(s&&ks(s))return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{resource:"agents"})});if(r)return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ut,{className:"h-6 w-6"})});if(!n)return o.jsx("div",{className:"py-4 text-center",children:"Agent not found"});const a=i=>{sessionStorage.setItem(`pending-scorer-items-${e}`,JSON.stringify(i)),t(`/agents/${e}/evaluate`)};return o.jsx(Qis,{agentId:e,onCreateScorer:a})}let Ku=(function(e){return e.AGENT="agent",e.SCORER="scorer",e.RAG_INGESTION="rag_ingestion",e.TRAJECTORY="trajectory",e.INPUT_PROCESSOR="input_processor",e.INPUT_STEP_PROCESSOR="input_step_processor",e.OUTPUT_PROCESSOR="output_processor",e.OUTPUT_STEP_PROCESSOR="output_step_processor",e.TOOL_RESULT_PROCESSOR="tool_result_processor",e.WORKFLOW_STEP="workflow_step",e.TOOL="tool",e.WORKFLOW_RUN="workflow_run",e.MEMORY="memory",e})({});I_().describe("Database record creation time");const Vus=I_().describe("Database record last update time");Vus.nullable();const EQ=je({page:x2().int().min(0).optional().default(0).describe("Zero-indexed page number"),perPage:x2().int().min(1).max(100).optional().default(10).describe("Number of items per page")}).describe("Pagination options for list queries"),TQ=je({total:Nt().describe("Total number of items available"),page:Nt().describe("Current page"),perPage:Gn([Nt(),zt(!1)]).describe("Number of items per page, or false if pagination is disabled"),hasMore:Ds().describe("True if more pages are available")}),yS=he().min(1).describe("Opaque cursor value for incremental polling"),jQ=Js(["page","delta"]).describe("List mode: 'page' | 'delta', defaults to 'page' when omitted."),NQ=x2().int().min(1).max(100).optional().describe("Maximum number of updates to return in one delta poll"),Hus={page:0,perPage:10};function IQ(e,t){if(e.mode==="delta"){e.pagination!==void 0&&t.addIssue({code:"custom",path:["pagination"],message:"pagination is not allowed in delta mode"}),e.orderBy!==void 0&&t.addIssue({code:"custom",path:["orderBy"],message:"orderBy is not allowed in delta mode"});return}e.after!==void 0&&t.addIssue({code:"custom",path:["after"],message:"after is only allowed in delta mode"}),e.limit!==void 0&&t.addIssue({code:"custom",path:["limit"],message:"limit is only allowed in delta mode"})}function AQ(e,t){return{mode:e.mode==="delta"?"delta":"page",filters:e.filters,pagination:e.pagination??t.pagination??Hus,orderBy:e.orderBy??t.orderBy,after:e.after,limit:e.limit??t.limit??10}}const RQ=je({limit:Nt().describe("Maximum number of updates requested for this delta poll"),hasMore:Ds().describe("True when more matching updates remain after this response")}).describe("Incremental polling metadata"),Wus=je({start:uDe().optional().describe("Start of date range (inclusive by default)"),end:uDe().optional().describe("End of date range (inclusive by default)"),startExclusive:Ds().optional().describe("When true, excludes the start date from results (uses > instead of >=)"),endExclusive:Ds().optional().describe("When true, excludes the end date from results (uses < instead of <=)")}).describe("Date range filter for timestamps"),ML=Js(["ASC","DESC"]).describe("Sort direction: 'ASC' | 'DESC'"),Gy=Js(["sum","avg","min","max","count","count_distinct","last"]).describe("Aggregation function"),CC=Js(["1m","5m","15m","1h","1d"]).describe("Time bucket interval"),hAe=Js(["previous_period","previous_day","previous_week"]).describe("Comparison period for aggregate queries"),EC=$t(he()).min(1).describe("Fields to group by"),mAe=$t(Nt().min(0).max(1)).min(1).describe("Percentile values (0-1)"),gAe={value:Nt().nullable().describe("Aggregated value"),previousValue:Nt().nullable().optional().describe("Value from comparison period"),changePercent:Nt().nullable().optional().describe("Percentage change from comparison period")},vAe=Ws(he(),he().nullable()).describe("Dimension values for this group"),iA=Nt().describe("Aggregated value"),oA=I_().describe("Bucket timestamp"),yAe=Nt().describe("Percentile value"),bAe=Nt().describe("Percentile value at this bucket"),lA=ewe(Ku).describe("Entity type (e.g., 'agent' | 'processor' | 'tool' | 'workflow')"),Zus=he().describe('ID of the entity (e.g., "weatherAgent", "orderWorkflow")'),uqt=he().describe("Name of the entity"),dqt=he().describe("Human end-user who triggered execution"),fqt=he().describe("Multi-tenant organization/account"),pqt=he().describe("Broader resource context (Mastra memory compatibility)"),hqt=he().describe("Unique execution run identifier"),mqt=he().describe("Session identifier for grouping traces"),gqt=he().describe("Conversation thread identifier"),vqt=he().describe("HTTP request ID for log correlation"),yqt=he().describe('Environment (e.g., "production" | "staging" | "development")'),Gus=he().describe('Source of execution (e.g., "local" | "cloud" | "ci")'),bqt=he().describe('Source of execution (e.g., "local" | "cloud" | "ci")'),xqt=he().describe("Name of the service"),wqt=ewe(Ku).describe("Entity type of the parent entity"),Qus=he().describe("ID of the parent entity"),Sqt=he().describe("Name of the parent entity"),kqt=ewe(Ku).describe("Entity type of the root entity"),Yus=he().describe("ID of the root entity"),Oqt=he().describe("Name of the root entity"),_qt=he().describe("Version ID of the entity that produced this signal (e.g., agent version, workflow version)"),Cqt=he().describe("Version ID of the parent entity that produced this signal"),Eqt=he().describe("Version ID of the root entity that produced this signal"),PQ=he().describe("Experiment or eval run identifier"),Kus=Ws(he(),Fa()).describe('Arbitrary package/app version info (e.g., {"core": "1.0.0", "memory": "1.0.0", "gitSha": "abcd1234"})'),xAe=Ws(he(),Fa()).describe("User-defined metadata for custom filtering"),Tqt=$t(he()).describe("Labels for filtering"),Xus={entityType:lA.nullish(),entityId:Zus.nullish(),entityName:uqt.nullish(),parentEntityType:wqt.nullish(),parentEntityId:Qus.nullish(),parentEntityName:Sqt.nullish(),rootEntityType:kqt.nullish(),rootEntityId:Yus.nullish(),rootEntityName:Oqt.nullish(),userId:dqt.nullish(),organizationId:fqt.nullish(),resourceId:pqt.nullish(),runId:hqt.nullish(),sessionId:mqt.nullish(),threadId:gqt.nullish(),requestId:vqt.nullish(),environment:yqt.nullish(),serviceName:xqt.nullish(),scope:Kus.nullish(),entityVersionId:_qt.nullish(),parentEntityVersionId:Cqt.nullish(),rootEntityVersionId:Eqt.nullish(),experimentId:PQ.nullish()},$Q={...Xus,executionSource:bqt.nullish(),tags:Tqt.nullish()};Gus.nullish();const MQ={timestamp:Wus.optional().describe("Filter by timestamp range"),traceId:he().optional().describe("Filter by trace ID"),spanId:he().optional().describe("Filter by span ID"),entityType:lA.optional(),entityName:uqt.optional(),entityVersionId:_qt.optional(),parentEntityVersionId:Cqt.optional(),rootEntityVersionId:Eqt.optional(),userId:dqt.optional(),organizationId:fqt.optional(),experimentId:PQ.optional(),serviceName:xqt.optional(),environment:yqt.optional(),parentEntityType:wqt.optional(),parentEntityName:Sqt.optional(),rootEntityType:kqt.optional(),rootEntityName:Oqt.optional(),resourceId:pqt.optional(),runId:hqt.optional(),sessionId:mqt.optional(),threadId:gqt.optional(),requestId:vqt.optional(),executionSource:bqt.optional(),tags:$t(he()).optional().describe("Filter by tags (must have all specified tags)")},DL=he().describe("Unique trace identifier"),DQ=he().describe("Unique span identifier within a trace"),cV=Js(["debug","info","warn","error","fatal"]),jqt=he().describe("Log message"),Nqt=Ws(he(),Fa()).describe("Structured data attached to the log"),Iqt=je({logId:he().nullish().describe("Unique id for this log event"),timestamp:I_().describe("When the log was created"),level:cV.describe("Log severity level"),message:jqt,data:Nqt.nullish(),traceId:DL.nullish(),spanId:DQ.nullish(),...$Q,source:he().nullish().describe("Execution source"),metadata:xAe.nullish()}).describe("Log record as stored in the database");je({level:cV,message:jqt,data:Nqt.optional(),tags:Tqt.optional()}).describe("User-provided log input");const Jus=Iqt;je({logs:$t(Jus)}).describe("Arguments for batch creating logs");const eds=je({...MQ,source:he().optional().describe("Filter by execution source"),level:Gn([cV,$t(cV)]).optional().describe("Filter by log level(s)")}).describe("Filters for querying logs"),tds=Js(["timestamp"]).describe("Field to order by: 'timestamp'"),nds=je({field:tds.default("timestamp").describe("Field to order by"),direction:ML.default("DESC").describe("Sort direction")}).describe("Order by configuration");je({mode:jQ.optional(),filters:eds.optional().describe("Optional filters to apply"),pagination:EQ.optional(),orderBy:nds.optional(),after:yS.optional(),limit:NQ}).strict().superRefine(IQ).transform(e=>AQ(e,{orderBy:{field:"timestamp",direction:"DESC"}})).describe("Arguments for listing logs");je({pagination:TQ.optional(),delta:RQ.optional(),deltaCursor:yS.optional(),logs:$t(Iqt)}).describe("Response from listing logs");const cA=he().describe("Identifier of the scorer (e.g., relevance, accuracy)"),Aqt=he().describe("Display name of the scorer"),Rqt=he().describe("Version of the scorer"),Ey=he().describe("How the score was produced (e.g., manual, automated, experiment)"),Pqt=Nt().describe("Score value (range defined by scorer)"),$qt=he().describe("Explanation for the score"),Mqt=je({scoreId:he().nullish().describe("Unique id for this score event"),timestamp:I_().describe("When the score was recorded"),traceId:DL.nullish().describe("Trace that anchors the scored target when available"),spanId:DQ.nullish().describe("Span ID this score applies to"),scorerId:cA,scorerName:Aqt.nullish(),scorerVersion:Rqt.nullish(),scoreSource:Ey.nullish(),source:Ey.nullish(),score:Pqt,reason:$qt.nullish(),...$Q,scoreTraceId:he().nullish().describe("Trace ID of the scoring run for debugging score generation"),metadata:Ws(he(),Fa()).nullish().describe("User-defined metadata")}).describe("Score record as stored in the database");je({scorerId:cA,scorerName:Aqt.optional(),scorerVersion:Rqt.optional(),scoreSource:Ey.optional(),source:Ey.optional(),score:Pqt,reason:$qt.optional(),metadata:Ws(he(),Fa()).optional().describe("Additional scorer-specific metadata"),experimentId:PQ.optional(),scoreTraceId:he().optional().describe("Trace ID of the scoring run for debugging score generation"),targetEntityType:lA.optional().describe("Entity type the scorer evaluated when known")}).describe("User-provided score input");const wAe=Mqt;je({score:wAe}).describe("Arguments for creating a score");je({score:wAe.omit({timestamp:!0})}).describe("Arguments for creating a score");je({success:Ds()}).describe("Response from creating a score");je({scores:$t(wAe)}).describe("Arguments for batch recording scores");const LL=je({...MQ,scorerId:Gn([he(),$t(he())]).optional().describe("Filter by scorer ID(s)"),scoreSource:Ey.optional().describe("Filter by how the score was produced"),metadata:xAe.nullish().describe("Filter by metadata key-value pairs (exact match per key)"),source:Ey.optional().describe("Filter by how the score was produced")}).describe("Filters for querying scores"),rds=Js(["timestamp","score"]).describe("Field to order by: 'timestamp' | 'score'"),sds=je({field:rds.default("timestamp").describe("Field to order by"),direction:ML.default("DESC").describe("Sort direction")}).describe("Order by configuration");je({mode:jQ.optional(),filters:LL.optional(),pagination:EQ.optional(),orderBy:sds.optional(),after:yS.optional(),limit:NQ}).strict().superRefine(IQ).transform(e=>AQ(e,{orderBy:{field:"timestamp",direction:"DESC"}})).describe("Arguments for listing scores");je({pagination:TQ.optional(),delta:RQ.optional(),deltaCursor:yS.optional(),scores:$t(Mqt)}).describe("Response from listing scores");je({scorerId:cA,scoreSource:Ey.optional(),aggregation:Gy,filters:LL.optional(),comparePeriod:hAe.optional()}).describe("Arguments for getting a score aggregate");je(gAe);je({scorerId:cA,scoreSource:Ey.optional(),groupBy:EC,aggregation:Gy,filters:LL.optional()}).describe("Arguments for getting a score breakdown");je({groups:$t(je({dimensions:vAe,value:iA}))});je({scorerId:cA,scoreSource:Ey.optional(),interval:CC,aggregation:Gy,filters:LL.optional(),groupBy:EC.optional()}).describe("Arguments for getting score time series");je({series:$t(je({name:he().describe("Series name (scorer ID or group key)"),points:$t(je({timestamp:oA,value:iA}))}))});je({scorerId:cA,scoreSource:Ey.optional(),percentiles:mAe,interval:CC,filters:LL.optional()}).describe("Arguments for getting score percentiles");je({series:$t(je({percentile:yAe,points:$t(je({timestamp:oA,value:bAe}))}))});const Ty=he().describe("Source of feedback (e.g., 'user', 'system', 'manual')"),uA=he().describe("Type of feedback (e.g., 'thumbs', 'rating', 'correction')"),Dqt=Gn([Nt(),he()]).describe("Feedback value (rating number or correction text)"),Lqt=he().describe("Additional comment or context"),uV=he().describe("User who provided the feedback");function SAe(e){if(!e||typeof e!="object"||Array.isArray(e))return e;const t={...e};return typeof t.userId=="string"&&t.feedbackUserId==null&&(t.feedbackUserId=t.userId,delete t.userId),t}const LQ=je({feedbackId:he().nullish().describe("Unique id for this feedback event"),timestamp:I_().describe("When the feedback was recorded"),traceId:DL.nullish().describe("Trace that anchors the feedback target when available"),spanId:DQ.nullish().describe("Span ID this feedback applies to"),feedbackSource:Ty.nullish(),source:Ty.nullish(),feedbackType:uA,value:Dqt,comment:Lqt.nullish(),feedbackUserId:uV.nullish(),...$Q,sourceId:he().nullish().describe("ID of the source record this feedback is linked to (e.g. experiment result ID)"),metadata:Ws(he(),Fa()).nullish().describe("User-defined metadata")}),ads=je(LQ.shape).describe("Feedback record as stored in the database"),ids=je({feedbackSource:Ty.optional(),source:Ty.optional(),feedbackType:uA,value:Dqt,comment:Lqt.optional(),feedbackUserId:uV.optional(),userId:uV.optional(),metadata:Ws(he(),Fa()).optional().describe("Additional feedback-specific metadata"),experimentId:PQ.optional(),sourceId:he().optional().describe("ID of the source record this feedback is linked to")});je(ids.shape).describe("User-provided feedback input");je({feedback:swe(SAe,LQ)}).describe("Arguments for creating feedback");je({feedback:LQ.omit({timestamp:!0})}).describe("Arguments for creating feedback");je({success:Ds()}).describe("Response from creating feedback");je({feedbacks:$t(swe(SAe,LQ))}).describe("Arguments for batch recording feedback");const Fqt=je({...MQ,feedbackType:Gn([he(),$t(he())]).optional().describe("Filter by feedback type(s)"),feedbackSource:Ty.optional(),source:Ty.optional(),feedbackUserId:uV.optional()}),FQ=je(Fqt.shape).describe("Filters for querying feedback"),ods=Js(["timestamp"]).describe("Field to order by: 'timestamp'"),lds=je({field:ods.default("timestamp").describe("Field to order by"),direction:ML.default("DESC").describe("Sort direction")}).describe("Order by configuration");je({mode:jQ.optional(),filters:swe(SAe,Fqt).optional(),pagination:EQ.optional(),orderBy:lds.optional(),after:yS.optional(),limit:NQ}).strict().superRefine(IQ).transform(e=>AQ(e,{orderBy:{field:"timestamp",direction:"DESC"}})).describe("Arguments for listing feedback");je({pagination:TQ.optional(),delta:RQ.optional(),deltaCursor:yS.optional(),feedback:$t(ads)}).describe("Response from listing feedback");je({feedbackType:uA,feedbackSource:Ty.optional(),aggregation:Gy,filters:FQ.optional(),comparePeriod:hAe.optional()}).describe("Arguments for getting a feedback aggregate over numeric values");je(gAe);je({feedbackType:uA,feedbackSource:Ty.optional(),groupBy:EC,aggregation:Gy,filters:FQ.optional()}).describe("Arguments for getting a feedback breakdown over numeric values");je({groups:$t(je({dimensions:vAe,value:iA}))});je({feedbackType:uA,feedbackSource:Ty.optional(),interval:CC,aggregation:Gy,filters:FQ.optional(),groupBy:EC.optional()}).describe("Arguments for getting feedback time series over numeric values");je({series:$t(je({name:he().describe("Series name (feedback type or group key)"),points:$t(je({timestamp:oA,value:iA}))}))});je({feedbackType:uA,feedbackSource:Ty.optional(),percentiles:mAe,interval:CC,filters:FQ.optional()}).describe("Arguments for getting feedback percentiles over numeric values");je({series:$t(je({percentile:yAe,points:$t(je({timestamp:oA,value:bAe}))}))});Js(["counter","gauge","histogram"]);const zqt=he().describe("Metric name (e.g., mastra_agent_duration_ms)"),Bqt=Nt().describe("Metric value"),Uqt=Ws(he(),he()).describe("Metric labels for dimensional filtering"),qqt=he().describe("Model provider"),Vqt=he().describe("Model"),cds=Nt().describe("Estimated cost"),Hqt=he().describe("Unit for the estimated cost (e.g., usd)"),uds=Ws(he(),Fa()).nullish().describe("Structured costing metadata"),Wqt=je({metricId:he().nullish().describe("Unique id for this metric event"),timestamp:I_().describe("When the metric was recorded"),name:zqt,value:Bqt,traceId:DL.nullish(),spanId:DQ.nullish(),...$Q,source:he().nullish().describe("Execution source"),provider:qqt.nullish(),model:Vqt.nullish(),estimatedCost:cds.nullish(),costUnit:Hqt.nullish(),costMetadata:uds.nullish(),labels:Uqt.default({}),metadata:xAe.nullish()}).describe("Metric record as stored in the database");je({name:zqt,value:Bqt,labels:Uqt.optional()}).describe("User-provided metric input");const dds=Wqt;je({metrics:$t(dds)}).describe("Arguments for batch recording metrics");je({type:Gy,interval:CC.optional(),groupBy:EC.optional()}).describe("Metrics aggregation configuration");const FL=je({...MQ,traceIds:$t(DL).nonempty().max(1e3).optional().describe("Filter by one or more trace IDs"),name:$t(he()).nonempty().optional().describe("Filter by metric name(s)"),source:he().optional().describe("Filter by execution source"),provider:qqt.optional(),model:Vqt.optional(),costUnit:Hqt.optional(),labels:Ws(he(),he()).optional().describe("Exact match on label key-value pairs")}).describe("Filters for querying metrics"),fds=Js(["timestamp"]).describe("Field to order by: 'timestamp'"),pds=je({field:fds.default("timestamp").describe("Field to order by"),direction:ML.default("DESC").describe("Sort direction")}).describe("Order by configuration");je({mode:jQ.optional(),filters:FL.optional(),pagination:EQ.optional(),orderBy:pds.optional(),after:yS.optional(),limit:NQ}).strict().superRefine(IQ).transform(e=>AQ(e,{orderBy:{field:"timestamp",direction:"DESC"}})).describe("Arguments for listing metrics");je({pagination:TQ.optional(),delta:RQ.optional(),deltaCursor:yS.optional(),metrics:$t(Wqt)}).describe("Response from listing metrics");const hds=["entityType","entityName","parentEntityType","parentEntityName","rootEntityType","rootEntityName","name","provider","model","environment","executionSource","serviceName","threadId","resourceId"],kAe=Js(hds).optional().describe("Column to apply count_distinct over (required when aggregation is 'count_distinct'). Restricted to allowlisted metric dimensions."),qN={check:e=>e.aggregation!=="count_distinct"||e.distinctColumn!==void 0,options:{message:"distinctColumn is required when aggregation is 'count_distinct'",path:["distinctColumn"]}};je({name:$t(he()).nonempty().describe("Metric name(s) to aggregate"),aggregation:Gy,distinctColumn:kAe,filters:FL.optional(),comparePeriod:hAe.optional()}).refine(qN.check,qN.options).describe("Arguments for getting a metric aggregate");je({...gAe,estimatedCost:Nt().nullable().optional().describe("Aggregated estimated cost from the same filtered row set"),costUnit:he().nullable().optional().describe("Shared cost unit for the aggregated rows, or null when mixed/unknown"),previousEstimatedCost:Nt().nullable().optional().describe("Aggregated estimated cost from the comparison period"),costChangePercent:Nt().nullable().optional().describe("Percentage change in estimated cost from comparison period")});je({name:$t(he()).nonempty().describe("Metric name(s) to break down"),groupBy:EC,aggregation:Gy,distinctColumn:kAe,filters:FL.optional(),limit:Nt().int().positive().max(1e3).optional().describe("Maximum number of groups to return (server-side TopK). Required for high-cardinality groupBy."),orderDirection:ML.optional().describe("Sort direction for the aggregated value (defaults to 'DESC' at the storage layer; pairs with limit for top/bottom-N).")}).refine(qN.check,qN.options).describe("Arguments for getting a metric breakdown");je({groups:$t(je({dimensions:vAe,value:iA,estimatedCost:Nt().nullable().optional().describe("Summed estimated cost for this group"),costUnit:he().nullable().optional().describe("Shared cost unit for this group, or null when mixed/unknown")}))});je({name:$t(he()).nonempty().describe("Metric name(s)"),interval:CC,aggregation:Gy,distinctColumn:kAe,filters:FL.optional(),groupBy:EC.optional()}).refine(qN.check,qN.options).describe("Arguments for getting metric time series");je({series:$t(je({name:he().describe("Series name (metric name or group key)"),costUnit:he().nullable().optional().describe("Shared cost unit for this series, or null when mixed/unknown"),points:$t(je({timestamp:oA,value:iA,estimatedCost:Nt().nullable().optional().describe("Summed estimated cost in this bucket")}))}))});je({name:he().describe("Metric name"),percentiles:mAe,interval:CC,filters:FL.optional()}).describe("Arguments for getting metric percentiles");je({series:$t(je({percentile:yAe,points:$t(je({timestamp:oA,value:bAe}))}))});je({prefix:he().optional().describe("Filter metric names by prefix"),limit:x2().int().min(1).optional().describe("Maximum number of names to return")}).describe("Arguments for getting metric names");je({names:$t(he()).describe("Distinct metric names")});je({metricName:he().describe("Metric name to get label keys for")}).describe("Arguments for getting metric label keys");je({keys:$t(he()).describe("Distinct label keys for the metric")});je({metricName:he().describe("Metric name"),labelKey:he().describe("Label key to get values for"),prefix:he().optional().describe("Filter values by prefix"),limit:x2().int().min(1).optional().describe("Maximum number of values to return")}).describe("Arguments for getting label values");je({values:$t(he()).describe("Distinct label values")});je({}).describe("Arguments for getting entity types");je({entityTypes:$t(lA).describe("Distinct entity types")});je({entityType:lA.optional().describe("Optional entity type filter")}).describe("Arguments for getting entity names");je({names:$t(he()).describe("Distinct entity names")});je({}).describe("Arguments for getting service names");je({serviceNames:$t(he()).describe("Distinct service names")});je({}).describe("Arguments for getting environments");je({environments:$t(he()).describe("Distinct environments")});je({entityType:lA.optional().describe("Optional entity type filter")}).describe("Arguments for getting tags");je({tags:$t(he()).describe("Distinct tags")});new Set(Object.values(Ku));function OAe({disabled:e,onClear:t,onRemoveAll:n,onSave:r,onRemoveSaved:s}){const a=!!(n||r||s);return!t&&!a?null:o.jsxs("div",{className:"flex items-center gap-2",children:[t&&o.jsxs(oe,{disabled:e,size:"md",onClick:t,children:[o.jsx(or,{}),"Clear"]}),a&&o.jsxs(rt,{children:[o.jsx(rt.Trigger,{asChild:!0,children:o.jsx(oe,{disabled:e,size:"md","aria-label":"More filter actions",children:o.jsx(JN,{})})}),o.jsxs(rt.Content,{align:"end",children:[n&&o.jsxs(rt.Item,{onSelect:()=>n(),children:[o.jsx(or,{}),"Remove all filters"]}),n&&(r||s)&&o.jsx(rt.Separator,{}),r&&o.jsxs(rt.Item,{onSelect:()=>r(),children:[o.jsx(Gu,{}),"Save filters for next time"]}),s&&o.jsxs(rt.Item,{onSelect:()=>s(),children:[o.jsx(Ml,{}),"Remove saved filters"]})]})]})]})}function Zqt({field:e,tokens:t,onChange:n}){const[r,s]=g.useState(""),a=g.useMemo(()=>{const u=r.trim().toLowerCase();return u?e.options.filter(d=>d.label.toLowerCase().includes(u)):e.options},[e.options,r]),i=g.useMemo(()=>t.find(u=>u.fieldId===e.id),[t,e.id]),l=typeof i?.value=="string"?i.value:e.multi?void 0:e.defaultValue,c=g.useMemo(()=>{const u=i?.value;return Array.isArray(u)?u:typeof u=="string"?[u]:[]},[i]);return o.jsxs(o.Fragment,{children:[e.searchable!==!1&&o.jsx(In,{size:"sm",value:r,onChange:u=>s(u.target.value),placeholder:`Search ${e.label.toLowerCase()}...`,className:"mb-2",onKeyDown:u=>{if(u.key!=="ArrowDown")return;const f=u.currentTarget.closest("[data-pick-multi-panel]")?.querySelector("[data-pick-multi-item]:not([disabled])");f&&(u.preventDefault(),u.stopPropagation(),f.focus())}}),e.isLoading?o.jsxs("div",{className:"text-ui-sm text-neutral3 flex items-center gap-2 px-2 py-1.5",children:[o.jsx(Ut,{size:"sm",className:"text-neutral3 size-3"}),"Loading options…"]}):a.length===0?o.jsx("div",{className:"text-ui-sm text-neutral3 px-2 py-1.5",children:e.emptyText??"No option found."}):e.multi?o.jsx("div",{className:"max-h-[80dvh] overflow-auto",children:a.map(u=>{const d=c.includes(u.value);return o.jsxs("label",{title:u.label,className:"text-ui-md text-neutral4 focus-within:bg-surface4 focus-within:text-neutral6 hover:bg-surface4 hover:text-neutral6 flex min-w-0 cursor-pointer items-center gap-2 rounded-md px-2 py-1.5",children:[o.jsx(So,{"data-pick-multi-item":"",checked:d,onCheckedChange:f=>{const h=f===!0?c.includes(u.value)?c:[...c,u.value]:c.filter(m=>m!==u.value);n(e.id,h)},className:"shrink-0"}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:u.label})]},u.value)})}):o.jsxs(G4,{value:l??"",onValueChange:u=>n(e.id,u),className:"max-h-[80dvh] gap-0 overflow-auto",children:[a.map(u=>o.jsxs("label",{title:u.label,className:"text-ui-md text-neutral4 focus-within:bg-surface4 focus-within:text-neutral6 hover:bg-surface4 hover:text-neutral6 flex min-w-0 cursor-pointer items-center gap-2 rounded-md px-2 py-1.5",children:[o.jsx(Pp,{"data-pick-multi-item":"",value:u.value,className:"shrink-0"}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:u.label})]},u.value)),!e.omitAnyOption&&o.jsxs("label",{title:"Any",className:"text-ui-md text-neutral4 focus-within:bg-surface4 focus-within:text-neutral6 hover:bg-surface4 hover:text-neutral6 flex min-w-0 cursor-pointer items-center gap-2 rounded-md px-2 py-1.5",children:[o.jsx(Pp,{"data-pick-multi-item":"",value:"Any",className:"shrink-0"}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:"Any"})]})]})]})}function _Ae(e){return Array.isArray(e)?e.length===0?"Any":e.join(", "):e}const mds="This filter is set by the current context and cannot be removed here.";function gds(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:_Ae(t)}function vds({field:e,value:t,tooltipContent:n}){const r=gds(e,t),s=`${e.label} filter is locked by context`;return o.jsx(zl,{delayDuration:150,children:o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:o.jsxs(hs,{spacing:"close","data-locked-field-id":e.id,"data-property-filter-pill":"locked",tabIndex:0,"aria-label":s,children:[o.jsx(Kh,{size:"md",children:e.label}),o.jsx(Kh,{size:"md",children:"is"}),o.jsx(Kh,{size:"md",children:r}),o.jsx(Kh,{size:"md",children:o.jsx(Bd,{})})]})}),o.jsx(vn,{children:n})]})})}function yds({field:e,value:t,onChange:n,onRemove:r,disabled:s,autoFocus:a}){const[i,l]=g.useState(t),c=g.useRef(null);return g.useEffect(()=>{i.trim()!==t&&l(t)},[t]),g.useEffect(()=>{a&&c.current?.focus()},[a]),o.jsxs(hs,{spacing:"close",children:[o.jsx(Kh,{size:"md",children:e.label}),o.jsx(Kh,{size:"md",children:"is"}),o.jsx(In,{ref:c,size:"md",disabled:s,value:i,placeholder:e.placeholder??`Enter ${e.label}`,onChange:u=>{const d=u.target.value;l(d),d.trim()!==t&&n(d)},onKeyDown:u=>{if(u.key==="Enter"){u.preventDefault();const d=i.trim();d!==t&&n(d)}else u.key==="Escape"&&(u.preventDefault(),l(t),u.target.blur())}}),o.jsx(oe,{type:"button",disabled:s,"aria-label":`Remove ${e.label} filter`,size:"md",onMouseDown:u=>u.preventDefault(),onClick:r,children:o.jsx(or,{})})]})}function bds({field:e,token:t,tokens:n,onChange:r,onRemove:s,disabled:a}){const[i,l]=g.useState(!1);return o.jsxs(hs,{spacing:"close",children:[o.jsx(Kh,{size:"md",children:e.label}),o.jsx(Kh,{size:"md",children:"is"}),o.jsxs(Uf,{open:i,onOpenChange:l,children:[o.jsx(Kd,{asChild:!0,children:o.jsx(oe,{type:"button",disabled:a,size:"md",children:_Ae(t.value)})}),o.jsx(Xd,{align:"start",sideOffset:8,className:"w-64 p-2","data-pick-multi-panel":!0,children:o.jsx(Zqt,{field:e,tokens:n,onChange:r})})]}),o.jsx(oe,{type:"button",disabled:a,"aria-label":`Remove ${e.label} filter`,size:"md",onClick:s,children:o.jsx(or,{})})]})}function CAe({fields:e,tokens:t,onTokensChange:n,disabled:r,autoFocusFieldId:s,lockedFieldIds:a,lockedTooltipContent:i=mds}){if(t.length===0)return null;const l=new Set(a??[]),c=(d,f)=>{const p=[...t];p[d]=f,n(p)},u=d=>{n(t.filter((f,p)=>p!==d))};return o.jsx("div",{className:"flex flex-wrap items-center gap-2",children:t.map((d,f)=>{const p=e.find(h=>h.id===d.fieldId);return p?l.has(d.fieldId)?o.jsx(vds,{field:p,value:d.value,tooltipContent:i},`${d.fieldId}-${f}`):p.kind==="text"&&typeof d.value=="string"?o.jsx(yds,{field:p,value:d.value,disabled:r,autoFocus:s===d.fieldId,onChange:h=>c(f,{fieldId:d.fieldId,value:h}),onRemove:()=>u(f)},`${d.fieldId}-${f}`):p.kind==="pick-multi"?o.jsx(bds,{field:p,token:d,tokens:t,disabled:r,onChange:(h,m)=>c(f,{fieldId:h,value:m}),onRemove:()=>u(f)},`${d.fieldId}-${f}`):o.jsxs(hs,{spacing:"close",children:[o.jsx(Kh,{size:"md",children:p.label}),o.jsx(Kh,{size:"md",children:"is"}),o.jsx(Kh,{size:"md",children:_Ae(d.value)}),o.jsx(oe,{type:"button",disabled:r,size:"md","aria-label":`Remove ${p.label} filter`,onClick:()=>u(f),children:o.jsx(or,{})})]},`${d.fieldId}-${f}`):null})})}function EAe({fields:e,tokens:t,onTokensChange:n,label:r="Add Filter",disabled:s,size:a,onStartTextFilter:i,hiddenFieldIds:l}){const c=g.useMemo(()=>{if(!l||l.length===0)return e;const A=new Set(l);return e.filter(R=>!A.has(R.id))},[e,l]),[u,d]=g.useState(!1),[f,p]=g.useState(),[h,m]=g.useState([]),[v,y]=g.useState(),[b,x]=g.useState(),S=g.useRef(!1),k=g.useCallback(A=>{x(R=>R===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 R of t){const L=e.find(D=>D.id===R.fieldId);L&&L.kind!=="pick-multi"&&A.add(R.fieldId)}return A},[t,e]),E=g.useCallback(()=>{p(void 0),m([]),y(void 0)},[]);g.useEffect(()=>{u||E()},[u,E]);const N=g.useCallback((A,R)=>{const L=t.findIndex(F=>F.fieldId===A);if(Array.isArray(R)&&R.length===0){if(L===-1)return;n(t.filter((F,H)=>H!==L));return}if(L===-1){n([...t,{fieldId:A,value:R}]);return}const D=[...t];D[L]={fieldId:A,value:R},n(D)},[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(h.length===0){y(`Choose at least one ${C.label.toLowerCase()} value.`);return}n([...t,{fieldId:C.id,value:h}]),d(!1)},[h,n,C,T,t]);return o.jsxs(Uf,{open:u,onOpenChange:d,children:[o.jsx(Kd,{asChild:!0,children:o.jsxs(oe,{variant:"outline",size:a,disabled:s,children:[o.jsx($Kt,{}),r]})}),o.jsx(Xd,{align:"end",className:"w-64 p-3",initialFocus:!1,finalFocus:()=>S.current?(S.current=!1,!1):!0,children:o.jsxs("div",{className:"grid 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(gl,{className:"size-4"})}),o.jsx(i0e,{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 R=Array.from(A.currentTarget.querySelectorAll("[data-filter-item]:not([disabled])"));if(R.length===0)return;A.preventDefault();const L=document.activeElement,D=R.findIndex(H=>H===L);let F;A.key==="Home"?F=0:A.key==="End"?F=R.length-1:A.key==="ArrowDown"?F=D<0?0:(D+1)%R.length:F=D<=0?R.length-1:D-1,R[F]?.focus()},children:c.length>0?c.map(A=>{const R=T.has(A.id);return A.kind==="pick-multi"?o.jsx(xds,{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("group flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-ui-md transition-colors","focus:bg-surface4 focus:text-neutral6 focus:outline-none",R?"cursor-not-allowed text-neutral2 opacity-70":"text-neutral4 hover:bg-surface4 hover:text-neutral6"),disabled:R,onClick:()=>{if(y(void 0),A.kind==="text"){n([...t,{fieldId:A.id,value:""}]),i?.(A.id),S.current=!0,d(!1);return}p(A.id)},children:[o.jsx("span",{className:"truncate",children:A.label}),R?o.jsx("span",{className:"text-neutral3 ml-auto",children:"In use"}):o.jsx(Or,{className:"text-neutral3 ml-auto size-4 opacity-0 transition-opacity group-hover:opacity-100 group-focus:opacity-100"})]},A.id)}):o.jsx("div",{className:"text-ui-sm text-neutral3 px-2 py-1.5",children:"No matching property."})}),C&&o.jsx(ml,{multiple:!0,options:C.options??[],value:h,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(oe,{variant:"ghost",size:"md",onClick:()=>d(!1),children:"Cancel"}),o.jsx(oe,{variant:"outline",size:"md",onClick:I,children:"Add filter"})]})]})})]})}function xds({field:e,tokens:t,onChange:n,open:r,onToggle:s,onClose:a}){const i=g.useRef(null);return o.jsxs(Uf,{open:r,onOpenChange:l=>{l?s(e.id):a()},children:[o.jsx(Kd,{asChild:!0,children:o.jsxs("button",{type:"button",role:"menuitem","data-filter-item":"",className:K("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-ui-md text-neutral4 transition-colors hover:bg-surface4 hover:text-neutral6","focus:bg-surface4 focus:text-neutral6 focus:outline-none"),onKeyDown:l=>{l.key!=="ArrowRight"&&l.key!=="ArrowLeft"||(r||s(e.id),l.preventDefault(),requestAnimationFrame(()=>{i.current?.querySelector('input, button, [tabindex]:not([tabindex="-1"])')?.focus()}))},children:[r&&o.jsx(Ur,{className:"text-neutral3 size-4 shrink-0"}),o.jsx("span",{className:"truncate",children:e.label}),!r&&o.jsx(Ur,{className:"text-neutral3 ml-auto size-4 shrink-0"})]})}),o.jsx(Xd,{ref:i,side:"right",align:"start",sideOffset:8,className:"w-64 p-2",initialFocus:!1,onKeyDown:l=>{if(l.key!=="ArrowDown"&&l.key!=="ArrowUp"&&l.key!=="Home"&&l.key!=="End")return;const c=Array.from(l.currentTarget.querySelectorAll("[data-pick-multi-item]:not([disabled])"));if(c.length===0)return;l.preventDefault(),l.stopPropagation();const u=document.activeElement,d=c.findIndex(p=>p===u);let f;l.key==="Home"?f=0:l.key==="End"?f=c.length-1:l.key==="ArrowDown"?f=d<0?0:(d+1)%c.length:f=d<=0?c.length-1:d-1,c[f]?.focus()},"data-pick-multi-panel":!0,children:o.jsx(Zqt,{field:e,tokens:t,onChange:n})})]})}const wds={"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"},yie="MMM d, yyyy HH:mm",bie="Pick a wider time range — older traces may fall outside the current window.";function Sds({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No traces for ${wds[e]}`,description:bie}:t&&n?{title:`No traces between ${hr(t,yie)} and ${hr(n,yie)}`,description:bie}:t?{title:`No traces since ${hr(t,yie)}`,description:bie}:{title:"No traces yet",description:"Traces will appear here once agents, workflows, or tools are executed."}}const kds=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=Sds({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Er,{iconSlot:o.jsx(Mc,{}),titleSlot:r,descriptionSlot:s})})},Ods=["input","entity","duration"],pet={input:"Input",entity:"Entity",duration:"Duration",inputTokens:"Input tokens",outputTokens:"Output tokens",estimatedCost:"Estimated cost"};function _ds({preferences:e,usageDisabledReason:t,onToggleColumn:n,onAddMetadataColumn:r,onRemoveMetadataColumn:s,onReset:a}){const[i,l]=g.useState(!1),[c,u]=g.useState(""),[d,f]=g.useState(),p=m=>{l(m),m||(u(""),f(void 0))},h=m=>{m.preventDefault();const v=c.trim();if(!v){f("Enter a metadata key.");return}if(e.metadataKeys.includes(v)){f("That metadata column is already visible.");return}r(v),p(!1)};return o.jsxs(o.Fragment,{children:[o.jsxs(rt,{children:[o.jsx(rt.Trigger,{render:o.jsxs(oe,{variant:"outline",size:"md",children:[o.jsx(Mlt,{"aria-hidden":!0}),"Columns"]})}),o.jsxs(rt.Content,{align:"end",className:"min-w-56",children:[o.jsx(rt.Label,{children:"Standard columns"}),Ods.map(m=>o.jsx(rt.CheckboxItem,{checked:e.visibleColumns.includes(m),onCheckedChange:()=>n(m),children:pet[m]},m)),o.jsx(rt.Separator,{}),o.jsx(rt.Label,{children:"Usage columns"}),VUt.map(m=>o.jsx(rt.CheckboxItem,{checked:e.visibleColumns.includes(m),disabled:!!t,onCheckedChange:()=>n(m),children:pet[m]},m)),t&&o.jsx("p",{className:"text-ui-xs leading-ui-sm text-neutral2 px-2 py-1",role:"note",children:t}),o.jsx(rt.Separator,{}),o.jsx(rt.Label,{children:"Metadata columns"}),e.metadataKeys.map(m=>o.jsx(rt.CheckboxItem,{checked:!0,title:m,onCheckedChange:()=>s(m),children:m},m)),o.jsxs(rt.Item,{onSelect:()=>l(!0),children:[o.jsx(Or,{"aria-hidden":!0}),"Add metadata column"]}),o.jsx(rt.Separator,{}),o.jsx(rt.Item,{onSelect:a,children:"Reset to defaults"})]})]}),o.jsx(vr,{open:i,onOpenChange:p,children:o.jsx(yr,{children:o.jsxs("form",{onSubmit:h,children:[o.jsxs(br,{children:[o.jsx(pr,{children:"Add metadata column"}),o.jsx(Ps,{children:"Enter a top-level trace metadata key. Only the key is saved, never its values."})]}),o.jsxs(Mr,{className:"space-y-2",children:[o.jsx(Mt,{htmlFor:"trace-metadata-key",children:"Metadata key"}),o.jsx(In,{id:"trace-metadata-key",value:c,onChange:m=>{u(m.target.value),f(void 0)},placeholder:"tenantId",autoFocus:!0,error:!!d,"aria-describedby":d?"trace-metadata-key-error":void 0}),d&&o.jsx("p",{id:"trace-metadata-key-error",className:"text-ui-xs text-error",role:"alert",children:d})]}),o.jsxs(lc,{children:[o.jsx(oe,{type:"button",variant:"outline",onClick:()=>p(!1),children:"Cancel"}),o.jsx(oe,{type:"submit",variant:"primary",children:"Add column"})]})]})})})]})}function Cds({listSlot:e,tracePanelSlot:t,spanPanelSlot:n,scorePanelSlot:r,traceCollapsed:s,sidePanelWide:a}){const i=!!t;return o.jsxs("div",{className:K("grid max-h-full min-h-0 items-start gap-4 transition-[grid-template-columns] duration-300 ease-in-out",i?a?"grid-cols-[1fr_4fr]":"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[e,i&&o.jsxs("div",{className:K("grid max-h-full gap-4 overflow-auto",!s&&"h-full",r?s?"grid-rows-[auto_3fr_3fr]":"grid-rows-[2fr_3fr_3fr]":n?s?"grid-rows-[auto_3fr]":"grid-rows-[2fr_3fr]":s?"grid-rows-[auto]":"grid-rows-[1fr]"),children:[t,n,r]})]})}function Eds({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c,lockedFieldIds:u,lockedTooltipContent:d}){const f=i.length>0,p=new Set(u??[]),h=i.filter(y=>!p.has(y.fieldId)),m=h.some(y=>Tds(y,a)),v=h.length>0;return f?o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] items-start gap-3 "),children:[o.jsx(CAe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c,lockedFieldIds:u,lockedTooltipContent:d}),f&&v&&o.jsx(OAe,{disabled:s,onClear:m?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function Tds(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 zQ=300*1e3,Hz={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},TAe=[{label:"Agent",entityType:Hz.AGENT},{label:"Workflow",entityType:Hz.WORKFLOW},{label:"Scorer",entityType:Hz.SCORER},{label:"Ingest",entityType:Hz.INGEST}],jds=[{label:"Running",value:"running"},{label:"Success",value:"success"},{label:"Error",value:"error"}],Gx="rootEntityType",Qx="status",Mw="listMode",k9="anchorSpanId",Nds=new Set(["traces","branches"]),Dw="datePreset",Lw="dateFrom",Fw="dateTo",Ids=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),Ol={tags:"filterTags",entityId:"filterEntityId",entityName:"filterEntityName",traceId:"filterTraceId",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId"},zL=Object.keys(Ol),Ads=new Set(["running","success","error"]),jAe="mastra:traces:saved-filters";function Rds(e,t=jAe){const n=Lds(e),r=e.get(Dw);r&&n.set(Dw,r);const s=e.get(Lw);s&&n.set(Lw,s);const a=e.get(Fw);a&&n.set(Fw,a);try{localStorage.setItem(t,n.toString())}catch{}}function Pds(e=jAe){try{localStorage.removeItem(e)}catch{}}function het(e=jAe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function $ds(e){if(e.has(Dw)||e.has(Lw)||e.has(Fw)||e.has(Gx)||e.has(Qx)||e.has(Mw))return!0;for(const t of zL)if(e.has(Ol[t]))return!0;return!1}function Mds({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:TAe.map(u=>({label:u.label,value:u.entityType})),placeholder:"Choose entity type",emptyText:"No entity types."},{id:"entityName",label:"Primitive Name",kind:"pick-multi",options:t.map(u=>({label:u,value:u})),placeholder:"Choose entity names",emptyText:"No entity names found.",isLoading:s?.entityNames},{id:"entityId",label:"Primitive ID",kind:"text"},{id:"status",label:"Status",kind:"pick-multi",searchable:!1,options:jds.map(u=>({label:u.label,value:u.value})),placeholder:"Choose status",emptyText:"No statuses."},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"traceId",label:"Trace ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"threadId",label:"Thread ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function Dds(e){const t=[],n=new Map([[Gx,"rootEntityType"],[Qx,"status"]]);for(const s of zL)n.set(Ol[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),a==="tags"){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function Lds(e){const t=new URLSearchParams,n=e.get(Gx);n&&t.set(Gx,n);const r=e.get(Qx);r&&t.set(Qx,r);const s=e.get(Mw);s&&t.set(Mw,s);for(const a of zL){const i=Ol[a];if(a==="tags"){for(const c of e.getAll(i))t.append(i,c);continue}const l=e.get(i);l&&t.set(i,l)}return t}function Fds(e,t){e.delete(Gx),e.delete(Qx);for(const n of zL)e.delete(Ol[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(Gx,n.value);continue}if(n.fieldId==="status"&&typeof n.value=="string"){e.set(Qx,n.value);continue}const r=Ol[n.fieldId];if(r){if(n.fieldId==="tags"&&Array.isArray(n.value)){if(n.value.length===0)e.append(r,"");else for(const s of n.value)e.append(r,s);continue}typeof n.value=="string"&&e.set(r,n.value.trim())}}}function zds({rootEntityType:e,status:t,dateFrom:n,dateTo:r,tokens:s}){const a={};e&&(a.entityType=e),t&&(a.status=t),n&&(a.startedAt={start:n}),r&&(a.endedAt={end:r});for(const i of s){if(i.fieldId==="tags"){Array.isArray(i.value)&&i.value.length>0?a.tags=i.value:typeof i.value=="string"&&i.value.trim()&&(a.tags=[i.value.trim()]);continue}if(typeof i.value=="string"&&i.value.trim()&&i.value!=="Any")switch(i.fieldId){case"entityId":a.entityId=i.value;break;case"entityName":a.entityName=i.value;break;case"traceId":a.traceId=i.value;break;case"runId":a.runId=i.value;break;case"threadId":a.threadId=i.value;break;case"sessionId":a.sessionId=i.value;break;case"requestId":a.requestId=i.value;break;case"resourceId":a.resourceId=i.value;break;case"userId":a.userId=i.value;break;case"organizationId":a.organizationId=i.value;break;case"serviceName":a.serviceName=i.value;break;case"environment":a.environment=i.value;break;case"experimentId":a.experimentId=i.value;break}}return a}function Bds(e,t){return t.map(n=>{const r=e.find(s=>s.id===n.fieldId);return r?r.kind==="text"?{fieldId:n.fieldId,value:""}:r.kind==="pick-multi"?r.omitAnyOption?n:r.multi?{fieldId:n.fieldId,value:[]}:{fieldId:n.fieldId,value:"Any"}:n:n})}function met(e){return Object.values(Ku).find(t=>t===e)}const NAe=({entityType:e,rootOnly:t=!1}={})=>{const n=Qe();return yt({queryKey:e?["observability-entity-names","by-type",e]:["observability-entity-names","all",t?"root-only":"all-types"],queryFn:async()=>{try{if(e){const a=met(e);return a?await n.getEntityNames({entityType:a}):{names:[]}}if(!t)return await n.getEntityNames();const s=await Promise.all(TAe.map(a=>{const i=met(a.entityType);return i?n.getEntityNames({entityType:i}):{names:[]}}));return{names:Array.from(new Set(s.flatMap(a=>a?.names??[]))).sort()}}catch{return{names:[]}}},select:s=>s?.names??[],retry:!1,staleTime:zQ})},IAe=()=>{const e=Qe();return yt({queryKey:["observability-environments"],queryFn:async()=>{try{return await e.getEnvironments()}catch{return{environments:[]}}},select:t=>t?.environments??[],retry:!1,staleTime:zQ})},AAe=()=>{const e=Qe();return yt({queryKey:["observability-service-names"],queryFn:async()=>{try{return await e.getServiceNames()}catch{return{serviceNames:[]}}},select:t=>t?.serviceNames??[],retry:!1,staleTime:zQ})},RAe=()=>{const e=Qe();return yt({queryKey:["observability-tags"],queryFn:async()=>{try{return await e.getTags()}catch{return{tags:[]}}},select:t=>t?.tags??[],retry:!1,staleTime:zQ})};function xie(e){if(typeof window>"u")return $w;try{return Rcs(window.localStorage.getItem(e)??void 0)}catch{return $w}}function Uds(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,Pcs(t))}catch{}}function qds(){const e=Qe(),t=e.options.baseUrl||(typeof window>"u"?"local":window.location.origin||"local"),n=e.options.apiPrefix??"/api",r=`mastra:traces:columns:${t}:${n}`,[s,a]=g.useState(()=>({storageKey:r,preferences:xie(r),shouldPersist:!1})),i=s.storageKey===r?s.preferences:xie(r);g.useEffect(()=>{s.storageKey===r&&s.shouldPersist&&Uds(r,s.preferences)},[s,r]);const l=p=>{a(h=>{const m=h.storageKey===r?h.preferences:xie(r),v=p(m);return{storageKey:r,preferences:v,shouldPersist:!0}})};return{preferences:i,toggleColumn:p=>{l(h=>{const m=h.visibleColumns.includes(p);return{...h,visibleColumns:m?h.visibleColumns.filter(v=>v!==p):[...h.visibleColumns,p]}})},addMetadataColumn:p=>{const h=p.trim();h&&l(m=>m.metadataKeys.includes(h)?m:{...m,metadataKeys:[...m.metadataKeys,h]})},removeMetadataColumn:p=>{l(h=>({...h,metadataKeys:h.metadataKeys.filter(m=>m!==p)}))},resetColumns:()=>l(()=>$w)}}const Vds="Trace filter settings saved.",Hds="Trace filter settings cleared.";function Wds(e,t,n){const{storageKey:r,messages:s,skipHydration:a}=n??{},[i,l]=g.useState(()=>het(r)!==null),c=g.useCallback(()=>{Rds(e,r),l(!0);const f=s?.saved??Vds;f!==!1&&Be.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{Pds(r),l(!1);const f=s?.cleared??Hds;f!==!1&&Be.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(a||d.current||(d.current=!0,$ds(e)))return;const f=het(r);f&&t(p=>{const h=new URLSearchParams(p);for(const[m,v]of f)h.append(m,v);return h},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}const O9="traceId",Db="spanId",Ev="tab",Tv="scoreId",wP=1440*60*1e3,Zds={"last-24h":wP,"last-3d":3*wP,"last-7d":7*wP,"last-14d":14*wP,"last-30d":30*wP};function SP(e){e.delete(O9),e.delete(Db),e.delete(k9),e.delete(Ev),e.delete(Tv)}function Gds(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const B=e.get(Dw);return B&&Ids.has(B)?B:"last-24h"},[e]),a=e.get(Lw),i=e.get(Fw),l=g.useMemo(()=>{if(s==="custom"){if(!a)return;const z=new Date(a);return Number.isNaN(z.getTime())?void 0:z}const B=Zds[s];return B?new Date(Date.now()-B):void 0},[s,a]),c=g.useMemo(()=>{if(s!=="custom"||!i)return;const B=new Date(i);return Number.isNaN(B.getTime())?void 0:B},[s,i]),u=g.useRef(s);u.current=s;const d=e.get(O9)||void 0,f=e.get(Db)||void 0,p=e.get(k9)||void 0,h=e.get(Ev),m=h==="feedback"?"feedback":h==="details"?"details":void 0,v=e.get(Tv)||void 0,y=g.useMemo(()=>{const B=e.get(Mw);return B&&Nds.has(B)?B:"traces"},[e]),b=g.useMemo(()=>TAe.find(B=>B.entityType===e.get(Gx)),[e]),x=g.useMemo(()=>{const B=e.get(Qx);return B&&Ads.has(B)?B:void 0},[e]),S=g.useMemo(()=>Dds(e),[e]),k=g.useCallback((B,z,V)=>{t(M=>{const G=new URLSearchParams(M);return B?G.set(O9,B):G.delete(O9),z?G.set(Db,z):G.delete(Db),V?G.set(k9,V):G.delete(k9),G.delete(Ev),G.delete(Tv),G},{replace:!0})},[t]),_=g.useCallback(()=>k(""),[k]),C=g.useCallback(B=>{const z=e.get(Db)||null;B!==z&&t(V=>{const M=new URLSearchParams(V);return B?M.set(Db,B):M.delete(Db),M.delete(Ev),M.delete(Tv),M},{replace:!0})},[e,t]),T=g.useCallback(()=>C(null),[C]),E=g.useCallback(B=>{const z=e.get(Ev)||null;B!==z&&t(V=>{const M=new URLSearchParams(V);return B&&B!=="details"?M.set(Ev,B):M.delete(Ev),M.delete(Tv),M},{replace:!0})},[e,t]),N=g.useCallback((B,z)=>{const V=z&&z!=="details"?z:null;B===(e.get(Db)||null)&&V===(e.get(Ev)||null)&&!e.get(Tv)||t(G=>{const U=new URLSearchParams(G);return U.set(Db,B),V?U.set(Ev,V):U.delete(Ev),U.delete(Tv),U},{replace:!0})},[e,t]),I=g.useCallback(B=>{const z=e.get(Tv)||null;B!==z&&t(V=>{const M=new URLSearchParams(V);return B?M.set(Tv,B):M.delete(Tv),M},{replace:!0})},[e,t]),A=g.useCallback(B=>{t(z=>{const V=new URLSearchParams(z);return Fds(V,B),SP(V),V},{replace:!0})},[t]),R=A,L=g.useCallback((B,z)=>{if(u.current!=="custom")return;const V=z==="from"?Lw:Fw;t(M=>{const G=new URLSearchParams(M);return B?G.set(V,B.toISOString()):G.delete(V),SP(G),G},{replace:!0})},[t]),D=g.useCallback(B=>{u.current=B,t(z=>{const V=new URLSearchParams(z);return B==="last-24h"?(V.delete(Dw),V.delete(Lw),V.delete(Fw)):B==="custom"?V.set(Dw,"custom"):(V.set(Dw,B),V.delete(Lw),V.delete(Fw)),SP(V),V},{replace:!0})},[t]),F=g.useCallback(B=>{t(z=>{const V=new URLSearchParams(z);return B==="traces"?V.delete(Mw):V.set(Mw,B),SP(V),V},{replace:!0})},[t]),H=g.useCallback(()=>{t(B=>{const z=new URLSearchParams(B);z.delete(Mw),z.delete(Gx),z.delete(Qx);for(const V of zL)z.delete(Ol[V]);return SP(z),z},{replace:!0}),r?.()},[t,r]);return{searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,traceIdParam:d,spanIdParam:f,anchorSpanIdParam:p,spanTabParam:m,scoreIdParam:v,listMode:y,selectedEntityOption:b,selectedStatus:x,filterTokens:S,handleTraceClick:k,handleTraceClose:_,handleSpanChange:C,handleSpanClose:T,handleSpanTabChange:E,handleSpanChangeWithTab:N,handleScoreChange:I,handleListModeChange:F,handleFilterTokensChange:R,handleDateChange:L,handleDatePresetChange:D,handleRemoveAll:H,applyFilterTokens:A}}function dA(e,t,n){const r=e.get(t);if(r!==void 0)return r;const s=n();return e.set(t,s),s}const $xe="mastra_model_total_input_tokens",Gqt="mastra_model_total_output_tokens",get=500;function Qds(e){const t=[];for(let n=0;n<e.length;n+=get)t.push(e.slice(n,n+get));return t}function Yds(){return{estimatedCost:0,hasEstimatedCost:!1,costUnits:new Set,hasUnknownCostUnit:!1}}function Kds(e,t){for(const n of t.groups){const r=n.dimensions.traceId,s=n.dimensions.name;if(!r||s!==$xe&&s!==Gqt)continue;const a=dA(e,r,Yds),i=s===$xe?"inputTokens":"outputTokens";a[i]=(a[i]??0)+n.value,n.estimatedCost!=null&&(a.estimatedCost+=n.estimatedCost,a.hasEstimatedCost=!0,n.costUnit?a.costUnits.add(n.costUnit.toLowerCase()):a.hasUnknownCostUnit=!0)}}function Xds(e){const t=new Map;for(const[n,r]of e){const s={inputTokens:r.inputTokens,outputTokens:r.outputTokens};r.hasEstimatedCost&&!r.hasUnknownCostUnit&&r.costUnits.size===1&&(s.estimatedCost=r.estimatedCost,s.costUnit=[...r.costUnits][0]),t.set(n,s)}return t}function vet({traceIds:e,enabled:t,autoRefetch:n}){const r=Qe(),s=[...new Set(e)].toSorted(),i=`${r.options.baseUrl||(typeof window>"u"?"local":window.location.origin||"local")}:${r.options.apiPrefix??"/api"}`;return yt({queryKey:["trace-usage",i,s],enabled:t&&s.length>0,queryFn:async()=>{const l=Qds(s),c=await Promise.allSettled(l.map(d=>r.getMetricBreakdown({name:[$xe,Gqt],aggregation:"sum",groupBy:["traceId","name"],filters:{traceIds:d},limit:d.length*2}))),u=new Map;for(const d of c)d.status==="fulfilled"&&Kds(u,d.value);return Xds(u)},placeholderData:(l,c)=>c?.queryKey[1]===i?l:void 0,refetchInterval:t&&n?1e4:!1})}const Jds=new Set(["ObservabilityStorageClickhouseVNext","ObservabilityStorageDuckDB","ObservabilityInMemory","ObservabilitySpanner","ObservabilityStoragePostgresVNext"]),Qqt=()=>{const{data:e,isLoading:t}=H4(),n=e?.observabilityStorageType;return{supportsMetrics:e?.observabilityStorageCapabilities?.metrics??(n?Jds.has(n):!1),isInMemory:n==="ObservabilityInMemory",isLoading:t}};function efs(e){return e.startsWith("agent-")}function tfs(e){return e.match(/^(?:mcp_)?tool:\s*'(.*?)'/)?.[1]??e}function Yqt(e){return Kqt(e,[])}function Kqt(e,t){if(!e)return t;for(const n of e){const r=n.stepType==="tool_call"||n.stepType==="mcp_tool_call";if(r&&n.name){const s=tfs(n.name),a="toolArgs"in n?n.toolArgs:void 0,i="toolResult"in n?n.toolResult:void 0;t.push({toolName:s,args:a??{},output:i??null,...efs(s)?{matchArgs:"ignore"}:{}})}!r&&n.children?.length&&Kqt(n.children,t)}return t}function nfs(e){const t=(()=>{try{const r=JSON.stringify(e.input);return r?r.length>40?`${r.slice(0,40)}…`:r:""}catch{return""}})(),n=dS(e.id)??e.id;return t?`${n} — ${t}`:n}function rfs({traceId:e,isOpen:t,onClose:n,level:r=2}){const s=Qe(),{data:a,isLoading:i}=yt({queryKey:["trace-trajectory",e],queryFn:()=>s.getTraceTrajectory(e),enabled:t&&!!e}),l=a?.steps?Yqt(a.steps):[],c=l.length>0?dO(l,2):"";return o.jsxs(Sa,{dialogTitle:"Add Tool Mocks to Item",dialogDescription:"Append trace-derived tool mocks to an existing dataset item",isOpen:t,onClose:n,level:r,children:[o.jsxs(Sa.Top,{children:[o.jsxs(Nl,{children:[o.jsx(ec,{})," ",dS(e)]}),"›",o.jsxs(Nl,{children:[o.jsx(Ud,{})," Add Tool Mocks to Item"]})]}),o.jsxs(Sa.Content,{children:[o.jsx(Sa.Header,{children:o.jsxs(Sa.Heading,{children:[o.jsx(Ud,{})," Add Tool Mocks to Item"]})}),i?o.jsx("div",{className:"text-neutral4 px-2 py-4 text-sm",children:"Loading tool calls from trace..."}):o.jsx(sfs,{initialMocksJson:c,onClose:n},e??"no-trace")]})]})}function sfs({initialMocksJson:e,onClose:t}){const[n,r]=g.useState(""),[s,a]=g.useState(""),[i,l]=g.useState(e),{data:c,isLoading:u}=Im(),d=c?.datasets??[],{data:f=[],isLoading:p}=Zx(n),{data:h,isFetching:m}=FD(n,s),{updateItem:v}=qi(),y=(()=>{if(!i.trim())return!1;try{const S=JSON.parse(i);return Array.isArray(S)&&S.length>0}catch{return!1}})(),b=S=>{r(S),a("")},x=async S=>{if(S.preventDefault(),!n||!s){Be.error("Please select a dataset and an item");return}let k;try{const T=i.trim()?JSON.parse(i):[];if(!Array.isArray(T)){Be.error("Tool Mocks must be a JSON array");return}k=T}catch{Be.error("Tool Mocks must be valid JSON");return}if(k.length===0){Be.error("There are no tool mocks to add");return}if(!h||h.id!==s){Be.error("Item is still loading, please try again");return}const C=[...h.toolMocks??[],...k];try{await v.mutateAsync({datasetId:n,itemId:s,toolMocks:C}),Be.success(`Added ${k.length} tool mock(s) to the item`),t()}catch(T){Be.error(`Failed to add tool mocks: ${T instanceof Error?T.message:"Unknown error"}`)}};return o.jsxs("form",{onSubmit:x,className:"grid gap-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{htmlFor:"target-dataset",children:"Dataset *"}),o.jsxs(ha,{value:n,onValueChange:b,disabled:u,children:[o.jsx(ga,{id:"target-dataset",children:o.jsx(ma,{placeholder:u?"Loading datasets...":"Select a dataset"})}),o.jsx(va,{children:d.length===0?o.jsx("div",{className:"text-neutral4 px-2 py-4 text-center text-sm",children:"No datasets available"}):d.map(S=>o.jsx(Nr,{value:S.id,children:S.name},S.id))})]})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{htmlFor:"target-item",children:"Item *"}),o.jsxs(ha,{value:s,onValueChange:a,disabled:!n||p,children:[o.jsx(ga,{id:"target-item",children:o.jsx(ma,{placeholder:n?p?"Loading items...":"Select an item":"Select a dataset first"})}),o.jsx(va,{children:f.length===0?o.jsx("div",{className:"text-neutral4 px-2 py-4 text-center text-sm",children:"No items available"}):f.map(S=>o.jsx(Nr,{value:S.id,children:nfs(S)},S.id))})]})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{htmlFor:"derived-mocks",children:"Tool Mocks (JSON)"}),o.jsx(Zr,{value:i,onChange:l,showCopyButton:!1,className:"min-h-[160px]"}),o.jsx("p",{className:"text-neutral4 text-xs",children:"Seeded from the trace's tool calls. Edit or remove entries before appending."})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(oe,{type:"button",variant:"outline",onClick:t,children:"Cancel"}),o.jsx(oe,{type:"submit",variant:"default",disabled:v.isPending||m||!y||!n||!s||h?.id!==s,children:v.isPending?"Adding...":"Append Tool Mocks"})]})]})}function afs(e){if(e?.input==null)return"{}";const t=e.input,r=e.spanType==="agent_run"&&t&&typeof t=="object"&&!Array.isArray(t)&&"messages"in t?t.messages??e.input:e.input;return dO(r,2)}function ifs({traceDetails:e,rootSpanId:t,traceId:n,isOpen:r,onClose:s,level:a=2}){const i=Qe(),{data:l}=_Q(!e&&r?n:null,!e&&r?t:null),c=e??l?.span,{data:u,isLoading:d}=yt({queryKey:["trace-trajectory",n],queryFn:()=>i.getTraceTrajectory(n),enabled:r&&!!n}),f=u?.steps&&u.steps.length>0?dO({steps:u.steps.map(m=>{const{name:v,stepType:y,children:b,...x}=m,S={name:v,stepType:y};for(const[k,_]of Object.entries(x))_!=null&&k!=="durationMs"&&k!=="metadata"&&(S[k]=_);return S}),ordering:"relaxed"},2):void 0,p=u?.steps?Yqt(u.steps):[],h=p.length>0?dO(p,2):void 0;return o.jsx(W3t,{initialInput:afs(c),initialGroundTruth:c?.output!=null?dO(c.output,2):"",initialTrajectory:f,trajectoryLoading:d,initialToolMocks:h,breadcrumb:o.jsxs(Nl,{children:[o.jsx(ec,{})," ",dS(n)]}),isOpen:r,onClose:s,level:a,source:n?{type:"trace",referenceId:n}:void 0})}const Xqt=({traceId:e,spanId:t})=>{const n=Qe(),r=Lr();return An({mutationFn:({text:s})=>n.createFeedback({feedback:{traceId:e,...t?{spanId:t}:{},feedbackType:"comment",feedbackSource:"user",value:s}}),onSuccess:()=>r.invalidateQueries({queryKey:t?["span-feedback",e,t]:["trace-feedback",e]})})},ofs=3e3;function Jqt(e){return R4(e.state.error,"feedback")||P4(e.state.error)?!1:ofs}const eVt=({traceId:e="",page:t})=>{const n=Qe(),r=t??0;return yt({queryKey:["trace-feedback",e,r],queryFn:()=>n.listFeedback({filters:{traceId:e},pagination:{page:r,perPage:10}}),enabled:!!e,select:s=>{const a=s.feedback.filter(i=>!i.spanId);return s.pagination?{...s,feedback:a,pagination:{...s.pagination,total:a.length}}:{...s,feedback:a}},refetchInterval:Jqt,gcTime:0,staleTime:0})},tVt=({traceId:e="",spanId:t="",page:n})=>{const r=Qe(),s=n??0;return yt({queryKey:["span-feedback",e,t,s],queryFn:()=>r.listFeedback({filters:{traceId:e,spanId:t},pagination:{page:s,perPage:10}}),enabled:!!e&&!!t,refetchInterval:Jqt,gcTime:0,staleTime:0})},nVt=g.createContext(null);function BQ(){const e=g.useContext(nVt);if(!e)throw new Error("Comment compounds must be rendered within Comment");return e}const lfs=Ii("flex flex-col",{variants:{variant:{default:"gap-2",embed:"gap-1 rounded-xl border border-border1 bg-surface3 p-3"}},defaultVariants:{variant:"default"}}),rVt=g.forwardRef(({className:e,variant:t="default",...n},r)=>o.jsx(nVt.Provider,{value:t,children:o.jsx("div",{ref:r,"data-slot":"comment","data-variant":t,className:K(lfs({variant:t}),e),...n})}));rVt.displayName="Comment";const cfs={default:"gap-3",embed:"gap-2"},sVt=g.forwardRef(({className:e,...t},n)=>{const r=BQ();return o.jsx("ul",{ref:n,"data-slot":"comment-list",className:K("flex flex-col",cfs[r],e),...t})});sVt.displayName="CommentList";const aVt=g.forwardRef(({className:e,...t},n)=>o.jsx("li",{ref:n,"data-slot":"comment-item",className:K("group/comment-item flex flex-col gap-1",e),...t}));aVt.displayName="CommentItem";const iVt=g.forwardRef(({className:e,...t},n)=>o.jsx("div",{ref:n,"data-slot":"comment-item-header",className:K("flex items-center gap-2",e),...t}));iVt.displayName="CommentItemHeader";const ufs=g.forwardRef(({className:e,...t},n)=>o.jsx(me,{ref:n,as:"span",variant:"ui-md","data-slot":"comment-item-author",className:K("font-medium text-neutral6",e),...t}));ufs.displayName="CommentItemAuthor";const oVt=g.forwardRef(({className:e,...t},n)=>o.jsx("time",{ref:n,"data-slot":"comment-item-timestamp",className:K("text-ui-sm leading-ui-sm text-neutral3",e),...t}));oVt.displayName="CommentItemTimestamp";const dfs={default:"border-l border-border1 pl-3",embed:""},lVt=g.forwardRef(({className:e,...t},n)=>{const r=BQ();return o.jsx(me,{ref:n,variant:"ui-md","data-slot":"comment-item-body",className:K("whitespace-pre-wrap text-neutral6",dfs[r],e),...t})});lVt.displayName="CommentItemBody";const ffs=g.forwardRef(({className:e,...t},n)=>BQ()==="embed"?null:o.jsx("div",{ref:n,"data-slot":"comment-item-actions",className:K("flex items-center gap-1 opacity-0 group-focus-within/comment-item:opacity-100 group-hover/comment-item:opacity-100","motion-safe:transition-opacity",e),...t}));ffs.displayName="CommentItemActions";const cVt=g.forwardRef(({className:e,...t},n)=>o.jsx("form",{ref:n,"data-slot":"comment-composer",className:K("flex w-full items-center gap-2",e),...t}));cVt.displayName="CommentComposer";const pfs={default:"md",embed:"sm"},hfs={default:"outline",embed:"default"},uVt=g.forwardRef(({groupClassName:e,children:t,...n},r)=>{const s=BQ();return o.jsxs(uu,{size:pfs[s],variant:hfs[s],className:e,children:[o.jsx(du,{ref:r,"data-slot":"comment-composer-input",...n}),t]})});uVt.displayName="CommentComposerInput";const dVt=g.forwardRef(({"aria-label":e="Send comment",type:t="submit",...n},r)=>o.jsx(Nc,{align:"inline-end",children:o.jsx(OTe,{ref:r,"data-slot":"comment-composer-send",type:t,"aria-label":e,...n,children:o.jsx(q1,{})})}));dVt.displayName="CommentComposerSend";function mfs(e){const t=e.comment||(typeof e.value=="string"?e.value:"");return t||(e.feedbackType==="thumbs"?e.value===1?"👍":"👎":String(e.value??""))}function fVt({feedbackData:e,isLoadingFeedbackData:t,onPageChange:n,onSubmit:r,isSubmitting:s=!1}){const[a,i]=g.useState(""),l=a.trim().length===0||s,c=e?.feedback??[],u=e?.pagination?.page??0,d=e?.pagination?.hasMore??!1;return o.jsxs(rVt,{className:"min-h-0 gap-4 px-3",children:[o.jsx("div",{className:"min-h-0 overflow-y-auto",children:t?o.jsx(me,{variant:"ui-md",className:"text-neutral3",children:"Loading feedback..."}):c.length===0?o.jsx(me,{variant:"ui-md",className:"text-neutral3",children:"No feedback yet"}):o.jsx(sVt,{children:c.map((f,p)=>{const h=new Date(f.timestamp);return o.jsxs(aVt,{children:[o.jsx(iVt,{children:o.jsx(oVt,{dateTime:h.toISOString(),children:hr(h,"MMM d, h:mm:ss aaa")})}),o.jsx(lVt,{children:mfs(f)})]},`${f.traceId}-${p}`)})})}),(d||u>0)&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(oe,{size:"sm",variant:"ghost",disabled:u===0,onClick:()=>n?.(u-1),children:"Previous"}),o.jsx(oe,{size:"sm",variant:"ghost",disabled:!d,onClick:()=>n?.(u+1),children:"Next"})]}),o.jsx(cVt,{"aria-label":"Leave feedback",onSubmit:async f=>{if(f.preventDefault(),!l)try{await r(a.trim()),i("")}catch{}},children:o.jsx(uVt,{"aria-label":"Leave feedback",placeholder:"Leave feedback...",value:a,onChange:f=>i(f.target.value),children:o.jsx(dVt,{"aria-label":"Send feedback",disabled:l})})})]})}function gfs({traceId:e,spanId:t}){const[n,r]=g.useState(0),{data:s,isLoading:a}=tVt({traceId:e,spanId:t,page:n}),{mutateAsync:i,isPending:l}=Xqt({traceId:e,spanId:t});return o.jsx(fVt,{feedbackData:s,isLoadingFeedbackData:a,onPageChange:r,onSubmit:c=>i({text:c}),isSubmitting:l})}function vfs({traceId:e}){const[t,n]=g.useState(0),{data:r,isLoading:s}=eVt({traceId:e,page:t}),{mutateAsync:a,isPending:i}=Xqt({traceId:e});return o.jsx(fVt,{feedbackData:r,isLoadingFeedbackData:s,onPageChange:n,onSubmit:l=>a({text:l}),isSubmitting:i})}const yet="auto auto auto auto 1fr";function yfs({scoresData:e,isLoadingScoresData:t,onPageChange:n,onScoreSelect:r}){const{containerRef:s,getRowProps:a}=wo({count:e?.scores?.length??0});return t?o.jsx(Pl,{columns:yet}):!e?.scores||e.scores.length===0?o.jsx(Er,{iconSlot:o.jsx(Rlt,{}),titleSlot:"No scores yet",descriptionSlot:"Score this trace to see results here."}):o.jsxs("div",{className:"grid gap-2",children:[o.jsxs(be,{columns:yet,className:"min-w-0",scrollRef:s,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"ID"}),o.jsx(be.TopCell,{children:"Date"}),o.jsx(be.TopCell,{children:"Time"}),o.jsx(be.TopCell,{children:"Score"}),o.jsx(be.TopCell,{children:"Scorer"})]}),e.scores.map((i,l)=>{const c=new Date(i.createdAt),u=$3(c);return o.jsxs(be.RowButton,{onClick:()=>r?.(i),...a(l),children:[o.jsx(be.Cell,{className:"text-neutral3 text-ui-smd font-mono",children:dS(i?.id)||"n/a"}),o.jsx(be.Cell,{className:"text-neutral2 text-ui-smd",children:u?"Today":hr(c,"MMM dd")}),o.jsx(be.Cell,{className:"text-neutral3 text-ui-smd font-mono",children:hr(c,"h:mm:ss aaa")}),o.jsx(be.Cell,{className:"text-ui-smd",children:String(i?.score??"")}),o.jsx(be.Cell,{className:"text-ui-smd",children:String(i?.scorer?.name||i?.scorer?.id||"")})]},i.id)})]}),o.jsx(be.Pagination,{currentPage:e?.pagination?.page||0,hasMore:e?.pagination?.hasMore,onNextPage:()=>n?.((e?.pagination?.page||0)+1),onPrevPage:()=>n?.((e?.pagination?.page||0)-1)})]})}const bfs=()=>{const e=Qe();return An({mutationFn:async({scorerName:t,traceId:n,spanId:r})=>await e.score({scorerName:t,targets:[{traceId:n,spanId:r}]})})};function xfs({traceId:e,spanId:t,entityType:n,isTopLevelSpan:r,scorers:s,isLoadingScorers:a}){const[i,l]=g.useState(null),{mutate:c,isPending:u}=bfs();let d=Object.entries(s||{}).map(([m,v])=>({id:m,name:v.scorer.config.name,description:v.scorer.config.description,isRegistered:v.isRegistered,type:v.scorer.config.type})).filter(m=>m.isRegistered);(n!=="Agent"||!r)&&(d=d.filter(m=>m.type!=="agent"));const f=u||a,p=()=>{i&&e&&c({scorerName:i,traceId:e,spanId:t},{onSuccess:()=>Be.info("Scorer triggered",{description:"Results will appear once scoring completes."})})},h=d.find(m=>m.id===i)?.description||"";return s===void 0&&!a?o.jsx(Wn,{variant:"destructive",children:"Failed to load scorers."}):!a&&d.length===0?o.jsx(Wn,{variant:"info",children:"No eligible scorers have been defined to run."}):o.jsxs("div",{className:"grid grid-cols-[3fr_1fr] items-start gap-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Pc,{name:"select-scorer",label:"Select scorer",labelIsHidden:!0,placeholder:"Select a scorer...",options:d.map(m=>({label:m.name||m.id,value:m.id||m.name||""})),onValueChange:l,value:i||"",className:"min-w-80",disabled:f}),h&&o.jsxs(Nl,{className:"text-neutral3 text-ui-sm",children:[o.jsx(km,{})," ",h]})]}),o.jsx(oe,{disabled:!i||f,onClick:p,children:u?"Starting...":"Start Scoring"})]})}function wfs(e){const t=[...e].sort((s,a)=>new Date(s.createdAt).getTime()-new Date(a.createdAt).getTime()),n=[];return{data:t.map(s=>{const a=String(s.scorer?.name||s.scorer?.id||"unknown");return n.includes(a)||n.push(a),{time:hr(new Date(s.createdAt),"h:mm:ss aaa"),[a]:s.score}}),scorerNames:n}}const bet=["#22c55e","#4f83f1","#8b5cf6","#fb923c","#f472b6","#facc15"];function Sfs({scoresData:e,className:t}){const{data:n,scorerNames:r}=g.useMemo(()=>wfs(e?.scores??[]),[e?.scores]),s=g.useMemo(()=>r.map((a,i)=>({dataKey:a,label:a,color:bet[i%bet.length],aggregate:l=>{const c=l.map(u=>u[a]).filter(u=>typeof u=="number");return{value:c.length>0?(c.reduce((u,d)=>u+d,0)/c.length).toFixed(2):"0",suffix:"avg"}}})),[r]);return n.length===0?null:o.jsx(Yu,{appearance:"surface",className:t,children:o.jsx(Ag,{children:o.jsx(OD,{data:n,series:s,height:90,yDomain:[0,1],xAxisInterval:"preserveStartEnd",xAxisMinTickGap:40,showDots:!0})})})}function kfs({traceId:e,spanId:t,isTopLevelSpan:n,entityType:r,onScoreSelect:s}){const[a,i]=g.useState(0),{data:l,isLoading:c}=c4t({traceId:e,spanId:t,page:a}),{data:u,isLoading:d}=oh();return o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_auto_1fr] gap-6",children:[o.jsx(xfs,{traceId:e,isTopLevelSpan:n,spanId:t,entityType:r,scorers:u,isLoadingScorers:d}),o.jsx(Sfs,{scoresData:l,className:"min-h-0 w-full"}),o.jsx(Yu,{appearance:"surface",className:"min-h-0 w-full overflow-hidden",children:o.jsx(Ag,{className:"h-full overflow-y-auto",children:o.jsx(yfs,{scoresData:l,onPageChange:i,isLoadingScoresData:c,onScoreSelect:f=>s(f.id)})})})]})}function pVt({scopedEntityId:e,scopedEntityType:t}={}){const n=!!e,[r,s]=hi(),a=Gds(r,s);g.useEffect(()=>{if(!e)return;const Re=r.get("rootEntityType"),Ge=r.get("filterEntityId");!(t&&Re!==t)&&!(Ge!==e)||s($e=>{const ye=new URLSearchParams($e);return t&&ye.set("rootEntityType",t),ye.set("filterEntityId",e),ye},{replace:!0})},[e,t,r,s]);const i=g.useMemo(()=>n?["rootEntityType","entityId"]:[],[n]),l=g.useMemo(()=>n?["rootEntityType","entityId","entityName"]:[],[n]),c=n?"This filter is scoped to the current agent. Open the global Traces view to change it.":void 0,[u,d]=g.useState(),[f,p]=g.useState(!1),[h,m]=g.useState(!1),[v,y]=g.useState(null),[b,x]=g.useState(null),{data:S}=eVt({traceId:a.traceIdParam}),{data:k}=tVt({traceId:a.traceIdParam,spanId:a.spanIdParam}),{spans:_,anchorSpanId:C,isLoading:T}=KUt({traceId:a.traceIdParam??null,anchorSpanId:a.listMode==="branches"?a.anchorSpanIdParam??null:null,listMode:a.listMode}),E=g.useMemo(()=>C?_?.find(Re=>Re.spanId===C):_?.find(Re=>Re.parentSpanId==null),[_,C]),{data:N}=c4t({traceId:a.traceIdParam,spanId:E?.spanId}),I=E?.entityType==="agent"?"Agent":E?.entityType==="workflow_run"?"Workflow":void 0,A=a.scoreIdParam?N?.scores?.find(Re=>Re.id===a.scoreIdParam):void 0,{data:R=[],isPending:L}=RAe(),{data:D=[],isPending:F}=NAe({entityType:a.selectedEntityOption?.entityType,rootOnly:!0}),{data:H=[],isPending:B}=IAe(),{data:z=[],isPending:V}=AAe(),M=g.useMemo(()=>Mds({availableTags:R,availableRootEntityNames:D,availableServiceNames:z,availableEnvironments:H,loading:{tags:L,entityNames:F,serviceNames:V,environments:B}}),[R,D,z,H,L,F,V,B]),G=g.useMemo(()=>zds({rootEntityType:a.selectedEntityOption?.entityType,status:a.selectedStatus,dateFrom:a.selectedDateFrom,dateTo:a.selectedDateTo,tokens:a.filterTokens}),[a.filterTokens,a.selectedDateFrom,a.selectedDateTo,a.selectedEntityOption,a.selectedStatus]),{data:U,isLoading:$,isFetchingNextPage:q,hasNextPage:Z,setEndOfListElement:Y,error:ne,autoRefetch:J,setAutoRefetch:ee,recentlyAddedKeys:re}=XUt({filters:G,listMode:a.listMode}),le=g.useMemo(()=>U?.spans??[],[U?.spans]),X=qds(),te=Qqt(),se=a.listMode==="branches"?"Token and cost totals are only available for full traces.":te.isLoading?"Checking whether this storage supports usage data.":te.supportsMetrics?void 0:"This observability store does not support token and cost metrics.",pe=a.listMode==="branches"||!te.isLoading&&!te.supportsMetrics,ce=pe?{...X.preferences,visibleColumns:X.preferences.visibleColumns.filter(Re=>!WUt(Re))}:X.preferences,Se=!pe&&!te.isLoading&&Dcs(ce),ve=vet({traceIds:le.map(Re=>Re.traceId),enabled:Se,autoRefetch:J}),ke=Se&&le.some(Re=>Re.traceId===a.traceIdParam),Ne=vet({traceIds:a.traceIdParam?[a.traceIdParam]:[],enabled:a.listMode==="traces"&&!te.isLoading&&te.supportsMetrics&&!ke,autoRefetch:J}),Me=a.traceIdParam?ve.data?.get(a.traceIdParam)??Ne.data?.get(a.traceIdParam):void 0;g.useEffect(()=>{!ne||f||eQe(ne)&&(p(!0),a.listMode==="branches"&&a.handleListModeChange("traces"))},[ne,f,a]);const Ae=Wds(r,s,{storageKey:n?`mastra:traces:saved-filters:${t}:${e}`:void 0}),Ie=g.useCallback(()=>a.applyFilterTokens(Bds(M,a.filterTokens)),[M,a]),ae=g.useCallback((Re,Ge)=>{a.listMode==="branches"?a.handleTraceClick(Re,Ge,Ge):a.handleTraceClick(Re)},[a]),{handlePreviousTrace:fe,handleNextTrace:ue}=QUt(le,a.traceIdParam,a.listMode==="branches"?a.anchorSpanIdParam:null,ae),we=E?.entityType==="agent",Ee=!!a.selectedEntityOption||!!a.selectedStatus||a.filterTokens.length>0||a.datePreset!=="last-24h"||!!a.selectedDateTo,ge=o.jsxs(o.Fragment,{children:[o.jsx(I4,{preset:a.datePreset,onPresetChange:a.handleDatePresetChange,dateFrom:a.selectedDateFrom,dateTo:a.selectedDateTo,onDateChange:a.handleDateChange,disabled:$,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),o.jsx(EAe,{fields:M,tokens:a.filterTokens,onTokensChange:a.handleFilterTokensChange,disabled:$,onStartTextFilter:d,hiddenFieldIds:l}),o.jsxs("div",{className:"min-h-form-default ml-auto flex max-w-full flex-wrap items-center justify-end gap-2",children:[o.jsx(_ds,{preferences:X.preferences,usageDisabledReason:se,onToggleColumn:X.toggleColumn,onAddMetadataColumn:X.addMetadataColumn,onRemoveMetadataColumn:X.removeMetadataColumn,onReset:X.resetColumns}),!f&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(So,{id:"show-subtraces",checked:a.listMode==="branches",onCheckedChange:Re=>a.handleListModeChange(Re===!0?"branches":"traces"),disabled:$}),o.jsx(Mt,{htmlFor:"show-subtraces",children:"Subtraces"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(So,{id:"auto-refetch",checked:J,onCheckedChange:Re=>ee(Re===!0),disabled:$}),o.jsx(Mt,{htmlFor:"auto-refetch",children:"Auto refresh"})]})]})]}),Ce=f&&!h?o.jsx(Wn,{variant:"info",action:o.jsx(Wn.Button,{variant:"ghost",onClick:()=>m(!0),children:"Dismiss"}),className:"mb-4",children:o.jsx(Wn.Message,{children:"Selected list mode isn't supported by this storage provider — switched to default."})}):null,Ue=o.jsxs(Vt.TopArea,{children:[o.jsx(Vt.Row,{children:o.jsx(Vt.Column,{className:"flex w-full flex-wrap items-start justify-start gap-2",children:ge})}),o.jsx(Eds,{isLoading:$,filterFields:M,filterTokens:a.filterTokens,onFilterTokensChange:a.handleFilterTokensChange,onClear:Ie,onRemoveAll:a.handleRemoveAll,onSave:Ae.handleSave,onRemoveSaved:Ae.hasSavedFilters?Ae.handleRemoveSaved:void 0,autoFocusFilterFieldId:u,lockedFieldIds:i,lockedTooltipContent:c}),Ce]});if(ne&&!eQe(ne))return o.jsxs(Vt,{width:"wide",height:"full",children:[Ue,o.jsx(Vt.MainArea,{isCentered:!0,children:o.jsx(BUt,{error:ne,resource:"traces",errorTitle:"Failed to load traces"})})]});const Fe=!!a.selectedEntityOption||!!a.selectedStatus||a.filterTokens.length>0;return le.length===0&&!$&&!Fe&&!a.traceIdParam?o.jsxs(Vt,{width:"wide",height:"full",children:[Ue,o.jsx(Vt.MainArea,{isCentered:!0,children:o.jsx(kds,{datePreset:a.datePreset,dateFrom:a.selectedDateFrom,dateTo:a.selectedDateTo})})]}):o.jsxs(Vt,{width:"wide",height:"full",children:[Ue,o.jsx(Cds,{sidePanelWide:!!a.spanIdParam,listSlot:o.jsx(GUt,{traces:le,isLoading:$,isFetchingNextPage:q,hasNextPage:Z,setEndOfListElement:Y,filtersApplied:Ee,featuredTraceId:a.traceIdParam,featuredSpanId:a.listMode==="branches"?a.anchorSpanIdParam:null,isBranchesMode:a.listMode==="branches",recentlyAddedKeys:re,columnPreferences:ce,usageByTraceId:ve.data,onTraceClick:Re=>{const Ge=a.listMode==="branches";if(Ge?a.traceIdParam===Re.traceId&&a.anchorSpanIdParam===Re.spanId:a.traceIdParam===Re.traceId){a.handleTraceClick("");return}const mt=Ge?Re.spanId??void 0:void 0;a.handleTraceClick(Re.traceId,mt,mt)}},a.listMode),tracePanelSlot:a.traceIdParam&&(a.listMode!=="branches"||a.anchorSpanIdParam)?o.jsx(cqt,{traceId:a.traceIdParam,spans:_,anchorSpanId:C,usage:Me,isLoadingSpans:T,selectedSpanId:a.spanIdParam??null,onClose:a.handleTraceClose,onSpanSelect:Re=>a.handleSpanChange(Re??null),onSpanClose:a.handleSpanClose,onSaveAsDatasetItem:Re=>y(Re),onAddTraceMocksToItem:we?Re=>x(Re):void 0,initialSpanId:a.spanIdParam,onPrevious:fe,onNext:ue,feedbackTabBadge:S?.pagination?.total??void 0,feedbackTabSlot:({traceId:Re})=>o.jsx(vfs,{traceId:Re}),scoresTabBadge:N?.pagination?.total??void 0,scoresTabSlot:({traceId:Re,rootSpanId:Ge})=>Ge?o.jsx(kfs,{traceId:Re,spanId:Ge,isTopLevelSpan:!E?.parentSpanId,entityType:I,onScoreSelect:a.handleScoreChange}):null,spanActiveTab:a.spanTabParam??"details",onSpanTabChange:Re=>a.handleSpanTabChange(Re),spanFeedbackTabBadge:k?.pagination?.total??void 0,spanFeedbackTabSlot:({traceId:Re,spanId:Ge})=>Re&&Ge?o.jsx(gfs,{traceId:Re,spanId:Ge},`${Re}:${Ge}`):null,spanPanelClassName:"rounded-none border-0 bg-transparent"},`${a.traceIdParam}:${a.anchorSpanIdParam??""}`):null,scorePanelSlot:A?o.jsx(Z3t,{score:A,onClose:()=>a.handleScoreChange(null)}):null}),o.jsx(ifs,{rootSpanId:v?.rootSpanId,traceId:v?.traceId,isOpen:!!v,onClose:()=>y(null)}),o.jsx(rfs,{traceId:b?.traceId,isOpen:!!b,onClose:()=>x(null)})]})}function Ofs(){const{agentId:e}=mr();return e?o.jsx(pVt,{scopedEntityId:e,scopedEntityType:Ku.AGENT}):null}function _fs(){return o.jsx(aas,{})}function Cfs(){const{navigate:e,paths:t}=cn(),n=zo(),{form:r,handlePublish:s,isSubmitting:a,canPublish:i}=wQ({mode:"create",onSuccess:l=>e(t.agentLink(l))});return o.jsxs(_s,{children:[o.jsx($y,{owner:"cms-agent-create",children:o.jsx(oe,{variant:"primary",onClick:()=>{s()},disabled:a||!i,children:a?o.jsxs(o.Fragment,{children:[o.jsx(Ut,{className:"h-4 w-4"}),"Creating..."]}):o.jsxs(o.Fragment,{children:[o.jsx(He,{children:o.jsx(Qr,{})}),"Create agent"]})})}),o.jsx(JBt,{form:r,mode:"create",isSubmitting:a,handlePublish:s,basePath:"/cms/agents/create",currentPath:n.pathname,children:o.jsx(Fg,{})})]})}function xet({agentId:e,selectedVersionId:t,versionData:n,readOnly:r=!1,form:s,handlePublish:a,handleSaveDraft:i,isSubmitting:l,isSavingDraft:c,onVersionSelect:u,activeVersionId:d,latestVersionId:f,hideVersionPanel:p=!1,isCodeAgentOverride:h=!1,isCodeSourceAgent:m=!1,editorConfig:v}){const[,y]=hi(),{pathname:b}=zo(),k=!!t&&!!n&&t!==f?o.jsxs(Wn,{variant:"info",title:"This is a previous version",className:"mb-4",children:[o.jsx(Wn.Message,{children:"You are seeing a specific version of the agent."}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(oe,{type:"button",variant:"default",size:"sm",onClick:()=>y({}),children:"View latest version"}),o.jsx(oe,{type:"button",variant:"default",size:"sm",onClick:()=>{a(t??void 0)},disabled:t===d,children:"Publish This Version"})]})]}):void 0,_=p?void 0:o.jsx(Zas,{agentId:e,selectedVersionId:t??void 0,onVersionSelect:u,activeVersionId:d}),C=kC(h,v).isFullyLocked;return o.jsx(JBt,{form:s,mode:"edit",agentId:e,isSubmitting:l,isSavingDraft:c,handlePublish:a,handleSaveDraft:i,readOnly:r,isCodeAgentOverride:h,isCodeSourceAgent:m,editorConfig:v,basePath:`/cms/agents/${e}/edit`,currentPath:b,banner:k,versionId:t??void 0,rightPanel:_,children:C?o.jsx("div",{className:"p-6",children:o.jsx(Wn,{variant:"info",title:"Editing disabled",children:o.jsx(Wn.Message,{children:"This code-defined agent has disabled Studio editing."})})}):o.jsx(Fg,{})})}function Efs(){const{agentId:e}=mr(),{navigate:t,paths:n}=cn(),r=es(),{hash:s,pathname:a,search:i}=zo(),[l,c]=hi(),u=l.get("versionId"),{isMastraPlatform:d,mastraPlatformApiEndpoint:f,mastraPlatformProjectId:p}=CQ(),{data:h,isLoading:m}=Vl(e),{data:v}=vS({agentId:e,params:{orderBy:{direction:"DESC"}}}),y=(v?.versions?.length??0)>0,{data:b,isLoading:x}=A4(e,{status:"draft",enabled:y}),S=h?.source==="code",k=g.useMemo(()=>S?ZIe(h?.editor):[],[h?.editor,S]),_=b??null,C=m||y&&x,T=`/cms/agents/${e}/edit`,E=a===T||a===`${T}/`;g.useEffect(()=>{if(!S||k.length===0)return;const te=k.some(se=>a===`${T}${se.pathSuffix}`);(E||!te)&&r(`${T}${k[0].pathSuffix}${i}${s}`,{replace:!0})},[k,S,E,a,r,T,i,s]);const{data:N}=aBt({agentId:e??"",versionId:u??""}),I=_?.activeVersionId,A=v?.versions?.[0],R=!!(A&&A.id!==I),L=!!u&&!!N,D=L&&u!==A?.id,F=g.useMemo(()=>L&&N?N:_||(h?YIe(h):{}),[L,N,_,h]),{form:H,handlePublish:B,handleSaveDraft:z,handleDownloadJson:V,handleOpenPr:M,isSubmitting:G,isSavingDraft:U,isDirty:$}=wQ({mode:"edit",agentId:e??"",dataSource:F,isCodeAgentOverride:S,hasStoredOverride:S&&!!b,editorConfig:h?.editor,onSuccess:te=>t(n.agentLink(te))}),q=g.useCallback(async()=>{D&&u?await B(u):await B()},[B,D,u]),Z=g.useCallback(te=>{c(te?{versionId:te}:{})},[c]),Y=!C&&!_&&!h,ne=!C&&!!e&&(!!_||!!h),J=!kC(S,h?.editor).isFullyLocked,ee=pAe(),re=S&&ee==="code",le=J&&d&&!!f&&!!p,X=le?"Open a pull request with this agent override JSON":"Open PR is available on Mastra-hosted projects with GitHub App support";return o.jsxs(_s,{children:[ne&&o.jsx($y,{owner:"cms-agent-edit",children:o.jsxs("div",{className:"flex items-center gap-2",children:[R&&o.jsx(St,{variant:"blue",children:"Unpublished changes"}),re?J?o.jsxs(o.Fragment,{children:[o.jsxs(oe,{onClick:()=>{V()},disabled:U||G,children:[o.jsx(Pd,{}),"Download JSON"]}),o.jsxs(oe,{variant:"primary",disabled:!le||U||G,title:X,onClick:()=>{!f||!p||M({platformApiEndpoint:f,projectId:p})},children:[o.jsx(Flt,{}),"Open PR"]})]}):null:J?o.jsxs(o.Fragment,{children:[o.jsx(oe,{onClick:()=>{z()},disabled:!$||U||G,children:U?o.jsxs(o.Fragment,{children:[o.jsx(Ut,{className:"h-4 w-4"}),"Saving..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Gu,{}),"Save"]})}),o.jsx(oe,{variant:"primary",onClick:()=>{q()},disabled:D?u===I||G||U:!R||G||U,children:G?o.jsxs(o.Fragment,{children:[o.jsx(Ut,{className:"h-4 w-4"}),"Publishing..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Qr,{}),D?"Publish This Version":"Publish"]})})]}):null]})}),Y?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"text-neutral3 flex h-full items-center justify-center",children:"Agent not found"}),o.jsx("div",{className:"hidden",children:o.jsx(xet,{agentId:e??"",selectedVersionId:u,versionData:N,readOnly:!0,form:H,handlePublish:B,handleSaveDraft:z,isSubmitting:G,isSavingDraft:U,onVersionSelect:Z,activeVersionId:I,latestVersionId:A?.id,editorConfig:void 0})})]}):o.jsx(xet,{agentId:e??"",selectedVersionId:u,versionData:N,readOnly:!J,form:H,handlePublish:B,handleSaveDraft:z,isSubmitting:G,isSavingDraft:U,onVersionSelect:Z,activeVersionId:I,latestVersionId:A?.id,hideVersionPanel:S&&!b,isCodeAgentOverride:S,isCodeSourceAgent:re,editorConfig:h?.editor})]})}function Tfs(){return o.jsx(Hss,{})}function jfs(){return o.jsx(EBt,{})}function Nfs(){return o.jsx(cas,{})}function Ifs(){return o.jsx(ias,{})}function Afs(){return o.jsx(Ras,{})}function Rfs(){return o.jsx(jBt,{})}function Pfs(){return o.jsx(vas,{})}function $fs(){return o.jsx(las,{})}function Mfs(){const{navigate:e,paths:t}=cn();return o.jsx(_s,{className:"grid-rows-[1fr]",children:o.jsx(bss,{onSuccess:n=>e(t.cmsPromptBlockEditLink(n.id))})})}function wet(e){return{name:e.name,description:e.description||void 0,content:e.content,rules:e.rules||void 0,requestContextSchema:e.variables||void 0}}function Dfs({block:e,blockId:t,selectedVersionId:n,hasDraft:r,latestVersionId:s,activeVersionId:a,onClearVersion:i}){const l=Qe(),c=Lr(),{navigate:u,paths:d}=cn(),{updateStoredPromptBlock:f}=gQ(t),[p,h]=g.useState(!1),[m,v]=g.useState(!1),{data:y}=xss({blockId:t,versionId:n??""}),b=!!n&&!!y,x=b&&n!==s,S=b?y:e,k=g.useMemo(()=>({name:S.name||"",description:S.description||"",content:S.content||"",rules:S.rules,variables:S.requestContextSchema}),[S]),{form:_}=kBt({initialValues:k}),[C,T]=g.useState(0);g.useEffect(()=>{k&&(_.reset(k),T(A=>A+1))},[k,_]);const E=g.useCallback(async()=>{if(!await _.trigger()){Be.error("Please fill in all required fields");return}v(!0);try{const R=wet(_.getValues());await f.mutateAsync(R),_.reset(_.getValues()),Be.success("Draft saved")}catch(R){Be.error(`Failed to save draft: ${R instanceof Error?R.message:"Unknown error"}`)}finally{v(!1)}},[_,f]),N=g.useCallback(async()=>{if(!await _.trigger()){Be.error("Please fill in all required fields");return}h(!0);try{const R=wet(_.getValues());await f.mutateAsync(R);const D=(await l.getStoredPromptBlock(t).listVersions({orderBy:{direction:"DESC"},perPage:1})).versions[0];if(!D)throw new Error("No version found to publish");await l.getStoredPromptBlock(t).activateVersion(D.id),c.invalidateQueries({queryKey:["stored-prompt-blocks"]}),c.invalidateQueries({queryKey:["stored-prompt-block"]}),c.invalidateQueries({queryKey:["prompt-block-versions",t]}),Be.success("Prompt block published"),u(d.promptBlocksLink())}catch(R){Be.error(`Failed to publish: ${R instanceof Error?R.message:"Unknown error"}`)}finally{h(!1)}},[_,f,l,t,u,d,c]),I=g.useCallback(async()=>{if(x&&n){h(!0);try{await l.getStoredPromptBlock(t).activateVersion(n),c.invalidateQueries({queryKey:["stored-prompt-blocks"]}),c.invalidateQueries({queryKey:["stored-prompt-block"]}),c.invalidateQueries({queryKey:["prompt-block-versions",t]}),Be.success("Version published"),u(d.promptBlocksLink())}catch(A){Be.error(`Failed to publish version: ${A instanceof Error?A.message:"Unknown error"}`)}finally{h(!1)}}else await N()},[N,x,n,l,t,c,u,d]);return o.jsxs(M1,{leftSlot:o.jsx(SBt,{form:_,onPublish:N,onSaveDraft:E,isSubmitting:p,isSavingDraft:m,isDirty:_.formState.isDirty,hasDraft:r,formResetKey:C,mode:"edit",blockId:t}),children:[x&&o.jsxs(Wn,{variant:"info",title:"This is a previous version",className:"m-4 mb-0",children:[o.jsx(Wn.Message,{children:"You are seeing a specific version of the prompt block."}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(oe,{type:"button",variant:"default",size:"sm",onClick:i,children:"View latest version"}),o.jsx(oe,{type:"button",variant:"default",size:"sm",onClick:I,disabled:n===a||p,children:p?"Publishing...":"Publish This Version"})]})]}),o.jsx("form",{className:"h-full",children:o.jsx(dBt,{form:_,formResetKey:C})})]})}function Lfs(){const{promptBlockId:e}=mr(),[t,n]=hi(),r=t.get("versionId"),{data:s,isLoading:a}=AL(e,{status:"draft"}),{data:i}=OBt({blockId:e??"",params:{orderBy:{direction:"DESC"}}}),l=s?.activeVersionId,c=i?.versions?.[0],u=!!(c&&(!l||c.id!==l)),d=g.useCallback(p=>{n(p?{versionId:p}:{})},[n]),f=g.useCallback(()=>{n({})},[n]);return a?o.jsx(_s,{className:"grid-rows-[1fr]",children:o.jsx(M1,{leftSlot:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ut,{className:"size-8"})}),children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ut,{className:"size-8"})})})}):!s||!e?o.jsx(_s,{className:"grid-rows-[1fr]",children:o.jsx(M1,{leftSlot:o.jsx("div",{className:"text-neutral3 flex h-full items-center justify-center",children:"Prompt block not found"}),children:o.jsx("div",{className:"text-neutral3 flex h-full items-center justify-center",children:"Prompt block not found"})})}):o.jsxs(_s,{className:"grid-rows-[1fr]",children:[o.jsx($y,{owner:"cms-prompt-block-edit",children:o.jsxs("div",{className:"flex items-center gap-2",children:[u&&o.jsx(St,{variant:"blue",children:"Unpublished changes"}),o.jsx(Sss,{blockId:e,value:r??"",onValueChange:d,variant:"ghost",activeVersionId:l})]})}),o.jsx(Dfs,{block:s,blockId:e,selectedVersionId:r,hasDraft:u,latestVersionId:c?.id,activeVersionId:l,onClearVersion:f})]})}function Ffs(){const{navigate:e,paths:t}=cn();return o.jsx(_s,{className:"grid-rows-[1fr]",children:o.jsx(Z7r,{onSuccess:n=>e(t.scorerLink(n.id))})})}function ket(e){return{name:e.name,description:e.description||void 0,type:e.type,model:e.model,instructions:e.instructions||void 0,scoreRange:e.scoreRange,defaultSampling:e.defaultSampling?.type==="ratio"&&typeof e.defaultSampling.rate=="number"?e.defaultSampling:{type:"none"}}}function zfs({scorer:e,scorerId:t,selectedVersionId:n,latestVersionId:r,activeVersionId:s,onClearVersion:a}){const i=Qe(),l=Lr(),{navigate:c,paths:u}=cn(),{updateStoredScorer:d}=GTe(t),[f,p]=g.useState(!1),[h,m]=g.useState(!1),v=g.useRef(null),{data:y}=Y7r({scorerId:t,versionId:n??""}),b=!!n&&!!y,x=b&&n!==r,S=b?y:e,k=g.useMemo(()=>({name:S.name||"",description:S.description||"",type:"llm-judge",model:{provider:S.model?.provider||"",name:S.model?.name||""},instructions:S.instructions||"",scoreRange:{min:S.scoreRange?.min??0,max:S.scoreRange?.max??1},defaultSampling:S.defaultSampling}),[S]),{form:_}=o4t({initialValues:k});g.useEffect(()=>{k&&_.reset(k)},[k,_]);const C=g.useCallback(async()=>{if(!await _.trigger()){Be.error("Please fill in all required fields");return}m(!0);try{const I=ket(_.getValues());await d.mutateAsync(I),Be.success("Draft saved")}catch(I){Be.error(`Failed to save draft: ${I instanceof Error?I.message:"Unknown error"}`)}finally{m(!1)}},[_,d]),T=g.useCallback(async()=>{if(!await _.trigger()){Be.error("Please fill in all required fields");return}p(!0);try{const I=ket(_.getValues());await d.mutateAsync(I);const R=(await i.getStoredScorer(t).listVersions({orderBy:{direction:"DESC"},perPage:1})).versions[0];R&&await i.getStoredScorer(t).activateVersion(R.id),l.invalidateQueries({queryKey:["scorers"]}),l.invalidateQueries({queryKey:["stored-scorers"]}),Be.success("Scorer published"),c(u.scorerLink(t))}catch(I){Be.error(`Failed to publish scorer: ${I instanceof Error?I.message:"Unknown error"}`)}finally{p(!1)}},[_,d,i,t,c,u,l]),E=g.useCallback(async()=>{if(x&&n){p(!0);try{await i.getStoredScorer(t).activateVersion(n),l.invalidateQueries({queryKey:["scorers"]}),l.invalidateQueries({queryKey:["stored-scorers"]}),l.invalidateQueries({queryKey:["scorer-versions",t]}),Be.success("Version published"),c(u.scorerLink(t))}catch(N){Be.error(`Failed to publish version: ${N instanceof Error?N.message:"Unknown error"}`)}finally{p(!1)}}else await T()},[T,x,n,i,t,l,c,u]);return o.jsxs(M1,{leftSlot:o.jsx(a4t,{form:_,onPublish:T,onSaveDraft:C,isSubmitting:f,isSavingDraft:h,formRef:v,mode:"edit"}),children:[x&&o.jsxs(Wn,{variant:"info",title:"This is a previous version",className:"m-4 mb-0",children:[o.jsx(Wn.Message,{children:"You are seeing a specific version of the scorer."}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(oe,{type:"button",variant:"default",size:"sm",onClick:a,children:"View latest version"}),o.jsx(oe,{type:"button",variant:"default",size:"sm",onClick:E,disabled:n===s||f,children:f?"Publishing...":"Publish This Version"})]})]}),o.jsx("form",{ref:v,className:"h-full",children:o.jsx(i4t,{form:_})})]})}function Bfs(){const{scorerId:e}=mr(),[t,n]=hi(),r=t.get("versionId"),{data:s,isLoading:a}=l4t(e,{status:"draft"}),{data:i}=u4t({scorerId:e??"",params:{orderBy:{direction:"DESC"}}}),l=s?.activeVersionId,c=i?.versions?.[0],u=!!(c&&l&&c.id!==l),d=g.useCallback(p=>{n(p?{versionId:p}:{})},[n]),f=g.useCallback(()=>{n({})},[n]);return a?o.jsx(_s,{className:"grid-rows-[1fr]",children:o.jsx(M1,{leftSlot:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ut,{className:"size-8"})}),children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ut,{className:"size-8"})})})}):!s||!e?o.jsx(_s,{className:"grid-rows-[1fr]",children:o.jsx(M1,{leftSlot:o.jsx("div",{className:"text-neutral3 flex h-full items-center justify-center",children:"Scorer not found"}),children:o.jsx("div",{className:"text-neutral3 flex h-full items-center justify-center",children:"Scorer not found"})})}):o.jsxs(_s,{className:"grid-rows-[1fr]",children:[o.jsx($y,{owner:"cms-scorer-edit",children:o.jsxs("div",{className:"flex items-center gap-2",children:[u&&o.jsx(St,{variant:"blue",children:"Unpublished changes"}),o.jsx(J7r,{scorerId:e,value:r??"",onValueChange:d,variant:"ghost",activeVersionId:l})]})}),o.jsx(zfs,{scorer:s,scorerId:e,selectedVersionId:r,latestVersionId:c?.id,activeVersionId:l,onClearVersion:f})]})}const PAe=(e,t)=>{const n=Qe();return yt({queryKey:["dataset-item-versions",e,t],queryFn:async()=>((await n.getItemHistory(e,t))?.history??[]).map((s,a)=>({id:s.id,datasetId:s.datasetId,datasetVersion:s.datasetVersion,input:s.input,groundTruth:s.groundTruth,expectedTrajectory:s.expectedTrajectory,toolMocks:s.toolMocks,scorerIds:s.scorerIds,metadata:s.metadata,validTo:s.validTo,isDeleted:s.isDeleted,createdAt:s.createdAt,updatedAt:s.updatedAt,isLatest:a===0})),enabled:!!e&&!!t})},Mxe=(e,t,n,r)=>{const s=Qe();return yt({queryKey:["dataset-item-version",e,t,n],queryFn:async()=>{const a=await s.getDatasetItemVersion(e,t,n);return{id:a.id,datasetId:a.datasetId,datasetVersion:a.datasetVersion,input:a.input,groundTruth:a.groundTruth,expectedTrajectory:a.expectedTrajectory,toolMocks:a.toolMocks,scorerIds:a.scorerIds,metadata:a.metadata,validTo:a.validTo??null,isDeleted:a.isDeleted??!1,createdAt:a.createdAt,updatedAt:a.updatedAt,isLatest:r!=null?n===r:!1}},enabled:!!e&&!!t&&n>0})},UQ=e=>{const t=Qe();return yt({queryKey:["experiments",e],queryFn:()=>t.listExperiments(e)})},Ufs=(e,t,n,r)=>{const s=Qe();return yt({queryKey:["compare-experiments",e,t,n,r],queryFn:()=>s.compareExperiments({datasetId:e,experimentIdA:t,experimentIdB:n,...r}),enabled:!!e&&!!t&&!!n})};var _9={exports:{}};var qfs=_9.exports,Oet;function Vfs(){return Oet||(Oet=1,(function(e,t){((n,r)=>{e.exports=r()})(qfs,function n(){var r=typeof self<"u"?self:typeof window<"u"?window:r!==void 0?r:{},s,a=!r.document&&!!r.postMessage,i=r.IS_PAPA_WORKER||!1,l={},c=0,u={};function d(N){return N.charCodeAt(0)===65279?N.slice(1):N}function f(N){this._handle=null,this._finished=!1,this._completed=!1,this._halted=!1,this._input=null,this._baseIndex=0,this._partialLine="",this._rowCount=0,this._start=0,this._nextChunk=null,this.isFirstChunk=!0,this._completeResults={data:[],errors:[],meta:{}},(function(I){var A=C(I);A.chunkSize=parseInt(A.chunkSize),I.step||I.chunk||(A.chunkSize=null),this._handle=new y(A),(this._handle.streamer=this)._config=A}).call(this,N),this.parseChunk=function(I,A){var R=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&0<R){let D=this._config.newline;D||(L=this._config.quoteChar||'"',D=this._handle.guessLineEndings(I,L)),I=[...I.split(D).slice(R)].join(D)}this.isFirstChunk&&E(this._config.beforeFirstChunk)&&(L=this._config.beforeFirstChunk(I))!==void 0&&(I=L),this.isFirstChunk=!1,this._halted=!1;var R=this._partialLine+I,L=(this._partialLine="",this._handle.parse(R,this._baseIndex,!this._finished));if(!this._handle.paused()&&!this._handle.aborted()){if(I=L.meta.cursor,R=(this._finished||(this._partialLine=R.substring(I-this._baseIndex),this._baseIndex=I),L&&L.data&&(this._rowCount+=L.data.length),this._finished||this._config.preview&&this._rowCount>=this._config.preview),i)r.postMessage({results:L,workerId:u.WORKER_ID,finished:R});else if(E(this._config.chunk)&&!A){if(this._config.chunk(L,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);this._completeResults=L=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(L.data),this._completeResults.errors=this._completeResults.errors.concat(L.errors),this._completeResults.meta=L.meta),this._completed||!R||!E(this._config.complete)||L&&L.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),R||L&&L.meta.paused||this._nextChunk(),L}this._halted=!0},this._sendError=function(I){E(this._config.error)?this._config.error(I):i&&this._config.error&&r.postMessage({workerId:u.WORKER_ID,error:I,finished:!1})}}function p(N){var I;(N=N||{}).chunkSize||(N.chunkSize=u.RemoteChunkSize),f.call(this,N),this._nextChunk=a?function(){this._readChunk(),this._chunkLoaded()}:function(){this._readChunk()},this.stream=function(A){this._input=A,this._nextChunk()},this._readChunk=function(){if(this._finished)this._chunkLoaded();else{if(I=new XMLHttpRequest,this._config.withCredentials&&(I.withCredentials=this._config.withCredentials),a||(I.onload=T(this._chunkLoaded,this),I.onerror=T(this._chunkError,this)),I.open(this._config.downloadRequestBody?"POST":"GET",this._input,!a),this._config.downloadRequestHeaders){var A,R=this._config.downloadRequestHeaders;for(A in R)I.setRequestHeader(A,R[A])}var L;this._config.chunkSize&&(L=this._start+this._config.chunkSize-1,I.setRequestHeader("Range","bytes="+this._start+"-"+L));try{I.send(this._config.downloadRequestBody)}catch(D){this._chunkError(D.message)}a&&I.status===0&&this._chunkError()}},this._chunkLoaded=function(){I.readyState===4&&(I.status<200||400<=I.status?this._chunkError():(this._start+=this._config.chunkSize||I.responseText.length,this._finished=!this._config.chunkSize||this._start>=(A=>(A=A.getResponseHeader("Content-Range"))!==null?parseInt(A.substring(A.lastIndexOf("/")+1)):-1)(I),this.parseChunk(I.responseText)))},this._chunkError=function(A){A=I.statusText||A,this._sendError(new Error(A))}}function h(N){(N=N||{}).chunkSize||(N.chunkSize=u.LocalChunkSize),f.call(this,N);var I,A,R=typeof FileReader<"u";this.stream=function(L){this._input=L,A=L.slice||L.webkitSlice||L.mozSlice,R?((I=new FileReader).onload=T(this._chunkLoaded,this),I.onerror=T(this._chunkError,this)):I=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){this._finished||this._config.preview&&!(this._rowCount<this._config.preview)||this._readChunk()},this._readChunk=function(){var L=this._input,D=(this._config.chunkSize&&(D=Math.min(this._start+this._config.chunkSize,this._input.size),L=A.call(L,this._start,D)),I.readAsText(L,this._config.encoding));R||this._chunkLoaded({target:{result:D}})},this._chunkLoaded=function(L){this._start+=this._config.chunkSize,this._finished=!this._config.chunkSize||this._start>=this._input.size,this.parseChunk(L.target.result)},this._chunkError=function(){this._sendError(I.error)}}function m(N){var I;f.call(this,N=N||{}),this.stream=function(A){return I=A,this._nextChunk()},this._nextChunk=function(){var A,R;if(!this._finished)return A=this._config.chunkSize,I=A?(R=I.substring(0,A),I.substring(A)):(R=I,""),this._finished=!I,this.parseChunk(R)}}function v(N){f.call(this,N=N||{});var I=[],A=!0,R=!1;this.pause=function(){f.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){f.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function(L){this._input=L,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){R&&I.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),I.length?this.parseChunk(I.shift()):A=!0},this._streamData=T(function(L){try{I.push(typeof L=="string"?L:L.toString(this._config.encoding)),A&&(A=!1,this._checkIsFinished(),this.parseChunk(I.shift()))}catch(D){this._streamError(D)}},this),this._streamError=T(function(L){this._streamCleanUp(),this._sendError(L)},this),this._streamEnd=T(function(){this._streamCleanUp(),R=!0,this._streamData("")},this),this._streamCleanUp=T(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}function y(N){var I,A,R,L,D=Math.pow(2,53),F=-D,H=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,B=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,z=this,V=0,M=0,G=!1,U=!1,$=[],q={data:[],errors:[],meta:{}};function Z(ee){return N.skipEmptyLines==="greedy"?ee.join("").trim()==="":ee.length===1&&ee[0].length===0}function Y(){if(q&&R&&(J("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+u.DefaultDelimiter+"'"),R=!1),N.skipEmptyLines&&(q.data=q.data.filter(function(X){return!Z(X)})),ne()){let X=function(te,se){te=d(te),E(N.transformHeader)&&(te=N.transformHeader(te,se)),$.push(te)};if(q)if(Array.isArray(q.data[0])){for(var ee=0;ne()&&ee<q.data.length;ee++)q.data[ee].forEach(X);q.data.splice(0,1)}else q.data.forEach(X)}function re(X,te){for(var se=N.header?{}:[],pe=0;pe<X.length;pe++){var ce=pe,Se=X[pe],Se=((ve,ke)=>(Ne=>(N.dynamicTypingFunction&&N.dynamicTyping[Ne]===void 0&&(N.dynamicTyping[Ne]=N.dynamicTypingFunction(Ne)),(N.dynamicTyping[Ne]||N.dynamicTyping)===!0))(ve)?ke==="true"||ke==="TRUE"||ke!=="false"&&ke!=="FALSE"&&((Ne=>{if(H.test(Ne)&&(Ne=parseFloat(Ne),F<Ne&&Ne<D))return 1})(ke)?parseFloat(ke):B.test(ke)?new Date(ke):ke===""?null:ke):ke)(ce=N.header?pe>=$.length?"__parsed_extra":$[pe]:ce,Se=N.transform?N.transform(Se,ce):Se);ce==="__parsed_extra"?(se[ce]=se[ce]||[],se[ce].push(Se)):se[ce]=Se}return N.header&&(pe>$.length?J("FieldMismatch","TooManyFields","Too many fields: expected "+$.length+" fields but parsed "+pe,M+te):pe<$.length&&J("FieldMismatch","TooFewFields","Too few fields: expected "+$.length+" fields but parsed "+pe,M+te)),se}var le;q&&(N.header||N.dynamicTyping||N.transform)&&(le=1,!q.data.length||Array.isArray(q.data[0])?(q.data=q.data.map(re),le=q.data.length):q.data=re(q.data,0),N.header&&q.meta&&(q.meta.fields=$),M+=le)}function ne(){return N.header&&$.length===0}function J(ee,re,le,X){ee={type:ee,code:re,message:le},X!==void 0&&(ee.row=X),q.errors.push(ee)}E(N.step)&&(L=N.step,N.step=function(ee){q=ee,ne()?Y():(Y(),q.data.length!==0&&(V+=ee.data.length,N.preview&&V>N.preview?A.abort():(q.data=q.data[0],L(q,z))))}),this.parse=function(ee,re,le){var X=N.quoteChar||'"',X=(N.newline||(N.newline=this.guessLineEndings(ee,X)),R=!1,N.delimiter?E(N.delimiter)&&(N.delimiter=N.delimiter(ee),q.meta.delimiter=N.delimiter):((X=((te,se,pe,ce,Se)=>{var ve,ke,Ne,Me;Se=Se||[","," ","|",";",u.RECORD_SEP,u.UNIT_SEP];for(var Ae=0;Ae<Se.length;Ae++){for(var Ie,ae=Se[Ae],fe=0,ue=0,we=0,Ee=(Ne=void 0,new x({comments:ce,delimiter:ae,newline:se,preview:10}).parse(te)),ge=0;ge<Ee.data.length;ge++)pe&&Z(Ee.data[ge])?we++:(Ie=Ee.data[ge].length,ue+=Ie,Ne===void 0?Ne=Ie:0<Ie&&(fe+=Math.abs(Ie-Ne),Ne=Ie));0<Ee.data.length&&(ue/=Ee.data.length-we),(ke===void 0||fe<=ke)&&(Me===void 0||Me<ue)&&1.99<ue&&(ke=fe,ve=ae,Me=ue)}return{successful:!!(N.delimiter=ve),bestDelimiter:ve}})(ee,N.newline,N.skipEmptyLines,N.comments,N.delimitersToGuess)).successful?N.delimiter=X.bestDelimiter:(R=!0,N.delimiter=u.DefaultDelimiter),q.meta.delimiter=N.delimiter),C(N));return N.preview&&N.header&&X.preview++,I=ee,A=new x(X),q=A.parse(I,re,le),Y(),G?{meta:{paused:!0}}:q||{meta:{paused:!1}}},this.paused=function(){return G},this.pause=function(){G=!0,A.abort(),I=E(N.chunk)?"":I.substring(A.getCharIndex())},this.resume=function(){z.streamer._halted?(G=!1,z.streamer.parseChunk(I,!0)):setTimeout(z.resume,3)},this.aborted=function(){return U},this.abort=function(){U=!0,A.abort(),q.meta.aborted=!0,E(N.complete)&&N.complete(q),I=""},this.guessLineEndings=function(te,X){te=te.substring(0,1048576);var X=new RegExp(b(X)+"([^]*?)"+b(X),"gm"),le=(te=te.replace(X,"")).split("\r"),X=te.split(`
|
|
627
|
+
Token usage: ${n} input + ${r} output = ${s} total`:`The model stopped generating because it reached the maximum token limit (${s} tokens). The response was truncated and may be incomplete.`}function nl(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString()}function Vp(e,t){return t?.toLowerCase()==="usd"||!t?`$${e<.01&&e>0?e.toFixed(4):e.toFixed(2)}`:`${e.toFixed(4)} ${t}`}const Rxe={className:"max-h-80",mask:{left:!1},stickyHeaderBackground:"tinted"},Hp={orange:"#fb923c",pink:"#f472b6",purple:"#8b5cf6",blue:"#4f83f1",blueDark:"#2b5cd9",yellow:"#facc15"},Vcs=36,Hcs=8;function GUt({traces:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,filtersApplied:a,featuredTraceId:i,featuredSpanId:l,isBranchesMode:c,recentlyAddedKeys:u,columnPreferences:d=$w,usageByTraceId:f,onTraceClick:p}){const h=g.useRef(null),m=$cs(d),v=qUt({count:e.length,getScrollElement:()=>h.current,estimateSize:()=>Vcs,overscan:Hcs}),{getRowProps:y}=wo({count:e.length,containerRef:h,onNavigate:C=>v.scrollToIndex(C)}),b=g.useRef(t);if(g.useEffect(()=>{b.current&&!t&&h.current?.dispatchEvent(new Event("scroll")),b.current=t},[t]),t)return o.jsx(Pl,{columns:m,fit:"container"});const x=v.getVirtualItems(),S=v.getTotalSize(),k=x[0]?.start??0,_=x.length>0?Math.max(0,S-(x[x.length-1]?.end??0)):0;return o.jsxs(Go,{columns:m,variant:"striped",fit:"container",scrollRef:h,className:"min-w-0",children:[o.jsxs(Go.Top,{children:[o.jsx(Go.TopCell,{children:"Created"}),o.jsx(Go.TopCell,{children:"Name"}),Th(d,"input")&&o.jsx(Go.TopCell,{children:"Input"}),Th(d,"entity")&&o.jsx(Go.TopCell,{children:"Entity"}),o.jsx(Go.TopCell,{children:"Status"}),Th(d,"duration")&&o.jsx(Go.TopCell,{className:"justify-end text-right",children:"Duration"}),Th(d,"inputTokens")&&o.jsx(Go.TopCell,{className:"justify-end text-right",children:"Input tokens"}),Th(d,"outputTokens")&&o.jsx(Go.TopCell,{className:"justify-end text-right",children:"Output tokens"}),Th(d,"estimatedCost")&&o.jsx(Go.TopCell,{className:"justify-end text-right",children:"Est. cost"}),d.metadataKeys.map(C=>o.jsx(Go.TopCellWithTooltip,{tooltip:C,children:C},C))]}),e.length===0?o.jsx(Go.NoMatch,{message:a?"No traces found for applied filters":"No traces found yet"}):o.jsxs(o.Fragment,{children:[o.jsx(Go.Spacer,{height:k}),x.map(C=>{const T=e[C.index];if(!T)return null;const E=T.traceId===i&&(l==null||T.spanId===l),N=`${T.traceId}:${T.spanId??""}`,I=u?.has(N)??!1,A=T.startedAt??T.createdAt,R=T.entityName||T.entityId,L=f?.get(T.traceId);return o.jsxs(Go.RowButton,{ref:v.measureElement,"data-index":C.index,...y(C.index),onClick:()=>p(T),featured:E,className:K(I&&"animate-row-highlight"),children:[o.jsx(Go.CreatedCell,{timestamp:A}),o.jsx(Go.NameCell,{name:T.name,parentSpanId:T.parentSpanId,showLevelTooltip:c}),Th(d,"input")&&o.jsx(Go.InputCell,{input:T.inputPreview??Bcs(T.input)}),Th(d,"entity")&&o.jsx(Go.EntityCell,{entityType:T.entityType,entityName:R}),o.jsx(Go.StatusCell,{status:T.status}),Th(d,"duration")&&o.jsx(be.NumberCell,{children:OQ(T.startedAt,T.endedAt)}),Th(d,"inputTokens")&&o.jsx(be.NumberCell,{children:L?.inputTokens===void 0?void 0:nl(L.inputTokens)}),Th(d,"outputTokens")&&o.jsx(be.NumberCell,{children:L?.outputTokens===void 0?void 0:nl(L.outputTokens)}),Th(d,"estimatedCost")&&o.jsx(be.NumberCell,{children:L?.estimatedCost===void 0?void 0:Vp(L.estimatedCost,L.costUnit)}),d.metadataKeys.map(D=>{const F=Mcs(T.metadata,D);return o.jsx(be.TextCell,{font:"mono",children:F},D)})]},N)}),o.jsx(Go.Spacer,{height:_}),o.jsx(Go.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})]})}function QUt(e,t,n,r){const s=g.useMemo(()=>t?e.findIndex(u=>u.traceId===t&&(n==null||u.spanId===n)):-1,[e,t,n]),a=n!=null,i=u=>r(u.traceId,a?u.spanId??void 0:void 0),l=s>0?()=>{const u=e[s-1];u&&i(u)}:void 0,c=s>=0&&s<e.length-1?()=>{const u=e[s+1];u&&i(u)}:void 0;return{featuredTraceIdx:s,handlePreviousTrace:l,handleNextTrace:c}}function Wcs(e){const t=[];return lw(e,t,new Set),t.join(" ")}function lw(e,t,n){if(e==null)return;switch(typeof e){case"string":{const s=e.trim();s&&t.push(s);return}case"number":{Number.isFinite(e)&&t.push(String(e));return}case"boolean":case"bigint":t.push(String(e));return;case"function":case"symbol":return}const r=e;if(!n.has(r)){n.add(r);try{Zcs(r,t,n)}finally{n.delete(r)}}}function Zcs(e,t,n){if(e instanceof Date){const r=e.getTime();Number.isNaN(r)||t.push(e.toISOString());return}if(e instanceof Error){lw(e.message,t,n);return}if(Array.isArray(e)){for(const r of e)lw(r,t,n);return}if(e instanceof Map){for(const[r,s]of e)lw(r,t,n),lw(s,t,n);return}if(e instanceof Set){for(const r of e)lw(r,t,n);return}for(const r of Object.keys(e)){lw(r,t,n);let s;try{s=e[r]}catch{continue}lw(s,t,n)}}function Gcs(e){return e.map(t=>({...t,searchText:Wcs(t).toLowerCase()}))}function uAe(e){return e?{...e,spans:Gcs(e.spans)}:null}const Qcs=1e3*60*60*24*30;function Ycs({traceId:e,spanId:t,depth:n}){const r=Qe();return yt({queryKey:["branch",e,t,n],queryFn:async()=>{if(!e||!t)throw new Error("traceId and spanId are required");return r.getBranch({traceId:e,spanId:t,depth:n})},select:uAe,enabled:!!e&&!!t,staleTime:s=>s.state.data?.spans.every(l=>!!l.endedAt)?Qcs:0})}const Kcs=1e3*60*60*24*30;function YUt(e){const t=Qe();return yt({queryKey:["trace-spans",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return await t.getTrace(e)},select:uAe,enabled:!!e,staleTime:n=>n.state.data?.spans.every(a=>!!a.endedAt)?Kcs:0})}function KUt({traceId:e,anchorSpanId:t,listMode:n,depth:r}){const s=n==="branches",a=YUt(s?null:e),i=Ycs({traceId:s?e:null,spanId:s?t:null,depth:r});return s?{spans:i.data?.spans,anchorSpanId:t??void 0,isLoading:i.isLoading,isError:i.isError,error:i.error}:{spans:a.data?.spans,anchorSpanId:void 0,isLoading:a.isLoading,isError:a.isError,error:a.error}}const fie=new WeakMap,pie=new WeakMap,hie=new WeakMap,Xcs=1e4,sw={deltaPollIntervalMs:5e3,deltaChaseIntervalMs:100,deltaLimit:100,pageModeRefetchIntervalMs:1e4,page0StatusRefreshIntervalMs:6e4,idleGuardThresholdMs:15*6e4,minRefetchSpinMs:400,deltaHighlightMs:1e3};function Jcs(e,t,n){return e===0?!1:t-e>n}function eus(e){return e?.status===501}function tus(e){const t=e?.status;return t===404||t===500?t:void 0}function nus(e,t,n){return e===404?!0:e!==500||t===void 0?!1:n-t>=Xcs}const mie=async e=>{const{client:t,filters:n,listMode:r="traces"}=e,s=e.mode==="delta"?{mode:"delta",after:e.after,limit:e.limit,filters:n}:{pagination:{page:e.page,perPage:e.perPage},filters:n};if(r==="branches")return t.listBranches(s);if(pie.get(t)==="unsupported")return t.listTraces(s);try{const a=await t.listTracesLight(s);if(e.mode!=="delta"){const i=a.spans??[];if(i.length>0&&i.every(l=>l.status===void 0))return pie.set(t,"unsupported"),t.listTraces(s)}return hie.delete(t),a}catch(a){const i=tus(a);if(i===void 0)throw a;const l=Date.now(),c=hie.get(t);return i===500&&c===void 0&&hie.set(t,l),nus(i,c,l)&&pie.set(t,"unsupported"),t.listTraces(s)}},set=25;function rus(e,t,n){if(e?.pagination?.hasMore)return n+1}function sus(e){return"branches"in e?e.branches??[]:e.spans??[]}function aus(e){const t=new Set;return{spans:e.pages.flatMap(r=>sus(r)).filter(r=>{const s=`${r.traceId}:${r.spanId}`;return t.has(s)?!1:(t.add(s),!0)}),deltaCursor:e.pages[0]?.deltaCursor}}function Pxe(e){return`${e.traceId}:${e.spanId}`}function aet(e){return new Map(e.map(t=>[Pxe(t),t]))}function ius(e,t,n){if(!e||e.pages.length===0)return e;const[r,...s]=e.pages;if(!r)return e;let a;if(n==="branches"&&"branches"in r&&"branches"in t){const i=aet(t.branches??[]);if(i.size===0)return e;a={...r,branches:(r.branches??[]).map(l=>i.get(Pxe(l))??l)}}else if("spans"in r&&"spans"in t){const i=aet(t.spans??[]);if(i.size===0)return e;a={...r,spans:(r.spans??[]).map(l=>i.get(Pxe(l))??l)}}else return e;return{...e,pages:[a,...s]}}function iet(e){return[...e].sort((t,n)=>{const r=t.startedAt?new Date(t.startedAt).getTime():0;return(n.startedAt?new Date(n.startedAt).getTime():0)-r})}function ous(e,t,n){if(!e||e.pages.length===0)return e;const[r,...s]=e.pages;if(!r)return e;const a=t.deltaCursor??r.deltaCursor;let i;if(n==="branches"&&"branches"in r){const l=t.branches??[];i={...r,branches:iet([...l,...r.branches??[]]),deltaCursor:a}}else if("spans"in r){const l=t.spans??[];i={...r,spans:iet([...l,...r.spans??[]]),deltaCursor:a}}else return e;return{...e,pages:[i,...s]}}const XUt=({filters:e,listMode:t="traces",polling:n={}})=>{const{deltaPollIntervalMs:r=sw.deltaPollIntervalMs,deltaChaseIntervalMs:s=sw.deltaChaseIntervalMs,deltaLimit:a=sw.deltaLimit,pageModeRefetchIntervalMs:i=sw.pageModeRefetchIntervalMs,page0StatusRefreshIntervalMs:l=sw.page0StatusRefreshIntervalMs,idleGuardThresholdMs:c=sw.idleGuardThresholdMs,minRefetchSpinMs:u=sw.minRefetchSpinMs,deltaHighlightMs:d=sw.deltaHighlightMs}=n,f=Qe(),p=Lr(),{inView:h,setRef:m}=tC(),[v,y]=g.useState(()=>fie.get(f)??"unknown"),b=v==="unsupported",[x,S]=g.useState(!0),[k,_]=g.useState(()=>new Set);g.useEffect(()=>{_(new Set)},[t,e]);const C=["traces",t,e],T=K1({queryKey:C,queryFn:({pageParam:U})=>mie({client:f,page:U,perPage:set,filters:e,listMode:t}),initialPageParam:0,getNextPageParam:rus,select:aus,retry:!1,refetchInterval:U=>ks(U.state.error)||!x?!1:b?i:!1}),E=T.data?.deltaCursor;g.useEffect(()=>{T.isSuccess&&E===void 0&&v==="unknown"&&(fie.set(f,"unsupported"),y("unsupported"))},[T.isSuccess,E,v,f]);const N=yt({queryKey:["traces-delta",t,e],queryFn:()=>{const U=p.getQueryData(C)?.pages[0]?.deltaCursor;return U?mie({client:f,mode:"delta",after:U,limit:a,filters:e,listMode:t}):null},enabled:!!E&&!b&&x,retry:!1,refetchInterval:U=>U.state.error?!1:U.state.data?.delta?.hasMore?s:r});g.useEffect(()=>{const U=N.data;if(!U)return;p.setQueryData(C,Z=>ous(Z,U,t));const $=t==="branches"&&"branches"in U?U.branches??[]:"spans"in U?U.spans??[]:[];if($.length===0)return;const q=$.map(Z=>`${Z.traceId}:${Z.spanId??""}`);_(Z=>{const Y=new Set(Z);for(const ne of q)Y.add(ne);return Y}),setTimeout(()=>{_(Z=>{const Y=new Set(Z);for(const ne of q)Y.delete(ne);return Y})},d)},[N.data,p,t,e,d]),g.useEffect(()=>{eus(N.error)&&(fie.set(f,"unsupported"),y("unsupported"))},[N.error,f]);const I=yt({queryKey:["traces-status-refresh",t,e],queryFn:()=>mie({client:f,page:0,perPage:set,filters:e,listMode:t}),enabled:!!E&&!b&&x,refetchInterval:l,refetchOnMount:!1,retry:!1});g.useEffect(()=>{const U=I.data;U&&p.setQueryData(C,$=>ius($,U,t))},[I.data,p,t,e]);const A=g.useRef(0);g.useEffect(()=>{const U=Math.max(T.dataUpdatedAt,N.dataUpdatedAt,I.dataUpdatedAt);U>A.current&&(A.current=U)},[T.dataUpdatedAt,N.dataUpdatedAt,I.dataUpdatedAt]);const R=g.useRef(x);g.useEffect(()=>{R.current=x},[x]),g.useEffect(()=>{const U=()=>{document.visibilityState==="visible"&&R.current&&Jcs(A.current,Date.now(),c)&&p.resetQueries({queryKey:["traces",t,e]})};return document.addEventListener("visibilitychange",U),()=>document.removeEventListener("visibilitychange",U)},[p,t,e,c]);const{hasNextPage:L,isFetchingNextPage:D,fetchNextPage:F}=T;g.useEffect(()=>{h&&L&&!D&&F()},[h,L,D,F]);const H=T.isFetching||I.isFetching||N.isFetching,B=Math.max(T.dataUpdatedAt,T.errorUpdatedAt,N.dataUpdatedAt,N.errorUpdatedAt,I.dataUpdatedAt,I.errorUpdatedAt),[z,V]=g.useState(!1),M=g.useRef(B);return g.useEffect(()=>{if(B>M.current){M.current=B,V(!0);const U=setTimeout(()=>V(!1),u);return()=>clearTimeout(U)}},[B,u]),{...T,setEndOfListElement:m,isRefetching:H||z,autoRefetch:x,setAutoRefetch:S,recentlyAddedKeys:k}};function oet(e){return!!e&&Object.values(e).some(t=>typeof t=="number")}function lus(e){if(!e)return null;const t=typeof e.inputTokens=="number",n=typeof e.outputTokens=="number";if(!t&&!n)return null;const r=e.inputTokens??0,s=e.outputTokens??0,a=r+s,i=a>0;return{inputValue:r,outputValue:s,total:a,showSplit:i,inputPct:i?r/a*100:0,outputPct:i?s/a*100:0,inputDetails:t&&oet(e.inputDetails)?e.inputDetails:void 0,outputDetails:n&&oet(e.outputDetails)?e.outputDetails:void 0}}const cus={text:"Text",cacheRead:"Cache read",cacheWrite:"Cache write",audio:"Audio",image:"Image",reasoning:"Reasoning"},cet="oklch(0.78 0.16 320)",uet="oklch(0.55 0.18 320)";function uus({usage:e,className:t}){const n=lus(e);if(!n)return null;const{inputValue:r,outputValue:s,total:a,showSplit:i,inputPct:l,outputPct:c,inputDetails:u,outputDetails:d}=n;return o.jsxs("div",{className:K("mt-2 mb-8 grid grid-cols-1 border-b border-border1 pb-3 4xl:grid-cols-2 4xl:gap-12",t),children:[i&&o.jsxs("div",{className:"mb-2",children:[o.jsxs("div",{className:"text-neutral2 flex items-baseline gap-3",children:[o.jsx("span",{className:"text-ui-md",children:"Tokens Used"}),o.jsx("span",{className:"text-ui-md text-neutral4 font-semibold",children:a.toLocaleString()}),o.jsxs("span",{className:"text-ui-sm ml-auto",children:[Math.round(l),"% Input vs ",Math.round(c),"% Output"]})]}),o.jsx("div",{className:"bg-surface4 mt-2 rounded-md p-1.5",children:o.jsxs("div",{className:"relative h-1.5 w-full overflow-hidden rounded-sm",children:[o.jsx("div",{className:"absolute top-0 left-0 h-1.5",style:{width:`${l}%`,backgroundColor:cet}}),o.jsx("div",{className:"absolute top-0 h-1.5",style:{left:`${l}%`,width:`${c}%`,backgroundColor:uet}})]})})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[o.jsx(det,{label:"Input",color:cet,value:r,details:u}),o.jsx(det,{label:"Output",color:uet,value:s,details:d})]})]})}function det({label:e,color:t,value:n,details:r}){return o.jsxs("div",{children:[o.jsxs("div",{className:"text-neutral2 mb-2 flex items-baseline gap-3",children:[o.jsx("span",{className:"text-ui-md",children:e}),typeof n=="number"&&o.jsxs("span",{className:"flex items-baseline gap-1.5",children:[o.jsx("span",{className:"text-ui-md text-neutral4 font-semibold",children:n.toLocaleString()}),o.jsx("span",{className:"size-2 self-center rounded-full",style:{backgroundColor:t}})]})]}),r&&o.jsx(dus,{details:r})]})}function dus({details:e}){return o.jsx(_n,{density:"dense",children:Object.entries(e).map(([t,n])=>typeof n!="number"?null:o.jsxs(g.Fragment,{children:[o.jsx(_n.Key,{children:cus[t]||t}),o.jsx(_n.Value,{className:"text-right",children:n.toLocaleString()})]},t))})}function qz(e,t,n){return o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"text-neutral2 flex items-center gap-1.5 tracking-widest uppercase [&>svg]:size-3.5",children:[t,e]}),o.jsxs("span",{children:["› Span ",o.jsxs("b",{className:"text-neutral3",children:["#",n.spanId]})]}),o.jsxs("span",{children:["› Trace ",o.jsxs("b",{className:"text-neutral3",children:["#",n.traceId]})]})]})}function JUt({traceId:e,spanId:t,span:n,isLoading:r,onClose:s,onPrevious:a,onNext:i,activeTab:l,onTabChange:c,feedbackTabSlot:u,feedbackTabBadge:d,isAnchor:f,className:p}){return o.jsxs(fn,{className:p,children:[o.jsxs(fn.Header,{children:[o.jsxs(fn.Heading,{children:["Span ",o.jsxs("b",{children:["# ",t]})]}),o.jsxs(hs,{className:"ml-auto shrink-0",children:[o.jsx(fn.NextPrevNav,{onPrevious:a,onNext:i,previousLabel:"Previous span",nextLabel:"Next span"}),o.jsx(fn.CloseButton,{onClick:s})]})]}),r?o.jsx(fn.LoadingData,{children:"Loading span details..."}):n?o.jsx(fus,{span:n,traceId:e,spanId:t,activeTab:l,onTabChange:c,feedbackTabSlot:u,feedbackTabBadge:d,isAnchor:f}):o.jsx(fn.NoData,{children:"Span not found."})]})}function fus({span:e,traceId:t,spanId:n,activeTab:r,onTabChange:s,feedbackTabSlot:a,feedbackTabBadge:i,isAnchor:l}){const c=OQ(e.startedAt,e.endedAt),u=iV(e.startedAt),d=iV(e.endedAt),f=e.attributes?.usage,p=o.jsxs(o.Fragment,{children:[Ucs(e)&&o.jsx("div",{className:"mb-3",children:o.jsx(Wn,{variant:"warning",title:"Token Limit Exceeded",children:o.jsx(Wn.Message,{children:qcs(e)})})}),f&&o.jsx(uus,{usage:f,className:"mb-3"}),o.jsxs(_n,{children:[(l??e.parentSpanId==null)&&o.jsxs(o.Fragment,{children:[e.traceId&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Trace Id"}),o.jsx(_n.ValueWithCopyBtn,{copyTooltip:"Copy Trace Id to clipboard",copyValue:e.traceId,children:e.traceId})]}),e.tags&&e.tags.length>0&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Tags"}),o.jsx(_n.Value,{children:e.tags.join(", ")})]}),e.runId&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Run Id"}),o.jsx(_n.ValueWithCopyBtn,{copyTooltip:"Copy Run Id to clipboard",copyValue:e.runId,children:e.runId})]}),e.threadId&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Thread Id"}),o.jsx(_n.ValueWithCopyBtn,{copyTooltip:"Copy Thread Id to clipboard",copyValue:e.threadId,children:e.threadId})]}),e.sessionId&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Session Id"}),o.jsx(_n.ValueWithCopyBtn,{copyTooltip:"Copy Session Id to clipboard",copyValue:e.sessionId,children:e.sessionId})]}),e.requestId&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Request Id"}),o.jsx(_n.ValueWithCopyBtn,{copyTooltip:"Copy Request Id to clipboard",copyValue:e.requestId,children:e.requestId})]}),e.resourceId&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Resource Id"}),o.jsx(_n.ValueWithCopyBtn,{copyTooltip:"Copy Resource Id to clipboard",copyValue:e.resourceId,children:e.resourceId})]}),e.userId&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"User Id"}),o.jsx(_n.ValueWithCopyBtn,{copyTooltip:"Copy User Id to clipboard",copyValue:e.userId,children:e.userId})]}),e.organizationId&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Organization Id"}),o.jsx(_n.ValueWithCopyBtn,{copyTooltip:"Copy Organization Id to clipboard",copyValue:e.organizationId,children:e.organizationId})]}),e.experimentId&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Experiment Id"}),o.jsx(_n.ValueWithCopyBtn,{copyTooltip:"Copy Experiment Id to clipboard",copyValue:e.experimentId,children:e.experimentId})]})]}),e.name&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Name"}),o.jsx(_n.Value,{children:e.name})]}),e.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Type"}),o.jsx(_n.Value,{children:e.spanType})]}),u&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Started"}),o.jsx(_n.Value,{children:u})]}),d&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Ended"}),o.jsx(_n.Value,{children:d})]}),c&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Duration"}),o.jsx(_n.Value,{children:c})]})]}),o.jsxs("div",{className:"mt-3 grid gap-3",children:[o.jsx(fn.CodeSection,{title:"Input",dialogTitle:qz("Input",o.jsx(xx,{}),{spanId:n,traceId:t}),icon:o.jsx(xx,{}),codeStr:JSON.stringify(e.input??null,null,2)}),o.jsx(fn.CodeSection,{title:"Output",dialogTitle:qz("Output",o.jsx(em,{}),{spanId:n,traceId:t}),icon:o.jsx(em,{}),codeStr:JSON.stringify(e.output??null,null,2)}),o.jsx(fn.CodeSection,{title:"Metadata",dialogTitle:qz("Metadata",o.jsx(Jl,{}),{spanId:n,traceId:t}),icon:o.jsx(Jl,{}),codeStr:JSON.stringify(e.metadata??null,null,2)}),o.jsx(fn.CodeSection,{title:"Attributes",dialogTitle:qz("Attributes",o.jsx(Jl,{}),{spanId:n,traceId:t}),icon:o.jsx(Jl,{}),codeStr:JSON.stringify(e.attributes??null,null,2)})]})]});return a?o.jsx(fn.Content,{children:o.jsxs(yc,{defaultTab:"details",value:r,onValueChange:s,children:[o.jsxs(vc,{variant:"pill-ghost",className:"px-0",children:[o.jsx(Ar,{value:"details",children:"Details"}),o.jsxs(Ar,{value:"feedback",children:["Feedback ",i!=null&&o.jsxs(o.Fragment,{children:["(",i,")"]})]})]}),o.jsx(fs,{value:"details",children:p}),o.jsx(fs,{value:"feedback",children:a({span:e,traceId:t,spanId:n})})]})}):o.jsx(fn.Content,{children:p})}const pus=1e3*60*60*24*30;function _Q(e,t){const n=Qe();return yt({queryKey:["span-detail",e,t],queryFn:async()=>{if(!e||!t)throw new Error("Trace ID and Span ID are required");return n.getSpan(e,t)},enabled:!!e&&!!t,staleTime:r=>r.state.data?.span?.endedAt?pus:0})}const dAe=(e,t)=>{if(!e||e.length===0)return[];const n=e.reduce((u,d)=>{const f=d?.endedAt?new Date(d.endedAt):void 0;return f&&(!u||f>u)?f:u},null),r=new Map,s=[];e.forEach(u=>{const d=new Date(u.startedAt),f=u.endedAt?new Date(u.endedAt):void 0,p={id:u.spanId,name:u.name,type:u.spanType,latency:f?f.getTime()-d.getTime():0,startTime:d.toISOString(),endTime:f?f.toISOString():void 0,spans:[],parentSpanId:u.parentSpanId,matchedInPayloadOnly:u.matchedInPayloadOnly};r.set(u.spanId,p)});const a=u=>t?u.spanId===t:u?.parentSpanId==null;e.forEach(u=>{const d=r.get(u.spanId);if(d)if(a(u)){if(n&&d.endTime&&n>new Date(d.endTime)){d.endTime=n.toISOString();const f=new Date(n).getTime(),p=new Date(d.startTime).getTime();d.latency=f-p}s.push(d)}else{const f=u.parentSpanId?r.get(u.parentSpanId):void 0;f?(f.spans??=[],f.spans.push(d)):s.push(d)}});const i=u=>u.sort((d,f)=>new Date(d.startTime).getTime()-new Date(f.startTime).getTime()),l=i(s),c=u=>{u.forEach(d=>{d.spans&&d.spans.length>0&&(d.spans=i(d.spans),c(d.spans))})};return c(l),l};function oV(e){if(!e.spans||e.spans.length===0)return[];const t=[];return e.spans.forEach(n=>{t.push(n.id),t.push(...oV(n))}),t}function fAe(e){const t=[];for(const n of e)t.push(n.id),t.push(...oV(n));return t}function eqt(e,t,n){const r=g.useMemo(()=>fAe(dAe(e??[])),[e]),s=t?r.indexOf(t):-1,a=s>0?()=>{const l=r[s-1];l!==void 0&&n(l)}:void 0,i=s>=0&&s<r.length-1?()=>{const l=r[s+1];l!==void 0&&n(l)}:void 0;return{handlePreviousSpan:a,handleNextSpan:i,timelineSpanIds:r}}function hus(){const e=Qe(),[t,n]=g.useState(!1);return{download:s=>{if(t)return;n(!0);const a=e.getTrace(s).then(i=>QUr(`trace-${s}.json`,i)).finally(()=>n(!1));Be.promise({myPromise:a,loadingMessage:"Preparing trace download…",successMessage:"Trace downloaded",errorMessage:"Failed to download trace"})},isPending:t}}function mus(e,t){if(!e||e.length===0)return[];const n=new Map,r=new Map,s=[];for(const l of e)if(l){if(n.set(l.spanId,l),l.parentSpanId){const c=r.get(l.parentSpanId);c?c.push(l):r.set(l.parentSpanId,[l])}t(l)&&s.push(l)}if(s.length===0)return[];const a=new Set,i=[...s];for(;i.length>0;){const l=i.pop();if(!l||a.has(l.spanId))continue;a.add(l.spanId);const c=r.get(l.spanId);c&&i.push(...c)}for(const l of s){let c=l.parentSpanId;for(;c&&!a.has(c);){const u=n.get(c);if(!u)break;a.add(u.spanId),c=u.parentSpanId}}return e.filter(l=>l&&a.has(l.spanId))}function gus(e){const[t,n]=g.useState(""),r=g.useDeferredValue(t),{results:s,payloadOnlyMatchIds:a}=g.useMemo(()=>{const i=r.trim().toLowerCase();if(!i)return{results:e,payloadOnlyMatchIds:new Set};const l=new Set;return{results:mus(e,u=>u.searchText.includes(i)?(u.name.toLowerCase().includes(i)||l.add(u.spanId),!0):!1),payloadOnlyMatchIds:l}},[e,r]);return{query:t,setQuery:n,results:s,payloadOnlyMatchIds:a,isPending:t!==r}}function vus(e){return e.split("_").map(t=>`${t.charAt(0).toUpperCase()}${t.slice(1)}`).join(" ")}function xP({label:e,children:t}){return o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:o.jsx("span",{tabIndex:0,className:"flex shrink-0 cursor-help items-center gap-1 whitespace-nowrap","aria-label":e,children:t})}),o.jsx(vn,{children:e})]})}function yus({rootSpan:e,usage:t,entityHref:n,LinkComponent:r,className:s}){const a=e.startedAt?new Date(e.startedAt):null,i=e.endedAt?new Date(e.endedAt):null,l=OQ(a,i),c=Lcs(a,i),u=Fcs(a),d=zcs(a),f=e.entityName||e.entityId,p=e.entityType,h=p?vus(p):"Entity",m=p?.includes("workflow")?Uc:Ti,v=r??"a";return o.jsxs("div",{className:K("flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-ui-xs leading-ui-xs text-neutral3",s),children:[f&&o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:n?o.jsxs(v,{href:n,className:"text-neutral4 hover:text-neutral5 flex shrink-0 items-center gap-1 whitespace-nowrap hover:underline",children:[o.jsx(m,{className:"size-3.5 shrink-0","aria-hidden":"true"}),o.jsx("span",{children:f}),o.jsx(Yr,{className:"size-3 shrink-0","aria-hidden":"true"})]}):o.jsxs("span",{tabIndex:0,className:"flex shrink-0 cursor-help items-center gap-1 whitespace-nowrap",children:[o.jsx(m,{className:"size-3.5 shrink-0","aria-hidden":"true"}),o.jsx("span",{children:f})]})}),o.jsx(vn,{children:h})]}),u&&d&&o.jsxs(xP,{label:`Started at ${d}`,children:[o.jsx(KN,{className:"size-3.5 shrink-0","aria-hidden":"true"}),o.jsx("span",{children:u})]}),l&&c&&o.jsxs(xP,{label:`Duration ${c}`,children:[o.jsx(Ipe,{className:"size-3.5 shrink-0","aria-hidden":"true"}),o.jsx("span",{children:l})]}),t&&o.jsxs(o.Fragment,{children:[o.jsxs(xP,{label:"Input tokens",children:[o.jsx(RGt,{className:"size-3.5 shrink-0","aria-hidden":"true"}),o.jsx("span",{children:t.inputTokens===void 0?"—":nl(t.inputTokens)})]}),o.jsxs(xP,{label:"Output tokens",children:[o.jsx(FGt,{className:"size-3.5 shrink-0","aria-hidden":"true"}),o.jsx("span",{children:t.outputTokens===void 0?"—":nl(t.outputTokens)})]}),o.jsxs(xP,{label:"Estimated cost",children:[o.jsx(AQt,{className:"size-3.5 shrink-0","aria-hidden":"true"}),o.jsx("span",{children:t.estimatedCost===void 0?"—":Vp(t.estimatedCost,t.costUnit)})]})]})]})}const tqt=e=>o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:o.jsx("path",{d:"M1.5 8.5V8C1.5 7.60218 1.65804 7.22064 1.93934 6.93934C2.22064 6.65804 2.60218 6.5 3 6.5H13C13.3978 6.5 13.7794 6.65804 14.0607 6.93934C14.342 7.22064 14.5 7.60218 14.5 8V8.5M8.70667 4.20667L7.29333 2.79333C7.20048 2.70037 7.09022 2.62661 6.96886 2.57628C6.84749 2.52595 6.71739 2.50003 6.586 2.5H3C2.60218 2.5 2.22064 2.65804 1.93934 2.93934C1.65804 3.22064 1.5 3.60218 1.5 4V12C1.5 12.3978 1.65804 12.7794 1.93934 13.0607C2.22064 13.342 2.60218 13.5 3 13.5H13C13.3978 13.5 13.7794 13.342 14.0607 13.0607C14.342 12.7794 14.5 12.3978 14.5 12V6C14.5 5.60218 14.342 5.22064 14.0607 4.93934C13.7794 4.65804 13.3978 4.5 13 4.5H9.414C9.14887 4.49977 8.89402 4.39426 8.70667 4.20667Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})}),fet=["agent","workflow","model","mcp","tool","provider","memory","workspace","skill","scorer","other"],bus={agent:{icon:o.jsx(Ti,{}),color:"oklch(0.75 0.15 250)",label:"Agent",typePrefix:"agent"},workflow:{icon:o.jsx(Uc,{}),color:"oklch(0.75 0.15 200)",label:"Workflow",typePrefix:"workflow"},model:{icon:o.jsx(kg,{}),color:"oklch(0.75 0.15 320)",label:"Model",typePrefix:"model"},mcp:{icon:o.jsx(OC,{}),color:"oklch(0.75 0.15 160)",label:"MCP",typePrefix:"mcp"},tool:{icon:o.jsx(Ff,{}),color:"oklch(0.75 0.15 100)",label:"Tool",typePrefix:"tool"},provider:{icon:o.jsx(Ff,{}),color:"oklch(0.75 0.15 60)",label:"Provider Tool",typePrefix:"provider"},memory:{icon:o.jsx(RL,{}),color:"oklch(0.75 0.12 50)",label:"Memory",typePrefix:"memory"},workspace:{icon:o.jsx(tqt,{}),color:"oklch(0.75 0.15 40)",label:"Workspace",typePrefix:"workspace"},skill:{icon:o.jsx(fC,{}),color:"oklch(0.75 0.15 130)",label:"Skill",typePrefix:"skill"},scorer:{icon:o.jsx(Wp,{}),color:"oklch(0.75 0.15 280)",label:"Scorer",typePrefix:"scorer"}},xus={color:"oklch(0.65 0 0)",label:"Other",typePrefix:"other"};function nqt(e){const t=e?.toLowerCase().split("_")[0]??"";return bus[t]??xus}function wus({isSelected:e,isFaded:t,isExpanded:n,isRootSpan:r,toggleChildren:s,expandAllDescendants:a,collapseAllDescendants:i,collapseAll:l,totalDescendants:c=0,allDescendantsExpanded:u,numOfChildren:d=0,toggleSiblings:f,siblingsAllExpanded:p,siblingsWithChildrenCount:h=0}){const m=n?`Collapse children (${d})`:`Expand children (${d})`,v=!r&&!!d&&d>0,y=!r&&v&&c>d,b=!r&&h>=2,x=!!r&&!!d&&d>0,S=!!n&&!!u;return o.jsx("div",{className:K("flex h-full items-center justify-end px-1.5",{"opacity-30 [&:hover]:opacity-60":t,"bg-surface4":e}),children:o.jsxs("div",{className:"grid grid-cols-[1.625rem_1.625rem_1.625rem] gap-1",children:[o.jsx("div",{children:v&&o.jsx(Vz,{onClick:()=>s?.(),tooltip:m,children:n?o.jsx(O_,{}):o.jsx(Xs,{})})}),o.jsx("div",{children:y&&o.jsx(Vz,{onClick:()=>u?i?.():a?.(),tooltip:u?`Collapse all descendants (${c})`:`Expand all descendants (${c})`,children:u?o.jsx(EQt,{}):o.jsx(wQt,{})})}),o.jsxs("div",{children:[b&&o.jsx(Vz,{onClick:()=>f?.(),tooltip:p?"Collapse at this level":"Expand at this level",children:p?o.jsx(HYt,{}):o.jsx(nen,{})}),x&&o.jsx(Vz,{onClick:()=>S?l?.():a?.(),tooltip:S?"Collapse all":"Expand all",children:S?o.jsx(hV,{}):o.jsx(XN,{})})]})]})})}function Vz({onClick:e,children:t,className:n,tooltip:r}){return o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:o.jsx("button",{onClick:e,className:K("h-full shrink-0 cursor-pointer",n),"aria-label":r,children:o.jsx("div",{className:K("flex items-center gap-[0.1rem] rounded-md p-1 transition-all","hover:bg-surface5","[&:hover>svg]:opacity-100 [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:opacity-50 [&>svg]:transition-all"),children:t})})}),r&&o.jsx(vn,{children:r})]})}function Sus({isLastChild:e}){return o.jsx("div",{className:K("relative h-[1.8rem] w-2 shrink-0 opacity-100",'after:absolute after:inset-y-0 after:-left-px after:w-0 after:border-l-[1px] after:border-dashed after:border-neutral3 after:content-[""] ','before:absolute before:top-[50%] before:left-0 before:h-0 before:w-full before:border-b-[1px] before:border-dashed before:border-neutral3 before:content-[""]',{"after:bottom-[50%]":e})})}const kus=e=>{e?.scrollIntoView({block:"nearest"})};function Ous({span:e,spanUI:t,isFaded:n,depth:r=0,onSpanClick:s,selectedSpanId:a,isLastChild:i,hasChildren:l,isRootSpan:c,isExpanded:u}){const d=a===e.id;return o.jsxs("div",{ref:d?kus:void 0,"aria-label":`View details for span ${e.name}`,className:K("flex min-h-8 items-center rounded-md rounded-l-lg opacity-80",{"opacity-30 [&:hover]:opacity-60":n,"bg-surface4":d}),style:{paddingLeft:`${r*1}rem`},children:[!c&&o.jsx(Sus,{isLastChild:i}),o.jsxs("button",{onClick:()=>s?.(e.id),className:K("flex size-full min-w-0 items-center gap-1.5 rounded-md px-2 py-1 text-left text-ui-smd text-neutral6 transition-colors","[&>svg]:ml-auto [&>svg]:size-[1em] [&>svg]:shrink-0 [&>svg]:opacity-0 [&>svg]:transition-all","hover:bg-surface4 [&:hover>svg]:opacity-60","focus:outline-none focus-visible:ring-1 focus-visible:ring-accent1 focus-visible:ring-inset"),children:[t?.color&&o.jsx("span",{"aria-hidden":!0,title:t.label,className:"inline-block size-2 shrink-0 rounded-full",style:{backgroundColor:t.color}}),o.jsx("span",{"data-highlight":e.matchedInPayloadOnly?void 0:"","data-highlight-indirect":e.matchedInPayloadOnly?"":void 0,title:e.matchedInPayloadOnly?"Matches your search in this span’s details":void 0,className:"min-w-0 truncate",children:e.name})]})]})}function _us({span:e,selectedSpanId:t,isFaded:n,overallLatency:r,overallStartTime:s,color:a,chartWidth:i="default"}){const l=r?Math.ceil(e.latency/r*100):0,c=s?new Date(s):null,u=e.startTime?new Date(e.startTime):null,d=u&&c?u.getTime()-c.getTime():0,f=r&&Math.floor(d/r*100);return o.jsxs(XI,{children:[o.jsxs(pC,{className:K("grid h-8 cursor-help grid-cols-[1fr_auto] items-center gap-2 rounded-r-md p-1 pr-2",i==="wide"?"min-w-72":"min-w-32","[&:hover>div]:bg-surface5",{"opacity-30 [&:hover]:opacity-60":n,"bg-surface4":t===e.id}),children:[o.jsx("div",{className:K("w-full rounded-md bg-surface4 p-1.5 transition-colors duration-1000"),children:o.jsx("div",{className:"relative h-1.5 w-full overflow-hidden rounded-sm",children:o.jsx("div",{className:K("absolute top-0 h-1.5 rounded-sm bg-neutral1"),style:{width:l?`${l}%`:"2px",left:`${f||0}%`,backgroundColor:a}})})}),o.jsxs("div",{className:K("flex justify-end text-ui-xs text-neutral3"),children:[(e.latency/1e3).toFixed(3)," s"]})]}),o.jsxs(hC,{className:"bg-surface4 pr-6",children:[o.jsx("div",{className:K("mt-1 mb-2 flex items-center gap-2 text-ui-sm"),children:"Span Timing"}),o.jsxs(_n,{children:[o.jsx(_n.Key,{children:"Latency"}),o.jsxs(_n.Value,{children:[e.latency," ms"]}),o.jsx(_n.Key,{children:"Started at"}),o.jsx(_n.Value,{children:e.startTime?hr(new Date(e.startTime),"hh:mm:ss:SSS a"):"-"}),o.jsx(_n.Key,{children:"Ended at"}),o.jsx(_n.Value,{children:e.endTime?hr(new Date(e.endTime),"hh:mm:ss:SSS a"):"-"}),o.jsx(_n.Key,{children:"Start Shift"}),o.jsxs(_n.Value,{children:[d,"ms"]})]})]})]})}function rqt({span:e,siblings:t,depth:n=0,onSpanClick:r,selectedSpanId:s,isLastChild:a,overallLatency:i,overallStartTime:l,fadedTypes:c,searchPhrase:u,featuredSpanIds:d,expandedSpanIds:f,setExpandedSpanIds:p,chartWidth:h}){const m=e.spans&&e.spans.length>0,v=e.spans?e.spans.length:0,y=oV(e),b=y.length,x=n===0,S=nqt(e?.type),k=f?f.includes(e.id):!1,_=d&&d.length>0?!d.includes(e.id):!1,T=(c&&c.length>0?c.includes(S?.typePrefix||""):!1)||_;g.useEffect(()=>{if(!d||y.length===0||k)return;y.some(z=>d.includes(z))&&p&&p(z=>!z||z.includes(e.id)?z??[e.id]:[...z,e.id])},[d,y]);const E=()=>{p&&p(B=>B&&(k?B.filter(z=>z!==e.id):[...B,e.id]))},N=()=>{p&&p(B=>B&&Array.from(new Set([...B,e.id,...y])))},I=()=>{p&&p(B=>{if(!B)return B;const z=new Set(y);return B.filter(V=>!z.has(V))})},A=()=>{p&&p(B=>{if(!B)return B;const z=new Set([e.id,...y]);return B.filter(V=>!z.has(V))})},R=y.every(B=>f?.includes(B)),L=(t??[]).filter(B=>B.spans&&B.spans.length>0),D=L.length,F=D>0&&L.every(B=>f?.includes(B.id)),H=()=>{!p||D===0||p(B=>{if(!B)return B;if(F){const z=new Set;return L.forEach(V=>{z.add(V.id),oV(V).forEach(M=>z.add(M))}),B.filter(V=>!z.has(V))}return Array.from(new Set([...B,...L.map(z=>z.id)]))})};return o.jsxs(o.Fragment,{children:[o.jsx(Ous,{span:e,spanUI:S,isFaded:T,depth:n,onSpanClick:r,selectedSpanId:s,isLastChild:a,hasChildren:m,isRootSpan:x,isExpanded:k}),o.jsx(wus,{isSelected:s===e.id,isFaded:T,isExpanded:k,isRootSpan:x,toggleChildren:E,expandAllDescendants:N,collapseAllDescendants:I,collapseAll:A,totalDescendants:b,allDescendantsExpanded:R,numOfChildren:v,toggleSiblings:H,siblingsAllExpanded:F,siblingsWithChildrenCount:D}),o.jsx(_us,{span:e,selectedSpanId:s,isFaded:T,overallLatency:i,overallStartTime:l,color:S?.color,chartWidth:h}),m&&k&&e.spans?.map((B,z,V)=>{const M=z===V.length-1;return o.jsx(rqt,{span:B,siblings:V,depth:n+1,onSpanClick:r,selectedSpanId:s,isLastChild:M,overallLatency:i,overallStartTime:l,fadedTypes:c,searchPhrase:u,expandedSpanIds:f,setExpandedSpanIds:p,featuredSpanIds:d,chartWidth:h},B.id)})]})}function sqt({hierarchicalSpans:e=[],onSpanClick:t,selectedSpanId:n,isLoading:r,fadedTypes:s,expandedSpanIds:a,setExpandedSpanIds:i,featuredSpanIds:l,chartWidth:c="default",leadingSlot:u}){const d=e?.[0]?.latency||0,f=e?.[0]?.startTime||"",p=g.useMemo(()=>{const h=b=>{const x=new Set;for(const S of b){const k=S.type?.toLowerCase().split("_")[0];if(k&&x.add(k),S.spans)for(const _ of h(S.spans))x.add(_)}return x},m=h(e),v=[...m].some(b=>!fet.includes(b)),y=fet.filter(b=>b!=="other"&&m.has(b));return v&&y.push("other"),y},[e]);return o.jsx(o.Fragment,{children:r?o.jsxs("div",{className:K("flex items-center justify-center gap-3 rounded-md bg-surface3/50 p-3 text-ui-sm text-neutral3","[&_svg]:size-[1.25em] [&_svg]:opacity-50"),children:[o.jsx(Ut,{})," Loading Trace Timeline ..."]}):o.jsxs(o.Fragment,{children:[(p.length>0||u)&&o.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-3 px-2 py-1.5",children:[u&&o.jsx("div",{className:"min-w-0 flex-1",children:u}),p.map(h=>{const m=nqt(h);return o.jsxs("div",{className:"text-ui-sm text-neutral3 flex shrink-0 items-center gap-1",children:[o.jsx("span",{className:"inline-block size-1.5 shrink-0 rounded-full",style:{backgroundColor:m?.color}}),m?.label||h]},h)})]}),o.jsx("div",{className:"grid grid-cols-[minmax(0,1fr)_auto_auto] content-start items-start gap-y-px overflow-hidden py-1",children:e?.map(h=>o.jsx(rqt,{span:h,siblings:e,onSpanClick:t,selectedSpanId:n,overallLatency:d,overallStartTime:f,fadedTypes:s,featuredSpanIds:l,expandedSpanIds:a,setExpandedSpanIds:i,chartWidth:c},h.id))})]})})}const gie="search-result",vie="search-result-indirect",aqt=2,iqt="[data-highlight]",lV="[data-highlight-indirect]";function oqt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Cus(e,t){const n=new RegExp(oqt(t),"iu"),r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(s){return s.parentElement.closest(`${iqt}, ${lV}`)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}});for(;r.nextNode();){const s=r.currentNode;if(s.parentElement.closest(lV)){if(s.data.length>0)return s;continue}if(n.test(s.data))return s}return null}function Eus(e){const[t,n]=g.useState(null);return uG(()=>{if(!t||e.trim().length<aqt||typeof CSS>"u"||!("highlights"in CSS)||typeof StaticRange>"u"){CSS?.highlights?.delete(gie),CSS?.highlights?.delete(vie);return}let r=null;const s=()=>{const l=[],c=[],u=new RegExp(oqt(e),"giu"),d=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(f){return f.parentElement.closest(`${iqt}, ${lV}`)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}});for(;d.nextNode();){const f=d.currentNode;if(f.parentElement.closest(lV)){f.data.length>0&&c.push(new StaticRange({startContainer:f,startOffset:0,endContainer:f,endOffset:f.data.length}));continue}u.lastIndex=0;let h;for(;(h=u.exec(f.data))!==null;)l.push(new StaticRange({startContainer:f,startOffset:h.index,endContainer:f,endOffset:h.index+h[0].length}))}CSS.highlights.set(gie,new Highlight(...l)),CSS.highlights.set(vie,new Highlight(...c))},a=()=>{r!==null&&cancelAnimationFrame(r),r=requestAnimationFrame(()=>{r=null,s()})};s();const i=new MutationObserver(a);return i.observe(t,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:["data-highlight","data-highlight-indirect"]}),()=>{i.disconnect(),r!==null&&cancelAnimationFrame(r),CSS.highlights.delete(gie),CSS.highlights.delete(vie)}},[t,e]),{ref:n}}function Tus(e,t){const[n,r]=g.useState(null);return g.useEffect(()=>{if(!n||e.trim().length<aqt)return;let s=null,a=null,i="";const l=()=>{const d=Cus(n,e);if(!d)return;a=d,i=d.data;const f=d.parentElement;f&&typeof f.scrollIntoView=="function"&&f.scrollIntoView({block:"center"})},c=()=>a!==null&&a.isConnected&&a.data===i;l();const u=new MutationObserver(()=>{s===null&&(s=requestAnimationFrame(()=>{s=null,c()||l()}))});return u.observe(n,{subtree:!0,childList:!0,characterData:!0}),()=>{u.disconnect(),s!==null&&cancelAnimationFrame(s)}},[n,e,t]),{ref:r}}function lqt({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,onEvaluateTrace:a,onSaveAsDatasetItem:i,onAddTraceMocksToItem:l,initialSpanId:c,onPrevious:u,onNext:d,collapsed:f,onCollapsedChange:p,placement:h,timelineChartWidth:m="default",LinkComponent:v,traceHref:y,entityHref:b,usage:x,anchorSpanId:S,showUnavailableFeaturesMsg:k=!0,scoresTabSlot:_,scoresTabBadge:C,feedbackTabSlot:T,feedbackTabBadge:E,activeTab:N,onTabChange:I,spanPanelSlot:A,className:R}){const L=h==="trace-page",[D,F]=g.useState(!1),H=f??D,B=p??F,{download:z,isPending:V}=hus(),[M,G]=g.useState(c??void 0);g.useEffect(()=>{if(!c){G(void 0),s?.(void 0);return}if(n||!t)return;t.find(se=>se.spanId===c)?(G(c),s?.(c)):(G(void 0),s?.(void 0))},[c,t,n]);const U=g.useId(),{query:$,setQuery:q,results:Z,payloadOnlyMatchIds:Y}=gus(t??[]),ne=g.useMemo(()=>dAe(Z.map(te=>({...te,matchedInPayloadOnly:Y.has(te.spanId)})),S),[Z,Y,S]),[J,ee]=g.useState([]);g.useEffect(()=>{ne.length>0&&ee(fAe(ne))},[ne]);const re=g.useMemo(()=>S?t?.find(te=>te.spanId===S):t?.find(te=>te.parentSpanId==null),[t,S]),le=te=>{const se=M===te?void 0:te;G(se),s?.(se)},X=o.jsxs(rt,{children:[o.jsx(rt.Trigger,{render:o.jsx(oe,{size:"md",tooltip:"Trace actions","aria-label":"Trace actions",children:o.jsx(vYt,{})})}),o.jsxs(rt.Content,{align:"end",children:[!L&&p&&o.jsxs(rt.Item,{onSelect:()=>B(!H),children:[H?o.jsx(XN,{}):o.jsx(hV,{}),H?"Expand panel":"Collapse panel"]}),!L&&a&&o.jsxs(rt.Item,{onSelect:a,children:[o.jsx(Rlt,{}),"Evaluate trace"]}),!L&&i&&o.jsxs(rt.Item,{onSelect:()=>i({traceId:e,rootSpanId:re?.spanId}),children:[o.jsx(Gu,{}),"Add full trace to dataset"]}),!L&&l&&o.jsxs(rt.Item,{onSelect:()=>l({traceId:e}),children:[o.jsx(Ud,{}),"Add tool mocks to item"]}),!L&&v&&y&&o.jsxs(rt.Item,{render:o.jsx(v,{href:y}),children:[o.jsx(c0e,{}),"Open trace page"]}),o.jsxs(rt.Item,{disabled:V,onSelect:()=>z(e),children:[V?o.jsx(qs,{className:"animate-spin"}):o.jsx(Pd,{}),"Download trace JSON"]})]})]});return o.jsxs(fn,{collapsed:H,className:R,children:[o.jsx(fn.Header,{children:L?o.jsxs(o.Fragment,{children:[o.jsx(fn.Heading,{children:"Trace Timeline"}),o.jsx(hs,{className:"ml-auto shrink-0",children:X})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[o.jsxs(fn.Heading,{children:["Trace ",o.jsxs("b",{children:["# ",Xh(e,12)]})]}),!H&&re&&o.jsx(yus,{rootSpan:re,usage:x,entityHref:b,LinkComponent:v})]}),o.jsxs(hs,{className:"ml-auto shrink-0 self-start",children:[X,(u||d)&&o.jsx(fn.NextPrevNav,{onPrevious:u,onNext:d,previousLabel:"Previous trace",nextLabel:"Next trace"}),o.jsx(fn.CloseButton,{onClick:r})]})]})}),!H&&o.jsx(jus,{spanPanelSlot:A,highlightQuery:$,spanPanelKey:M,children:n?o.jsx(fn.LoadingData,{children:"Loading trace..."}):t?.length?o.jsx(fn.Content,{children:(()=>{const te=o.jsxs(o.Fragment,{children:[!L&&!a&&!i&&!l&&k&&o.jsx(Wn,{variant:"info",className:"mb-6",children:o.jsx(Wn.Message,{children:"Evaluating traces and saving them as dataset items is available in Mastra Studio (local or deployed)."})}),o.jsx(sqt,{hierarchicalSpans:ne,onSpanClick:le,selectedSpanId:M,expandedSpanIds:J,setExpandedSpanIds:ee,chartWidth:m,leadingSlot:o.jsx(m_,{name:U,label:"Search spans",labelIsHidden:!0,placeholder:"Search spans...",value:$,onChange:se=>q(se.target.value),onReset:()=>q(""),size:"sm",variant:"outline",className:"w-full"})}),ne.length===0&&o.jsx(fn.NoData,{children:"No spans match your search."})]});return!_&&!T?te:o.jsxs(yc,{defaultTab:"details",value:N,onValueChange:I,className:N==="scores"||N==="feedback"?"grid h-full min-h-0 grid-rows-[auto_1fr]":void 0,children:[o.jsxs(vc,{variant:"pill-ghost",className:"px-0",children:[o.jsx(Ar,{value:"details",children:"Spans"}),_&&o.jsxs(Ar,{value:"scores",children:["Evaluations ",C!=null&&o.jsxs(o.Fragment,{children:["(",C,")"]})]}),T&&o.jsxs(Ar,{value:"feedback",children:["Feedback ",E!=null&&o.jsxs(o.Fragment,{children:["(",E,")"]})]})]}),o.jsx(fs,{value:"details",children:te}),_&&o.jsx(fs,{value:"scores",className:"h-full min-h-0",children:_({traceId:e,rootSpanId:re?.spanId})}),T&&o.jsx(fs,{value:"feedback",className:"h-full min-h-0",children:T({traceId:e})})]})})()}):o.jsx(fn.NoData,{children:"No spans found for this trace."})})]})}function jus({spanPanelSlot:e,highlightQuery:t,spanPanelKey:n,children:r}){const{ref:s}=Eus(t),{ref:a}=Tus(t,n);return e?o.jsxs("div",{ref:s,className:"grid min-h-0 flex-1 grid-cols-[1fr_1fr]",children:[o.jsx("div",{className:"flex min-h-0 flex-col overflow-hidden",children:r}),o.jsx("div",{ref:a,"data-highlight":!0,className:"animate-in border-border1 fade-in-0 flex min-h-0 flex-col overflow-hidden border-l duration-300",children:e})]}):o.jsx("div",{ref:s,className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:r})}function Nus(e){const[t,n]=g.useState("details");return o.jsx(lqt,{...e,onEvaluateTrace:()=>n("scores"),activeTab:t,onTabChange:n})}function Ius(e,t){if(!t||!e)return;const n=e.toLowerCase();if(n.includes("workflow"))return`/workflows/${encodeURIComponent(t)}/graph`;if(n.includes("agent"))return`/agents/${encodeURIComponent(t)}/chat/new`}function cqt({traceId:e,spans:t,isLoadingSpans:n,selectedSpanId:r,onSpanSelect:s,onClose:a,onSpanClose:i,anchorSpanId:l,initialSpanId:c,onPrevious:u,onNext:d,onSaveAsDatasetItem:f,onAddTraceMocksToItem:p,feedbackTabBadge:h,feedbackTabSlot:m,scoresTabBadge:v,scoresTabSlot:y,usage:b,traceHref:x,className:S,spanActiveTab:k,onSpanTabChange:_,spanFeedbackTabBadge:C,spanFeedbackTabSlot:T,spanPanelClassName:E}){const{data:N,isLoading:I}=_Q(e,r??""),{handlePreviousSpan:A,handleNextSpan:R}=eqt(t,r,s),L=l?t?.find(F=>F.spanId===l):t?.find(F=>F.parentSpanId==null),D=Ius(L?.entityType,L?.entityId);return o.jsx(Nus,{className:S,traceId:e,spans:t,anchorSpanId:l,entityHref:D,usage:b,isLoading:n,onClose:a,onSpanSelect:s,onSaveAsDatasetItem:f,onAddTraceMocksToItem:p,initialSpanId:c??r,onPrevious:u,onNext:d,placement:"traces-list",LinkComponent:cy,traceHref:x,feedbackTabBadge:h,feedbackTabSlot:m,scoresTabBadge:v,scoresTabSlot:y,spanPanelSlot:r?o.jsx(JUt,{className:E,traceId:e,spanId:r,span:N?.span,isAnchor:l?r===l:void 0,isLoading:I,onClose:i??(()=>s(void 0)),onPrevious:A,onNext:R,activeTab:k,onTabChange:_,feedbackTabBadge:C,feedbackTabSlot:T}):null})}function Aus({threadId:e,onTraceOpenChange:t,onSpanOpenChange:n}){const r=g.useMemo(()=>({threadId:e}),[e]),{data:s,isLoading:a,isFetchingNextPage:i,hasNextPage:l,setEndOfListElement:c,error:u}=XUt({filters:r}),d=s?.spans??[],[f,p]=g.useState(null),[h,m]=g.useState(void 0),v=C=>{!!C!=!!h&&n?.(!!C),m(C)},y=C=>{p(C),t?.(!0)},b=()=>{v(void 0),p(null),t?.(!1)},{handlePreviousTrace:x,handleNextTrace:S}=QUt(d,f??void 0,null,C=>{v(void 0),p(C)}),{spans:k,isLoading:_}=KUt({traceId:f,anchorSpanId:null,listMode:"traces"});return u?o.jsx("div",{className:"flex h-full items-center justify-center p-4",children:o.jsx(BUt,{error:u,resource:"traces",errorTitle:"Failed to load traces"})}):f?o.jsx(cqt,{className:"h-full rounded-none border-0",spanPanelClassName:"rounded-none border-0",traceId:f,spans:k,isLoadingSpans:_,selectedSpanId:h??null,onClose:b,onSpanSelect:v,onPrevious:x,onNext:S,traceHref:`/traces?traceId=${encodeURIComponent(f)}`},f):a?o.jsx("div",{className:"flex flex-col gap-3 p-4","aria-hidden":"true",children:["80%","60%","90%","70%","65%"].map((C,T)=>o.jsx("div",{className:"bg-surface6 h-4 animate-pulse rounded-lg",style:{width:C}},T))}):o.jsx("div",{className:"h-full min-h-0 p-1.5",children:o.jsx(GUt,{traces:d,isLoading:a,isFetchingNextPage:i,hasNextPage:l,setEndOfListElement:c,onTraceClick:C=>y(C.traceId)})})}function Rus(){const{agentId:e,threadId:t}=mr(),[n]=hi(),{data:r,isLoading:s,error:a}=Vl(e),{data:i}=yC(e),l=es(),c=t==="new",u=g.useMemo(()=>vo(),[t]),d=!!i?.result,{data:f,isLoading:p,refetch:h}=k4t({agentId:e,isMemoryEnabled:d,resourceId:e}),m=g.useMemo(()=>(f||[]).map(k=>({...k,createdAt:new Date(k.createdAt),updatedAt:new Date(k.updatedAt)})),[f]),v=n.get("messageId")??void 0,y=ccs(r?.metadata),b=g.useMemo(()=>KIe(r),[r]);if(a&&Ss(a))return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Gs,{})});if(a&&ks(a))return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{resource:"agents"})});if(s)return o.jsx(zus,{});if(!r)return o.jsx("div",{className:"py-4 text-center",children:"Agent not found"});const x=c?u:t??u,S=async()=>{await h(),c&&l(`/agents/${e}/threads/${u}`)};return o.jsx(jH,{entityId:e,entityType:"agent",children:o.jsx(JTe,{agentId:e,defaultSettings:b,children:o.jsx(I3,{children:o.jsx($4t,{agentId:e,threadId:x,resourceId:e,children:o.jsx(qZ,{children:o.jsx(VZ,{agentId:e,threadId:x,enabled:!!(r?.hasBrowser??r?.browserTools?.length),children:o.jsx(qIe,{children:o.jsx(L4t,{children:o.jsx(eUr,{children:o.jsx(JZ,{children:o.jsx(rAe,{storageKey:"agent-thread",children:o.jsxs("div",{className:"bg-surface1 h-full lg:grid lg:grid-cols-[auto_1fr] lg:grid-rows-[1fr]",children:[o.jsx($us,{agentId:e,agentName:r.name,threads:m,threadId:x,isLoading:p}),o.jsxs("div",{className:"relative min-h-0",children:[o.jsx("div",{className:"rounded-studio-frame border-border1 bg-surface2 shadow-main-frame m-1.5 h-[calc(100%-0.75rem)] min-h-0 overflow-hidden border [--studio-frame-inset:0.5rem] [--studio-frame-radius:1.5rem] lg:m-2 lg:ml-0 lg:h-[calc(100%-1rem)]",children:o.jsx("div",{className:"relative grid h-full min-h-0 overflow-y-auto pt-6",children:o.jsx(eAe,{agentId:e,agentName:r?.name,modelVersion:r?.modelVersion,supportsMemory:r?.supportsMemory,threadId:x,memory:d,refreshThreadList:S,modelList:r?.modelList,messageId:v,suggestedPrompts:y,isNewThread:c},x)})}),!c&&o.jsx(Pus,{threadId:x},x)]})]})})},`${e}-${x}`)},`memory-timeline-${e}-${x}`)})})},`session-${e}-${x}`)},`browser-${e}-${x}`)})})})})}const Pus=({threadId:e})=>{const[t,n]=g.useState("closed"),[r,s]=g.useState(!1),[a,i]=g.useState(!1),l=()=>{n("closing"),s(!1),i(!1)};return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"absolute top-3 right-3 z-10 hidden lg:top-4 lg:right-4 lg:block",children:o.jsxs(oe,{variant:"outline",onClick:()=>t==="open"?l():n("open"),children:[o.jsx(Ilt,{}),"Traces"]})}),t!=="closed"&&o.jsx("div",{onAnimationEnd:c=>{c.target===c.currentTarget&&t==="closing"&&n("closed")},className:`absolute top-3 right-3 bottom-3 z-20 hidden transition-[width] duration-300 ease-out lg:top-4 lg:right-4 lg:bottom-4 lg:block ${t==="closing"?"animate-out fade-out-0 slide-out-to-right-full fill-mode-forwards":"animate-in fade-in-0 slide-in-from-right-full"} ${a?"w-[70%]":"w-[40%]"}`,children:o.jsx(ucs,{title:r?void 0:"Traces",onClose:l,children:o.jsx(Aus,{threadId:e,onTraceOpenChange:s,onSpanOpenChange:i})})})]})},$us=({agentId:e,agentName:t,threads:n,threadId:r,isLoading:s})=>{const{Link:a}=cn(),{state:i}=_C(),l=es(),{canDelete:c}=_o(),{mutateAsync:u}=OBr(),[d,f]=g.useState(null),p=c("memory"),h=async()=>{d&&(await u({threadId:d,agentId:e}),d===r&&l(`/agents/${e}/threads/new`),f(null))},m=o.jsx(ns.Nav,{children:o.jsxs(ns.NavSection,{children:[o.jsx(ns.NavHeader,{state:i,children:"Threads"}),s?o.jsx(Dus,{}):o.jsx(ns.NavList,{"data-testid":"thread-list",children:n.map(v=>o.jsx(ns.NavLink,{LinkComponent:a,state:i,isActive:v.id===r,link:{name:Fus(v),url:`/agents/${e}/threads/${v.id}`},className:"group/thread-row",action:p?o.jsx(oe,{variant:"ghost",size:"icon-sm",className:"shrink-0 opacity-0 transition-opacity group-focus-within/thread-row:opacity-100 group-hover/thread-row:opacity-100",onClick:()=>f(v.id),"aria-label":"Delete thread",children:o.jsx(or,{})}):void 0},v.id))})]})});return o.jsxs(o.Fragment,{children:[o.jsx(Mus,{open:!!d,onOpenChange:()=>f(null),onDelete:()=>{h()}}),o.jsxs(ns,{children:[o.jsx("div",{className:"mb-1.5 pt-2.5",children:o.jsxs("span",{className:"flex h-7 items-center gap-2 pr-2 pl-3",children:[o.jsx(qp,{className:"h-[1.5rem] w-[1.5rem] shrink-0"}),o.jsx("span",{className:"font-display truncate text-sm font-semibold tracking-tight whitespace-nowrap",children:"Mastra Studio"})]})}),o.jsx("div",{className:"mb-1",children:o.jsxs(ns.NavList,{children:[o.jsx(ns.NavLink,{state:i,asChild:!0,children:o.jsxs(a,{href:`/agents/${e}/overview`,"data-testid":"thread-sidebar-back",children:[o.jsx(gl,{}),o.jsxs(ns.NavLabel,{state:i,children:["Back to ",t??"agent"]})]})}),o.jsx(ns.NavLink,{state:i,asChild:!0,children:o.jsxs(a,{href:`/agents/${e}/threads/new`,"data-testid":"thread-sidebar-new-chat",children:[o.jsx(Or,{}),o.jsx(ns.NavLabel,{state:i,children:"New Chat"})]})})]})}),i==="collapsed"?m:o.jsx("div",{className:"min-h-0 flex-1",children:o.jsx(ocs,{agentId:e,threadId:r,threadsSlot:m})})]})]})},Mus=({open:e,onOpenChange:t,onDelete:n})=>o.jsx(Pt,{open:e,onOpenChange:t,children:o.jsxs(Pt.Content,{children:[o.jsxs(Pt.Header,{children:[o.jsx(Pt.Title,{children:"Are you absolutely sure?"}),o.jsx(Pt.Description,{children:"This action cannot be undone. This will permanently delete your chat and remove it from our servers."})]}),o.jsxs(Pt.Footer,{children:[o.jsx(Pt.Cancel,{children:"Cancel"}),o.jsx(Pt.Action,{onClick:n,children:"Continue"})]})]})}),Dus=()=>o.jsx("div",{className:"flex flex-col gap-px","data-testid":"thread-list-skeleton","aria-busy":"true",children:["w-32","w-24","w-36","w-28"].map(e=>o.jsx("div",{className:"flex h-9 items-center px-3",children:o.jsx(jt,{className:`h-3 ${e}`})},e))}),Lus=/^New Thread \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;function Fus(e){return e.title&&!Lus.test(e.title)?e.title:new Date(e.createdAt).toLocaleString("en-us",{month:"short",day:"numeric",hour:"numeric",minute:"numeric",hour12:!0}).replace(","," at")}const zus=()=>o.jsx(_s,{className:"grid-rows-[1fr]",children:o.jsx("div",{className:"relative grid h-full overflow-y-auto pt-6","data-testid":"agent-thread-skeleton","aria-busy":"true",children:o.jsx($3t,{})})}),pAe=()=>{const{data:e}=H4();return e?.editorSource==="code"?"code":"db"};function Bus(){const{agentId:e}=mr(),{navigate:t}=cn(),{data:n,isLoading:r,error:s}=Vl(e),{data:a}=vS({agentId:e,params:{orderBy:{direction:"DESC"}}}),i=(a?.versions?.length??0)>0,{data:l,isLoading:c}=A4(e,{status:"draft",enabled:i}),u=pAe(),d=n?.source==="code",f=d&&u==="code",p=r||i&&c,h=g.useMemo(()=>l||(n?YIe(n):{}),[l,n]),{form:m,handlePublish:v,handleSaveDraft:y,isSubmitting:b,isSavingDraft:x}=wQ({mode:"edit",agentId:e??"",dataSource:h,isCodeAgentOverride:d,hasStoredOverride:d&&!!l,editorConfig:n?.editor,onSuccess:()=>{}}),[S,k]=g.useState(()=>{const _=sessionStorage.getItem(`pending-scorer-items-${e}`);if(_){sessionStorage.removeItem(`pending-scorer-items-${e}`);try{return JSON.parse(_)}catch{return null}}return null});return s&&Ss(s)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Gs,{})}):s&&ks(s)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{resource:"agents"})}):p?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ut,{className:"h-6 w-6"})}):n?o.jsx(aje,{form:m,mode:"edit",agentId:e,isSubmitting:b,isSavingDraft:x,handlePublish:v,handleSaveDraft:y,isCodeAgentOverride:d,isCodeSourceAgent:f,readOnly:!1,children:o.jsx(qis,{agentId:e,onSwitchToReview:()=>t(`/agents/${e}/review`),pendingScorerItems:S,onPendingScorerItemsConsumed:()=>k(null)})}):o.jsx("div",{className:"py-4 text-center",children:"Agent not found"})}const CQ=()=>{const e=window.MASTRA_CLOUD_API_ENDPOINT,t=window.MASTRA_PLATFORM_PROJECT_ID,n=window.MASTRA_ORGANIZATION_ID,r=window.MASTRA_PLATFORM_OBSERVABILITY_ENDPOINT;return{isMastraPlatform:!!e,mastraPlatformEndpoint:e,mastraPlatformApiEndpoint:e,mastraPlatformProjectId:t,mastraOrganizationId:n,platformObservabilityEndpoint:r}};function Uus(){const{agentId:e}=mr(),[t,n]=g.useState(null),{data:r,isLoading:s,error:a}=Vl(e),{data:i}=yC(e),l=pAe(),{isMastraPlatform:c,mastraPlatformApiEndpoint:u,mastraPlatformProjectId:d}=CQ(),{data:f,isLoading:p}=vS({agentId:e,params:{orderBy:{direction:"DESC"}}}),h=(f?.versions?.length??0)>0,{data:m,isLoading:v}=A4(e,{status:"draft",enabled:h}),y=r?.source==="code",b=y&&l==="code",x=!kC(y,r?.editor).isFullyLocked,S=b&&x,k=S&&c&&!!u&&!!d,_=k?"Open a pull request for these JSON changes":void 0,C=s||p||h&&v,T=!!i?.result,{data:E}=aBt({agentId:e??"",versionId:t??""}),N=m?.activeVersionId,I=f?.versions?.[0],A=!!(I&&I.id!==N),R=!!t&&!!E,L=R&&t!==I?.id,D=g.useMemo(()=>R&&E?E:m||(r?YIe(r):{}),[R,E,m,r]),{form:F,handlePublish:H,handleSaveDraft:B,handleDownloadJson:z,handleOpenPr:V,isSubmitting:M,isSavingDraft:G,isDirty:U}=wQ({mode:"edit",agentId:e??"",dataSource:D,isCodeAgentOverride:y,hasStoredOverride:y&&!!m,editorConfig:r?.editor,saveSuccessMessage:b?"Saved to filesystem":void 0,onSuccess:()=>{}}),$=g.useCallback(async()=>{L&&t?await H(t):await H()},[H,L,t]),q=g.useCallback(async()=>{!u||!d||await V({platformApiEndpoint:u,projectId:d})},[V,u,d]),Z=g.useCallback(Y=>{Y===I?.id?n(null):n(Y)},[I?.id]);return a&&Ss(a)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Gs,{})}):a&&ks(a)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{resource:"agents"})}):C?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ut,{className:"h-6 w-6"})}):r?o.jsx(aje,{form:F,mode:"edit",agentId:e,isSubmitting:M,isSavingDraft:G,handlePublish:H,handleSaveDraft:B,isCodeAgentOverride:y,isCodeSourceAgent:b,readOnly:L||!x,editorConfig:r?.editor,children:o.jsx(vis,{agentId:e,agentName:r?.name,modelVersion:r?.modelVersion,agentVersionId:t??I?.id,hasMemory:T,activeVersionId:N,selectedVersionId:t??void 0,latestVersionId:I?.id,onVersionSelect:Z,isDirty:U,isSavingDraft:G,isPublishing:M,hasDraft:A,readOnly:L||!x,isCodeSourceAgent:b,showCodeModeActions:S,canOpenPr:k,openPrTitle:_,onSaveDraft:B,onPublish:$,onDownloadJson:z,onOpenPr:q,isViewingPreviousVersion:L})}):o.jsx("div",{className:"py-4 text-center",children:"Agent not found"})}function qus(){const{agentId:e}=mr(),{navigate:t}=cn(),{data:n,isLoading:r,error:s}=Vl(e);if(s&&Ss(s))return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Gs,{})});if(s&&ks(s))return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{resource:"agents"})});if(r)return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ut,{className:"h-6 w-6"})});if(!n)return o.jsx("div",{className:"py-4 text-center",children:"Agent not found"});const a=i=>{sessionStorage.setItem(`pending-scorer-items-${e}`,JSON.stringify(i)),t(`/agents/${e}/evaluate`)};return o.jsx(Qis,{agentId:e,onCreateScorer:a})}let Ku=(function(e){return e.AGENT="agent",e.SCORER="scorer",e.RAG_INGESTION="rag_ingestion",e.TRAJECTORY="trajectory",e.INPUT_PROCESSOR="input_processor",e.INPUT_STEP_PROCESSOR="input_step_processor",e.OUTPUT_PROCESSOR="output_processor",e.OUTPUT_STEP_PROCESSOR="output_step_processor",e.TOOL_RESULT_PROCESSOR="tool_result_processor",e.WORKFLOW_STEP="workflow_step",e.TOOL="tool",e.WORKFLOW_RUN="workflow_run",e.MEMORY="memory",e})({});I_().describe("Database record creation time");const Vus=I_().describe("Database record last update time");Vus.nullable();const EQ=je({page:x2().int().min(0).optional().default(0).describe("Zero-indexed page number"),perPage:x2().int().min(1).max(100).optional().default(10).describe("Number of items per page")}).describe("Pagination options for list queries"),TQ=je({total:Nt().describe("Total number of items available"),page:Nt().describe("Current page"),perPage:Gn([Nt(),zt(!1)]).describe("Number of items per page, or false if pagination is disabled"),hasMore:Ds().describe("True if more pages are available")}),yS=he().min(1).describe("Opaque cursor value for incremental polling"),jQ=Js(["page","delta"]).describe("List mode: 'page' | 'delta', defaults to 'page' when omitted."),NQ=x2().int().min(1).max(100).optional().describe("Maximum number of updates to return in one delta poll"),Hus={page:0,perPage:10};function IQ(e,t){if(e.mode==="delta"){e.pagination!==void 0&&t.addIssue({code:"custom",path:["pagination"],message:"pagination is not allowed in delta mode"}),e.orderBy!==void 0&&t.addIssue({code:"custom",path:["orderBy"],message:"orderBy is not allowed in delta mode"});return}e.after!==void 0&&t.addIssue({code:"custom",path:["after"],message:"after is only allowed in delta mode"}),e.limit!==void 0&&t.addIssue({code:"custom",path:["limit"],message:"limit is only allowed in delta mode"})}function AQ(e,t){return{mode:e.mode==="delta"?"delta":"page",filters:e.filters,pagination:e.pagination??t.pagination??Hus,orderBy:e.orderBy??t.orderBy,after:e.after,limit:e.limit??t.limit??10}}const RQ=je({limit:Nt().describe("Maximum number of updates requested for this delta poll"),hasMore:Ds().describe("True when more matching updates remain after this response")}).describe("Incremental polling metadata"),Wus=je({start:uDe().optional().describe("Start of date range (inclusive by default)"),end:uDe().optional().describe("End of date range (inclusive by default)"),startExclusive:Ds().optional().describe("When true, excludes the start date from results (uses > instead of >=)"),endExclusive:Ds().optional().describe("When true, excludes the end date from results (uses < instead of <=)")}).describe("Date range filter for timestamps"),ML=Js(["ASC","DESC"]).describe("Sort direction: 'ASC' | 'DESC'"),Gy=Js(["sum","avg","min","max","count","count_distinct","last"]).describe("Aggregation function"),CC=Js(["1m","5m","15m","1h","1d"]).describe("Time bucket interval"),hAe=Js(["previous_period","previous_day","previous_week"]).describe("Comparison period for aggregate queries"),EC=$t(he()).min(1).describe("Fields to group by"),mAe=$t(Nt().min(0).max(1)).min(1).describe("Percentile values (0-1)"),gAe={value:Nt().nullable().describe("Aggregated value"),previousValue:Nt().nullable().optional().describe("Value from comparison period"),changePercent:Nt().nullable().optional().describe("Percentage change from comparison period")},vAe=Ws(he(),he().nullable()).describe("Dimension values for this group"),iA=Nt().describe("Aggregated value"),oA=I_().describe("Bucket timestamp"),yAe=Nt().describe("Percentile value"),bAe=Nt().describe("Percentile value at this bucket"),lA=ewe(Ku).describe("Entity type (e.g., 'agent' | 'processor' | 'tool' | 'workflow')"),Zus=he().describe('ID of the entity (e.g., "weatherAgent", "orderWorkflow")'),uqt=he().describe("Name of the entity"),dqt=he().describe("Human end-user who triggered execution"),fqt=he().describe("Multi-tenant organization/account"),pqt=he().describe("Broader resource context (Mastra memory compatibility)"),hqt=he().describe("Unique execution run identifier"),mqt=he().describe("Session identifier for grouping traces"),gqt=he().describe("Conversation thread identifier"),vqt=he().describe("HTTP request ID for log correlation"),yqt=he().describe('Environment (e.g., "production" | "staging" | "development")'),Gus=he().describe('Source of execution (e.g., "local" | "cloud" | "ci")'),bqt=he().describe('Source of execution (e.g., "local" | "cloud" | "ci")'),xqt=he().describe("Name of the service"),wqt=ewe(Ku).describe("Entity type of the parent entity"),Qus=he().describe("ID of the parent entity"),Sqt=he().describe("Name of the parent entity"),kqt=ewe(Ku).describe("Entity type of the root entity"),Yus=he().describe("ID of the root entity"),Oqt=he().describe("Name of the root entity"),_qt=he().describe("Version ID of the entity that produced this signal (e.g., agent version, workflow version)"),Cqt=he().describe("Version ID of the parent entity that produced this signal"),Eqt=he().describe("Version ID of the root entity that produced this signal"),PQ=he().describe("Experiment or eval run identifier"),Kus=Ws(he(),Fa()).describe('Arbitrary package/app version info (e.g., {"core": "1.0.0", "memory": "1.0.0", "gitSha": "abcd1234"})'),xAe=Ws(he(),Fa()).describe("User-defined metadata for custom filtering"),Tqt=$t(he()).describe("Labels for filtering"),Xus={entityType:lA.nullish(),entityId:Zus.nullish(),entityName:uqt.nullish(),parentEntityType:wqt.nullish(),parentEntityId:Qus.nullish(),parentEntityName:Sqt.nullish(),rootEntityType:kqt.nullish(),rootEntityId:Yus.nullish(),rootEntityName:Oqt.nullish(),userId:dqt.nullish(),organizationId:fqt.nullish(),resourceId:pqt.nullish(),runId:hqt.nullish(),sessionId:mqt.nullish(),threadId:gqt.nullish(),requestId:vqt.nullish(),environment:yqt.nullish(),serviceName:xqt.nullish(),scope:Kus.nullish(),entityVersionId:_qt.nullish(),parentEntityVersionId:Cqt.nullish(),rootEntityVersionId:Eqt.nullish(),experimentId:PQ.nullish()},$Q={...Xus,executionSource:bqt.nullish(),tags:Tqt.nullish()};Gus.nullish();const MQ={timestamp:Wus.optional().describe("Filter by timestamp range"),traceId:he().optional().describe("Filter by trace ID"),spanId:he().optional().describe("Filter by span ID"),entityType:lA.optional(),entityName:uqt.optional(),entityVersionId:_qt.optional(),parentEntityVersionId:Cqt.optional(),rootEntityVersionId:Eqt.optional(),userId:dqt.optional(),organizationId:fqt.optional(),experimentId:PQ.optional(),serviceName:xqt.optional(),environment:yqt.optional(),parentEntityType:wqt.optional(),parentEntityName:Sqt.optional(),rootEntityType:kqt.optional(),rootEntityName:Oqt.optional(),resourceId:pqt.optional(),runId:hqt.optional(),sessionId:mqt.optional(),threadId:gqt.optional(),requestId:vqt.optional(),executionSource:bqt.optional(),tags:$t(he()).optional().describe("Filter by tags (must have all specified tags)")},DL=he().describe("Unique trace identifier"),DQ=he().describe("Unique span identifier within a trace"),cV=Js(["debug","info","warn","error","fatal"]),jqt=he().describe("Log message"),Nqt=Ws(he(),Fa()).describe("Structured data attached to the log"),Iqt=je({logId:he().nullish().describe("Unique id for this log event"),timestamp:I_().describe("When the log was created"),level:cV.describe("Log severity level"),message:jqt,data:Nqt.nullish(),traceId:DL.nullish(),spanId:DQ.nullish(),...$Q,source:he().nullish().describe("Execution source"),metadata:xAe.nullish()}).describe("Log record as stored in the database");je({level:cV,message:jqt,data:Nqt.optional(),tags:Tqt.optional()}).describe("User-provided log input");const Jus=Iqt;je({logs:$t(Jus)}).describe("Arguments for batch creating logs");const eds=je({...MQ,source:he().optional().describe("Filter by execution source"),level:Gn([cV,$t(cV)]).optional().describe("Filter by log level(s)")}).describe("Filters for querying logs"),tds=Js(["timestamp"]).describe("Field to order by: 'timestamp'"),nds=je({field:tds.default("timestamp").describe("Field to order by"),direction:ML.default("DESC").describe("Sort direction")}).describe("Order by configuration");je({mode:jQ.optional(),filters:eds.optional().describe("Optional filters to apply"),pagination:EQ.optional(),orderBy:nds.optional(),after:yS.optional(),limit:NQ}).strict().superRefine(IQ).transform(e=>AQ(e,{orderBy:{field:"timestamp",direction:"DESC"}})).describe("Arguments for listing logs");je({pagination:TQ.optional(),delta:RQ.optional(),deltaCursor:yS.optional(),logs:$t(Iqt)}).describe("Response from listing logs");const cA=he().describe("Identifier of the scorer (e.g., relevance, accuracy)"),Aqt=he().describe("Display name of the scorer"),Rqt=he().describe("Version of the scorer"),Ey=he().describe("How the score was produced (e.g., manual, automated, experiment)"),Pqt=Nt().describe("Score value (range defined by scorer)"),$qt=he().describe("Explanation for the score"),Mqt=je({scoreId:he().nullish().describe("Unique id for this score event"),timestamp:I_().describe("When the score was recorded"),traceId:DL.nullish().describe("Trace that anchors the scored target when available"),spanId:DQ.nullish().describe("Span ID this score applies to"),scorerId:cA,scorerName:Aqt.nullish(),scorerVersion:Rqt.nullish(),scoreSource:Ey.nullish(),source:Ey.nullish(),score:Pqt,reason:$qt.nullish(),...$Q,scoreTraceId:he().nullish().describe("Trace ID of the scoring run for debugging score generation"),metadata:Ws(he(),Fa()).nullish().describe("User-defined metadata")}).describe("Score record as stored in the database");je({scorerId:cA,scorerName:Aqt.optional(),scorerVersion:Rqt.optional(),scoreSource:Ey.optional(),source:Ey.optional(),score:Pqt,reason:$qt.optional(),metadata:Ws(he(),Fa()).optional().describe("Additional scorer-specific metadata"),experimentId:PQ.optional(),scoreTraceId:he().optional().describe("Trace ID of the scoring run for debugging score generation"),targetEntityType:lA.optional().describe("Entity type the scorer evaluated when known")}).describe("User-provided score input");const wAe=Mqt;je({score:wAe}).describe("Arguments for creating a score");je({score:wAe.omit({timestamp:!0})}).describe("Arguments for creating a score");je({success:Ds()}).describe("Response from creating a score");je({scores:$t(wAe)}).describe("Arguments for batch recording scores");const LL=je({...MQ,scorerId:Gn([he(),$t(he())]).optional().describe("Filter by scorer ID(s)"),scoreSource:Ey.optional().describe("Filter by how the score was produced"),metadata:xAe.nullish().describe("Filter by metadata key-value pairs (exact match per key)"),source:Ey.optional().describe("Filter by how the score was produced")}).describe("Filters for querying scores"),rds=Js(["timestamp","score"]).describe("Field to order by: 'timestamp' | 'score'"),sds=je({field:rds.default("timestamp").describe("Field to order by"),direction:ML.default("DESC").describe("Sort direction")}).describe("Order by configuration");je({mode:jQ.optional(),filters:LL.optional(),pagination:EQ.optional(),orderBy:sds.optional(),after:yS.optional(),limit:NQ}).strict().superRefine(IQ).transform(e=>AQ(e,{orderBy:{field:"timestamp",direction:"DESC"}})).describe("Arguments for listing scores");je({pagination:TQ.optional(),delta:RQ.optional(),deltaCursor:yS.optional(),scores:$t(Mqt)}).describe("Response from listing scores");je({scorerId:cA,scoreSource:Ey.optional(),aggregation:Gy,filters:LL.optional(),comparePeriod:hAe.optional()}).describe("Arguments for getting a score aggregate");je(gAe);je({scorerId:cA,scoreSource:Ey.optional(),groupBy:EC,aggregation:Gy,filters:LL.optional()}).describe("Arguments for getting a score breakdown");je({groups:$t(je({dimensions:vAe,value:iA}))});je({scorerId:cA,scoreSource:Ey.optional(),interval:CC,aggregation:Gy,filters:LL.optional(),groupBy:EC.optional()}).describe("Arguments for getting score time series");je({series:$t(je({name:he().describe("Series name (scorer ID or group key)"),points:$t(je({timestamp:oA,value:iA}))}))});je({scorerId:cA,scoreSource:Ey.optional(),percentiles:mAe,interval:CC,filters:LL.optional()}).describe("Arguments for getting score percentiles");je({series:$t(je({percentile:yAe,points:$t(je({timestamp:oA,value:bAe}))}))});const Ty=he().describe("Source of feedback (e.g., 'user', 'system', 'manual')"),uA=he().describe("Type of feedback (e.g., 'thumbs', 'rating', 'correction')"),Dqt=Gn([Nt(),he()]).describe("Feedback value (rating number or correction text)"),Lqt=he().describe("Additional comment or context"),uV=he().describe("User who provided the feedback");function SAe(e){if(!e||typeof e!="object"||Array.isArray(e))return e;const t={...e};return typeof t.userId=="string"&&t.feedbackUserId==null&&(t.feedbackUserId=t.userId,delete t.userId),t}const LQ=je({feedbackId:he().nullish().describe("Unique id for this feedback event"),timestamp:I_().describe("When the feedback was recorded"),traceId:DL.nullish().describe("Trace that anchors the feedback target when available"),spanId:DQ.nullish().describe("Span ID this feedback applies to"),feedbackSource:Ty.nullish(),source:Ty.nullish(),feedbackType:uA,value:Dqt,comment:Lqt.nullish(),feedbackUserId:uV.nullish(),...$Q,sourceId:he().nullish().describe("ID of the source record this feedback is linked to (e.g. experiment result ID)"),metadata:Ws(he(),Fa()).nullish().describe("User-defined metadata")}),ads=je(LQ.shape).describe("Feedback record as stored in the database"),ids=je({feedbackSource:Ty.optional(),source:Ty.optional(),feedbackType:uA,value:Dqt,comment:Lqt.optional(),feedbackUserId:uV.optional(),userId:uV.optional(),metadata:Ws(he(),Fa()).optional().describe("Additional feedback-specific metadata"),experimentId:PQ.optional(),sourceId:he().optional().describe("ID of the source record this feedback is linked to")});je(ids.shape).describe("User-provided feedback input");je({feedback:swe(SAe,LQ)}).describe("Arguments for creating feedback");je({feedback:LQ.omit({timestamp:!0})}).describe("Arguments for creating feedback");je({success:Ds()}).describe("Response from creating feedback");je({feedbacks:$t(swe(SAe,LQ))}).describe("Arguments for batch recording feedback");const Fqt=je({...MQ,feedbackType:Gn([he(),$t(he())]).optional().describe("Filter by feedback type(s)"),feedbackSource:Ty.optional(),source:Ty.optional(),feedbackUserId:uV.optional()}),FQ=je(Fqt.shape).describe("Filters for querying feedback"),ods=Js(["timestamp"]).describe("Field to order by: 'timestamp'"),lds=je({field:ods.default("timestamp").describe("Field to order by"),direction:ML.default("DESC").describe("Sort direction")}).describe("Order by configuration");je({mode:jQ.optional(),filters:swe(SAe,Fqt).optional(),pagination:EQ.optional(),orderBy:lds.optional(),after:yS.optional(),limit:NQ}).strict().superRefine(IQ).transform(e=>AQ(e,{orderBy:{field:"timestamp",direction:"DESC"}})).describe("Arguments for listing feedback");je({pagination:TQ.optional(),delta:RQ.optional(),deltaCursor:yS.optional(),feedback:$t(ads)}).describe("Response from listing feedback");je({feedbackType:uA,feedbackSource:Ty.optional(),aggregation:Gy,filters:FQ.optional(),comparePeriod:hAe.optional()}).describe("Arguments for getting a feedback aggregate over numeric values");je(gAe);je({feedbackType:uA,feedbackSource:Ty.optional(),groupBy:EC,aggregation:Gy,filters:FQ.optional()}).describe("Arguments for getting a feedback breakdown over numeric values");je({groups:$t(je({dimensions:vAe,value:iA}))});je({feedbackType:uA,feedbackSource:Ty.optional(),interval:CC,aggregation:Gy,filters:FQ.optional(),groupBy:EC.optional()}).describe("Arguments for getting feedback time series over numeric values");je({series:$t(je({name:he().describe("Series name (feedback type or group key)"),points:$t(je({timestamp:oA,value:iA}))}))});je({feedbackType:uA,feedbackSource:Ty.optional(),percentiles:mAe,interval:CC,filters:FQ.optional()}).describe("Arguments for getting feedback percentiles over numeric values");je({series:$t(je({percentile:yAe,points:$t(je({timestamp:oA,value:bAe}))}))});Js(["counter","gauge","histogram"]);const zqt=he().describe("Metric name (e.g., mastra_agent_duration_ms)"),Bqt=Nt().describe("Metric value"),Uqt=Ws(he(),he()).describe("Metric labels for dimensional filtering"),qqt=he().describe("Model provider"),Vqt=he().describe("Model"),cds=Nt().describe("Estimated cost"),Hqt=he().describe("Unit for the estimated cost (e.g., usd)"),uds=Ws(he(),Fa()).nullish().describe("Structured costing metadata"),Wqt=je({metricId:he().nullish().describe("Unique id for this metric event"),timestamp:I_().describe("When the metric was recorded"),name:zqt,value:Bqt,traceId:DL.nullish(),spanId:DQ.nullish(),...$Q,source:he().nullish().describe("Execution source"),provider:qqt.nullish(),model:Vqt.nullish(),estimatedCost:cds.nullish(),costUnit:Hqt.nullish(),costMetadata:uds.nullish(),labels:Uqt.default({}),metadata:xAe.nullish()}).describe("Metric record as stored in the database");je({name:zqt,value:Bqt,labels:Uqt.optional()}).describe("User-provided metric input");const dds=Wqt;je({metrics:$t(dds)}).describe("Arguments for batch recording metrics");je({type:Gy,interval:CC.optional(),groupBy:EC.optional()}).describe("Metrics aggregation configuration");const FL=je({...MQ,traceIds:$t(DL).nonempty().max(1e3).optional().describe("Filter by one or more trace IDs"),name:$t(he()).nonempty().optional().describe("Filter by metric name(s)"),source:he().optional().describe("Filter by execution source"),provider:qqt.optional(),model:Vqt.optional(),costUnit:Hqt.optional(),labels:Ws(he(),he()).optional().describe("Exact match on label key-value pairs")}).describe("Filters for querying metrics"),fds=Js(["timestamp"]).describe("Field to order by: 'timestamp'"),pds=je({field:fds.default("timestamp").describe("Field to order by"),direction:ML.default("DESC").describe("Sort direction")}).describe("Order by configuration");je({mode:jQ.optional(),filters:FL.optional(),pagination:EQ.optional(),orderBy:pds.optional(),after:yS.optional(),limit:NQ}).strict().superRefine(IQ).transform(e=>AQ(e,{orderBy:{field:"timestamp",direction:"DESC"}})).describe("Arguments for listing metrics");je({pagination:TQ.optional(),delta:RQ.optional(),deltaCursor:yS.optional(),metrics:$t(Wqt)}).describe("Response from listing metrics");const hds=["entityType","entityName","parentEntityType","parentEntityName","rootEntityType","rootEntityName","name","provider","model","environment","executionSource","serviceName","threadId","resourceId"],kAe=Js(hds).optional().describe("Column to apply count_distinct over (required when aggregation is 'count_distinct'). Restricted to allowlisted metric dimensions."),qN={check:e=>e.aggregation!=="count_distinct"||e.distinctColumn!==void 0,options:{message:"distinctColumn is required when aggregation is 'count_distinct'",path:["distinctColumn"]}};je({name:$t(he()).nonempty().describe("Metric name(s) to aggregate"),aggregation:Gy,distinctColumn:kAe,filters:FL.optional(),comparePeriod:hAe.optional()}).refine(qN.check,qN.options).describe("Arguments for getting a metric aggregate");je({...gAe,estimatedCost:Nt().nullable().optional().describe("Aggregated estimated cost from the same filtered row set"),costUnit:he().nullable().optional().describe("Shared cost unit for the aggregated rows, or null when mixed/unknown"),previousEstimatedCost:Nt().nullable().optional().describe("Aggregated estimated cost from the comparison period"),costChangePercent:Nt().nullable().optional().describe("Percentage change in estimated cost from comparison period")});je({name:$t(he()).nonempty().describe("Metric name(s) to break down"),groupBy:EC,aggregation:Gy,distinctColumn:kAe,filters:FL.optional(),limit:Nt().int().positive().max(1e3).optional().describe("Maximum number of groups to return (server-side TopK). Required for high-cardinality groupBy."),orderDirection:ML.optional().describe("Sort direction for the aggregated value (defaults to 'DESC' at the storage layer; pairs with limit for top/bottom-N).")}).refine(qN.check,qN.options).describe("Arguments for getting a metric breakdown");je({groups:$t(je({dimensions:vAe,value:iA,estimatedCost:Nt().nullable().optional().describe("Summed estimated cost for this group"),costUnit:he().nullable().optional().describe("Shared cost unit for this group, or null when mixed/unknown")}))});je({name:$t(he()).nonempty().describe("Metric name(s)"),interval:CC,aggregation:Gy,distinctColumn:kAe,filters:FL.optional(),groupBy:EC.optional()}).refine(qN.check,qN.options).describe("Arguments for getting metric time series");je({series:$t(je({name:he().describe("Series name (metric name or group key)"),costUnit:he().nullable().optional().describe("Shared cost unit for this series, or null when mixed/unknown"),points:$t(je({timestamp:oA,value:iA,estimatedCost:Nt().nullable().optional().describe("Summed estimated cost in this bucket")}))}))});je({name:he().describe("Metric name"),percentiles:mAe,interval:CC,filters:FL.optional()}).describe("Arguments for getting metric percentiles");je({series:$t(je({percentile:yAe,points:$t(je({timestamp:oA,value:bAe}))}))});je({prefix:he().optional().describe("Filter metric names by prefix"),limit:x2().int().min(1).optional().describe("Maximum number of names to return")}).describe("Arguments for getting metric names");je({names:$t(he()).describe("Distinct metric names")});je({metricName:he().describe("Metric name to get label keys for")}).describe("Arguments for getting metric label keys");je({keys:$t(he()).describe("Distinct label keys for the metric")});je({metricName:he().describe("Metric name"),labelKey:he().describe("Label key to get values for"),prefix:he().optional().describe("Filter values by prefix"),limit:x2().int().min(1).optional().describe("Maximum number of values to return")}).describe("Arguments for getting label values");je({values:$t(he()).describe("Distinct label values")});je({}).describe("Arguments for getting entity types");je({entityTypes:$t(lA).describe("Distinct entity types")});je({entityType:lA.optional().describe("Optional entity type filter")}).describe("Arguments for getting entity names");je({names:$t(he()).describe("Distinct entity names")});je({}).describe("Arguments for getting service names");je({serviceNames:$t(he()).describe("Distinct service names")});je({}).describe("Arguments for getting environments");je({environments:$t(he()).describe("Distinct environments")});je({entityType:lA.optional().describe("Optional entity type filter")}).describe("Arguments for getting tags");je({tags:$t(he()).describe("Distinct tags")});new Set(Object.values(Ku));function OAe({disabled:e,onClear:t,onRemoveAll:n,onSave:r,onRemoveSaved:s}){const a=!!(n||r||s);return!t&&!a?null:o.jsxs("div",{className:"flex items-center gap-2",children:[t&&o.jsxs(oe,{disabled:e,size:"md",onClick:t,children:[o.jsx(or,{}),"Clear"]}),a&&o.jsxs(rt,{children:[o.jsx(rt.Trigger,{asChild:!0,children:o.jsx(oe,{disabled:e,size:"md","aria-label":"More filter actions",children:o.jsx(JN,{})})}),o.jsxs(rt.Content,{align:"end",children:[n&&o.jsxs(rt.Item,{onSelect:()=>n(),children:[o.jsx(or,{}),"Remove all filters"]}),n&&(r||s)&&o.jsx(rt.Separator,{}),r&&o.jsxs(rt.Item,{onSelect:()=>r(),children:[o.jsx(Gu,{}),"Save filters for next time"]}),s&&o.jsxs(rt.Item,{onSelect:()=>s(),children:[o.jsx(Ml,{}),"Remove saved filters"]})]})]})]})}function Zqt({field:e,tokens:t,onChange:n}){const[r,s]=g.useState(""),a=g.useMemo(()=>{const u=r.trim().toLowerCase();return u?e.options.filter(d=>d.label.toLowerCase().includes(u)):e.options},[e.options,r]),i=g.useMemo(()=>t.find(u=>u.fieldId===e.id),[t,e.id]),l=typeof i?.value=="string"?i.value:e.multi?void 0:e.defaultValue,c=g.useMemo(()=>{const u=i?.value;return Array.isArray(u)?u:typeof u=="string"?[u]:[]},[i]);return o.jsxs(o.Fragment,{children:[e.searchable!==!1&&o.jsx(In,{size:"sm",value:r,onChange:u=>s(u.target.value),placeholder:`Search ${e.label.toLowerCase()}...`,className:"mb-2",onKeyDown:u=>{if(u.key!=="ArrowDown")return;const f=u.currentTarget.closest("[data-pick-multi-panel]")?.querySelector("[data-pick-multi-item]:not([disabled])");f&&(u.preventDefault(),u.stopPropagation(),f.focus())}}),e.isLoading?o.jsxs("div",{className:"text-ui-sm text-neutral3 flex items-center gap-2 px-2 py-1.5",children:[o.jsx(Ut,{size:"sm",className:"text-neutral3 size-3"}),"Loading options…"]}):a.length===0?o.jsx("div",{className:"text-ui-sm text-neutral3 px-2 py-1.5",children:e.emptyText??"No option found."}):e.multi?o.jsx("div",{className:"max-h-[80dvh] overflow-auto",children:a.map(u=>{const d=c.includes(u.value);return o.jsxs("label",{title:u.label,className:"text-ui-md text-neutral4 focus-within:bg-surface4 focus-within:text-neutral6 hover:bg-surface4 hover:text-neutral6 flex min-w-0 cursor-pointer items-center gap-2 rounded-md px-2 py-1.5",children:[o.jsx(So,{"data-pick-multi-item":"",checked:d,onCheckedChange:f=>{const h=f===!0?c.includes(u.value)?c:[...c,u.value]:c.filter(m=>m!==u.value);n(e.id,h)},className:"shrink-0"}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:u.label})]},u.value)})}):o.jsxs(G4,{value:l??"",onValueChange:u=>n(e.id,u),className:"max-h-[80dvh] gap-0 overflow-auto",children:[a.map(u=>o.jsxs("label",{title:u.label,className:"text-ui-md text-neutral4 focus-within:bg-surface4 focus-within:text-neutral6 hover:bg-surface4 hover:text-neutral6 flex min-w-0 cursor-pointer items-center gap-2 rounded-md px-2 py-1.5",children:[o.jsx(Pp,{"data-pick-multi-item":"",value:u.value,className:"shrink-0"}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:u.label})]},u.value)),!e.omitAnyOption&&o.jsxs("label",{title:"Any",className:"text-ui-md text-neutral4 focus-within:bg-surface4 focus-within:text-neutral6 hover:bg-surface4 hover:text-neutral6 flex min-w-0 cursor-pointer items-center gap-2 rounded-md px-2 py-1.5",children:[o.jsx(Pp,{"data-pick-multi-item":"",value:"Any",className:"shrink-0"}),o.jsx("span",{className:"min-w-0 flex-1 truncate",children:"Any"})]})]})]})}function _Ae(e){return Array.isArray(e)?e.length===0?"Any":e.join(", "):e}const mds="This filter is set by the current context and cannot be removed here.";function gds(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:_Ae(t)}function vds({field:e,value:t,tooltipContent:n}){const r=gds(e,t),s=`${e.label} filter is locked by context`;return o.jsx(zl,{delayDuration:150,children:o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:o.jsxs(hs,{spacing:"close","data-locked-field-id":e.id,"data-property-filter-pill":"locked",tabIndex:0,"aria-label":s,children:[o.jsx(Kh,{size:"md",children:e.label}),o.jsx(Kh,{size:"md",children:"is"}),o.jsx(Kh,{size:"md",children:r}),o.jsx(Kh,{size:"md",children:o.jsx(Bd,{})})]})}),o.jsx(vn,{children:n})]})})}function yds({field:e,value:t,onChange:n,onRemove:r,disabled:s,autoFocus:a}){const[i,l]=g.useState(t),c=g.useRef(null);return g.useEffect(()=>{i.trim()!==t&&l(t)},[t]),g.useEffect(()=>{a&&c.current?.focus()},[a]),o.jsxs(hs,{spacing:"close",children:[o.jsx(Kh,{size:"md",children:e.label}),o.jsx(Kh,{size:"md",children:"is"}),o.jsx(In,{ref:c,size:"md",disabled:s,value:i,placeholder:e.placeholder??`Enter ${e.label}`,onChange:u=>{const d=u.target.value;l(d),d.trim()!==t&&n(d)},onKeyDown:u=>{if(u.key==="Enter"){u.preventDefault();const d=i.trim();d!==t&&n(d)}else u.key==="Escape"&&(u.preventDefault(),l(t),u.target.blur())}}),o.jsx(oe,{type:"button",disabled:s,"aria-label":`Remove ${e.label} filter`,size:"md",onMouseDown:u=>u.preventDefault(),onClick:r,children:o.jsx(or,{})})]})}function bds({field:e,token:t,tokens:n,onChange:r,onRemove:s,disabled:a}){const[i,l]=g.useState(!1);return o.jsxs(hs,{spacing:"close",children:[o.jsx(Kh,{size:"md",children:e.label}),o.jsx(Kh,{size:"md",children:"is"}),o.jsxs(Uf,{open:i,onOpenChange:l,children:[o.jsx(Kd,{asChild:!0,children:o.jsx(oe,{type:"button",disabled:a,size:"md",children:_Ae(t.value)})}),o.jsx(Xd,{align:"start",sideOffset:8,className:"w-64 p-2","data-pick-multi-panel":!0,children:o.jsx(Zqt,{field:e,tokens:n,onChange:r})})]}),o.jsx(oe,{type:"button",disabled:a,"aria-label":`Remove ${e.label} filter`,size:"md",onClick:s,children:o.jsx(or,{})})]})}function CAe({fields:e,tokens:t,onTokensChange:n,disabled:r,autoFocusFieldId:s,lockedFieldIds:a,lockedTooltipContent:i=mds}){if(t.length===0)return null;const l=new Set(a??[]),c=(d,f)=>{const p=[...t];p[d]=f,n(p)},u=d=>{n(t.filter((f,p)=>p!==d))};return o.jsx("div",{className:"flex flex-wrap items-center gap-2",children:t.map((d,f)=>{const p=e.find(h=>h.id===d.fieldId);return p?l.has(d.fieldId)?o.jsx(vds,{field:p,value:d.value,tooltipContent:i},`${d.fieldId}-${f}`):p.kind==="text"&&typeof d.value=="string"?o.jsx(yds,{field:p,value:d.value,disabled:r,autoFocus:s===d.fieldId,onChange:h=>c(f,{fieldId:d.fieldId,value:h}),onRemove:()=>u(f)},`${d.fieldId}-${f}`):p.kind==="pick-multi"?o.jsx(bds,{field:p,token:d,tokens:t,disabled:r,onChange:(h,m)=>c(f,{fieldId:h,value:m}),onRemove:()=>u(f)},`${d.fieldId}-${f}`):o.jsxs(hs,{spacing:"close",children:[o.jsx(Kh,{size:"md",children:p.label}),o.jsx(Kh,{size:"md",children:"is"}),o.jsx(Kh,{size:"md",children:_Ae(d.value)}),o.jsx(oe,{type:"button",disabled:r,size:"md","aria-label":`Remove ${p.label} filter`,onClick:()=>u(f),children:o.jsx(or,{})})]},`${d.fieldId}-${f}`):null})})}function EAe({fields:e,tokens:t,onTokensChange:n,label:r="Add Filter",disabled:s,size:a,onStartTextFilter:i,hiddenFieldIds:l}){const c=g.useMemo(()=>{if(!l||l.length===0)return e;const A=new Set(l);return e.filter(R=>!A.has(R.id))},[e,l]),[u,d]=g.useState(!1),[f,p]=g.useState(),[h,m]=g.useState([]),[v,y]=g.useState(),[b,x]=g.useState(),S=g.useRef(!1),k=g.useCallback(A=>{x(R=>R===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 R of t){const L=e.find(D=>D.id===R.fieldId);L&&L.kind!=="pick-multi"&&A.add(R.fieldId)}return A},[t,e]),E=g.useCallback(()=>{p(void 0),m([]),y(void 0)},[]);g.useEffect(()=>{u||E()},[u,E]);const N=g.useCallback((A,R)=>{const L=t.findIndex(F=>F.fieldId===A);if(Array.isArray(R)&&R.length===0){if(L===-1)return;n(t.filter((F,H)=>H!==L));return}if(L===-1){n([...t,{fieldId:A,value:R}]);return}const D=[...t];D[L]={fieldId:A,value:R},n(D)},[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(h.length===0){y(`Choose at least one ${C.label.toLowerCase()} value.`);return}n([...t,{fieldId:C.id,value:h}]),d(!1)},[h,n,C,T,t]);return o.jsxs(Uf,{open:u,onOpenChange:d,children:[o.jsx(Kd,{asChild:!0,children:o.jsxs(oe,{variant:"outline",size:a,disabled:s,children:[o.jsx($Kt,{}),r]})}),o.jsx(Xd,{align:"end",className:"w-64 p-3",initialFocus:!1,finalFocus:()=>S.current?(S.current=!1,!1):!0,children:o.jsxs("div",{className:"grid 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(gl,{className:"size-4"})}),o.jsx(i0e,{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 R=Array.from(A.currentTarget.querySelectorAll("[data-filter-item]:not([disabled])"));if(R.length===0)return;A.preventDefault();const L=document.activeElement,D=R.findIndex(H=>H===L);let F;A.key==="Home"?F=0:A.key==="End"?F=R.length-1:A.key==="ArrowDown"?F=D<0?0:(D+1)%R.length:F=D<=0?R.length-1:D-1,R[F]?.focus()},children:c.length>0?c.map(A=>{const R=T.has(A.id);return A.kind==="pick-multi"?o.jsx(xds,{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("group flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-ui-md transition-colors","focus:bg-surface4 focus:text-neutral6 focus:outline-none",R?"cursor-not-allowed text-neutral2 opacity-70":"text-neutral4 hover:bg-surface4 hover:text-neutral6"),disabled:R,onClick:()=>{if(y(void 0),A.kind==="text"){n([...t,{fieldId:A.id,value:""}]),i?.(A.id),S.current=!0,d(!1);return}p(A.id)},children:[o.jsx("span",{className:"truncate",children:A.label}),R?o.jsx("span",{className:"text-neutral3 ml-auto",children:"In use"}):o.jsx(Or,{className:"text-neutral3 ml-auto size-4 opacity-0 transition-opacity group-hover:opacity-100 group-focus:opacity-100"})]},A.id)}):o.jsx("div",{className:"text-ui-sm text-neutral3 px-2 py-1.5",children:"No matching property."})}),C&&o.jsx(ml,{multiple:!0,options:C.options??[],value:h,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(oe,{variant:"ghost",size:"md",onClick:()=>d(!1),children:"Cancel"}),o.jsx(oe,{variant:"outline",size:"md",onClick:I,children:"Add filter"})]})]})})]})}function xds({field:e,tokens:t,onChange:n,open:r,onToggle:s,onClose:a}){const i=g.useRef(null);return o.jsxs(Uf,{open:r,onOpenChange:l=>{l?s(e.id):a()},children:[o.jsx(Kd,{asChild:!0,children:o.jsxs("button",{type:"button",role:"menuitem","data-filter-item":"",className:K("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-ui-md text-neutral4 transition-colors hover:bg-surface4 hover:text-neutral6","focus:bg-surface4 focus:text-neutral6 focus:outline-none"),onKeyDown:l=>{l.key!=="ArrowRight"&&l.key!=="ArrowLeft"||(r||s(e.id),l.preventDefault(),requestAnimationFrame(()=>{i.current?.querySelector('input, button, [tabindex]:not([tabindex="-1"])')?.focus()}))},children:[r&&o.jsx(Ur,{className:"text-neutral3 size-4 shrink-0"}),o.jsx("span",{className:"truncate",children:e.label}),!r&&o.jsx(Ur,{className:"text-neutral3 ml-auto size-4 shrink-0"})]})}),o.jsx(Xd,{ref:i,side:"right",align:"start",sideOffset:8,className:"w-64 p-2",initialFocus:!1,onKeyDown:l=>{if(l.key!=="ArrowDown"&&l.key!=="ArrowUp"&&l.key!=="Home"&&l.key!=="End")return;const c=Array.from(l.currentTarget.querySelectorAll("[data-pick-multi-item]:not([disabled])"));if(c.length===0)return;l.preventDefault(),l.stopPropagation();const u=document.activeElement,d=c.findIndex(p=>p===u);let f;l.key==="Home"?f=0:l.key==="End"?f=c.length-1:l.key==="ArrowDown"?f=d<0?0:(d+1)%c.length:f=d<=0?c.length-1:d-1,c[f]?.focus()},"data-pick-multi-panel":!0,children:o.jsx(Zqt,{field:e,tokens:t,onChange:n})})]})}const wds={"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"},yie="MMM d, yyyy HH:mm",bie="Pick a wider time range — older traces may fall outside the current window.";function Sds({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No traces for ${wds[e]}`,description:bie}:t&&n?{title:`No traces between ${hr(t,yie)} and ${hr(n,yie)}`,description:bie}:t?{title:`No traces since ${hr(t,yie)}`,description:bie}:{title:"No traces yet",description:"Traces will appear here once agents, workflows, or tools are executed."}}const kds=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=Sds({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Er,{iconSlot:o.jsx(Mc,{}),titleSlot:r,descriptionSlot:s})})},Ods=["input","entity","duration"],pet={input:"Input",entity:"Entity",duration:"Duration",inputTokens:"Input tokens",outputTokens:"Output tokens",estimatedCost:"Estimated cost"};function _ds({preferences:e,usageDisabledReason:t,onToggleColumn:n,onAddMetadataColumn:r,onRemoveMetadataColumn:s,onReset:a}){const[i,l]=g.useState(!1),[c,u]=g.useState(""),[d,f]=g.useState(),p=m=>{l(m),m||(u(""),f(void 0))},h=m=>{m.preventDefault();const v=c.trim();if(!v){f("Enter a metadata key.");return}if(e.metadataKeys.includes(v)){f("That metadata column is already visible.");return}r(v),p(!1)};return o.jsxs(o.Fragment,{children:[o.jsxs(rt,{children:[o.jsx(rt.Trigger,{render:o.jsxs(oe,{variant:"outline",size:"md",children:[o.jsx(Mlt,{"aria-hidden":!0}),"Columns"]})}),o.jsxs(rt.Content,{align:"end",className:"min-w-56",children:[o.jsx(rt.Label,{children:"Standard columns"}),Ods.map(m=>o.jsx(rt.CheckboxItem,{checked:e.visibleColumns.includes(m),onCheckedChange:()=>n(m),children:pet[m]},m)),o.jsx(rt.Separator,{}),o.jsx(rt.Label,{children:"Usage columns"}),VUt.map(m=>o.jsx(rt.CheckboxItem,{checked:e.visibleColumns.includes(m),disabled:!!t,onCheckedChange:()=>n(m),children:pet[m]},m)),t&&o.jsx("p",{className:"text-ui-xs leading-ui-sm text-neutral2 px-2 py-1",role:"note",children:t}),o.jsx(rt.Separator,{}),o.jsx(rt.Label,{children:"Metadata columns"}),e.metadataKeys.map(m=>o.jsx(rt.CheckboxItem,{checked:!0,title:m,onCheckedChange:()=>s(m),children:m},m)),o.jsxs(rt.Item,{onSelect:()=>l(!0),children:[o.jsx(Or,{"aria-hidden":!0}),"Add metadata column"]}),o.jsx(rt.Separator,{}),o.jsx(rt.Item,{onSelect:a,children:"Reset to defaults"})]})]}),o.jsx(vr,{open:i,onOpenChange:p,children:o.jsx(yr,{children:o.jsxs("form",{onSubmit:h,children:[o.jsxs(br,{children:[o.jsx(pr,{children:"Add metadata column"}),o.jsx(Ps,{children:"Enter a top-level trace metadata key. Only the key is saved, never its values."})]}),o.jsxs(Mr,{className:"space-y-2",children:[o.jsx(Mt,{htmlFor:"trace-metadata-key",children:"Metadata key"}),o.jsx(In,{id:"trace-metadata-key",value:c,onChange:m=>{u(m.target.value),f(void 0)},placeholder:"tenantId",autoFocus:!0,error:!!d,"aria-describedby":d?"trace-metadata-key-error":void 0}),d&&o.jsx("p",{id:"trace-metadata-key-error",className:"text-ui-xs text-error",role:"alert",children:d})]}),o.jsxs(lc,{children:[o.jsx(oe,{type:"button",variant:"outline",onClick:()=>p(!1),children:"Cancel"}),o.jsx(oe,{type:"submit",variant:"primary",children:"Add column"})]})]})})})]})}function Cds({listSlot:e,tracePanelSlot:t,spanPanelSlot:n,scorePanelSlot:r,traceCollapsed:s,sidePanelWide:a}){const i=!!t;return o.jsxs("div",{className:K("grid max-h-full min-h-0 items-start gap-4 transition-[grid-template-columns] duration-300 ease-in-out",i?a?"grid-cols-[1fr_4fr]":"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[e,i&&o.jsxs("div",{className:K("grid max-h-full gap-4 overflow-auto",!s&&"h-full",r?s?"grid-rows-[auto_3fr_3fr]":"grid-rows-[2fr_3fr_3fr]":n?s?"grid-rows-[auto_3fr]":"grid-rows-[2fr_3fr]":s?"grid-rows-[auto]":"grid-rows-[1fr]"),children:[t,n,r]})]})}function Eds({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c,lockedFieldIds:u,lockedTooltipContent:d}){const f=i.length>0,p=new Set(u??[]),h=i.filter(y=>!p.has(y.fieldId)),m=h.some(y=>Tds(y,a)),v=h.length>0;return f?o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] items-start gap-3 "),children:[o.jsx(CAe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c,lockedFieldIds:u,lockedTooltipContent:d}),f&&v&&o.jsx(OAe,{disabled:s,onClear:m?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function Tds(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 zQ=300*1e3,Hz={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},TAe=[{label:"Agent",entityType:Hz.AGENT},{label:"Workflow",entityType:Hz.WORKFLOW},{label:"Scorer",entityType:Hz.SCORER},{label:"Ingest",entityType:Hz.INGEST}],jds=[{label:"Running",value:"running"},{label:"Success",value:"success"},{label:"Error",value:"error"}],Gx="rootEntityType",Qx="status",Mw="listMode",k9="anchorSpanId",Nds=new Set(["traces","branches"]),Dw="datePreset",Lw="dateFrom",Fw="dateTo",Ids=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),Ol={tags:"filterTags",entityId:"filterEntityId",entityName:"filterEntityName",traceId:"filterTraceId",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId"},zL=Object.keys(Ol),Ads=new Set(["running","success","error"]),jAe="mastra:traces:saved-filters";function Rds(e,t=jAe){const n=Lds(e),r=e.get(Dw);r&&n.set(Dw,r);const s=e.get(Lw);s&&n.set(Lw,s);const a=e.get(Fw);a&&n.set(Fw,a);try{localStorage.setItem(t,n.toString())}catch{}}function Pds(e=jAe){try{localStorage.removeItem(e)}catch{}}function het(e=jAe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function $ds(e){if(e.has(Dw)||e.has(Lw)||e.has(Fw)||e.has(Gx)||e.has(Qx)||e.has(Mw))return!0;for(const t of zL)if(e.has(Ol[t]))return!0;return!1}function Mds({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:TAe.map(u=>({label:u.label,value:u.entityType})),placeholder:"Choose entity type",emptyText:"No entity types."},{id:"entityName",label:"Primitive Name",kind:"pick-multi",options:t.map(u=>({label:u,value:u})),placeholder:"Choose entity names",emptyText:"No entity names found.",isLoading:s?.entityNames},{id:"entityId",label:"Primitive ID",kind:"text"},{id:"status",label:"Status",kind:"pick-multi",searchable:!1,options:jds.map(u=>({label:u.label,value:u.value})),placeholder:"Choose status",emptyText:"No statuses."},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"traceId",label:"Trace ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"threadId",label:"Thread ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function Dds(e){const t=[],n=new Map([[Gx,"rootEntityType"],[Qx,"status"]]);for(const s of zL)n.set(Ol[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),a==="tags"){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function Lds(e){const t=new URLSearchParams,n=e.get(Gx);n&&t.set(Gx,n);const r=e.get(Qx);r&&t.set(Qx,r);const s=e.get(Mw);s&&t.set(Mw,s);for(const a of zL){const i=Ol[a];if(a==="tags"){for(const c of e.getAll(i))t.append(i,c);continue}const l=e.get(i);l&&t.set(i,l)}return t}function Fds(e,t){e.delete(Gx),e.delete(Qx);for(const n of zL)e.delete(Ol[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(Gx,n.value);continue}if(n.fieldId==="status"&&typeof n.value=="string"){e.set(Qx,n.value);continue}const r=Ol[n.fieldId];if(r){if(n.fieldId==="tags"&&Array.isArray(n.value)){if(n.value.length===0)e.append(r,"");else for(const s of n.value)e.append(r,s);continue}typeof n.value=="string"&&e.set(r,n.value.trim())}}}function zds({rootEntityType:e,status:t,dateFrom:n,dateTo:r,tokens:s}){const a={};e&&(a.entityType=e),t&&(a.status=t),n&&(a.startedAt={start:n}),r&&(a.endedAt={end:r});for(const i of s){if(i.fieldId==="tags"){Array.isArray(i.value)&&i.value.length>0?a.tags=i.value:typeof i.value=="string"&&i.value.trim()&&(a.tags=[i.value.trim()]);continue}if(typeof i.value=="string"&&i.value.trim()&&i.value!=="Any")switch(i.fieldId){case"entityId":a.entityId=i.value;break;case"entityName":a.entityName=i.value;break;case"traceId":a.traceId=i.value;break;case"runId":a.runId=i.value;break;case"threadId":a.threadId=i.value;break;case"sessionId":a.sessionId=i.value;break;case"requestId":a.requestId=i.value;break;case"resourceId":a.resourceId=i.value;break;case"userId":a.userId=i.value;break;case"organizationId":a.organizationId=i.value;break;case"serviceName":a.serviceName=i.value;break;case"environment":a.environment=i.value;break;case"experimentId":a.experimentId=i.value;break}}return a}function Bds(e,t){return t.map(n=>{const r=e.find(s=>s.id===n.fieldId);return r?r.kind==="text"?{fieldId:n.fieldId,value:""}:r.kind==="pick-multi"?r.omitAnyOption?n:r.multi?{fieldId:n.fieldId,value:[]}:{fieldId:n.fieldId,value:"Any"}:n:n})}function met(e){return Object.values(Ku).find(t=>t===e)}const NAe=({entityType:e,rootOnly:t=!1}={})=>{const n=Qe();return yt({queryKey:e?["observability-entity-names","by-type",e]:["observability-entity-names","all",t?"root-only":"all-types"],queryFn:async()=>{try{if(e){const a=met(e);return a?await n.getEntityNames({entityType:a}):{names:[]}}if(!t)return await n.getEntityNames();const s=await Promise.all(TAe.map(a=>{const i=met(a.entityType);return i?n.getEntityNames({entityType:i}):{names:[]}}));return{names:Array.from(new Set(s.flatMap(a=>a?.names??[]))).sort()}}catch{return{names:[]}}},select:s=>s?.names??[],retry:!1,staleTime:zQ})},IAe=()=>{const e=Qe();return yt({queryKey:["observability-environments"],queryFn:async()=>{try{return await e.getEnvironments()}catch{return{environments:[]}}},select:t=>t?.environments??[],retry:!1,staleTime:zQ})},AAe=()=>{const e=Qe();return yt({queryKey:["observability-service-names"],queryFn:async()=>{try{return await e.getServiceNames()}catch{return{serviceNames:[]}}},select:t=>t?.serviceNames??[],retry:!1,staleTime:zQ})},RAe=()=>{const e=Qe();return yt({queryKey:["observability-tags"],queryFn:async()=>{try{return await e.getTags()}catch{return{tags:[]}}},select:t=>t?.tags??[],retry:!1,staleTime:zQ})};function xie(e){if(typeof window>"u")return $w;try{return Rcs(window.localStorage.getItem(e)??void 0)}catch{return $w}}function Uds(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,Pcs(t))}catch{}}function qds(){const e=Qe(),t=e.options.baseUrl||(typeof window>"u"?"local":window.location.origin||"local"),n=e.options.apiPrefix??"/api",r=`mastra:traces:columns:${t}:${n}`,[s,a]=g.useState(()=>({storageKey:r,preferences:xie(r),shouldPersist:!1})),i=s.storageKey===r?s.preferences:xie(r);g.useEffect(()=>{s.storageKey===r&&s.shouldPersist&&Uds(r,s.preferences)},[s,r]);const l=p=>{a(h=>{const m=h.storageKey===r?h.preferences:xie(r),v=p(m);return{storageKey:r,preferences:v,shouldPersist:!0}})};return{preferences:i,toggleColumn:p=>{l(h=>{const m=h.visibleColumns.includes(p);return{...h,visibleColumns:m?h.visibleColumns.filter(v=>v!==p):[...h.visibleColumns,p]}})},addMetadataColumn:p=>{const h=p.trim();h&&l(m=>m.metadataKeys.includes(h)?m:{...m,metadataKeys:[...m.metadataKeys,h]})},removeMetadataColumn:p=>{l(h=>({...h,metadataKeys:h.metadataKeys.filter(m=>m!==p)}))},resetColumns:()=>l(()=>$w)}}const Vds="Trace filter settings saved.",Hds="Trace filter settings cleared.";function Wds(e,t,n){const{storageKey:r,messages:s,skipHydration:a}=n??{},[i,l]=g.useState(()=>het(r)!==null),c=g.useCallback(()=>{Rds(e,r),l(!0);const f=s?.saved??Vds;f!==!1&&Be.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{Pds(r),l(!1);const f=s?.cleared??Hds;f!==!1&&Be.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(a||d.current||(d.current=!0,$ds(e)))return;const f=het(r);f&&t(p=>{const h=new URLSearchParams(p);for(const[m,v]of f)h.append(m,v);return h},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}const O9="traceId",Db="spanId",Ev="tab",Tv="scoreId",wP=1440*60*1e3,Zds={"last-24h":wP,"last-3d":3*wP,"last-7d":7*wP,"last-14d":14*wP,"last-30d":30*wP};function SP(e){e.delete(O9),e.delete(Db),e.delete(k9),e.delete(Ev),e.delete(Tv)}function Gds(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const B=e.get(Dw);return B&&Ids.has(B)?B:"last-24h"},[e]),a=e.get(Lw),i=e.get(Fw),l=g.useMemo(()=>{if(s==="custom"){if(!a)return;const z=new Date(a);return Number.isNaN(z.getTime())?void 0:z}const B=Zds[s];return B?new Date(Date.now()-B):void 0},[s,a]),c=g.useMemo(()=>{if(s!=="custom"||!i)return;const B=new Date(i);return Number.isNaN(B.getTime())?void 0:B},[s,i]),u=g.useRef(s);u.current=s;const d=e.get(O9)||void 0,f=e.get(Db)||void 0,p=e.get(k9)||void 0,h=e.get(Ev),m=h==="feedback"?"feedback":h==="details"?"details":void 0,v=e.get(Tv)||void 0,y=g.useMemo(()=>{const B=e.get(Mw);return B&&Nds.has(B)?B:"traces"},[e]),b=g.useMemo(()=>TAe.find(B=>B.entityType===e.get(Gx)),[e]),x=g.useMemo(()=>{const B=e.get(Qx);return B&&Ads.has(B)?B:void 0},[e]),S=g.useMemo(()=>Dds(e),[e]),k=g.useCallback((B,z,V)=>{t(M=>{const G=new URLSearchParams(M);return B?G.set(O9,B):G.delete(O9),z?G.set(Db,z):G.delete(Db),V?G.set(k9,V):G.delete(k9),G.delete(Ev),G.delete(Tv),G},{replace:!0})},[t]),_=g.useCallback(()=>k(""),[k]),C=g.useCallback(B=>{const z=e.get(Db)||null;B!==z&&t(V=>{const M=new URLSearchParams(V);return B?M.set(Db,B):M.delete(Db),M.delete(Ev),M.delete(Tv),M},{replace:!0})},[e,t]),T=g.useCallback(()=>C(null),[C]),E=g.useCallback(B=>{const z=e.get(Ev)||null;B!==z&&t(V=>{const M=new URLSearchParams(V);return B&&B!=="details"?M.set(Ev,B):M.delete(Ev),M.delete(Tv),M},{replace:!0})},[e,t]),N=g.useCallback((B,z)=>{const V=z&&z!=="details"?z:null;B===(e.get(Db)||null)&&V===(e.get(Ev)||null)&&!e.get(Tv)||t(G=>{const U=new URLSearchParams(G);return U.set(Db,B),V?U.set(Ev,V):U.delete(Ev),U.delete(Tv),U},{replace:!0})},[e,t]),I=g.useCallback(B=>{const z=e.get(Tv)||null;B!==z&&t(V=>{const M=new URLSearchParams(V);return B?M.set(Tv,B):M.delete(Tv),M},{replace:!0})},[e,t]),A=g.useCallback(B=>{t(z=>{const V=new URLSearchParams(z);return Fds(V,B),SP(V),V},{replace:!0})},[t]),R=A,L=g.useCallback((B,z)=>{if(u.current!=="custom")return;const V=z==="from"?Lw:Fw;t(M=>{const G=new URLSearchParams(M);return B?G.set(V,B.toISOString()):G.delete(V),SP(G),G},{replace:!0})},[t]),D=g.useCallback(B=>{u.current=B,t(z=>{const V=new URLSearchParams(z);return B==="last-24h"?(V.delete(Dw),V.delete(Lw),V.delete(Fw)):B==="custom"?V.set(Dw,"custom"):(V.set(Dw,B),V.delete(Lw),V.delete(Fw)),SP(V),V},{replace:!0})},[t]),F=g.useCallback(B=>{t(z=>{const V=new URLSearchParams(z);return B==="traces"?V.delete(Mw):V.set(Mw,B),SP(V),V},{replace:!0})},[t]),H=g.useCallback(()=>{t(B=>{const z=new URLSearchParams(B);z.delete(Mw),z.delete(Gx),z.delete(Qx);for(const V of zL)z.delete(Ol[V]);return SP(z),z},{replace:!0}),r?.()},[t,r]);return{searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,traceIdParam:d,spanIdParam:f,anchorSpanIdParam:p,spanTabParam:m,scoreIdParam:v,listMode:y,selectedEntityOption:b,selectedStatus:x,filterTokens:S,handleTraceClick:k,handleTraceClose:_,handleSpanChange:C,handleSpanClose:T,handleSpanTabChange:E,handleSpanChangeWithTab:N,handleScoreChange:I,handleListModeChange:F,handleFilterTokensChange:R,handleDateChange:L,handleDatePresetChange:D,handleRemoveAll:H,applyFilterTokens:A}}function dA(e,t,n){const r=e.get(t);if(r!==void 0)return r;const s=n();return e.set(t,s),s}const $xe="mastra_model_total_input_tokens",Gqt="mastra_model_total_output_tokens",get=500;function Qds(e){const t=[];for(let n=0;n<e.length;n+=get)t.push(e.slice(n,n+get));return t}function Yds(){return{estimatedCost:0,hasEstimatedCost:!1,costUnits:new Set,hasUnknownCostUnit:!1}}function Kds(e,t){for(const n of t.groups){const r=n.dimensions.traceId,s=n.dimensions.name;if(!r||s!==$xe&&s!==Gqt)continue;const a=dA(e,r,Yds),i=s===$xe?"inputTokens":"outputTokens";a[i]=(a[i]??0)+n.value,n.estimatedCost!=null&&(a.estimatedCost+=n.estimatedCost,a.hasEstimatedCost=!0,n.costUnit?a.costUnits.add(n.costUnit.toLowerCase()):a.hasUnknownCostUnit=!0)}}function Xds(e){const t=new Map;for(const[n,r]of e){const s={inputTokens:r.inputTokens,outputTokens:r.outputTokens};r.hasEstimatedCost&&!r.hasUnknownCostUnit&&r.costUnits.size===1&&(s.estimatedCost=r.estimatedCost,s.costUnit=[...r.costUnits][0]),t.set(n,s)}return t}function vet({traceIds:e,enabled:t,autoRefetch:n}){const r=Qe(),s=[...new Set(e)].toSorted(),i=`${r.options.baseUrl||(typeof window>"u"?"local":window.location.origin||"local")}:${r.options.apiPrefix??"/api"}`;return yt({queryKey:["trace-usage",i,s],enabled:t&&s.length>0,queryFn:async()=>{const l=Qds(s),c=await Promise.allSettled(l.map(d=>r.getMetricBreakdown({name:[$xe,Gqt],aggregation:"sum",groupBy:["traceId","name"],filters:{traceIds:d},limit:d.length*2}))),u=new Map;for(const d of c)d.status==="fulfilled"&&Kds(u,d.value);return Xds(u)},placeholderData:(l,c)=>c?.queryKey[1]===i?l:void 0,refetchInterval:t&&n?1e4:!1})}const Jds=new Set(["ObservabilityStorageClickhouseVNext","ObservabilityStorageDuckDB","ObservabilityInMemory","ObservabilitySpanner","ObservabilityStoragePostgresVNext"]),Qqt=()=>{const{data:e,isLoading:t}=H4(),n=e?.observabilityStorageType;return{supportsMetrics:e?.observabilityStorageCapabilities?.metrics??(n?Jds.has(n):!1),isInMemory:n==="ObservabilityInMemory",isLoading:t}};function efs(e){return e.startsWith("agent-")}function tfs(e){return e.match(/^(?:mcp_)?tool:\s*'(.*?)'/)?.[1]??e}function Yqt(e){return Kqt(e,[])}function Kqt(e,t){if(!e)return t;for(const n of e){const r=n.stepType==="tool_call"||n.stepType==="mcp_tool_call";if(r&&n.name){const s=tfs(n.name),a="toolArgs"in n?n.toolArgs:void 0,i="toolResult"in n?n.toolResult:void 0;t.push({toolName:s,args:a??{},output:i??null,...efs(s)?{matchArgs:"ignore"}:{}})}!r&&n.children?.length&&Kqt(n.children,t)}return t}function nfs(e){const t=(()=>{try{const r=JSON.stringify(e.input);return r?r.length>40?`${r.slice(0,40)}…`:r:""}catch{return""}})(),n=dS(e.id)??e.id;return t?`${n} — ${t}`:n}function rfs({traceId:e,isOpen:t,onClose:n,level:r=2}){const s=Qe(),{data:a,isLoading:i}=yt({queryKey:["trace-trajectory",e],queryFn:()=>s.getTraceTrajectory(e),enabled:t&&!!e}),l=a?.steps?Yqt(a.steps):[],c=l.length>0?dO(l,2):"";return o.jsxs(Sa,{dialogTitle:"Add Tool Mocks to Item",dialogDescription:"Append trace-derived tool mocks to an existing dataset item",isOpen:t,onClose:n,level:r,children:[o.jsxs(Sa.Top,{children:[o.jsxs(Nl,{children:[o.jsx(ec,{})," ",dS(e)]}),"›",o.jsxs(Nl,{children:[o.jsx(Ud,{})," Add Tool Mocks to Item"]})]}),o.jsxs(Sa.Content,{children:[o.jsx(Sa.Header,{children:o.jsxs(Sa.Heading,{children:[o.jsx(Ud,{})," Add Tool Mocks to Item"]})}),i?o.jsx("div",{className:"text-neutral4 px-2 py-4 text-sm",children:"Loading tool calls from trace..."}):o.jsx(sfs,{initialMocksJson:c,onClose:n},e??"no-trace")]})]})}function sfs({initialMocksJson:e,onClose:t}){const[n,r]=g.useState(""),[s,a]=g.useState(""),[i,l]=g.useState(e),{data:c,isLoading:u}=Im(),d=c?.datasets??[],{data:f=[],isLoading:p}=Zx(n),{data:h,isFetching:m}=FD(n,s),{updateItem:v}=qi(),y=(()=>{if(!i.trim())return!1;try{const S=JSON.parse(i);return Array.isArray(S)&&S.length>0}catch{return!1}})(),b=S=>{r(S),a("")},x=async S=>{if(S.preventDefault(),!n||!s){Be.error("Please select a dataset and an item");return}let k;try{const T=i.trim()?JSON.parse(i):[];if(!Array.isArray(T)){Be.error("Tool Mocks must be a JSON array");return}k=T}catch{Be.error("Tool Mocks must be valid JSON");return}if(k.length===0){Be.error("There are no tool mocks to add");return}if(!h||h.id!==s){Be.error("Item is still loading, please try again");return}const C=[...h.toolMocks??[],...k];try{await v.mutateAsync({datasetId:n,itemId:s,toolMocks:C}),Be.success(`Added ${k.length} tool mock(s) to the item`),t()}catch(T){Be.error(`Failed to add tool mocks: ${T instanceof Error?T.message:"Unknown error"}`)}};return o.jsxs("form",{onSubmit:x,className:"grid gap-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{htmlFor:"target-dataset",children:"Dataset *"}),o.jsxs(ha,{value:n,onValueChange:b,disabled:u,children:[o.jsx(ga,{id:"target-dataset",children:o.jsx(ma,{placeholder:u?"Loading datasets...":"Select a dataset"})}),o.jsx(va,{children:d.length===0?o.jsx("div",{className:"text-neutral4 px-2 py-4 text-center text-sm",children:"No datasets available"}):d.map(S=>o.jsx(Nr,{value:S.id,children:S.name},S.id))})]})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{htmlFor:"target-item",children:"Item *"}),o.jsxs(ha,{value:s,onValueChange:a,disabled:!n||p,children:[o.jsx(ga,{id:"target-item",children:o.jsx(ma,{placeholder:n?p?"Loading items...":"Select an item":"Select a dataset first"})}),o.jsx(va,{children:f.length===0?o.jsx("div",{className:"text-neutral4 px-2 py-4 text-center text-sm",children:"No items available"}):f.map(S=>o.jsx(Nr,{value:S.id,children:nfs(S)},S.id))})]})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{htmlFor:"derived-mocks",children:"Tool Mocks (JSON)"}),o.jsx(Zr,{value:i,onChange:l,showCopyButton:!1,className:"min-h-[160px]"}),o.jsx("p",{className:"text-neutral4 text-xs",children:"Seeded from the trace's tool calls. Edit or remove entries before appending."})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(oe,{type:"button",variant:"outline",onClick:t,children:"Cancel"}),o.jsx(oe,{type:"submit",variant:"default",disabled:v.isPending||m||!y||!n||!s||h?.id!==s,children:v.isPending?"Adding...":"Append Tool Mocks"})]})]})}function afs(e){if(e?.input==null)return"{}";const t=e.input,r=e.spanType==="agent_run"&&t&&typeof t=="object"&&!Array.isArray(t)&&"messages"in t?t.messages??e.input:e.input;return dO(r,2)}function ifs({traceDetails:e,rootSpanId:t,traceId:n,isOpen:r,onClose:s,level:a=2}){const i=Qe(),{data:l}=_Q(!e&&r?n:null,!e&&r?t:null),c=e??l?.span,{data:u,isLoading:d}=yt({queryKey:["trace-trajectory",n],queryFn:()=>i.getTraceTrajectory(n),enabled:r&&!!n}),f=u?.steps&&u.steps.length>0?dO({steps:u.steps.map(m=>{const{name:v,stepType:y,children:b,...x}=m,S={name:v,stepType:y};for(const[k,_]of Object.entries(x))_!=null&&k!=="durationMs"&&k!=="metadata"&&(S[k]=_);return S}),ordering:"relaxed"},2):void 0,p=u?.steps?Yqt(u.steps):[],h=p.length>0?dO(p,2):void 0;return o.jsx(W3t,{initialInput:afs(c),initialGroundTruth:c?.output!=null?dO(c.output,2):"",initialTrajectory:f,trajectoryLoading:d,initialToolMocks:h,breadcrumb:o.jsxs(Nl,{children:[o.jsx(ec,{})," ",dS(n)]}),isOpen:r,onClose:s,level:a,source:n?{type:"trace",referenceId:n}:void 0})}const Xqt=({traceId:e,spanId:t})=>{const n=Qe(),r=Lr();return An({mutationFn:({text:s})=>n.createFeedback({feedback:{traceId:e,...t?{spanId:t}:{},feedbackType:"comment",feedbackSource:"user",value:s}}),onSuccess:()=>r.invalidateQueries({queryKey:t?["span-feedback",e,t]:["trace-feedback",e]})})},ofs=3e3;function Jqt(e){return R4(e.state.error,"feedback")||P4(e.state.error)?!1:ofs}const eVt=({traceId:e="",page:t})=>{const n=Qe(),r=t??0;return yt({queryKey:["trace-feedback",e,r],queryFn:()=>n.listFeedback({filters:{traceId:e},pagination:{page:r,perPage:10}}),enabled:!!e,select:s=>{const a=s.feedback.filter(i=>!i.spanId);return s.pagination?{...s,feedback:a,pagination:{...s.pagination,total:a.length}}:{...s,feedback:a}},refetchInterval:Jqt,gcTime:0,staleTime:0})},tVt=({traceId:e="",spanId:t="",page:n})=>{const r=Qe(),s=n??0;return yt({queryKey:["span-feedback",e,t,s],queryFn:()=>r.listFeedback({filters:{traceId:e,spanId:t},pagination:{page:s,perPage:10}}),enabled:!!e&&!!t,refetchInterval:Jqt,gcTime:0,staleTime:0})},nVt=g.createContext(null);function BQ(){const e=g.useContext(nVt);if(!e)throw new Error("Comment compounds must be rendered within Comment");return e}const lfs=Ii("flex flex-col",{variants:{variant:{default:"gap-2",embed:"gap-1 rounded-xl border border-border1 bg-surface3 p-3"}},defaultVariants:{variant:"default"}}),rVt=g.forwardRef(({className:e,variant:t="default",...n},r)=>o.jsx(nVt.Provider,{value:t,children:o.jsx("div",{ref:r,"data-slot":"comment","data-variant":t,className:K(lfs({variant:t}),e),...n})}));rVt.displayName="Comment";const cfs={default:"gap-3",embed:"gap-2"},sVt=g.forwardRef(({className:e,...t},n)=>{const r=BQ();return o.jsx("ul",{ref:n,"data-slot":"comment-list",className:K("flex flex-col",cfs[r],e),...t})});sVt.displayName="CommentList";const aVt=g.forwardRef(({className:e,...t},n)=>o.jsx("li",{ref:n,"data-slot":"comment-item",className:K("group/comment-item flex flex-col gap-1",e),...t}));aVt.displayName="CommentItem";const iVt=g.forwardRef(({className:e,...t},n)=>o.jsx("div",{ref:n,"data-slot":"comment-item-header",className:K("flex items-center gap-2",e),...t}));iVt.displayName="CommentItemHeader";const ufs=g.forwardRef(({className:e,...t},n)=>o.jsx(me,{ref:n,as:"span",variant:"ui-md","data-slot":"comment-item-author",className:K("font-medium text-neutral6",e),...t}));ufs.displayName="CommentItemAuthor";const oVt=g.forwardRef(({className:e,...t},n)=>o.jsx("time",{ref:n,"data-slot":"comment-item-timestamp",className:K("text-ui-sm leading-ui-sm text-neutral3",e),...t}));oVt.displayName="CommentItemTimestamp";const dfs={default:"border-l border-border1 pl-3",embed:""},lVt=g.forwardRef(({className:e,...t},n)=>{const r=BQ();return o.jsx(me,{ref:n,variant:"ui-md","data-slot":"comment-item-body",className:K("whitespace-pre-wrap text-neutral6",dfs[r],e),...t})});lVt.displayName="CommentItemBody";const ffs=g.forwardRef(({className:e,...t},n)=>BQ()==="embed"?null:o.jsx("div",{ref:n,"data-slot":"comment-item-actions",className:K("flex items-center gap-1 opacity-0 group-focus-within/comment-item:opacity-100 group-hover/comment-item:opacity-100","motion-safe:transition-opacity",e),...t}));ffs.displayName="CommentItemActions";const cVt=g.forwardRef(({className:e,...t},n)=>o.jsx("form",{ref:n,"data-slot":"comment-composer",className:K("flex w-full items-center gap-2",e),...t}));cVt.displayName="CommentComposer";const pfs={default:"md",embed:"sm"},hfs={default:"outline",embed:"default"},uVt=g.forwardRef(({groupClassName:e,children:t,...n},r)=>{const s=BQ();return o.jsxs(uu,{size:pfs[s],variant:hfs[s],className:e,children:[o.jsx(du,{ref:r,"data-slot":"comment-composer-input",...n}),t]})});uVt.displayName="CommentComposerInput";const dVt=g.forwardRef(({"aria-label":e="Send comment",type:t="submit",...n},r)=>o.jsx(Nc,{align:"inline-end",children:o.jsx(OTe,{ref:r,"data-slot":"comment-composer-send",type:t,"aria-label":e,...n,children:o.jsx(q1,{})})}));dVt.displayName="CommentComposerSend";function mfs(e){const t=e.comment||(typeof e.value=="string"?e.value:"");return t||(e.feedbackType==="thumbs"?e.value===1?"👍":"👎":String(e.value??""))}function fVt({feedbackData:e,isLoadingFeedbackData:t,onPageChange:n,onSubmit:r,isSubmitting:s=!1}){const[a,i]=g.useState(""),l=a.trim().length===0||s,c=e?.feedback??[],u=e?.pagination?.page??0,d=e?.pagination?.hasMore??!1;return o.jsxs(rVt,{className:"min-h-0 gap-4 px-3",children:[o.jsx("div",{className:"min-h-0 overflow-y-auto",children:t?o.jsx(me,{variant:"ui-md",className:"text-neutral3",children:"Loading feedback..."}):c.length===0?o.jsx(me,{variant:"ui-md",className:"text-neutral3",children:"No feedback yet"}):o.jsx(sVt,{children:c.map((f,p)=>{const h=new Date(f.timestamp);return o.jsxs(aVt,{children:[o.jsx(iVt,{children:o.jsx(oVt,{dateTime:h.toISOString(),children:hr(h,"MMM d, h:mm:ss aaa")})}),o.jsx(lVt,{children:mfs(f)})]},`${f.traceId}-${p}`)})})}),(d||u>0)&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(oe,{size:"sm",variant:"ghost",disabled:u===0,onClick:()=>n?.(u-1),children:"Previous"}),o.jsx(oe,{size:"sm",variant:"ghost",disabled:!d,onClick:()=>n?.(u+1),children:"Next"})]}),o.jsx(cVt,{"aria-label":"Leave feedback",onSubmit:async f=>{if(f.preventDefault(),!l)try{await r(a.trim()),i("")}catch{}},children:o.jsx(uVt,{"aria-label":"Leave feedback",placeholder:"Leave feedback...",value:a,onChange:f=>i(f.target.value),children:o.jsx(dVt,{"aria-label":"Send feedback",disabled:l})})})]})}function gfs({traceId:e,spanId:t}){const[n,r]=g.useState(0),{data:s,isLoading:a}=tVt({traceId:e,spanId:t,page:n}),{mutateAsync:i,isPending:l}=Xqt({traceId:e,spanId:t});return o.jsx(fVt,{feedbackData:s,isLoadingFeedbackData:a,onPageChange:r,onSubmit:c=>i({text:c}),isSubmitting:l})}function vfs({traceId:e}){const[t,n]=g.useState(0),{data:r,isLoading:s}=eVt({traceId:e,page:t}),{mutateAsync:a,isPending:i}=Xqt({traceId:e});return o.jsx(fVt,{feedbackData:r,isLoadingFeedbackData:s,onPageChange:n,onSubmit:l=>a({text:l}),isSubmitting:i})}const yet="auto auto auto auto 1fr";function yfs({scoresData:e,isLoadingScoresData:t,onPageChange:n,onScoreSelect:r}){const{containerRef:s,getRowProps:a}=wo({count:e?.scores?.length??0});return t?o.jsx(Pl,{columns:yet}):!e?.scores||e.scores.length===0?o.jsx(Er,{iconSlot:o.jsx(Rlt,{}),titleSlot:"No scores yet",descriptionSlot:"Score this trace to see results here."}):o.jsxs("div",{className:"grid gap-2",children:[o.jsxs(be,{columns:yet,className:"min-w-0",scrollRef:s,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"ID"}),o.jsx(be.TopCell,{children:"Date"}),o.jsx(be.TopCell,{children:"Time"}),o.jsx(be.TopCell,{children:"Score"}),o.jsx(be.TopCell,{children:"Scorer"})]}),e.scores.map((i,l)=>{const c=new Date(i.createdAt),u=$3(c);return o.jsxs(be.RowButton,{onClick:()=>r?.(i),...a(l),children:[o.jsx(be.Cell,{className:"text-neutral3 text-ui-smd font-mono",children:dS(i?.id)||"n/a"}),o.jsx(be.Cell,{className:"text-neutral2 text-ui-smd",children:u?"Today":hr(c,"MMM dd")}),o.jsx(be.Cell,{className:"text-neutral3 text-ui-smd font-mono",children:hr(c,"h:mm:ss aaa")}),o.jsx(be.Cell,{className:"text-ui-smd",children:String(i?.score??"")}),o.jsx(be.Cell,{className:"text-ui-smd",children:String(i?.scorer?.name||i?.scorer?.id||"")})]},i.id)})]}),o.jsx(be.Pagination,{currentPage:e?.pagination?.page||0,hasMore:e?.pagination?.hasMore,onNextPage:()=>n?.((e?.pagination?.page||0)+1),onPrevPage:()=>n?.((e?.pagination?.page||0)-1)})]})}const bfs=()=>{const e=Qe();return An({mutationFn:async({scorerName:t,traceId:n,spanId:r})=>await e.score({scorerName:t,targets:[{traceId:n,spanId:r}]})})};function xfs({traceId:e,spanId:t,entityType:n,isTopLevelSpan:r,scorers:s,isLoadingScorers:a}){const[i,l]=g.useState(null),{mutate:c,isPending:u}=bfs();let d=Object.entries(s||{}).map(([m,v])=>({id:m,name:v.scorer.config.name,description:v.scorer.config.description,isRegistered:v.isRegistered,type:v.scorer.config.type})).filter(m=>m.isRegistered);(n!=="Agent"||!r)&&(d=d.filter(m=>m.type!=="agent"));const f=u||a,p=()=>{i&&e&&c({scorerName:i,traceId:e,spanId:t},{onSuccess:()=>Be.info("Scorer triggered",{description:"Results will appear once scoring completes."})})},h=d.find(m=>m.id===i)?.description||"";return s===void 0&&!a?o.jsx(Wn,{variant:"destructive",children:"Failed to load scorers."}):!a&&d.length===0?o.jsx(Wn,{variant:"info",children:"No eligible scorers have been defined to run."}):o.jsxs("div",{className:"grid grid-cols-[3fr_1fr] items-start gap-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Pc,{name:"select-scorer",label:"Select scorer",labelIsHidden:!0,placeholder:"Select a scorer...",options:d.map(m=>({label:m.name||m.id,value:m.id||m.name||""})),onValueChange:l,value:i||"",className:"min-w-80",disabled:f}),h&&o.jsxs(Nl,{className:"text-neutral3 text-ui-sm",children:[o.jsx(km,{})," ",h]})]}),o.jsx(oe,{disabled:!i||f,onClick:p,children:u?"Starting...":"Start Scoring"})]})}function wfs(e){const t=[...e].sort((s,a)=>new Date(s.createdAt).getTime()-new Date(a.createdAt).getTime()),n=[];return{data:t.map(s=>{const a=String(s.scorer?.name||s.scorer?.id||"unknown");return n.includes(a)||n.push(a),{time:hr(new Date(s.createdAt),"h:mm:ss aaa"),[a]:s.score}}),scorerNames:n}}const bet=["#22c55e","#4f83f1","#8b5cf6","#fb923c","#f472b6","#facc15"];function Sfs({scoresData:e,className:t}){const{data:n,scorerNames:r}=g.useMemo(()=>wfs(e?.scores??[]),[e?.scores]),s=g.useMemo(()=>r.map((a,i)=>({dataKey:a,label:a,color:bet[i%bet.length],aggregate:l=>{const c=l.map(u=>u[a]).filter(u=>typeof u=="number");return{value:c.length>0?(c.reduce((u,d)=>u+d,0)/c.length).toFixed(2):"0",suffix:"avg"}}})),[r]);return n.length===0?null:o.jsx(Yu,{appearance:"surface",className:t,children:o.jsx(Ag,{children:o.jsx(OD,{data:n,series:s,height:90,yDomain:[0,1],xAxisInterval:"preserveStartEnd",xAxisMinTickGap:40,showDots:!0})})})}function kfs({traceId:e,spanId:t,isTopLevelSpan:n,entityType:r,onScoreSelect:s}){const[a,i]=g.useState(0),{data:l,isLoading:c}=c4t({traceId:e,spanId:t,page:a}),{data:u,isLoading:d}=oh();return o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_auto_1fr] gap-6",children:[o.jsx(xfs,{traceId:e,isTopLevelSpan:n,spanId:t,entityType:r,scorers:u,isLoadingScorers:d}),o.jsx(Sfs,{scoresData:l,className:"min-h-0 w-full"}),o.jsx(Yu,{appearance:"surface",className:"min-h-0 w-full overflow-hidden",children:o.jsx(Ag,{className:"h-full overflow-y-auto",children:o.jsx(yfs,{scoresData:l,onPageChange:i,isLoadingScoresData:c,onScoreSelect:f=>s(f.id)})})})]})}function pVt({scopedEntityId:e,scopedEntityType:t}={}){const n=!!e,[r,s]=hi(),a=Gds(r,s);g.useEffect(()=>{if(!e)return;const Re=r.get("rootEntityType"),Ge=r.get("filterEntityId");!(t&&Re!==t)&&!(Ge!==e)||s($e=>{const ye=new URLSearchParams($e);return t&&ye.set("rootEntityType",t),ye.set("filterEntityId",e),ye},{replace:!0})},[e,t,r,s]);const i=g.useMemo(()=>n?["rootEntityType","entityId"]:[],[n]),l=g.useMemo(()=>n?["rootEntityType","entityId","entityName"]:[],[n]),c=n?"This filter is scoped to the current agent. Open the global Traces view to change it.":void 0,[u,d]=g.useState(),[f,p]=g.useState(!1),[h,m]=g.useState(!1),[v,y]=g.useState(null),[b,x]=g.useState(null),{data:S}=eVt({traceId:a.traceIdParam}),{data:k}=tVt({traceId:a.traceIdParam,spanId:a.spanIdParam}),{spans:_,anchorSpanId:C,isLoading:T}=KUt({traceId:a.traceIdParam??null,anchorSpanId:a.listMode==="branches"?a.anchorSpanIdParam??null:null,listMode:a.listMode}),E=g.useMemo(()=>C?_?.find(Re=>Re.spanId===C):_?.find(Re=>Re.parentSpanId==null),[_,C]),{data:N}=c4t({traceId:a.traceIdParam,spanId:E?.spanId}),I=E?.entityType==="agent"?"Agent":E?.entityType==="workflow_run"?"Workflow":void 0,A=a.scoreIdParam?N?.scores?.find(Re=>Re.id===a.scoreIdParam):void 0,{data:R=[],isPending:L}=RAe(),{data:D=[],isPending:F}=NAe({entityType:a.selectedEntityOption?.entityType,rootOnly:!0}),{data:H=[],isPending:B}=IAe(),{data:z=[],isPending:V}=AAe(),M=g.useMemo(()=>Mds({availableTags:R,availableRootEntityNames:D,availableServiceNames:z,availableEnvironments:H,loading:{tags:L,entityNames:F,serviceNames:V,environments:B}}),[R,D,z,H,L,F,V,B]),G=g.useMemo(()=>zds({rootEntityType:a.selectedEntityOption?.entityType,status:a.selectedStatus,dateFrom:a.selectedDateFrom,dateTo:a.selectedDateTo,tokens:a.filterTokens}),[a.filterTokens,a.selectedDateFrom,a.selectedDateTo,a.selectedEntityOption,a.selectedStatus]),{data:U,isLoading:$,isFetchingNextPage:q,hasNextPage:Z,setEndOfListElement:Y,error:ne,autoRefetch:J,setAutoRefetch:ee,recentlyAddedKeys:re}=XUt({filters:G,listMode:a.listMode}),le=g.useMemo(()=>U?.spans??[],[U?.spans]),X=qds(),te=Qqt(),se=a.listMode==="branches"?"Token and cost totals are only available for full traces.":te.isLoading?"Checking whether this storage supports usage data.":te.supportsMetrics?void 0:"This observability store does not support token and cost metrics.",pe=a.listMode==="branches"||!te.isLoading&&!te.supportsMetrics,ce=pe?{...X.preferences,visibleColumns:X.preferences.visibleColumns.filter(Re=>!WUt(Re))}:X.preferences,Se=!pe&&!te.isLoading&&Dcs(ce),ve=vet({traceIds:le.map(Re=>Re.traceId),enabled:Se,autoRefetch:J}),ke=Se&&le.some(Re=>Re.traceId===a.traceIdParam),Ne=vet({traceIds:a.traceIdParam?[a.traceIdParam]:[],enabled:Se&&!ke,autoRefetch:J}),Me=a.traceIdParam?ve.data?.get(a.traceIdParam)??Ne.data?.get(a.traceIdParam):void 0;g.useEffect(()=>{!ne||f||eQe(ne)&&(p(!0),a.listMode==="branches"&&a.handleListModeChange("traces"))},[ne,f,a]);const Ae=Wds(r,s,{storageKey:n?`mastra:traces:saved-filters:${t}:${e}`:void 0}),Ie=g.useCallback(()=>a.applyFilterTokens(Bds(M,a.filterTokens)),[M,a]),ae=g.useCallback((Re,Ge)=>{a.listMode==="branches"?a.handleTraceClick(Re,Ge,Ge):a.handleTraceClick(Re)},[a]),{handlePreviousTrace:fe,handleNextTrace:ue}=QUt(le,a.traceIdParam,a.listMode==="branches"?a.anchorSpanIdParam:null,ae),we=E?.entityType==="agent",Ee=!!a.selectedEntityOption||!!a.selectedStatus||a.filterTokens.length>0||a.datePreset!=="last-24h"||!!a.selectedDateTo,ge=o.jsxs(o.Fragment,{children:[o.jsx(I4,{preset:a.datePreset,onPresetChange:a.handleDatePresetChange,dateFrom:a.selectedDateFrom,dateTo:a.selectedDateTo,onDateChange:a.handleDateChange,disabled:$,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),o.jsx(EAe,{fields:M,tokens:a.filterTokens,onTokensChange:a.handleFilterTokensChange,disabled:$,onStartTextFilter:d,hiddenFieldIds:l}),o.jsxs("div",{className:"min-h-form-default ml-auto flex max-w-full flex-wrap items-center justify-end gap-2",children:[o.jsx(_ds,{preferences:X.preferences,usageDisabledReason:se,onToggleColumn:X.toggleColumn,onAddMetadataColumn:X.addMetadataColumn,onRemoveMetadataColumn:X.removeMetadataColumn,onReset:X.resetColumns}),!f&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(So,{id:"show-subtraces",checked:a.listMode==="branches",onCheckedChange:Re=>a.handleListModeChange(Re===!0?"branches":"traces"),disabled:$}),o.jsx(Mt,{htmlFor:"show-subtraces",children:"Subtraces"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(So,{id:"auto-refetch",checked:J,onCheckedChange:Re=>ee(Re===!0),disabled:$}),o.jsx(Mt,{htmlFor:"auto-refetch",children:"Auto refresh"})]})]})]}),Ce=f&&!h?o.jsx(Wn,{variant:"info",action:o.jsx(Wn.Button,{variant:"ghost",onClick:()=>m(!0),children:"Dismiss"}),className:"mb-4",children:o.jsx(Wn.Message,{children:"Selected list mode isn't supported by this storage provider — switched to default."})}):null,Ue=o.jsxs(Vt.TopArea,{children:[o.jsx(Vt.Row,{children:o.jsx(Vt.Column,{className:"flex w-full flex-wrap items-start justify-start gap-2",children:ge})}),o.jsx(Eds,{isLoading:$,filterFields:M,filterTokens:a.filterTokens,onFilterTokensChange:a.handleFilterTokensChange,onClear:Ie,onRemoveAll:a.handleRemoveAll,onSave:Ae.handleSave,onRemoveSaved:Ae.hasSavedFilters?Ae.handleRemoveSaved:void 0,autoFocusFilterFieldId:u,lockedFieldIds:i,lockedTooltipContent:c}),Ce]});if(ne&&!eQe(ne))return o.jsxs(Vt,{width:"wide",height:"full",children:[Ue,o.jsx(Vt.MainArea,{isCentered:!0,children:o.jsx(BUt,{error:ne,resource:"traces",errorTitle:"Failed to load traces"})})]});const Fe=!!a.selectedEntityOption||!!a.selectedStatus||a.filterTokens.length>0;return le.length===0&&!$&&!Fe&&!a.traceIdParam?o.jsxs(Vt,{width:"wide",height:"full",children:[Ue,o.jsx(Vt.MainArea,{isCentered:!0,children:o.jsx(kds,{datePreset:a.datePreset,dateFrom:a.selectedDateFrom,dateTo:a.selectedDateTo})})]}):o.jsxs(Vt,{width:"wide",height:"full",children:[Ue,o.jsx(Cds,{sidePanelWide:!!a.spanIdParam,listSlot:o.jsx(GUt,{traces:le,isLoading:$,isFetchingNextPage:q,hasNextPage:Z,setEndOfListElement:Y,filtersApplied:Ee,featuredTraceId:a.traceIdParam,featuredSpanId:a.listMode==="branches"?a.anchorSpanIdParam:null,isBranchesMode:a.listMode==="branches",recentlyAddedKeys:re,columnPreferences:ce,usageByTraceId:ve.data,onTraceClick:Re=>{const Ge=a.listMode==="branches";if(Ge?a.traceIdParam===Re.traceId&&a.anchorSpanIdParam===Re.spanId:a.traceIdParam===Re.traceId){a.handleTraceClick("");return}const mt=Ge?Re.spanId??void 0:void 0;a.handleTraceClick(Re.traceId,mt,mt)}},a.listMode),tracePanelSlot:a.traceIdParam&&(a.listMode!=="branches"||a.anchorSpanIdParam)?o.jsx(cqt,{traceId:a.traceIdParam,spans:_,anchorSpanId:C,usage:Me,isLoadingSpans:T,selectedSpanId:a.spanIdParam??null,onClose:a.handleTraceClose,onSpanSelect:Re=>a.handleSpanChange(Re??null),onSpanClose:a.handleSpanClose,onSaveAsDatasetItem:Re=>y(Re),onAddTraceMocksToItem:we?Re=>x(Re):void 0,initialSpanId:a.spanIdParam,onPrevious:fe,onNext:ue,feedbackTabBadge:S?.pagination?.total??void 0,feedbackTabSlot:({traceId:Re})=>o.jsx(vfs,{traceId:Re}),scoresTabBadge:N?.pagination?.total??void 0,scoresTabSlot:({traceId:Re,rootSpanId:Ge})=>Ge?o.jsx(kfs,{traceId:Re,spanId:Ge,isTopLevelSpan:!E?.parentSpanId,entityType:I,onScoreSelect:a.handleScoreChange}):null,spanActiveTab:a.spanTabParam??"details",onSpanTabChange:Re=>a.handleSpanTabChange(Re),spanFeedbackTabBadge:k?.pagination?.total??void 0,spanFeedbackTabSlot:({traceId:Re,spanId:Ge})=>Re&&Ge?o.jsx(gfs,{traceId:Re,spanId:Ge},`${Re}:${Ge}`):null,spanPanelClassName:"rounded-none border-0 bg-transparent"},`${a.traceIdParam}:${a.anchorSpanIdParam??""}`):null,scorePanelSlot:A?o.jsx(Z3t,{score:A,onClose:()=>a.handleScoreChange(null)}):null}),o.jsx(ifs,{rootSpanId:v?.rootSpanId,traceId:v?.traceId,isOpen:!!v,onClose:()=>y(null)}),o.jsx(rfs,{traceId:b?.traceId,isOpen:!!b,onClose:()=>x(null)})]})}function Ofs(){const{agentId:e}=mr();return e?o.jsx(pVt,{scopedEntityId:e,scopedEntityType:Ku.AGENT}):null}function _fs(){return o.jsx(aas,{})}function Cfs(){const{navigate:e,paths:t}=cn(),n=zo(),{form:r,handlePublish:s,isSubmitting:a,canPublish:i}=wQ({mode:"create",onSuccess:l=>e(t.agentLink(l))});return o.jsxs(_s,{children:[o.jsx($y,{owner:"cms-agent-create",children:o.jsx(oe,{variant:"primary",onClick:()=>{s()},disabled:a||!i,children:a?o.jsxs(o.Fragment,{children:[o.jsx(Ut,{className:"h-4 w-4"}),"Creating..."]}):o.jsxs(o.Fragment,{children:[o.jsx(He,{children:o.jsx(Qr,{})}),"Create agent"]})})}),o.jsx(JBt,{form:r,mode:"create",isSubmitting:a,handlePublish:s,basePath:"/cms/agents/create",currentPath:n.pathname,children:o.jsx(Fg,{})})]})}function xet({agentId:e,selectedVersionId:t,versionData:n,readOnly:r=!1,form:s,handlePublish:a,handleSaveDraft:i,isSubmitting:l,isSavingDraft:c,onVersionSelect:u,activeVersionId:d,latestVersionId:f,hideVersionPanel:p=!1,isCodeAgentOverride:h=!1,isCodeSourceAgent:m=!1,editorConfig:v}){const[,y]=hi(),{pathname:b}=zo(),k=!!t&&!!n&&t!==f?o.jsxs(Wn,{variant:"info",title:"This is a previous version",className:"mb-4",children:[o.jsx(Wn.Message,{children:"You are seeing a specific version of the agent."}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(oe,{type:"button",variant:"default",size:"sm",onClick:()=>y({}),children:"View latest version"}),o.jsx(oe,{type:"button",variant:"default",size:"sm",onClick:()=>{a(t??void 0)},disabled:t===d,children:"Publish This Version"})]})]}):void 0,_=p?void 0:o.jsx(Zas,{agentId:e,selectedVersionId:t??void 0,onVersionSelect:u,activeVersionId:d}),C=kC(h,v).isFullyLocked;return o.jsx(JBt,{form:s,mode:"edit",agentId:e,isSubmitting:l,isSavingDraft:c,handlePublish:a,handleSaveDraft:i,readOnly:r,isCodeAgentOverride:h,isCodeSourceAgent:m,editorConfig:v,basePath:`/cms/agents/${e}/edit`,currentPath:b,banner:k,versionId:t??void 0,rightPanel:_,children:C?o.jsx("div",{className:"p-6",children:o.jsx(Wn,{variant:"info",title:"Editing disabled",children:o.jsx(Wn.Message,{children:"This code-defined agent has disabled Studio editing."})})}):o.jsx(Fg,{})})}function Efs(){const{agentId:e}=mr(),{navigate:t,paths:n}=cn(),r=es(),{hash:s,pathname:a,search:i}=zo(),[l,c]=hi(),u=l.get("versionId"),{isMastraPlatform:d,mastraPlatformApiEndpoint:f,mastraPlatformProjectId:p}=CQ(),{data:h,isLoading:m}=Vl(e),{data:v}=vS({agentId:e,params:{orderBy:{direction:"DESC"}}}),y=(v?.versions?.length??0)>0,{data:b,isLoading:x}=A4(e,{status:"draft",enabled:y}),S=h?.source==="code",k=g.useMemo(()=>S?ZIe(h?.editor):[],[h?.editor,S]),_=b??null,C=m||y&&x,T=`/cms/agents/${e}/edit`,E=a===T||a===`${T}/`;g.useEffect(()=>{if(!S||k.length===0)return;const te=k.some(se=>a===`${T}${se.pathSuffix}`);(E||!te)&&r(`${T}${k[0].pathSuffix}${i}${s}`,{replace:!0})},[k,S,E,a,r,T,i,s]);const{data:N}=aBt({agentId:e??"",versionId:u??""}),I=_?.activeVersionId,A=v?.versions?.[0],R=!!(A&&A.id!==I),L=!!u&&!!N,D=L&&u!==A?.id,F=g.useMemo(()=>L&&N?N:_||(h?YIe(h):{}),[L,N,_,h]),{form:H,handlePublish:B,handleSaveDraft:z,handleDownloadJson:V,handleOpenPr:M,isSubmitting:G,isSavingDraft:U,isDirty:$}=wQ({mode:"edit",agentId:e??"",dataSource:F,isCodeAgentOverride:S,hasStoredOverride:S&&!!b,editorConfig:h?.editor,onSuccess:te=>t(n.agentLink(te))}),q=g.useCallback(async()=>{D&&u?await B(u):await B()},[B,D,u]),Z=g.useCallback(te=>{c(te?{versionId:te}:{})},[c]),Y=!C&&!_&&!h,ne=!C&&!!e&&(!!_||!!h),J=!kC(S,h?.editor).isFullyLocked,ee=pAe(),re=S&&ee==="code",le=J&&d&&!!f&&!!p,X=le?"Open a pull request with this agent override JSON":"Open PR is available on Mastra-hosted projects with GitHub App support";return o.jsxs(_s,{children:[ne&&o.jsx($y,{owner:"cms-agent-edit",children:o.jsxs("div",{className:"flex items-center gap-2",children:[R&&o.jsx(St,{variant:"blue",children:"Unpublished changes"}),re?J?o.jsxs(o.Fragment,{children:[o.jsxs(oe,{onClick:()=>{V()},disabled:U||G,children:[o.jsx(Pd,{}),"Download JSON"]}),o.jsxs(oe,{variant:"primary",disabled:!le||U||G,title:X,onClick:()=>{!f||!p||M({platformApiEndpoint:f,projectId:p})},children:[o.jsx(Flt,{}),"Open PR"]})]}):null:J?o.jsxs(o.Fragment,{children:[o.jsx(oe,{onClick:()=>{z()},disabled:!$||U||G,children:U?o.jsxs(o.Fragment,{children:[o.jsx(Ut,{className:"h-4 w-4"}),"Saving..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Gu,{}),"Save"]})}),o.jsx(oe,{variant:"primary",onClick:()=>{q()},disabled:D?u===I||G||U:!R||G||U,children:G?o.jsxs(o.Fragment,{children:[o.jsx(Ut,{className:"h-4 w-4"}),"Publishing..."]}):o.jsxs(o.Fragment,{children:[o.jsx(Qr,{}),D?"Publish This Version":"Publish"]})})]}):null]})}),Y?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"text-neutral3 flex h-full items-center justify-center",children:"Agent not found"}),o.jsx("div",{className:"hidden",children:o.jsx(xet,{agentId:e??"",selectedVersionId:u,versionData:N,readOnly:!0,form:H,handlePublish:B,handleSaveDraft:z,isSubmitting:G,isSavingDraft:U,onVersionSelect:Z,activeVersionId:I,latestVersionId:A?.id,editorConfig:void 0})})]}):o.jsx(xet,{agentId:e??"",selectedVersionId:u,versionData:N,readOnly:!J,form:H,handlePublish:B,handleSaveDraft:z,isSubmitting:G,isSavingDraft:U,onVersionSelect:Z,activeVersionId:I,latestVersionId:A?.id,hideVersionPanel:S&&!b,isCodeAgentOverride:S,isCodeSourceAgent:re,editorConfig:h?.editor})]})}function Tfs(){return o.jsx(Hss,{})}function jfs(){return o.jsx(EBt,{})}function Nfs(){return o.jsx(cas,{})}function Ifs(){return o.jsx(ias,{})}function Afs(){return o.jsx(Ras,{})}function Rfs(){return o.jsx(jBt,{})}function Pfs(){return o.jsx(vas,{})}function $fs(){return o.jsx(las,{})}function Mfs(){const{navigate:e,paths:t}=cn();return o.jsx(_s,{className:"grid-rows-[1fr]",children:o.jsx(bss,{onSuccess:n=>e(t.cmsPromptBlockEditLink(n.id))})})}function wet(e){return{name:e.name,description:e.description||void 0,content:e.content,rules:e.rules||void 0,requestContextSchema:e.variables||void 0}}function Dfs({block:e,blockId:t,selectedVersionId:n,hasDraft:r,latestVersionId:s,activeVersionId:a,onClearVersion:i}){const l=Qe(),c=Lr(),{navigate:u,paths:d}=cn(),{updateStoredPromptBlock:f}=gQ(t),[p,h]=g.useState(!1),[m,v]=g.useState(!1),{data:y}=xss({blockId:t,versionId:n??""}),b=!!n&&!!y,x=b&&n!==s,S=b?y:e,k=g.useMemo(()=>({name:S.name||"",description:S.description||"",content:S.content||"",rules:S.rules,variables:S.requestContextSchema}),[S]),{form:_}=kBt({initialValues:k}),[C,T]=g.useState(0);g.useEffect(()=>{k&&(_.reset(k),T(A=>A+1))},[k,_]);const E=g.useCallback(async()=>{if(!await _.trigger()){Be.error("Please fill in all required fields");return}v(!0);try{const R=wet(_.getValues());await f.mutateAsync(R),_.reset(_.getValues()),Be.success("Draft saved")}catch(R){Be.error(`Failed to save draft: ${R instanceof Error?R.message:"Unknown error"}`)}finally{v(!1)}},[_,f]),N=g.useCallback(async()=>{if(!await _.trigger()){Be.error("Please fill in all required fields");return}h(!0);try{const R=wet(_.getValues());await f.mutateAsync(R);const D=(await l.getStoredPromptBlock(t).listVersions({orderBy:{direction:"DESC"},perPage:1})).versions[0];if(!D)throw new Error("No version found to publish");await l.getStoredPromptBlock(t).activateVersion(D.id),c.invalidateQueries({queryKey:["stored-prompt-blocks"]}),c.invalidateQueries({queryKey:["stored-prompt-block"]}),c.invalidateQueries({queryKey:["prompt-block-versions",t]}),Be.success("Prompt block published"),u(d.promptBlocksLink())}catch(R){Be.error(`Failed to publish: ${R instanceof Error?R.message:"Unknown error"}`)}finally{h(!1)}},[_,f,l,t,u,d,c]),I=g.useCallback(async()=>{if(x&&n){h(!0);try{await l.getStoredPromptBlock(t).activateVersion(n),c.invalidateQueries({queryKey:["stored-prompt-blocks"]}),c.invalidateQueries({queryKey:["stored-prompt-block"]}),c.invalidateQueries({queryKey:["prompt-block-versions",t]}),Be.success("Version published"),u(d.promptBlocksLink())}catch(A){Be.error(`Failed to publish version: ${A instanceof Error?A.message:"Unknown error"}`)}finally{h(!1)}}else await N()},[N,x,n,l,t,c,u,d]);return o.jsxs(M1,{leftSlot:o.jsx(SBt,{form:_,onPublish:N,onSaveDraft:E,isSubmitting:p,isSavingDraft:m,isDirty:_.formState.isDirty,hasDraft:r,formResetKey:C,mode:"edit",blockId:t}),children:[x&&o.jsxs(Wn,{variant:"info",title:"This is a previous version",className:"m-4 mb-0",children:[o.jsx(Wn.Message,{children:"You are seeing a specific version of the prompt block."}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(oe,{type:"button",variant:"default",size:"sm",onClick:i,children:"View latest version"}),o.jsx(oe,{type:"button",variant:"default",size:"sm",onClick:I,disabled:n===a||p,children:p?"Publishing...":"Publish This Version"})]})]}),o.jsx("form",{className:"h-full",children:o.jsx(dBt,{form:_,formResetKey:C})})]})}function Lfs(){const{promptBlockId:e}=mr(),[t,n]=hi(),r=t.get("versionId"),{data:s,isLoading:a}=AL(e,{status:"draft"}),{data:i}=OBt({blockId:e??"",params:{orderBy:{direction:"DESC"}}}),l=s?.activeVersionId,c=i?.versions?.[0],u=!!(c&&(!l||c.id!==l)),d=g.useCallback(p=>{n(p?{versionId:p}:{})},[n]),f=g.useCallback(()=>{n({})},[n]);return a?o.jsx(_s,{className:"grid-rows-[1fr]",children:o.jsx(M1,{leftSlot:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ut,{className:"size-8"})}),children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ut,{className:"size-8"})})})}):!s||!e?o.jsx(_s,{className:"grid-rows-[1fr]",children:o.jsx(M1,{leftSlot:o.jsx("div",{className:"text-neutral3 flex h-full items-center justify-center",children:"Prompt block not found"}),children:o.jsx("div",{className:"text-neutral3 flex h-full items-center justify-center",children:"Prompt block not found"})})}):o.jsxs(_s,{className:"grid-rows-[1fr]",children:[o.jsx($y,{owner:"cms-prompt-block-edit",children:o.jsxs("div",{className:"flex items-center gap-2",children:[u&&o.jsx(St,{variant:"blue",children:"Unpublished changes"}),o.jsx(Sss,{blockId:e,value:r??"",onValueChange:d,variant:"ghost",activeVersionId:l})]})}),o.jsx(Dfs,{block:s,blockId:e,selectedVersionId:r,hasDraft:u,latestVersionId:c?.id,activeVersionId:l,onClearVersion:f})]})}function Ffs(){const{navigate:e,paths:t}=cn();return o.jsx(_s,{className:"grid-rows-[1fr]",children:o.jsx(Z7r,{onSuccess:n=>e(t.scorerLink(n.id))})})}function ket(e){return{name:e.name,description:e.description||void 0,type:e.type,model:e.model,instructions:e.instructions||void 0,scoreRange:e.scoreRange,defaultSampling:e.defaultSampling?.type==="ratio"&&typeof e.defaultSampling.rate=="number"?e.defaultSampling:{type:"none"}}}function zfs({scorer:e,scorerId:t,selectedVersionId:n,latestVersionId:r,activeVersionId:s,onClearVersion:a}){const i=Qe(),l=Lr(),{navigate:c,paths:u}=cn(),{updateStoredScorer:d}=GTe(t),[f,p]=g.useState(!1),[h,m]=g.useState(!1),v=g.useRef(null),{data:y}=Y7r({scorerId:t,versionId:n??""}),b=!!n&&!!y,x=b&&n!==r,S=b?y:e,k=g.useMemo(()=>({name:S.name||"",description:S.description||"",type:"llm-judge",model:{provider:S.model?.provider||"",name:S.model?.name||""},instructions:S.instructions||"",scoreRange:{min:S.scoreRange?.min??0,max:S.scoreRange?.max??1},defaultSampling:S.defaultSampling}),[S]),{form:_}=o4t({initialValues:k});g.useEffect(()=>{k&&_.reset(k)},[k,_]);const C=g.useCallback(async()=>{if(!await _.trigger()){Be.error("Please fill in all required fields");return}m(!0);try{const I=ket(_.getValues());await d.mutateAsync(I),Be.success("Draft saved")}catch(I){Be.error(`Failed to save draft: ${I instanceof Error?I.message:"Unknown error"}`)}finally{m(!1)}},[_,d]),T=g.useCallback(async()=>{if(!await _.trigger()){Be.error("Please fill in all required fields");return}p(!0);try{const I=ket(_.getValues());await d.mutateAsync(I);const R=(await i.getStoredScorer(t).listVersions({orderBy:{direction:"DESC"},perPage:1})).versions[0];R&&await i.getStoredScorer(t).activateVersion(R.id),l.invalidateQueries({queryKey:["scorers"]}),l.invalidateQueries({queryKey:["stored-scorers"]}),Be.success("Scorer published"),c(u.scorerLink(t))}catch(I){Be.error(`Failed to publish scorer: ${I instanceof Error?I.message:"Unknown error"}`)}finally{p(!1)}},[_,d,i,t,c,u,l]),E=g.useCallback(async()=>{if(x&&n){p(!0);try{await i.getStoredScorer(t).activateVersion(n),l.invalidateQueries({queryKey:["scorers"]}),l.invalidateQueries({queryKey:["stored-scorers"]}),l.invalidateQueries({queryKey:["scorer-versions",t]}),Be.success("Version published"),c(u.scorerLink(t))}catch(N){Be.error(`Failed to publish version: ${N instanceof Error?N.message:"Unknown error"}`)}finally{p(!1)}}else await T()},[T,x,n,i,t,l,c,u]);return o.jsxs(M1,{leftSlot:o.jsx(a4t,{form:_,onPublish:T,onSaveDraft:C,isSubmitting:f,isSavingDraft:h,formRef:v,mode:"edit"}),children:[x&&o.jsxs(Wn,{variant:"info",title:"This is a previous version",className:"m-4 mb-0",children:[o.jsx(Wn.Message,{children:"You are seeing a specific version of the scorer."}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(oe,{type:"button",variant:"default",size:"sm",onClick:a,children:"View latest version"}),o.jsx(oe,{type:"button",variant:"default",size:"sm",onClick:E,disabled:n===s||f,children:f?"Publishing...":"Publish This Version"})]})]}),o.jsx("form",{ref:v,className:"h-full",children:o.jsx(i4t,{form:_})})]})}function Bfs(){const{scorerId:e}=mr(),[t,n]=hi(),r=t.get("versionId"),{data:s,isLoading:a}=l4t(e,{status:"draft"}),{data:i}=u4t({scorerId:e??"",params:{orderBy:{direction:"DESC"}}}),l=s?.activeVersionId,c=i?.versions?.[0],u=!!(c&&l&&c.id!==l),d=g.useCallback(p=>{n(p?{versionId:p}:{})},[n]),f=g.useCallback(()=>{n({})},[n]);return a?o.jsx(_s,{className:"grid-rows-[1fr]",children:o.jsx(M1,{leftSlot:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ut,{className:"size-8"})}),children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ut,{className:"size-8"})})})}):!s||!e?o.jsx(_s,{className:"grid-rows-[1fr]",children:o.jsx(M1,{leftSlot:o.jsx("div",{className:"text-neutral3 flex h-full items-center justify-center",children:"Scorer not found"}),children:o.jsx("div",{className:"text-neutral3 flex h-full items-center justify-center",children:"Scorer not found"})})}):o.jsxs(_s,{className:"grid-rows-[1fr]",children:[o.jsx($y,{owner:"cms-scorer-edit",children:o.jsxs("div",{className:"flex items-center gap-2",children:[u&&o.jsx(St,{variant:"blue",children:"Unpublished changes"}),o.jsx(J7r,{scorerId:e,value:r??"",onValueChange:d,variant:"ghost",activeVersionId:l})]})}),o.jsx(zfs,{scorer:s,scorerId:e,selectedVersionId:r,latestVersionId:c?.id,activeVersionId:l,onClearVersion:f})]})}const PAe=(e,t)=>{const n=Qe();return yt({queryKey:["dataset-item-versions",e,t],queryFn:async()=>((await n.getItemHistory(e,t))?.history??[]).map((s,a)=>({id:s.id,datasetId:s.datasetId,datasetVersion:s.datasetVersion,input:s.input,groundTruth:s.groundTruth,expectedTrajectory:s.expectedTrajectory,toolMocks:s.toolMocks,scorerIds:s.scorerIds,metadata:s.metadata,validTo:s.validTo,isDeleted:s.isDeleted,createdAt:s.createdAt,updatedAt:s.updatedAt,isLatest:a===0})),enabled:!!e&&!!t})},Mxe=(e,t,n,r)=>{const s=Qe();return yt({queryKey:["dataset-item-version",e,t,n],queryFn:async()=>{const a=await s.getDatasetItemVersion(e,t,n);return{id:a.id,datasetId:a.datasetId,datasetVersion:a.datasetVersion,input:a.input,groundTruth:a.groundTruth,expectedTrajectory:a.expectedTrajectory,toolMocks:a.toolMocks,scorerIds:a.scorerIds,metadata:a.metadata,validTo:a.validTo??null,isDeleted:a.isDeleted??!1,createdAt:a.createdAt,updatedAt:a.updatedAt,isLatest:r!=null?n===r:!1}},enabled:!!e&&!!t&&n>0})},UQ=e=>{const t=Qe();return yt({queryKey:["experiments",e],queryFn:()=>t.listExperiments(e)})},Ufs=(e,t,n,r)=>{const s=Qe();return yt({queryKey:["compare-experiments",e,t,n,r],queryFn:()=>s.compareExperiments({datasetId:e,experimentIdA:t,experimentIdB:n,...r}),enabled:!!e&&!!t&&!!n})};var _9={exports:{}};var qfs=_9.exports,Oet;function Vfs(){return Oet||(Oet=1,(function(e,t){((n,r)=>{e.exports=r()})(qfs,function n(){var r=typeof self<"u"?self:typeof window<"u"?window:r!==void 0?r:{},s,a=!r.document&&!!r.postMessage,i=r.IS_PAPA_WORKER||!1,l={},c=0,u={};function d(N){return N.charCodeAt(0)===65279?N.slice(1):N}function f(N){this._handle=null,this._finished=!1,this._completed=!1,this._halted=!1,this._input=null,this._baseIndex=0,this._partialLine="",this._rowCount=0,this._start=0,this._nextChunk=null,this.isFirstChunk=!0,this._completeResults={data:[],errors:[],meta:{}},(function(I){var A=C(I);A.chunkSize=parseInt(A.chunkSize),I.step||I.chunk||(A.chunkSize=null),this._handle=new y(A),(this._handle.streamer=this)._config=A}).call(this,N),this.parseChunk=function(I,A){var R=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&0<R){let D=this._config.newline;D||(L=this._config.quoteChar||'"',D=this._handle.guessLineEndings(I,L)),I=[...I.split(D).slice(R)].join(D)}this.isFirstChunk&&E(this._config.beforeFirstChunk)&&(L=this._config.beforeFirstChunk(I))!==void 0&&(I=L),this.isFirstChunk=!1,this._halted=!1;var R=this._partialLine+I,L=(this._partialLine="",this._handle.parse(R,this._baseIndex,!this._finished));if(!this._handle.paused()&&!this._handle.aborted()){if(I=L.meta.cursor,R=(this._finished||(this._partialLine=R.substring(I-this._baseIndex),this._baseIndex=I),L&&L.data&&(this._rowCount+=L.data.length),this._finished||this._config.preview&&this._rowCount>=this._config.preview),i)r.postMessage({results:L,workerId:u.WORKER_ID,finished:R});else if(E(this._config.chunk)&&!A){if(this._config.chunk(L,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);this._completeResults=L=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(L.data),this._completeResults.errors=this._completeResults.errors.concat(L.errors),this._completeResults.meta=L.meta),this._completed||!R||!E(this._config.complete)||L&&L.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),R||L&&L.meta.paused||this._nextChunk(),L}this._halted=!0},this._sendError=function(I){E(this._config.error)?this._config.error(I):i&&this._config.error&&r.postMessage({workerId:u.WORKER_ID,error:I,finished:!1})}}function p(N){var I;(N=N||{}).chunkSize||(N.chunkSize=u.RemoteChunkSize),f.call(this,N),this._nextChunk=a?function(){this._readChunk(),this._chunkLoaded()}:function(){this._readChunk()},this.stream=function(A){this._input=A,this._nextChunk()},this._readChunk=function(){if(this._finished)this._chunkLoaded();else{if(I=new XMLHttpRequest,this._config.withCredentials&&(I.withCredentials=this._config.withCredentials),a||(I.onload=T(this._chunkLoaded,this),I.onerror=T(this._chunkError,this)),I.open(this._config.downloadRequestBody?"POST":"GET",this._input,!a),this._config.downloadRequestHeaders){var A,R=this._config.downloadRequestHeaders;for(A in R)I.setRequestHeader(A,R[A])}var L;this._config.chunkSize&&(L=this._start+this._config.chunkSize-1,I.setRequestHeader("Range","bytes="+this._start+"-"+L));try{I.send(this._config.downloadRequestBody)}catch(D){this._chunkError(D.message)}a&&I.status===0&&this._chunkError()}},this._chunkLoaded=function(){I.readyState===4&&(I.status<200||400<=I.status?this._chunkError():(this._start+=this._config.chunkSize||I.responseText.length,this._finished=!this._config.chunkSize||this._start>=(A=>(A=A.getResponseHeader("Content-Range"))!==null?parseInt(A.substring(A.lastIndexOf("/")+1)):-1)(I),this.parseChunk(I.responseText)))},this._chunkError=function(A){A=I.statusText||A,this._sendError(new Error(A))}}function h(N){(N=N||{}).chunkSize||(N.chunkSize=u.LocalChunkSize),f.call(this,N);var I,A,R=typeof FileReader<"u";this.stream=function(L){this._input=L,A=L.slice||L.webkitSlice||L.mozSlice,R?((I=new FileReader).onload=T(this._chunkLoaded,this),I.onerror=T(this._chunkError,this)):I=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){this._finished||this._config.preview&&!(this._rowCount<this._config.preview)||this._readChunk()},this._readChunk=function(){var L=this._input,D=(this._config.chunkSize&&(D=Math.min(this._start+this._config.chunkSize,this._input.size),L=A.call(L,this._start,D)),I.readAsText(L,this._config.encoding));R||this._chunkLoaded({target:{result:D}})},this._chunkLoaded=function(L){this._start+=this._config.chunkSize,this._finished=!this._config.chunkSize||this._start>=this._input.size,this.parseChunk(L.target.result)},this._chunkError=function(){this._sendError(I.error)}}function m(N){var I;f.call(this,N=N||{}),this.stream=function(A){return I=A,this._nextChunk()},this._nextChunk=function(){var A,R;if(!this._finished)return A=this._config.chunkSize,I=A?(R=I.substring(0,A),I.substring(A)):(R=I,""),this._finished=!I,this.parseChunk(R)}}function v(N){f.call(this,N=N||{});var I=[],A=!0,R=!1;this.pause=function(){f.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){f.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function(L){this._input=L,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){R&&I.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),I.length?this.parseChunk(I.shift()):A=!0},this._streamData=T(function(L){try{I.push(typeof L=="string"?L:L.toString(this._config.encoding)),A&&(A=!1,this._checkIsFinished(),this.parseChunk(I.shift()))}catch(D){this._streamError(D)}},this),this._streamError=T(function(L){this._streamCleanUp(),this._sendError(L)},this),this._streamEnd=T(function(){this._streamCleanUp(),R=!0,this._streamData("")},this),this._streamCleanUp=T(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}function y(N){var I,A,R,L,D=Math.pow(2,53),F=-D,H=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,B=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,z=this,V=0,M=0,G=!1,U=!1,$=[],q={data:[],errors:[],meta:{}};function Z(ee){return N.skipEmptyLines==="greedy"?ee.join("").trim()==="":ee.length===1&&ee[0].length===0}function Y(){if(q&&R&&(J("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+u.DefaultDelimiter+"'"),R=!1),N.skipEmptyLines&&(q.data=q.data.filter(function(X){return!Z(X)})),ne()){let X=function(te,se){te=d(te),E(N.transformHeader)&&(te=N.transformHeader(te,se)),$.push(te)};if(q)if(Array.isArray(q.data[0])){for(var ee=0;ne()&&ee<q.data.length;ee++)q.data[ee].forEach(X);q.data.splice(0,1)}else q.data.forEach(X)}function re(X,te){for(var se=N.header?{}:[],pe=0;pe<X.length;pe++){var ce=pe,Se=X[pe],Se=((ve,ke)=>(Ne=>(N.dynamicTypingFunction&&N.dynamicTyping[Ne]===void 0&&(N.dynamicTyping[Ne]=N.dynamicTypingFunction(Ne)),(N.dynamicTyping[Ne]||N.dynamicTyping)===!0))(ve)?ke==="true"||ke==="TRUE"||ke!=="false"&&ke!=="FALSE"&&((Ne=>{if(H.test(Ne)&&(Ne=parseFloat(Ne),F<Ne&&Ne<D))return 1})(ke)?parseFloat(ke):B.test(ke)?new Date(ke):ke===""?null:ke):ke)(ce=N.header?pe>=$.length?"__parsed_extra":$[pe]:ce,Se=N.transform?N.transform(Se,ce):Se);ce==="__parsed_extra"?(se[ce]=se[ce]||[],se[ce].push(Se)):se[ce]=Se}return N.header&&(pe>$.length?J("FieldMismatch","TooManyFields","Too many fields: expected "+$.length+" fields but parsed "+pe,M+te):pe<$.length&&J("FieldMismatch","TooFewFields","Too few fields: expected "+$.length+" fields but parsed "+pe,M+te)),se}var le;q&&(N.header||N.dynamicTyping||N.transform)&&(le=1,!q.data.length||Array.isArray(q.data[0])?(q.data=q.data.map(re),le=q.data.length):q.data=re(q.data,0),N.header&&q.meta&&(q.meta.fields=$),M+=le)}function ne(){return N.header&&$.length===0}function J(ee,re,le,X){ee={type:ee,code:re,message:le},X!==void 0&&(ee.row=X),q.errors.push(ee)}E(N.step)&&(L=N.step,N.step=function(ee){q=ee,ne()?Y():(Y(),q.data.length!==0&&(V+=ee.data.length,N.preview&&V>N.preview?A.abort():(q.data=q.data[0],L(q,z))))}),this.parse=function(ee,re,le){var X=N.quoteChar||'"',X=(N.newline||(N.newline=this.guessLineEndings(ee,X)),R=!1,N.delimiter?E(N.delimiter)&&(N.delimiter=N.delimiter(ee),q.meta.delimiter=N.delimiter):((X=((te,se,pe,ce,Se)=>{var ve,ke,Ne,Me;Se=Se||[","," ","|",";",u.RECORD_SEP,u.UNIT_SEP];for(var Ae=0;Ae<Se.length;Ae++){for(var Ie,ae=Se[Ae],fe=0,ue=0,we=0,Ee=(Ne=void 0,new x({comments:ce,delimiter:ae,newline:se,preview:10}).parse(te)),ge=0;ge<Ee.data.length;ge++)pe&&Z(Ee.data[ge])?we++:(Ie=Ee.data[ge].length,ue+=Ie,Ne===void 0?Ne=Ie:0<Ie&&(fe+=Math.abs(Ie-Ne),Ne=Ie));0<Ee.data.length&&(ue/=Ee.data.length-we),(ke===void 0||fe<=ke)&&(Me===void 0||Me<ue)&&1.99<ue&&(ke=fe,ve=ae,Me=ue)}return{successful:!!(N.delimiter=ve),bestDelimiter:ve}})(ee,N.newline,N.skipEmptyLines,N.comments,N.delimitersToGuess)).successful?N.delimiter=X.bestDelimiter:(R=!0,N.delimiter=u.DefaultDelimiter),q.meta.delimiter=N.delimiter),C(N));return N.preview&&N.header&&X.preview++,I=ee,A=new x(X),q=A.parse(I,re,le),Y(),G?{meta:{paused:!0}}:q||{meta:{paused:!1}}},this.paused=function(){return G},this.pause=function(){G=!0,A.abort(),I=E(N.chunk)?"":I.substring(A.getCharIndex())},this.resume=function(){z.streamer._halted?(G=!1,z.streamer.parseChunk(I,!0)):setTimeout(z.resume,3)},this.aborted=function(){return U},this.abort=function(){U=!0,A.abort(),q.meta.aborted=!0,E(N.complete)&&N.complete(q),I=""},this.guessLineEndings=function(te,X){te=te.substring(0,1048576);var X=new RegExp(b(X)+"([^]*?)"+b(X),"gm"),le=(te=te.replace(X,"")).split("\r"),X=te.split(`
|
|
628
628
|
`),te=1<X.length&&X[0].length<le[0].length;if(le.length===1||te)return`
|
|
629
629
|
`;for(var se=0,pe=0;pe<le.length;pe++)le[pe][0]===`
|
|
630
630
|
`&&se++;return se>=le.length/2?`\r
|
|
@@ -641,7 +641,7 @@ Token usage: ${n} input + ${r} output = ${s} total`:`The model stopped generatin
|
|
|
641
641
|
}
|
|
642
642
|
]`})]})]})}function hhs({errors:e,maxErrors:t=5}){if(e.length===0)return null;const n=e.slice(0,t),r=e.length-t;return o.jsxs("div",{className:"bg-accent2/10 border-accent2/30 rounded-md border p-3",children:[o.jsxs("div",{className:"text-accent2 mb-2 flex items-center gap-2",children:[o.jsx(He,{children:o.jsx(ac,{className:"h-4 w-4"})}),o.jsxs("span",{className:"text-sm font-medium",children:[e.length," validation error",e.length!==1?"s":""]})]}),o.jsx("ul",{className:"text-accent2/80 space-y-1 text-sm",children:n.map((s,a)=>o.jsxs("li",{className:"flex gap-2",children:[o.jsx("span",{className:"shrink-0",children:"•"}),o.jsx("span",{children:s.message})]},a))}),r>0&&o.jsxs("div",{className:"text-accent2/60 mt-2 text-xs",children:["+",r," more error",r!==1?"s":""]})]})}function mhs({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=g.useState("upload"),[i,l]=g.useState(null),[c,u]=g.useState({current:0,total:0}),[d,f]=g.useState(null),[p,h]=g.useState(!1),{parseFile:m,isParsing:v,error:y}=Xfs(),{batchInsertItems:b}=qi(),x=g.useCallback(async I=>{try{const A=await m(I);l(A),a("preview")}catch{}},[m]),S=g.useCallback(async()=>{if(!i||i.items.length===0)return;a("importing"),h(!0);const{items:I}=i;u({current:0,total:I.length});try{await b.mutateAsync({datasetId:e,items:I.map(A=>({input:A.input,groundTruth:A.groundTruth,metadata:A.metadata}))}),f({success:I.length,errors:0})}catch{f({success:0,errors:I.length})}u({current:I.length,total:I.length}),h(!1),a("complete")},[i,b,e]),k=g.useCallback(()=>{n(!1),r?.(),d&&d.success>0&&Be.success(`Imported ${d.success} item${d.success!==1?"s":""}`),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150)},[n,r,d]),_=g.useCallback(()=>{p||(n(!1),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150))},[p,n]),C=i&&i.items.length>0&&i.errors.length===0,T=()=>{switch(s){case"upload":return o.jsx(phs,{onFileSelect:x,isParsing:v,error:y?.message});case"preview":return i?o.jsx("div",{className:"flex flex-col gap-4",children:i.errors.length>0?o.jsxs(o.Fragment,{children:[o.jsx(hhs,{errors:i.errors}),o.jsx("div",{className:"text-neutral4 text-sm",children:"Please fix the errors in your JSON file and try again."})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"text-neutral4 text-sm",children:["Found ",i.items.length," valid item",i.items.length!==1?"s":""," to import."]}),o.jsx(fhs,{items:i.items,maxRows:5})]})}):null;case"importing":return o.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[o.jsx(Ut,{}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-neutral1 text-lg font-medium",children:"Importing items..."}),o.jsxs("div",{className:"text-neutral4 mt-1 text-sm",children:[c.current," of ",c.total]})]})]});case"complete":return o.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[o.jsx("div",{className:"text-4xl",children:d&&d.errors===0?"✓":"⚠"}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-neutral1 text-lg font-medium",children:"Import Complete"}),o.jsxs("div",{className:"text-neutral4 mt-1 text-sm",children:[d?.success??0," item",d?.success!==1?"s":""," imported",d&&d.errors>0&&o.jsxs("span",{className:"text-accent2",children:[" ","(",d.errors," error",d.errors!==1?"s":"",")"]})]})]})]})}},E=()=>{switch(s){case"upload":return o.jsx(oe,{onClick:_,children:"Cancel"});case"preview":return o.jsxs(o.Fragment,{children:[o.jsx(oe,{onClick:()=>a("upload"),children:"Back"}),o.jsxs(oe,{variant:"primary",onClick:S,disabled:!C,children:["Import ",i?.items.length??0," Item",i?.items.length!==1?"s":""]})]});case"importing":return null;case"complete":return o.jsx(oe,{variant:"primary",onClick:k,children:"Done"})}},N={upload:"Import JSON",preview:"Preview Data",importing:"Importing",complete:"Import Complete"};return o.jsx(vr,{open:t,onOpenChange:_,children:o.jsxs(yr,{className:"max-h-[90vh] max-w-2xl",children:[o.jsxs(br,{children:[o.jsx(pr,{children:N[s]}),o.jsx(Ps,{children:"Import dataset items from a JSON file."})]}),o.jsx(Mr,{className:"max-h-[50vh] min-h-[200px] overflow-y-auto",children:T()}),o.jsx(lc,{className:"flex justify-end gap-2 px-6 pt-4",children:E()})]})})}function ghs(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 bVt({active:e,onPrevious:t,onNext:n,onClose:r}){g.useEffect(()=>{if(!e)return;const s=a=>{a.defaultPrevented||ghs(a.target)||(a.key==="PageUp"?(a.preventDefault(),t?.()):a.key==="PageDown"?(a.preventDefault(),n?.()):a.key==="Escape"&&(a.preventDefault(),r()))};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,t,n,r])}const xVt=g.createContext(null);function vhs({datasetId:e,items:t,isLoadingItems:n,children:r}){const s=es(),i=mgt("/datasets/:datasetId/items/:itemId")?.params.itemId,l=g.useCallback(h=>{s(`/datasets/${e}/items/${encodeURIComponent(h)}`)},[s,e]),c=g.useCallback(()=>{s(`/datasets/${e}`)},[s,e]),u=g.useMemo(()=>i?t.findIndex(h=>h.id===i):-1,[t,i]),d=g.useMemo(()=>{if(u<=0)return;const h=t[u-1].id;return()=>l(h)},[u,t,l]),f=g.useMemo(()=>{if(u<0||u>=t.length-1)return;const h=t[u+1].id;return()=>l(h)},[u,t,l]);bVt({active:!!i,onPrevious:d,onNext:f,onClose:c});const p=g.useMemo(()=>({datasetId:e,items:t,isLoadingItems:n,currentItemId:i,openItem:l,close:c,goToPreviousItem:d,goToNextItem:f}),[e,t,n,i,l,c,d,f]);return o.jsx(xVt.Provider,{value:p,children:r})}function wVt(){const e=g.useContext(xVt);if(!e)throw new Error("useDatasetItemPanel must be used within a DatasetItemPanelProvider");return e}const MAe=e=>{const t=Qe(),{data:n}=DD(e),r=n?.experiments;return yt({queryKey:["dataset-review-items",e,r?.map(s=>s.id)],queryFn:async()=>!r||r.length===0?[]:(await Promise.all(r.map(async a=>{if(!a.datasetId)return[];try{const{results:i}=await t.listDatasetExperimentResults(a.datasetId,a.id);return i.filter(l=>l.status==="needs-review").map(l=>({id:l.id,input:l.input,output:l.output,error:l.error,itemId:l.itemId,experimentId:l.experimentId,datasetId:a.datasetId??void 0,traceId:l.traceId??void 0,scores:l.scores?Object.fromEntries(l.scores.map(c=>[c.scorerId,c.score??0])):{},tags:l.tags??[],comment:l.comment??""}))}catch{return[]}}))).flat(),enabled:!!e&&!!r&&r.length>0,refetchOnWindowFocus:!1})},yhs=e=>{const t=Qe(),{data:n}=DD(e),r=n?.experiments;return yt({queryKey:["dataset-completed-items",e,r?.map(s=>s.id)],queryFn:async()=>!r||r.length===0?[]:(await Promise.all(r.map(async a=>{if(!a.datasetId)return[];try{const{results:i}=await t.listDatasetExperimentResults(a.datasetId,a.id);return i.filter(l=>l.status==="complete").map(l=>({id:l.id,input:l.input,output:l.output,error:l.error,itemId:l.itemId,experimentId:l.experimentId,datasetId:a.datasetId??void 0,traceId:l.traceId??void 0,scores:l.scores?Object.fromEntries(l.scores.map(c=>[c.scorerId,c.score??0])):{},tags:l.tags??[],comment:l.comment??""}))}catch{return[]}}))).flat(),enabled:!!e&&!!r&&r.length>0,refetchOnWindowFocus:!1})};function DAe({label:e,wide:t=!1,children:n}){return o.jsxs("div",{className:K("pointer-events-none absolute inset-0 z-30","grid transition-[grid-template-columns] duration-300 ease-in-out",t?"grid-cols-[1fr_4fr]":"grid-cols-[1fr_1fr]"),children:[o.jsx("div",{className:"pointer-events-none"}),o.jsx("div",{role:"dialog","data-item-panel":!0,"aria-label":e,className:"pointer-events-auto h-full min-h-0 min-w-0 overflow-y-auto",children:n})]})}function bhs(e,t){if(typeof e=="string")return e.length>t?e.slice(0,t)+"...":e;try{const n=JSON.stringify(e);return n.length>t?n.slice(0,t)+"...":n}catch{return String(e)}}function SVt({datasetId:e,experimentId:t,featuredItemId:n,detailPanelVariant:r="inline"}){const s=Qe(),{data:a}=Yg(e),{data:i,isLoading:l}=MAe(e),{data:c,isLoading:u}=yhs(e),d=g.useMemo(()=>t?(i??[]).filter($e=>$e.experimentId===t):i,[i,t]),f=g.useMemo(()=>t?(c??[]).filter($e=>$e.experimentId===t):c,[c,t]),{updateExperimentResult:p}=qi(),[h,m]=g.useState(n??null);g.useEffect(()=>{n!==void 0&&m(n)},[n]);const[v,y]=g.useState(null),[b,x]=g.useState(new Set),[S,k]=g.useState(!1),[_,C]=g.useState(!1),[T,E]=g.useState(!1),[N,I]=g.useState(""),[A,R]=g.useState(""),[L,D]=g.useState(""),[F,H]=g.useState([]),[B,z]=g.useState(!1),[V,M]=g.useState(null),G=g.useMemo(()=>V??d??[],[V,d]);g.useEffect(()=>{M(null)},[e,t]),g.useEffect(()=>{d&&V===null&&M(d)},[d,V]);const U=g.useMemo(()=>{const $e=new Set;if(a?.tags)for(const ye of a.tags)$e.add(ye);for(const ye of G)for(const xe of ye.tags)$e.add(xe);return[...$e].sort()},[a,G]),$=g.useCallback($e=>{!a||!e||(a.tags??[]).includes($e)},[a,e]),q=g.useMemo(()=>v?v==="__untagged__"?G.filter($e=>$e.tags.length===0):G.filter($e=>$e.tags.includes(v)):G,[G,v]),Z=g.useMemo(()=>{const $e=new Map;for(const ye of G)for(const xe of ye.tags)$e.set(xe,($e.get(xe)??0)+1);return[...$e.entries()].sort((ye,xe)=>xe[1]-ye[1])},[G]),Y=g.useMemo(()=>G.filter($e=>$e.tags.length===0).length,[G]),ne=g.useMemo(()=>{let $e=0;return v&&$e++,S&&$e++,$e},[v,S]),J=g.useCallback(($e,ye)=>{M(Pe=>(Pe??[]).map(tt=>tt.id===$e?{...tt,tags:ye}:tt));const xe=G.find(Pe=>Pe.id===$e);xe?.experimentId&&xe?.datasetId&&p.mutate({datasetId:xe.datasetId,experimentId:xe.experimentId,resultId:xe.id,tags:ye})},[G,p]),ee=g.useCallback(($e,ye)=>{const xe=G.find(Pe=>Pe.id===$e);xe?.traceId&&ye!==void 0&&s.createFeedback({feedback:{traceId:xe.traceId,source:"studio",feedbackSource:"studio",feedbackType:"rating",value:ye==="positive"?1:-1,experimentId:xe.experimentId??void 0,sourceId:xe.id}}).catch(()=>{}),M(Pe=>(Pe??[]).map(tt=>tt.id===$e?{...tt,rating:ye}:tt))},[G,s]),re=g.useCallback(($e,ye)=>{const xe=G.find(Pe=>Pe.id===$e);xe?.experimentId&&xe?.datasetId&&p.mutate({datasetId:xe.datasetId,experimentId:xe.experimentId,resultId:xe.id,comment:ye}),xe?.traceId&&s.createFeedback({feedback:{traceId:xe.traceId,source:"studio",feedbackSource:"studio",feedbackType:"comment",value:ye,comment:ye,experimentId:xe.experimentId??void 0,sourceId:xe.id}}).catch(()=>{}),M(Pe=>(Pe??[]).map(tt=>tt.id===$e?{...tt,comment:ye}:tt))},[G,s,p]),le=g.useCallback($e=>{const ye=G.find(xe=>xe.id===$e);M(xe=>(xe??[]).filter(Pe=>Pe.id!==$e)),x(xe=>{const Pe=new Set(xe);return Pe.delete($e),Pe}),h===$e&&m(null),ye?.experimentId&&ye?.datasetId&&p.mutate({datasetId:ye.datasetId,experimentId:ye.experimentId,resultId:ye.id,status:null})},[G,p,h]),X=g.useCallback($e=>{const ye=G.find(xe=>xe.id===$e);M(xe=>(xe??[]).filter(Pe=>Pe.id!==$e)),x(xe=>{const Pe=new Set(xe);return Pe.delete($e),Pe}),h===$e&&m(null),ye?.experimentId&&ye?.datasetId&&p.mutate({datasetId:ye.datasetId,experimentId:ye.experimentId,resultId:ye.id,status:"complete"})},[G,p,h]),te=g.useMemo(()=>{const $e=S?f??[]:q;return!S||!v?$e:v==="__untagged__"?$e.filter(ye=>ye.tags.length===0):$e.filter(ye=>ye.tags.includes(v))},[S,f,q,v]),se=S?u:!1,pe=g.useMemo(()=>new Set(te.map($e=>$e.id)),[te]),ce=g.useMemo(()=>[...b].filter($e=>pe.has($e)).length,[b,pe]),Se=te.length>0&&ce===te.length,ve=ce>0&&!Se,ke=g.useCallback($e=>{x(ye=>{const xe=new Set(ye);return xe.has($e)?xe.delete($e):xe.add($e),xe})},[]),Ne=g.useCallback(()=>{x(Se?new Set:new Set(te.map($e=>$e.id)))},[Se,te]),Me=g.useCallback($e=>{for(const ye of b){const xe=G.find(Pe=>Pe.id===ye);xe&&!xe.tags.includes($e)&&J(ye,[...xe.tags,$e])}},[G,b,J]),Ae=g.useCallback($e=>{for(const ye of b){const xe=G.find(Pe=>Pe.id===ye);xe&&xe.tags.includes($e)&&J(ye,xe.tags.filter(Pe=>Pe!==$e))}},[G,b,J]),Ie=g.useCallback(()=>{for(const $e of b)X($e);x(new Set)},[b,X]),ae=g.useCallback(()=>{for(const $e of b)le($e);x(new Set)},[b,le]),fe=g.useCallback(()=>{I(""),E(!0)},[]),ue=g.useCallback(async()=>{if(!(!A||!L)){C(!0),E(!1);try{const $e=G.filter(xe=>b.has(xe.id));if($e.length===0){C(!1);return}const ye=await s.clusterFailures({modelId:`${A}/${L}`,items:$e.map(xe=>({id:xe.id,input:xe.input,output:xe.output??void 0,error:typeof xe.error=="string"?xe.error:xe.error?String(xe.error):void 0,scores:xe.scores,existingTags:xe.tags.length>0?xe.tags:void 0})),availableTags:U.length>0?U:void 0,prompt:N||void 0});ye.proposedTags&&ye.proposedTags.length>0&&(H(ye.proposedTags.map(xe=>({...xe,accepted:!0}))),z(!0))}catch($e){console.error("Analysis failed:",$e)}finally{C(!1)}}},[A,L,G,b,s,U,N]),we=g.useCallback(()=>{for(const $e of F){if(!$e.accepted)continue;const ye=G.find(xe=>xe.id===$e.itemId);if(ye){const xe=[...new Set([...ye.tags,...$e.tags])];J(ye.id,xe)}}z(!1)},[F,G,J]),Ee=g.useCallback($e=>{m(ye=>ye===$e?null:$e)},[]),ge=g.useMemo(()=>h?te.find($e=>$e.id===h)??null:null,[h,te]),Ce=h?te.findIndex($e=>$e.id===h):-1,Ue=Ce>0?()=>m(te[Ce-1].id):void 0,Fe=Ce>=0&&Ce<te.length-1?()=>m(te[Ce+1].id):void 0,Re="auto minmax(15rem,1fr) 10rem 8rem 6rem 6rem",{containerRef:Ge,getRowProps:st}=wo({count:te.length});if(l)return o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(Ut,{className:"h-6 w-6"})});const mt=ge?o.jsx(lUt,{className:"h-full",item:ge,isCompleted:S,tagVocabulary:U,onRate:$e=>ee(ge.id,$e),onSetTags:$e=>{J(ge.id,$e);for(const ye of $e)U.includes(ye)||$(ye)},onComment:$e=>re(ge.id,$e),onRemove:()=>le(ge.id),onComplete:S?void 0:()=>X(ge.id),onPrevious:Ue,onNext:Fe,onClose:()=>m(null)}):null;return o.jsxs("div",{className:K("flex h-full min-h-0 flex-1",r==="overlay"?"overflow-visible":"overflow-hidden"),children:[o.jsx(vr,{open:T,onOpenChange:E,children:o.jsxs(yr,{children:[o.jsxs(br,{children:[o.jsx(pr,{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(Mt,{className:"mb-1 block text-xs",children:"Provider"}),o.jsx(Vy,{value:A,onValueChange:R})]}),o.jsxs("div",{children:[o.jsx(Mt,{className:"mb-1 block text-xs",children:"Model"}),o.jsx(Hy,{llmId:A,value:L,onValueChange:D})]})]}),o.jsxs(me,{variant:"ui-xs",className:"text-neutral3",children:[b.size," item",b.size!==1?"s":""," will be analyzed"]}),o.jsxs("div",{children:[o.jsx(Mt,{className:"text-xs",children:"Instructions (optional)"}),o.jsx(Il,{value:N,onChange:$e=>I($e.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3,className:"mt-1 text-xs"})]})]}),o.jsxs(lc,{children:[o.jsx(oe,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),o.jsxs(oe,{onClick:ue,disabled:!A||!L||_,children:[_?o.jsx(Ut,{className:"mr-1 h-4 w-4"}):null,"Analyze"]})]})]})}),o.jsx(vr,{open:B,onOpenChange:z,children:o.jsxs(yr,{className:"max-h-[80vh] max-w-2xl overflow-y-auto",children:[o.jsxs(br,{children:[o.jsx(pr,{children:"Review Proposed Tags"}),o.jsxs(Ps,{children:[F.filter($e=>$e.accepted).length," of ",F.length," proposals selected"]})]}),o.jsx("div",{className:"space-y-3 py-2",children:F.map(($e,ye)=>{const xe=G.find(Pe=>Pe.id===$e.itemId);return o.jsx("div",{className:K("p-3 border rounded-lg",!$e.accepted&&"opacity-50"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(So,{checked:$e.accepted,onCheckedChange:Pe=>H(tt=>tt.map((nt,Dt)=>Dt===ye?{...nt,accepted:!!Pe}:nt))}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral4 block truncate",children:xe?typeof xe.input=="string"?xe.input.slice(0,100):JSON.stringify(xe.input).slice(0,100):$e.itemId}),o.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:$e.tags.map((Pe,tt)=>o.jsx(uUt,{tag:Pe,onRename:nt=>H(Dt=>Dt.map((Te,Ke)=>Ke===ye?{...Te,tags:Te.tags.map((pt,Qt)=>Qt===tt?nt:pt)}:Te)),onRemove:()=>H(nt=>nt.map((Dt,Te)=>Te===ye?{...Dt,tags:Dt.tags.filter((Ke,pt)=>pt!==tt)}:Dt))},`${Pe}-${tt}`))}),$e.reason&&o.jsx(me,{variant:"ui-xs",className:"text-neutral3 mt-1 block italic",children:$e.reason})]})]})},$e.itemId)})}),o.jsxs(lc,{children:[o.jsx(oe,{variant:"outline",onClick:()=>z(!1),children:"Cancel"}),o.jsxs(oe,{onClick:we,disabled:F.filter($e=>$e.accepted).length===0,children:["Accept ",F.filter($e=>$e.accepted).length," proposals"]})]})]})}),o.jsxs("div",{className:K("grid h-full min-h-0 w-full grid-cols-1 gap-4",r==="overlay"?"overflow-visible":"overflow-hidden",ge&&r==="inline"&&"grid-cols-[1fr_1fr]"),children:[o.jsxs("div",{className:"grid min-h-0 w-full grid-rows-[auto_1fr] gap-3 overflow-hidden pt-3",children:[(G.length>0||ne>0)&&o.jsxs("div",{className:"flex w-full flex-wrap items-center justify-start gap-3",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs(rt,{children:[o.jsx(rt.Trigger,{asChild:!0,children:o.jsxs(oe,{size:"sm",children:[o.jsx(i0e,{}),"Filter",ne>0&&o.jsx(St,{size:"xs",children:ne})]})}),o.jsxs(rt.Content,{align:"start",className:K("min-w-48"),children:[o.jsxs(rt.Sub,{children:[o.jsxs(rt.SubTrigger,{children:["Status",S&&o.jsx("span",{className:K("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(rt.SubContent,{children:[o.jsx(rt.CheckboxItem,{checked:!S,onCheckedChange:()=>{k(!1),m(null)},onSelect:$e=>$e.preventDefault(),children:"Review Queue"}),o.jsx(rt.CheckboxItem,{checked:S,onCheckedChange:()=>{k(!0),m(null)},onSelect:$e=>$e.preventDefault(),children:"Completed"})]})]}),o.jsxs(rt.Sub,{children:[o.jsxs(rt.SubTrigger,{children:["Tags",v&&o.jsx("span",{className:K("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(rt.SubContent,{children:[o.jsx(rt.CheckboxItem,{checked:!v,onCheckedChange:()=>y(null),onSelect:$e=>$e.preventDefault(),children:"All"}),Y>0&&o.jsx(rt.CheckboxItem,{checked:v==="__untagged__",onCheckedChange:()=>y(v==="__untagged__"?null:"__untagged__"),onSelect:$e=>$e.preventDefault(),children:"Untagged"}),Z.length>0&&o.jsx(rt.Separator,{}),Z.map(([$e])=>o.jsx(rt.CheckboxItem,{checked:v===$e,onCheckedChange:()=>y(v===$e?null:$e),onSelect:ye=>ye.preventDefault(),children:$e},$e))]})]}),ne>0&&o.jsxs(o.Fragment,{children:[o.jsx(rt.Separator,{}),o.jsxs(rt.Item,{onSelect:()=>{y(null),k(!1),m(null)},children:[o.jsx(or,{}),"Clear all filters"]})]})]})]}),ne>0&&o.jsxs(oe,{size:"sm",onClick:()=>{y(null),k(!1),m(null)},children:[o.jsx(or,{}),"Reset"]})]}),!S&&b.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(cUt,{selectedCount:b.size,vocabulary:U,onApplyTag:Me,onRemoveTag:Ae,onNewTag:$e=>Me($e)}),o.jsxs(rt,{children:[o.jsx(rt.Trigger,{asChild:!0,children:o.jsxs(oe,{size:"sm",disabled:_,children:[_?o.jsx(Ut,{className:"h-4 w-4"}):o.jsx(He,{size:"sm",children:o.jsx(Xs,{})}),"Actions"]})}),o.jsxs(rt.Content,{align:"end",children:[o.jsxs(rt.Item,{onSelect:Ie,children:[o.jsx(He,{size:"sm",children:o.jsx(mO,{})}),"Complete"]}),o.jsxs(rt.Item,{onSelect:ae,children:[o.jsx(He,{size:"sm",children:o.jsx(Ml,{})}),"Remove"]}),o.jsx(rt.Separator,{}),o.jsxs(rt.Item,{onSelect:fe,children:[o.jsx(He,{size:"sm",children:o.jsx($g,{})}),"Analyze"]})]})]})]})]}),se?o.jsx("div",{className:"flex flex-1 items-center justify-center",children:o.jsx(Ut,{className:"h-6 w-6"})}):te.length===0?o.jsx("div",{className:"flex h-full items-center justify-center py-12",children:o.jsx(Er,{iconSlot:o.jsx(vO,{className:"text-neutral3 h-8 w-8"}),titleSlot:S?"No completed reviews yet":"No items to review",descriptionSlot:S?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here."})}):o.jsxs(be,{columns:Re,className:"min-w-0",scrollRef:Ge,children:[o.jsxs(be.Top,{hasLeadingCell:!0,children:[S?o.jsx(be.TopCell,{children:" "}):o.jsx(be.TopSelectCell,{checked:Se?!0:ve?"indeterminate":!1,onToggle:()=>Ne(),"aria-label":"Select all"}),o.jsxs(be.TopCells,{colStart:2,children:[o.jsx(be.TopCell,{children:"Input"}),o.jsx(be.TopCell,{children:"Comment"}),o.jsx(be.TopCell,{children:"Tags"}),o.jsx(be.TopCell,{children:"Rating"}),o.jsx(be.TopCell,{children:"Scores"})]})]}),te.map(($e,ye)=>{const xe=$e.scores?Object.entries($e.scores):[],Pe=h===$e.id,tt=o.jsxs(o.Fragment,{children:[o.jsx(be.Cell,{className:"text-neutral4 min-w-0",children:o.jsx("span",{className:"block truncate",children:bhs($e.input,200)})}),o.jsx(be.Cell,{className:"min-w-0",children:$e.comment?o.jsx(me,{variant:"ui-xs",className:"text-neutral3 truncate",children:$e.comment}):o.jsx(me,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsx(be.Cell,{className:"min-w-0",children:$e.tags.length>0?o.jsx(me,{variant:"ui-xs",className:"text-neutral4 truncate",children:$e.tags.join(", ")}):o.jsx(me,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsxs(be.Cell,{children:[$e.rating==="positive"&&o.jsx(He,{size:"sm",className:"text-positive1",children:o.jsx(y0e,{})}),$e.rating==="negative"&&o.jsx(He,{size:"sm",className:"text-negative1",children:o.jsx(v0e,{})}),!$e.rating&&o.jsx(me,{variant:"ui-xs",className:"text-neutral2",children:"—"})]}),o.jsx(be.Cell,{children:xe.length>0?o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(He,{size:"sm",className:"text-neutral3",children:o.jsx(Wp,{})}),o.jsx(me,{variant:"ui-xs",className:"text-neutral4 font-mono",children:xe[0][1].toFixed(2)}),xe.length>1&&o.jsxs(St,{children:["+",xe.length-1]})]}):o.jsx(me,{variant:"ui-xs",className:"text-neutral2",children:"—"})})]});return o.jsxs(be.RowWrapper,{children:[S?o.jsx(be.Cell,{className:"justify-items-center px-4",children:o.jsx("div",{role:"img","aria-label":$e.error?"Error":"Success",title:$e.error?"Error":"Success",className:K("w-2 h-2 rounded-full",$e.error?"bg-red-700":"bg-green-600")})}):o.jsx(be.SelectCell,{checked:b.has($e.id),onToggle:()=>ke($e.id),"aria-label":`Select item ${$e.id}`}),o.jsx(be.RowButton,{colStart:2,featured:Pe,onClick:()=>Ee($e.id),...st(ye),children:tt})]},$e.id)})]})]}),mt&&(r==="overlay"?o.jsx(DAe,{label:`Review item ${ge?.id??""}`,children:mt}):mt)]})]})}function xhs({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,rightSlot:r}){const[s,a]=hi(),{tab:i,activeVersion:l,handleTabChange:c}=$Ae(s,a),[u,d]=g.useState(!1),[f,p]=g.useState(!1),[h,m]=g.useState(!1),[v,y]=g.useState([]),[b,x]=g.useState(!1),[S,k]=g.useState([]),[_,C]=g.useState(!1),[T,E]=g.useState([]),[N,I]=g.useState(0),[A,R]=g.useState(""),[L]=MH(A,300),{data:D}=Yg(e),{data:F=[],total:H,isLoading:B,setEndOfListElement:z,isFetchingNextPage:V,hasNextPage:M}=Zx(e,L||void 0,l),{total:G}=Zx(e,void 0,l),[U,$]=g.useState({}),{data:q,isLoading:Z}=DD(e,void 0,U),{data:Y}=DD(e),{deleteItems:ne}=qi(),J=q?.experiments??[],ee=Y?.experiments??[],re=Ups({hasSearchQuery:!!L,filteredItemsLength:F.length,unfilteredItemsTotal:G,itemsTotal:H}),{data:le}=MAe(e),X=le?.length??0,{currentItemId:te,openItem:se,close:pe}=wVt(),ce=ae=>{te===ae?pe():se(ae)},Se=ae=>{y(ae),m(!0)},ve=ae=>{k(ae),x(!0)},ke=ae=>{x(ae),ae||(k([]),I(fe=>fe+1))},Ne=ae=>{E(ae),C(!0)},Me=async()=>{await ne.mutateAsync({datasetId:e,itemIds:T}),Be.success(`Deleted ${T.length} items`),C(!1),E([]),I(ae=>ae+1)},Ae=ae=>{m(!1),y([]),I(fe=>fe+1),n?.(ae)},Ie=ae=>{m(ae),ae||(y([]),I(fe=>fe+1))};return o.jsxs(o.Fragment,{children:[o.jsxs(yc,{defaultTab:"items",value:i,onValueChange:c,className:"grid h-full grid-rows-[auto_1fr]",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4 px-6 py-3",children:[o.jsxs(vc,{variant:"pill-ghost",children:[o.jsxs(Ar,{value:"items",className:"px-3 py-2.5",children:[o.jsx(He,{size:"sm",children:o.jsx(wx,{})}),o.jsx(me,{variant:"ui-sm",className:"text-inherit",children:"Items"}),o.jsx(St,{size:"sm",children:re})]}),o.jsxs(Ar,{value:"experiments",className:"px-3 py-2.5",children:[o.jsx(He,{size:"sm",children:o.jsx(a0e,{})}),o.jsx(me,{variant:"ui-sm",className:"text-inherit",children:"Experiments"}),o.jsx(St,{size:"sm",children:J.length})]}),o.jsxs(Ar,{value:"review",className:"px-3 py-2.5",children:[o.jsx(He,{size:"sm",children:o.jsx(vO,{})}),o.jsx(me,{variant:"ui-sm",className:"text-inherit",children:"Review"}),X>0&&o.jsx(St,{variant:"yellow",size:"sm",children:X})]})]}),r&&o.jsx("div",{className:"shrink-0 whitespace-nowrap",children:r})]}),o.jsx(fs,{value:"items",className:"border-border1 grid overflow-auto border-t py-0",children:o.jsx(dhs,{items:F,isLoading:B,onItemClick:ce,featuredItemId:te,onAddClick:t??(()=>{}),onImportClick:()=>d(!0),onImportJsonClick:()=>p(!0),onBulkDeleteClick:Ne,onCreateDatasetClick:Se,onAddToDatasetClick:ve,datasetName:D?.name,clearSelectionTrigger:N,setEndOfListElement:z,isFetchingNextPage:V,hasNextPage:M,searchQuery:A,activeSearchQuery:L,onSearchChange:R,currentDatasetVersion:D?.version})}),o.jsx(fs,{value:"experiments",className:"border-border1 grid overflow-auto border-t px-6 pt-3 pb-6",children:o.jsx(ihs,{experiments:J,allExperiments:ee,isLoading:Z,datasetId:e,filters:U,onFiltersChange:$})}),o.jsx(fs,{value:"review",className:"border-border1 overflow-auto border-t px-6 pt-3 pb-6",children:o.jsx(SVt,{datasetId:e})})]}),o.jsx(Kps,{datasetId:e,open:u,onOpenChange:d}),o.jsx(mhs,{datasetId:e,open:f,onOpenChange:p}),o.jsx(jps,{open:h,onOpenChange:Ie,items:v,onSuccess:Ae}),o.jsx(Nps,{open:b,onOpenChange:ke,items:S,currentDatasetId:e}),o.jsx(Pt,{open:_,onOpenChange:C,children:o.jsxs(Pt.Content,{children:[o.jsxs(Pt.Header,{children:[o.jsx(Pt.Title,{children:"Delete Items"}),o.jsxs(Pt.Description,{children:["Are you sure you want to delete ",T.length," item",T.length!==1?"s":"","? This action cannot be undone."]})]}),o.jsxs(Pt.Footer,{children:[o.jsx(Pt.Cancel,{children:"Cancel"}),o.jsx(Pt.Action,{onClick:Me,children:ne.isPending?"Deleting...":"Delete"})]})]})})]})}function kVt({selectedScorers:e,setSelectedScorers:t,disabled:n=!1,container:r,label:s="Scorers (Optional)",helperText:a}){const{data:i,isLoading:l}=oh(),c=Object.entries(i??{}).filter(([,u])=>u.isRegistered).map(([u,d])=>({value:u,label:d.scorer?.config?.name||u,description:d.scorer?.config?.description||""}));return o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{children:s}),a?o.jsx("p",{className:"text-muted-foreground text-xs",children:a}):null,o.jsx(ml,{multiple:!0,options:c,value:e,onValueChange:t,placeholder:"Select scorers...",searchPlaceholder:"Search scorers...",emptyText:"No scorers available",disabled:n||l,container:r})]})}function OVt({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(oc,{id:"override-dataset-scorers",checked:e,onCheckedChange:t,disabled:s}),o.jsx(Mt,{htmlFor:"override-dataset-scorers",children:"Override dataset scorers"})]}),o.jsx("p",{className:"text-muted-foreground text-xs",children:e?"Only selected scorers run for this item. Leave empty to run no scorers.":"Use scorers attached to the dataset."}),e?o.jsx(kVt,{selectedScorers:n,setSelectedScorers:r,disabled:s,label:"Item scorers",helperText:"Choose from scorers that can be resolved by this Mastra instance."}):null]})}function whs(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 Oie({field:e,errors:t}){return t.length?o.jsx("div",{className:"mt-2 space-y-1",children:t.map((n,r)=>o.jsxs("p",{className:"text-destructive text-xs",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function Shs({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=g.useState("{}"),[i,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState(""),[p,h]=g.useState(!1),[m,v]=g.useState([]),[y,b]=g.useState(""),[x,S]=g.useState(null),{addItem:k}=qi(),_=()=>{a("{}"),l(""),u(""),f(""),h(!1),v([]),b(""),S(null)},C=R=>{_(),n(R)},T=async R=>{R.preventDefault();let L;try{L=JSON.parse(s)}catch{Be.error("Input must be valid JSON");return}let D;if(i.trim())try{D=JSON.parse(i)}catch{Be.error("Ground Truth must be valid JSON");return}let F;if(c.trim())try{F=JSON.parse(c)}catch{Be.error("Expected Trajectory must be valid JSON");return}let H;if(d.trim())try{const z=JSON.parse(d);if(!Array.isArray(z)){Be.error("Tool Mocks must be a JSON array");return}H=z}catch{Be.error("Tool Mocks must be valid JSON");return}let B;if(y.trim())try{B=JSON.parse(y)}catch{Be.error("Request Context must be valid JSON");return}try{await k.mutateAsync({datasetId:e,input:L,groundTruth:D,expectedTrajectory:F,toolMocks:H,scorerIds:p?m:void 0,requestContext:B}),Be.success("Item added successfully"),C(!1),r?.()}catch(z){const V=whs(z);V?S(V):Be.error(`Failed to add item: ${z instanceof Error?z.message:"Unknown error"}`)}},E=R=>{a(R),x?.field==="input"&&S(null)},N=R=>{l(R),x?.field==="groundTruth"&&S(null)},I=R=>{f(R),x?.field==="toolMocks"&&S(null)},A=()=>{C(!1)};return o.jsxs(Sa,{dialogTitle:"Add Item",dialogDescription:"Create a new dataset item",isOpen:t,onClose:A,level:1,children:[o.jsx(Sa.Top,{children:"Add Item"}),o.jsxs(Sa.Content,{children:[o.jsx(Sa.Header,{children:o.jsx(Sa.Heading,{children:"Add Item"})}),o.jsxs("form",{onSubmit:T,className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Zr,{value:s,onChange:E,showCopyButton:!1,className:"min-h-[240px]"}),x?.field==="input"&&o.jsx(Oie,{field:"input",errors:x.errors})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{htmlFor:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),o.jsx(Zr,{value:i,onChange:N,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="groundTruth"&&o.jsx(Oie,{field:"groundTruth",errors:x.errors})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{htmlFor:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),o.jsx(Zr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[200px]"})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{htmlFor:"item-tool-mocks",children:"Tool Mocks (JSON array, optional)"}),o.jsx(Zr,{value:d,onChange:I,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="toolMocks"&&o.jsx(Oie,{field:"toolMocks",errors:x.errors})]}),o.jsx(OVt,{overrideEnabled:p,onOverrideEnabledChange:h,selectedScorerIds:m,onSelectedScorerIdsChange:v,disabled:k.isPending}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{htmlFor:"item-request-context",children:"Request Context (JSON, optional)"}),o.jsx(Zr,{value:y,onChange:b,showCopyButton:!1,className:"min-h-[200px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(oe,{type:"button",onClick:A,children:"Cancel"}),o.jsx(oe,{type:"submit",variant:"primary",disabled:k.isPending,children:k.isPending?"Adding...":"Add Item"})]})]})]})]})}function khs({item:e}){return o.jsx(Ia,{withMargins:!1,children:o.jsxs(Ia.Column,{children:[o.jsxs(Ia.Title,{size:"smaller",children:[o.jsx(vV,{}),o.jsx("span",{className:"truncate",children:e.id}),o.jsx(ka,{content:e.id,tooltip:`Copy item ID: ${e.id}`})]}),o.jsxs(Ia.Description,{children:[o.jsxs(Nl,{children:[o.jsx(uQt,{})," Created ",hr(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")]}),e.datasetVersion!=null&&o.jsxs(Nl,{children:[o.jsx(rI,{})," Version v",e.datasetVersion]})]})]})})}function LAe({item:e}){const t=e?.input?JSON.stringify(e.input,null,2):"null",n=e?.groundTruth?JSON.stringify(e.groundTruth,null,2):"null",r=e?.metadata?JSON.stringify(e.metadata,null,2):"null",s=e?.expectedTrajectory?JSON.stringify(e.expectedTrajectory,null,2):null;return o.jsxs(M9r,{children:[o.jsx(Sa.CodeSection,{title:"Input",icon:o.jsx(xx,{}),codeStr:t}),o.jsx(Sa.CodeSection,{title:"Ground Truth",icon:o.jsx(em,{}),codeStr:n}),s&&o.jsx(Sa.CodeSection,{title:"Expected Trajectory",icon:o.jsx(p0e,{}),codeStr:s}),o.jsx(Sa.CodeSection,{title:"Scorers",icon:o.jsx(wV,{}),codeStr:e.scorerIds===void 0?"Inherited from dataset":JSON.stringify(e.scorerIds,null,2)}),o.jsx(Sa.CodeSection,{title:"Metadata",icon:o.jsx(sI,{}),codeStr:r})]})}function _ie({field:e,errors:t}){return t.length?o.jsx("div",{className:"mt-2 space-y-1",children:t.map((n,r)=>o.jsxs("p",{className:"text-destructive text-xs",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function Ohs({inputValue:e,setInputValue:t,groundTruthValue:n,setGroundTruthValue:r,metadataValue:s,setMetadataValue:a,trajectoryValue:i,setTrajectoryValue:l,toolMocksValue:c,setToolMocksValue:u,scorerOverrideEnabled:d,setScorerOverrideEnabled:f,selectedScorerIds:p,setSelectedScorerIds:h,requestContextValue:m,setRequestContextValue:v,validationErrors:y,onSave:b,onCancel:x,isSaving:S}){return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"mb-4",children:o.jsxs("h3",{className:"flex items-center gap-2 text-lg font-medium",children:[o.jsx(um,{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(Mt,{children:"Input (JSON) *"}),o.jsx(Zr,{value:e,onChange:t,showCopyButton:!1,className:"min-h-[120px]"}),y?.field==="input"&&o.jsx(_ie,{field:"input",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mt,{children:"Ground Truth (JSON, optional)"}),o.jsx(Zr,{value:n,onChange:r,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="groundTruth"&&o.jsx(_ie,{field:"groundTruth",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mt,{children:"Expected Trajectory (JSON, optional)"}),o.jsx(Zr,{value:i,onChange:l,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mt,{children:"Tool Mocks (JSON array, optional)"}),o.jsxs("p",{className:"text-muted-foreground text-xs",children:["Ordered static mocks served in place of executing the tool. Each entry is"," ",o.jsx("code",{children:'{ "toolName", "args", "output" }'}),". Calling a mocked tool with non-matching args fails the item; unmocked tools run live."]}),o.jsx(Zr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="toolMocks"&&o.jsx(_ie,{field:"toolMocks",errors:y.errors})]}),o.jsx(OVt,{overrideEnabled:d,onOverrideEnabledChange:f,selectedScorerIds:p,onSelectedScorerIdsChange:h,disabled:S}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mt,{children:"Request Context (JSON, optional)"}),o.jsx(Zr,{value:m,onChange:v,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mt,{children:"Metadata (JSON, optional)"}),o.jsx(Zr,{value:s,onChange:a,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex gap-2 pt-4",children:[o.jsx(oe,{variant:"primary",onClick:b,disabled:S,children:S?"Saving...":"Save Changes"}),o.jsx(oe,{onClick:x,disabled:S,children:"Cancel"})]})]})]})}const _hs=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function Chs({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:a,isLoading:i}=Dm(),{data:l,isLoading:c}=Wy(),{data:u,isLoading:d}=oh(),f=e==="agent"?Object.entries(a??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="workflow"?Object.entries(l??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="scorer"?Object.entries(u??{}).map(([v,y])=>({value:v,label:y.scorer?.config?.name??v})):[],p=e==="agent"&&i||e==="workflow"&&c||e==="scorer"&&d,h=v=>{t(v),r("")},m=e==="agent"?"Agent":e==="workflow"?"Workflow":"Scorer";return o.jsxs("div",{className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{children:"Target Type"}),o.jsx(ml,{options:_hs,value:e,onValueChange:h,placeholder:"Select target type",searchPlaceholder:"Search types...",emptyText:"No types available",container:s})]}),e&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{children:m}),o.jsx(ml,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:p,container:s})]})]})}function Ehs({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return vm(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(Mt,{children:"Request Context"}),o.jsx(U3,{schema:n,onValuesChange:t,className:"[&_button[type=submit]]:hidden"})]}):o.jsx("p",{className:"text-destructive text-sm",children:"Failed to parse request context schema"})}function FAe({initialDatasetId:e,initialDatasetVersion:t,initialScorerIds:n,open:r,onOpenChange:s,onSuccess:a}){const i=g.useRef(null),[l,c]=g.useState(e??""),[u,d]=g.useState(t??null),[f,p]=g.useState(""),[h,m]=g.useState(""),[v,y]=g.useState(n??[]),[b,x]=g.useState({}),[S,k]=g.useState(""),{triggerExperiment:_}=qi(),{data:C}=Yg(l),T=C?.requestContextSchema,E=!!(T&&Object.keys(T).length>0),N=l&&f&&h,I=_.isPending,A=H=>{c(H),d(null),x({})},R=()=>{c(e??""),d(t??null),p(""),m(""),y(n??[]),x({}),k("")},L=()=>{if(E){const H=Object.entries(b).filter(([,B])=>B!==void 0&&B!=="");return H.length>0?Object.fromEntries(H):void 0}if(S.trim()){let H;try{H=JSON.parse(S)}catch{throw new Error("Request Context must be valid JSON")}if(!H||typeof H!="object"||Array.isArray(H))throw new Error("Request Context must be a JSON object");return H}},D=async()=>{if(!N)return;let H;try{H=L()}catch(B){const z=B instanceof Error?B.message:"Request Context must be valid JSON";gu.error(z);return}try{const B=await _.mutateAsync({datasetId:l,targetType:f,targetId:h,scorerIds:v.length>0?v:void 0,version:u??void 0,requestContext:H});gu.success("Experiment triggered successfully"),s(!1),a?.(B.experimentId),R()}catch(B){const z=B instanceof Error?B.message:"Failed to trigger experiment";gu.error(z)}},F=()=>{I||(s(!1),R())};return o.jsx(vr,{open:r,onOpenChange:F,children:o.jsxs(yr,{ref:i,children:[o.jsxs(br,{children:[o.jsx(pr,{children:"Run Experiment"}),o.jsx(Ps,{children:u!=null?`Execute items from version v${u} of the dataset against a target.`:"Execute dataset items against a target."})]}),o.jsxs(Mr,{className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{children:"Dataset"}),o.jsx(Mps,{value:l,onValueChange:A,container:i})]}),l&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{children:"Version"}),o.jsx(gVt,{datasetId:l,value:u,onValueChange:d,container:i})]})]}),o.jsx(Chs,{targetType:f,setTargetType:p,targetId:h,setTargetId:m,container:i}),o.jsx(kVt,{selectedScorers:v,setSelectedScorers:y,disabled:I,container:i}),E?o.jsx(Ehs,{requestContextSchema:T,onChange:x}):o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mt,{children:"Request Context (JSON, optional)"}),o.jsx(Zr,{value:S,onChange:k,showCopyButton:!1,className:"min-h-[80px]"})]})]}),o.jsxs(lc,{className:"px-6 pt-4",children:[o.jsx(oe,{onClick:F,disabled:I,children:"Cancel"}),o.jsx(oe,{variant:"primary",onClick:D,disabled:!N||I,children:I?o.jsxs(o.Fragment,{children:[o.jsx(Ut,{className:"h-4 w-4"}),"Running..."]}):"Run"})]})]})})}const _Vt=g.createContext(null);function Ths({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:a,children:i}){const l=es(),u=mgt("/experiments/:experimentId/items/:itemId")?.params.itemId,d=g.useCallback(b=>{l(`/experiments/${e}/items/${encodeURIComponent(b)}`)},[l,e]),f=g.useCallback(()=>{l(`/experiments/${e}`)},[l,e]),p=g.useCallback(b=>{l(`/experiments/${e}?review=${encodeURIComponent(b)}`)},[l,e]),h=g.useMemo(()=>u?r.findIndex(b=>b.itemId===u):-1,[r,u]),m=g.useMemo(()=>{if(h<=0)return;const b=r[h-1].itemId;return()=>d(b)},[h,r,d]),v=g.useMemo(()=>{if(h<0||h>=r.length-1)return;const b=r[h+1].itemId;return()=>d(b)},[h,r,d]);bVt({active:!!u,onPrevious:m,onNext:v,onClose:f});const y=g.useMemo(()=>({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:a,currentItemId:u,openItem:d,close:f,openInReview:p,goToPreviousItem:m,goToNextItem:v}),[e,t,n,r,s,a,u,d,f,p,m,v]);return o.jsx(_Vt.Provider,{value:y,children:i})}function CVt(){const e=g.useContext(_Vt);if(!e)throw new Error("useExperimentItemPanel must be used within an ExperimentItemPanelProvider");return e}function jhs({results:e,isLoading:t,featuredResultId:n,onResultClick:r,columns:s,scoresByItemId:a,scorerIds:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u,selectedIds:d,onToggleSelect:f}){const{Link:p,paths:h}=cn(),m=!!(d&&f),v=[m?"auto":"",...s.map(k=>k.size)].filter(Boolean).join(" "),y=s.some(k=>k.name==="input"),{containerRef:b,getRowProps:x}=wo({count:e.length}),S=k=>i?.includes(k.name)?o.jsx(be.TopCell,{children:o.jsxs(p,{href:h.scorerLink(k.name),target:"_blank",rel:"noopener noreferrer",className:"flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[o.jsx(TC,{}),o.jsx("span",{className:"min-w-0 truncate",children:k.label}),o.jsx(Yr,{className:"text-neutral3"})]})},k.name):o.jsx(be.TopCell,{children:k.label},k.name);return t?o.jsx(Pl,{columns:v}):o.jsxs(be,{columns:v,className:"min-w-0",scrollRef:b,children:[o.jsxs(be.Top,{hasLeadingCell:m,children:[m&&o.jsx(be.TopCell,{children:" "}),m?o.jsx(be.TopCells,{colStart:2,children:s.map(S)}):s.map(S)]}),e.length===0?o.jsx(be.NoMatch,{message:"No results yet"}):o.jsxs(o.Fragment,{children:[e.map((k,_)=>{const C=!!k.error,T=k.id===n,E=o.jsxs(o.Fragment,{children:[o.jsxs(be.Cell,{className:"text-ui-smd text-neutral3 flex items-center gap-1.5 tracking-wide",children:[o.jsx("span",{children:k.itemId?.slice(0,8)??""}),C&&o.jsxs(yn,{children:[o.jsx(gn,{render:o.jsx(hO,{role:"img","aria-label":"Error",className:"text-error size-3.5"})}),o.jsx(vn,{children:k.error?.message||"Error"})]})]}),y&&o.jsx(be.TextCell,{font:"mono",children:Ihs(Nhs(k.input),200)}),i?.map(N=>{const A=a?.[k.itemId]?.find(R=>R.scorerId===N);return o.jsx(be.Cell,{className:"text-neutral3 text-ui-smd font-mono",children:A!=null?A.score.toFixed(3):"-"},N)})]});return m?o.jsxs(be.RowWrapper,{children:[o.jsx(be.SelectCell,{checked:d.has(k.id),onToggle:()=>f(k.id),"aria-label":`Select result ${k.itemId}`}),o.jsx(be.RowButton,{colStart:2,featured:T,"data-selected":T||void 0,onClick:()=>r(k.id),...x(_),children:E})]},k.id):o.jsx(be.RowButton,{featured:T,"data-selected":T||void 0,onClick:()=>r(k.id),...x(_),children:E},k.id)}),o.jsx(be.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function Nhs(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Ihs(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}function Ahs({scoresByItemId:e,experimentStatus:t}){const{Link:n,paths:r}=cn(),{data:s}=oh(),a=g.useMemo(()=>{if(!e)return[];const i={};for(const l of Object.values(e))for(const c of l)i[c.scorerId]||(i[c.scorerId]={sum:0,count:0}),i[c.scorerId].sum+=c.score,i[c.scorerId].count++;return Object.entries(i).map(([l,{sum:c,count:u}])=>({scorerId:l,avg:c/u})).sort((l,c)=>l.scorerId.localeCompare(c.scorerId))},[e]);if(a.length===0){const i=t==="running"||t==="pending",l=e!==void 0;let c,u;return i?(c="Experiment in progress",u="Summary metrics will appear here once the experiment completes."):l?(c="No scorers configured",u="Add scorers when triggering an experiment to evaluate results and see summary metrics here."):(c="Loading scores",u="Fetching scorer results…"),o.jsxs("div",{className:"text-ui-sm text-neutral3 flex items-center gap-2",children:[o.jsx(Wp,{className:"text-neutral3 size-4 shrink-0"}),o.jsx("span",{className:"text-neutral4",children:c}),o.jsx("span",{className:"truncate",children:u})]})}return o.jsx("div",{className:"flex items-stretch gap-2 overflow-x-auto pb-1",children:a.map(({scorerId:i,avg:l})=>{const c=s?.[i]?.scorer?.config?.name??i;return o.jsxs(Xr,{className:"w-52 min-w-0 flex-none p-3",children:[o.jsxs(n,{href:r.scorerLink(i),target:"_blank",rel:"noopener noreferrer",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(yn,{children:[o.jsx(gn,{render:o.jsx(TC,{role:"img","aria-label":"Scorer"})}),o.jsx(vn,{children:"Scorer"})]}),o.jsx("span",{className:"truncate",children:c}),o.jsx(Yr,{})]}),o.jsxs("strong",{className:"text-ui-lg text-neutral4 font-semibold",children:[l.toFixed(3),o.jsx("span",{className:"text-ui-sm text-neutral3 ml-1.5 font-normal",children:"avg score"})]})]},i)})})}function Rhs({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoading:s,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l}){const{currentItemId:c,openItem:u,close:d}=CVt(),[f,p]=g.useState(new Set),[h,m]=g.useState(!1),{updateExperimentResult:v}=qi(),y=g.useCallback(B=>{p(z=>{const V=new Set(z);return V.has(B)?V.delete(B):V.add(B),V})},[]),b=g.useCallback(()=>p(new Set),[]),x=g.useCallback(async B=>{if(h||B.length===0)return;m(!0);let z=0;const V=new Set;try{for(const M of B)try{await v.mutateAsync({datasetId:t,experimentId:e,resultId:M,status:"needs-review"}),z++,V.add(M)}catch{}}finally{m(!1)}V.size>0&&p(M=>{const G=new Set(M);for(const U of V)G.delete(U);return G}),z>0&&Be(`${z} result${z>1?"s":""} flagged for review`)},[t,e,h,v]),S=g.useMemo(()=>c?r.find(B=>B.itemId===c)?.id??null:null,[r,c]),[k,_]=g.useState("results"),[C,T]=hi(),E=C.get("review"),N=c?"results":E?"reviews":k,I=B=>{_(B),B!=="results"&&c&&d(),B!=="reviews"&&E&&T(z=>{const V=new URLSearchParams(z);return V.delete("review"),V},{replace:!0})},{data:A}=MAe(t),R=(A??[]).filter(B=>B.experimentId===e).length,{data:L}=w_(e,n),D=g.useMemo(()=>{if(!L)return[];const B=new Set;for(const z of Object.values(L))for(const V of z)B.add(V.scorerId);return[...B].sort()},[L]),F=g.useCallback(B=>{const z=r.find(V=>V.id===B);z&&(z.itemId===c?d():u(z.itemId))},[r,c,d,u]),H=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"7rem"},{name:"input",label:"Input",size:"minmax(15rem,1fr)"},...D.map(B=>({name:B,label:B,size:"12rem"}))],[D]);return o.jsxs(yc,{defaultTab:"results",value:N,onValueChange:I,className:"grid h-full grid-rows-[auto_1fr] overflow-visible",children:[o.jsxs(vc,{variant:"pill-ghost",children:[o.jsxs(Ar,{value:"results",className:"px-3 py-2.5",children:[o.jsx(He,{size:"sm",children:o.jsx(wx,{})}),o.jsx(me,{variant:"ui-sm",className:"text-inherit",children:"Results"})]}),o.jsxs(Ar,{value:"reviews",className:"px-3 py-2.5",children:[o.jsx(He,{size:"sm",children:o.jsx(vO,{})}),o.jsx(me,{variant:"ui-sm",className:"text-inherit",children:"Reviews"}),R>0&&o.jsx(St,{size:"xs",children:R})]})]}),o.jsx(fs,{value:"reviews",className:"h-full min-h-0 overflow-visible py-0",children:o.jsx(SVt,{datasetId:t,experimentId:e,featuredItemId:E,detailPanelVariant:"overlay"})}),o.jsxs(fs,{value:"results",className:K("grid gap-3 overflow-hidden pt-3",f.size>0?"grid-rows-[auto_auto_1fr]":"grid-rows-[auto_1fr]"),children:[o.jsx(Ahs,{scoresByItemId:L,experimentStatus:n}),f.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(oe,{variant:"outline",size:"sm",disabled:h,onClick:()=>x([...f]),children:[o.jsx(He,{size:"sm",children:o.jsx(vO,{})}),"Flag ",f.size," to review"]}),o.jsx(oe,{variant:"ghost",size:"sm",onClick:b,children:"Clear"})]}),o.jsx("div",{className:"min-h-0 overflow-y-auto",children:o.jsx(jhs,{results:r,isLoading:s,featuredResultId:S,onResultClick:F,columns:H,scoresByItemId:L,scorerIds:D,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l,selectedIds:f,onToggleSelect:y})})]})]})}const Pet={pending:{icon:o.jsx(r1,{className:"text-warning1 size-4"}),label:"Pending"},running:{icon:o.jsx(Ut,{size:"sm"}),label:"Running"},completed:{icon:o.jsx(WD,{className:"text-neutral3 size-4"}),label:"Completed"},failed:{icon:o.jsx(gO,{className:"text-error size-4"}),label:"Failed"}};function Phs({status:e,className:t}){const n=Pet[e]??Pet.pending;return o.jsxs(yn,{children:[o.jsx(gn,{render:o.jsx("span",{tabIndex:0,className:K("flex shrink-0 items-center",t),children:n.icon})}),o.jsx(vn,{children:n.label})]})}const $hs=e=>{const t=Qe();return yt({queryKey:["experiment-trace-light",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return t.getTraceLight(e)},select:uAe,enabled:!!e})},Mhs={present:!1,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},$et=e=>e?e instanceof Date?e.toISOString():e:null,Met=e=>{const t=new Map;for(const n of e??[])t.set(n.itemId,n);return t},Det=(e,t,n)=>{if(!e)return Mhs;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:$et(t?.startedAt),completedAt:$et(t?.completedAt),scores:Object.entries(e.scores).map(([s,a])=>({scorerId:s,value:a,reason:r.get(s)??null})).sort((s,a)=>s.scorerId.localeCompare(a.scorerId))}},Dhs=({comparison:e,baselineId:t,contenderId:n,baselineResults:r,contenderResults:s,baselineScores:a,contenderScores:i})=>{if(!e)return[];const l=Met(r),c=Met(s);return e.items.map(u=>{const d=Det(u.results[t],l.get(u.itemId),a?.[u.itemId]),f=Det(u.results[n],c.get(u.itemId),i?.[u.itemId]),p={};for(const h of new Set([...d.scores,...f.scores].map(m=>m.scorerId))){const m=d.scores.find(y=>y.scorerId===h)?.value??null,v=f.scores.find(y=>y.scorerId===h)?.value??null;p[h]=m!=null&&v!=null?v-m:null}return{itemId:u.itemId,input:u.input,groundTruth:u.groundTruth,baseline:d,contender:f,deltas:p}})};function Tk({title:e,actions:t,tone:n="default",defaultOpen:r=!0,children:s}){return o.jsxs(Fc,{defaultOpen:r,className:"grid gap-2",children:[o.jsxs("div",{className:"flex min-h-6 items-center justify-between gap-2",children:[o.jsxs(cc,{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(Ur,{}),e]}),t]}),o.jsx(uc,{role:"region","aria-label":e,children:s})]})}function Let({label:e,value:t}){return t==null?null:o.jsx(Tk,{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 EVt({delta:e}){const t=e>0?"text-positive1":e<0?"text-negative1":"text-neutral3";return o.jsxs("span",{className:K("inline-flex min-w-20 items-center gap-1 font-mono text-sm",t),children:[o.jsx("span",{className:"inline-block w-3",children:e>0?"+":e<0?"-":""}),Math.abs(e).toFixed(2),e>0?o.jsx(BGt,{className:"size-3.5"}):e<0?o.jsx(IGt,{className:"size-3.5"}):null]})}function TVt({scorerId:e,value:t,delta:n,reason:r}){const{Link:s,paths:a}=cn();return o.jsxs("div",{className:"bg-surface2 grid gap-1 rounded-lg px-3 py-2",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4",children:[o.jsxs(s,{href:a.scorerLink(e),target:"_blank",rel:"noopener noreferrer","aria-label":`Open ${e}`,className:"text-neutral5 flex min-w-0 items-center gap-1.5 text-sm font-medium hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[o.jsx(TC,{}),o.jsx("span",{className:"min-w-0 truncate",children:e}),o.jsx(Yr,{})]}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:"text-neutral3 font-mono text-sm",children:t!=null?t.toFixed(2):"-"}),n!=null&&o.jsx(EVt,{delta:n})]})]}),r&&o.jsx("p",{className:"text-neutral3 text-sm",children:r})]})}function Fet(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Lhs(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 Fhs="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 zet({side:e,row:t,showDeltas:n,isLoading:r}){const s=t[e],a=Lhs(s);if(r)return o.jsx("div",{className:"flex h-32 items-center justify-center",children:o.jsx(Ut,{})});if(!s.present)return o.jsx("p",{className:"text-neutral3 py-8 text-center text-sm",children:"Not present in this experiment"});const i=Fet(s.output);return o.jsxs("div",{className:"grid content-start gap-5",children:[a&&o.jsxs(yn,{children:[o.jsx(gn,{render:o.jsxs("p",{className:"text-neutral3 flex items-center justify-end gap-1.5 text-sm [&>svg]:size-3.5",children:[o.jsx(r1,{}),a]})}),o.jsx(vn,{children:"Run duration"})]}),s.error?o.jsx(Tk,{title:"Error",tone:"negative",actions:o.jsx(ka,{content:s.error.message}),children:o.jsx("p",{className:"border-negative1/40 bg-negative1/5 text-ui-md text-neutral4 rounded-xl border p-4 break-words",children:s.error.message})}):o.jsx(Tk,{title:"Output",actions:o.jsx(ka,{content:i}),children:o.jsx("pre",{className:Fhs,children:i})}),s.scores.length>0&&o.jsx(Tk,{title:"Scores",children:o.jsx("div",{className:"grid gap-2",children:s.scores.map(l=>o.jsx(TVt,{scorerId:l.scorerId,value:l.value,delta:n?t.deltas[l.scorerId]:null,reason:l.reason},l.scorerId))})}),s.comment&&o.jsx(Tk,{title:"Comment",defaultOpen:!1,children:o.jsx("p",{className:"text-neutral3 text-sm",children:s.comment})}),s.metadata&&Object.keys(s.metadata).length>0&&o.jsx(Tk,{title:"Metadata",defaultOpen:!1,children:o.jsx("dl",{className:"grid gap-1",children:Object.entries(s.metadata).map(([l,c])=>o.jsxs("div",{className:"flex items-start justify-between gap-4 text-sm",children:[o.jsx("dt",{className:"text-neutral3",children:l}),o.jsx("dd",{className:"text-neutral5 font-mono break-all",children:Fet(c)})]},l))})})]})}const zhs={baseline:"Baseline",contender:"Contender"},Bhs={baseline:"purple",contender:"blue"},Uhs="flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0";function Bet({side:e,experiment:t,summary:n,showDeltas:r,versionMismatch:s}){const{Link:a,paths:i}=cn(),l=zhs[e],c=t?dS(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(St,{variant:Bhs[e],size:"xs",children:l}),t&&o.jsxs(oe,{as:a,size:"xs",href:`/experiments/${t.id}`,target:"_blank",rel:"noopener noreferrer","aria-label":`Open experiment ${t.name||c}`,children:[o.jsx("span",{className:"min-w-0 truncate",children:t.name||c}),o.jsx(Yr,{})]})]}),t&&o.jsxs("div",{className:"text-ui-sm text-neutral3 flex flex-wrap gap-x-4 gap-y-1",children:[t.name&&o.jsxs(Nl,{children:[o.jsx(bV,{})," ",c]}),t.targetType==="agent"&&t.targetId?o.jsxs(a,{href:i.agentLink(t.targetId),target:"_blank",rel:"noopener noreferrer",className:Uhs,children:[o.jsx(Ti,{}),o.jsx("span",{className:"min-w-0 truncate",children:t.targetId}),o.jsx(Yr,{})]}):o.jsxs(Nl,{children:[o.jsx(ect,{})," ",t.targetId]}),o.jsx("span",{className:K(s&&"text-accent6"),children:o.jsxs(Nl,{children:[o.jsx(xV,{})," v",t.datasetVersion??"—",s&&" · different dataset version"]})}),u&&o.jsxs(Nl,{children:[o.jsx(I9,{})," ",hr(u,"MMM d, yyyy HH:mm")]})]}),d.length>0&&o.jsx(Tk,{title:"Overall score",children:o.jsx("div",{className:"grid gap-2",children:d.map(({scorerId:f,average:p,delta:h})=>o.jsx(TVt,{scorerId:f,value:p,delta:r?h:null},f))})})]})}const FE="min-w-0 px-4 py-3";function qhs({datasetId:e,experimentIdA:t,experimentIdB:n}){const{Link:r,paths:s}=cn(),{data:a,isLoading:i,error:l}=Ufs(e,t,n),{data:c}=Exe(e,t),{data:u}=Exe(e,n),d=c&&u&&c.datasetVersion!==u.datasetVersion,f=a?.baselineId??t,p=t===f?n:t,h=c?.id===f?c:u,m=c?.id===p?c:u,{data:v,isLoading:y}=LD({datasetId:e,experimentId:f,experimentStatus:h?.status}),{data:b,isLoading:x}=LD({datasetId:e,experimentId:p,experimentStatus:m?.status}),{data:S}=w_(f,h?.status),{data:k}=w_(p,m?.status),_=g.useMemo(()=>Dhs({comparison:a,baselineId:f,contenderId:p,baselineResults:v,contenderResults:b,baselineScores:S,contenderScores:k}),[a,f,p,v,b,S,k]),C=g.useMemo(()=>[...new Set(_.flatMap(E=>Object.keys(E.deltas)))].sort(),[_]),T=g.useMemo(()=>{const E=(A,R)=>{const L=_.map(D=>D[A].scores.find(F=>F.scorerId===R)?.value).filter(D=>D!=null);return L.length>0?L.reduce((D,F)=>D+F,0)/L.length:null},N=C.map(A=>({scorerId:A,average:E("baseline",A),delta:null})),I=C.map(A=>{const R=E("baseline",A),L=E("contender",A);return{scorerId:A,average:L,delta:R!=null&&L!=null?L-R:null}});return{baseline:N,contender:I}},[_,C]);return i?o.jsx("div",{className:"flex h-64 items-center justify-center",children:o.jsx(Ut,{})}):l?o.jsx(Wn,{variant:"warning",title:"Error loading comparison",children:o.jsx(Wn.Message,{children:l instanceof Error?l.message:"Unknown error"})}):!a||a.items.length===0?o.jsx("div",{className:"text-neutral4 py-8 text-center text-sm",children:"No comparison data"}):o.jsx("div",{className:"grid gap-4",children:o.jsxs("div",{role:"table","aria-label":"Experiments comparison",className:"grid",children:[o.jsxs("div",{role:"row",className:"border-border1 grid border-y xl:grid-cols-[minmax(20rem,24rem)_1fr_1fr] xl:divide-x xl:divide-[var(--border1)]",children:[o.jsx("div",{role:"columnheader","aria-label":"Items",className:`${FE} text-neutral3 text-ui-sm uppercase`,children:"Items"}),o.jsx("div",{role:"columnheader","aria-label":"Baseline",className:FE,children:o.jsx(Bet,{side:"baseline",experiment:h,summary:T.baseline,versionMismatch:d})}),o.jsx("div",{role:"columnheader","aria-label":"Contender",className:FE,children:o.jsx(Bet,{side:"contender",experiment:m,summary:T.contender,versionMismatch:d,showDeltas:!0})})]}),_.map(E=>{const N=Object.entries(E.deltas).filter(([,I])=>I!=null&&I!==0);return o.jsxs("div",{role:"row","aria-label":E.itemId,className:"border-border1 grid border-b xl:grid-cols-[minmax(20rem,24rem)_1fr_1fr] xl:divide-x xl:divide-[var(--border1)]",children:[o.jsxs("div",{role:"cell",className:`${FE} grid content-start gap-1`,children:[o.jsxs(r,{href:s.datasetItemLink(e,E.itemId),target:"_blank",rel:"noopener noreferrer","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}),o.jsx(Yr,{})]}),N.length>0&&o.jsx("span",{className:"flex flex-wrap items-center gap-2",children:N.map(([I,A])=>o.jsx(EVt,{delta:A},I))}),o.jsxs("div",{className:"grid pt-3",children:[o.jsx(Let,{label:"Input",value:E.input}),o.jsx(Let,{label:"Ground truth",value:E.groundTruth})]})]}),o.jsx("div",{role:"cell","aria-label":"Baseline",className:FE,children:o.jsx(zet,{side:"baseline",row:E,isLoading:y})}),o.jsx("div",{role:"cell","aria-label":"Contender",className:FE,children:o.jsx(zet,{side:"contender",row:E,isLoading:x,showDeltas:!0})})]},E.itemId)})]})})}function jVt({children:e,className:t}){return o.jsx("div",{className:K("",t),children:e})}function Vhs({date:e,className:t,withTime:n=!1}){const r=e?rxt(new Date(e)):!1,s=e?$3(new Date(e))?"Today":hr(new Date(e),"MMM dd"):"",a=e&&!r?hr(new Date(e),"yyyy"):"",i=e&&n?`${hr(new Date(e),"'at' h:mm aaa")}`:"";return o.jsxs("div",{className:K("truncate text-ui-md text-neutral2",t),children:[s," ",a," ",i]})}function zAe(e){return!e||e.length===0?"":e?.map(t=>t.size).join(" ")}function Hhs({columns:e,isSelectionActive:t,children:n}){return o.jsx("div",{className:K("sticky top-0 z-10 mb-4 rounded-lg bg-surface3 px-4"),children:o.jsx("div",{className:K("grid items-center gap-4 text-left text-ui-xs tracking-widest text-neutral3 uppercase",{"pl-12 [&>label]:absolute [&>label]:left-0":t}),style:{gridTemplateColumns:zAe(e)},children:n})})}function Whs({children:e,className:t}){return o.jsx("span",{className:K("py-3",t),children:e})}function Zhs({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 Ghs({children:e}){return o.jsx("ul",{className:"grid content-start",children:e})}function Qhs({children:e}){const t=g.useRef(null);return o.jsx("div",{ref:t,className:K("overflow-y-auto"),children:e})}function Yhs({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 Khs({children:e,href:t,className:n,LinkComponent:r,tooltip:s}){const a=o.jsx(r,{href:t,className:K("flex w-full items-center justify-center gap-6 rounded-lg px-3 py-[0.6rem] text-left","hover:bg-surface4",Gr.colors,j3.visible,n),children:e});return s==null?a:o.jsxs(yn,{children:[o.jsx(gn,{render:a}),o.jsx(vn,{children:s})]})}function Xhs({children:e,message:t,className:n,type:r}){return!e&&!t?null:o.jsx("div",{className:K("grid border-t border-border1",n),children:t?o.jsxs("p",{className:K("grid justify-center justify-items-center gap-2 p-8 text-center text-ui-md text-neutral3","[&>svg]:size-[1.5em] [&>svg]:opacity-75",{"[&>svg]:text-red-500":r==="error"}),children:[r==="error"?o.jsx(ac,{}):o.jsx(km,{})," ",t]}):e})}function Jhs({isLoading:e,hasMore:t,setEndOfListElement:n,loadingText:r="Loading more data...",noMoreDataText:s="No more data to load"}){return n?o.jsxs("div",{ref:n,className:"text-ui-md text-neutral3 mt-8 flex justify-center opacity-50",children:[e&&r,!t&&!e&&s]}):null}function ems({currentPage:e,hasMore:t,onNextPage:n,onPrevPage:r}){const s=typeof e=="number"&&e>0||t;return o.jsxs("div",{className:K("flex items-center justify-center gap-8 pt-6 text-ui-md text-neutral3"),children:[o.jsxs("span",{children:["Page ",o.jsx("b",{children:e?e+1:"1"})]}),s&&o.jsxs("div",{className:K("flex gap-4","[&>button]:flex [&>button]:items-center [&>button]:gap-2 [&>button]:rounded-md [&>button]:border [&>button]:border-border1 [&>button]:p-1 [&>button]:px-2 [&>button]:text-neutral4 [&>button]:transition-colors [&>button:hover]:text-neutral5","[&_svg]:size-[1em] [&_svg]:text-neutral3"),children:[typeof e=="number"&&e>0&&o.jsxs("button",{onClick:r,children:[o.jsx(gl,{}),"Previous"]}),t&&o.jsxs("button",{onClick:n,children:["Next",o.jsx(Fd,{})]})]})]})}function tms({children:e,className:t}){return o.jsx("div",{className:K("grid grid-rows-[auto_1fr] overflow-y-auto",t),children:e})}function nms({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",Gr.colors,{"selected-row":e,"grid px-4 gap-4 ":n}),style:{gridTemplateColumns:zAe(n)},children:t})}function rms({item:e,isFeatured:t,onClick:n,children:r,columns:s,className:a,disabled:i,tooltip:l,...c}){const u=()=>{n?.(e?.id)},d=o.jsx("button",{...c,onClick:u,className:K("grid w-full items-center gap-4 rounded-lg px-4 text-left",Gr.colors,j3.visible,{"bg-surface4":t,"hover:bg-surface4":e&&!t&&!i},a),style:{gridTemplateColumns:zAe(s)},disabled:i,children:r});return l==null?d:o.jsxs(yn,{children:[o.jsx(gn,{render:d}),o.jsx(vn,{children:l})]})}function sms(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ams({status:e}){return e?o.jsxs(yn,{children:[o.jsx(gn,{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(vn,{children:sms(e)})]}):null}function ims({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 dV={latest:"Latest version",deleted:"Deleted in this version"};function oms({isLatest:e,isDeleted:t}){const n=[];return e&&n.push(dV.latest),t&&n.push(dV.deleted),n.length>0?n.join(" · "):void 0}function lms({version:e,date:t,isLatest:n,isDeleted:r}){return o.jsxs(jVt,{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?hr(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":dV.latest,children:o.jsx(St,{variant:"blue",size:"sm",icon:o.jsx(r1,{})})}),r&&o.jsx("span",{className:"inline-flex",role:"img","aria-label":dV.deleted,children:o.jsx(St,{variant:"red",size:"sm",icon:o.jsx(t0e,{})})})]})]})}const li=Object.assign(tms,{Header:Hhs,HeaderCol:Whs,Items:Ghs,Scroller:Qhs,Row:nms,RowButton:rms,Message:Xhs,NextPageLoading:Jhs,Pagination:ems,Cell:jVt,TextCell:ims,StatusCell:ams,VersionCell:lms,IdCell:Zhs,DateCell:Vhs,LinkCell:Khs,LabelCell:Yhs});function cms({datasetId:e,itemId:t,onVersionSelect:n,onCompareVersionsClick:r,activeVersion:s}){const{data:a,isLoading:i}=PAe(e,t),[l,c]=g.useState(!1),[u,d]=g.useState(new Set),f=b=>{n?.(b)},p=b=>s==null?b.isLatest:b.datasetVersion===s,h=b=>{d(x=>{const S=new Set(x);if(S.has(b))S.delete(b);else if(S.size>=2){const[k]=Array.from(S);return new Set([k,b])}else S.add(b);return S})},m=()=>{c(!1),d(new Set)},v=()=>{c(!0)},y=()=>{u.size===2&&r?.([...u])};return o.jsxs(ta,{className:"min-w-56",children:[l?o.jsx(ta.Toolbar,{className:"grid w-full justify-stretch gap-3",children:o.jsxs(hs,{children:[o.jsx(oe,{onClick:m,children:"Cancel"}),o.jsx(oe,{variant:"primary",disabled:u.size!==2,onClick:y,tooltip:u.size!==2?"Check 2 versions to compare":void 0,className:"grow",children:"Compare"})]})}):o.jsx(o.Fragment,{children:(a||[]).length>1&&o.jsx(ta.Toolbar,{children:o.jsxs(oe,{onClick:v,className:"w-full",children:[o.jsx(Oj,{})," Compare Ver."]})})}),i?o.jsx(ums,{}):o.jsxs(li,{children:[o.jsx(li.Header,{children:o.jsx(li.HeaderCol,{children:"Item Version History"})}),o.jsx(li.Scroller,{children:o.jsx(li.Items,{children:a?.map(b=>{const x=String(b.datasetVersion),S=typeof b.updatedAt=="string"?new Date(b.updatedAt):b.updatedAt;return o.jsxs(li.Row,{isSelected:l&&u.has(x),children:[l&&o.jsx(li.LabelCell,{children:o.jsx(So,{checked:u.has(x),disabled:b.isDeleted,onCheckedChange:()=>{},onClick:k=>{k.stopPropagation(),b.isDeleted||h(x)},"aria-label":`Select version ${b.datasetVersion}`})}),o.jsx(li.RowButton,{item:b,columns:[{name:"version",label:"Item Version History",size:"1fr"}],isFeatured:p(b),onClick:()=>f(b),className:"py-2",tooltip:oms({isLatest:b.isLatest,isDeleted:b.isDeleted}),children:o.jsx(li.VersionCell,{version:b.datasetVersion,date:S,isLatest:b.isLatest,isDeleted:b.isDeleted})})]},String(b.datasetVersion))})})})]})]})}function ums(){return o.jsxs(li,{children:[o.jsx(li.Header,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(li.HeaderCol,{children:"Item Version History"})}),o.jsx(li.Items,{children:Array.from({length:3}).map((e,t)=>o.jsx(li.Row,{children:o.jsx(li.RowButton,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(li.TextCell,{isLoading:!0,children:"Loading..."})})},t))})]})}function dms(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${hr(n,"MMM dd 'at' H:mm:ss a")}`}return`v${e}`}function fms({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=JIe(e),a=(s??[]).map(i=>({value:String(i.version),label:`${dms(i.version,i.createdAt)}${i.isCurrent?" (current)":""}`}));return o.jsxs(ta.Toolbar,{className:"grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4",children:[o.jsx("div",{}),o.jsx(Pc,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:a,value:t??"",onValueChange:i=>r?.(i,n??"")}),o.jsx(Pc,{label:"Version B",labelIsHidden:!0,name:"version-b",options:a,value:n??"",onValueChange:i=>r?.(t??"",i)}),o.jsx("div",{})]})}const pms=[{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"}],C9={added:{badgeVariant:"blue",borderColor:"border-blue-900",icon:o.jsx(Or,{}),tooltip:"Added in this version"},changed:{badgeVariant:"yellow",borderColor:"border-yellow-900",icon:o.jsx(DXt,{}),tooltip:"Changed in this version"},same:{badgeVariant:"green",borderColor:"border-green-900",icon:o.jsx(Llt,{}),tooltip:"Same in both versions"}};function Cie({red:e=!1,tooltip:t}){return o.jsxs(yn,{children:[o.jsx(gn,{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(t0e,{className:K("text-neutral3/40 w-5 h-5 ",{"text-red-900":e})})}),o.jsx(vn,{children:t})]})}function Eie({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}=C9[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(St,{variant:n,size:"xs",icon:r})})]})}function hms(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function Uet({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return"added";if(t==="changed"&&n)return"changed"}function mms({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:a}){const{Link:i}=cn(),l=t>n;return o.jsx(li,{children:o.jsx(li.Scroller,{children:o.jsx(li.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=a.get(c),f=hms(u,d),p=Uet({otherVersionExists:d!==void 0,status:f,isNewer:l}),h=Uet({otherVersionExists:u!==void 0,status:f,isNewer:!l});return o.jsxs(li.Row,{columns:pms,children:[o.jsx(li.IdCell,{id:c,isShortened:!1}),f!=="same"?o.jsxs(o.Fragment,{children:[u?.datasetVersion?o.jsx(li.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:p?C9[p].tooltip:void 0,children:o.jsx(Eie,{variant:p,version:u.datasetVersion})}):o.jsx(li.Cell,{className:"flex items-center justify-center",children:o.jsx(Cie,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?o.jsx(li.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:h?C9[h].tooltip:void 0,children:o.jsx(Eie,{variant:h,version:d.datasetVersion})}):o.jsx(li.Cell,{className:"flex items-center justify-center",children:o.jsx(Cie,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):o.jsx(li.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",tooltip:C9.same.tooltip,children:o.jsx(Eie,{variant:"same",version:d?.datasetVersion})}),f==="changed"?o.jsx(li.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}/versions?ids=${u?.datasetVersion},${d?.datasetVersion}`,children:"Compare"}):o.jsx(li.Cell,{children:o.jsx(Cie,{tooltip:"Comparing is available only for changed items"})})]},c)})})})})}const qet={needsReview:"#facc15",complete:"#22c55e"},gms=[{label:"Needs Review",color:qet.needsReview},{label:"Reviewed",color:qet.complete}];function vms({reviewSummary:e,experiments:t,datasets:n,isLoading:r,isError:s}){const{data:a,maxVal:i,totalInPipeline:l}=g.useMemo(()=>{if(!e?.counts||!t)return{data:[],maxVal:0,totalInPipeline:0};const u=new Map;for(const m of t)u.set(m.id,m);const d=new Map;if(n)for(const m of n)d.set(m.id,m.name);let f=0,p=0;const h=[];for(const m of e.counts){const v=m.needsReview+m.complete;if(v===0)continue;p+=v,v>f&&(f=v);const y=u.get(m.experimentId),b=y?.datasetId?d.get(y.datasetId):void 0,x=b?`${b} · ${m.experimentId.slice(0,8)}`:m.experimentId.slice(0,8);h.push({name:x,values:[m.needsReview,m.complete]})}return{data:h,maxVal:f,totalInPipeline:p}},[e,t,n]),c=a.length>0;return o.jsxs(Bt,{children:[o.jsxs(Bt.TopBar,{children:[o.jsx(Bt.TitleAndDescription,{title:"Review Pipeline",description:"Items in review across experiments."}),c&&o.jsx(Bt.Summary,{value:String(l),label:"Items in pipeline"})]}),r?o.jsx(Bt.Loading,{}):s?o.jsx(Bt.Error,{message:"Failed to load review data"}):o.jsx(Bt.Content,{children:c?o.jsx(VN,{data:a,segments:gms,maxVal:i,fmt:u=>String(u)}):o.jsx(Bt.NoData,{message:"No items have been sent to review yet"})})]})}function BAe(){const e=Qe();return yt({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function NVt(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 yms(e,t){const n=new Map,r=NVt(e);if(!r.size||!t)return n;for(const s of t){const a=r.get(s.id);if(!a||!s.datasetId||a.needsReview+a.complete===0)continue;const l=n.get(s.datasetId)??{needsReview:0,complete:0};l.needsReview+=a.needsReview,l.complete+=a.complete,n.set(s.datasetId,l)}return n}function bms(e){return e?.counts?e.counts.reduce((t,n)=>({needsReview:t.needsReview+n.needsReview,complete:t.complete+n.complete,inPipeline:t.inPipeline+n.needsReview+n.complete}),{needsReview:0,complete:0,inPipeline:0}):{needsReview:0,complete:0,inPipeline:0}}const xms=10;function wms(){const e=es(),[t,n]=g.useState(""),[r,s]=g.useState("all"),[a,i]=g.useState("all"),[l,c]=g.useState("all"),[u,d]=g.useState(0),{data:f,isLoading:p,error:h}=Im({page:u,perPage:xms}),{data:m,isLoading:v,error:y}=UQ(),{data:b}=BAe(),x=g.useMemo(()=>f?.datasets??[],[f?.datasets]),S=f?.pagination?.hasMore??!1,k=g.useMemo(()=>m?.experiments??[],[m?.experiments]),_=g.useMemo(()=>ops(x),[x]),C=g.useMemo(()=>yms(b,k),[b,k]),T=p||v,E=h||y,N=()=>{e("/datasets/new")},I=g.useCallback(()=>d(z=>z+1),[]),A=g.useCallback(()=>d(z=>Math.max(0,z-1)),[]),R=g.useCallback(z=>{n(z),d(0)},[]),L=g.useCallback(z=>{s(z),d(0)},[]),D=g.useCallback(z=>{i(z),d(0)},[]),F=g.useCallback(z=>{c(z),d(0)},[]);if(E&&Ss(E))return o.jsx(ir,{children:o.jsx(Gs,{})});if(E&&ks(E))return o.jsx(ir,{children:o.jsx(Fs,{resource:"datasets"})});if(E)return o.jsx(ir,{children:o.jsx(Ui,{title:"Failed to load datasets",message:E.message})});if(x.length===0&&!T&&u===0)return o.jsx(ir,{children:o.jsx(pps,{onCreateClick:N})});const H=r!=="all"||a!=="all"||l!=="all"||t!=="",B=()=>{n(""),s("all"),i("all"),c("all"),d(0)};return o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx(gps,{search:t,onSearchChange:R,targetFilter:r,onTargetFilterChange:L,experimentFilter:a,onExperimentFilterChange:D,tagFilter:l,onTagFilterChange:F,tagOptions:_,onReset:B,hasActiveFilters:H,onCreateClick:N})}),o.jsx(fps,{datasets:x,experiments:k,reviewByDataset:C,isLoading:T,search:t,targetFilter:r,experimentFilter:a,tagFilter:l,currentPage:u,hasMore:S,onNextPage:I,onPrevPage:A})]})}function Wz({children:e}){return o.jsxs(Vt,{height:"full",children:[o.jsx("div",{}),o.jsx(Vt.MainArea,{isCentered:!0,children:e})]})}function Sms(){const{datasetId:e}=mr(),t=es(),[n,r]=hi(),{activeVersion:s,handleVersionChange:a}=$Ae(n,r),[i,l]=g.useState(!1),[c,u]=g.useState(!1),[d,f]=g.useState(!1),[p,h]=g.useState(!1),{data:m,error:v,isLoading:y}=Yg(e),{data:b=[],isLoading:x}=Zx(e,void 0,s),S=!x&&b.length===0;if(y)return null;if(v&&Ss(v))return o.jsx(Wz,{children:o.jsx(Gs,{})});if(v&&ks(v))return o.jsx(Wz,{children:o.jsx(Fs,{resource:"datasets"})});if(v&&o2t(v)||!y&&!v&&!m)return o.jsx(Wz,{children:o.jsx(Er,{iconSlot:o.jsx(cm,{}),titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:o.jsxs(oe,{as:wi,to:"/datasets",children:[o.jsx(gl,{}),"Back to Datasets"]})})});if(v)return o.jsx(Wz,{children:o.jsx(Ui,{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(vhs,{datasetId:e,items:b,isLoadingItems:x,children:[o.jsxs("div",{className:"relative h-full overflow-hidden",children:[o.jsx(Vt,{height:"full",className:"grid-rows-[1fr] p-0",children:o.jsx(Vt.MainArea,{children:o.jsx(xhs,{datasetId:e,onAddItemClick:()=>u(!0),rightSlot:o.jsxs(hs,{children:[o.jsx("span",{className:"text-ui-sm text-neutral3 mr-3 whitespace-nowrap",children:m?.createdAt?`Created ${hr(new Date(m.createdAt),"MMM d")}`:""}),o.jsx(gVt,{datasetId:e,value:s,onValueChange:a,currentVersion:m?.version,className:"w-36"}),S?o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:o.jsx("span",{className:"cursor-not-allowed",children:o.jsx("div",{className:"pointer-events-none opacity-50",inert:!0,"aria-disabled":"true",children:o.jsxs(oe,{variant:"primary",children:[o.jsx(Dc,{}),"Run Experiment"]})})})}),o.jsx(vn,{children:"Add items to the dataset before running an experiment"})]}):o.jsxs(oe,{variant:"primary",onClick:()=>l(!0),children:[o.jsx(Dc,{}),"Run Experiment"]}),o.jsxs(rt,{children:[o.jsx(rt.Trigger,{asChild:!0,children:o.jsx(oe,{size:"lg","aria-label":"Dataset actions menu",children:o.jsx(JN,{})})}),o.jsxs(rt.Content,{align:"end",className:"w-48",children:[o.jsxs(rt.Item,{onSelect:()=>{t(`/datasets/${e}/edit`)},children:[o.jsx(um,{})," Edit Dataset"]}),o.jsxs(rt.Item,{onSelect:()=>h(!0),children:[o.jsx(zd,{})," Duplicate Dataset"]}),o.jsxs(rt.Item,{onSelect:()=>f(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(Ml,{})," Delete Dataset"]})]})]})]})})})}),o.jsx(Fg,{})]}),o.jsx(FAe,{initialDatasetId:e,initialDatasetVersion:s??void 0,open:i,onOpenChange:l,onSuccess:k},`${e}:${s??"latest"}`),o.jsx(Shs,{datasetId:e,open:c,onOpenChange:u}),m&&o.jsx(Ips,{open:p,onOpenChange:h,sourceDatasetId:m.id,sourceDatasetName:m.name,sourceDatasetDescription:m.description,sourceDatasetTargetType:m.targetType}),m&&o.jsx($ps,{open:d,onOpenChange:f,datasetId:m.id,datasetName:m.name,onSuccess:_})]})}function Tie({children:e}){return o.jsxs(Vt,{height:"full",children:[o.jsx("div",{}),o.jsx(Vt.MainArea,{isCentered:!0,children:e})]})}function kms(){const{datasetId:e}=mr(),t=es(),{data:n,error:r,isLoading:s}=Yg(e),a=()=>{t(`/datasets/${e}`)};return s?null:r&&Ss(r)?o.jsx(Tie,{children:o.jsx(Gs,{})}):r&&ks(r)?o.jsx(Tie,{children:o.jsx(Fs,{resource:"datasets"})}):r||!n?o.jsx(Tie,{children:o.jsx(Ui,{title:"Failed to load dataset",message:r instanceof Error?r.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Vt,{height:"full",children:[o.jsx("div",{}),o.jsx(Vt.MainArea,{isCentered:!0,children:o.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-6 py-8",children:[o.jsx(Ia,{className:"mb-6 p-0",children:o.jsxs(Ia.Column,{children:[o.jsxs(Ia.Title,{children:[o.jsx(cm,{})," Edit dataset"]}),o.jsx(Ia.Description,{children:n.name})]})}),o.jsx(Yu,{className:"p-6",children:o.jsx(Pps,{dataset:{id:n.id,name:n.name,description:n.description||"",targetType:n.targetType,inputSchema:n.inputSchema,groundTruthSchema:n.groundTruthSchema,requestContextSchema:n.requestContextSchema},onSuccess:a,onCancel:a})})]})})]})}function Vet({experimentId:e}){return o.jsxs(oe,{as:wi,to:`/experiments/${e}`,target:"_blank",rel:"noopener noreferrer",size:"sm","aria-label":`Open experiment ${e}`,children:[e.slice(0,8),o.jsx(Yr,{})]})}function Oms(){const{datasetId:e}=mr(),[t,n]=hi(),{error:r}=Yg(e??""),s=t.get("baseline")??"",a=t.get("contender")??"";return r&&Ss(r)?o.jsx(_s,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Gs,{})})}):r&&ks(r)?o.jsx(_s,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{resource:"datasets"})})}):!e||!s||!a?o.jsx(_s,{children:o.jsx(Hx,{children:o.jsxs("div",{className:"text-neutral4 py-8 text-center",children:[o.jsx("p",{children:"Select two experiments to compare."}),o.jsxs("p",{className:"mt-2 text-sm",children:["Use the URL format: /datasets/","{datasetId}","/experiments?baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})}):o.jsx(_s,{children:o.jsx(Hx,{children:o.jsxs("div",{className:"grid w-full content-start",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4 px-6 py-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[o.jsx(me,{as:"h1",variant:"ui-lg",className:"text-neutral6 font-medium",children:"Experiments comparison"}),o.jsxs("p",{className:"text-ui-sm text-neutral4 flex items-center gap-2",children:[o.jsx(Vet,{experimentId:s}),"and",o.jsx(Vet,{experimentId:a})]})]}),o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:o.jsxs(oe,{onClick:()=>n({baseline:a,contender:s}),children:[o.jsx(Elt,{}),"Swap sides"]})}),o.jsx(vn,{children:"Switch baseline and contender"})]})]}),o.jsx(qhs,{datasetId:e,experimentIdA:s,experimentIdB:a})]})})})}const Zz=()=>{},_ms=new Set,Cms=[{name:"id",label:"ID",size:"7rem"},{name:"input",label:"Input",size:"minmax(10rem,1fr)"},{name:"groundTruth",label:"Ground Truth",size:"minmax(10rem,1fr)"},{name:"trajectory",label:"Trajectory",size:"8rem"},{name:"createdAt",label:"Created",size:"10rem"}];function Ems({datasetId:e,currentItemId:t,open:n,onOpenChange:r}){const{navigate:s,paths:a}=cn(),[i,l]=g.useState(""),[c]=MH(i,300),{data:u,isLoading:d,setEndOfListElement:f,isFetchingNextPage:p,hasNextPage:h}=Zx(e,c||void 0),m=u.filter(y=>y.id!==t),v=y=>{r(!1),s(a.datasetItemCompareLink(e,t,y))};return o.jsx(vr,{open:n,onOpenChange:r,children:o.jsxs(yr,{className:"sm:max-w-[min(72rem,calc(100%-4rem))]",children:[o.jsxs(br,{children:[o.jsx(pr,{children:"Compare with…"}),o.jsx(Ps,{children:"Pick an item to compare with the current one."})]}),o.jsxs(Mr,{className:"grid max-h-[70vh] min-h-[24rem] grid-rows-[auto_1fr] gap-3",children:[o.jsx(m_,{name:"compare-with-dialog-search",label:"Search items to compare",labelIsHidden:!0,value:i,onChange:y=>l(y.target.value),placeholder:"Search items..."}),o.jsx("div",{className:"min-h-0 overflow-y-auto",children:o.jsx(yVt,{items:m,isLoading:d,onItemClick:v,selectOnNavigate:!1,columns:Cms,searchQuery:c||" ",setEndOfListElement:f,isFetchingNextPage:p,hasNextPage:h,isSelectionActive:!1,selectedIds:_ms,onToggleSelection:Zz,onSelectAll:Zz,onClearSelection:Zz,onAddClick:Zz})})]})]})})}function Tms(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 jms({datasetId:e,item:t,items:n,onItemChange:r,onClose:s}){const{Link:a}=cn(),{updateItem:i,deleteItem:l}=qi(),[c,u]=g.useState(!1),[d,f]=g.useState(""),[p,h]=g.useState(""),[m,v]=g.useState(""),[y,b]=g.useState(""),[x,S]=g.useState(""),[k,_]=g.useState(t.scorerIds!==void 0),[C,T]=g.useState(t.scorerIds??[]),[E,N]=g.useState(""),[I,A]=g.useState(null),[R,L]=g.useState(!1),[D,F]=g.useState(!1);g.useEffect(()=>{t&&(f(JSON.stringify(t.input,null,2)),h(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),v(t.metadata?JSON.stringify(t.metadata,null,2):""),b(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),S(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),_(t.scorerIds!==void 0),T(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),L(!1),A(null))},[t?.id]);const H=n.findIndex(q=>q.id===t.id),B=H>0?()=>r(n[H-1].id):void 0,z=H>=0&&H<n.length-1?()=>r(n[H+1].id):void 0,V=async()=>{let q;try{q=JSON.parse(d)}catch{Be.error("Input must be valid JSON");return}let Z;if(p.trim())try{Z=JSON.parse(p)}catch{Be.error("Ground Truth must be valid JSON");return}let Y;if(m.trim())try{Y=JSON.parse(m)}catch{Be.error("Metadata must be valid JSON");return}let ne=null;if(y.trim())try{ne=JSON.parse(y)}catch{Be.error("Expected Trajectory must be valid JSON");return}let J;if(x.trim())try{const le=JSON.parse(x);if(!Array.isArray(le)){Be.error("Tool Mocks must be a JSON array");return}J=le}catch{Be.error("Tool Mocks must be valid JSON");return}else J=[];let ee;if(E.trim())try{ee=JSON.parse(E)}catch{Be.error("Request Context must be valid JSON");return}let re;k?re=C:t.scorerIds!==void 0&&(re=null);try{const le=await i.mutateAsync({datasetId:e,itemId:t.id,input:q,groundTruth:Z,metadata:Y,expectedTrajectory:ne,toolMocks:J,scorerIds:re,requestContext:ee});Be.success("Item updated successfully"),_(le.scorerIds!==void 0),T(le.scorerIds??[]),u(!1),A(null)}catch(le){const X=Tms(le);X?A(X):Be.error(`Failed to update item: ${le instanceof Error?le.message:"Unknown error"}`)}},M=()=>{f(JSON.stringify(t.input,null,2)),h(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),v(t.metadata?JSON.stringify(t.metadata,null,2):""),b(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),S(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),_(t.scorerIds!==void 0),T(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),A(null)},G=q=>{f(q),I?.field==="input"&&A(null)},U=q=>{h(q),I?.field==="groundTruth"&&A(null)},$=async()=>{try{await l.mutateAsync({datasetId:e,itemId:t.id}),Be.success("Item deleted successfully"),L(!1),s()}catch(q){Be.error(`Failed to delete item: ${q instanceof Error?q.message:"Unknown error"}`)}};return o.jsxs(o.Fragment,{children:[o.jsxs(fn,{children:[o.jsxs(fn.Header,{children:[o.jsxs(fn.Heading,{children:["Item ",o.jsxs("b",{children:["# ",t.id.length>12?`${t.id.slice(0,12)}…`:t.id]})]}),o.jsxs(hs,{className:"ml-auto shrink-0",children:[o.jsx(fn.NextPrevNav,{onPrevious:B,onNext:z,previousLabel:"Previous item",nextLabel:"Next item"}),!c&&o.jsxs(o.Fragment,{children:[o.jsx(oe,{as:a,href:`/datasets/${e}/items/${t.id}/versions`,size:"md",tooltip:"Go to item versions history","aria-label":"Go to item versions history",children:o.jsx(rI,{})}),o.jsxs(rt,{children:[o.jsx(rt.Trigger,{asChild:!0,children:o.jsx(oe,{size:"md","aria-label":"Actions menu",children:o.jsx(JN,{})})}),o.jsxs(rt.Content,{align:"end",className:"w-48",children:[o.jsxs(rt.Item,{onSelect:()=>u(!0),children:[o.jsx(um,{}),"Edit"]}),o.jsxs(rt.Item,{onSelect:()=>F(!0),children:[o.jsx(Oj,{}),"Compare with…"]}),o.jsxs(rt.Item,{onSelect:()=>L(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(Ml,{}),"Delete Item"]})]})]})]}),o.jsx(fn.CloseButton,{onClick:s,tooltip:"Close detail panel"})]})]}),o.jsx(fn.Content,{children:c?o.jsx(Ohs,{inputValue:d,setInputValue:G,groundTruthValue:p,setGroundTruthValue:U,metadataValue:m,setMetadataValue:v,trajectoryValue:y,setTrajectoryValue:b,toolMocksValue:x,setToolMocksValue:S,scorerOverrideEnabled:k,setScorerOverrideEnabled:_,selectedScorerIds:C,setSelectedScorerIds:T,requestContextValue:E,setRequestContextValue:N,validationErrors:I,onSave:V,onCancel:M,isSaving:i.isPending}):o.jsxs(o.Fragment,{children:[o.jsxs(_n,{children:[o.jsx(_n.Key,{children:"Dataset Id"}),o.jsx(_n.ValueWithCopyBtn,{copyTooltip:"Copy Dataset Id to clipboard",copyValue:t.datasetId,children:t.datasetId}),o.jsx(_n.Key,{children:"Version"}),o.jsxs(_n.Value,{children:["v",t.datasetVersion]}),o.jsx(_n.Key,{children:"Created"}),o.jsx(_n.Value,{children:hr(new Date(t.createdAt),"MMM d, yyyy h:mm aaa")}),t.updatedAt&&new Date(t.updatedAt).getTime()!==new Date(t.createdAt).getTime()&&o.jsxs(o.Fragment,{children:[o.jsx(_n.Key,{children:"Updated"}),o.jsx(_n.Value,{children:hr(new Date(t.updatedAt),"MMM d, yyyy h:mm aaa")})]})]}),o.jsxs("div",{className:"mt-3 grid gap-3",children:[o.jsx(fn.CodeSection,{title:"Input",icon:o.jsx(xx,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(fn.CodeSection,{title:"Ground Truth",icon:o.jsx(em,{}),codeStr:JSON.stringify(t.groundTruth??null,null,2)}),t.expectedTrajectory!=null&&o.jsx(fn.CodeSection,{title:"Expected Trajectory",icon:o.jsx(p0e,{}),codeStr:JSON.stringify(t.expectedTrajectory,null,2)}),o.jsx(fn.CodeSection,{title:"Tool Mocks",icon:o.jsx(Ud,{}),codeStr:JSON.stringify(t.toolMocks??[],null,2)}),o.jsx(fn.CodeSection,{title:"Scorers",icon:o.jsx(wV,{}),codeStr:t.scorerIds===void 0?"Inherited from dataset":JSON.stringify(t.scorerIds,null,2)}),t.requestContext!=null&&o.jsx(fn.CodeSection,{title:"Request Context",icon:o.jsx(Jl,{}),codeStr:JSON.stringify(t.requestContext,null,2)}),o.jsx(fn.CodeSection,{title:"Metadata",icon:o.jsx(sI,{}),codeStr:JSON.stringify(t.metadata??null,null,2)})]})]})})]}),o.jsx(Ems,{datasetId:e,currentItemId:t.id,open:D,onOpenChange:F}),o.jsx(Pt,{open:R,onOpenChange:L,children:o.jsxs(Pt.Content,{children:[o.jsxs(Pt.Header,{children:[o.jsx(Pt.Title,{children:"Delete Item"}),o.jsx(Pt.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),o.jsxs(Pt.Footer,{children:[o.jsx(Pt.Cancel,{children:"Cancel"}),o.jsx(Pt.Action,{onClick:$,children:l.isPending?"Deleting...":"Yes, Delete"})]})]})})]})}function Nms(){const{itemId:e}=mr(),{datasetId:t,items:n,isLoadingItems:r,openItem:s,close:a}=wVt(),i=g.useMemo(()=>n.find(d=>d.id===e)??null,[n,e]),{data:l,isLoading:c}=FD(i?"":t,!i&&e?e:""),u=i??l??null;return e?o.jsx(DAe,{label:`Dataset item ${e}`,children:u?o.jsx("div",{className:"[&>section]:bg-surface3 flex min-h-full flex-col p-3 [&>section]:min-h-0 [&>section]:flex-1 [&>section]:rounded-lg [&>section]:shadow-lg",children:o.jsx(jms,{datasetId:t,item:u,items:n,onItemChange:s,onClose:a})}):r||c?o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(Ut,{})})}):o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(Er,{iconSlot:o.jsx(cm,{}),titleSlot:"Item not found",descriptionSlot:`No loaded item "${e}".`,actionSlot:o.jsx(oe,{onClick:a,children:"Close"})})})})}):null}function Het(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,metadata:e.metadata??null},null,2)}function Ims(){const{datasetId:e,itemId:t,secondItemId:n}=mr(),r=es(),s=[t,n].filter(h=>!!h),{data:a,error:i}=Yg(e??""),{Link:l,paths:c}=cn(),[u,d]=g.useState(!1),{data:f}=FD(e??"",s[0]??""),{data:p}=FD(e??"",s[1]??"");return i&&Ss(i)?o.jsx(_s,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Gs,{})})}):i&&ks(i)?o.jsx(_s,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{resource:"datasets"})})}):!e||s.length<2?o.jsx(_s,{children:o.jsx(Hx,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Select at least two items to compare."})})})}):o.jsxs(_s,{children:[o.jsx($y,{owner:"dataset-items-compare",children:o.jsxs(oe,{as:wi,to:`/datasets/${e}`,variant:"outline",children:[o.jsx(gl,{}),"Back to Dataset"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:K("grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",{"grid-rows-[auto_auto_1fr]":u}),children:[o.jsxs(Ia,{children:[o.jsxs(Ia.Column,{children:[o.jsxs(Ia.Title,{children:[o.jsx(Oj,{}),"Compare Dataset Items"]}),o.jsx(Ia.Description,{children:o.jsxs(Nl,{children:["Comparing ",s.length," items of"," ",o.jsx(wi,{to:`/datasets/${e}`,className:"text-info1 hover:underline",children:a?.name||e?.slice(0,8)})]})})]}),o.jsx(Ia.Column,{children:o.jsx(hs,{children:o.jsx(oe,{variant:"primary",onClick:()=>d(h=>!h),children:u?o.jsxs(o.Fragment,{children:[o.jsx(s0e,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(cYt,{})," Diff View"]})})})})]}),o.jsx(vx,{className:"grid-cols-[1fr_3vw_1fr]",children:s.map((h,m)=>o.jsxs(g.Fragment,{children:[o.jsx(Ams,{datasetId:e,itemId:h,Link:l,idx:m,itemIds:s,showContent:!u,onItemChange:v=>{const y=[...s];y[m]=v,r(c.datasetItemCompareLink(e,y[0],y[1]))}}),m==0&&o.jsx("div",{className:K("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},h))}),u&&f&&p&&o.jsx(cAe,{codeA:Het(f),codeB:Het(p)})]})})]})}function Ams({datasetId:e,itemId:t,Link:n,idx:r,itemIds:s,onItemChange:a,showContent:i=!0}){const{data:l,isLoading:c}=FD(e,t),{data:u}=Zx(e),d=new Set(s.filter((p,h)=>h!==r)),f=(u??[]).map(p=>({value:p.id,label:p.id,disabled:d.has(p.id)}));return o.jsxs(ta,{children:[o.jsxs(ta.Toolbar,{className:"flex gap-4",children:[o.jsxs(ha,{name:`compare-item-${r}`,value:t,onValueChange:a,children:[o.jsx(ga,{"aria-label":"Item",children:o.jsx(ma,{placeholder:"Select item"})}),o.jsx(va,{children:f.map(p=>o.jsx(Nr,{value:p.value,disabled:p.disabled,children:p.label},p.value))})]}),o.jsxs(oe,{as:n,to:`/datasets/${e}/items/${t}`,children:[o.jsx(rI,{}),"Versions"]})]}),i&&o.jsx(ta.Content,{children:c?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):l?o.jsxs(o.Fragment,{children:[o.jsx(khs,{item:l}),o.jsx(LAe,{item:l,Link:n})]}):o.jsxs("div",{className:"text-neutral4 text-sm",children:["Item ",t.slice(0,8)," not found"]})})]})}function Wet(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,scorerIds:e.scorerIds??null,metadata:e.metadata??null},null,2)}function Rms(){const{datasetId:e,itemId:t}=mr(),[n,r]=hi(),[s,a]=g.useState(!1),i=n.get("ids")?.split(",").map(Number).filter(h=>!isNaN(h)&&h>0)??[],{data:l,error:c}=Yg(e??""),{Link:u}=cn(),{data:d}=PAe(e??"",t??""),{data:f}=Mxe(e??"",t??"",i[0]??0,l?.version),{data:p}=Mxe(e??"",t??"",i[1]??0,l?.version);return c&&Ss(c)?o.jsx(_s,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Gs,{})})}):c&&ks(c)?o.jsx(_s,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{resource:"datasets"})})}):!e||!t?o.jsx(_s,{children:o.jsx(Hx,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Item not found."})})})}):i.length<2?o.jsx(Pms,{datasetId:e,itemId:t,Link:u,onCompare:h=>r({ids:h.join(",")})}):o.jsxs(_s,{children:[o.jsx($y,{owner:"dataset-item-versions-compare",children:o.jsxs(oe,{as:wi,to:`/datasets/${e}/items/${t}`,variant:"outline",children:[o.jsx(gl,{}),"Back to Item"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:K("grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",{"grid-rows-[auto_auto_1fr]":s}),children:[o.jsxs(Ia,{children:[o.jsxs(Ia.Column,{children:[o.jsxs(Ia.Title,{children:[o.jsx(Oj,{}),"Compare Dataset Item Versions"]}),o.jsx(Ia.Description,{children:o.jsxs(Nl,{children:["Comparing ",i.length," versions of"," ",o.jsx(wi,{to:`/datasets/${e}/items/${t}`,className:"text-info1 hover:underline",children:t})]})})]}),o.jsx(Ia.Column,{children:o.jsx(hs,{children:o.jsx(oe,{variant:"primary",onClick:()=>a(h=>!h),children:s?o.jsxs(o.Fragment,{children:[o.jsx(s0e,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(sKt,{})," Diff View"]})})})})]}),o.jsx(vx,{className:"grid-cols-[1fr_3vw_1fr]",children:i.map((h,m)=>o.jsxs(g.Fragment,{children:[o.jsx($ms,{datasetId:e,itemId:t,datasetVersion:h,latestVersion:l?.version,allVersions:d??[],versionNumbers:i,Link:u,idx:m,showContent:!s,onVersionChange:v=>{const y=[...i];y[m]=v,r({ids:y.join(",")})}}),m===0&&o.jsx("div",{className:K("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},h))}),s&&f&&p&&o.jsx(cAe,{codeA:Wet(f),codeB:Wet(p)})]})})]})}function Pms({datasetId:e,itemId:t,Link:n,onCompare:r}){const[s,a]=g.useState(null),{data:i,isLoading:l}=PAe(e,t),c=(s!=null?i?.find(d=>d.datasetVersion===s):void 0)??i?.[0],u=c?{id:c.id,datasetId:e,datasetVersion:c.datasetVersion,input:c.input,groundTruth:c.groundTruth,scorerIds:c.scorerIds,metadata:c.metadata,createdAt:c.createdAt,updatedAt:c.updatedAt}:null;return o.jsxs(_s,{children:[o.jsx($y,{owner:"dataset-item-versions-history",children:o.jsxs(oe,{as:wi,to:`/datasets/${e}/items/${t}`,variant:"outline",children:[o.jsx(gl,{}),"Back to Item"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:"mx-auto grid h-full max-w-[140rem] grid-rows-[auto_1fr] gap-6",children:[o.jsx(Ia,{children:o.jsxs(Ia.Column,{children:[o.jsxs(Ia.Title,{children:[o.jsx(rI,{}),"Item Version History"]}),o.jsx(Ia.Description,{children:o.jsxs(Nl,{children:["Versions of ",t]})})]})}),o.jsxs(vx,{className:"grid-cols-[1fr_auto]",children:[o.jsx(ta,{children:o.jsx(ta.Content,{children:l?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):u?o.jsx(LAe,{item:u,Link:n}):o.jsx("div",{className:"text-neutral4 text-sm",children:"Item data not available"})})}),o.jsx(cms,{datasetId:e,itemId:t,onClose:()=>{},onVersionSelect:d=>a(d.datasetVersion),onCompareVersionsClick:r,activeVersion:s})]})]})})]})}function $ms({datasetId:e,itemId:t,datasetVersion:n,latestVersion:r,allVersions:s,versionNumbers:a,Link:i,idx:l,showContent:c=!0,onVersionChange:u}){const{data:d,isLoading:f}=Mxe(e,t,n,r),p=new Set(a.filter((v,y)=>y!==l)),h=s.map(v=>{const y=typeof v.updatedAt=="string"?new Date(v.updatedAt):v.updatedAt;return{value:String(v.datasetVersion),label:o.jsxs(o.Fragment,{children:[o.jsxs("b",{children:["v. ",v.datasetVersion]})," - ",hr(y,"MMM d, yyyy h:mm a"),v.isLatest?o.jsx(St,{variant:"blue",size:"xs",children:"Latest"}):null]}),disabled:p.has(v.datasetVersion)}}),m=d?{id:d.id,datasetId:e,datasetVersion:d.datasetVersion,input:d.input,groundTruth:d.groundTruth,scorerIds:d.scorerIds,metadata:d.metadata,createdAt:d.createdAt,updatedAt:d.updatedAt}:null;return o.jsxs(ta,{children:[o.jsxs(ta.Toolbar,{className:"grid grid-cols-[auto_1fr] gap-4",children:[o.jsx(rI,{className:"h-6 w-6 opacity-50"}),o.jsxs(ha,{name:`compare-version-${l}`,value:String(n),onValueChange:v=>u(Number(v)),children:[o.jsx(ga,{"aria-label":"Version",className:"w-full",children:o.jsx(ma,{placeholder:"Select version"})}),o.jsx(va,{children:h.map(v=>o.jsx(Nr,{value:v.value,disabled:v.disabled,children:v.label},v.value))})]})]}),c&&o.jsx(ta.Content,{children:f?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):!d||!m?o.jsxs("div",{className:"text-neutral4 text-sm",children:["Version ",n," not found"]}):o.jsx(LAe,{item:m,Link:i})})]})}function Mms(){const{datasetId:e}=mr(),[t]=hi(),n=t.get("ids")?.split(",").map(Number).filter(v=>!isNaN(v)&&v>0)??[],r=es(),{data:s,error:a}=Yg(e??""),i=Zx(e??"",void 0,n[0]??null),l=Zx(e??"",void 0,n[1]??null),c=g.useMemo(()=>i.data??[],[i.data]),u=g.useMemo(()=>l.data??[],[l.data]),d=g.useMemo(()=>{const v=new Map;for(const y of[...c,...u])v.has(y.id)||v.set(y.id,{id:y.id,createdAt:new Date(y.createdAt)});return[...v.values()].sort((y,b)=>b.createdAt.getTime()-y.createdAt.getTime())},[c,u]),f=g.useMemo(()=>new Map(c.map(v=>[v.id,v])),[c]),p=g.useMemo(()=>new Map(u.map(v=>[v.id,v])),[u]);if(a&&Ss(a))return o.jsx(_s,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Gs,{})})});if(a&&ks(a))return o.jsx(_s,{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(_s,{children:o.jsx(Hx,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Select at least two versions to compare."})})})});const h=(v,y,b)=>{r(`/datasets/${e}/items/${v}/versions?ids=${y?.datasetVersion??""},${b?.datasetVersion??""}`)},m=(v,y)=>{r(`/datasets/${e}/versions?ids=${v},${y}`,{replace:!0})};return o.jsx(_s,{children:o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:"mx-auto grid h-full max-w-[140rem] grid-rows-[auto_1fr] gap-6",children:[o.jsxs(Ia,{children:[o.jsxs(Ia.Column,{children:[o.jsxs(Ia.Title,{children:[o.jsx(dJt,{})," Compare Dataset Versions"]}),o.jsx(Ia.Description,{children:o.jsxs(Nl,{children:[o.jsx(rI,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),o.jsx(Ia.Column,{children:o.jsxs(oe,{as:wi,to:`/datasets/${e}`,children:[o.jsx(gl,{}),"Back to Dataset"]})})]}),o.jsx(vx,{children:o.jsxs(ta,{children:[o.jsx(fms,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:m}),o.jsx(mms,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:p,onItemClick:h})]})})]})})})}function Dms(){const e=es(),[t]=hi(),n=t.get("targetType"),r=BD(n)?n:void 0,s=t.get("targetIds"),a=r&&s?s.split(",").map(i=>i.trim()).filter(Boolean):void 0;return o.jsxs(Vt,{height:"full",children:[o.jsx("div",{}),o.jsx(Vt.MainArea,{isCentered:!0,children:o.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-6 py-8",children:[o.jsx(Ia,{className:"mb-6 p-0",children:o.jsxs(Ia.Column,{children:[o.jsxs(Ia.Title,{children:[o.jsx(cm,{})," Create new dataset"]}),o.jsx(Ia.Description,{children:"Datasets group test cases used to evaluate your agents and workflows."})]})}),o.jsx(Yu,{className:"p-6",children:o.jsx(Tps,{targetType:r,targetIds:a,onSuccess:i=>{e(`/datasets/${i}`)},onCancel:()=>{e(-1)}})})]})})]})}function Fxe({children:e,className:t}){return o.jsx("div",{className:K("flex flex-wrap gap-8",t),children:e})}function Lms(e){if(!e||e.length<2)return null;const t=[...e].sort((i,l)=>new Date(i.createdAt).getTime()-new Date(l.createdAt).getTime()),n=Math.floor(t.length/2),r=n,s=t.length-n;if(r===0)return null;const a=(s-r)/r*100;return{changePct:Math.round(a*10)/10,prevValue:String(r)}}function Fms({scorers:e,datasets:t,experiments:n,avgScore:r,prevAvgScore:s,totalNeedsReview:a,isLoadingScorers:i,isLoadingDatasets:l,isLoadingExperiments:c,isLoadingScores:u,isLoadingReview:d}){const f=e?Object.keys(e).length:void 0,p=t?.length,h=n?.length,m=r!=null&&s!=null&&s!==0?{changePct:Math.round((r-s)/s*100*10)/10,prevValue:String(s)}:null,v=Lms(n);return o.jsxs(o.Fragment,{children:[o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Total Scorers"}),i?o.jsx(Xr.Loading,{}):f!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(f)}),o.jsx(Xr.NoChange,{message:"Static count"})]}):o.jsx(Xr.NoData,{})]}),o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Total Datasets"}),l?o.jsx(Xr.Loading,{}):p!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(p)}),o.jsx(Xr.NoChange,{message:"Static count"})]}):o.jsx(Xr.NoData,{})]}),o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Avg Score"}),u?o.jsx(Xr.Loading,{}):r!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(r)}),m?o.jsx(Xr.Change,{changePct:m.changePct,prevValue:m.prevValue}):o.jsx(Xr.NoChange,{})]}):o.jsx(Xr.NoData,{})]}),o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Total Experiments"}),c?o.jsx(Xr.Loading,{}):h!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(h)}),v?o.jsx(Xr.Change,{changePct:v.changePct,prevValue:v.prevValue}):o.jsx(Xr.NoChange,{})]}):o.jsx(Xr.NoData,{})]}),o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:"Needs Review"}),d?o.jsx(Xr.Loading,{}):a!=null?o.jsxs(o.Fragment,{children:[o.jsx(Xr.Value,{children:String(a)}),a>0?o.jsx(Xr.NoChange,{message:"items pending review"}):o.jsx(Xr.NoChange,{message:"All caught up"})]}):o.jsx(Xr.NoData,{})]})]})}const Zet=`${rUt} ${yis} ${sUt}`;function zms({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:a="all",datasetFilter:i="all"}){const{paths:l,Link:c}=cn(),u=g.useMemo(()=>{const m=new Map;return t?.forEach(v=>m.set(v.id,v.name)),m},[t]),d=g.useMemo(()=>[...e].sort((m,v)=>{const y=m.createdAt?new Date(m.createdAt).getTime():0;return(v.createdAt?new Date(v.createdAt).getTime():0)-y}),[e]),f=g.useMemo(()=>{const m=s.toLowerCase();return d.filter(v=>{const y=v.datasetId?u.get(v.datasetId)??"":"",b=!m||v.id.toLowerCase().includes(m)||(v.name??"").toLowerCase().includes(m)||y.toLowerCase().includes(m)||(v.targetId??"").toLowerCase().includes(m),x=a==="all"||v.status===a,S=i==="all"||v.datasetId===i;return b&&x&&S})},[d,s,u,a,i]),{containerRef:p,getRowProps:h}=wo({count:f.length});return r?o.jsx(Pl,{columns:Zet}):o.jsxs(be,{columns:Zet,variant:"striped",scrollRef:p,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:au.experiment}),o.jsx(be.TopCell,{children:au.dataset}),o.jsx(be.TopCell,{children:au.target}),o.jsx(be.TopCell,{children:au.status}),o.jsx(be.TopCell,{className:"text-center",children:au.items}),o.jsx(be.TopCell,{className:"text-center",children:au.succeeded}),o.jsx(be.TopCell,{className:"text-center",children:au.failed}),o.jsx(be.TopCell,{className:"text-center",children:au.review}),o.jsx(be.TopCell,{children:au.date})]}),f.map((m,v)=>{const y=m.datasetId?u.get(m.datasetId)??dS(m.datasetId)??m.datasetId:"—";return o.jsx(be.RowLink,{to:l.experimentLink(m.id),LinkComponent:c,...h(v),children:o.jsx(vVt,{experiment:m,datasetName:y,review:n?.get(m.id)})},m.id)})]})}const Bms=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function Ums(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const Gz={completed:j7.neutral3,running:"#facc15",pending:"#fb923c",failed:"#f87171"},qms=[{label:"Completed",color:Gz.completed},{label:"Running",color:Gz.running},{label:"Pending",color:Gz.pending},{label:"Failed",color:Gz.failed}];function Vms({experiments:e,datasets:t,isLoading:n,isError:r}){const{data:s,maxVal:a}=g.useMemo(()=>{if(!e||e.length===0)return{data:[],maxVal:0};const l=new Map;if(t)for(const f of t)l.set(f.id,f.name);const c=new Map;for(const f of e){const p=f.datasetId??"unknown";c.has(p)||c.set(p,{completed:0,running:0,pending:0,failed:0});const h=c.get(p),m=f.status;m in h&&h[m]++}let u=0;return{data:Array.from(c.entries()).map(([f,p])=>{const h=p.completed+p.running+p.pending+p.failed;return h>u&&(u=h),{name:l.get(f)??f.slice(0,12),values:[p.completed,p.running,p.pending,p.failed]}}),maxVal:u}},[e,t]),i=s.length>0;return o.jsxs(Bt,{children:[o.jsxs(Bt.TopBar,{children:[o.jsx(Bt.TitleAndDescription,{title:"Experiments by Dataset",description:"Experiment status breakdown per dataset."}),i&&o.jsx(Bt.Summary,{value:String(e?.length??0),label:"Total experiments"})]}),n?o.jsx(Bt.Loading,{}):r?o.jsx(Bt.Error,{message:"Failed to load experiments data"}):o.jsx(Bt.Content,{children:i?o.jsx(VN,{data:s,segments:qms,maxVal:a,fmt:l=>String(l)}):o.jsx(Bt.NoData,{message:"No experiments have been run yet"})})]})}const Hms=({onRunExperiment:e})=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Er,{iconSlot:o.jsx(Mc,{}),titleSlot:"No Experiments yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Run an experiment from a dataset to evaluate ",o.jsx("br",{}),"your agents and workflows."]}),actionSlot:o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e&&o.jsxs(oe,{variant:"primary",onClick:e,children:[o.jsx(Dc,{}),"Run Experiment"]}),o.jsxs(oe,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/datasets/running-experiments",target:"_blank",rel:"noopener noreferrer",children:["Experiments Documentation ",o.jsx(Yr,{})]})]})})});function Wms({search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:i,onReset:l,hasActiveFilters:c,onRunClick:u,runTooltip:d="Run an experiment"}){return o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx("div",{className:"max-w-120 min-w-64 flex-1",children:o.jsx(ah,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t})}),o.jsxs(hs,{children:[o.jsx(Pc,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...Bms],value:n,onValueChange:r,className:"whitespace-nowrap"}),o.jsx(Pc,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:i,value:s,onValueChange:a,className:"whitespace-nowrap"}),l&&c&&o.jsxs(oe,{onClick:l,size:"sm",variant:"default",children:[o.jsx(or,{className:"size-3"})," Reset"]})]}),u&&o.jsxs(oe,{onClick:u,tooltip:d,variant:"primary",className:"ml-auto shrink-0",children:[o.jsx(Dc,{}),"Run Experiment"]})]})}function Zms(){const[e,t]=g.useState("all"),[n,r]=g.useState({}),{data:s,isLoading:a,error:i}=oh(),{data:l,isLoading:c,error:u}=Im(),{data:d,isLoading:f,error:p}=UQ(),{data:h,isLoading:m,isError:v,error:y}=K7r(n),{data:b,isLoading:x,isError:S,error:k}=BAe(),_=l?.datasets,C=d?.experiments,T=g.useMemo(()=>bms(b),[b]),E=i||u||p||y||k;return E&&Ss(E)?o.jsx(ir,{children:o.jsx(Gs,{})}):E&&ks(E)?o.jsx(ir,{children:o.jsx(Fs,{resource:"evaluation"})}):E?o.jsx(ir,{children:o.jsx(Ui,{title:"Failed to load evaluation data",message:E.message})}):o.jsxs(Vt,{width:"wide",height:"full",children:[o.jsx(Vt.TopArea,{children:o.jsx(Vt.Row,{children:o.jsx(Vt.Column,{children:o.jsx(I4,{preset:e,onPresetChange:t,dateFrom:n.start,dateTo:n.end,onDateChange:(N,I)=>r(A=>I==="from"?{...A,start:N}:{...A,end:N})})})})}),o.jsxs("div",{className:"flex flex-col gap-6",children:[o.jsx(Fxe,{children:o.jsx(Fms,{scorers:s,datasets:_,experiments:C,avgScore:h?.avgScore??null,prevAvgScore:h?.prevAvgScore??null,totalNeedsReview:T.needsReview,isLoadingScorers:a,isLoadingDatasets:c,isLoadingExperiments:f,isLoadingScores:m,isLoadingReview:x})}),o.jsx(c7r,{summaryData:h?.summaryData??[],overTimeData:h?.overTimeData??[],scorerNames:h?.scorerNames??[],avgScore:h?.avgScore??null,isLoading:m,isError:v}),o.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:[o.jsx(mps,{experiments:C,isLoading:f,isError:!!p}),o.jsx(Vms,{experiments:C,datasets:_,isLoading:f,isError:!!p})]}),o.jsx(vms,{reviewSummary:b,experiments:C,datasets:_,isLoading:x,isError:!!S})]})]})}function Gms(){const[e,t]=g.useState(""),[n,r]=g.useState("all"),[s,a]=g.useState("all"),[i,l]=g.useState(!1),c=es(),{data:u,isLoading:d,error:f}=Im(),{data:p,isLoading:h,error:m}=UQ(),{data:v}=BAe(),y=g.useMemo(()=>u?.datasets??[],[u?.datasets]),b=g.useMemo(()=>p?.experiments??[],[p?.experiments]),x=g.useMemo(()=>Ums(y),[y]),S=g.useMemo(()=>NVt(v),[v]),k=d||h,_=m||f;if(_&&Ss(_))return o.jsx(ir,{children:o.jsx(Gs,{})});if(m&&ks(m))return o.jsx(ir,{children:o.jsx(Fs,{resource:"experiments"})});if(f&&ks(f))return o.jsx(ir,{children:o.jsx(Fs,{resource:"datasets"})});if(_)return o.jsx(ir,{children:o.jsx(Ui,{title:"Failed to load experiments",message:_.message})});const C=o.jsx(FAe,{open:i,onOpenChange:l,onSuccess:N=>{c(`/experiments/${N}`)}});if(b.length===0&&!k)return o.jsxs(ir,{children:[o.jsx(Hms,{onRunExperiment:()=>l(!0)}),C]});const T=n!=="all"||s!=="all"||e!=="",E=()=>{t(""),r("all"),a("all")};return o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx(Wms,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:x,onReset:E,hasActiveFilters:T,onRunClick:()=>l(!0)})}),o.jsx(zms,{experiments:b,datasets:y,reviewByExperiment:S,isLoading:k,search:e,statusFilter:n,datasetFilter:s}),C]})}const IVt=e=>o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 8.64637 9.45103",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:o.jsx("path",{d:"M7.80735 5.87241C7.63209 5.97219 7.43696 6.06166 7.22844 6.13866C6.46456 6.42068 5.43714 6.58649 4.32296 6.58649C3.20873 6.58649 2.18135 6.4207 1.41747 6.13866C1.20889 6.06164 1.01385 5.97223 0.838558 5.87241V7.59003C0.838558 7.62341 0.855765 7.70759 1.00172 7.83512C1.14707 7.96201 1.38219 8.09563 1.70829 8.21605C2.3572 8.45563 3.28149 8.61268 4.32296 8.61269C5.36456 8.61269 6.28937 8.45568 6.9383 8.21605C7.26428 8.09566 7.49888 7.96198 7.64419 7.83512C7.79024 7.70754 7.80735 7.62342 7.80735 7.59003V5.87241ZM7.80735 3.00789C7.63214 3.10763 7.4369 3.19647 7.22844 3.27345C6.46455 3.55549 5.43719 3.72129 4.32296 3.72129C3.20868 3.72128 2.18136 3.55552 1.41747 3.27345C1.20896 3.19645 1.01381 3.10766 0.838558 3.00789V4.72551C0.838558 4.7589 0.855657 4.84301 1.00172 4.97059C1.14707 5.09749 1.38219 5.23111 1.70829 5.35153C2.3572 5.59109 3.28154 5.74747 4.32296 5.74748C5.36456 5.74748 6.28937 5.59116 6.9383 5.35153C7.26432 5.23112 7.49887 5.09747 7.64419 4.97059C7.7536 4.87505 7.79089 4.80404 7.80257 4.76033L7.80735 4.72551V3.00789ZM7.80735 1.86099C7.80735 1.82758 7.79045 1.74291 7.64419 1.61522C7.49887 1.48838 7.26421 1.35534 6.9383 1.23497C6.28937 0.995339 5.36456 0.838331 4.32296 0.838331C3.28149 0.83834 2.3572 0.995383 1.70829 1.23497C1.38219 1.35539 1.14707 1.48832 1.00172 1.61522C0.855475 1.7429 0.838558 1.82758 0.838558 1.86099C0.838673 1.89462 0.855968 1.97882 1.00172 2.10607C1.14707 2.23297 1.38219 2.3659 1.70829 2.48632C2.3572 2.7259 3.28149 2.88295 4.32296 2.88296C5.36456 2.88296 6.28937 2.72595 6.9383 2.48632C7.26421 2.36595 7.49887 2.23291 7.64419 2.10607C7.78996 1.97881 7.80724 1.89462 7.80735 1.86099ZM8.64637 7.59003C8.64637 7.95465 8.44458 8.25006 8.1958 8.46728C7.94608 8.68529 7.60876 8.86274 7.22844 9.00318C6.46455 9.28522 5.43718 9.45102 4.32296 9.45102C3.20869 9.45101 2.18135 9.28525 1.41747 9.00318C1.03715 8.86274 0.699831 8.68529 0.450113 8.46728C0.201377 8.25007 0.000227451 7.9546 0.000227451 7.59003V1.86099C0.000227451 1.49643 0.201388 1.20095 0.450113 0.983742C0.699831 0.765728 1.03715 0.588275 1.41747 0.447838C2.18136 0.165769 3.20868 8.74396e-06 4.32296 0C5.43719 0 6.46455 0.165797 7.22844 0.447838C7.60876 0.588275 7.94608 0.765728 8.1958 0.983742C8.44457 1.20096 8.64637 1.49638 8.64637 1.86099V7.59003Z",fill:"currentColor"})}),Qms={agent:Ti,workflow:Uc,scorer:TC,processor:SD},Yms={agent:"Agent",workflow:"Workflow",scorer:"Scorer",processor:"Processor"};function jie({icon:e,typeLabel:t,children:n}){return o.jsxs("div",{className:"text-ui-sm text-neutral5 flex flex-none items-center gap-1.5 [&_svg]:size-3.5 [&_svg]:shrink-0",children:[o.jsxs(yn,{children:[o.jsx(gn,{render:o.jsx("span",{className:"text-neutral3 flex",role:"img","aria-label":t}),children:e}),o.jsx(vn,{children:t})]}),n]})}function Nie({label:e}){return o.jsxs("div",{className:"text-neutral2 text-ui-xs flex flex-none items-center gap-1.5",children:[o.jsx("span",{className:"whitespace-nowrap",children:e}),o.jsx(Fd,{className:"size-3.5 shrink-0","aria-hidden":!0})]})}const Get="text-neutral5 inline-flex items-center gap-1.5 hover:underline [&>svg]:text-neutral3 [&>svg]:size-3 [&>svg]:shrink-0";function Kms({experiment:e,className:t}){const{Link:n,paths:r}=cn(),{data:s}=Dm(),{data:a}=Wy(),{data:i}=oh(),{data:l,isLoading:c}=Yg(e.datasetId??""),{data:u}=w_(e.id,e.status),d=g.useMemo(()=>{if(e.scorerIds?.length)return e.scorerIds;if(!u)return[];const S=new Set;for(const k of Object.values(u))for(const _ of k)S.add(_.scorerId);return[...S].sort()},[e.scorerIds,u]),f=d.map(S=>i?.[S]?.scorer?.config?.name??S),p=e.targetType,h=e.targetId,m=()=>{if(!h)return"External (caller-run)";switch(p){case"agent":return s?.[h]?.name??h;case"workflow":return a?.[h]?.name??h;case"scorer":return i?.[h]?.scorer?.config?.name??h;default:return h}},v=()=>{if(!h)return null;switch(p){case"agent":return r.agentLink(h);case"workflow":return r.workflowLink(h);case"scorer":return r.scorerLink(h);default:return null}},y=p&&Qms[p]||Ti,b=p&&Yms[p]||"Evaluation target",x=v();return o.jsxs("div",{className:K("flex items-center gap-3 overflow-x-auto",t),children:[o.jsx(jie,{icon:o.jsx(IVt,{}),typeLabel:"Dataset",children:e.datasetId?o.jsxs(n,{href:r.datasetLink(e.datasetId),target:"_blank",rel:"noopener noreferrer",className:Get,children:[c?o.jsx(jt,{className:"h-4 w-28"}):l?.name??e.datasetId,e.datasetVersion!=null&&o.jsxs("span",{className:"text-neutral3",children:["(v",e.datasetVersion,")"]}),o.jsx(Yr,{})]}):o.jsx("span",{className:"text-neutral3",children:"No dataset"})}),o.jsx(Nie,{label:"each item"}),o.jsx(jie,{icon:o.jsx(y,{}),typeLabel:b,children:x?o.jsxs(n,{href:x,target:"_blank",rel:"noopener noreferrer",className:Get,children:[m(),o.jsx(Yr,{})]}):o.jsx("span",{className:"text-neutral3",children:m()})}),o.jsx(Nie,{label:"output"}),o.jsxs(yn,{children:[o.jsx(gn,{render:o.jsx("div",{tabIndex:0,className:"flex outline-offset-4",children:o.jsx(jie,{icon:o.jsx(TC,{}),typeLabel:"Scorers",children:d.length===0?"Scorers":`${d.length} scorer${d.length===1?"":"s"}`})})}),o.jsx(vn,{children:f.length>0?f.join(", "):"No scorer has produced a score yet"})]}),o.jsx(Nie,{label:"comparing ground truth"}),o.jsx("div",{className:"text-ui-sm text-neutral5 flex-none whitespace-nowrap",children:"Score"})]})}function Qz({label:e,children:t}){return o.jsxs("div",{className:"min-w-0 flex-1 px-6 py-3",children:[o.jsx("div",{className:"text-ui-sm text-neutral2 tracking-widest uppercase",children:e}),o.jsx("div",{className:"text-ui-md text-neutral5 mt-1 flex flex-wrap items-baseline gap-x-1.5",children:t})]})}function Xms(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 Jms({experiment:e,className:t}){const{data:n}=w_(e.id,e.status),r=g.useMemo(()=>{if(!n)return;const l=Object.values(n).flat();if(l.length!==0)return l.reduce((c,u)=>c+u.score,0)/l.length},[n]),s=e.startedAt??e.createdAt,a=s?new Date(s):null,i=(()=>{if(e.status==="running")return"Running…";if(!e.startedAt||!e.completedAt)return"—";const l=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return l<0?"—":Xms(l)})();return o.jsxs("div",{className:K("flex w-full items-stretch divide-x divide-border1 border-y border-border1",t),children:[o.jsx(Qz,{label:"Avg score",children:r===void 0?o.jsx("span",{className:"text-neutral3",children:"—"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{children:r.toFixed(3)}),(e.status==="running"||e.status==="pending")&&o.jsx("span",{className:"text-neutral3",children:"· so far"})]})}),o.jsx(Qz,{label:"Items",children:e.status==="running"||e.status==="pending"?o.jsxs("span",{className:"text-neutral3",children:[(e.succeededCount??0)+(e.failedCount??0),"/",e.totalItems," items processed"]}):o.jsxs(o.Fragment,{children:[o.jsxs("span",{children:[e.totalItems," item",e.totalItems===1?"":"s"]}),(e.failedCount??0)>0&&o.jsxs("span",{className:"text-error",children:["· ",e.failedCount," errored"]})]})}),o.jsx(Qz,{label:"Started",children:a?o.jsxs(o.Fragment,{children:[o.jsx("span",{children:hr(a,"MMM d, h:mm a")}),o.jsxs("span",{className:"text-neutral3",children:["· ",v2n(a,{addSuffix:!0})]})]}):o.jsx("span",{children:"—"})}),o.jsx(Qz,{label:"Duration",children:o.jsx("span",{children:i})})]})}function egs({experiment:e}){const{Link:t,paths:n}=cn(),r=e.agentVersion&&e.targetType==="agent"&&e.targetId?`${n.agentLink(e.targetId)}/editor?version=${encodeURIComponent(e.agentVersion)}`:null;return o.jsxs(Vt.TopArea,{children:[o.jsxs(Vt.Row,{children:[o.jsx(Vt.Column,{className:"justify-items-start gap-3",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx(Phs,{status:e.status,className:"h-7"}),o.jsxs(bu,{children:[o.jsxs(bu.Title,{children:["Experiment #",e.id.slice(0,8)]}),e.description&&o.jsx(bu.Description,{children:e.description}),o.jsx(Kms,{experiment:e,className:"mt-2"})]})]})}),o.jsx(Vt.Column,{className:"justify-items-end gap-3",children:e.agentVersion&&o.jsxs(_n,{numOfCol:1,children:[o.jsx(_n.Key,{children:"Version"}),r?o.jsx(_n.ValueLink,{href:r,as:t,children:e.agentVersion}):o.jsx(_n.Value,{children:e.agentVersion})]})})]}),o.jsx(Jms,{experiment:e,className:"-mx-6 w-auto"})]})}function Yz({children:e}){return o.jsxs(Vt,{height:"full",children:[o.jsx("div",{}),o.jsx(Vt.MainArea,{isCentered:!0,children:e})]})}function tgs(){const{experimentId:e}=mr(),{data:t,isLoading:n}=UQ(),s=t?.experiments?.find(h=>h.id===e)?.datasetId??"",{data:a,isLoading:i,error:l}=Exe(s,e??""),{data:c,isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p}=LD({datasetId:s,experimentId:e??"",experimentStatus:a?.status});return!e||n||i?null:l&&Ss(l)?o.jsx(Yz,{children:o.jsx(Gs,{})}):l&&ks(l)?o.jsx(Yz,{children:o.jsx(Fs,{resource:"datasets"})}):l&&o2t(l)||!n&&!s||!i&&!l&&!a?o.jsx(Yz,{children:o.jsx(Er,{iconSlot:o.jsx(n0e,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:o.jsxs(oe,{as:wi,to:"/experiments",children:[o.jsx(gl,{}),"Back to Experiments"]})})}):l?o.jsx(Yz,{children:o.jsx(Ui,{title:"Failed to load experiment",message:l instanceof Error?l.message:"An unexpected error occurred. Please try again."})}):o.jsx(Ths,{experimentId:e,datasetId:s,experimentStatus:a.status,results:c??[],isLoadingResults:u,hasNextPage:p,children:o.jsxs("div",{className:"relative h-full overflow-hidden",children:[o.jsxs(Vt,{height:"full",children:[o.jsx(egs,{experiment:a}),o.jsx(Vt.MainArea,{className:"overflow-visible",children:o.jsx(Rhs,{experimentId:e,datasetId:s,experimentStatus:a.status,results:c??[],isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p})})]}),o.jsx(Fg,{})]})})}const UAe=e=>o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 9.45892 8.88606",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{d:"M8.53702 7.36403C8.98547 7.36403 9.34918 7.70502 9.34918 8.12535C9.34906 8.54559 8.9854 8.88606 8.53702 8.88606H5.6839C5.23552 8.88606 4.87186 8.54559 4.87174 8.12535C4.87174 7.70502 5.23545 7.36403 5.6839 7.36403H8.53702Z",fill:"currentColor"}),o.jsx("path",{d:"M8.53702 3.67209C8.98547 3.67209 9.34918 4.01309 9.34918 4.43342C9.34911 4.8537 8.98543 5.19413 8.53702 5.19413H5.6839C5.23549 5.19413 4.87181 4.8537 4.87174 4.43342C4.87174 4.01309 5.23545 3.67209 5.6839 3.67209H8.53702Z",fill:"currentColor"}),o.jsx("path",{d:"M8.67155 0C9.10635 2.06584e-05 9.45892 0.341006 9.45892 0.761326C9.45878 1.18153 9.10627 1.52201 8.67155 1.52203H2.88163C2.4469 1.52203 2.0944 1.18154 2.09427 0.761326C2.09427 0.340993 2.44681 3.80132e-08 2.88163 0H8.67155Z",fill:"currentColor"}),o.jsx("path",{d:"M0.757606 0.760086V4.01122H3.50594V4.76883H0.759466L0.762566 5.4291C0.76837 6.70703 1.8058 7.73972 3.08374 7.73973H3.67953V8.49796H3.08374C1.38863 8.49795 0.0120204 7.1273 0.00433981 5.4322L0 4.39188V0.760086H0.757606Z",fill:"currentColor"})]});function Iie(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function ngs({report:e}){const{served:t,unconsumed:n,liveCalls:r,failure:s}=e,a=[...t.map(i=>({outcome:"served",toolName:i.toolName,args:i.args})),...r.map(i=>({outcome:"live",toolName:i.toolName,args:i.args})),...n.map(i=>({outcome:"unconsumed",toolName:i.toolName,args:i.args}))];return o.jsxs("div",{className:"grid gap-2","data-testid":"tool-mock-report",children:[o.jsx(fn.SectionHeading,{icon:o.jsx(Ud,{}),className:"mb-2",children:"Tool Mocks"}),s&&o.jsx(Wn,{variant:"destructive",title:"Mock mismatch",children:o.jsxs(Wn.Message,{children:[o.jsx("span",{className:"block",children:`Tool "${s.toolName}" was called with arguments that did not match an available mock (${s.code}).`}),o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Called with: ",Iie(s.args)]}),n.length>0&&o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Unconsumed mocks: ",n.map(i=>Iie(i.args)).join(", ")]})]})}),o.jsx("div",{className:"border-border1 divide-border1 divide-y rounded border text-sm",children:a.map((i,l)=>o.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-1.5",children:[o.jsxs("span",{className:"min-w-0 truncate",children:[o.jsx("span",{className:"text-neutral4 font-mono",children:i.toolName}),o.jsx("span",{className:"text-neutral3 ml-2 font-mono text-xs",children:Iie(i.args)})]}),o.jsx("span",{className:`shrink-0 rounded px-2 py-0.5 text-xs ${rgs(i.outcome)}`,children:i.outcome})]},`${i.outcome}-${i.toolName}-${l}`))})]})}function rgs(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 sgs({result:e,scores:t,onPrevious:n,onNext:r,onClose:s,onShowTrace:a,onOpenInReview:i,onScoreClick:l,featuredScoreId:c,onFlagForReview:u,collapsed:d=!1,scorePanelSlot:f}){const p=!!e?.error,h=Kz(e?.input),m=Kz(e?.output),v=Kz(e?.groundTruth),y=u&&e.status!=="needs-review"&&e.status!=="complete",b=Array.isArray(e.tags)?e.tags:[];return o.jsxs(fn,{collapsed:d,children:[o.jsxs(fn.Header,{children:[o.jsxs(fn.Heading,{children:["Result ",o.jsxs("b",{children:["# ",e.id.length>12?`${e.id.slice(0,12)}…`:e.id]})]}),o.jsxs(hs,{className:"ml-auto shrink-0",children:[o.jsx(fn.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Previous result",nextLabel:"Next result"}),e.traceId&&o.jsxs(oe,{size:"md",onClick:a,children:[o.jsx(UAe,{}),"Trace"]}),o.jsx(fn.CloseButton,{onClick:s,tooltip:"Close result panel"})]})]}),!d&&o.jsx(ags,{scorePanelSlot:f,children:o.jsxs(fn.Content,{children:[o.jsxs("div",{className:"mb-6 grid gap-4",children:[o.jsxs(_n,{children:[o.jsx(_n.Key,{children:"Item Id"}),o.jsx(_n.ValueWithCopyBtn,{copyTooltip:"Copy Item Id to clipboard",copyValue:e.itemId,children:e.itemId}),o.jsx(_n.Key,{children:"Created"}),o.jsx(_n.Value,{children:hr(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")})]}),p&&o.jsx(Wn,{variant:"destructive",title:"Error",children:o.jsx(Wn.Message,{children:Kz(e?.error&&typeof e.error=="object"?e.error.message:e?.error)})}),t&&t.length>0&&o.jsxs(be,{columns:"1fr 1fr",children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"Scorer"}),o.jsx(be.TopCell,{children:"Score"})]}),t.map(x=>o.jsxs(be.RowButton,{featured:c===x.id,onClick:()=>l?.(x.id),children:[o.jsx(be.Cell,{children:x.scorerId}),o.jsx(be.TextCell,{font:"mono",children:x.score.toFixed(3)})]},x.id))]}),e.toolMockReport&&o.jsx(ngs,{report:e.toolMockReport}),(e.status||b.length>0||y)&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(fn.SectionHeading,{icon:o.jsx(sI,{}),className:"mb-2",children:"Review"}),(e.status||b.length>0)&&o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.status&&o.jsx("span",{className:`rounded-full px-2 py-0.5 text-xs font-medium ${e.status==="needs-review"?"bg-orange-500/10 text-orange-400":e.status==="complete"?"bg-accent1/10 text-accent1":"bg-neutral3/10 text-neutral4"}`,children:e.status}),b.map(x=>o.jsx("span",{className:"bg-surface4 text-neutral4 rounded px-2 py-0.5 text-xs",children:x},x))]}),y&&o.jsx("div",{children:o.jsxs(oe,{size:"sm",onClick:()=>u(e.id),children:[o.jsx(vO,{}),"Flag for Review"]})}),e.status==="needs-review"&&i&&o.jsx("div",{children:o.jsxs(oe,{size:"sm",onClick:i,children:[o.jsx(Yr,{}),"Review"]})})]})]}),o.jsxs("div",{className:"grid gap-3",children:[o.jsx(fn.CodeSection,{title:"Input",icon:o.jsx(vV,{}),codeStr:h}),o.jsx(fn.CodeSection,{title:"Output",icon:o.jsx(em,{}),codeStr:m}),o.jsx(fn.CodeSection,{title:"Ground Truth",icon:o.jsx(ect,{}),codeStr:v})]})]})})]})}function ags({scorePanelSlot:e,children:t}){return e?o.jsxs("div",{className:"grid min-h-0 flex-1 grid-cols-[1fr_1fr]",children:[o.jsx("div",{className:"flex min-h-0 flex-col overflow-hidden",children:t}),o.jsx("div",{className:"animate-in border-border1 fade-in-0 flex min-h-0 flex-col overflow-hidden border-l duration-300",children:e})]}):o.jsx(o.Fragment,{children:t})}function Kz(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function igs(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function ogs({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s,collapsed:a,onCollapsedChange:i,className:l}){const[c,u]=g.useState(!1),d=a??c,f=i??u,p=igs(e),h=p?"N/A — code-based scorer":"N/A — step not configured";return o.jsxs(fn,{collapsed:d,className:l,children:[o.jsxs(fn.Header,{children:[o.jsxs(fn.Heading,{children:["Score ",o.jsx("b",{children:e.scorerId})]}),o.jsxs(hs,{className:"ml-auto shrink-0",children:[i&&o.jsx(oe,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(XN,{}):o.jsx(hV,{})}),(n||t)&&o.jsx(fn.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:"Previous score",nextLabel:"Next score"}),s&&e.traceId&&o.jsxs(oe,{size:"md",onClick:s,children:[o.jsx(UAe,{}),"Trace"]}),o.jsx(fn.CloseButton,{onClick:r,tooltip:"Close score panel"})]})]}),!d&&o.jsx(fn.Content,{children:o.jsxs("div",{className:"grid gap-3",children:[o.jsx(fn.CodeSection,{title:`Score: ${e.score}`,icon:o.jsx(Wp,{}),codeStr:e.reason||h,simplified:!0}),!p&&o.jsxs(o.Fragment,{children:[o.jsx(fn.CodeSection,{title:"Preprocess Prompt",icon:o.jsx(Ah,{}),codeStr:e.preprocessPrompt||h,simplified:!0}),o.jsx(fn.CodeSection,{title:"Analyze Prompt",icon:o.jsx(Ah,{}),codeStr:e.analyzePrompt||h,simplified:!0}),o.jsx(fn.CodeSection,{title:"Generate Score Prompt",icon:o.jsx(Ah,{}),codeStr:e.generateScorePrompt||h,simplified:!0}),o.jsx(fn.CodeSection,{title:"Generate Reason Prompt",icon:o.jsx(Ah,{}),codeStr:e.generateReasonPrompt||h,simplified:!0})]})]})})]})}function lgs(){const{itemId:e}=mr();return e?o.jsx(cgs,{itemId:e},e):null}function cgs({itemId:e}){const{experimentId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:a,close:i,openInReview:l,goToPreviousItem:c,goToNextItem:u}=CVt(),d=g.useMemo(()=>r.find(M=>M.itemId===e)??null,[r,e]),{data:f}=w_(t,n),p=d?f?.[d.itemId]:void 0,[h,m]=g.useState(null),[v,y]=g.useState(void 0),[b,x]=g.useState(null),[S,k]=g.useState(!1),[_,C]=g.useState(!1),T=p?.find(M=>M.id===b)??null,E=g.useCallback(M=>{x(G=>M===G?null:M),m(null),y(void 0)},[]),N=()=>{if(!b||!p)return;const M=p.findIndex(G=>G.id===b);if(M>=0&&M<p.length-1)return()=>x(p[M+1].id)},I=()=>{if(!b||!p)return;const M=p.findIndex(G=>G.id===b);if(M>0)return()=>x(p[M-1].id)},{data:A,isLoading:R}=$hs(h),L=A?.spans,{data:D,isLoading:F}=_Q(h,v),H=D?.span,{handlePreviousSpan:B,handleNextSpan:z}=eqt(L,v??null,y),V=(()=>{const M=[],G=!!h;return M.push(S?"auto":G?"2fr":"1fr"),G&&M.push(_?"auto":"3fr"),G&&v&&M.push("3fr"),M.join(" ")})();return o.jsx(DAe,{label:`Experiment item ${e}`,wide:!!T&&!S,children:d?o.jsxs("div",{className:"[&>section]:bg-surface3 grid h-full min-h-0 content-start gap-4 p-3 [&>section]:rounded-lg [&>section]:shadow-lg",style:{gridTemplateRows:V},children:[o.jsx(sgs,{result:d,scores:p,onPrevious:c,onNext:u,onClose:i,onScoreClick:E,featuredScoreId:b,onShowTrace:()=>{d.traceId&&(m(d.traceId),y(void 0),x(null),k(!0),C(!1))},onOpenInReview:()=>l(d.id),collapsed:S,scorePanelSlot:T?o.jsx(ogs,{score:T,onNext:N(),onPrevious:I(),onClose:()=>x(null),onShowTrace:()=>{T.traceId&&(m(T.traceId),y(void 0),k(!0),C(!1))},className:"rounded-none border-0 bg-transparent"}):null}),h&&o.jsxs(o.Fragment,{children:[o.jsx(lqt,{traceId:h,spans:L,isLoading:R,onClose:()=>{m(null),y(void 0),k(!1)},onSpanSelect:y,initialSpanId:v??null,placement:"traces-list",showUnavailableFeaturesMsg:!1,collapsed:_,onCollapsedChange:C,LinkComponent:cy,traceHref:`/traces?traceId=${encodeURIComponent(h)}`}),v&&o.jsx(JUt,{traceId:h,spanId:v,span:H,isLoading:F,onPrevious:B,onNext:z,onClose:()=>y(void 0)})]})]}):s||a?o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(Ut,{})})}):o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(Er,{iconSlot:o.jsx(n0e,{}),titleSlot:"Item not found",descriptionSlot:`No loaded result for item "${e}".`,actionSlot:o.jsx(oe,{onClick:i,children:"Close"})})})})})}function ugs({connection:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsxs("li",{className:"flex items-center justify-between border-b py-2",children:[o.jsxs("div",{children:[o.jsx("div",{className:"font-mono text-xs",children:e.connectionId}),o.jsxs("div",{className:"text-xs text-gray-500",children:[e.label??"(no label)"," · ",e.status,e.scope?` · ${e.scope}`:"",t&&e.authorId?` · author: ${e.authorId}`:""]})]}),o.jsx("button",{type:"button",className:"text-red-600 underline disabled:opacity-50",onClick:r,disabled:n,children:"Disconnect"})]})}function AVt({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("ul",{className:"space-y-1",children:e.map(s=>o.jsx(ugs,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function dgs({groups:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("div",{className:"space-y-4",children:e.map(([s,a])=>o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-semibold text-gray-700","data-testid":`integration-author-group-${s}`,children:s==="shared"?"Shared":`Owned by ${s}`}),o.jsx(AVt,{connections:a,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function fgs({providerId:e,toolkit:t,connections:n,groupedByAuthor:r,isAdmin:s,isLoading:a,error:i,disconnectPending:l,disconnectError:c,onDisconnect:u}){return o.jsxs("div",{className:"space-y-2 border rounded p-4",children:[o.jsx("h2",{className:"text-lg font-semibold",children:"Existing connections"}),!e||!t?o.jsx("p",{className:"text-gray-500",children:"Pick a provider and toolkit to list connections."}):a?o.jsx("p",{className:"text-gray-500",children:"Loading…"}):i?o.jsx("p",{className:"text-red-600",children:String(i)}):n.length===0?o.jsx("p",{className:"text-gray-500",children:"No connections."}):r?o.jsx(dgs,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):o.jsx(AVt,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?o.jsx("p",{className:"text-red-600",children:String(c)}):null]})}function pgs({providers:e,toolkits:t,providerId:n,toolkit:r,label:s,providersLoading:a,providersError:i,toolkitsLoading:l,toolkitsError:c,authorizePending:u,authorizeError:d,authorizedConnection:f,onProviderChange:p,onToolkitChange:h,onLabelChange:m,onConnect:v}){return o.jsxs("div",{className:"space-y-4 border rounded p-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"provider-select",children:"Provider"}),o.jsxs("select",{id:"provider-select",className:"border rounded px-2 py-1 w-full",value:n,onChange:y=>p(y.target.value),disabled:a,children:[o.jsx("option",{value:"",children:"— select provider —"}),e.map(y=>o.jsxs("option",{value:y.id,children:[y.displayName??y.name," (",y.id,")"]},y.id))]}),a&&o.jsx("span",{className:"text-gray-500",children:"Loading providers…"}),i?o.jsx("span",{className:"text-red-600",children:String(i)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"toolkit-select",children:"Toolkit"}),o.jsxs("select",{id:"toolkit-select",className:"border rounded px-2 py-1 w-full",value:r,onChange:y=>h(y.target.value),disabled:!n||l,children:[o.jsx("option",{value:"",children:"— select toolkit —"}),t.map(y=>o.jsxs("option",{value:y.slug,children:[y.name," (",y.slug,")"]},y.slug))]}),l&&o.jsx("span",{className:"text-gray-500",children:"Loading toolkits…"}),c?o.jsx("span",{className:"text-red-600",children:String(c)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"label-input",children:"Label (optional)"}),o.jsx("input",{id:"label-input",type:"text",className:"border rounded px-2 py-1 w-full",placeholder:"My personal Gmail",value:s,onChange:y=>m(y.target.value),disabled:!n||!r})]}),o.jsx("button",{type:"button",className:"bg-blue-600 text-white rounded px-4 py-2 disabled:opacity-50",onClick:v,disabled:!n||!r||u,children:u?"Authorizing…":"Connect"}),d?o.jsx("p",{className:"text-red-600",children:String(d)}):null,f&&o.jsxs("p",{className:"text-green-700",children:["Authorized: ",f.connectionId," (status: ",f.status,")"]})]})}const Qet=e=>e.authorId?.trim()||"shared",hgs=(e,t)=>{if(!t||new Set(e.map(Qet)).size<=1)return null;const r=new Map;for(const a of e){const i=Qet(a);r.set(i,[...r.get(i)??[],a])}const s=Array.from(r.entries());return s.sort(([a],[i])=>a==="shared"?1:i==="shared"?-1:a.localeCompare(i)),s},mgs=["*","tool-providers:*","tool-providers:admin"];function ggs(){const{data:e}=Mm();return e?.permissions?.some(t=>mgs.includes(t))??!1}function vgs(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,a]=g.useState(""),i=YI(),l=UZ(e||null),c=LDt(e||null,n||null),u=DDt(),d=PDt(),f=ggs(),p=i.data?.providers??[],h=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),v=g.useMemo(()=>hgs(m,f),[m,f]),y=S=>{t(S),r("")},b=()=>{!e||!n||u.mutate({providerId:e,toolkit:n,label:s.trim()||null},{onSuccess:()=>{a(""),c.refetch()}})},x=S=>{d.mutate({providerId:e,connectionId:S})};return o.jsxs("div",{className:"p-6 max-w-3xl space-y-6 text-sm",children:[o.jsx("h1",{className:"text-2xl font-semibold",children:"Integrations"}),o.jsx("p",{className:"text-gray-500",children:"Minimal page to verify the ToolProvider backend. Pick a provider and toolkit, then connect."}),o.jsx(pgs,{providers:p,toolkits:h,providerId:e,toolkit:n,label:s,providersLoading:i.isLoading,providersError:i.error,toolkitsLoading:l.isLoading,toolkitsError:l.error,authorizePending:u.isPending,authorizeError:u.error,authorizedConnection:u.data,onProviderChange:y,onToolkitChange:r,onLabelChange:a,onConnect:b}),o.jsx(fgs,{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 ygs({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(qp,{className:"h-10 w-10"}),o.jsx("h1",{className:"text-neutral6 text-xl font-semibold",children:e})]}),t,n,r]})})}function RVt({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:a}=fc(),{mutate:i,isPending:l,error:c}=vAr(),{mutate:u,isPending:d,error:f}=bAr(),{mutate:p,isPending:h}=F2t(),[m,v]=g.useState(n),[y,b]=g.useState(""),[x,S]=g.useState(""),[k,_]=g.useState("");if(a)return o.jsx("div",{className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"text-neutral3",children:"Loading..."})});if(!s?.enabled||!s?.login)return o.jsx("div",{className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"text-neutral3",children:"Authentication is not configured"})});const{login:C}=s,T=C.type==="sso"||C.type==="both",E=C.type==="credentials"||C.type==="both",N=C.sso,I=C.signUpEnabled!==!1,A=m==="signin"||!I,R=A?l:d,L=A?c:f,D=()=>{t?t():e?window.location.href=e:window.location.href=sG("/")},F=M=>{M.preventDefault(),A?i({email:x,password:k},{onSuccess:D}):u({email:x,password:k,name:y||void 0},{onSuccess:D})},H=()=>{p({redirectUri:e},{onSuccess:M=>{window.location.href=M.url}})},B=()=>{v(A?"signup":"signin")},z=C.description?o.jsxs("div",{className:"border-border1 bg-surface1 flex items-start gap-2.5 rounded-md border p-3",children:[o.jsx(Bd,{className:"text-neutral4 mt-0.5 h-4 w-4 shrink-0"}),o.jsx("p",{className:"text-neutral3 text-sm",children:C.description})]}):null,V=r?o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:r}):null;return o.jsxs(ygs,{title:A?"Sign in to Mastra Studio":"Create your account",description:z,errorBanner:V,children:[E&&o.jsxs("form",{onSubmit:F,className:"space-y-4",children:[!A&&o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"name",className:"text-neutral4 block text-sm",children:"Name"}),o.jsx(In,{id:"name",type:"text",value:y,onChange:M=>b(M.target.value),placeholder:"Your name",variant:"default",size:"lg"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"email",className:"text-neutral4 block text-sm",children:"Email"}),o.jsx(In,{id:"email",type:"email",value:x,onChange:M=>S(M.target.value),placeholder:"you@example.com",required:!0,variant:"default",size:"lg"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"password",className:"text-neutral4 block text-sm",children:"Password"}),o.jsx(In,{id:"password",type:"password",value:k,onChange:M=>_(M.target.value),placeholder:A?"Enter your password":"Create a password",required:!0,variant:"default",size:"lg"})]}),L&&o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:L.message}),o.jsx(oe,{type:"submit",disabled:R,className:"w-full",size:"lg",children:R?A?"Signing in...":"Creating account...":A?"Sign in":"Create account"}),I&&o.jsxs("div",{className:"text-center text-sm",children:[o.jsx("span",{className:"text-neutral3",children:A?"Don't have an account? ":"Already have an account? "}),o.jsx("button",{type:"button",onClick:B,className:"text-neutral6 hover:underline",children:A?"Sign up":"Sign in"})]})]}),T&&E&&o.jsxs("div",{className:"relative",children:[o.jsx("div",{className:"absolute inset-0 flex items-center",children:o.jsx("div",{className:"border-border1 w-full border-t"})}),o.jsx("div",{className:"relative flex justify-center text-sm",children:o.jsx("span",{className:"bg-surface1 text-neutral3 px-2",children:"or continue with"})})]}),T&&N&&o.jsxs(oe,{onClick:H,disabled:h,className:"w-full",size:"lg",variant:"outline",children:[N.icon&&o.jsx("span",{className:"mr-2",children:N.icon}),h?"Redirecting...":N.text||"Sign in"]})]})}function bgs(){const[e]=hi(),t=es(),n=e.get("redirect")||"/",s=e.get("mode")==="signup"?"signup":"signin",a=e.get("error_description")||e.get("error")||null,i=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(RVt,{redirectUri:n,onSuccess:i,initialMode:s,errorMessage:a})}function xgs({collapsed:e,children:t}){return o.jsx("section",{className:K("flex flex-col overflow-hidden rounded-xl border border-border1 bg-surface2",e?"h-auto":"h-full"),children:t})}function wgs({onClick:e,tooltip:t="Close panel",className:n}){return o.jsx(oe,{size:"md",onClick:e,"aria-label":"Close Panel",tooltip:t,className:n,children:o.jsx(or,{})})}function Sgs(){return kI({settings:{fontFamily:"var(--font-mono)",fontSize:"0.75rem",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"#939393",background:"transparent"},styles:[{tag:[de.className,de.propertyName]}]})}function kgs(){const e=Rt.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"0.75rem"},"&.cm-editor .cm-scroller":{fontFamily:"var(--font-mono)"},".cm-gutters":{backgroundColor:"transparent",color:"var(--neutral2)",borderRight:"none"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-activeLine":{backgroundColor:"transparent"},".cm-activeLineGutter":{backgroundColor:"transparent"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"var(--neutral6)"}}),t=Kg.define([{tag:[de.comment,de.bracket],color:"var(--neutral2)"},{tag:[de.string,de.meta,de.regexp],color:"var(--accent1)"},{tag:[de.atom,de.bool,de.special(de.variableName)],color:"var(--accent6)"},{tag:[de.keyword,de.operator,de.tagName],color:"var(--accent2)"},{tag:[de.function(de.propertyName),de.propertyName],color:"var(--accent5)"},{tag:[de.definition(de.variableName),de.function(de.variableName),de.className,de.attributeName],color:"var(--accent3)"},{tag:[de.variableName,de.number],color:"var(--accent5)"},{tag:[de.name,de.quote],color:"var(--accent1)"}]);return[e,rS(t)]}const Ogs=()=>{const e=K_().resolvedTheme==="dark";return g.useMemo(()=>e?Sgs():kgs(),[e])};function _gs({codeStr:e="",title:t,icon:n,simplified:r=!1,className:s}){const a=Ogs(),[i,l]=g.useState(!1),c=g.useMemo(()=>{try{const f=JSON.parse(e);return zxe(f||"")}catch{return!1}},[e]),u=i?e?.replace(/\\n/g,`
|
|
643
643
|
`):e,d=r||i;return!e||e==="null"?null:o.jsxs("div",{className:K("flex flex-col gap-2",s),children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:K("flex items-center gap-1.5 text-ui-xs tracking-widest text-neutral2 uppercase","[&>svg]:size-3.5"),children:[n,t]}),o.jsxs(hs,{children:[o.jsx(ka,{content:e||"No content",size:"sm"}),c&&o.jsx(oe,{size:"sm","aria-label":i?"Show escaped newlines":"Show multiline text",onClick:()=>l(f=>!f),children:i?o.jsx(s1,{}):o.jsx(R9,{})})]})]}),o.jsx("div",{className:"border-border1 bg-surface3 text-ui-sm text-neutral4 max-h-[30vh] overflow-hidden overflow-y-auto rounded-lg border p-3 break-all dark:border-white/10 dark:bg-black/20",children:d?o.jsx("div",{className:"text-neutral4 font-mono break-all",children:o.jsx("pre",{className:"text-wrap",children:u})}):o.jsx(rd,{extensions:[Yj(),Rt.lineWrapping],theme:a,value:e,editable:!1})})]})}function zxe(e){if(typeof e=="string"){const t=e.indexOf(`
|
|
644
|
-
`);return t!==-1&&t!==e.length-1}else{if(Array.isArray(e))return e.some(t=>zxe(t));if(e&&typeof e=="object")return Object.values(e).some(t=>zxe(t))}return!1}function Cgs({children:e}){return o.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e})}function Egs({className:e,children:t}){return o.jsx("div",{className:K("mx-4 flex items-center justify-between gap-2 border-b border-border1 py-3",e),children:t})}function Tgs({className:e,children:t}){return o.jsx("h3",{className:K("flex gap-2 text-ui-md text-neutral3 [&>b]:font-normal [&>b]:text-neutral2",e),children:t})}function jgs({className:e,children:t}){return o.jsx("dl",{className:K("grid grid-cols-[auto_1fr] gap-x-4 gap-y-1.5",e),children:t})}function Ngs({className:e,children:t}){return o.jsx("dt",{className:K("shrink-0 py-0.5 text-ui-smd text-neutral2",e),children:t})}function Igs({className:e,children:t}){return o.jsx("dd",{className:K("min-w-0 truncate py-0.5 text-ui-smd text-neutral3",e),children:t})}function Ags({className:e,children:t}){return o.jsx("dt",{className:K("col-span-2 py-3 text-ui-sm tracking-widest text-neutral2 uppercase",e),children:t})}const Rgs=Object.assign(jgs,{Key:Ngs,Value:Igs,Header:Ags});function Pgs({children:e}){return o.jsxs("div",{className:"text-ui-sm text-neutral3 flex items-center justify-center gap-2 px-4 py-6",children:[o.jsx(Ut,{size:"sm",variant:"pulse",className:"text-neutral3"})," ",e??"Loading..."]})}function $gs({children:e}){return o.jsx("p",{className:"text-ui-sm text-neutral2 px-4 py-6",children:e??"No data found."})}const Li=Object.assign(xgs,{Header:Egs,Heading:Tgs,CloseButton:wgs,LoadingData:Pgs,NoData:$gs,Content:Cgs,KeyValueList:Rgs,CodeSection:_gs}),hp=Li.KeyValueList;function Mgs(e){return e instanceof Date?e:new Date(e)}function Dgs({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:a,collapsed:i,onCollapsedChange:l}){const[c,u]=g.useState(!1),d=i??c,f=l??u,p=Mgs(e.timestamp),h=e.traceId,m=e.spanId;return o.jsxs(Li,{collapsed:d,children:[o.jsxs(Li.Header,{children:[o.jsxs(Li.Heading,{children:["Log ",o.jsx("b",{children:hr(p,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(hs,{className:"ml-auto shrink-0",children:[l&&o.jsx(oe,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(XN,{}):o.jsx(hV,{})}),o.jsxs(hs,{spacing:"close",children:[o.jsx(oe,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(q1,{})}),o.jsx(oe,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(pV,{})})]}),o.jsx(Li.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(Li.Content,{children:[o.jsx("p",{className:"text-ui-md text-neutral4 font-mono wrap-break-word whitespace-pre-wrap",children:e.message}),(h||m)&&o.jsxs("div",{className:K("my-8 grid gap-2","[&>button]:justify-between [&>button]:overflow-hidden"),children:[h&&o.jsxs(hs,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(oe,{size:"md",className:"min-w-0 flex-1 overflow-hidden",onClick:()=>n?.(h),children:[o.jsx(Fd,{}),o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",h]})]}),o.jsx(ka,{content:h,size:"md",tooltip:"Copy Trace ID to clipboard"})]}),m&&o.jsxs(hs,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(oe,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!h||!r,onClick:()=>h&&r?.(h,m),children:[o.jsx(Fd,{}),o.jsx("span",{children:"Span"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",m]})]}),o.jsx(ka,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(hp,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(hp.Key,{children:"Entity Type"}),o.jsx(hp.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(hp.Key,{children:"Entity Name"}),o.jsx(hp.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(hp.Key,{children:"Service"}),o.jsx(hp.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(hp.Key,{children:"Environment"}),o.jsx(hp.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(hp.Key,{children:"Source"}),o.jsx(hp.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(hp.Key,{children:v}),o.jsx(hp.Value,{children:String(y)})]},v))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(Li.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function Lgs({error:e,resource:t,errorTitle:n}){if(Ss(e))return o.jsx(Gs,{});if(ks(e))return o.jsx(Fs,{resource:t});if(P4(e))return o.jsx(Er,{iconSlot:o.jsx(Mc,{}),titleSlot:"Observability storage is not available",descriptionSlot:"The observability storage domain is disabled or not configured. Enable it in your storage configuration to view logs in Studio."});if(R4(e,"logs"))return o.jsx(Er,{iconSlot:o.jsx(Mc,{}),titleSlot:"Logs are not available with your current storage",descriptionSlot:"The configured observability storage provider does not support listing logs. Switch to a storage provider with logs support to view runtime logs in Studio."});const r=e instanceof Error?e.message:void 0;return o.jsx(Ui,{title:n,message:r??"Unknown error"})}function Fgs({listSlot:e,logPanelSlot:t,tracePanelSlot:n,spanPanelSlot:r,logCollapsed:s}){const a=!!t;return o.jsxs("div",{className:K("grid h-full min-h-0 items-start gap-4",a?"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[e,a&&o.jsxs("div",{className:K("grid h-full gap-4 overflow-auto",n&&r?s?"grid-rows-[auto_1fr_1fr]":"grid-rows-[1fr_1fr_1fr]":n?s?"grid-rows-[auto_1fr]":"grid-rows-[1fr_1fr]":s?"grid-rows-[auto]":"grid-rows-[1fr]"),children:[t,n,r]})]})}const zgs={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 Bgs({level:e}){const t=zgs[e];return o.jsx(lo,{children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function Ugs({entityType:e,className:t}){const n=K("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case"agent":return o.jsx(Ti,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return o.jsx(Uc,{className:n,"aria-hidden":!0});case"tool":return o.jsx(Ff,{className:n,"aria-hidden":!0});default:return null}}function qgs({entityType:e,entityName:t}){const n=e??"";return o.jsxs(lo,{className:"flex min-w-0 items-center gap-2",children:[o.jsx(Ugs,{entityType:n}),t?o.jsx("span",{className:"text-ui-smd min-w-0 truncate",children:t}):"-"]})}function Vgs({message:e}){return o.jsx(lo,{className:"text-ui-smd text-neutral4 min-w-0 truncate font-mono",children:e})}function Hgs({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(lo,{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(RTe,{font:"mono",children:t})}const Ql=Object.assign(q4,{Top:KZ,TopCell:mC,TopCellWithTooltip:XZ,TopCellSmart:T3t,RowWrapper:MTe,RowButton:V4,RowLink:E3t,Spacer:DTe,NoMatch:YZ,DateCell:O3t,TimeCell:_3t,LevelCell:Bgs,EntityCell:qgs,MessageCell:Vgs,DataCell:Hgs,NextPageLoading:QZ}),Yet="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",Wgs=36,Zgs=8;function Ggs({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=g.useRef(null),u=qUt({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>Wgs,overscan:Zgs}),{getRowProps:d}=wo({count:e.length,containerRef:c,onNavigate:y=>u.scrollToIndex(y)}),f=g.useRef(t);if(g.useEffect(()=>{f.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),f.current=t},[t]),t)return o.jsx(Pl,{columns:Yet});const p=u.getVirtualItems(),h=u.getTotalSize(),m=p[0]?.start??0,v=p.length>0?Math.max(0,h-(p[p.length-1]?.end??0)):0;return o.jsxs(Ql,{columns:Yet,variant:"striped",scrollRef:c,className:"min-w-0",children:[o.jsxs(Ql.Top,{children:[o.jsx(Ql.TopCell,{children:"Date"}),o.jsx(Ql.TopCell,{children:"Time"}),o.jsx(Ql.TopCell,{children:"Level"}),o.jsx(Ql.TopCell,{children:"Entity"}),o.jsx(Ql.TopCell,{children:"Message"}),o.jsx(Ql.TopCell,{children:"Data"})]}),e.length===0?o.jsx(Ql.NoMatch,{message:"No logs match your search"}):o.jsxs(o.Fragment,{children:[o.jsx(Ql.Spacer,{height:m}),p.map(y=>{const b=e[y.index];if(!b)return null;const x=a.get(b);if(!x)return null;const S=x===i;return o.jsxs(Ql.RowButton,{ref:u.measureElement,"data-index":y.index,...d(y.index),onClick:()=>l(b),featured:S,variant:b.level==="error"||b.level==="fatal"?"error":"default",children:[o.jsx(Ql.DateCell,{timestamp:b.timestamp}),o.jsx(Ql.TimeCell,{timestamp:b.timestamp}),o.jsx(Ql.LevelCell,{level:b.level}),o.jsx(Ql.EntityCell,{entityType:b.entityType,entityName:b.entityName}),o.jsx(Ql.MessageCell,{message:b.message}),o.jsx(Ql.DataCell,{data:b.data})]},x)}),o.jsx(Ql.Spacer,{height:v})]}),o.jsx(Ql.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function Qgs({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>Ygs(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(CAe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(OAe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function Ygs(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 Kgs={"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"},Aie="MMM d, yyyy HH:mm",Rie="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function Xgs({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${Kgs[e]}`,description:Rie}:t&&n?{title:`No logs between ${hr(t,Aie)} and ${hr(n,Aie)}`,description:Rie}:t?{title:`No logs since ${hr(t,Aie)}`,description:Rie}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const Jgs=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=Xgs({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Er,{iconSlot:o.jsx(Mc,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(oe,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",children:["Logging Documentation ",o.jsx(Yr,{})]})})})},evs=20,tvs=1e4;function nvs(e,t,n){if(e?.pagination?.hasMore)return n+1}function rvs(e){const t=new Set,n=[];for(const r of e.pages)for(const s of r.logs??[]){const a=s.logId??JSON.stringify(s);t.has(a)||(t.add(a),n.push(s))}return n}function svs(e){return R4(e.state.error,"logs")||P4(e.state.error)?!1:tvs}const avs=({filters:e}={})=>{const t=Qe(),{inView:n,setRef:r}=tC(),s=K1({queryKey:["logs",e],queryFn:({pageParam:p})=>t.listLogsVNext({pagination:{page:p,perPage:evs},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:nvs,select:rvs,retry:!1,refetchInterval:svs}),{hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,data:c,isLoading:u,isError:d,error:f}=s;return g.useEffect(()=>{n&&a&&!i&&l()},[n,a,i,l]),{data:c,hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,isLoading:u,isError:d,error:f,setEndOfListElement:r}},Xz={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},PVt=[{label:"Agent",entityType:Xz.AGENT},{label:"Workflow",entityType:Xz.WORKFLOW},{label:"Scorer",entityType:Xz.SCORER},{label:"Ingest",entityType:Xz.INGEST}],ivs=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],Yx="rootEntityType",Jb="datePreset",ex="dateFrom",tx="dateTo",ovs=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),_l={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"},BL=Object.keys(_l),qAe=new Set(["tags"]),VAe="mastra:logs:saved-filters";function lvs(e,t=VAe){const n=pvs(e),r=e.get(Jb);r&&n.set(Jb,r);const s=e.get(ex);s&&n.set(ex,s);const a=e.get(tx);a&&n.set(tx,a);try{localStorage.setItem(t,n.toString())}catch{}}function cvs(e=VAe){try{localStorage.removeItem(e)}catch{}}function Ket(e=VAe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function uvs(e){if(e.has(Jb)||e.has(ex)||e.has(tx)||e.has(Yx))return!0;for(const t of BL)if(e.has(_l[t]))return!0;return!1}function dvs({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:PVt.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:ivs.map(u=>({label:u.label,value:u.value})),placeholder:"Choose level",emptyText:"No levels."},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"traceId",label:"Trace ID",kind:"text"},{id:"spanId",label:"Span ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"threadId",label:"Thread ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function fvs(e){const t=[],n=new Map([[Yx,"rootEntityType"]]);for(const s of BL)n.set(_l[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),qAe.has(a)){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function pvs(e){const t=new URLSearchParams,n=e.get(Yx);n&&t.set(Yx,n);for(const r of BL){const s=_l[r];if(qAe.has(r)){for(const i of e.getAll(s))t.append(s,i);continue}const a=e.get(s);a&&t.set(s,a)}return t}function hvs(e,t){e.delete(Yx);for(const n of BL)e.delete(_l[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(Yx,n.value);continue}const r=_l[n.fieldId];if(r){if(qAe.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 mvs({rootEntityType:e,dateFrom:t,dateTo:n,tokens:r}){const s={};e&&(s.rootEntityType=e),(t||n)&&(s.timestamp={...t?{start:t}:{},...n?{end:n}:{}});for(const a of r){if(a.fieldId==="tags"){Array.isArray(a.value)&&a.value.length>0?s.tags=a.value:typeof a.value=="string"&&a.value.trim()&&(s.tags=[a.value.trim()]);continue}if(a.fieldId==="level"){typeof a.value=="string"&&a.value.trim()&&a.value!=="Any"&&(s.level=a.value);continue}if(typeof a.value=="string"&&a.value.trim()&&a.value!=="Any")switch(a.fieldId){case"entityName":s.rootEntityName=a.value;break;case"traceId":s.traceId=a.value;break;case"spanId":s.spanId=a.value;break;case"runId":s.runId=a.value;break;case"threadId":s.threadId=a.value;break;case"sessionId":s.sessionId=a.value;break;case"requestId":s.requestId=a.value;break;case"resourceId":s.resourceId=a.value;break;case"userId":s.userId=a.value;break;case"organizationId":s.organizationId=a.value;break;case"serviceName":s.serviceName=a.value;break;case"environment":s.environment=a.value;break;case"experimentId":s.experimentId=a.value;break}}return s}function gvs(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 vvs="Filters setting for Logs saved",yvs="Filters setting for Logs cleared up";function bvs(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=g.useState(()=>Ket(r)!==null),c=g.useCallback(()=>{lvs(e,r),l(!0);const f=s?.saved??vvs;f!==!1&&Be.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{cvs(r),l(!1);const f=s?.cleared??yvs;f!==!1&&Be.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(a||d.current||(d.current=!0,uvs(e)))return;const f=Ket(r);f&&t(p=>{const h=new URLSearchParams(p);for(const[m,v]of f)h.append(m,v);return h},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function xvs(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 wvs(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,xvs(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function Svs(e,t,n,r){const s=g.useMemo(()=>wvs(e),[e]),a=g.useMemo(()=>{const h=new Map;for(const[m,v]of e.entries()){const y=s.get(v);y&&h.set(y,{log:v,idx:m})}return h},[e,s]),l=(t?a.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=g.useCallback(h=>s.get(h),[s]),d=g.useCallback(h=>{const m=s.get(h);if(m){if(t===m){n({logId:null});return}n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}},[s,t,r,n]),f=l>0?()=>{const h=e[l-1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0,p=l>=0&&l<e.length-1?()=>{const h=e[l+1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0;return{logIdMap:s,getLogId:u,featuredLog:c,handleLogClick:d,handlePreviousLog:f,handleNextLog:p}}const Bxe="logId",Uxe="traceId",qxe="spanId",kP=1440*60*1e3,kvs={"last-24h":kP,"last-3d":3*kP,"last-7d":7*kP,"last-14d":14*kP,"last-30d":30*kP};function Jz(e){e.delete(Bxe),e.delete(Uxe),e.delete(qxe)}function Ovs(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const _=e.get(Jb);return _&&ovs.has(_)?_:"last-24h"},[e]),a=e.get(ex),i=e.get(tx),l=g.useMemo(()=>{if(s==="custom"){if(!a)return;const C=new Date(a);return Number.isNaN(C.getTime())?void 0:C}if(s==="all")return;const _=kvs[s];return _?new Date(Date.now()-_):void 0},[s,a]),c=g.useMemo(()=>{if(s!=="custom"||!i)return;const _=new Date(i);return Number.isNaN(_.getTime())?void 0:_},[s,i]),u=g.useRef(s);u.current=s;const d=e.get(Bxe),f=e.get(Uxe),p=e.get(qxe),h=g.useMemo(()=>PVt.find(_=>_.entityType===e.get(Yx)),[e]),m=g.useMemo(()=>fvs(e),[e]),v=g.useCallback(_=>{t(C=>{const T=new URLSearchParams(C);for(const[E,N]of Object.entries(_)){const I=E==="logId"?Bxe:E==="traceId"?Uxe:qxe;N?T.set(I,N):T.delete(I)}return T},{replace:!0})},[t]),y=g.useCallback(_=>{t(C=>{const T=new URLSearchParams(C);return hvs(T,_),Jz(T),T},{replace:!0})},[t]),b=y,x=g.useCallback((_,C)=>{if(u.current!=="custom")return;const T=C==="from"?ex:tx;t(E=>{const N=new URLSearchParams(E);return _?N.set(T,_.toISOString()):N.delete(T),Jz(N),N},{replace:!0})},[t]),S=g.useCallback(_=>{u.current=_,t(C=>{const T=new URLSearchParams(C);return _==="last-24h"?(T.delete(Jb),T.delete(ex),T.delete(tx)):_==="custom"?T.set(Jb,"custom"):(T.set(Jb,_),T.delete(ex),T.delete(tx)),Jz(T),T},{replace:!0})},[t]),k=g.useCallback(()=>{t(_=>{const C=new URLSearchParams(_);C.delete(Yx);for(const T of BL)C.delete(_l[T]);return C.delete(Jb),C.delete(ex),C.delete(tx),Jz(C),C},{replace:!0}),r?.()},[t,r]);return g.useMemo(()=>({searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,featuredLogId:d,featuredTraceId:f,featuredSpanId:p,selectedEntityOption:h,filterTokens:m,handleFeaturedChange:v,handleFilterTokensChange:b,handleDateChange:x,handleDatePresetChange:S,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,p,h,m,v,b,x,S,k,y])}const Eb=Li.KeyValueList;function _vs({spanId:e,span:t,isLoading:n,onClose:r}){const s=OQ(t?.startedAt,t?.endedAt),a=iV(t?.startedAt),i=iV(t?.endedAt);return o.jsxs(Li,{children:[o.jsxs(Li.Header,{children:[o.jsxs(Li.Heading,{children:["Span ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Li.CloseButton,{onClick:r})]}),n?o.jsx(Li.LoadingData,{children:"Loading span..."}):t?o.jsxs(Li.Content,{children:[o.jsxs(Eb,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(Eb.Key,{children:"Type"}),o.jsx(Eb.Value,{children:t.spanType})]}),a&&o.jsxs(o.Fragment,{children:[o.jsx(Eb.Key,{children:"Started"}),o.jsx(Eb.Value,{children:a})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(Eb.Key,{children:"Ended"}),o.jsx(Eb.Value,{children:i})]}),s&&o.jsxs(o.Fragment,{children:[o.jsx(Eb.Key,{children:"Duration"}),o.jsx(Eb.Value,{children:s})]})]}),o.jsx("br",{}),o.jsx(Li.CodeSection,{title:"Input",icon:o.jsx(xx,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(Li.CodeSection,{title:"Output",icon:o.jsx(em,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(Li.CodeSection,{title:"Metadata",icon:o.jsx(Jl,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(Li.CodeSection,{title:"Attributes",icon:o.jsx(Jl,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(Li.NoData,{children:"Span not found."})]})}function Cvs({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:a}){const i=g.useMemo(()=>dAe(t??[]),[t]),[l,c]=g.useState([]);g.useEffect(()=>{i.length>0&&c(fAe(i))},[i]);const u=d=>{s?.(a===d?void 0:d)};return o.jsxs(Li,{children:[o.jsxs(Li.Header,{children:[o.jsxs(Li.Heading,{children:["Trace ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Li.CloseButton,{onClick:r})]}),n?o.jsx(Li.LoadingData,{children:"Loading trace..."}):i.length===0?o.jsx(Li.NoData,{children:"No spans found for this trace."}):o.jsx(Li.Content,{children:o.jsx(sqt,{hierarchicalSpans:i,onSpanClick:u,selectedSpanId:a??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}function Evs(){const[e,t]=hi(),n=Ovs(e,t),r=bvs(e,t),[s,a]=g.useState(),[i,l]=g.useState(!1),{data:c=[],isPending:u}=RAe(),{data:d=[],isPending:f}=NAe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:p=[],isPending:h}=IAe(),{data:m=[],isPending:v}=AAe(),y=g.useMemo(()=>dvs({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:p,loading:{tags:u,entityNames:f,serviceNames:v,environments:h}}),[c,d,m,p,u,f,v,h]),b=g.useMemo(()=>mvs({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:x=[],isLoading:S,error:k,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:T}=avs({filters:b}),{logIdMap:E,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:R}=Svs(x,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:L,isLoading:D}=YUt(n.featuredTraceId??null),{data:F,isLoading:H}=_Q(n.featuredTraceId??"",n.featuredSpanId??""),B=g.useCallback(()=>n.applyFilterTokens(gvs(y,n.filterTokens)),[y,n]),z=g.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),V=g.useCallback(Y=>n.handleFeaturedChange({traceId:Y,spanId:null}),[n]),M=g.useCallback((Y,ne)=>n.handleFeaturedChange({traceId:Y,spanId:ne}),[n]),G=g.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),U=g.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),$=g.useCallback(Y=>n.handleFeaturedChange({spanId:Y??null}),[n]),q=o.jsxs(Vt.TopArea,{children:[o.jsx(Vt.Row,{children:o.jsxs(Vt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(I4,{preset:n.datePreset,onPresetChange:n.handleDatePresetChange,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,onDateChange:n.handleDateChange,disabled:S,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),o.jsx(EAe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:S,onStartTextFilter:a})]})}),o.jsx(Qgs,{isLoading:S,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:B,onRemoveAll:n.handleRemoveAll,onSave:r.handleSave,onRemoveSaved:r.hasSavedFilters?r.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(k)return o.jsxs(Vt,{width:"wide",height:"full",children:[q,o.jsx(Vt.MainArea,{isCentered:!0,children:o.jsx(Lgs,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const Z=!!n.selectedEntityOption||n.filterTokens.length>0;return x.length===0&&!S&&!Z?o.jsxs(Vt,{width:"wide",height:"full",children:[q,o.jsx(Vt.MainArea,{isCentered:!0,children:o.jsx(Jgs,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Vt,{width:"wide",height:"full",children:[q,o.jsx(Fgs,{logCollapsed:i,listSlot:o.jsx(Ggs,{logs:x,isLoading:S,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:T,logIdMap:E,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(Dgs,{log:N,onClose:z,onTraceClick:V,onSpanClick:M,onPrevious:A,onNext:R,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(Cvs,{traceId:n.featuredTraceId,spans:L?.spans,isLoading:D,onClose:G,onSpanSelect:$,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(_vs,{spanId:n.featuredSpanId,span:F?.span,isLoading:H,onClose:U}):null})]})}function Tvs({server:e,rowProps:t}){const{paths:n,Link:r}=cn(),a=Qe().options.baseUrl,i=a?`${a}/api/mcp/${e.id}/sse`:"",{data:l}=X7t(e),c=Object.values(l||{}),u=c.length,d=c.filter(h=>h.toolType==="agent").length,f=c.filter(h=>h.toolType==="workflow").length,p=Xh(e.name,50);return o.jsxs(be.RowLink,{to:n.mcpServerLink(e.id),LinkComponent:r,...t,children:[o.jsx(be.NameCell,{children:p}),o.jsx(be.DescriptionCell,{children:i}),o.jsx(be.TextCell,{className:"text-center",children:d||""}),o.jsx(be.TextCell,{className:"text-center",children:u||""}),o.jsx(be.TextCell,{className:"text-center",children:f||""})]})}function jvs({mcpServers:e,isLoading:t,search:n=""}){const r=g.useMemo(()=>{const i=n.toLowerCase();return e.filter(l=>l.name?.toLowerCase().includes(i)||l.id?.toLowerCase().includes(i))},[e,n]),{containerRef:s,getRowProps:a}=wo({count:r.length});return t?o.jsx(Pl,{columns:"auto 1fr auto auto auto"}):o.jsxs(be,{columns:"auto 1fr auto auto auto",variant:"striped",scrollRef:s,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"Name"}),o.jsx(be.TopCell,{children:"URL"}),o.jsx(be.TopCellSmart,{long:"Agents",short:o.jsx(Ti,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(be.TopCellSmart,{long:"Tools",short:o.jsx(Ff,{}),tooltip:"Tools",className:"text-center"}),o.jsx(be.TopCellSmart,{long:"Workflows",short:o.jsx(Uc,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(be.NoMatch,{message:"No MCP Servers match your search"}):null,r.map((i,l)=>o.jsx(Tvs,{server:i,rowProps:a(l)},i.id))]})}const Nvs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Er,{iconSlot:o.jsx(Mc,{}),titleSlot:"No MCP Servers yet",descriptionSlot:o.jsxs(o.Fragment,{children:["MCP servers are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsxs(oe,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(Yr,{})]})})}),Ivs=()=>{const{data:e=[],isLoading:t,error:n}=mQ(),[r,s]=g.useState("");return n&&Ss(n)?o.jsx(ir,{children:o.jsx(Gs,{})}):n&&ks(n)?o.jsx(ir,{children:o.jsx(Fs,{resource:"MCP servers"})}):n?o.jsx(ir,{children:o.jsx(Ui,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(ir,{children:o.jsx(Nvs,{})}):o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx(ah,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(jvs,{mcpServers:e,isLoading:t,search:r})]})},Avs=(e,t)=>{const n=new Map,r=Object.keys(t);for(const s of r){const a=t[s],i=a.tools,l=Object.keys(i);for(const c of l){const u=i[c];n.has(u.id)||n.set(u.id,{...u,agents:[]}),n.get(u.id).agents.push({...a,id:s})}}for(const[s,a]of Object.entries(e))n.has(a.id)||n.set(a.id,{...a,agents:[]});return Array.from(n.values())};function Rvs({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=cn(),i=g.useMemo(()=>Avs(e,t),[e,t]),l=g.useMemo(()=>i.filter(d=>d.id.toLowerCase().includes(r.toLowerCase())),[i,r]),{containerRef:c,getRowProps:u}=wo({count:l.length});return n?o.jsx(Pl,{columns:"auto 1fr auto"}):o.jsxs(be,{columns:"auto 1fr auto",variant:"striped",scrollRef:c,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"Name"}),o.jsx(be.TopCell,{children:"Description"}),o.jsx(be.TopCellSmart,{long:"Agents",short:o.jsx(Ti,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(be.NoMatch,{message:"No Tools match your search"}):null,l.map((d,f)=>{const p=Xh(d.id,50),h=Xh(d.description??"",200),m=d.agents.length;return o.jsxs(be.RowLink,{to:s.toolLink(d.id),LinkComponent:a,...u(f),children:[o.jsx(be.NameCell,{children:p}),o.jsx(be.DescriptionCell,{children:h}),o.jsx(be.TextCell,{className:"text-center",children:m||""})]},d.id)})]})}const Pvs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Er,{iconSlot:o.jsx(Mc,{}),titleSlot:"No Tools yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Mastra tools are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsxs(oe,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(Yr,{})]})})}),$vs=()=>{const e=Qe();return An({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new A_;Object.entries(r??{}).forEach(([a,i])=>{s.set(a,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(a){throw Be.error("Error executing dev tool"),console.error("Error executing dev tool:",a),a}}})},Mvs=({toolId:e})=>{const{canExecute:t}=_o(),n=t("tools"),{data:r={}}=Dm(),s=g.useMemo(()=>{for(const v of Object.values(r))if(v.tools){const y=Object.values(v.tools).find(b=>b.id===e);if(y)return y}return null},[r,e]),{data:a,isLoading:i,error:l}=IIr(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=$vs(),{requestContext:p}=vs();g.useEffect(()=>{if(l){const v=l instanceof Error?l.message:"Failed to load tool";Be.error(`Error loading tool: ${v}`)}},[l]);const h=async(v,y)=>{if(!c)return;const b={...p??{},...y??{}};return u({toolId:c.id,input:v,requestContext:b})},m=c?.inputSchema?vm(Tx(c?.inputSchema)):xs({});return i?o.jsxs("div",{className:"p-6",children:[o.jsx(jt,{className:"mb-4 h-8 w-48"}),o.jsx(jt,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(BIe,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:h,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(me,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(me,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function Dvs({value:e,onValueChange:t,placeholder:n="Select a tool...",searchPlaceholder:r="Search tools...",emptyText:s="No tools found.",className:a,disabled:i=!1,variant:l}){const{data:c={},isLoading:u,isError:d,error:f}=GI(),{data:p={},isLoading:h,isError:m,error:v}=Dm(),{navigate:y,paths:b}=cn();g.useEffect(()=>{if(d){const _=f instanceof Error?f.message:"Failed to load tools";Be.error(`Error loading tools: ${_}`)}},[d,f]),g.useEffect(()=>{if(m){const _=v instanceof Error?v.message:"Failed to load agents";Be.error(`Error loading agents: ${_}`)}},[m,v]);const x=new Map;Object.values(p).forEach(_=>{_.tools&&Object.values(_.tools).forEach(C=>{x.has(C.id)||x.set(C.id,C)})}),Object.values(c).forEach(_=>{x.has(_.id)||x.set(_.id,_)});const S=Array.from(x.values()).map(_=>({label:_.id,value:_.id})),k=_=>{t?t(_):_&&_!==e&&y(b.toolLink(_))};return o.jsx(ml,{options:S,value:e,onValueChange:k,placeholder:u||h?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||u||h||d||m,variant:l})}const Lvs=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=g.useState({sseUrl:"",httpStreamUrl:""});if(g.useEffect(()=>{if(!t)return;const i=window.MASTRA_SERVER_HOST,l=window.MASTRA_SERVER_PORT;let c=null;i&&l&&(c=`http://${i}:${l}`);const u=c||"http://localhost:4111",d=`${u}/api/mcp/${t.id}/sse`,f=`${u}/api/mcp/${t.id}/mcp`;s({sseUrl:d,httpStreamUrl:f})},[t]),e)return null;if(!t)return o.jsx(Hx,{children:o.jsx(me,{as:"h1",variant:"header-md",className:"text-neutral3 py-20 text-center font-medium",children:"Server not found"})});const a=`npx -y mcp-remote ${n}`;return o.jsxs(Hx,{isDivided:!0,children:[o.jsxs("div",{className:"mx-auto w-full max-w-2xl px-8 py-12",children:[o.jsx(me,{as:"h1",variant:"header-md",className:"text-neutral6 pb-4 font-medium",children:t.name}),o.jsxs("div",{className:"flex items-center gap-1 pb-6",children:[o.jsx(St,{icon:o.jsx(tqt,{}),size:"sm",children:"Version"}),o.jsx(St,{size:"sm",children:t.version_detail.version})]}),o.jsx(me,{className:"text-neutral3 pb-4",children:"This MCP server can be accessed through multiple transport methods. Choose the one that best fits your use case."}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(St,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"HTTP"}),children:"Regular HTTP Endpoint"}),o.jsx(me,{className:"text-neutral3 pt-1 pb-2",children:"Use for stateless HTTP transport with streamable responses."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(me,{className:"bg-surface4 rounded-lg px-2 py-1",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx(ka,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(St,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"SSE"}),children:"Server-Sent Events"}),o.jsx(me,{className:"text-neutral3 pt-1 pb-2",children:"Use for real-time communication via SSE."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(me,{className:"bg-surface4 rounded-lg px-2 py-1",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx(ka,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(St,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"CLI"}),children:"Command Line"}),o.jsx(me,{className:"text-neutral3 pt-1 pb-2",children:"Use for local command-line access via npx and mcp-remote."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(me,{className:"bg-surface4 rounded-lg px-2 py-1",children:a}),o.jsx("div",{className:"pt-1",children:o.jsx(ka,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"border-border1 h-full overflow-y-scroll border-l",children:o.jsx(Fvs,{server:t})})]})},Fvs=({server:e})=>{const{data:t={},isLoading:n}=X7t(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(He,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(OC,{})}),o.jsx(me,{variant:"header-md",as:"h2",className:"font-medium",children:"Available Tools"})]}),o.jsx("div",{className:"flex flex-col gap-2 pt-6",children:r.map(s=>{const a=t[s];return o.jsx(Bvs,{tool:a,serverId:e.id},s)})})]})};function zvs(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 Bvs=({tool:e,serverId:t})=>{const n=g.useRef(null),{Link:r,paths:s}=cn(),a=iBt[e.toolType||"tool"],i=zvs(e._meta);return o.jsxs(Vf,{onClick:()=>n.current?.click(),children:[o.jsx(MDt,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Wf,{children:[o.jsx(Hf,{children:o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(r,{ref:n,href:s.mcpServerToolLink(t,e.id),children:e.id}),i&&o.jsx(St,{size:"xs",children:"App"})]})}),o.jsx(ih,{children:e.description})]})]})},Uvs=()=>{const{serverId:e}=mr(),{data:t=[],isLoading:n}=mQ(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(Lvs,{isLoading:n,server:r})})};function qvs(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 Vvs=({toolId:e,serverId:t})=>{const{canExecute:n}=_o(),r=n("tools"),s=Qe(),{data:a,isLoading:i,error:l}=FIe(t,e),{mutateAsync:c,isPending:u,data:d}=bns(t,e),f=a?qvs(a._meta):void 0,{data:p}=yt({queryKey:["mcp-app-resource",t,f],queryFn:async()=>f?(await s.readMcpServerResource(t,f)).contents[0]?.text??null:null,enabled:!!f}),h=g.useCallback(async(y,b)=>await c(b),[c]);g.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";Be.error(`Error loading tool: ${y}`)}},[l]);const m=async y=>{if(a)return await c(y)};if(i)return o.jsxs("div",{className:"p-6",children:[o.jsx(jt,{className:"mb-4 h-8 w-48"}),o.jsx(jt,{className:"h-32 w-full"})]});if(l)return null;if(!a)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(me,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(me,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let v;try{v=vm(a.inputSchema)}catch(y){console.error("Error processing input schema:",y),Be.error("Failed to process tool input schema."),v=xs({})}return o.jsxs("div",{className:"flex flex-col gap-4",children:[p&&o.jsx("div",{className:"border-border1 border-b p-4",children:o.jsx(K7t,{html:p,toolName:a.name??a.id,onToolCall:h})}),o.jsx(BIe,{executionResult:d,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},Hvs=()=>{const{serverId:e,toolId:t}=mr(),{data:n,isLoading:r}=FIe(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(Vvs,{toolId:t,serverId:e})})},$Vt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],HN="rootEntityType",WN={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"},VQ=Object.keys(WN),HAe="mastra:metrics:saved-filters";function Wvs(e){const t=Kvs(e);try{localStorage.setItem(HAe,t.toString())}catch{}}function Zvs(){try{localStorage.removeItem(HAe)}catch{}}function MVt(){try{const e=localStorage.getItem(HAe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function Gvs(e){if(e.has(HN))return!0;for(const t of VQ)if(e.has(WN[t]))return!0;return!1}function Qvs({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:$Vt.map(u=>({label:u.label,value:u.entityType})),placeholder:"Choose entity type",emptyText:"No entity types."},{id:"entityName",label:"Primitive Name",kind:"pick-multi",options:t.map(u=>({label:u,value:u})),placeholder:"Choose entity names",emptyText:"No entity names found.",isLoading:s?.entityNames},{id:"entityId",label:"Primitive ID",kind:"text"},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"threadId",label:"Thread ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function Yvs(e){const t=[],n=new Map([[HN,"rootEntityType"]]);for(const s of VQ)n.set(WN[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),a==="tags"){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}if(a==="rootEntityType"||a==="entityName"||a==="serviceName"||a==="environment"||a==="provider"||a==="model"){const l=e.getAll(s);if(l.length>1){t.push({fieldId:a,value:l});continue}}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function Kvs(e){const t=new URLSearchParams,n=e.getAll(HN);for(const r of n)t.append(HN,r);for(const r of VQ){const s=WN[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function Xvs(e,t){e.delete(HN);for(const n of VQ)e.delete(WN[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?HN:WN[n.fieldId];if(r)if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string"&&a!=="");if(s.length===0){n.fieldId==="tags"&&e.append(r,"");continue}for(const a of s)e.append(r,a)}else typeof n.value=="string"&&e.set(r,n.value.trim())}}const Jvs="Any";function Xet(e){const t=e.trim();return t===""||t===Jvs}const eys=new Set($Vt.map(e=>e.entityType));function Jet(e){const t=e.trim();return eys.has(t)?t:void 0}function tys(e){const t={};for(const n of e){const r=n.fieldId;if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string").map(a=>a.trim()).filter(a=>!Xet(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?Jet(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(Xet(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=Jet(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const DVt=[{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"}],nys=new Set(DVt.map(e=>e.value));function rys(e){return typeof e=="string"&&(nys.has(e)||e==="custom")}const LVt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function HQ(){return g.useContext(LVt)}function sys(e,t){return e!=="custom"?DVt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${hr(t.from,"MMM d, yyyy")} – ${hr(t.to,"MMM d, yyyy")}`:hr(t.from,"MMM d, yyyy"):"Custom range"}function ays({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:a,onCustomRangeChange:i,tracesBasePath:l,logsBasePath:c}){const u=g.useMemo(()=>JSON.stringify(n),[n]),d=g.useMemo(()=>n,[u]),f=g.useMemo(()=>tys(d),[d]),p=g.useMemo(()=>JSON.stringify(f),[f]),h=sys(t,a),m=g.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:a,setCustomRange:i??(()=>{}),dateRangeLabel:h,filterTokens:d,setFilterTokens:s,dimensionalFilter:f,dimensionalFilterKey:p,tracesBasePath:l,logsBasePath:c}),[t,r,a,i,h,d,s,f,p,l,c]);return o.jsx(LVt.Provider,{value:m,children:e})}const iys=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function oys(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 lys(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 cys(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=HQ(),s=g.useRef(e);s.current=e;const a=g.useRef(n);return a.current=n,o.jsx(I4,{preset:oys(e),onPresetChange:i=>{const l=lys(i);s.current=l,t(l)},dateFrom:n?.from,dateTo:n?.to,onDateChange:(i,l)=>{if(s.current!=="custom")return;const c={...a.current,[l]:i};a.current=c,r(c)},presets:iys})}const Vxe=1440*60*1e3,uys={"24h":Vxe,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function dys(e,t,n){if(e!=="custom"){const r=uys[e]??Vxe;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-Vxe),end:t?.to??new Date(n)}}function Bm(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=HQ(),s=g.useRef(null),a=e==="custom"?`custom:${t?.from?.getTime()??""}:${t?.to?.getTime()??""}`:`preset:${e}`;(!s.current||s.current.key!==a)&&(s.current={key:a,anchor:Date.now()});const i=s.current.anchor,l=g.useMemo(()=>dys(e,t,i),[e,t,i]),c=g.useMemo(()=>({timestamp:l,...n}),[l,r]),u=g.useMemo(()=>`${a}|${r}`,[a,r]);return{datePreset:e,customRange:t,timestamp:l,filters:c,dimensionalFilter:n,filterKey:u}}function FVt(){const e=Qe(),{filters:t,filterKey:n}=Bm();return yt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function UL({href:e,LinkComponent:t="a"}){return o.jsx(oe,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(ec,{})})}function fys({href:e,LinkComponent:t="a"}){return o.jsx(oe,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(GKt,{})})}function pys(e){return e==="agents"||e==="workflows"||e==="tools"}function ett(e,t){if(e.length===0)return"0";const n=e.reduce((r,s)=>{const a=s[t];return r+(typeof a=="number"&&Number.isFinite(a)?a:0)},0);return`${Math.round(n/e.length)}`}function hys(e){const t=e;return typeof t?.tsMs=="number"&&Number.isFinite(t.tsMs)}const mys=[{dataKey:"p50",label:"p50",color:Hp.blue,aggregate:e=>({value:ett(e,"p50"),suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:Hp.yellow,aggregate:e=>({value:ett(e,"p95"),suffix:"avg ms"})}];function Pie({data:e,onPointClick:t}){return e.length===0?o.jsx(Bt.NoData,{message:"No latency data yet"}):o.jsx(OD,{data:e,series:mys,onPointClick:t?n=>hys(n)?t(n):void 0:void 0})}function gys({data:e,isLoading:t,isError:n,onPointClick:r,actions:s}){const a=(e?.agentData.length??0)>0,i=(e?.workflowData.length??0)>0,l=(e?.toolData.length??0)>0,c={agents:a,workflows:i,tools:l},u=a?"agents":i?"workflows":l?"tools":"agents",[d,f]=g.useState("agents"),p=c[d]?d:u,h=typeof s=="function"?s(p):s,m=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),v=e?Object.values(e).filter(Array.isArray).flat().map(b=>b.p50).filter(b=>typeof b=="number"):[],y=v.length>0?`${Math.round(v.reduce((b,x)=>b+x,0)/v.length)}ms`:"—";return o.jsxs(Bt,{children:[o.jsxs(Bt.TopBar,{children:[o.jsx(Bt.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(Bt.Summary,{value:y,label:"Avg p50"}),h?o.jsx(Bt.Actions,{children:h}):null]}),t?o.jsx(Bt.Loading,{}):n?o.jsx(Bt.Error,{message:"Failed to load latency data"}):o.jsx(Bt.Content,{children:m?o.jsxs(yc,{value:p,onValueChange:b=>{pys(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(vc,{children:[o.jsx(Ar,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(Ar,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(Ar,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(fs,{value:"agents",children:o.jsx(Pie,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(fs,{value:"workflows",children:o.jsx(Pie,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(fs,{value:"tools",children:o.jsx(Pie,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Bt.NoData,{message:"No latency data yet"})})]})}function vys(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 yys(e,t){if(t==="1h"){const s=new Date(e);s.setUTCMinutes(0,0,0);const a=new Date(s.getTime()+3600*1e3);return{from:s,to:a}}const n=new Date(e);n.setUTCHours(0,0,0,0);const r=new Date(n.getTime()+1440*60*1e3);return{from:n,to:r}}function zVt(e,t,n,r,s,a,i){if(i){e.set(t,"custom"),e.set(n,i.from.toISOString()),e.set(r,i.to.toISOString());return}if(s==="custom"){e.set(t,"custom"),a?.from&&e.set(n,a.from.toISOString()),a?.to&&e.set(r,a.to.toISOString());return}const l=vys(s);l&&e.set(t,l)}function Ro(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function BVt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function ttt({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const a=new URLSearchParams;a.set(Mw,"branches"),zVt(a,Dw,Lw,Fw,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Gx,i),r.status&&a.set(Qx,r.status),Ro(a,Ol.entityName,r.entityName??n.entityName),Ro(a,Ol.threadId,r.threadId??n.threadId),Ro(a,Ol.resourceId,r.resourceId??n.resourceId),Ro(a,Ol.entityId,n.entityId),Ro(a,Ol.runId,n.runId),Ro(a,Ol.sessionId,n.sessionId),Ro(a,Ol.requestId,n.requestId),Ro(a,Ol.userId,n.userId),Ro(a,Ol.organizationId,n.organizationId),Ro(a,Ol.experimentId,n.experimentId),Ro(a,Ol.serviceName,n.serviceName),Ro(a,Ol.environment,n.environment),BVt(a,Ol.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function bys({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;zVt(a,Jb,ex,tx,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Yx,i),Ro(a,_l.entityName,r.entityName??n.entityName),Ro(a,_l.threadId,r.threadId??n.threadId),Ro(a,_l.resourceId,r.resourceId??n.resourceId),Ro(a,_l.runId,n.runId),Ro(a,_l.sessionId,n.sessionId),Ro(a,_l.requestId,n.requestId),Ro(a,_l.userId,n.userId),Ro(a,_l.organizationId,n.organizationId),Ro(a,_l.experimentId,n.experimentId),Ro(a,_l.serviceName,n.serviceName),Ro(a,_l.environment,n.environment),BVt(a,_l.tags,n.tags),r.status==="error"&&a.append(_l.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function fA(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=HQ(),a=g.useCallback((c={})=>ttt({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=g.useCallback((c={})=>bys({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=yys(u,d);return ttt({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const UVt="1h";async function $ie(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:UVt,filters:n}),s=r.series.find(l=>l.percentile===.5),a=r.series.find(l=>l.percentile===.95);if(!s||!a)return[];const i=new Map(a.points.map(l=>[new Date(l.timestamp).getTime(),l.value]));return s.points.map(l=>{const c=new Date(l.timestamp),u=c.getTime();return{time:c.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}),tsMs:u,p50:Math.round(l.value),p95:Math.round(i.get(u)??0)}})}function xys(){const e=Qe(),{filters:t,filterKey:n}=Bm();return yt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([$ie(e,"mastra_agent_duration_ms",t),$ie(e,"mastra_workflow_duration_ms",t),$ie(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:UVt}}})}const ntt={agents:Ku.AGENT,workflows:Ku.WORKFLOW_RUN,tools:Ku.TOOL};function wys(){const{data:e,isLoading:t,isError:n}=xys(),{getTracesHref:r,getBucketTracesHref:s}=fA(),{Link:a}=cn(),i=es();return o.jsx(gys,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:ntt[l]},c.tsMs,"1h"))},actions:l=>o.jsx(UL,{href:r({rootEntityType:ntt[l]}),LinkComponent:a})})}function Sys(e){return e==="threads"||e==="resources"}function Mie(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function kys({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("threads"),c=e.data?.map(y=>({...y,key:y.threadId}))??[],u=t.data?.map(y=>({...y,key:y.resourceId}))??[],d=c.length>0,f=u.length>0,p=e.data?.reduce((y,b)=>y+b.runs,0)??0,h=t.data?.reduce((y,b)=>y+b.threadCount,0)??0,m=i==="threads"?e:t,v=typeof s=="function"?s(i):s;return o.jsxs(Bt,{children:[o.jsxs(Bt.TopBar,{children:[o.jsx(Bt.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&o.jsx(Bt.Summary,{value:p.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&o.jsx(Bt.Summary,{value:h.toLocaleString(),label:"Total threads"}),v?o.jsx(Bt.Actions,{children:v}):null]}),m.isLoading?o.jsx(Bt.Loading,{}):m.isError?o.jsx(Bt.Error,{message:"Failed to load memory data"}):o.jsx(Bt.Content,{children:o.jsxs(yc,{defaultTab:"threads",value:i,onValueChange:y=>{Sys(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(vc,{children:[o.jsx(Ar,{value:"threads",children:"Threads"}),o.jsx(Ar,{value:"resources",children:"Resources"})]}),o.jsx(fs,{value:"threads",children:d?o.jsxs(be,{columns:"auto auto auto auto auto",...Rxe,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(be.RowHeaderCell,{className:"text-ui-sm",children:Mie(y.threadId)}),o.jsx(be.NumberCell,{children:y.resourceId?Mie(y.resourceId):"—"}),o.jsx(be.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(be.NumberCell,{children:y.tokens>0?nl(y.tokens):"—"}),o.jsx(be.NumberCell,{children:y.cost!=null?Vp(y.cost,y.costUnit):"—"})]});return b?o.jsx(be.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(be.RowStatic,{children:x},y.key)})]}):o.jsx(Bt.NoData,{message:"No thread activity yet"})}),o.jsx(fs,{value:"resources",children:f?o.jsxs(be,{columns:"auto auto auto auto",...Rxe,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(be.RowHeaderCell,{className:"text-ui-sm",children:Mie(y.resourceId)}),o.jsx(be.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(be.NumberCell,{children:y.tokens>0?nl(y.tokens):"—"}),o.jsx(be.NumberCell,{children:y.cost!=null?Vp(y.cost,y.costUnit):"—"})]});return b?o.jsx(be.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(be.RowStatic,{children:x},y.key)})]}):o.jsx(Bt.NoData,{message:"No resource activity yet"})})]})})]})}const Die=20;function Oys(){const e=Qe(),{filters:t,filterKey:n}=Bm();return yt({queryKey:["metrics","top-active-threads",n],queryFn:async()=>{const r={groupBy:["threadId","resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count",limit:Die}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:Die}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:Die})]),l=new Map,c=d=>dA(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.threadId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.threadId).map(d=>{const f=d.dimensions.threadId,p=l.get(f);return{threadId:f,resourceId:d.dimensions.resourceId??null,runs:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}const Lie=20;function _ys(){const e=Qe(),{filters:t,filterKey:n}=Bm();return yt({queryKey:["metrics","top-resources-by-threads",n],queryFn:async()=>{const r={groupBy:["resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",limit:Lie}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:Lie}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:Lie})]),l=new Map,c=d=>dA(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.resourceId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.resourceId).map(d=>{const f=d.dimensions.resourceId,p=l.get(f);return{resourceId:f,threadCount:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}function Cys(){const e=Oys(),t=_ys(),{getTracesHref:n}=fA(),{Link:r}=cn();return o.jsx(kys,{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 qL({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:a}){const i=t!=null;return o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:e}),o.jsx(Xr.Value,{className:i?void 0:"invisible",children:i?t:"—"}),a?o.jsx(Xr.Error,{}):s?o.jsx(Xr.Loading,{}):i?r!=null?o.jsx(Xr.Change,{changePct:r,prevValue:n}):o.jsx(Xr.NoChange,{}):o.jsx(Xr.NoData,{})]})}function Eys(){const e=Qe(),{filters:t,filterKey:n}=Bm();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 Tys(){const e=Qe(),{filters:t,filterKey:n}=Bm();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 jys(){const e=Qe(),{filters:t,filterKey:n}=Bm();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 Nys(){const e=Qe(),{filters:t,filterKey:n}=Bm();return yt({queryKey:["metrics","total-tokens-kpi",n],queryFn:async()=>{const[r,s]=await Promise.all([e.getMetricAggregate({name:["mastra_model_total_input_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"}),e.getMetricAggregate({name:["mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"})]),a=r.value!=null||s.value!=null,i=r.previousValue!=null||s.previousValue!=null,l=(r.value??0)+(s.value??0),c=(r.previousValue??0)+(s.previousValue??0),u=i&&c>0?(l-c)/c*100:null;return{value:a?l:null,previousValue:i?c:null,changePercent:u}}})}function Iys(){const{data:e,isLoading:t,isError:n}=FVt();return o.jsx(qL,{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 Ays(){const{data:e,isLoading:t,isError:n}=jys();return o.jsx(qL,{label:"Total Model Cost",value:e?.cost!=null?Vp(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?Vp(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function Rys(){const{data:e,isLoading:t,isError:n}=Nys();return o.jsx(qL,{label:"Total Tokens",value:e?.value!=null?nl(e.value):null,prevValue:e?.previousValue!=null?nl(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Pys(){const{data:e,isLoading:t,isError:n}=Tys();return o.jsx(qL,{label:"Total Threads",value:e?.value!=null?nl(e.value):null,prevValue:e?.previousValue!=null?nl(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function $ys(){const{data:e,isLoading:t,isError:n}=Eys();return o.jsx(qL,{label:"Total Resources",value:e?.value!=null?nl(e.value):null,prevValue:e?.previousValue!=null?nl(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Mys({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>Dys(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(CAe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(OAe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function Dys(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 Lys({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const i=!!e&&e.length>0;return o.jsxs(Bt,{children:[o.jsxs(Bt.TopBar,{children:[o.jsx(Bt.TitleAndDescription,{title:"Model Usage & Cost",description:"Token consumption by model."}),i&&(()=>{const l=e.reduce((d,f)=>d+(f.cost??0),0),c=new Set;for(const d of e)d.cost!=null&&d.costUnit&&c.add(d.costUnit);let u;return c.size===0?u=l>0?Vp(l):"—":c.size===1?u=l>0?Vp(l,[...c][0]):"—":u="Mixed",o.jsx(Bt.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(Bt.Actions,{children:s}):null]}),t?o.jsx(Bt.Loading,{}):n?o.jsx(Bt.Error,{message:"Failed to load model usage data"}):o.jsx(Bt.Content,{children:i?o.jsxs(be,{columns:"auto auto auto auto auto auto",...Rxe,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{sticky:"start",children:"Model"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(be.RowHeaderCell,{className:"text-ui-sm",children:l.model}),o.jsx(be.NumberCell,{children:l.input}),o.jsx(be.NumberCell,{children:l.output}),o.jsx(be.NumberCell,{children:l.cacheRead}),o.jsx(be.NumberCell,{children:l.cacheWrite}),o.jsx(be.NumberCell,{highlight:!0,children:l.cost!=null?Vp(l.cost,l.costUnit):"—"})]});return c?o.jsx(be.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(be.RowStatic,{children:u},l.model)})]}):o.jsx(Bt.NoData,{message:"No model usage data yet"})})]})}function Fys(){const e=Qe(),{filters:t,filterKey:n}=Bm();return yt({queryKey:["metrics","model-usage-cost",n],queryFn:async()=>{const[r,s,a,i]=await Promise.all(["mastra_model_total_input_tokens","mastra_model_total_output_tokens","mastra_model_input_cache_read_tokens","mastra_model_input_cache_write_tokens"].map(d=>e.getMetricBreakdown({name:[d],groupBy:["model"],aggregation:"sum",orderDirection:"DESC",filters:t})));if(!r||!s||!a||!i)return[];const l=new Map,c=d=>dA(l,d,()=>({input:0,output:0,cacheRead:0,cacheWrite:0,cost:null,costUnit:null})),u=(d,f)=>{f.estimatedCost!=null&&(d.cost=(d.cost??0)+f.estimatedCost,f.costUnit&&(d.costUnit=f.costUnit))};for(const d of r.groups){const f=d.dimensions.model??"unknown",p=c(f);p.input=d.value,u(p,d)}for(const d of s.groups){const f=d.dimensions.model??"unknown",p=c(f);p.output=d.value,u(p,d)}for(const d of a.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheRead=d.value}for(const d of i.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheWrite=d.value}return Array.from(l.entries()).map(([d,f])=>({model:d,input:nl(f.input),output:nl(f.output),cacheRead:nl(f.cacheRead),cacheWrite:nl(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function zys(){const{data:e,isLoading:t,isError:n}=Fys(),{getTracesHref:r}=fA(),{Link:s}=cn();return o.jsx(Lys,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:Ku.AGENT}),actions:o.jsx(UL,{href:r({rootEntityType:Ku.AGENT}),LinkComponent:s})})}function Bys(e){return e==="tokens"||e==="cost"}function Uys({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("tokens"),c=e??[],u=c.length>0,d=c.reduce((b,x)=>b+x.total,0),f=c.filter(b=>b.cost!=null&&b.cost>0),p=new Set(f.map(b=>b.costUnit??"usd")),h=p.size<=1,m=h?[...p][0]??"usd":null,v=h?f.reduce((b,x)=>b+(x.cost??0),0):0,y=h&&v>0;return o.jsxs(Bt,{children:[o.jsxs(Bt.TopBar,{children:[o.jsx(Bt.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&y?o.jsx(Bt.Summary,{value:Vp(v,m),label:"Total cost"}):o.jsx(Bt.Summary,{value:nl(d),label:"Total tokens"})),u&&s?o.jsx(Bt.Actions,{children:s}):null]}),t?o.jsx(Bt.Loading,{}):n?o.jsx(Bt.Error,{message:"Failed to load token usage data"}):o.jsx(Bt.Content,{children:u?o.jsxs(yc,{defaultTab:"tokens",value:i,onValueChange:b=>{Bys(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(vc,{children:[o.jsx(Ar,{value:"tokens",children:"Tokens"}),o.jsx(Ar,{value:"cost",children:"Cost"})]}),o.jsx(fs,{value:"tokens",children:o.jsx(VN,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:Hp.blueDark},{label:"Output",color:Hp.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:nl})}),o.jsx(fs,{value:"cost",children:y?o.jsx(VN,{LinkComponent:a,data:f.slice().sort((b,x)=>(x.cost??0)-(b.cost??0)).map(b=>({name:b.name,values:[b.cost],href:r?.(b)})),segments:[{label:"Cost",color:Hp.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>Vp(b,m)}):o.jsx(Bt.NoData,{message:"No cost data yet"})})]}):o.jsx(Bt.NoData,{message:"No token usage data yet"})})]})}function qys(){const e=Qe(),{filters:t,filterKey:n}=Bm();return yt({queryKey:["metrics","token-usage-by-agent",n],queryFn:async()=>{const r={groupBy:["entityName"],aggregation:"sum",orderDirection:"DESC",filters:t},[s,a]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"]}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"]})]),i=new Map,l=u=>dA(i,u,()=>({input:0,output:0,cost:null,costUnit:null})),c=(u,d)=>{d.estimatedCost!=null&&(u.cost=(u.cost??0)+d.estimatedCost,d.costUnit&&(u.costUnit=d.costUnit))};for(const u of s.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.input=u.value,c(f,u)}for(const u of a.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.output=u.value,c(f,u)}return Array.from(i.entries()).map(([u,d])=>({name:u,input:d.input,output:d.output,total:d.input+d.output,cost:d.cost,costUnit:d.costUnit})).sort((u,d)=>d.total-u.total)}})}function Vys(){const{data:e,isLoading:t,isError:n}=qys(),{getTracesHref:r}=fA(),{Link:s}=cn();return o.jsx(Uys,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:Ku.AGENT,entityName:a.name}),actions:o.jsx(UL,{href:r({rootEntityType:Ku.AGENT}),LinkComponent:s})})}function Hxe(e,t=nl){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const Hys=[{dataKey:"input",label:"Input tokens",color:Hp.blue,aggregate:Hxe("input")},{dataKey:"output",label:"Output tokens",color:Hp.yellow,aggregate:Hxe("output")}];function Wys(e){return e==="tokens"||e==="cost"}function Zys({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[a,i]=g.useState("tokens"),l=e??[],c=l.map(k=>({...k})),u=l.length>0,d=l.reduce((k,_)=>k+_.total,0),f=l.filter(k=>k.cost!=null&&k.cost>0),p=f.map(k=>({...k})),h=new Set(f.map(k=>k.costUnit).filter(k=>!!k)),m=h.size===1&&f.every(k=>k.costUnit!=null),v=m?[...h][0]??null:null,y=m?f.reduce((k,_)=>k+(_.cost??0),0):0,b=m&&y>0,x=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",S=[{dataKey:"cost",label:"Cost",color:Hp.purple,aggregate:Hxe("cost",k=>Vp(k,v))}];return o.jsxs(Bt,{children:[o.jsxs(Bt.TopBar,{children:[o.jsx(Bt.TitleAndDescription,{title:"Token usage over time",description:x}),u&&(a==="cost"&&b?o.jsx(Bt.Summary,{value:Vp(y,v),label:"Total cost"}):o.jsx(Bt.Summary,{value:nl(d),label:"Total tokens"})),u&&s?o.jsx(Bt.Actions,{children:s}):null]}),n?o.jsx(Bt.Loading,{}):r?o.jsx(Bt.Error,{message:"Failed to load token usage timeline"}):o.jsx(Bt.Content,{children:u?o.jsxs(yc,{defaultTab:"tokens",value:a,onValueChange:k=>{Wys(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(vc,{children:[o.jsx(Ar,{value:"tokens",children:"Tokens"}),o.jsx(Ar,{value:"cost",children:"Cost"})]}),o.jsx(fs,{value:"tokens",children:o.jsx(OD,{data:c,series:Hys})}),o.jsx(fs,{value:"cost",children:b?o.jsx(OD,{data:p,series:S}):o.jsx(Bt.NoData,{message:"No cost data yet"})})]}):o.jsx(Bt.NoData,{message:"No token usage data yet"})})]})}function Gys(e){return e==="24h"?"1h":"1d"}function Qys(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 rtt(e,t,n){for(const r of t?.points??[]){const s=new Date(r.timestamp).getTime();if(!Number.isFinite(s))continue;const a=e.get(s)??{tsMs:s,input:0,output:0,cost:null,costUnits:new Set,hasUnknownCostUnit:!1};a[n]+=r.value,r.estimatedCost!=null&&(a.cost=(a.cost??0)+r.estimatedCost,t?.costUnit?a.costUnits.add(t.costUnit):a.hasUnknownCostUnit=!0),e.set(s,a)}}function Yys(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function Kys(){const e=Qe(),{datePreset:t,filters:n,filterKey:r}=Bm(),s=Gys(t);return yt({queryKey:["metrics","token-usage-timeseries",r,s],queryFn:async()=>{const[a,i]=await Promise.all([e.getMetricTimeSeries({name:["mastra_model_total_input_tokens"],interval:s,aggregation:"sum",filters:n}),e.getMetricTimeSeries({name:["mastra_model_total_output_tokens"],interval:s,aggregation:"sum",filters:n})]),l=new Map;return rtt(l,a.series[0],"input"),rtt(l,i.series[0],"output"),{data:Array.from(l.values()).sort((u,d)=>u.tsMs-d.tsMs).map(u=>{const d=new Date(u.tsMs);return{time:Qys(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:Yys(u)}}),interval:s}}})}function Xys(){const{data:e,isLoading:t,isError:n}=Kys(),{getTracesHref:r}=fA(),{Link:s}=cn();return o.jsx(Zys,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(UL,{href:r(),LinkComponent:s})})}function Fie({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(VN,{LinkComponent:r,data:e.map(s=>{const a=n?.(s),i=t?.(s);return a?{name:s.name,values:[s.completed,s.errors],hrefs:[i,a]}:{name:s.name,values:[s.completed,s.errors],href:i}}),segments:[{label:"Completed",color:Hp.blueDark},{label:"Errors",color:Hp.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:nl})}function Jys({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:a,LinkComponent:i}){const[l,c]=g.useState("agents"),u=typeof a=="function"?a(l):a,d=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),f=e?[...e.agentData,...e.workflowData,...e.toolData].reduce((m,v)=>m+v.completed+v.errors,0):0,p=m=>r?v=>r(m,v):void 0,h=m=>s?v=>s(m,v):void 0;return o.jsxs(Bt,{children:[o.jsxs(Bt.TopBar,{children:[o.jsx(Bt.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(Bt.Summary,{value:nl(f),label:"Total runs"}),u?o.jsx(Bt.Actions,{children:u}):null]}),t?o.jsx(Bt.Loading,{}):n?o.jsx(Bt.Error,{message:"Failed to load trace volume data"}):o.jsx(Bt.Content,{children:d?o.jsxs(yc,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(vc,{children:[o.jsx(Ar,{value:"agents",children:"Agents"}),o.jsx(Ar,{value:"workflows",children:"Workflows"}),o.jsx(Ar,{value:"tools",children:"Tools"})]}),o.jsx(fs,{value:"agents",children:e.agentData.length>0?o.jsx(Fie,{data:e.agentData,rowHrefs:p("agents"),errorHrefs:h("agents"),LinkComponent:i}):o.jsx(Bt.NoData,{message:"No agent data yet"})}),o.jsx(fs,{value:"workflows",children:e.workflowData.length>0?o.jsx(Fie,{data:e.workflowData,rowHrefs:p("workflows"),errorHrefs:h("workflows"),LinkComponent:i}):o.jsx(Bt.NoData,{message:"No workflow data yet"})}),o.jsx(fs,{value:"tools",children:e.toolData.length>0?o.jsx(Fie,{data:e.toolData,rowHrefs:p("tools"),errorHrefs:h("tools"),LinkComponent:i}):o.jsx(Bt.NoData,{message:"No tool data yet"})})]}):o.jsx(Bt.NoData,{message:"No trace volume data yet"})})]})}async function zie(e,t,n){const r=await e.getMetricBreakdown({name:[t],groupBy:["entityName","status"],aggregation:"count",orderDirection:"DESC",filters:n}),s=new Map;for(const a of r.groups){const i=a.dimensions.entityName??"unknown",l=a.dimensions.status??"ok",c=dA(s,i,()=>({completed:0,errors:0}));l==="error"?c.errors+=a.value:c.completed+=a.value}return Array.from(s.entries()).map(([a,i])=>({name:a,...i})).sort((a,i)=>i.completed+i.errors-(a.completed+a.errors))}function ebs(){const e=Qe(),{filters:t,filterKey:n}=Bm();return yt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([zie(e,"mastra_agent_duration_ms",t),zie(e,"mastra_workflow_duration_ms",t),zie(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const e8={agents:Ku.AGENT,workflows:Ku.WORKFLOW_RUN,tools:Ku.TOOL};function tbs(){const{data:e,isLoading:t,isError:n}=ebs(),{getTracesHref:r,getLogsHref:s}=fA(),{Link:a}=cn();return o.jsx(Jys,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:e8[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:e8[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(UL,{href:r({rootEntityType:e8[i]}),LinkComponent:a}),o.jsx(fys,{href:s({rootEntityType:e8[i],status:"error"}),LinkComponent:a})]})})}const Bie="period",t8="dateFrom",n8="dateTo";function nbs(){const[e,t]=hi(),n=e.get(Bie),r=rys(n)?n:"24h",s=g.useMemo(()=>{if(r!=="custom")return;const d=h=>{if(!h)return;const m=new Date(h);return Number.isNaN(m.getTime())?void 0:m},f=d(e.get(t8)),p=d(e.get(n8));if(!(!f&&!p))return{from:f,to:p}},[r,e.toString()]),a=g.useMemo(()=>Yvs(e),[e.toString()]),i=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d==="24h"?p.delete(Bie):p.set(Bie,d),d!=="custom"&&(p.delete(t8),p.delete(n8)),p},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d?.from?p.set(t8,d.from.toISOString()):p.delete(t8),d?.to?p.set(n8,d.to.toISOString()):p.delete(n8),p},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return Xvs(p,d),p},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,Gvs(e)))return;const d=MVt();d&&t(f=>{const p=new URLSearchParams(f);for(const[h,m]of d)p.append(h,m);return p},{replace:!0})},[]),o.jsx(ays,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(rbs,{})})}function rbs(){const[e]=hi(),{error:t,isLoading:n}=FVt(),{filterTokens:r,setFilterTokens:s}=HQ(),[a,i]=g.useState(),{supportsMetrics:l,isInMemory:c,isLoading:u}=Qqt(),{data:d,isLoading:f}=RAe(),{data:p,isLoading:h}=NAe(),{data:m,isLoading:v}=AAe(),{data:y,isLoading:b}=IAe(),x=g.useMemo(()=>Qvs({availableTags:d??[],availableEntityNames:p??[],availableServiceNames:m??[],availableEnvironments:y??[],loading:{tags:f,entityNames:h,serviceNames:v,environments:b}}),[d,p,m,y,f,h,v,b]),[S,k]=g.useState(()=>MVt()!==null),_=g.useCallback(()=>{Wvs(e),k(!0),Be.success("Filters setting for Metrics saved")},[e]),C=g.useCallback(()=>{Zvs(),k(!1),Be.success("Filters setting for Metrics cleared up")},[]),T=g.useCallback(()=>{s([])},[s]),E=g.useCallback(()=>{const N=r.map(I=>{const A=x.find(R=>R.id===I.fieldId);return A?A.kind==="text"?{fieldId:I.fieldId,value:""}:A.kind==="pick-multi"?A.multi?{fieldId:I.fieldId,value:[]}:{fieldId:I.fieldId,value:"Any"}:A.kind==="multi-select"?{fieldId:I.fieldId,value:[]}:I:I});s(N)},[x,r,s]);return t&&Ss(t)?o.jsx(ir,{children:o.jsx(Gs,{})}):t&&ks(t)?o.jsx(ir,{children:o.jsx(Fs,{resource:"metrics"})}):t?o.jsx(ir,{children:o.jsx(Ui,{title:"Failed to load metrics",message:t.message})}):o.jsxs(Vt,{width:"wide",height:"full",children:[o.jsxs(Vt.TopArea,{children:[o.jsx(Vt.Row,{children:o.jsxs(Vt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(cys,{}),o.jsx(EAe,{fields:x,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(Mys,{isLoading:n,filterFields:x,filterTokens:r,onFilterTokensChange:s,onClear:E,onRemoveAll:T,onSave:_,onRemoveSaved:S?C:void 0,autoFocusFilterFieldId:a})]}),u?null:l?o.jsxs("div",{className:"grid content-start gap-8 pb-10",children:[c&&o.jsx(Wn,{variant:"info",title:"Metrics are not persisted",children:o.jsx(Wn.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(Fxe,{children:[o.jsx(Iys,{}),o.jsx(Ays,{}),o.jsx(Rys,{}),o.jsx(Pys,{}),o.jsx($ys,{})]}),o.jsxs(Fxe,{children:[o.jsx(zys,{}),o.jsx(Vys,{}),o.jsx(Xys,{}),o.jsx(Cys,{}),o.jsx(tbs,{}),o.jsx(wys,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Er,{iconSlot:o.jsx(Mc,{}),titleSlot:"Metrics are not available with your current storage",descriptionSlot:"Metrics require ClickHouse, DuckDB, Postgres v-next, Spanner, or in-memory storage for observability. Other relational databases (LibSQL, MSSQL) and document stores (MongoDB) do not support metrics collection. To enable metrics on an existing project, switch the observability storage in the Mastra configuration.",actionSlot:o.jsxs(oe,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(Yr,{})]})})})]})}const sbs=50;function abs(){const{paths:e}=cn(),{isCmsAvailable:t}=hS(),[n,r]=g.useState(""),[s,a]=g.useState(0),{data:i,isLoading:l,error:c,isPlaceholderData:u}=uBt({page:s,perPage:sbs}),d=i?.promptBlocks??[],f=i?.hasMore??!1,p=g.useCallback(()=>{u||a(v=>v+1)},[u]),h=g.useCallback(()=>{u||a(v=>Math.max(0,v-1))},[u]),m=g.useCallback(v=>{r(v),a(0)},[]);return c&&Ss(c)?o.jsx(ir,{children:o.jsx(Gs,{})}):c&&ks(c)?o.jsx(ir,{children:o.jsx(Fs,{resource:"prompt blocks"})}):c?o.jsx(ir,{children:o.jsx(Ui,{title:"Failed to load prompt blocks",message:c.message})}):d.length===0&&!l&&s===0?o.jsx(ir,{children:o.jsx(Oss,{})}):o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsxs(Vt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(ah,{onSearch:m,label:"Filter prompts",placeholder:"Filter by name or description"})}),t&&o.jsxs(oe,{as:wi,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(Or,{}),"Create Prompt"]})]})}),o.jsx(kss,{promptBlocks:d,isLoading:l,search:n,currentPage:s,hasMore:f,onNextPage:p,onPrevPage:h})]})}function ibs(){return o.jsx(Vt,{width:"narrow",children:o.jsx(Vt.MainArea,{children:o.jsx(crs,{children:o.jsx(gxe,{})})})})}const obs=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:hYt,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:jlt,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Yr,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:u0e,href:"https://discord.gg/BTYqqHKUrf",external:!0},{title:"Share with your team",description:"Running Mastra Studio locally? Deploy to the cloud so your team can collaborate.",icon:$lt,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:Nlt,href:"https://mastra.ai/contact?ref=studio",external:!0}];function lbs(){return o.jsx(Vt,{width:"narrow",children:o.jsx(Vt.MainArea,{children:o.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:obs.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(Yr,{className:"text-icon3 ml-auto h-3.5 w-3.5 opacity-0 transition-opacity group-hover:opacity-100"})]}),o.jsx("p",{className:"text-ui-sm text-text3 leading-relaxed",children:e.description})]},e.href))})})})}function cbs(){const{data:e={},isLoading:t,error:n}=oh(),[r,s]=g.useState(""),[a,i]=g.useState("all");if(n&&Ss(n))return o.jsx(ir,{children:o.jsx(Gs,{})});if(n&&ks(n))return o.jsx(ir,{children:o.jsx(Fs,{resource:"scorers"})});if(n)return o.jsx(ir,{children:o.jsx(Ui,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(ir,{children:o.jsx(d7r,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx(p7r,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(u7r,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}function ubs(){const{scorerId:e}=mr(),[t,n]=hi(),r=t.get("scoreId")??void 0,[s,a]=g.useState(r),[i,l]=g.useState(!1),c=es(),[u,d]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:f,error:p}=V9r(e),{data:h={},isLoading:m,error:v}=Dm(),{isLoading:y,error:b}=Wy(),{data:x=[],isLoading:S,error:k,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:T}=q9r({scorerId:e,entityId:u?.value==="all"?void 0:u?.value,entityType:u?.type==="ALL"?void 0:u?.type}),E=g.useMemo(()=>f?.agentIds?.filter($=>h[$]).map($=>({value:$,label:h[$].name,type:"AGENT"}))||[],[f?.agentIds,h]),N=g.useMemo(()=>f?.workflowIds?.map($=>({value:$,label:$,type:"WORKFLOW"}))||[],[f?.workflowIds]),I=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...E,...N],[E,N]),A=t.get("entity")??"all",R=I.find($=>$.value===A);R&&R.value!==u?.value&&d(R),g.useEffect(()=>{if(p){const $=p instanceof Error?p.message:"Failed to load scorer";Be.error(`Error loading scorer: ${$}`)}},[p]),g.useEffect(()=>{if(v){const $=v instanceof Error?v.message:"Failed to load agents";Be.error(`Error loading agents: ${$}`)}},[v]),g.useEffect(()=>{if(b){const $=b instanceof Error?b.message:"Failed to load workflows";Be.error(`Error loading workflows: ${$}`)}},[b]);const L=$=>{$?.value&&n(q=>{const Z=new URLSearchParams(q);return Z.set("entity",$.value),Z})};g.useEffect(()=>{const $=t.get("scoreId")??void 0;if($===s)return;if(!$){a(void 0);return}x.find(Z=>Z.id===$)&&a($)},[t,x]);const D=g.useCallback($=>{a($||void 0),n(q=>{const Z=new URLSearchParams(q);return $?Z.set("scoreId",$):Z.delete("scoreId"),Z})},[n]);if(!f)return null;const F=Ss(p)||Ss(v)||Ss(b),H=p&&ks(p),B=!F&&!H&&(p||v||b),z=!S&&x.length===0,V=u?.value!=="all",M=f?.scorer?.source==="stored"?o.jsx($y,{owner:"scorer-detail",children:o.jsxs(oe,{variant:"default",as:wi,to:`/cms/scorers/${e}/edit`,size:"sm",children:[o.jsx(um,{})," Edit"]})}):null,G=e?o.jsx(FAe,{open:i,onOpenChange:l,initialScorerIds:[e],onSuccess:$=>{c(`/experiments/${$}`)}}):null;if(F||H||B||z&&!V){const $=(p instanceof Error?p.message:void 0)??(v instanceof Error?v.message:void 0)??(b instanceof Error?b.message:void 0)??"An unexpected error occurred";return o.jsxs(Vt,{width:"wide",height:"full",className:"grid-rows-[1fr]",children:[M,o.jsx(Vt.MainArea,{isCentered:!0,children:F?o.jsx(Gs,{}):H?o.jsx(Fs,{resource:"scorers"}):B?o.jsx(Ui,{title:"Failed to load scorer",message:$}):o.jsx($9r,{onRunExperiment:()=>l(!0)})}),G]})}return o.jsxs(Vt,{width:"wide",height:"full",children:[M,o.jsx(Vt.TopArea,{children:o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx(D9r,{selectedEntity:u,entityOptions:I,onEntityChange:L,onReset:()=>{n($=>{const q=new URLSearchParams($);return q.set("entity","all"),q})},isLoading:S||m||y}),o.jsxs(oe,{variant:"primary",onClick:()=>l(!0),children:[o.jsx(Dc,{}),"Run Experiment"]})]})}),o.jsx(P9r,{scores:x,isLoading:S,selectedScoreId:s,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:T,onScoreClick:D,errorMsg:k?.message}),G]})}const dbs=Ii("flex min-w-0 flex-col",{variants:{variant:{default:"gap-3 sm:flex-row sm:items-center sm:justify-between",factory:"gap-2 px-4 py-3 lg:flex-row lg:items-center lg:justify-between lg:gap-4"}},defaultVariants:{variant:"default"}}),fbs=Ii("flex min-w-0 flex-col",{variants:{variant:{default:"",factory:"gap-0.5"}},defaultVariants:{variant:"default"}}),stt=Ii("",{variants:{variant:{default:"text-sm font-medium",factory:"text-ui-md leading-ui-md text-neutral5"}},defaultVariants:{variant:"default"}}),pbs=Ii("flex flex-col gap-0.5",{variants:{variant:{default:"text-sm text-neutral3",factory:"text-ui-sm text-neutral3"}},defaultVariants:{variant:"default"}});function hbs({label:e,description:t,htmlFor:n,variant:r,className:s,children:a}){return o.jsxs("div",{className:K(dbs({variant:r}),s),"data-slot":"settings-row",children:[o.jsxs("div",{className:fbs({variant:r}),children:[n?o.jsx(Mt,{htmlFor:n,className:stt({variant:r}),children:e}):o.jsx("span",{className:stt({variant:r}),children:e}),t&&o.jsx("div",{className:pbs({variant:r}),children:t})]}),a]})}const qVt=[{value:"dark",label:"Dark",Icon:pXt},{value:"light",label:"Light",Icon:MJt},{value:"system",label:"System",Icon:Wlt}],mbs=e=>qVt.some(t=>t.value===e);function gbs({option:e}){const{Icon:t}=e;return o.jsxs("span",{className:"inline-flex max-w-full min-w-0 items-center gap-2",children:[o.jsx(t,{"aria-hidden":"true",className:"h-4 w-4 shrink-0 opacity-70"}),o.jsx("span",{className:"min-w-0 truncate",children:e.label})]})}const vbs=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=SH(),{theme:r,setTheme:s}=K_();return o.jsx(Vt,{width:"narrow",children:o.jsxs(Vt.MainArea,{className:"mt-6 flex flex-col gap-5",children:[o.jsx(qbe,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(hbs,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(ha,{value:r,onValueChange:a=>{mbs(a)&&s(a)},children:[o.jsx(ga,{id:"theme",className:"w-full sm:w-48",children:o.jsx(ma,{className:"inline-flex max-w-full min-w-0 items-center"})}),o.jsx(va,{children:qVt.map(a=>o.jsx(Nr,{value:a.value,children:o.jsx(gbs,{option:a})},a.value))})]})})}),o.jsx(qbe,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(F3t,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function ybs(){const[e]=hi(),t=es(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(RVt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}function bbs(e){return e.replace(/\/$/,"").split("/").pop()}function WQ({children:e,className:t}){return o.jsx("div",{className:K("border border-border1 rounded-lg mt-12 py-8 lg:min-h-[25rem] transition-height px-4 lg:px-12",t),children:e})}function xbs({templates:e,linkComponent:t,className:n,isLoading:r}){const s=t||"a";return r?o.jsx("div",{className:K("grid gap-y-4",n),children:Array.from({length:5}).map((a,i)=>o.jsx("div",{className:"bg-surface3 h-16 animate-pulse rounded-lg"},i))}):o.jsx("div",{className:K("grid gap-y-4",n),children:e.map(a=>{const i=a?.agents||a?.tools||a?.networks||a?.workflows||a?.mcp;return o.jsxs("article",{className:K("border border-border1 rounded-lg overflow-hidden w-full grid grid-cols-[1fr_auto] bg-surface3 transition-colors hover:bg-surface4"),children:[o.jsxs(s,{to:`/templates/${a.slug}`,className:K("grid [&:hover_p]:text-neutral5",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":a.imageURL}),children:[a.imageURL&&o.jsx("div",{className:K("overflow-hidden"),children:o.jsx("div",{className:"thumb transition-scale h-full w-full bg-cover duration-150",style:{backgroundImage:`url(${a.imageURL})`}})}),o.jsxs("div",{className:K("grid py-3 px-6 w-full gap-0.5","[&_svg]:w-[1em] [&_svg]:h-[1em] [&_svg]:text-neutral3"),children:[o.jsx("h2",{className:"text-ui-lg text-neutral5",children:a.title}),o.jsx("p",{className:"text-ui-md text-neutral4 transition-colors duration-500",children:a.description}),o.jsxs("div",{className:"text-neutral3 text-ui-md mt-3 hidden flex-wrap items-center gap-4 2xl:flex",children:[i&&o.jsxs("ul",{className:K("flex gap-4 text-ui-md text-neutral3 m-0 p-0 list-none","[&>li]:flex [&>li]:items-center [&>li]:gap-0.5 text-neutral4"),children:[a?.agents&&a.agents.length>0&&o.jsxs("li",{children:[o.jsx(Ti,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(Ff,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(Glt,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(aI,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(OC,{})," ",a.mcp.length]})]}),i&&a.supportedProviders&&o.jsx("small",{children:"|"}),o.jsx("div",{className:"text-neutral3 flex items-center gap-4",children:a.supportedProviders.map(l=>o.jsx("span",{className:"",children:l},l))})]})]})]}),o.jsx("a",{href:a.githubUrl,className:K("group items-center gap-2 text-ui-md ml-auto pr-4 hidden","lg:flex"),target:"_blank",rel:"noopener noreferrer",children:o.jsxs("span",{className:"bg-surface1 group-hover:bg-surface2 text-neutral3 group-hover:text-neutral5 flex items-center gap-2 rounded px-2 py-1 transition-colors",children:[o.jsx(HZ,{})," ",bbs(a.githubUrl)]})})]},a.slug)})})}function wbs({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:s,onProviderChange:a,searchTerm:i,onSearchChange:l,onReset:c,className:u,isLoading:d}){return d?o.jsxs("div",{className:K("h-[6.5rem] flex items-center gap-8","[&>div]:bg-surface3 [&>div]:w-48 [&>div]:h-8 [&>div]:animate-pulse",u),children:[o.jsx("div",{})," ",o.jsx("div",{})," ",o.jsx("div",{})]}):o.jsxs("div",{className:K("flex flex-wrap mx-auto sticky top-0 gap-4 bg-surface2 py-8",u),children:[o.jsx(m_,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(Pc,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(Pc,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(oe,{onClick:c,children:["Reset ",o.jsx(or,{})]})]})}function Sbs(){const{data:e,isLoading:t}=ynr(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[a,i]=g.useState("all"),[l,c]=g.useState("all"),[u,d]=g.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(x=>{f.push({value:x,label:x})});const p=[{value:"all",label:"Any provider"}];(s||[]).forEach(x=>{p.push({value:x,label:x})});const h=(x,S)=>{S==="tag"?i(x):S==="provider"&&c(x)},m=x=>{d(x)},v=()=>{i("all"),c("all"),d("")},y=n.filter(x=>!(u&&!x.title.toLowerCase().includes(u)&&!x.description.toLowerCase().includes(u)||a!=="all"&&!x.tags.includes(a)||l!=="all"&&!x.supportedProviders.includes(l))),b=u||a!=="all"||l!=="all";return o.jsxs(_s,{children:[o.jsx(iSe,{children:o.jsxs(ebt,{children:[o.jsx(He,{children:o.jsx(oy,{})}),"Templates"]})}),o.jsxs("div",{className:K("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(wbs,{selectedTag:a,onTagChange:x=>h(x,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:x=>h(x,"provider"),providerOptions:p,searchTerm:u,onSearchChange:m,onReset:b?v:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(xbs,{templates:y,linkComponent:wi,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const kbs="1.64.0-alpha.5";function Obs({errorMsg:e,validationErrors:t}){const n=typeof e=="string"?e:e!=null?String(e):void 0,r=n?.includes("Invalid schema for function"),s=n?.includes("validation issue")||t&&t.length>0,a=()=>s?"Template installation completed but some validation issues remain. The template may still be functional, but you should review and fix these issues.":r?"There was an issue with the AI model configuration. This may be related to the selected model or AI SDK version compatibility.":"An unexpected error occurred during template installation.",i=()=>s?{icon:o.jsx(ac,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(TYt,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(WQ,{className:"text-neutral3 mb-8 content-center space-y-4",children:[o.jsxs("div",{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[l,o.jsxs("div",{className:"space-y-2 text-center",children:[o.jsx("p",{className:"text-ui-md text-neutral5 font-medium",children:c}),o.jsx("p",{className:"text-ui-md text-neutral3",children:a()})]})]}),t&&t.length>0&&o.jsxs("details",{className:"text-xs",children:[o.jsxs("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:["Show Validation Issues (",t.length,")"]}),o.jsx("div",{className:"mt-4 max-h-60 space-y-2 overflow-auto rounded bg-gray-100 p-3 text-left text-xs dark:bg-gray-800",children:t.map((u,d)=>o.jsxs("div",{className:"border-l-2 border-red-400 pl-2",children:[o.jsx("div",{className:"font-medium text-red-600 dark:text-red-400",children:u.type==="typescript"?"🔴 TypeScript Error":"⚠️ Lint Error"}),o.jsx("div",{className:"mt-1 font-mono text-xs wrap-break-word whitespace-pre-wrap text-gray-700 dark:text-gray-300",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-xs",children:[o.jsx("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:"Show Details"}),o.jsx("div",{className:"mt-4 max-h-60 overflow-auto rounded bg-gray-100 p-3 text-left font-mono text-xs dark:bg-gray-800",children:o.jsx("div",{className:"wrap-break-word whitespace-pre-wrap",children:n})})]})]})}function _bs({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:s,handleInstallTemplate:a,handleVariableChange:i,isLoadingEnvVars:l,isInstalling:c,defaultModelProvider:u,defaultModelId:d,onModelUpdate:f}){return o.jsx(WQ,{children:o.jsxs("div",{className:"mx-auto my-4 grid max-w-[40rem] gap-8 p-4 lg:p-8",children:[o.jsxs("h2",{className:K("text-neutral4 text-header-sm font-semibold flex items-center gap-2","[&>svg]:w-[1.2em] [&_svg]:h-[1.2em] [&_svg]:opacity-70"),children:["Install Template ",o.jsx(Qlt,{})]}),o.jsx(Pc,{name:"template-provider",options:e,label:"Template AI Model Provider",onValueChange:n,value:t,placeholder:"Select",layout:"horizontal"}),t&&Object.entries(r||{}).length>0&&o.jsxs(o.Fragment,{children:[o.jsx("h3",{className:"text-neutral3 text-ui-md",children:"Set required Environmental Variables"}),o.jsx("div",{className:"grid grid-cols-[1fr_1fr] items-start gap-4",children:l?o.jsxs("div",{className:K("flex items-center justify-center col-span-2 text-neutral3 text-ui-sm gap-4","[&_svg]:opacity-50 [&_svg]:w-[1.1em] [&_svg]:h-[1.1em]","animate-in fade-in duration-300"),children:[o.jsx(Ut,{})," Loading variables..."]}):Object.entries(r).map(([p,h])=>o.jsxs(g.Fragment,{children:[o.jsx(Bg,{name:`env-${p}`,labelIsHidden:!0,label:"Key",value:p,disabled:!0,className:"w-full"}),o.jsx(Bg,{name:p,labelIsHidden:!0,label:"Value",value:h,onChange:i,errorMsg:s.includes(p)?"Value is required.":"",autoComplete:"off",className:"w-full"})]},p))}),o.jsxs("div",{className:"border-border1 relative mt-3.5 border-t pt-12",children:[o.jsx("div",{className:"bg-surface2 text-ui-sm text-neutral3 absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full",children:"And"}),o.jsx("h3",{className:"text-neutral4 text-ui-lg",children:"Set AI Model for Template Installation"}),o.jsx("p",{className:"text-neutral3 text-ui-md mt-2 mb-8",children:"This model will be used by the workflow to process and install the template"}),o.jsx(L3t,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(oe,{className:K("flex items-center gap-2 mt-4 justify-center text-ui-md w-full bg-surface5 min-h-10 rounded-lg text-neutral5 hover:bg-surface6 transition-colors","[&>svg]:w-[1.1em] [&_svg]:h-[1.1em] [&_svg]:text-neutral5"),onClick:a,disabled:!t||!u||!d||s.length>0||c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(Ut,{className:"h-4 w-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(Fd,{})]})})]})})}function Cbs({title:e,description:t,githubUrl:n,isLoading:r,infoData:s,templateSlug:a}){const i=a?`feat/install-template-${a}`:"feat/install-template-[slug]";return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:K("grid mt-8 items-center"),children:o.jsxs("div",{className:K("text-header-lg flex items-center gap-3","[&>svg]:w-[1.2em] [&>svg]:h-[1.2em] [&>svg]:opacity-50",{"[&>svg]:opacity-20":r}),children:[o.jsx(oy,{}),o.jsx("h2",{className:K({"bg-surface4 flex rounded-lg min-w-[50%]":r}),children:r?o.jsx(o.Fragment,{children:" "}):e})]})}),o.jsxs("div",{className:"grid gap-x-24 lg:grid-cols-[1fr_1fr]",children:[o.jsxs("div",{className:"grid",children:[o.jsx("p",{className:K("mb-4 text-ui-md text-neutral4 mt-2 leading-7",{"bg-surface4 rounded-lg ":r}),children:r?o.jsx(o.Fragment,{children:" "}):t}),!r&&a&&o.jsxs("div",{className:K("bg-surface2 border border-surface4 rounded-lg p-4 mb-4","flex items-start gap-3"),children:[o.jsx("div",{className:"mt-0.5 shrink-0",children:o.jsx(km,{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(o0e,{className:"text-neutral4 h-[1em] w-[1em]"}),o.jsx("span",{className:"text-ui-md text-neutral5 font-medium",children:"A new Git branch will be created"})]}),o.jsxs("div",{className:"text-ui-sm text-neutral4 space-y-1",children:[o.jsxs("div",{children:[o.jsx("span",{className:"font-medium",children:"Branch name:"})," ",o.jsx("code",{className:"bg-surface3 text-ui-sm rounded px-1.5 py-0.5 font-mono",children:i})]}),o.jsx("div",{children:"This ensures safe installation with easy rollback if needed. Your main branch remains unchanged."})]})]})]}),n&&o.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"text-neutral3 text-ui-md hover:text-neutral5 mt-auto flex items-center gap-2",children:[o.jsx(HZ,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(WTe,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function att(e){switch(e){case"running":return o.jsx(Ut,{size:"sm","aria-hidden":!0});case"success":return o.jsx(Qr,{"aria-hidden":!0});case"failed":return o.jsx(or,{"aria-hidden":!0});default:return null}}function Ebs(){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 Tbs({status:e,variant:t}){return t==="plain"?o.jsx("span",{className:K("flex size-4 items-center justify-center self-center [&>svg]:size-4",Gr.colors,{"[&>svg]:text-positive1":e==="success","[&>svg]:text-negative1":e==="failed"}),children:e==="pending"?o.jsx(Ebs,{}):att(e)}):o.jsx("span",{className:K("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",Gr.colors,Gr.transform,Gr.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:att(e)})}function jbs({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",Gr.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",Gr.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",Gr.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(Tbs,{status:e.status,variant:r})]})}function Nbs({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:K(n),children:t.map((r,s)=>o.jsx(jbs,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function Ibs({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",Gr.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",Gr.colors,Gr.transform,Gr.shadow,{"border border-dashed border-neutral2":r.status==="pending","bg-accent1Dark text-notice-success-fg shadow-glow-accent1 scale-110":r.status==="success","bg-accent2Dark text-notice-destructive-fg shadow-glow-accent2 scale-110":r.status==="failed"}),children:r.status==="running"?o.jsx(Ut,{}):s+1})},r.id))}),o.jsxs("div",{className:K("text-center text-xs text-neutral3",Gr.colors),children:[n," of ",t," steps completed"]})]})}function Abs({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",a=t?.payload?.workflowState,i=t?.payload?.currentStep,l=t?.error,c=a?.steps||{},u=Object.keys(c).length>0,d=v=>v==="input"||v.endsWith(".input")||v.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(v)||/[0-9a-f]{8,}/.test(v)?!1:r?.allSteps?v in r.allSteps:!0,f=Object.entries(c).filter(([v,y])=>d(v)),p=f.length,h=()=>{switch(s){case"initializing":return"Preparing template installation...";case"processing":return`Installing ${e} template`;case"completed":return"Template installation completed!";case"error":return"Template installation failed";default:return"Installing template..."}},m=f.map(([v,y])=>({id:v,status:y?.status,description:y?.description,title:v.charAt(0).toUpperCase()+v.slice(1).replace(/-/g," "),isActive:i?.id===v}));return o.jsxs(WQ,{className:"text-neutral3 mb-8 content-center space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h3",{className:"text-neutral5 text-lg font-semibold",children:h()}),(t?.runId||n)&&o.jsxs("div",{className:"text-ui-sm text-neutral3 mt-2",children:["Run ID: ",t?.runId??n]})]}),u&&p>0&&!["error"].includes(s)&&o.jsx("div",{className:"mx-auto w-full max-w-[30rem] px-6",children:o.jsx(Ibs,{steps:m})}),l&&s==="error"&&o.jsxs("div",{className:K("rounded-lg text-neutral5 p-6 flex items-center gap-3 text-ui-md bg-red-500/10","[&>svg]:w-6 [&>svg]:h-6 [&>svg]:opacity-70 [&>svg]:text-red-500"),children:[o.jsx(_Xt,{}),l||"Something went wrong"]}),u&&o.jsx(Nbs,{steps:m,currentStep:i,className:"pb-4"}),!u&&s==="initializing"&&o.jsxs("div",{className:"text-neutral3 grid justify-items-center gap-4 text-center text-sm",children:[o.jsx(Ut,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function Rbs({name:e,installedEntities:t}){return o.jsxs(WQ,{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(Qlt,{}),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(WTe,{data:t})]})}function Pbs(){const{templateSlug:e}=mr(),[t,n]=hi(),[r,s]=g.useState(""),[a,i]=g.useState(""),[l,c]=g.useState(""),[u,d]=g.useState({}),[f,p]=g.useState([]),[h,m]=g.useState(null),[v,y]=g.useState(!1),[b,x]=g.useState(""),[S,k]=g.useState(!1),[_,C]=g.useState(!1),[T,E]=g.useState([]),{data:N,isLoading:I}=bnr({repoOrSlug:e,owner:"mastra-ai"}),R=kbs?.includes("beta")??!1?"beta":"main",{data:L,isLoading:D}=xnr({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:R}),{data:F,isLoading:H}=wnr(),{mutateAsync:B,isPending:z}=Snr(),{mutateAsync:V}=knr(),{streamInstall:M,streamResult:G,isStreaming:U}=_nr(F),{observeInstall:$,streamResult:q,isStreaming:Z}=Cnr(F);g.useEffect(()=>{const te=t.get("runId");te&&!v&&!h&&!U&&!Z&&(console.info("🔄 Checking completed run after hot reload:",{runId:te}),x(te),V({runId:te}).then(se=>{const pe=se.snapshot;if(pe?.status==="success"&&pe?.result?.success)y(!0);else if(pe?.result?.success===!1)if(pe?.result?.validationResults&&!pe?.result?.validationResults?.valid&&pe?.result?.validationResults?.remainingErrors>0){const{remainingErrors:Se,errors:ve}=pe.result.validationResults,ke=`Template installation completed but ${Se} validation issue${Se>1?"s":""} remain unresolved.`;m(ke),E(ve||[])}else{const Se=pe?.result?.message||pe?.result?.error||"Template installation failed";m(typeof Se=="string"?Se:String(Se))}}).catch(se=>{console.error("❌ Failed to fetch run details:",se),m("Failed to retrieve installation status after reload")}))},[t,v,h,U,Z,V]),g.useEffect(()=>{const te=t.get("runId"),se=t.get("resume"),pe=t.get("provider");if(te&&se==="true"&&pe&&!U&&!Z&&!S&&!_&&F){x(te),k(!0);try{V({runId:te}).then(ce=>{if(ce.snapshot?.status==="running")return $.mutateAsync({runId:te})}).then(()=>{n(ce=>{const Se=new URLSearchParams(ce);return Se.delete("resume"),Se})}).catch(ce=>{console.error("❌ Failed to resume template installation:",ce),ce.message?.includes("404")||ce.message?.includes("not found")?m("Template installation run not found. It may have expired or been completed."):m("Failed to resume template installation. Please try again.")})}catch(ce){console.error("❌ Auto-resume failed with error:",ce),m("Failed to resume template installation. Please refresh and try again.")}}},[t,e,U,Z,S,_,F,V,$,n]);const Y=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],ne=[{key:"tools",label:"Tools",value:N?.tools?.length?N.tools.map(te=>te).join(", "):"n/a",icon:o.jsx(Ff,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(te=>te).join(", "):"n/a",icon:o.jsx(Ti,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(te=>te).join(", "):"n/a",icon:o.jsx(aI,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(kg,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(sI,{})}],J=[{...ne[0]},{...ne[1]},{...ne[2]}].filter(te=>te.value!=="n/a");g.useEffect(()=>{L&&d(L)},[L]),g.useEffect(()=>{const te=G||q;te?.phase==="error"&&te?.error&&m(typeof te.error=="string"?te.error:String(te.error))},[G?.phase,G?.error,q?.phase,q?.error]);const ee=te=>{s(te)},re=async te=>(i(te.provider),c(te.modelId),{message:"Model updated successfully"}),le=async()=>{const te=Object.entries(u).reduce((se,[pe,ce])=>(ce===""&&se.push(pe),se),[]);if(te.length>0){p(te);return}if(N){m(null),y(!1),x(""),C(!0);try{const pe={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:R,slug:N.slug,variables:u},{runId:ce}=await B({});x(ce),n(Se=>{const ve=new URLSearchParams(Se);return ve.set("runId",ce),ve.set("resume","true"),ve.set("provider",r||"openai"),ve}),await M.mutateAsync({inputData:pe,selectedModel:{provider:a,modelId:l},runId:ce})}catch(se){C(!1),m(se?.message||"Template installation failed"),console.error("Template installation failed",se)}}},X=te=>{const{name:se,value:pe}=te.target;pe.trim()===""?p(ce=>[...ce,se]):p(ce=>ce.filter(Se=>Se!==se)),d(ce=>({...ce,[se]:pe}))};return o.jsx(_s,{children:o.jsx("div",{className:K("w-full lg:px-12 h-full overflow-y-scroll"),children:o.jsxs("div",{className:"mx-auto grid w-full max-w-[80rem] gap-y-4 p-6",children:[o.jsx(Cbs,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:ne,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(U||Z)&&o.jsx(Abs,{name:N.title,streamResult:Z?q:G,runId:b,workflowInfo:F}),v&&o.jsx(Rbs,{name:N.title,installedEntities:J,linkComponent:wi}),h&&o.jsx(Obs,{errorMsg:h,validationErrors:T.length>0?T:G?.validationResults?.errors||q?.validationResults?.errors}),!U&&!Z&&!v&&!h&&o.jsx(_bs,{providerOptions:Y,selectedProvider:r,onProviderChange:ee,variables:u,setVariables:d,errors:f,setErrors:p,handleInstallTemplate:le,handleVariableChange:X,isLoadingEnvVars:D||H,isInstalling:z,defaultModelProvider:a,defaultModelId:l,onModelUpdate:re})]})]})})})}const $bs=()=>{const{toolId:e,agentId:t}=mr();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(Crs,{toolId:e,agentId:t})})},Mbs=()=>{const{toolId:e}=mr();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(Mvs,{toolId:e})})};function Dbs(){const{data:e,isLoading:t,error:n}=Wy(),[r,s]=g.useState("");return n&&Ss(n)?o.jsx(ir,{children:o.jsx(Gs,{})}):n&&ks(n)?o.jsx(ir,{children:o.jsx(Fs,{resource:"workflows"})}):n?o.jsx(ir,{children:o.jsx(Ui,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(ir,{children:o.jsx(hWr,{})}):o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsxs(Vt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(ah,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsxs(oe,{as:wi,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(KN,{}),"Schedules"]})]})}),o.jsx(pWr,{workflows:e||{},isLoading:t,search:r})]})}const Lbs={active:"bg-accent1",paused:"bg-accent3"},Fbs={active:"text-accent1",paused:"text-accent3"},VVt=({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 ${Lbs[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${Fbs[e]}`,children:e})]}),wj=e=>!e||e<=0?"—":new Date(e).toLocaleString(),s2=e=>{if(!e||e<=0)return"—";const t=e-Date.now(),n=Math.abs(t),r=Math.floor(n/1e3);if(r<60)return t>=0?`in ${r}s`:`${r}s ago`;const s=Math.floor(r/60);if(s<60)return t>=0?`in ${s}m`:`${s}m ago`;const a=Math.floor(s/60);if(a<24)return t>=0?`in ${a}h`:`${a}h ago`;const i=Math.floor(a/24);return t>=0?`in ${i}d`:`${i}d ago`};function HVt({status:e}){const{icon:t,color:n}=zbs(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 zbs(e){switch(e){case"success":return{icon:o.jsx(Qr,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(or,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(Ut,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(mV,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(Mc,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(r1,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const itt="auto auto auto auto 1fr";function Bbs(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 Ubs(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 qbs=3e4,Vbs=5*6e4;function Hbs({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=cn(),c=h=>!!(n&&h.runId&&h.outcome!=="failed"),u=e.filter(c).length,{containerRef:d,getRowProps:f}=wo({count:u});let p=-1;return t?o.jsx(Pl,{columns:itt}):e.length===0?o.jsx(me,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(be,{columns:itt,className:"min-w-0",scrollRef:d,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"Run"}),o.jsx(be.TopCell,{children:"Status"}),o.jsx(be.TopCell,{children:"Started"}),o.jsx(be.TopCell,{children:"Duration"}),o.jsx(be.TopCell,{children:" "})]}),e.map(h=>{const m=h.actualFireAt-h.scheduledFireAt,v=Ubs(m),y=`Scheduled ${wj(h.scheduledFireAt)} — published ${wj(h.actualFireAt)} (drift ${v})`,b=h.outcome==="failed",x=b?h.error:h.run?.error,S=Math.abs(m),k=!b&&S>qbs&&S<=Vbs,_=`${h.scheduleId}-${h.runId}-${h.actualFireAt}`,C=c(h);C&&(p+=1);const T=o.jsx("span",{className:C?"text-accent1 text-ui-sm font-mono whitespace-nowrap":"text-neutral3 text-ui-sm font-mono whitespace-nowrap",children:h.runId}),E=o.jsxs(o.Fragment,{children:[o.jsx(be.Cell,{children:T}),o.jsx(be.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(ac,{size:14}),"publish failed"]}):h.run?o.jsx(HVt,{status:h.run.status}):o.jsx("span",{className:"text-ui-sm text-neutral3 inline-flex items-center gap-1.5 whitespace-nowrap",children:"pending"}),x?o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(ac,{size:14})})}),o.jsx(vn,{children:x})]}):null]})}),o.jsx(be.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:y,children:s2(h.actualFireAt)}),k?o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(ac,{size:14})})}),o.jsxs(vn,{children:["Published ",v," after the scheduled fire time"]})]}):null]})}),o.jsx(be.Cell,{children:h.run?o.jsx("span",{children:Bbs(h.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(be.Cell,{children:" "})]});return C?o.jsx(be.RowLink,{to:l.workflowRunLink(n,h.runId),LinkComponent:i,...f(p),children:E},_):o.jsx(be.RowStatic,{children:E},_)}),o.jsx(be.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const Wbs=e=>{const t=Qe();return yt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},ott=25,Zbs=e=>{const t=Qe(),{inView:n,setRef:r}=tC(),s=K1({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:ott,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<ott))return u.triggers[u.triggers.length-1].actualFireAt},refetchInterval:u=>(u.state.data?.pages.flatMap(p=>p.triggers)??[]).some(p=>p.run?p.run.status==="pending"||p.run.status==="running"||p.run.status==="waiting":p.outcome==="published")?5e3:!1}),a=s.data?.pages.flatMap(u=>u?.triggers??[])??[],{hasNextPage:i,isFetchingNextPage:l,fetchNextPage:c}=s;return g.useEffect(()=>{n&&i&&!l&&c()},[n,i,l,c]),{...s,data:a,setEndOfListElement:r}},Gbs=e=>{const t=Qe(),n=Lr();return An({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"]}),Be.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{Be.error(r.message)}})};function r8({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral4 tracking-wide uppercase",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function Qbs(){const{scheduleId:e}=mr(),{paths:t}=cn(),{data:n,error:r}=Wbs(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=Zbs(e),d=Gbs(e);if(r&&Ss(r))return o.jsx(ir,{children:o.jsx(Gs,{})});if(r&&ks(r))return o.jsx(ir,{children:o.jsx(Fs,{resource:"schedules"})});if(r)return o.jsx(ir,{children:o.jsx(Ui,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,p=n?.agentId;return o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx(Vt.Row,{className:"justify-end",children:o.jsxs(Vt.Column,{className:"flex justify-end gap-2",children:[o.jsxs(oe,{as:wi,to:t.schedulesLink(),variant:"ghost",children:[o.jsx(gl,{}),"Back to schedules"]}),f?o.jsx(oe,{as:wi,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(oe,{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(SV,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(Dc,{}),"Resume"]})}):null]})})}),n?o.jsxs("div",{className:"grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-6 overflow-hidden",children:[o.jsxs("div",{className:"border-border1 flex h-fit flex-col gap-4 rounded-md border p-4",children:[o.jsx(r8,{label:p?"Agent":"Workflow",children:f?o.jsx(wi,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):p?o.jsx(wi,{to:t.agentLink(p),className:"text-accent1 hover:underline",children:p}):"—"}),o.jsxs(r8,{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(r8,{label:"Status",children:o.jsx(VVt,{status:n.status})}),o.jsx(r8,{label:"Next fire",children:o.jsx("span",{title:wj(n.nextFireAt),children:s2(n.nextFireAt)})})]}),o.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[o.jsx(me,{variant:"ui-md",className:"mb-3",children:"Trigger history"}),i?o.jsx(Ui,{title:"Failed to load trigger history",message:i.message}):o.jsx(Hbs,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const ltt="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function Ybs({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=cn(),a=g.useMemo(()=>{const c=n.toLowerCase();return c?e.filter(u=>u.id.toLowerCase().includes(c)||(u.workflowId??u.agentId??"").toLowerCase().includes(c)):e},[e,n]),{containerRef:i,getRowProps:l}=wo({count:a.length});return t?o.jsx(Pl,{columns:ltt}):o.jsxs(be,{columns:ltt,variant:"striped",className:"min-w-0",scrollRef:i,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"Target"}),o.jsx(be.TopCell,{children:"Schedule ID"}),o.jsx(be.TopCell,{children:"Cron"}),o.jsx(be.TopCell,{children:"Status"}),o.jsx(be.TopCell,{children:"Next fire"}),o.jsx(be.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(be.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(be.NoMatch,{message:"No schedules configured"}):null,a.map((c,u)=>o.jsxs(be.RowLink,{to:r.scheduleLink(c.id),LinkComponent:s,...l(u),children:[o.jsx(be.NameCell,{children:c.workflowId??c.agentId}),o.jsx(be.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(be.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(be.Cell,{children:o.jsx(VVt,{status:c.status})}),o.jsx(be.Cell,{children:o.jsx("span",{className:"whitespace-nowrap",title:wj(c.nextFireAt),children:s2(c.nextFireAt)})}),o.jsx(be.Cell,{children:c.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(HVt,{status:c.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:wj(c.lastFireAt),children:c.lastFireAt?s2(c.lastFireAt):""})]}):c.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:wj(c.lastFireAt),children:s2(c.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},c.id))]})}function Kbs({workflowId:e}={}){const{data:t,isLoading:n,error:r}=sSe(e?{workflowId:e}:{}),[s,a]=g.useState("");return r?o.jsx(Ui,{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(ah,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(Ybs,{schedules:t??[],isLoading:n,search:s})})]})}function Xbs(){const[e]=hi(),t=e.get("workflowId")??void 0,{error:n}=sSe(t?{workflowId:t}:{});return n&&Ss(n)?o.jsx(ir,{children:o.jsx(Gs,{})}):n&&ks(n)?o.jsx(ir,{children:o.jsx(Fs,{resource:"schedules"})}):o.jsx(Vt,{children:o.jsx("div",{className:"h-full",children:o.jsx(Kbs,{workflowId:t})})})}function Jbs({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=jOe({stepGraph:e}),[a,i]=g.useState(!1),[l,c,u]=C_t(r),[d]=E_t(s),{edgeTypes:f,nodeTypes:p,styledEdges:h}=PLt({edges:d,workflowName:n,stepGraph:e});return g.useEffect(()=>{if(t){const m=setTimeout(()=>{i(!0)},500);return()=>clearTimeout(m)}},[t]),o.jsx("div",{className:"bg-surface1 relative h-full w-full",children:a?o.jsxs(__t,{nodes:l,edges:h,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:p,onNodesChange:u,children:[o.jsx(mje,{position:"bottom-left"}),o.jsx(j_t,{variant:fy.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:o.jsx(Ut,{})})})}function exs(){const{stepDetail:e,closeStepDetail:t}=SW();return e?o.jsxs("div",{className:"flex h-full flex-col","data-testid":"workflow-step-detail-panel",children:[o.jsxs("div",{className:"border-border1 bg-surface1 flex items-center justify-between border-b px-4 py-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[e.type==="map-config"&&o.jsx(wx,{className:"h-4 w-4",style:{color:zu.map}}),e.type==="nested-graph"&&o.jsx(Uc,{className:"h-4 w-4",style:{color:zu.workflow}}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx(me,{variant:"ui-md",className:"text-neutral6 font-medium",children:e.type==="map-config"?`${e.stepName} Config`:`${e.stepName} Workflow`}),e.type==="map-config"&&e.stepId&&e.stepId!==e.stepName&&o.jsx(me,{variant:"ui-xs",className:"text-neutral3",children:e.stepId})]})]}),o.jsx("button",{onClick:t,className:"hover:bg-surface3 rounded p-1 transition-colors","aria-label":"Close",children:o.jsx(or,{className:"text-neutral3 h-4 w-4"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(e2,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(TOe,{children:o.jsx(Jbs,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function txs(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function nxs(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 rxs({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:o.jsxs("div",{className:"border-border1 bg-surface4 space-y-5 rounded-lg border p-5","data-testid":"workflow-suspended-steps",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs(me,{as:"p",variant:"ui-md",className:"text-neutral6 flex items-center gap-2 font-semibold",children:[o.jsx(He,{children:o.jsx(mV,{})}),"Step suspended"]}),o.jsx(St,{variant:"yellow",children:"Needs input"})]}),e.map((s,a)=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const l=i?.resumeSchema?vm(Tx(i.resumeSchema)):hf(cr(),Of());return o.jsx(sxs,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function sxs({step:e,stepSchema:t,description:n,isStreaming:r,onResume:s}){const[a,i]=g.useState(!1);return o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(me,{as:"p",variant:"ui-md",className:"text-neutral6 truncate font-medium",children:e.stepId}),n&&o.jsx(me,{as:"p",variant:"ui-sm",className:"text-neutral3",children:n})]}),e.suspendPayload&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs(me,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(He,{children:o.jsx(mXt,{})}),"The step is asking"]}),o.jsxs(Fc,{open:a,onOpenChange:i,children:[o.jsxs(cc,{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(He,{children:o.jsx(Ur,{className:K("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(me,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:nxs(e.suspendPayload,e.stepId)})]}),o.jsx(me,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:txs(e.suspendPayload)})]}),o.jsx(uc,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Zr,{data:e.suspendPayload,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs(me,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(He,{children:o.jsx(yXt,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(aU,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(Dc,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:l=>{const c=e.stepId?.split(".");s({stepId:c,runId:e.runId,suspendPayload:e.suspendPayload,resumeData:l,isLoading:!1})}})})]})]})}function axs(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext(Ul),{runId:a}=mr(),i=M_t(e,r??""),l=AJn(),c=!!a,u=t?.status==="suspended",f=!!(a&&r&&a===r)&&e?.status==="suspended";return s||!n||i.length===0||c&&!u&&!f?null:o.jsx("div",{"data-testid":"workflow-suspended-overlay",className:"animate-in fade-in-0 slide-in-from-top-2 zoom-in-95 absolute top-2 right-2 z-20 max-h-[calc(100%-1rem)] w-[380px] max-w-[calc(100%-1rem)] overflow-y-auto rounded-lg shadow-lg duration-300",children:o.jsx(rxs,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const ixs=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.97865 4.57004C8.22604 4.75795 8.27426 5.11082 8.08635 5.35821L6.05486 8.03279C5.94873 8.17251 5.78348 8.25471 5.60803 8.25505C5.43257 8.2554 5.267 8.17385 5.16032 8.03454L3.80937 6.27034C3.6205 6.02369 3.66733 5.67063 3.91398 5.48176C4.16063 5.29288 4.51369 5.33972 4.70257 5.58637L5.6051 6.76498L7.19048 4.67774C7.37839 4.43036 7.73126 4.38213 7.97865 4.57004Z",fill:"currentColor"})]}),oxs=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.89741 4.10293C8.11707 4.32261 8.11706 4.67877 7.89738 4.89843L6.79517 6.00058L7.8962 7.10155C8.11588 7.32122 8.11589 7.67737 7.89623 7.89705C7.67656 8.11673 7.32041 8.11674 7.10073 7.89707L5.99965 6.79605L4.89856 7.89707C4.67889 8.11673 4.32273 8.11672 4.10307 7.89704C3.88341 7.67737 3.88342 7.32121 4.10309 7.10155L5.20413 6.00058L4.10191 4.89843C3.88224 4.67877 3.88223 4.32262 4.10189 4.10294C4.32155 3.88326 4.67771 3.88325 4.89738 4.10292L5.99965 5.20511L7.10191 4.10291C7.32159 3.88325 7.67774 3.88326 7.89741 4.10293Z",fill:"currentColor"})]}),lxs=e=>e.includes("."),cxs=e=>e==="input"||e.endsWith(".input"),uxs=1;function dxs(e){return`${Number((e/1e3).toPrecision(3))}s`}function fxs(e,t){const n=Object.entries(e).filter(([i])=>!cxs(i));if(n.length===0)return[];const r=Math.min(...n.map(([,i])=>i.startedAt)),s=Math.max(...n.map(([,i])=>i.endedAt??t)),a=Math.max(s-r,1);return n.map(([i,l])=>{const c=l.endedAt===void 0,d=(l.endedAt??t)-l.startedAt,f=(l.startedAt-r)/a*100,p=Math.max(d/a*100,uxs);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:p,durationMs:d,isRunning:c,isNestedEntry:lxs(i)}})}const pxs=({status:e})=>o.jsxs(He,{children:[e==="success"&&o.jsx(ixs,{className:"text-accent1"}),e==="failed"&&o.jsx(oxs,{className:"text-accent2"}),e==="suspended"&&o.jsx(mV,{className:"text-accent3"}),e==="waiting"&&o.jsx(Npe,{className:"text-accent5"}),e==="skipped"&&o.jsx(Npe,{className:"text-icon3"}),e==="running"&&o.jsx(qs,{className:"text-accent6 animate-spin"})]}),hxs={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function WVt(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const ctt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},mxs=e=>{const t=e;return _Lt({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},gxs=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=mxs(e.step),u=e.status==="running",d=!e.isNestedEntry;return o.jsxs("div",{role:"button",tabIndex:0,"data-testid":"workflow-timeline-row","data-workflow-step-key":e.stepId,"data-workflow-step-active":n?"true":void 0,"data-workflow-step-hovered":r?"true":void 0,"data-workflow-step-nested":e.isNestedEntry?"true":void 0,"aria-pressed":n,"aria-disabled":!d,onMouseEnter:()=>{d&&a(e.stepId)},onMouseLeave:()=>{d&&a(null)},onClick:()=>{d&&s(e.stepId)},onKeyDown:f=>{!d||f.key!=="Enter"&&f.key!==" "||(f.preventDefault(),s(e.stepId))},className:K("grid grid-cols-[auto_auto_auto_minmax(0,10rem)_minmax(0,1fr)_auto_5rem] items-center gap-2 rounded-md border border-transparent px-2 py-1 text-left transition-colors focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-accent1",d&&"cursor-pointer",d&&"hover:bg-surface4",d&&r&&!n&&"border-neutral6 bg-surface4",d&&n&&"border-accent1",e.isNestedEntry&&"cursor-default opacity-55"),children:[o.jsx("div",{className:"flex justify-center",children:o.jsx(pxs,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(oe,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step input",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||i(e)},children:o.jsx(NJt,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(Uq,{indicators:c,className:"shrink-0"})}),o.jsx(me,{as:"span",variant:"ui-sm",className:"text-neutral6 block max-w-full min-w-0 justify-self-stretch overflow-hidden text-left text-ellipsis whitespace-nowrap",children:WVt(e.stepId)}),o.jsx("div",{className:"bg-surface4 relative h-2 min-w-0 rounded",children:o.jsx("div",{"data-testid":"workflow-timeline-bar","data-offset":String(e.offsetPct),"data-width":String(e.widthPct),className:`absolute top-0 h-full rounded ${hxs[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(oe,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step output",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||l(e)},children:o.jsx(TJt,{})})}),o.jsx(me,{as:"span",variant:"ui-sm",className:"text-neutral3 w-20 justify-self-end text-right tabular-nums",children:dxs(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function vxs(){const{steps:e}=K4(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=AH(),[a,i]=g.useState(()=>Date.now()),[l,c]=g.useState(!1),[u,d]=g.useState(null),f=g.useRef(null);pbt(f,{enabled:!l});const p=fxs(e,a),h=p.some(m=>m.isRunning);return g.useEffect(()=>{if(!h)return;const m=setInterval(()=>i(Date.now()),100);return()=>clearInterval(m)},[h]),g.useEffect(()=>{if(l||p.length===0)return;const m=f.current;m&&(m.scrollTop=m.scrollHeight)},[l,p.length]),p.length===0?null:o.jsxs(o.Fragment,{children:[o.jsx("div",{"data-testid":"workflow-timeline",className:"pointer-events-none absolute right-0 bottom-0 z-20 px-2 pb-2",style:{left:"var(--workflow-left-panel-width, 0px)"},children:o.jsxs("div",{className:"rounded-studio-panel border-border1/50 bg-surface3 pointer-events-auto flex max-h-64 w-full min-w-0 flex-col gap-3 overflow-hidden border p-4 shadow-lg",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3",children:[o.jsx(me,{as:"p",variant:"ui-md",className:"text-neutral3",children:"Timeline"}),o.jsx("button",{type:"button","aria-label":l?"Expand timeline":"Collapse timeline","aria-expanded":!l,onClick:()=>c(m=>!m),className:"text-neutral3 hover:bg-surface4 hover:text-neutral6 rounded-md p-1 transition-colors",children:o.jsx(Xs,{className:K("h-4 w-4 transition-transform",l&&"-rotate-90")})})]}),!l&&o.jsx("div",{ref:f,"data-testid":"workflow-timeline-list",className:"flex min-h-0 flex-col gap-2 overflow-y-auto",children:p.map((m,v)=>o.jsx(gxs,{row:m,index:v,isSelected:t===m.stepId,isHovered:n===m.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:y=>d({type:"input",stepId:y.stepId,data:ctt(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:ctt(y.step.output)})},`timeline-item-${m.stepId}-${v}`))})]})}),o.jsx(vr,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(L_t,{data:u.data,title:`${WVt(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const yxs=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=SW();return o.jsxs("div",{className:"flex h-full min-h-0",children:[o.jsx("div",{className:"flex h-full min-h-0 flex-1 flex-col",children:o.jsxs("div",{className:"relative min-h-0 flex-1 p-2 pb-0",children:[o.jsx(BLt,{workflowId:e,workflow:t,isLoading:n}),o.jsx(axs,{}),o.jsx(vxs,{})]})}),r&&o.jsx("div",{className:"border-border1 min-h-0 w-[420px] overflow-hidden border-l",children:o.jsx(exs,{})})]})},utt=()=>{const{workflowId:e}=mr(),{data:t,isLoading:n,error:r}=a4(e);return r&&Ss(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Gs,{})}):r&&ks(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{resource:"workflows"})}):o.jsx(ZOe,{children:o.jsx(yxs,{workflowId:e,workflow:t??void 0,isLoading:n})})};function bxs(e,t){if(e==null)return{};var n,r,s=USt(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function Wxe(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 xxs(e){if(Array.isArray(e))return Wxe(e)}function wxs(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function Sxs(e,t){if(e){if(typeof e=="string")return Wxe(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)?Wxe(e,t):void 0}}function kxs(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
644
|
+
`);return t!==-1&&t!==e.length-1}else{if(Array.isArray(e))return e.some(t=>zxe(t));if(e&&typeof e=="object")return Object.values(e).some(t=>zxe(t))}return!1}function Cgs({children:e}){return o.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e})}function Egs({className:e,children:t}){return o.jsx("div",{className:K("mx-4 flex items-center justify-between gap-2 border-b border-border1 py-3",e),children:t})}function Tgs({className:e,children:t}){return o.jsx("h3",{className:K("flex gap-2 text-ui-md text-neutral3 [&>b]:font-normal [&>b]:text-neutral2",e),children:t})}function jgs({className:e,children:t}){return o.jsx("dl",{className:K("grid grid-cols-[auto_1fr] gap-x-4 gap-y-1.5",e),children:t})}function Ngs({className:e,children:t}){return o.jsx("dt",{className:K("shrink-0 py-0.5 text-ui-smd text-neutral2",e),children:t})}function Igs({className:e,children:t}){return o.jsx("dd",{className:K("min-w-0 truncate py-0.5 text-ui-smd text-neutral3",e),children:t})}function Ags({className:e,children:t}){return o.jsx("dt",{className:K("col-span-2 py-3 text-ui-sm tracking-widest text-neutral2 uppercase",e),children:t})}const Rgs=Object.assign(jgs,{Key:Ngs,Value:Igs,Header:Ags});function Pgs({children:e}){return o.jsxs("div",{className:"text-ui-sm text-neutral3 flex items-center justify-center gap-2 px-4 py-6",children:[o.jsx(Ut,{size:"sm",variant:"pulse",className:"text-neutral3"})," ",e??"Loading..."]})}function $gs({children:e}){return o.jsx("p",{className:"text-ui-sm text-neutral2 px-4 py-6",children:e??"No data found."})}const Li=Object.assign(xgs,{Header:Egs,Heading:Tgs,CloseButton:wgs,LoadingData:Pgs,NoData:$gs,Content:Cgs,KeyValueList:Rgs,CodeSection:_gs}),hp=Li.KeyValueList;function Mgs(e){return e instanceof Date?e:new Date(e)}function Dgs({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:a,collapsed:i,onCollapsedChange:l}){const[c,u]=g.useState(!1),d=i??c,f=l??u,p=Mgs(e.timestamp),h=e.traceId,m=e.spanId;return o.jsxs(Li,{collapsed:d,children:[o.jsxs(Li.Header,{children:[o.jsxs(Li.Heading,{children:["Log ",o.jsx("b",{children:hr(p,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(hs,{className:"ml-auto shrink-0",children:[l&&o.jsx(oe,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(XN,{}):o.jsx(hV,{})}),o.jsxs(hs,{spacing:"close",children:[o.jsx(oe,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(q1,{})}),o.jsx(oe,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(pV,{})})]}),o.jsx(Li.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(Li.Content,{children:[o.jsx("p",{className:"text-ui-md text-neutral4 font-mono wrap-break-word whitespace-pre-wrap",children:e.message}),(h||m)&&o.jsxs("div",{className:K("my-8 grid gap-2","[&>button]:justify-between [&>button]:overflow-hidden"),children:[h&&o.jsxs(hs,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(oe,{size:"md",className:"min-w-0 flex-1 overflow-hidden",onClick:()=>n?.(h),children:[o.jsx(Fd,{}),o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",h]})]}),o.jsx(ka,{content:h,size:"md",tooltip:"Copy Trace ID to clipboard"})]}),m&&o.jsxs(hs,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(oe,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!h||!r,onClick:()=>h&&r?.(h,m),children:[o.jsx(Fd,{}),o.jsx("span",{children:"Span"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",m]})]}),o.jsx(ka,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(hp,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(hp.Key,{children:"Entity Type"}),o.jsx(hp.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(hp.Key,{children:"Entity Name"}),o.jsx(hp.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(hp.Key,{children:"Service"}),o.jsx(hp.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(hp.Key,{children:"Environment"}),o.jsx(hp.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(hp.Key,{children:"Source"}),o.jsx(hp.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(hp.Key,{children:v}),o.jsx(hp.Value,{children:String(y)})]},v))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(Li.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function Lgs({error:e,resource:t,errorTitle:n}){if(Ss(e))return o.jsx(Gs,{});if(ks(e))return o.jsx(Fs,{resource:t});if(P4(e))return o.jsx(Er,{iconSlot:o.jsx(Mc,{}),titleSlot:"Observability storage is not available",descriptionSlot:"The observability storage domain is disabled or not configured. Enable it in your storage configuration to view logs in Studio."});if(R4(e,"logs"))return o.jsx(Er,{iconSlot:o.jsx(Mc,{}),titleSlot:"Logs are not available with your current storage",descriptionSlot:"The configured observability storage provider does not support listing logs. Switch to a storage provider with logs support to view runtime logs in Studio."});const r=e instanceof Error?e.message:void 0;return o.jsx(Ui,{title:n,message:r??"Unknown error"})}function Fgs({listSlot:e,logPanelSlot:t,tracePanelSlot:n,spanPanelSlot:r,logCollapsed:s}){const a=!!t;return o.jsxs("div",{className:K("grid h-full min-h-0 items-start gap-4",a?"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[e,a&&o.jsxs("div",{className:K("grid h-full gap-4 overflow-auto",n&&r?s?"grid-rows-[auto_1fr_1fr]":"grid-rows-[1fr_1fr_1fr]":n?s?"grid-rows-[auto_1fr]":"grid-rows-[1fr_1fr]":s?"grid-rows-[auto]":"grid-rows-[1fr]"),children:[t,n,r]})]})}const zgs={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 Bgs({level:e}){const t=zgs[e];return o.jsx(lo,{children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function Ugs({entityType:e,className:t}){const n=K("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case"agent":return o.jsx(Ti,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return o.jsx(Uc,{className:n,"aria-hidden":!0});case"tool":return o.jsx(Ff,{className:n,"aria-hidden":!0});default:return null}}function qgs({entityType:e,entityName:t}){const n=e??"";return o.jsxs(lo,{className:"flex min-w-0 items-center gap-2",children:[o.jsx(Ugs,{entityType:n}),t?o.jsx("span",{className:"text-ui-smd min-w-0 truncate",children:t}):"-"]})}function Vgs({message:e}){return o.jsx(lo,{className:"text-ui-smd text-neutral4 min-w-0 truncate font-mono",children:e})}function Hgs({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(lo,{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(RTe,{font:"mono",children:t})}const Ql=Object.assign(q4,{Top:KZ,TopCell:mC,TopCellWithTooltip:XZ,TopCellSmart:T3t,RowWrapper:MTe,RowButton:V4,RowLink:E3t,Spacer:DTe,NoMatch:YZ,DateCell:O3t,TimeCell:_3t,LevelCell:Bgs,EntityCell:qgs,MessageCell:Vgs,DataCell:Hgs,NextPageLoading:QZ}),Yet="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",Wgs=36,Zgs=8;function Ggs({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=g.useRef(null),u=qUt({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>Wgs,overscan:Zgs}),{getRowProps:d}=wo({count:e.length,containerRef:c,onNavigate:y=>u.scrollToIndex(y)}),f=g.useRef(t);if(g.useEffect(()=>{f.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),f.current=t},[t]),t)return o.jsx(Pl,{columns:Yet});const p=u.getVirtualItems(),h=u.getTotalSize(),m=p[0]?.start??0,v=p.length>0?Math.max(0,h-(p[p.length-1]?.end??0)):0;return o.jsxs(Ql,{columns:Yet,variant:"striped",scrollRef:c,className:"min-w-0",children:[o.jsxs(Ql.Top,{children:[o.jsx(Ql.TopCell,{children:"Date"}),o.jsx(Ql.TopCell,{children:"Time"}),o.jsx(Ql.TopCell,{children:"Level"}),o.jsx(Ql.TopCell,{children:"Entity"}),o.jsx(Ql.TopCell,{children:"Message"}),o.jsx(Ql.TopCell,{children:"Data"})]}),e.length===0?o.jsx(Ql.NoMatch,{message:"No logs match your search"}):o.jsxs(o.Fragment,{children:[o.jsx(Ql.Spacer,{height:m}),p.map(y=>{const b=e[y.index];if(!b)return null;const x=a.get(b);if(!x)return null;const S=x===i;return o.jsxs(Ql.RowButton,{ref:u.measureElement,"data-index":y.index,...d(y.index),onClick:()=>l(b),featured:S,variant:b.level==="error"||b.level==="fatal"?"error":"default",children:[o.jsx(Ql.DateCell,{timestamp:b.timestamp}),o.jsx(Ql.TimeCell,{timestamp:b.timestamp}),o.jsx(Ql.LevelCell,{level:b.level}),o.jsx(Ql.EntityCell,{entityType:b.entityType,entityName:b.entityName}),o.jsx(Ql.MessageCell,{message:b.message}),o.jsx(Ql.DataCell,{data:b.data})]},x)}),o.jsx(Ql.Spacer,{height:v})]}),o.jsx(Ql.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function Qgs({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>Ygs(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(CAe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(OAe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function Ygs(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 Kgs={"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"},Aie="MMM d, yyyy HH:mm",Rie="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function Xgs({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${Kgs[e]}`,description:Rie}:t&&n?{title:`No logs between ${hr(t,Aie)} and ${hr(n,Aie)}`,description:Rie}:t?{title:`No logs since ${hr(t,Aie)}`,description:Rie}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const Jgs=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=Xgs({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Er,{iconSlot:o.jsx(Mc,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(oe,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",children:["Logging Documentation ",o.jsx(Yr,{})]})})})},evs=20,tvs=1e4;function nvs(e,t,n){if(e?.pagination?.hasMore)return n+1}function rvs(e){const t=new Set,n=[];for(const r of e.pages)for(const s of r.logs??[]){const a=s.logId??JSON.stringify(s);t.has(a)||(t.add(a),n.push(s))}return n}function svs(e){return R4(e.state.error,"logs")||P4(e.state.error)?!1:tvs}const avs=({filters:e}={})=>{const t=Qe(),{inView:n,setRef:r}=tC(),s=K1({queryKey:["logs",e],queryFn:({pageParam:p})=>t.listLogsVNext({pagination:{page:p,perPage:evs},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:nvs,select:rvs,retry:!1,refetchInterval:svs}),{hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,data:c,isLoading:u,isError:d,error:f}=s;return g.useEffect(()=>{n&&a&&!i&&l()},[n,a,i,l]),{data:c,hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,isLoading:u,isError:d,error:f,setEndOfListElement:r}},Xz={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},PVt=[{label:"Agent",entityType:Xz.AGENT},{label:"Workflow",entityType:Xz.WORKFLOW},{label:"Scorer",entityType:Xz.SCORER},{label:"Ingest",entityType:Xz.INGEST}],ivs=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],Yx="rootEntityType",Jb="datePreset",ex="dateFrom",tx="dateTo",ovs=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),_l={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"},BL=Object.keys(_l),qAe=new Set(["tags"]),VAe="mastra:logs:saved-filters";function lvs(e,t=VAe){const n=pvs(e),r=e.get(Jb);r&&n.set(Jb,r);const s=e.get(ex);s&&n.set(ex,s);const a=e.get(tx);a&&n.set(tx,a);try{localStorage.setItem(t,n.toString())}catch{}}function cvs(e=VAe){try{localStorage.removeItem(e)}catch{}}function Ket(e=VAe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function uvs(e){if(e.has(Jb)||e.has(ex)||e.has(tx)||e.has(Yx))return!0;for(const t of BL)if(e.has(_l[t]))return!0;return!1}function dvs({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:PVt.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:ivs.map(u=>({label:u.label,value:u.value})),placeholder:"Choose level",emptyText:"No levels."},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"traceId",label:"Trace ID",kind:"text"},{id:"spanId",label:"Span ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"threadId",label:"Thread ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function fvs(e){const t=[],n=new Map([[Yx,"rootEntityType"]]);for(const s of BL)n.set(_l[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),qAe.has(a)){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function pvs(e){const t=new URLSearchParams,n=e.get(Yx);n&&t.set(Yx,n);for(const r of BL){const s=_l[r];if(qAe.has(r)){for(const i of e.getAll(s))t.append(s,i);continue}const a=e.get(s);a&&t.set(s,a)}return t}function hvs(e,t){e.delete(Yx);for(const n of BL)e.delete(_l[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(Yx,n.value);continue}const r=_l[n.fieldId];if(r){if(qAe.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 mvs({rootEntityType:e,dateFrom:t,dateTo:n,tokens:r}){const s={};e&&(s.rootEntityType=e),(t||n)&&(s.timestamp={...t?{start:t}:{},...n?{end:n}:{}});for(const a of r){if(a.fieldId==="tags"){Array.isArray(a.value)&&a.value.length>0?s.tags=a.value:typeof a.value=="string"&&a.value.trim()&&(s.tags=[a.value.trim()]);continue}if(a.fieldId==="level"){typeof a.value=="string"&&a.value.trim()&&a.value!=="Any"&&(s.level=a.value);continue}if(typeof a.value=="string"&&a.value.trim()&&a.value!=="Any")switch(a.fieldId){case"entityName":s.rootEntityName=a.value;break;case"traceId":s.traceId=a.value;break;case"spanId":s.spanId=a.value;break;case"runId":s.runId=a.value;break;case"threadId":s.threadId=a.value;break;case"sessionId":s.sessionId=a.value;break;case"requestId":s.requestId=a.value;break;case"resourceId":s.resourceId=a.value;break;case"userId":s.userId=a.value;break;case"organizationId":s.organizationId=a.value;break;case"serviceName":s.serviceName=a.value;break;case"environment":s.environment=a.value;break;case"experimentId":s.experimentId=a.value;break}}return s}function gvs(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 vvs="Filters setting for Logs saved",yvs="Filters setting for Logs cleared up";function bvs(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=g.useState(()=>Ket(r)!==null),c=g.useCallback(()=>{lvs(e,r),l(!0);const f=s?.saved??vvs;f!==!1&&Be.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{cvs(r),l(!1);const f=s?.cleared??yvs;f!==!1&&Be.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(a||d.current||(d.current=!0,uvs(e)))return;const f=Ket(r);f&&t(p=>{const h=new URLSearchParams(p);for(const[m,v]of f)h.append(m,v);return h},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function xvs(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 wvs(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,xvs(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function Svs(e,t,n,r){const s=g.useMemo(()=>wvs(e),[e]),a=g.useMemo(()=>{const h=new Map;for(const[m,v]of e.entries()){const y=s.get(v);y&&h.set(y,{log:v,idx:m})}return h},[e,s]),l=(t?a.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=g.useCallback(h=>s.get(h),[s]),d=g.useCallback(h=>{const m=s.get(h);if(m){if(t===m){n({logId:null});return}n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}},[s,t,r,n]),f=l>0?()=>{const h=e[l-1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0,p=l>=0&&l<e.length-1?()=>{const h=e[l+1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0;return{logIdMap:s,getLogId:u,featuredLog:c,handleLogClick:d,handlePreviousLog:f,handleNextLog:p}}const Bxe="logId",Uxe="traceId",qxe="spanId",kP=1440*60*1e3,kvs={"last-24h":kP,"last-3d":3*kP,"last-7d":7*kP,"last-14d":14*kP,"last-30d":30*kP};function Jz(e){e.delete(Bxe),e.delete(Uxe),e.delete(qxe)}function Ovs(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const _=e.get(Jb);return _&&ovs.has(_)?_:"last-24h"},[e]),a=e.get(ex),i=e.get(tx),l=g.useMemo(()=>{if(s==="custom"){if(!a)return;const C=new Date(a);return Number.isNaN(C.getTime())?void 0:C}if(s==="all")return;const _=kvs[s];return _?new Date(Date.now()-_):void 0},[s,a]),c=g.useMemo(()=>{if(s!=="custom"||!i)return;const _=new Date(i);return Number.isNaN(_.getTime())?void 0:_},[s,i]),u=g.useRef(s);u.current=s;const d=e.get(Bxe),f=e.get(Uxe),p=e.get(qxe),h=g.useMemo(()=>PVt.find(_=>_.entityType===e.get(Yx)),[e]),m=g.useMemo(()=>fvs(e),[e]),v=g.useCallback(_=>{t(C=>{const T=new URLSearchParams(C);for(const[E,N]of Object.entries(_)){const I=E==="logId"?Bxe:E==="traceId"?Uxe:qxe;N?T.set(I,N):T.delete(I)}return T},{replace:!0})},[t]),y=g.useCallback(_=>{t(C=>{const T=new URLSearchParams(C);return hvs(T,_),Jz(T),T},{replace:!0})},[t]),b=y,x=g.useCallback((_,C)=>{if(u.current!=="custom")return;const T=C==="from"?ex:tx;t(E=>{const N=new URLSearchParams(E);return _?N.set(T,_.toISOString()):N.delete(T),Jz(N),N},{replace:!0})},[t]),S=g.useCallback(_=>{u.current=_,t(C=>{const T=new URLSearchParams(C);return _==="last-24h"?(T.delete(Jb),T.delete(ex),T.delete(tx)):_==="custom"?T.set(Jb,"custom"):(T.set(Jb,_),T.delete(ex),T.delete(tx)),Jz(T),T},{replace:!0})},[t]),k=g.useCallback(()=>{t(_=>{const C=new URLSearchParams(_);C.delete(Yx);for(const T of BL)C.delete(_l[T]);return C.delete(Jb),C.delete(ex),C.delete(tx),Jz(C),C},{replace:!0}),r?.()},[t,r]);return g.useMemo(()=>({searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,featuredLogId:d,featuredTraceId:f,featuredSpanId:p,selectedEntityOption:h,filterTokens:m,handleFeaturedChange:v,handleFilterTokensChange:b,handleDateChange:x,handleDatePresetChange:S,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,p,h,m,v,b,x,S,k,y])}const Eb=Li.KeyValueList;function _vs({spanId:e,span:t,isLoading:n,onClose:r}){const s=OQ(t?.startedAt,t?.endedAt),a=iV(t?.startedAt),i=iV(t?.endedAt);return o.jsxs(Li,{children:[o.jsxs(Li.Header,{children:[o.jsxs(Li.Heading,{children:["Span ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Li.CloseButton,{onClick:r})]}),n?o.jsx(Li.LoadingData,{children:"Loading span..."}):t?o.jsxs(Li.Content,{children:[o.jsxs(Eb,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(Eb.Key,{children:"Type"}),o.jsx(Eb.Value,{children:t.spanType})]}),a&&o.jsxs(o.Fragment,{children:[o.jsx(Eb.Key,{children:"Started"}),o.jsx(Eb.Value,{children:a})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(Eb.Key,{children:"Ended"}),o.jsx(Eb.Value,{children:i})]}),s&&o.jsxs(o.Fragment,{children:[o.jsx(Eb.Key,{children:"Duration"}),o.jsx(Eb.Value,{children:s})]})]}),o.jsx("br",{}),o.jsx(Li.CodeSection,{title:"Input",icon:o.jsx(xx,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(Li.CodeSection,{title:"Output",icon:o.jsx(em,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(Li.CodeSection,{title:"Metadata",icon:o.jsx(Jl,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(Li.CodeSection,{title:"Attributes",icon:o.jsx(Jl,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(Li.NoData,{children:"Span not found."})]})}function Cvs({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:a}){const i=g.useMemo(()=>dAe(t??[]),[t]),[l,c]=g.useState([]);g.useEffect(()=>{i.length>0&&c(fAe(i))},[i]);const u=d=>{s?.(a===d?void 0:d)};return o.jsxs(Li,{children:[o.jsxs(Li.Header,{children:[o.jsxs(Li.Heading,{children:["Trace ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Li.CloseButton,{onClick:r})]}),n?o.jsx(Li.LoadingData,{children:"Loading trace..."}):i.length===0?o.jsx(Li.NoData,{children:"No spans found for this trace."}):o.jsx(Li.Content,{children:o.jsx(sqt,{hierarchicalSpans:i,onSpanClick:u,selectedSpanId:a??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}function Evs(){const[e,t]=hi(),n=Ovs(e,t),r=bvs(e,t),[s,a]=g.useState(),[i,l]=g.useState(!1),{data:c=[],isPending:u}=RAe(),{data:d=[],isPending:f}=NAe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:p=[],isPending:h}=IAe(),{data:m=[],isPending:v}=AAe(),y=g.useMemo(()=>dvs({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:p,loading:{tags:u,entityNames:f,serviceNames:v,environments:h}}),[c,d,m,p,u,f,v,h]),b=g.useMemo(()=>mvs({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:x=[],isLoading:S,error:k,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:T}=avs({filters:b}),{logIdMap:E,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:R}=Svs(x,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:L,isLoading:D}=YUt(n.featuredTraceId??null),{data:F,isLoading:H}=_Q(n.featuredTraceId??"",n.featuredSpanId??""),B=g.useCallback(()=>n.applyFilterTokens(gvs(y,n.filterTokens)),[y,n]),z=g.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),V=g.useCallback(Y=>n.handleFeaturedChange({traceId:Y,spanId:null}),[n]),M=g.useCallback((Y,ne)=>n.handleFeaturedChange({traceId:Y,spanId:ne}),[n]),G=g.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),U=g.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),$=g.useCallback(Y=>n.handleFeaturedChange({spanId:Y??null}),[n]),q=o.jsxs(Vt.TopArea,{children:[o.jsx(Vt.Row,{children:o.jsxs(Vt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(I4,{preset:n.datePreset,onPresetChange:n.handleDatePresetChange,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,onDateChange:n.handleDateChange,disabled:S,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),o.jsx(EAe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:S,onStartTextFilter:a})]})}),o.jsx(Qgs,{isLoading:S,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:B,onRemoveAll:n.handleRemoveAll,onSave:r.handleSave,onRemoveSaved:r.hasSavedFilters?r.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(k)return o.jsxs(Vt,{width:"wide",height:"full",children:[q,o.jsx(Vt.MainArea,{isCentered:!0,children:o.jsx(Lgs,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const Z=!!n.selectedEntityOption||n.filterTokens.length>0;return x.length===0&&!S&&!Z?o.jsxs(Vt,{width:"wide",height:"full",children:[q,o.jsx(Vt.MainArea,{isCentered:!0,children:o.jsx(Jgs,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Vt,{width:"wide",height:"full",children:[q,o.jsx(Fgs,{logCollapsed:i,listSlot:o.jsx(Ggs,{logs:x,isLoading:S,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:T,logIdMap:E,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(Dgs,{log:N,onClose:z,onTraceClick:V,onSpanClick:M,onPrevious:A,onNext:R,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(Cvs,{traceId:n.featuredTraceId,spans:L?.spans,isLoading:D,onClose:G,onSpanSelect:$,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(_vs,{spanId:n.featuredSpanId,span:F?.span,isLoading:H,onClose:U}):null})]})}function Tvs({server:e,rowProps:t}){const{paths:n,Link:r}=cn(),a=Qe().options.baseUrl,i=a?`${a}/api/mcp/${e.id}/sse`:"",{data:l}=X7t(e),c=Object.values(l||{}),u=c.length,d=c.filter(h=>h.toolType==="agent").length,f=c.filter(h=>h.toolType==="workflow").length,p=Xh(e.name,50);return o.jsxs(be.RowLink,{to:n.mcpServerLink(e.id),LinkComponent:r,...t,children:[o.jsx(be.NameCell,{children:p}),o.jsx(be.DescriptionCell,{children:i}),o.jsx(be.TextCell,{className:"text-center",children:d||""}),o.jsx(be.TextCell,{className:"text-center",children:u||""}),o.jsx(be.TextCell,{className:"text-center",children:f||""})]})}function jvs({mcpServers:e,isLoading:t,search:n=""}){const r=g.useMemo(()=>{const i=n.toLowerCase();return e.filter(l=>l.name?.toLowerCase().includes(i)||l.id?.toLowerCase().includes(i))},[e,n]),{containerRef:s,getRowProps:a}=wo({count:r.length});return t?o.jsx(Pl,{columns:"auto 1fr auto auto auto"}):o.jsxs(be,{columns:"auto 1fr auto auto auto",variant:"striped",scrollRef:s,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"Name"}),o.jsx(be.TopCell,{children:"URL"}),o.jsx(be.TopCellSmart,{long:"Agents",short:o.jsx(Ti,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(be.TopCellSmart,{long:"Tools",short:o.jsx(Ff,{}),tooltip:"Tools",className:"text-center"}),o.jsx(be.TopCellSmart,{long:"Workflows",short:o.jsx(Uc,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(be.NoMatch,{message:"No MCP Servers match your search"}):null,r.map((i,l)=>o.jsx(Tvs,{server:i,rowProps:a(l)},i.id))]})}const Nvs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Er,{iconSlot:o.jsx(Mc,{}),titleSlot:"No MCP Servers yet",descriptionSlot:o.jsxs(o.Fragment,{children:["MCP servers are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsxs(oe,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(Yr,{})]})})}),Ivs=()=>{const{data:e=[],isLoading:t,error:n}=mQ(),[r,s]=g.useState("");return n&&Ss(n)?o.jsx(ir,{children:o.jsx(Gs,{})}):n&&ks(n)?o.jsx(ir,{children:o.jsx(Fs,{resource:"MCP servers"})}):n?o.jsx(ir,{children:o.jsx(Ui,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(ir,{children:o.jsx(Nvs,{})}):o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx(ah,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(jvs,{mcpServers:e,isLoading:t,search:r})]})},Avs=(e,t)=>{const n=new Map,r=Object.keys(t);for(const s of r){const a=t[s],i=a.tools,l=Object.keys(i);for(const c of l){const u=i[c];n.has(u.id)||n.set(u.id,{...u,agents:[]}),n.get(u.id).agents.push({...a,id:s})}}for(const[s,a]of Object.entries(e))n.has(a.id)||n.set(a.id,{...a,agents:[]});return Array.from(n.values())};function Rvs({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=cn(),i=g.useMemo(()=>Avs(e,t),[e,t]),l=g.useMemo(()=>i.filter(d=>d.id.toLowerCase().includes(r.toLowerCase())),[i,r]),{containerRef:c,getRowProps:u}=wo({count:l.length});return n?o.jsx(Pl,{columns:"auto 1fr auto"}):o.jsxs(be,{columns:"auto 1fr auto",variant:"striped",scrollRef:c,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"Name"}),o.jsx(be.TopCell,{children:"Description"}),o.jsx(be.TopCellSmart,{long:"Agents",short:o.jsx(Ti,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(be.NoMatch,{message:"No Tools match your search"}):null,l.map((d,f)=>{const p=Xh(d.id,50),h=Xh(d.description??"",200),m=d.agents.length;return o.jsxs(be.RowLink,{to:s.toolLink(d.id),LinkComponent:a,...u(f),children:[o.jsx(be.NameCell,{children:p}),o.jsx(be.DescriptionCell,{children:h}),o.jsx(be.TextCell,{className:"text-center",children:m||""})]},d.id)})]})}const Pvs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Er,{iconSlot:o.jsx(Mc,{}),titleSlot:"No Tools yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Mastra tools are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsxs(oe,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(Yr,{})]})})}),$vs=()=>{const e=Qe();return An({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new A_;Object.entries(r??{}).forEach(([a,i])=>{s.set(a,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(a){throw Be.error("Error executing dev tool"),console.error("Error executing dev tool:",a),a}}})},Mvs=({toolId:e})=>{const{canExecute:t}=_o(),n=t("tools"),{data:r={}}=Dm(),s=g.useMemo(()=>{for(const v of Object.values(r))if(v.tools){const y=Object.values(v.tools).find(b=>b.id===e);if(y)return y}return null},[r,e]),{data:a,isLoading:i,error:l}=IIr(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=$vs(),{requestContext:p}=vs();g.useEffect(()=>{if(l){const v=l instanceof Error?l.message:"Failed to load tool";Be.error(`Error loading tool: ${v}`)}},[l]);const h=async(v,y)=>{if(!c)return;const b={...p??{},...y??{}};return u({toolId:c.id,input:v,requestContext:b})},m=c?.inputSchema?vm(Tx(c?.inputSchema)):xs({});return i?o.jsxs("div",{className:"p-6",children:[o.jsx(jt,{className:"mb-4 h-8 w-48"}),o.jsx(jt,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(BIe,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:h,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(me,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})}):o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(me,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function Dvs({value:e,onValueChange:t,placeholder:n="Select a tool...",searchPlaceholder:r="Search tools...",emptyText:s="No tools found.",className:a,disabled:i=!1,variant:l}){const{data:c={},isLoading:u,isError:d,error:f}=GI(),{data:p={},isLoading:h,isError:m,error:v}=Dm(),{navigate:y,paths:b}=cn();g.useEffect(()=>{if(d){const _=f instanceof Error?f.message:"Failed to load tools";Be.error(`Error loading tools: ${_}`)}},[d,f]),g.useEffect(()=>{if(m){const _=v instanceof Error?v.message:"Failed to load agents";Be.error(`Error loading agents: ${_}`)}},[m,v]);const x=new Map;Object.values(p).forEach(_=>{_.tools&&Object.values(_.tools).forEach(C=>{x.has(C.id)||x.set(C.id,C)})}),Object.values(c).forEach(_=>{x.has(_.id)||x.set(_.id,_)});const S=Array.from(x.values()).map(_=>({label:_.id,value:_.id})),k=_=>{t?t(_):_&&_!==e&&y(b.toolLink(_))};return o.jsx(ml,{options:S,value:e,onValueChange:k,placeholder:u||h?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||u||h||d||m,variant:l})}const Lvs=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=g.useState({sseUrl:"",httpStreamUrl:""});if(g.useEffect(()=>{if(!t)return;const i=window.MASTRA_SERVER_HOST,l=window.MASTRA_SERVER_PORT;let c=null;i&&l&&(c=`http://${i}:${l}`);const u=c||"http://localhost:4111",d=`${u}/api/mcp/${t.id}/sse`,f=`${u}/api/mcp/${t.id}/mcp`;s({sseUrl:d,httpStreamUrl:f})},[t]),e)return null;if(!t)return o.jsx(Hx,{children:o.jsx(me,{as:"h1",variant:"header-md",className:"text-neutral3 py-20 text-center font-medium",children:"Server not found"})});const a=`npx -y mcp-remote ${n}`;return o.jsxs(Hx,{isDivided:!0,children:[o.jsxs("div",{className:"mx-auto w-full max-w-2xl px-8 py-12",children:[o.jsx(me,{as:"h1",variant:"header-md",className:"text-neutral6 pb-4 font-medium",children:t.name}),o.jsxs("div",{className:"flex items-center gap-1 pb-6",children:[o.jsx(St,{icon:o.jsx(tqt,{}),size:"sm",children:"Version"}),o.jsx(St,{size:"sm",children:t.version_detail.version})]}),o.jsx(me,{className:"text-neutral3 pb-4",children:"This MCP server can be accessed through multiple transport methods. Choose the one that best fits your use case."}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(St,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"HTTP"}),children:"Regular HTTP Endpoint"}),o.jsx(me,{className:"text-neutral3 pt-1 pb-2",children:"Use for stateless HTTP transport with streamable responses."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(me,{className:"bg-surface4 rounded-lg px-2 py-1",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx(ka,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(St,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"SSE"}),children:"Server-Sent Events"}),o.jsx(me,{className:"text-neutral3 pt-1 pb-2",children:"Use for real-time communication via SSE."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(me,{className:"bg-surface4 rounded-lg px-2 py-1",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx(ka,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(St,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"CLI"}),children:"Command Line"}),o.jsx(me,{className:"text-neutral3 pt-1 pb-2",children:"Use for local command-line access via npx and mcp-remote."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(me,{className:"bg-surface4 rounded-lg px-2 py-1",children:a}),o.jsx("div",{className:"pt-1",children:o.jsx(ka,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"border-border1 h-full overflow-y-scroll border-l",children:o.jsx(Fvs,{server:t})})]})},Fvs=({server:e})=>{const{data:t={},isLoading:n}=X7t(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(He,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(OC,{})}),o.jsx(me,{variant:"header-md",as:"h2",className:"font-medium",children:"Available Tools"})]}),o.jsx("div",{className:"flex flex-col gap-2 pt-6",children:r.map(s=>{const a=t[s];return o.jsx(Bvs,{tool:a,serverId:e.id},s)})})]})};function zvs(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 Bvs=({tool:e,serverId:t})=>{const n=g.useRef(null),{Link:r,paths:s}=cn(),a=iBt[e.toolType||"tool"],i=zvs(e._meta);return o.jsxs(Vf,{onClick:()=>n.current?.click(),children:[o.jsx(MDt,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Wf,{children:[o.jsx(Hf,{children:o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(r,{ref:n,href:s.mcpServerToolLink(t,e.id),children:e.id}),i&&o.jsx(St,{size:"xs",children:"App"})]})}),o.jsx(ih,{children:e.description})]})]})},Uvs=()=>{const{serverId:e}=mr(),{data:t=[],isLoading:n}=mQ(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(Lvs,{isLoading:n,server:r})})};function qvs(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 Vvs=({toolId:e,serverId:t})=>{const{canExecute:n}=_o(),r=n("tools"),s=Qe(),{data:a,isLoading:i,error:l}=FIe(t,e),{mutateAsync:c,isPending:u,data:d}=bns(t,e),f=a?qvs(a._meta):void 0,{data:p}=yt({queryKey:["mcp-app-resource",t,f],queryFn:async()=>f?(await s.readMcpServerResource(t,f)).contents[0]?.text??null:null,enabled:!!f}),h=g.useCallback(async(y,b)=>await c(b),[c]);g.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";Be.error(`Error loading tool: ${y}`)}},[l]);const m=async y=>{if(a)return await c(y)};if(i)return o.jsxs("div",{className:"p-6",children:[o.jsx(jt,{className:"mb-4 h-8 w-48"}),o.jsx(jt,{className:"h-32 w-full"})]});if(l)return null;if(!a)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(me,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(me,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let v;try{v=vm(a.inputSchema)}catch(y){console.error("Error processing input schema:",y),Be.error("Failed to process tool input schema."),v=xs({})}return o.jsxs("div",{className:"flex flex-col gap-4",children:[p&&o.jsx("div",{className:"border-border1 border-b p-4",children:o.jsx(K7t,{html:p,toolName:a.name??a.id,onToolCall:h})}),o.jsx(BIe,{executionResult:d,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},Hvs=()=>{const{serverId:e,toolId:t}=mr(),{data:n,isLoading:r}=FIe(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(Vvs,{toolId:t,serverId:e})})},$Vt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],HN="rootEntityType",WN={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"},VQ=Object.keys(WN),HAe="mastra:metrics:saved-filters";function Wvs(e){const t=Kvs(e);try{localStorage.setItem(HAe,t.toString())}catch{}}function Zvs(){try{localStorage.removeItem(HAe)}catch{}}function MVt(){try{const e=localStorage.getItem(HAe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function Gvs(e){if(e.has(HN))return!0;for(const t of VQ)if(e.has(WN[t]))return!0;return!1}function Qvs({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:$Vt.map(u=>({label:u.label,value:u.entityType})),placeholder:"Choose entity type",emptyText:"No entity types."},{id:"entityName",label:"Primitive Name",kind:"pick-multi",options:t.map(u=>({label:u,value:u})),placeholder:"Choose entity names",emptyText:"No entity names found.",isLoading:s?.entityNames},{id:"entityId",label:"Primitive ID",kind:"text"},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"threadId",label:"Thread ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function Yvs(e){const t=[],n=new Map([[HN,"rootEntityType"]]);for(const s of VQ)n.set(WN[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),a==="tags"){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}if(a==="rootEntityType"||a==="entityName"||a==="serviceName"||a==="environment"||a==="provider"||a==="model"){const l=e.getAll(s);if(l.length>1){t.push({fieldId:a,value:l});continue}}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function Kvs(e){const t=new URLSearchParams,n=e.getAll(HN);for(const r of n)t.append(HN,r);for(const r of VQ){const s=WN[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function Xvs(e,t){e.delete(HN);for(const n of VQ)e.delete(WN[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?HN:WN[n.fieldId];if(r)if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string"&&a!=="");if(s.length===0){n.fieldId==="tags"&&e.append(r,"");continue}for(const a of s)e.append(r,a)}else typeof n.value=="string"&&e.set(r,n.value.trim())}}const Jvs="Any";function Xet(e){const t=e.trim();return t===""||t===Jvs}const eys=new Set($Vt.map(e=>e.entityType));function Jet(e){const t=e.trim();return eys.has(t)?t:void 0}function tys(e){const t={};for(const n of e){const r=n.fieldId;if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string").map(a=>a.trim()).filter(a=>!Xet(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?Jet(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(Xet(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=Jet(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const DVt=[{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"}],nys=new Set(DVt.map(e=>e.value));function rys(e){return typeof e=="string"&&(nys.has(e)||e==="custom")}const LVt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function HQ(){return g.useContext(LVt)}function sys(e,t){return e!=="custom"?DVt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${hr(t.from,"MMM d, yyyy")} – ${hr(t.to,"MMM d, yyyy")}`:hr(t.from,"MMM d, yyyy"):"Custom range"}function ays({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:a,onCustomRangeChange:i,tracesBasePath:l,logsBasePath:c}){const u=g.useMemo(()=>JSON.stringify(n),[n]),d=g.useMemo(()=>n,[u]),f=g.useMemo(()=>tys(d),[d]),p=g.useMemo(()=>JSON.stringify(f),[f]),h=sys(t,a),m=g.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:a,setCustomRange:i??(()=>{}),dateRangeLabel:h,filterTokens:d,setFilterTokens:s,dimensionalFilter:f,dimensionalFilterKey:p,tracesBasePath:l,logsBasePath:c}),[t,r,a,i,h,d,s,f,p,l,c]);return o.jsx(LVt.Provider,{value:m,children:e})}const iys=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function oys(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 lys(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 cys(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=HQ(),s=g.useRef(e);s.current=e;const a=g.useRef(n);return a.current=n,o.jsx(I4,{preset:oys(e),onPresetChange:i=>{const l=lys(i);s.current=l,t(l)},dateFrom:n?.from,dateTo:n?.to,onDateChange:(i,l)=>{if(s.current!=="custom")return;const c={...a.current,[l]:i};a.current=c,r(c)},presets:iys})}const Vxe=1440*60*1e3,uys={"24h":Vxe,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function dys(e,t,n){if(e!=="custom"){const r=uys[e]??Vxe;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-Vxe),end:t?.to??new Date(n)}}function Bm(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=HQ(),s=g.useRef(null),a=e==="custom"?`custom:${t?.from?.getTime()??""}:${t?.to?.getTime()??""}`:`preset:${e}`;(!s.current||s.current.key!==a)&&(s.current={key:a,anchor:Date.now()});const i=s.current.anchor,l=g.useMemo(()=>dys(e,t,i),[e,t,i]),c=g.useMemo(()=>({timestamp:l,...n}),[l,r]),u=g.useMemo(()=>`${a}|${r}`,[a,r]);return{datePreset:e,customRange:t,timestamp:l,filters:c,dimensionalFilter:n,filterKey:u}}function FVt(){const e=Qe(),{filters:t,filterKey:n}=Bm();return yt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function UL({href:e,LinkComponent:t="a"}){return o.jsx(oe,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(ec,{})})}function fys({href:e,LinkComponent:t="a"}){return o.jsx(oe,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(GKt,{})})}function pys(e){return e==="agents"||e==="workflows"||e==="tools"}function ett(e,t){if(e.length===0)return"0";const n=e.reduce((r,s)=>{const a=s[t];return r+(typeof a=="number"&&Number.isFinite(a)?a:0)},0);return`${Math.round(n/e.length)}`}function hys(e){const t=e;return typeof t?.tsMs=="number"&&Number.isFinite(t.tsMs)}const mys=[{dataKey:"p50",label:"p50",color:Hp.blue,aggregate:e=>({value:ett(e,"p50"),suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:Hp.yellow,aggregate:e=>({value:ett(e,"p95"),suffix:"avg ms"})}];function Pie({data:e,onPointClick:t}){return e.length===0?o.jsx(Bt.NoData,{message:"No latency data yet"}):o.jsx(OD,{data:e,series:mys,onPointClick:t?n=>hys(n)?t(n):void 0:void 0})}function gys({data:e,isLoading:t,isError:n,onPointClick:r,actions:s}){const a=(e?.agentData.length??0)>0,i=(e?.workflowData.length??0)>0,l=(e?.toolData.length??0)>0,c={agents:a,workflows:i,tools:l},u=a?"agents":i?"workflows":l?"tools":"agents",[d,f]=g.useState("agents"),p=c[d]?d:u,h=typeof s=="function"?s(p):s,m=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),v=e?Object.values(e).filter(Array.isArray).flat().map(b=>b.p50).filter(b=>typeof b=="number"):[],y=v.length>0?`${Math.round(v.reduce((b,x)=>b+x,0)/v.length)}ms`:"—";return o.jsxs(Bt,{children:[o.jsxs(Bt.TopBar,{children:[o.jsx(Bt.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(Bt.Summary,{value:y,label:"Avg p50"}),h?o.jsx(Bt.Actions,{children:h}):null]}),t?o.jsx(Bt.Loading,{}):n?o.jsx(Bt.Error,{message:"Failed to load latency data"}):o.jsx(Bt.Content,{children:m?o.jsxs(yc,{value:p,onValueChange:b=>{pys(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(vc,{children:[o.jsx(Ar,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(Ar,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(Ar,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(fs,{value:"agents",children:o.jsx(Pie,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(fs,{value:"workflows",children:o.jsx(Pie,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(fs,{value:"tools",children:o.jsx(Pie,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Bt.NoData,{message:"No latency data yet"})})]})}function vys(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 yys(e,t){if(t==="1h"){const s=new Date(e);s.setUTCMinutes(0,0,0);const a=new Date(s.getTime()+3600*1e3);return{from:s,to:a}}const n=new Date(e);n.setUTCHours(0,0,0,0);const r=new Date(n.getTime()+1440*60*1e3);return{from:n,to:r}}function zVt(e,t,n,r,s,a,i){if(i){e.set(t,"custom"),e.set(n,i.from.toISOString()),e.set(r,i.to.toISOString());return}if(s==="custom"){e.set(t,"custom"),a?.from&&e.set(n,a.from.toISOString()),a?.to&&e.set(r,a.to.toISOString());return}const l=vys(s);l&&e.set(t,l)}function Ro(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function BVt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function ttt({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const a=new URLSearchParams;a.set(Mw,"branches"),zVt(a,Dw,Lw,Fw,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Gx,i),r.status&&a.set(Qx,r.status),Ro(a,Ol.entityName,r.entityName??n.entityName),Ro(a,Ol.threadId,r.threadId??n.threadId),Ro(a,Ol.resourceId,r.resourceId??n.resourceId),Ro(a,Ol.entityId,n.entityId),Ro(a,Ol.runId,n.runId),Ro(a,Ol.sessionId,n.sessionId),Ro(a,Ol.requestId,n.requestId),Ro(a,Ol.userId,n.userId),Ro(a,Ol.organizationId,n.organizationId),Ro(a,Ol.experimentId,n.experimentId),Ro(a,Ol.serviceName,n.serviceName),Ro(a,Ol.environment,n.environment),BVt(a,Ol.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function bys({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;zVt(a,Jb,ex,tx,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Yx,i),Ro(a,_l.entityName,r.entityName??n.entityName),Ro(a,_l.threadId,r.threadId??n.threadId),Ro(a,_l.resourceId,r.resourceId??n.resourceId),Ro(a,_l.runId,n.runId),Ro(a,_l.sessionId,n.sessionId),Ro(a,_l.requestId,n.requestId),Ro(a,_l.userId,n.userId),Ro(a,_l.organizationId,n.organizationId),Ro(a,_l.experimentId,n.experimentId),Ro(a,_l.serviceName,n.serviceName),Ro(a,_l.environment,n.environment),BVt(a,_l.tags,n.tags),r.status==="error"&&a.append(_l.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function fA(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=HQ(),a=g.useCallback((c={})=>ttt({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=g.useCallback((c={})=>bys({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=yys(u,d);return ttt({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const UVt="1h";async function $ie(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:UVt,filters:n}),s=r.series.find(l=>l.percentile===.5),a=r.series.find(l=>l.percentile===.95);if(!s||!a)return[];const i=new Map(a.points.map(l=>[new Date(l.timestamp).getTime(),l.value]));return s.points.map(l=>{const c=new Date(l.timestamp),u=c.getTime();return{time:c.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}),tsMs:u,p50:Math.round(l.value),p95:Math.round(i.get(u)??0)}})}function xys(){const e=Qe(),{filters:t,filterKey:n}=Bm();return yt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([$ie(e,"mastra_agent_duration_ms",t),$ie(e,"mastra_workflow_duration_ms",t),$ie(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:UVt}}})}const ntt={agents:Ku.AGENT,workflows:Ku.WORKFLOW_RUN,tools:Ku.TOOL};function wys(){const{data:e,isLoading:t,isError:n}=xys(),{getTracesHref:r,getBucketTracesHref:s}=fA(),{Link:a}=cn(),i=es();return o.jsx(gys,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:ntt[l]},c.tsMs,"1h"))},actions:l=>o.jsx(UL,{href:r({rootEntityType:ntt[l]}),LinkComponent:a})})}function Sys(e){return e==="threads"||e==="resources"}function Mie(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function kys({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("threads"),c=e.data?.map(y=>({...y,key:y.threadId}))??[],u=t.data?.map(y=>({...y,key:y.resourceId}))??[],d=c.length>0,f=u.length>0,p=e.data?.reduce((y,b)=>y+b.runs,0)??0,h=t.data?.reduce((y,b)=>y+b.threadCount,0)??0,m=i==="threads"?e:t,v=typeof s=="function"?s(i):s;return o.jsxs(Bt,{children:[o.jsxs(Bt.TopBar,{children:[o.jsx(Bt.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&o.jsx(Bt.Summary,{value:p.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&o.jsx(Bt.Summary,{value:h.toLocaleString(),label:"Total threads"}),v?o.jsx(Bt.Actions,{children:v}):null]}),m.isLoading?o.jsx(Bt.Loading,{}):m.isError?o.jsx(Bt.Error,{message:"Failed to load memory data"}):o.jsx(Bt.Content,{children:o.jsxs(yc,{defaultTab:"threads",value:i,onValueChange:y=>{Sys(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(vc,{children:[o.jsx(Ar,{value:"threads",children:"Threads"}),o.jsx(Ar,{value:"resources",children:"Resources"})]}),o.jsx(fs,{value:"threads",children:d?o.jsxs(be,{columns:"auto auto auto auto auto",...Rxe,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(be.RowHeaderCell,{className:"text-ui-sm",children:Mie(y.threadId)}),o.jsx(be.NumberCell,{children:y.resourceId?Mie(y.resourceId):"—"}),o.jsx(be.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(be.NumberCell,{children:y.tokens>0?nl(y.tokens):"—"}),o.jsx(be.NumberCell,{children:y.cost!=null?Vp(y.cost,y.costUnit):"—"})]});return b?o.jsx(be.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(be.RowStatic,{children:x},y.key)})]}):o.jsx(Bt.NoData,{message:"No thread activity yet"})}),o.jsx(fs,{value:"resources",children:f?o.jsxs(be,{columns:"auto auto auto auto",...Rxe,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(be.RowHeaderCell,{className:"text-ui-sm",children:Mie(y.resourceId)}),o.jsx(be.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(be.NumberCell,{children:y.tokens>0?nl(y.tokens):"—"}),o.jsx(be.NumberCell,{children:y.cost!=null?Vp(y.cost,y.costUnit):"—"})]});return b?o.jsx(be.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(be.RowStatic,{children:x},y.key)})]}):o.jsx(Bt.NoData,{message:"No resource activity yet"})})]})})]})}const Die=20;function Oys(){const e=Qe(),{filters:t,filterKey:n}=Bm();return yt({queryKey:["metrics","top-active-threads",n],queryFn:async()=>{const r={groupBy:["threadId","resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count",limit:Die}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:Die}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:Die})]),l=new Map,c=d=>dA(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.threadId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.threadId).map(d=>{const f=d.dimensions.threadId,p=l.get(f);return{threadId:f,resourceId:d.dimensions.resourceId??null,runs:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}const Lie=20;function _ys(){const e=Qe(),{filters:t,filterKey:n}=Bm();return yt({queryKey:["metrics","top-resources-by-threads",n],queryFn:async()=>{const r={groupBy:["resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",limit:Lie}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:Lie}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:Lie})]),l=new Map,c=d=>dA(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.resourceId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.resourceId).map(d=>{const f=d.dimensions.resourceId,p=l.get(f);return{resourceId:f,threadCount:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}function Cys(){const e=Oys(),t=_ys(),{getTracesHref:n}=fA(),{Link:r}=cn();return o.jsx(kys,{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 qL({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:a}){const i=t!=null;return o.jsxs(Xr,{children:[o.jsx(Xr.Label,{children:e}),o.jsx(Xr.Value,{className:i?void 0:"invisible",children:i?t:"—"}),a?o.jsx(Xr.Error,{}):s?o.jsx(Xr.Loading,{}):i?r!=null?o.jsx(Xr.Change,{changePct:r,prevValue:n}):o.jsx(Xr.NoChange,{}):o.jsx(Xr.NoData,{})]})}function Eys(){const e=Qe(),{filters:t,filterKey:n}=Bm();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 Tys(){const e=Qe(),{filters:t,filterKey:n}=Bm();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 jys(){const e=Qe(),{filters:t,filterKey:n}=Bm();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 Nys(){const e=Qe(),{filters:t,filterKey:n}=Bm();return yt({queryKey:["metrics","total-tokens-kpi",n],queryFn:async()=>{const[r,s]=await Promise.all([e.getMetricAggregate({name:["mastra_model_total_input_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"}),e.getMetricAggregate({name:["mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"})]),a=r.value!=null||s.value!=null,i=r.previousValue!=null||s.previousValue!=null,l=(r.value??0)+(s.value??0),c=(r.previousValue??0)+(s.previousValue??0),u=i&&c>0?(l-c)/c*100:null;return{value:a?l:null,previousValue:i?c:null,changePercent:u}}})}function Iys(){const{data:e,isLoading:t,isError:n}=FVt();return o.jsx(qL,{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 Ays(){const{data:e,isLoading:t,isError:n}=jys();return o.jsx(qL,{label:"Total Model Cost",value:e?.cost!=null?Vp(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?Vp(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function Rys(){const{data:e,isLoading:t,isError:n}=Nys();return o.jsx(qL,{label:"Total Tokens",value:e?.value!=null?nl(e.value):null,prevValue:e?.previousValue!=null?nl(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Pys(){const{data:e,isLoading:t,isError:n}=Tys();return o.jsx(qL,{label:"Total Threads",value:e?.value!=null?nl(e.value):null,prevValue:e?.previousValue!=null?nl(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function $ys(){const{data:e,isLoading:t,isError:n}=Eys();return o.jsx(qL,{label:"Total Resources",value:e?.value!=null?nl(e.value):null,prevValue:e?.previousValue!=null?nl(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Mys({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>Dys(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(CAe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(OAe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function Dys(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 Lys({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const i=!!e&&e.length>0;return o.jsxs(Bt,{children:[o.jsxs(Bt.TopBar,{children:[o.jsx(Bt.TitleAndDescription,{title:"Model Usage & Cost",description:"Token consumption by model."}),i&&(()=>{const l=e.reduce((d,f)=>d+(f.cost??0),0),c=new Set;for(const d of e)d.cost!=null&&d.costUnit&&c.add(d.costUnit);let u;return c.size===0?u=l>0?Vp(l):"—":c.size===1?u=l>0?Vp(l,[...c][0]):"—":u="Mixed",o.jsx(Bt.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(Bt.Actions,{children:s}):null]}),t?o.jsx(Bt.Loading,{}):n?o.jsx(Bt.Error,{message:"Failed to load model usage data"}):o.jsx(Bt.Content,{children:i?o.jsxs(be,{columns:"auto auto auto auto auto auto",...Rxe,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{sticky:"start",children:"Model"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(be.RowHeaderCell,{className:"text-ui-sm",children:l.model}),o.jsx(be.NumberCell,{children:l.input}),o.jsx(be.NumberCell,{children:l.output}),o.jsx(be.NumberCell,{children:l.cacheRead}),o.jsx(be.NumberCell,{children:l.cacheWrite}),o.jsx(be.NumberCell,{highlight:!0,children:l.cost!=null?Vp(l.cost,l.costUnit):"—"})]});return c?o.jsx(be.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(be.RowStatic,{children:u},l.model)})]}):o.jsx(Bt.NoData,{message:"No model usage data yet"})})]})}function Fys(){const e=Qe(),{filters:t,filterKey:n}=Bm();return yt({queryKey:["metrics","model-usage-cost",n],queryFn:async()=>{const[r,s,a,i]=await Promise.all(["mastra_model_total_input_tokens","mastra_model_total_output_tokens","mastra_model_input_cache_read_tokens","mastra_model_input_cache_write_tokens"].map(d=>e.getMetricBreakdown({name:[d],groupBy:["model"],aggregation:"sum",orderDirection:"DESC",filters:t})));if(!r||!s||!a||!i)return[];const l=new Map,c=d=>dA(l,d,()=>({input:0,output:0,cacheRead:0,cacheWrite:0,cost:null,costUnit:null})),u=(d,f)=>{f.estimatedCost!=null&&(d.cost=(d.cost??0)+f.estimatedCost,f.costUnit&&(d.costUnit=f.costUnit))};for(const d of r.groups){const f=d.dimensions.model??"unknown",p=c(f);p.input=d.value,u(p,d)}for(const d of s.groups){const f=d.dimensions.model??"unknown",p=c(f);p.output=d.value,u(p,d)}for(const d of a.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheRead=d.value}for(const d of i.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheWrite=d.value}return Array.from(l.entries()).map(([d,f])=>({model:d,input:nl(f.input),output:nl(f.output),cacheRead:nl(f.cacheRead),cacheWrite:nl(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function zys(){const{data:e,isLoading:t,isError:n}=Fys(),{getTracesHref:r}=fA(),{Link:s}=cn();return o.jsx(Lys,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:Ku.AGENT}),actions:o.jsx(UL,{href:r({rootEntityType:Ku.AGENT}),LinkComponent:s})})}function Bys(e){return e==="tokens"||e==="cost"}function Uys({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("tokens"),c=e??[],u=c.length>0,d=c.reduce((b,x)=>b+x.total,0),f=c.filter(b=>b.cost!=null&&b.cost>0),p=new Set(f.map(b=>b.costUnit??"usd")),h=p.size<=1,m=h?[...p][0]??"usd":null,v=h?f.reduce((b,x)=>b+(x.cost??0),0):0,y=h&&v>0;return o.jsxs(Bt,{children:[o.jsxs(Bt.TopBar,{children:[o.jsx(Bt.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&y?o.jsx(Bt.Summary,{value:Vp(v,m),label:"Total cost"}):o.jsx(Bt.Summary,{value:nl(d),label:"Total tokens"})),u&&s?o.jsx(Bt.Actions,{children:s}):null]}),t?o.jsx(Bt.Loading,{}):n?o.jsx(Bt.Error,{message:"Failed to load token usage data"}):o.jsx(Bt.Content,{children:u?o.jsxs(yc,{defaultTab:"tokens",value:i,onValueChange:b=>{Bys(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(vc,{children:[o.jsx(Ar,{value:"tokens",children:"Tokens"}),o.jsx(Ar,{value:"cost",children:"Cost"})]}),o.jsx(fs,{value:"tokens",children:o.jsx(VN,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:Hp.blueDark},{label:"Output",color:Hp.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:nl})}),o.jsx(fs,{value:"cost",children:y?o.jsx(VN,{LinkComponent:a,data:f.slice().sort((b,x)=>(x.cost??0)-(b.cost??0)).map(b=>({name:b.name,values:[b.cost],href:r?.(b)})),segments:[{label:"Cost",color:Hp.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>Vp(b,m)}):o.jsx(Bt.NoData,{message:"No cost data yet"})})]}):o.jsx(Bt.NoData,{message:"No token usage data yet"})})]})}function qys(){const e=Qe(),{filters:t,filterKey:n}=Bm();return yt({queryKey:["metrics","token-usage-by-agent",n],queryFn:async()=>{const r={groupBy:["entityName"],aggregation:"sum",orderDirection:"DESC",filters:t},[s,a]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"]}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"]})]),i=new Map,l=u=>dA(i,u,()=>({input:0,output:0,cost:null,costUnit:null})),c=(u,d)=>{d.estimatedCost!=null&&(u.cost=(u.cost??0)+d.estimatedCost,d.costUnit&&(u.costUnit=d.costUnit))};for(const u of s.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.input=u.value,c(f,u)}for(const u of a.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.output=u.value,c(f,u)}return Array.from(i.entries()).map(([u,d])=>({name:u,input:d.input,output:d.output,total:d.input+d.output,cost:d.cost,costUnit:d.costUnit})).sort((u,d)=>d.total-u.total)}})}function Vys(){const{data:e,isLoading:t,isError:n}=qys(),{getTracesHref:r}=fA(),{Link:s}=cn();return o.jsx(Uys,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:Ku.AGENT,entityName:a.name}),actions:o.jsx(UL,{href:r({rootEntityType:Ku.AGENT}),LinkComponent:s})})}function Hxe(e,t=nl){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const Hys=[{dataKey:"input",label:"Input tokens",color:Hp.blue,aggregate:Hxe("input")},{dataKey:"output",label:"Output tokens",color:Hp.yellow,aggregate:Hxe("output")}];function Wys(e){return e==="tokens"||e==="cost"}function Zys({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[a,i]=g.useState("tokens"),l=e??[],c=l.map(k=>({...k})),u=l.length>0,d=l.reduce((k,_)=>k+_.total,0),f=l.filter(k=>k.cost!=null&&k.cost>0),p=f.map(k=>({...k})),h=new Set(f.map(k=>k.costUnit).filter(k=>!!k)),m=h.size===1&&f.every(k=>k.costUnit!=null),v=m?[...h][0]??null:null,y=m?f.reduce((k,_)=>k+(_.cost??0),0):0,b=m&&y>0,x=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",S=[{dataKey:"cost",label:"Cost",color:Hp.purple,aggregate:Hxe("cost",k=>Vp(k,v))}];return o.jsxs(Bt,{children:[o.jsxs(Bt.TopBar,{children:[o.jsx(Bt.TitleAndDescription,{title:"Token usage over time",description:x}),u&&(a==="cost"&&b?o.jsx(Bt.Summary,{value:Vp(y,v),label:"Total cost"}):o.jsx(Bt.Summary,{value:nl(d),label:"Total tokens"})),u&&s?o.jsx(Bt.Actions,{children:s}):null]}),n?o.jsx(Bt.Loading,{}):r?o.jsx(Bt.Error,{message:"Failed to load token usage timeline"}):o.jsx(Bt.Content,{children:u?o.jsxs(yc,{defaultTab:"tokens",value:a,onValueChange:k=>{Wys(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(vc,{children:[o.jsx(Ar,{value:"tokens",children:"Tokens"}),o.jsx(Ar,{value:"cost",children:"Cost"})]}),o.jsx(fs,{value:"tokens",children:o.jsx(OD,{data:c,series:Hys})}),o.jsx(fs,{value:"cost",children:b?o.jsx(OD,{data:p,series:S}):o.jsx(Bt.NoData,{message:"No cost data yet"})})]}):o.jsx(Bt.NoData,{message:"No token usage data yet"})})]})}function Gys(e){return e==="24h"?"1h":"1d"}function Qys(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 rtt(e,t,n){for(const r of t?.points??[]){const s=new Date(r.timestamp).getTime();if(!Number.isFinite(s))continue;const a=e.get(s)??{tsMs:s,input:0,output:0,cost:null,costUnits:new Set,hasUnknownCostUnit:!1};a[n]+=r.value,r.estimatedCost!=null&&(a.cost=(a.cost??0)+r.estimatedCost,t?.costUnit?a.costUnits.add(t.costUnit):a.hasUnknownCostUnit=!0),e.set(s,a)}}function Yys(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function Kys(){const e=Qe(),{datePreset:t,filters:n,filterKey:r}=Bm(),s=Gys(t);return yt({queryKey:["metrics","token-usage-timeseries",r,s],queryFn:async()=>{const[a,i]=await Promise.all([e.getMetricTimeSeries({name:["mastra_model_total_input_tokens"],interval:s,aggregation:"sum",filters:n}),e.getMetricTimeSeries({name:["mastra_model_total_output_tokens"],interval:s,aggregation:"sum",filters:n})]),l=new Map;return rtt(l,a.series[0],"input"),rtt(l,i.series[0],"output"),{data:Array.from(l.values()).sort((u,d)=>u.tsMs-d.tsMs).map(u=>{const d=new Date(u.tsMs);return{time:Qys(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:Yys(u)}}),interval:s}}})}function Xys(){const{data:e,isLoading:t,isError:n}=Kys(),{getTracesHref:r}=fA(),{Link:s}=cn();return o.jsx(Zys,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(UL,{href:r(),LinkComponent:s})})}function Fie({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(VN,{LinkComponent:r,data:e.map(s=>{const a=n?.(s),i=t?.(s);return a?{name:s.name,values:[s.completed,s.errors],hrefs:[i,a]}:{name:s.name,values:[s.completed,s.errors],href:i}}),segments:[{label:"Completed",color:Hp.blueDark},{label:"Errors",color:Hp.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:nl})}function Jys({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:a,LinkComponent:i}){const[l,c]=g.useState("agents"),u=typeof a=="function"?a(l):a,d=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),f=e?[...e.agentData,...e.workflowData,...e.toolData].reduce((m,v)=>m+v.completed+v.errors,0):0,p=m=>r?v=>r(m,v):void 0,h=m=>s?v=>s(m,v):void 0;return o.jsxs(Bt,{children:[o.jsxs(Bt.TopBar,{children:[o.jsx(Bt.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(Bt.Summary,{value:nl(f),label:"Total runs"}),u?o.jsx(Bt.Actions,{children:u}):null]}),t?o.jsx(Bt.Loading,{}):n?o.jsx(Bt.Error,{message:"Failed to load trace volume data"}):o.jsx(Bt.Content,{children:d?o.jsxs(yc,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(vc,{children:[o.jsx(Ar,{value:"agents",children:"Agents"}),o.jsx(Ar,{value:"workflows",children:"Workflows"}),o.jsx(Ar,{value:"tools",children:"Tools"})]}),o.jsx(fs,{value:"agents",children:e.agentData.length>0?o.jsx(Fie,{data:e.agentData,rowHrefs:p("agents"),errorHrefs:h("agents"),LinkComponent:i}):o.jsx(Bt.NoData,{message:"No agent data yet"})}),o.jsx(fs,{value:"workflows",children:e.workflowData.length>0?o.jsx(Fie,{data:e.workflowData,rowHrefs:p("workflows"),errorHrefs:h("workflows"),LinkComponent:i}):o.jsx(Bt.NoData,{message:"No workflow data yet"})}),o.jsx(fs,{value:"tools",children:e.toolData.length>0?o.jsx(Fie,{data:e.toolData,rowHrefs:p("tools"),errorHrefs:h("tools"),LinkComponent:i}):o.jsx(Bt.NoData,{message:"No tool data yet"})})]}):o.jsx(Bt.NoData,{message:"No trace volume data yet"})})]})}async function zie(e,t,n){const r=await e.getMetricBreakdown({name:[t],groupBy:["entityName","status"],aggregation:"count",orderDirection:"DESC",filters:n}),s=new Map;for(const a of r.groups){const i=a.dimensions.entityName??"unknown",l=a.dimensions.status??"ok",c=dA(s,i,()=>({completed:0,errors:0}));l==="error"?c.errors+=a.value:c.completed+=a.value}return Array.from(s.entries()).map(([a,i])=>({name:a,...i})).sort((a,i)=>i.completed+i.errors-(a.completed+a.errors))}function ebs(){const e=Qe(),{filters:t,filterKey:n}=Bm();return yt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([zie(e,"mastra_agent_duration_ms",t),zie(e,"mastra_workflow_duration_ms",t),zie(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const e8={agents:Ku.AGENT,workflows:Ku.WORKFLOW_RUN,tools:Ku.TOOL};function tbs(){const{data:e,isLoading:t,isError:n}=ebs(),{getTracesHref:r,getLogsHref:s}=fA(),{Link:a}=cn();return o.jsx(Jys,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:e8[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:e8[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(UL,{href:r({rootEntityType:e8[i]}),LinkComponent:a}),o.jsx(fys,{href:s({rootEntityType:e8[i],status:"error"}),LinkComponent:a})]})})}const Bie="period",t8="dateFrom",n8="dateTo";function nbs(){const[e,t]=hi(),n=e.get(Bie),r=rys(n)?n:"24h",s=g.useMemo(()=>{if(r!=="custom")return;const d=h=>{if(!h)return;const m=new Date(h);return Number.isNaN(m.getTime())?void 0:m},f=d(e.get(t8)),p=d(e.get(n8));if(!(!f&&!p))return{from:f,to:p}},[r,e.toString()]),a=g.useMemo(()=>Yvs(e),[e.toString()]),i=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d==="24h"?p.delete(Bie):p.set(Bie,d),d!=="custom"&&(p.delete(t8),p.delete(n8)),p},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d?.from?p.set(t8,d.from.toISOString()):p.delete(t8),d?.to?p.set(n8,d.to.toISOString()):p.delete(n8),p},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return Xvs(p,d),p},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,Gvs(e)))return;const d=MVt();d&&t(f=>{const p=new URLSearchParams(f);for(const[h,m]of d)p.append(h,m);return p},{replace:!0})},[]),o.jsx(ays,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(rbs,{})})}function rbs(){const[e]=hi(),{error:t,isLoading:n}=FVt(),{filterTokens:r,setFilterTokens:s}=HQ(),[a,i]=g.useState(),{supportsMetrics:l,isInMemory:c,isLoading:u}=Qqt(),{data:d,isLoading:f}=RAe(),{data:p,isLoading:h}=NAe(),{data:m,isLoading:v}=AAe(),{data:y,isLoading:b}=IAe(),x=g.useMemo(()=>Qvs({availableTags:d??[],availableEntityNames:p??[],availableServiceNames:m??[],availableEnvironments:y??[],loading:{tags:f,entityNames:h,serviceNames:v,environments:b}}),[d,p,m,y,f,h,v,b]),[S,k]=g.useState(()=>MVt()!==null),_=g.useCallback(()=>{Wvs(e),k(!0),Be.success("Filters setting for Metrics saved")},[e]),C=g.useCallback(()=>{Zvs(),k(!1),Be.success("Filters setting for Metrics cleared up")},[]),T=g.useCallback(()=>{s([])},[s]),E=g.useCallback(()=>{const N=r.map(I=>{const A=x.find(R=>R.id===I.fieldId);return A?A.kind==="text"?{fieldId:I.fieldId,value:""}:A.kind==="pick-multi"?A.multi?{fieldId:I.fieldId,value:[]}:{fieldId:I.fieldId,value:"Any"}:A.kind==="multi-select"?{fieldId:I.fieldId,value:[]}:I:I});s(N)},[x,r,s]);return t&&Ss(t)?o.jsx(ir,{children:o.jsx(Gs,{})}):t&&ks(t)?o.jsx(ir,{children:o.jsx(Fs,{resource:"metrics"})}):t?o.jsx(ir,{children:o.jsx(Ui,{title:"Failed to load metrics",message:t.message})}):o.jsxs(Vt,{width:"wide",height:"full",children:[o.jsxs(Vt.TopArea,{children:[o.jsx(Vt.Row,{children:o.jsxs(Vt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(cys,{}),o.jsx(EAe,{fields:x,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(Mys,{isLoading:n,filterFields:x,filterTokens:r,onFilterTokensChange:s,onClear:E,onRemoveAll:T,onSave:_,onRemoveSaved:S?C:void 0,autoFocusFilterFieldId:a})]}),u?null:l?o.jsxs("div",{className:"grid content-start gap-8 pb-10",children:[c&&o.jsx(Wn,{variant:"info",title:"Metrics are not persisted",children:o.jsx(Wn.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(Fxe,{children:[o.jsx(Iys,{}),o.jsx(Ays,{}),o.jsx(Rys,{}),o.jsx(Pys,{}),o.jsx($ys,{})]}),o.jsxs(Fxe,{children:[o.jsx(zys,{}),o.jsx(Vys,{}),o.jsx(Xys,{}),o.jsx(Cys,{}),o.jsx(tbs,{}),o.jsx(wys,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Er,{iconSlot:o.jsx(Mc,{}),titleSlot:"Metrics are not available with your current storage",descriptionSlot:"Metrics require ClickHouse, DuckDB, Postgres v-next, Spanner, or in-memory storage for observability. Other relational databases (LibSQL, MSSQL) and document stores (MongoDB) do not support metrics collection. To enable metrics on an existing project, switch the observability storage in the Mastra configuration.",actionSlot:o.jsxs(oe,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(Yr,{})]})})})]})}const sbs=50;function abs(){const{paths:e}=cn(),{isCmsAvailable:t}=hS(),[n,r]=g.useState(""),[s,a]=g.useState(0),{data:i,isLoading:l,error:c,isPlaceholderData:u}=uBt({page:s,perPage:sbs}),d=i?.promptBlocks??[],f=i?.hasMore??!1,p=g.useCallback(()=>{u||a(v=>v+1)},[u]),h=g.useCallback(()=>{u||a(v=>Math.max(0,v-1))},[u]),m=g.useCallback(v=>{r(v),a(0)},[]);return c&&Ss(c)?o.jsx(ir,{children:o.jsx(Gs,{})}):c&&ks(c)?o.jsx(ir,{children:o.jsx(Fs,{resource:"prompt blocks"})}):c?o.jsx(ir,{children:o.jsx(Ui,{title:"Failed to load prompt blocks",message:c.message})}):d.length===0&&!l&&s===0?o.jsx(ir,{children:o.jsx(Oss,{})}):o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsxs(Vt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(ah,{onSearch:m,label:"Filter prompts",placeholder:"Filter by name or description"})}),t&&o.jsxs(oe,{as:wi,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(Or,{}),"Create Prompt"]})]})}),o.jsx(kss,{promptBlocks:d,isLoading:l,search:n,currentPage:s,hasMore:f,onNextPage:p,onPrevPage:h})]})}function ibs(){return o.jsx(Vt,{width:"narrow",children:o.jsx(Vt.MainArea,{children:o.jsx(crs,{children:o.jsx(gxe,{})})})})}const obs=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:hYt,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:jlt,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Yr,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:u0e,href:"https://discord.gg/BTYqqHKUrf",external:!0},{title:"Share with your team",description:"Running Mastra Studio locally? Deploy to the cloud so your team can collaborate.",icon:$lt,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:Nlt,href:"https://mastra.ai/contact?ref=studio",external:!0}];function lbs(){return o.jsx(Vt,{width:"narrow",children:o.jsx(Vt.MainArea,{children:o.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:obs.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(Yr,{className:"text-icon3 ml-auto h-3.5 w-3.5 opacity-0 transition-opacity group-hover:opacity-100"})]}),o.jsx("p",{className:"text-ui-sm text-text3 leading-relaxed",children:e.description})]},e.href))})})})}function cbs(){const{data:e={},isLoading:t,error:n}=oh(),[r,s]=g.useState(""),[a,i]=g.useState("all");if(n&&Ss(n))return o.jsx(ir,{children:o.jsx(Gs,{})});if(n&&ks(n))return o.jsx(ir,{children:o.jsx(Fs,{resource:"scorers"})});if(n)return o.jsx(ir,{children:o.jsx(Ui,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(ir,{children:o.jsx(d7r,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx(p7r,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(u7r,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}function ubs(){const{scorerId:e}=mr(),[t,n]=hi(),r=t.get("scoreId")??void 0,[s,a]=g.useState(r),[i,l]=g.useState(!1),c=es(),[u,d]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:f,error:p}=V9r(e),{data:h={},isLoading:m,error:v}=Dm(),{isLoading:y,error:b}=Wy(),{data:x=[],isLoading:S,error:k,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:T}=q9r({scorerId:e,entityId:u?.value==="all"?void 0:u?.value,entityType:u?.type==="ALL"?void 0:u?.type}),E=g.useMemo(()=>f?.agentIds?.filter($=>h[$]).map($=>({value:$,label:h[$].name,type:"AGENT"}))||[],[f?.agentIds,h]),N=g.useMemo(()=>f?.workflowIds?.map($=>({value:$,label:$,type:"WORKFLOW"}))||[],[f?.workflowIds]),I=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...E,...N],[E,N]),A=t.get("entity")??"all",R=I.find($=>$.value===A);R&&R.value!==u?.value&&d(R),g.useEffect(()=>{if(p){const $=p instanceof Error?p.message:"Failed to load scorer";Be.error(`Error loading scorer: ${$}`)}},[p]),g.useEffect(()=>{if(v){const $=v instanceof Error?v.message:"Failed to load agents";Be.error(`Error loading agents: ${$}`)}},[v]),g.useEffect(()=>{if(b){const $=b instanceof Error?b.message:"Failed to load workflows";Be.error(`Error loading workflows: ${$}`)}},[b]);const L=$=>{$?.value&&n(q=>{const Z=new URLSearchParams(q);return Z.set("entity",$.value),Z})};g.useEffect(()=>{const $=t.get("scoreId")??void 0;if($===s)return;if(!$){a(void 0);return}x.find(Z=>Z.id===$)&&a($)},[t,x]);const D=g.useCallback($=>{a($||void 0),n(q=>{const Z=new URLSearchParams(q);return $?Z.set("scoreId",$):Z.delete("scoreId"),Z})},[n]);if(!f)return null;const F=Ss(p)||Ss(v)||Ss(b),H=p&&ks(p),B=!F&&!H&&(p||v||b),z=!S&&x.length===0,V=u?.value!=="all",M=f?.scorer?.source==="stored"?o.jsx($y,{owner:"scorer-detail",children:o.jsxs(oe,{variant:"default",as:wi,to:`/cms/scorers/${e}/edit`,size:"sm",children:[o.jsx(um,{})," Edit"]})}):null,G=e?o.jsx(FAe,{open:i,onOpenChange:l,initialScorerIds:[e],onSuccess:$=>{c(`/experiments/${$}`)}}):null;if(F||H||B||z&&!V){const $=(p instanceof Error?p.message:void 0)??(v instanceof Error?v.message:void 0)??(b instanceof Error?b.message:void 0)??"An unexpected error occurred";return o.jsxs(Vt,{width:"wide",height:"full",className:"grid-rows-[1fr]",children:[M,o.jsx(Vt.MainArea,{isCentered:!0,children:F?o.jsx(Gs,{}):H?o.jsx(Fs,{resource:"scorers"}):B?o.jsx(Ui,{title:"Failed to load scorer",message:$}):o.jsx($9r,{onRunExperiment:()=>l(!0)})}),G]})}return o.jsxs(Vt,{width:"wide",height:"full",children:[M,o.jsx(Vt.TopArea,{children:o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx(D9r,{selectedEntity:u,entityOptions:I,onEntityChange:L,onReset:()=>{n($=>{const q=new URLSearchParams($);return q.set("entity","all"),q})},isLoading:S||m||y}),o.jsxs(oe,{variant:"primary",onClick:()=>l(!0),children:[o.jsx(Dc,{}),"Run Experiment"]})]})}),o.jsx(P9r,{scores:x,isLoading:S,selectedScoreId:s,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:T,onScoreClick:D,errorMsg:k?.message}),G]})}const dbs=Ii("flex min-w-0 flex-col",{variants:{variant:{default:"gap-3 sm:flex-row sm:items-center sm:justify-between",factory:"gap-2 px-4 py-3 lg:flex-row lg:items-center lg:justify-between lg:gap-4"}},defaultVariants:{variant:"default"}}),fbs=Ii("flex min-w-0 flex-col",{variants:{variant:{default:"",factory:"gap-0.5"}},defaultVariants:{variant:"default"}}),stt=Ii("",{variants:{variant:{default:"text-sm font-medium",factory:"text-ui-md leading-ui-md text-neutral5"}},defaultVariants:{variant:"default"}}),pbs=Ii("flex flex-col gap-0.5",{variants:{variant:{default:"text-sm text-neutral3",factory:"text-ui-sm text-neutral3"}},defaultVariants:{variant:"default"}});function hbs({label:e,description:t,htmlFor:n,variant:r,className:s,children:a}){return o.jsxs("div",{className:K(dbs({variant:r}),s),"data-slot":"settings-row",children:[o.jsxs("div",{className:fbs({variant:r}),children:[n?o.jsx(Mt,{htmlFor:n,className:stt({variant:r}),children:e}):o.jsx("span",{className:stt({variant:r}),children:e}),t&&o.jsx("div",{className:pbs({variant:r}),children:t})]}),a]})}const qVt=[{value:"dark",label:"Dark",Icon:pXt},{value:"light",label:"Light",Icon:MJt},{value:"system",label:"System",Icon:Wlt}],mbs=e=>qVt.some(t=>t.value===e);function gbs({option:e}){const{Icon:t}=e;return o.jsxs("span",{className:"inline-flex max-w-full min-w-0 items-center gap-2",children:[o.jsx(t,{"aria-hidden":"true",className:"h-4 w-4 shrink-0 opacity-70"}),o.jsx("span",{className:"min-w-0 truncate",children:e.label})]})}const vbs=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=SH(),{theme:r,setTheme:s}=K_();return o.jsx(Vt,{width:"narrow",children:o.jsxs(Vt.MainArea,{className:"mt-6 flex flex-col gap-5",children:[o.jsx(qbe,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(hbs,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(ha,{value:r,onValueChange:a=>{mbs(a)&&s(a)},children:[o.jsx(ga,{id:"theme",className:"w-full sm:w-48",children:o.jsx(ma,{className:"inline-flex max-w-full min-w-0 items-center"})}),o.jsx(va,{children:qVt.map(a=>o.jsx(Nr,{value:a.value,children:o.jsx(gbs,{option:a})},a.value))})]})})}),o.jsx(qbe,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(F3t,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function ybs(){const[e]=hi(),t=es(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(RVt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}function bbs(e){return e.replace(/\/$/,"").split("/").pop()}function WQ({children:e,className:t}){return o.jsx("div",{className:K("border border-border1 rounded-lg mt-12 py-8 lg:min-h-[25rem] transition-height px-4 lg:px-12",t),children:e})}function xbs({templates:e,linkComponent:t,className:n,isLoading:r}){const s=t||"a";return r?o.jsx("div",{className:K("grid gap-y-4",n),children:Array.from({length:5}).map((a,i)=>o.jsx("div",{className:"bg-surface3 h-16 animate-pulse rounded-lg"},i))}):o.jsx("div",{className:K("grid gap-y-4",n),children:e.map(a=>{const i=a?.agents||a?.tools||a?.networks||a?.workflows||a?.mcp;return o.jsxs("article",{className:K("border border-border1 rounded-lg overflow-hidden w-full grid grid-cols-[1fr_auto] bg-surface3 transition-colors hover:bg-surface4"),children:[o.jsxs(s,{to:`/templates/${a.slug}`,className:K("grid [&:hover_p]:text-neutral5",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":a.imageURL}),children:[a.imageURL&&o.jsx("div",{className:K("overflow-hidden"),children:o.jsx("div",{className:"thumb transition-scale h-full w-full bg-cover duration-150",style:{backgroundImage:`url(${a.imageURL})`}})}),o.jsxs("div",{className:K("grid py-3 px-6 w-full gap-0.5","[&_svg]:w-[1em] [&_svg]:h-[1em] [&_svg]:text-neutral3"),children:[o.jsx("h2",{className:"text-ui-lg text-neutral5",children:a.title}),o.jsx("p",{className:"text-ui-md text-neutral4 transition-colors duration-500",children:a.description}),o.jsxs("div",{className:"text-neutral3 text-ui-md mt-3 hidden flex-wrap items-center gap-4 2xl:flex",children:[i&&o.jsxs("ul",{className:K("flex gap-4 text-ui-md text-neutral3 m-0 p-0 list-none","[&>li]:flex [&>li]:items-center [&>li]:gap-0.5 text-neutral4"),children:[a?.agents&&a.agents.length>0&&o.jsxs("li",{children:[o.jsx(Ti,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(Ff,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(Glt,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(aI,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(OC,{})," ",a.mcp.length]})]}),i&&a.supportedProviders&&o.jsx("small",{children:"|"}),o.jsx("div",{className:"text-neutral3 flex items-center gap-4",children:a.supportedProviders.map(l=>o.jsx("span",{className:"",children:l},l))})]})]})]}),o.jsx("a",{href:a.githubUrl,className:K("group items-center gap-2 text-ui-md ml-auto pr-4 hidden","lg:flex"),target:"_blank",rel:"noopener noreferrer",children:o.jsxs("span",{className:"bg-surface1 group-hover:bg-surface2 text-neutral3 group-hover:text-neutral5 flex items-center gap-2 rounded px-2 py-1 transition-colors",children:[o.jsx(HZ,{})," ",bbs(a.githubUrl)]})})]},a.slug)})})}function wbs({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:s,onProviderChange:a,searchTerm:i,onSearchChange:l,onReset:c,className:u,isLoading:d}){return d?o.jsxs("div",{className:K("h-[6.5rem] flex items-center gap-8","[&>div]:bg-surface3 [&>div]:w-48 [&>div]:h-8 [&>div]:animate-pulse",u),children:[o.jsx("div",{})," ",o.jsx("div",{})," ",o.jsx("div",{})]}):o.jsxs("div",{className:K("flex flex-wrap mx-auto sticky top-0 gap-4 bg-surface2 py-8",u),children:[o.jsx(m_,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(Pc,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(Pc,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(oe,{onClick:c,children:["Reset ",o.jsx(or,{})]})]})}function Sbs(){const{data:e,isLoading:t}=ynr(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[a,i]=g.useState("all"),[l,c]=g.useState("all"),[u,d]=g.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(x=>{f.push({value:x,label:x})});const p=[{value:"all",label:"Any provider"}];(s||[]).forEach(x=>{p.push({value:x,label:x})});const h=(x,S)=>{S==="tag"?i(x):S==="provider"&&c(x)},m=x=>{d(x)},v=()=>{i("all"),c("all"),d("")},y=n.filter(x=>!(u&&!x.title.toLowerCase().includes(u)&&!x.description.toLowerCase().includes(u)||a!=="all"&&!x.tags.includes(a)||l!=="all"&&!x.supportedProviders.includes(l))),b=u||a!=="all"||l!=="all";return o.jsxs(_s,{children:[o.jsx(iSe,{children:o.jsxs(ebt,{children:[o.jsx(He,{children:o.jsx(oy,{})}),"Templates"]})}),o.jsxs("div",{className:K("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(wbs,{selectedTag:a,onTagChange:x=>h(x,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:x=>h(x,"provider"),providerOptions:p,searchTerm:u,onSearchChange:m,onReset:b?v:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(xbs,{templates:y,linkComponent:wi,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const kbs="1.64.0-alpha.6";function Obs({errorMsg:e,validationErrors:t}){const n=typeof e=="string"?e:e!=null?String(e):void 0,r=n?.includes("Invalid schema for function"),s=n?.includes("validation issue")||t&&t.length>0,a=()=>s?"Template installation completed but some validation issues remain. The template may still be functional, but you should review and fix these issues.":r?"There was an issue with the AI model configuration. This may be related to the selected model or AI SDK version compatibility.":"An unexpected error occurred during template installation.",i=()=>s?{icon:o.jsx(ac,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(TYt,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(WQ,{className:"text-neutral3 mb-8 content-center space-y-4",children:[o.jsxs("div",{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[l,o.jsxs("div",{className:"space-y-2 text-center",children:[o.jsx("p",{className:"text-ui-md text-neutral5 font-medium",children:c}),o.jsx("p",{className:"text-ui-md text-neutral3",children:a()})]})]}),t&&t.length>0&&o.jsxs("details",{className:"text-xs",children:[o.jsxs("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:["Show Validation Issues (",t.length,")"]}),o.jsx("div",{className:"mt-4 max-h-60 space-y-2 overflow-auto rounded bg-gray-100 p-3 text-left text-xs dark:bg-gray-800",children:t.map((u,d)=>o.jsxs("div",{className:"border-l-2 border-red-400 pl-2",children:[o.jsx("div",{className:"font-medium text-red-600 dark:text-red-400",children:u.type==="typescript"?"🔴 TypeScript Error":"⚠️ Lint Error"}),o.jsx("div",{className:"mt-1 font-mono text-xs wrap-break-word whitespace-pre-wrap text-gray-700 dark:text-gray-300",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-xs",children:[o.jsx("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:"Show Details"}),o.jsx("div",{className:"mt-4 max-h-60 overflow-auto rounded bg-gray-100 p-3 text-left font-mono text-xs dark:bg-gray-800",children:o.jsx("div",{className:"wrap-break-word whitespace-pre-wrap",children:n})})]})]})}function _bs({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:s,handleInstallTemplate:a,handleVariableChange:i,isLoadingEnvVars:l,isInstalling:c,defaultModelProvider:u,defaultModelId:d,onModelUpdate:f}){return o.jsx(WQ,{children:o.jsxs("div",{className:"mx-auto my-4 grid max-w-[40rem] gap-8 p-4 lg:p-8",children:[o.jsxs("h2",{className:K("text-neutral4 text-header-sm font-semibold flex items-center gap-2","[&>svg]:w-[1.2em] [&_svg]:h-[1.2em] [&_svg]:opacity-70"),children:["Install Template ",o.jsx(Qlt,{})]}),o.jsx(Pc,{name:"template-provider",options:e,label:"Template AI Model Provider",onValueChange:n,value:t,placeholder:"Select",layout:"horizontal"}),t&&Object.entries(r||{}).length>0&&o.jsxs(o.Fragment,{children:[o.jsx("h3",{className:"text-neutral3 text-ui-md",children:"Set required Environmental Variables"}),o.jsx("div",{className:"grid grid-cols-[1fr_1fr] items-start gap-4",children:l?o.jsxs("div",{className:K("flex items-center justify-center col-span-2 text-neutral3 text-ui-sm gap-4","[&_svg]:opacity-50 [&_svg]:w-[1.1em] [&_svg]:h-[1.1em]","animate-in fade-in duration-300"),children:[o.jsx(Ut,{})," Loading variables..."]}):Object.entries(r).map(([p,h])=>o.jsxs(g.Fragment,{children:[o.jsx(Bg,{name:`env-${p}`,labelIsHidden:!0,label:"Key",value:p,disabled:!0,className:"w-full"}),o.jsx(Bg,{name:p,labelIsHidden:!0,label:"Value",value:h,onChange:i,errorMsg:s.includes(p)?"Value is required.":"",autoComplete:"off",className:"w-full"})]},p))}),o.jsxs("div",{className:"border-border1 relative mt-3.5 border-t pt-12",children:[o.jsx("div",{className:"bg-surface2 text-ui-sm text-neutral3 absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full",children:"And"}),o.jsx("h3",{className:"text-neutral4 text-ui-lg",children:"Set AI Model for Template Installation"}),o.jsx("p",{className:"text-neutral3 text-ui-md mt-2 mb-8",children:"This model will be used by the workflow to process and install the template"}),o.jsx(L3t,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(oe,{className:K("flex items-center gap-2 mt-4 justify-center text-ui-md w-full bg-surface5 min-h-10 rounded-lg text-neutral5 hover:bg-surface6 transition-colors","[&>svg]:w-[1.1em] [&_svg]:h-[1.1em] [&_svg]:text-neutral5"),onClick:a,disabled:!t||!u||!d||s.length>0||c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(Ut,{className:"h-4 w-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(Fd,{})]})})]})})}function Cbs({title:e,description:t,githubUrl:n,isLoading:r,infoData:s,templateSlug:a}){const i=a?`feat/install-template-${a}`:"feat/install-template-[slug]";return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:K("grid mt-8 items-center"),children:o.jsxs("div",{className:K("text-header-lg flex items-center gap-3","[&>svg]:w-[1.2em] [&>svg]:h-[1.2em] [&>svg]:opacity-50",{"[&>svg]:opacity-20":r}),children:[o.jsx(oy,{}),o.jsx("h2",{className:K({"bg-surface4 flex rounded-lg min-w-[50%]":r}),children:r?o.jsx(o.Fragment,{children:" "}):e})]})}),o.jsxs("div",{className:"grid gap-x-24 lg:grid-cols-[1fr_1fr]",children:[o.jsxs("div",{className:"grid",children:[o.jsx("p",{className:K("mb-4 text-ui-md text-neutral4 mt-2 leading-7",{"bg-surface4 rounded-lg ":r}),children:r?o.jsx(o.Fragment,{children:" "}):t}),!r&&a&&o.jsxs("div",{className:K("bg-surface2 border border-surface4 rounded-lg p-4 mb-4","flex items-start gap-3"),children:[o.jsx("div",{className:"mt-0.5 shrink-0",children:o.jsx(km,{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(o0e,{className:"text-neutral4 h-[1em] w-[1em]"}),o.jsx("span",{className:"text-ui-md text-neutral5 font-medium",children:"A new Git branch will be created"})]}),o.jsxs("div",{className:"text-ui-sm text-neutral4 space-y-1",children:[o.jsxs("div",{children:[o.jsx("span",{className:"font-medium",children:"Branch name:"})," ",o.jsx("code",{className:"bg-surface3 text-ui-sm rounded px-1.5 py-0.5 font-mono",children:i})]}),o.jsx("div",{children:"This ensures safe installation with easy rollback if needed. Your main branch remains unchanged."})]})]})]}),n&&o.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"text-neutral3 text-ui-md hover:text-neutral5 mt-auto flex items-center gap-2",children:[o.jsx(HZ,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(WTe,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function att(e){switch(e){case"running":return o.jsx(Ut,{size:"sm","aria-hidden":!0});case"success":return o.jsx(Qr,{"aria-hidden":!0});case"failed":return o.jsx(or,{"aria-hidden":!0});default:return null}}function Ebs(){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 Tbs({status:e,variant:t}){return t==="plain"?o.jsx("span",{className:K("flex size-4 items-center justify-center self-center [&>svg]:size-4",Gr.colors,{"[&>svg]:text-positive1":e==="success","[&>svg]:text-negative1":e==="failed"}),children:e==="pending"?o.jsx(Ebs,{}):att(e)}):o.jsx("span",{className:K("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",Gr.colors,Gr.transform,Gr.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:att(e)})}function jbs({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",Gr.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",Gr.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",Gr.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(Tbs,{status:e.status,variant:r})]})}function Nbs({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:K(n),children:t.map((r,s)=>o.jsx(jbs,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function Ibs({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",Gr.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",Gr.colors,Gr.transform,Gr.shadow,{"border border-dashed border-neutral2":r.status==="pending","bg-accent1Dark text-notice-success-fg shadow-glow-accent1 scale-110":r.status==="success","bg-accent2Dark text-notice-destructive-fg shadow-glow-accent2 scale-110":r.status==="failed"}),children:r.status==="running"?o.jsx(Ut,{}):s+1})},r.id))}),o.jsxs("div",{className:K("text-center text-xs text-neutral3",Gr.colors),children:[n," of ",t," steps completed"]})]})}function Abs({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",a=t?.payload?.workflowState,i=t?.payload?.currentStep,l=t?.error,c=a?.steps||{},u=Object.keys(c).length>0,d=v=>v==="input"||v.endsWith(".input")||v.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(v)||/[0-9a-f]{8,}/.test(v)?!1:r?.allSteps?v in r.allSteps:!0,f=Object.entries(c).filter(([v,y])=>d(v)),p=f.length,h=()=>{switch(s){case"initializing":return"Preparing template installation...";case"processing":return`Installing ${e} template`;case"completed":return"Template installation completed!";case"error":return"Template installation failed";default:return"Installing template..."}},m=f.map(([v,y])=>({id:v,status:y?.status,description:y?.description,title:v.charAt(0).toUpperCase()+v.slice(1).replace(/-/g," "),isActive:i?.id===v}));return o.jsxs(WQ,{className:"text-neutral3 mb-8 content-center space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h3",{className:"text-neutral5 text-lg font-semibold",children:h()}),(t?.runId||n)&&o.jsxs("div",{className:"text-ui-sm text-neutral3 mt-2",children:["Run ID: ",t?.runId??n]})]}),u&&p>0&&!["error"].includes(s)&&o.jsx("div",{className:"mx-auto w-full max-w-[30rem] px-6",children:o.jsx(Ibs,{steps:m})}),l&&s==="error"&&o.jsxs("div",{className:K("rounded-lg text-neutral5 p-6 flex items-center gap-3 text-ui-md bg-red-500/10","[&>svg]:w-6 [&>svg]:h-6 [&>svg]:opacity-70 [&>svg]:text-red-500"),children:[o.jsx(_Xt,{}),l||"Something went wrong"]}),u&&o.jsx(Nbs,{steps:m,currentStep:i,className:"pb-4"}),!u&&s==="initializing"&&o.jsxs("div",{className:"text-neutral3 grid justify-items-center gap-4 text-center text-sm",children:[o.jsx(Ut,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function Rbs({name:e,installedEntities:t}){return o.jsxs(WQ,{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(Qlt,{}),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(WTe,{data:t})]})}function Pbs(){const{templateSlug:e}=mr(),[t,n]=hi(),[r,s]=g.useState(""),[a,i]=g.useState(""),[l,c]=g.useState(""),[u,d]=g.useState({}),[f,p]=g.useState([]),[h,m]=g.useState(null),[v,y]=g.useState(!1),[b,x]=g.useState(""),[S,k]=g.useState(!1),[_,C]=g.useState(!1),[T,E]=g.useState([]),{data:N,isLoading:I}=bnr({repoOrSlug:e,owner:"mastra-ai"}),R=kbs?.includes("beta")??!1?"beta":"main",{data:L,isLoading:D}=xnr({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:R}),{data:F,isLoading:H}=wnr(),{mutateAsync:B,isPending:z}=Snr(),{mutateAsync:V}=knr(),{streamInstall:M,streamResult:G,isStreaming:U}=_nr(F),{observeInstall:$,streamResult:q,isStreaming:Z}=Cnr(F);g.useEffect(()=>{const te=t.get("runId");te&&!v&&!h&&!U&&!Z&&(console.info("🔄 Checking completed run after hot reload:",{runId:te}),x(te),V({runId:te}).then(se=>{const pe=se.snapshot;if(pe?.status==="success"&&pe?.result?.success)y(!0);else if(pe?.result?.success===!1)if(pe?.result?.validationResults&&!pe?.result?.validationResults?.valid&&pe?.result?.validationResults?.remainingErrors>0){const{remainingErrors:Se,errors:ve}=pe.result.validationResults,ke=`Template installation completed but ${Se} validation issue${Se>1?"s":""} remain unresolved.`;m(ke),E(ve||[])}else{const Se=pe?.result?.message||pe?.result?.error||"Template installation failed";m(typeof Se=="string"?Se:String(Se))}}).catch(se=>{console.error("❌ Failed to fetch run details:",se),m("Failed to retrieve installation status after reload")}))},[t,v,h,U,Z,V]),g.useEffect(()=>{const te=t.get("runId"),se=t.get("resume"),pe=t.get("provider");if(te&&se==="true"&&pe&&!U&&!Z&&!S&&!_&&F){x(te),k(!0);try{V({runId:te}).then(ce=>{if(ce.snapshot?.status==="running")return $.mutateAsync({runId:te})}).then(()=>{n(ce=>{const Se=new URLSearchParams(ce);return Se.delete("resume"),Se})}).catch(ce=>{console.error("❌ Failed to resume template installation:",ce),ce.message?.includes("404")||ce.message?.includes("not found")?m("Template installation run not found. It may have expired or been completed."):m("Failed to resume template installation. Please try again.")})}catch(ce){console.error("❌ Auto-resume failed with error:",ce),m("Failed to resume template installation. Please refresh and try again.")}}},[t,e,U,Z,S,_,F,V,$,n]);const Y=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],ne=[{key:"tools",label:"Tools",value:N?.tools?.length?N.tools.map(te=>te).join(", "):"n/a",icon:o.jsx(Ff,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(te=>te).join(", "):"n/a",icon:o.jsx(Ti,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(te=>te).join(", "):"n/a",icon:o.jsx(aI,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(kg,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(sI,{})}],J=[{...ne[0]},{...ne[1]},{...ne[2]}].filter(te=>te.value!=="n/a");g.useEffect(()=>{L&&d(L)},[L]),g.useEffect(()=>{const te=G||q;te?.phase==="error"&&te?.error&&m(typeof te.error=="string"?te.error:String(te.error))},[G?.phase,G?.error,q?.phase,q?.error]);const ee=te=>{s(te)},re=async te=>(i(te.provider),c(te.modelId),{message:"Model updated successfully"}),le=async()=>{const te=Object.entries(u).reduce((se,[pe,ce])=>(ce===""&&se.push(pe),se),[]);if(te.length>0){p(te);return}if(N){m(null),y(!1),x(""),C(!0);try{const pe={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:R,slug:N.slug,variables:u},{runId:ce}=await B({});x(ce),n(Se=>{const ve=new URLSearchParams(Se);return ve.set("runId",ce),ve.set("resume","true"),ve.set("provider",r||"openai"),ve}),await M.mutateAsync({inputData:pe,selectedModel:{provider:a,modelId:l},runId:ce})}catch(se){C(!1),m(se?.message||"Template installation failed"),console.error("Template installation failed",se)}}},X=te=>{const{name:se,value:pe}=te.target;pe.trim()===""?p(ce=>[...ce,se]):p(ce=>ce.filter(Se=>Se!==se)),d(ce=>({...ce,[se]:pe}))};return o.jsx(_s,{children:o.jsx("div",{className:K("w-full lg:px-12 h-full overflow-y-scroll"),children:o.jsxs("div",{className:"mx-auto grid w-full max-w-[80rem] gap-y-4 p-6",children:[o.jsx(Cbs,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:ne,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(U||Z)&&o.jsx(Abs,{name:N.title,streamResult:Z?q:G,runId:b,workflowInfo:F}),v&&o.jsx(Rbs,{name:N.title,installedEntities:J,linkComponent:wi}),h&&o.jsx(Obs,{errorMsg:h,validationErrors:T.length>0?T:G?.validationResults?.errors||q?.validationResults?.errors}),!U&&!Z&&!v&&!h&&o.jsx(_bs,{providerOptions:Y,selectedProvider:r,onProviderChange:ee,variables:u,setVariables:d,errors:f,setErrors:p,handleInstallTemplate:le,handleVariableChange:X,isLoadingEnvVars:D||H,isInstalling:z,defaultModelProvider:a,defaultModelId:l,onModelUpdate:re})]})]})})})}const $bs=()=>{const{toolId:e,agentId:t}=mr();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(Crs,{toolId:e,agentId:t})})},Mbs=()=>{const{toolId:e}=mr();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(Mvs,{toolId:e})})};function Dbs(){const{data:e,isLoading:t,error:n}=Wy(),[r,s]=g.useState("");return n&&Ss(n)?o.jsx(ir,{children:o.jsx(Gs,{})}):n&&ks(n)?o.jsx(ir,{children:o.jsx(Fs,{resource:"workflows"})}):n?o.jsx(ir,{children:o.jsx(Ui,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(ir,{children:o.jsx(hWr,{})}):o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsxs(Vt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(ah,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsxs(oe,{as:wi,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(KN,{}),"Schedules"]})]})}),o.jsx(pWr,{workflows:e||{},isLoading:t,search:r})]})}const Lbs={active:"bg-accent1",paused:"bg-accent3"},Fbs={active:"text-accent1",paused:"text-accent3"},VVt=({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 ${Lbs[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${Fbs[e]}`,children:e})]}),wj=e=>!e||e<=0?"—":new Date(e).toLocaleString(),s2=e=>{if(!e||e<=0)return"—";const t=e-Date.now(),n=Math.abs(t),r=Math.floor(n/1e3);if(r<60)return t>=0?`in ${r}s`:`${r}s ago`;const s=Math.floor(r/60);if(s<60)return t>=0?`in ${s}m`:`${s}m ago`;const a=Math.floor(s/60);if(a<24)return t>=0?`in ${a}h`:`${a}h ago`;const i=Math.floor(a/24);return t>=0?`in ${i}d`:`${i}d ago`};function HVt({status:e}){const{icon:t,color:n}=zbs(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 zbs(e){switch(e){case"success":return{icon:o.jsx(Qr,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(or,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(Ut,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(mV,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(Mc,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(r1,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const itt="auto auto auto auto 1fr";function Bbs(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 Ubs(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 qbs=3e4,Vbs=5*6e4;function Hbs({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=cn(),c=h=>!!(n&&h.runId&&h.outcome!=="failed"),u=e.filter(c).length,{containerRef:d,getRowProps:f}=wo({count:u});let p=-1;return t?o.jsx(Pl,{columns:itt}):e.length===0?o.jsx(me,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(be,{columns:itt,className:"min-w-0",scrollRef:d,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"Run"}),o.jsx(be.TopCell,{children:"Status"}),o.jsx(be.TopCell,{children:"Started"}),o.jsx(be.TopCell,{children:"Duration"}),o.jsx(be.TopCell,{children:" "})]}),e.map(h=>{const m=h.actualFireAt-h.scheduledFireAt,v=Ubs(m),y=`Scheduled ${wj(h.scheduledFireAt)} — published ${wj(h.actualFireAt)} (drift ${v})`,b=h.outcome==="failed",x=b?h.error:h.run?.error,S=Math.abs(m),k=!b&&S>qbs&&S<=Vbs,_=`${h.scheduleId}-${h.runId}-${h.actualFireAt}`,C=c(h);C&&(p+=1);const T=o.jsx("span",{className:C?"text-accent1 text-ui-sm font-mono whitespace-nowrap":"text-neutral3 text-ui-sm font-mono whitespace-nowrap",children:h.runId}),E=o.jsxs(o.Fragment,{children:[o.jsx(be.Cell,{children:T}),o.jsx(be.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(ac,{size:14}),"publish failed"]}):h.run?o.jsx(HVt,{status:h.run.status}):o.jsx("span",{className:"text-ui-sm text-neutral3 inline-flex items-center gap-1.5 whitespace-nowrap",children:"pending"}),x?o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(ac,{size:14})})}),o.jsx(vn,{children:x})]}):null]})}),o.jsx(be.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:y,children:s2(h.actualFireAt)}),k?o.jsxs(yn,{children:[o.jsx(gn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(ac,{size:14})})}),o.jsxs(vn,{children:["Published ",v," after the scheduled fire time"]})]}):null]})}),o.jsx(be.Cell,{children:h.run?o.jsx("span",{children:Bbs(h.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(be.Cell,{children:" "})]});return C?o.jsx(be.RowLink,{to:l.workflowRunLink(n,h.runId),LinkComponent:i,...f(p),children:E},_):o.jsx(be.RowStatic,{children:E},_)}),o.jsx(be.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const Wbs=e=>{const t=Qe();return yt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},ott=25,Zbs=e=>{const t=Qe(),{inView:n,setRef:r}=tC(),s=K1({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:ott,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<ott))return u.triggers[u.triggers.length-1].actualFireAt},refetchInterval:u=>(u.state.data?.pages.flatMap(p=>p.triggers)??[]).some(p=>p.run?p.run.status==="pending"||p.run.status==="running"||p.run.status==="waiting":p.outcome==="published")?5e3:!1}),a=s.data?.pages.flatMap(u=>u?.triggers??[])??[],{hasNextPage:i,isFetchingNextPage:l,fetchNextPage:c}=s;return g.useEffect(()=>{n&&i&&!l&&c()},[n,i,l,c]),{...s,data:a,setEndOfListElement:r}},Gbs=e=>{const t=Qe(),n=Lr();return An({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"]}),Be.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{Be.error(r.message)}})};function r8({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(me,{variant:"ui-xs",className:"text-neutral4 tracking-wide uppercase",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function Qbs(){const{scheduleId:e}=mr(),{paths:t}=cn(),{data:n,error:r}=Wbs(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=Zbs(e),d=Gbs(e);if(r&&Ss(r))return o.jsx(ir,{children:o.jsx(Gs,{})});if(r&&ks(r))return o.jsx(ir,{children:o.jsx(Fs,{resource:"schedules"})});if(r)return o.jsx(ir,{children:o.jsx(Ui,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,p=n?.agentId;return o.jsxs(Vt,{children:[o.jsx(Vt.TopArea,{children:o.jsx(Vt.Row,{className:"justify-end",children:o.jsxs(Vt.Column,{className:"flex justify-end gap-2",children:[o.jsxs(oe,{as:wi,to:t.schedulesLink(),variant:"ghost",children:[o.jsx(gl,{}),"Back to schedules"]}),f?o.jsx(oe,{as:wi,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(oe,{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(SV,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(Dc,{}),"Resume"]})}):null]})})}),n?o.jsxs("div",{className:"grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-6 overflow-hidden",children:[o.jsxs("div",{className:"border-border1 flex h-fit flex-col gap-4 rounded-md border p-4",children:[o.jsx(r8,{label:p?"Agent":"Workflow",children:f?o.jsx(wi,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):p?o.jsx(wi,{to:t.agentLink(p),className:"text-accent1 hover:underline",children:p}):"—"}),o.jsxs(r8,{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(r8,{label:"Status",children:o.jsx(VVt,{status:n.status})}),o.jsx(r8,{label:"Next fire",children:o.jsx("span",{title:wj(n.nextFireAt),children:s2(n.nextFireAt)})})]}),o.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[o.jsx(me,{variant:"ui-md",className:"mb-3",children:"Trigger history"}),i?o.jsx(Ui,{title:"Failed to load trigger history",message:i.message}):o.jsx(Hbs,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const ltt="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function Ybs({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=cn(),a=g.useMemo(()=>{const c=n.toLowerCase();return c?e.filter(u=>u.id.toLowerCase().includes(c)||(u.workflowId??u.agentId??"").toLowerCase().includes(c)):e},[e,n]),{containerRef:i,getRowProps:l}=wo({count:a.length});return t?o.jsx(Pl,{columns:ltt}):o.jsxs(be,{columns:ltt,variant:"striped",className:"min-w-0",scrollRef:i,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"Target"}),o.jsx(be.TopCell,{children:"Schedule ID"}),o.jsx(be.TopCell,{children:"Cron"}),o.jsx(be.TopCell,{children:"Status"}),o.jsx(be.TopCell,{children:"Next fire"}),o.jsx(be.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(be.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(be.NoMatch,{message:"No schedules configured"}):null,a.map((c,u)=>o.jsxs(be.RowLink,{to:r.scheduleLink(c.id),LinkComponent:s,...l(u),children:[o.jsx(be.NameCell,{children:c.workflowId??c.agentId}),o.jsx(be.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(be.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(be.Cell,{children:o.jsx(VVt,{status:c.status})}),o.jsx(be.Cell,{children:o.jsx("span",{className:"whitespace-nowrap",title:wj(c.nextFireAt),children:s2(c.nextFireAt)})}),o.jsx(be.Cell,{children:c.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(HVt,{status:c.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:wj(c.lastFireAt),children:c.lastFireAt?s2(c.lastFireAt):""})]}):c.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:wj(c.lastFireAt),children:s2(c.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},c.id))]})}function Kbs({workflowId:e}={}){const{data:t,isLoading:n,error:r}=sSe(e?{workflowId:e}:{}),[s,a]=g.useState("");return r?o.jsx(Ui,{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(ah,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(Ybs,{schedules:t??[],isLoading:n,search:s})})]})}function Xbs(){const[e]=hi(),t=e.get("workflowId")??void 0,{error:n}=sSe(t?{workflowId:t}:{});return n&&Ss(n)?o.jsx(ir,{children:o.jsx(Gs,{})}):n&&ks(n)?o.jsx(ir,{children:o.jsx(Fs,{resource:"schedules"})}):o.jsx(Vt,{children:o.jsx("div",{className:"h-full",children:o.jsx(Kbs,{workflowId:t})})})}function Jbs({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=jOe({stepGraph:e}),[a,i]=g.useState(!1),[l,c,u]=C_t(r),[d]=E_t(s),{edgeTypes:f,nodeTypes:p,styledEdges:h}=PLt({edges:d,workflowName:n,stepGraph:e});return g.useEffect(()=>{if(t){const m=setTimeout(()=>{i(!0)},500);return()=>clearTimeout(m)}},[t]),o.jsx("div",{className:"bg-surface1 relative h-full w-full",children:a?o.jsxs(__t,{nodes:l,edges:h,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:p,onNodesChange:u,children:[o.jsx(mje,{position:"bottom-left"}),o.jsx(j_t,{variant:fy.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:o.jsx(Ut,{})})})}function exs(){const{stepDetail:e,closeStepDetail:t}=SW();return e?o.jsxs("div",{className:"flex h-full flex-col","data-testid":"workflow-step-detail-panel",children:[o.jsxs("div",{className:"border-border1 bg-surface1 flex items-center justify-between border-b px-4 py-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[e.type==="map-config"&&o.jsx(wx,{className:"h-4 w-4",style:{color:zu.map}}),e.type==="nested-graph"&&o.jsx(Uc,{className:"h-4 w-4",style:{color:zu.workflow}}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx(me,{variant:"ui-md",className:"text-neutral6 font-medium",children:e.type==="map-config"?`${e.stepName} Config`:`${e.stepName} Workflow`}),e.type==="map-config"&&e.stepId&&e.stepId!==e.stepName&&o.jsx(me,{variant:"ui-xs",className:"text-neutral3",children:e.stepId})]})]}),o.jsx("button",{onClick:t,className:"hover:bg-surface3 rounded p-1 transition-colors","aria-label":"Close",children:o.jsx(or,{className:"text-neutral3 h-4 w-4"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(e2,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(TOe,{children:o.jsx(Jbs,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function txs(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function nxs(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 rxs({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:o.jsxs("div",{className:"border-border1 bg-surface4 space-y-5 rounded-lg border p-5","data-testid":"workflow-suspended-steps",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs(me,{as:"p",variant:"ui-md",className:"text-neutral6 flex items-center gap-2 font-semibold",children:[o.jsx(He,{children:o.jsx(mV,{})}),"Step suspended"]}),o.jsx(St,{variant:"yellow",children:"Needs input"})]}),e.map((s,a)=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const l=i?.resumeSchema?vm(Tx(i.resumeSchema)):hf(cr(),Of());return o.jsx(sxs,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function sxs({step:e,stepSchema:t,description:n,isStreaming:r,onResume:s}){const[a,i]=g.useState(!1);return o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(me,{as:"p",variant:"ui-md",className:"text-neutral6 truncate font-medium",children:e.stepId}),n&&o.jsx(me,{as:"p",variant:"ui-sm",className:"text-neutral3",children:n})]}),e.suspendPayload&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs(me,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(He,{children:o.jsx(mXt,{})}),"The step is asking"]}),o.jsxs(Fc,{open:a,onOpenChange:i,children:[o.jsxs(cc,{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(He,{children:o.jsx(Ur,{className:K("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(me,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:nxs(e.suspendPayload,e.stepId)})]}),o.jsx(me,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:txs(e.suspendPayload)})]}),o.jsx(uc,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Zr,{data:e.suspendPayload,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs(me,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(He,{children:o.jsx(yXt,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(aU,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(Dc,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:l=>{const c=e.stepId?.split(".");s({stepId:c,runId:e.runId,suspendPayload:e.suspendPayload,resumeData:l,isLoading:!1})}})})]})]})}function axs(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext(Ul),{runId:a}=mr(),i=M_t(e,r??""),l=AJn(),c=!!a,u=t?.status==="suspended",f=!!(a&&r&&a===r)&&e?.status==="suspended";return s||!n||i.length===0||c&&!u&&!f?null:o.jsx("div",{"data-testid":"workflow-suspended-overlay",className:"animate-in fade-in-0 slide-in-from-top-2 zoom-in-95 absolute top-2 right-2 z-20 max-h-[calc(100%-1rem)] w-[380px] max-w-[calc(100%-1rem)] overflow-y-auto rounded-lg shadow-lg duration-300",children:o.jsx(rxs,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const ixs=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.97865 4.57004C8.22604 4.75795 8.27426 5.11082 8.08635 5.35821L6.05486 8.03279C5.94873 8.17251 5.78348 8.25471 5.60803 8.25505C5.43257 8.2554 5.267 8.17385 5.16032 8.03454L3.80937 6.27034C3.6205 6.02369 3.66733 5.67063 3.91398 5.48176C4.16063 5.29288 4.51369 5.33972 4.70257 5.58637L5.6051 6.76498L7.19048 4.67774C7.37839 4.43036 7.73126 4.38213 7.97865 4.57004Z",fill:"currentColor"})]}),oxs=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.89741 4.10293C8.11707 4.32261 8.11706 4.67877 7.89738 4.89843L6.79517 6.00058L7.8962 7.10155C8.11588 7.32122 8.11589 7.67737 7.89623 7.89705C7.67656 8.11673 7.32041 8.11674 7.10073 7.89707L5.99965 6.79605L4.89856 7.89707C4.67889 8.11673 4.32273 8.11672 4.10307 7.89704C3.88341 7.67737 3.88342 7.32121 4.10309 7.10155L5.20413 6.00058L4.10191 4.89843C3.88224 4.67877 3.88223 4.32262 4.10189 4.10294C4.32155 3.88326 4.67771 3.88325 4.89738 4.10292L5.99965 5.20511L7.10191 4.10291C7.32159 3.88325 7.67774 3.88326 7.89741 4.10293Z",fill:"currentColor"})]}),lxs=e=>e.includes("."),cxs=e=>e==="input"||e.endsWith(".input"),uxs=1;function dxs(e){return`${Number((e/1e3).toPrecision(3))}s`}function fxs(e,t){const n=Object.entries(e).filter(([i])=>!cxs(i));if(n.length===0)return[];const r=Math.min(...n.map(([,i])=>i.startedAt)),s=Math.max(...n.map(([,i])=>i.endedAt??t)),a=Math.max(s-r,1);return n.map(([i,l])=>{const c=l.endedAt===void 0,d=(l.endedAt??t)-l.startedAt,f=(l.startedAt-r)/a*100,p=Math.max(d/a*100,uxs);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:p,durationMs:d,isRunning:c,isNestedEntry:lxs(i)}})}const pxs=({status:e})=>o.jsxs(He,{children:[e==="success"&&o.jsx(ixs,{className:"text-accent1"}),e==="failed"&&o.jsx(oxs,{className:"text-accent2"}),e==="suspended"&&o.jsx(mV,{className:"text-accent3"}),e==="waiting"&&o.jsx(Npe,{className:"text-accent5"}),e==="skipped"&&o.jsx(Npe,{className:"text-icon3"}),e==="running"&&o.jsx(qs,{className:"text-accent6 animate-spin"})]}),hxs={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function WVt(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const ctt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},mxs=e=>{const t=e;return _Lt({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},gxs=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=mxs(e.step),u=e.status==="running",d=!e.isNestedEntry;return o.jsxs("div",{role:"button",tabIndex:0,"data-testid":"workflow-timeline-row","data-workflow-step-key":e.stepId,"data-workflow-step-active":n?"true":void 0,"data-workflow-step-hovered":r?"true":void 0,"data-workflow-step-nested":e.isNestedEntry?"true":void 0,"aria-pressed":n,"aria-disabled":!d,onMouseEnter:()=>{d&&a(e.stepId)},onMouseLeave:()=>{d&&a(null)},onClick:()=>{d&&s(e.stepId)},onKeyDown:f=>{!d||f.key!=="Enter"&&f.key!==" "||(f.preventDefault(),s(e.stepId))},className:K("grid grid-cols-[auto_auto_auto_minmax(0,10rem)_minmax(0,1fr)_auto_5rem] items-center gap-2 rounded-md border border-transparent px-2 py-1 text-left transition-colors focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-accent1",d&&"cursor-pointer",d&&"hover:bg-surface4",d&&r&&!n&&"border-neutral6 bg-surface4",d&&n&&"border-accent1",e.isNestedEntry&&"cursor-default opacity-55"),children:[o.jsx("div",{className:"flex justify-center",children:o.jsx(pxs,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(oe,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step input",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||i(e)},children:o.jsx(NJt,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(Uq,{indicators:c,className:"shrink-0"})}),o.jsx(me,{as:"span",variant:"ui-sm",className:"text-neutral6 block max-w-full min-w-0 justify-self-stretch overflow-hidden text-left text-ellipsis whitespace-nowrap",children:WVt(e.stepId)}),o.jsx("div",{className:"bg-surface4 relative h-2 min-w-0 rounded",children:o.jsx("div",{"data-testid":"workflow-timeline-bar","data-offset":String(e.offsetPct),"data-width":String(e.widthPct),className:`absolute top-0 h-full rounded ${hxs[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(oe,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step output",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||l(e)},children:o.jsx(TJt,{})})}),o.jsx(me,{as:"span",variant:"ui-sm",className:"text-neutral3 w-20 justify-self-end text-right tabular-nums",children:dxs(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function vxs(){const{steps:e}=K4(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=AH(),[a,i]=g.useState(()=>Date.now()),[l,c]=g.useState(!1),[u,d]=g.useState(null),f=g.useRef(null);pbt(f,{enabled:!l});const p=fxs(e,a),h=p.some(m=>m.isRunning);return g.useEffect(()=>{if(!h)return;const m=setInterval(()=>i(Date.now()),100);return()=>clearInterval(m)},[h]),g.useEffect(()=>{if(l||p.length===0)return;const m=f.current;m&&(m.scrollTop=m.scrollHeight)},[l,p.length]),p.length===0?null:o.jsxs(o.Fragment,{children:[o.jsx("div",{"data-testid":"workflow-timeline",className:"pointer-events-none absolute right-0 bottom-0 z-20 px-2 pb-2",style:{left:"var(--workflow-left-panel-width, 0px)"},children:o.jsxs("div",{className:"rounded-studio-panel border-border1/50 bg-surface3 pointer-events-auto flex max-h-64 w-full min-w-0 flex-col gap-3 overflow-hidden border p-4 shadow-lg",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3",children:[o.jsx(me,{as:"p",variant:"ui-md",className:"text-neutral3",children:"Timeline"}),o.jsx("button",{type:"button","aria-label":l?"Expand timeline":"Collapse timeline","aria-expanded":!l,onClick:()=>c(m=>!m),className:"text-neutral3 hover:bg-surface4 hover:text-neutral6 rounded-md p-1 transition-colors",children:o.jsx(Xs,{className:K("h-4 w-4 transition-transform",l&&"-rotate-90")})})]}),!l&&o.jsx("div",{ref:f,"data-testid":"workflow-timeline-list",className:"flex min-h-0 flex-col gap-2 overflow-y-auto",children:p.map((m,v)=>o.jsx(gxs,{row:m,index:v,isSelected:t===m.stepId,isHovered:n===m.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:y=>d({type:"input",stepId:y.stepId,data:ctt(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:ctt(y.step.output)})},`timeline-item-${m.stepId}-${v}`))})]})}),o.jsx(vr,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(L_t,{data:u.data,title:`${WVt(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const yxs=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=SW();return o.jsxs("div",{className:"flex h-full min-h-0",children:[o.jsx("div",{className:"flex h-full min-h-0 flex-1 flex-col",children:o.jsxs("div",{className:"relative min-h-0 flex-1 p-2 pb-0",children:[o.jsx(BLt,{workflowId:e,workflow:t,isLoading:n}),o.jsx(axs,{}),o.jsx(vxs,{})]})}),r&&o.jsx("div",{className:"border-border1 min-h-0 w-[420px] overflow-hidden border-l",children:o.jsx(exs,{})})]})},utt=()=>{const{workflowId:e}=mr(),{data:t,isLoading:n,error:r}=a4(e);return r&&Ss(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Gs,{})}):r&&ks(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{resource:"workflows"})}):o.jsx(ZOe,{children:o.jsx(yxs,{workflowId:e,workflow:t??void 0,isLoading:n})})};function bxs(e,t){if(e==null)return{};var n,r,s=USt(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function Wxe(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 xxs(e){if(Array.isArray(e))return Wxe(e)}function wxs(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function Sxs(e,t){if(e){if(typeof e=="string")return Wxe(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)?Wxe(e,t):void 0}}function kxs(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
645
645
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Zxe(e){return xxs(e)||wxs(e)||Sxs(e)||kxs()}function UD(e){"@babel/helpers - typeof";return UD=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},UD(e)}function Oxs(e,t){if(UD(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(UD(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function _xs(e){var t=Oxs(e,"string");return UD(t)=="symbol"?t:t+""}function ZVt(e,t,n){return(t=_xs(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function dtt(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 PT(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?dtt(Object(n),!0).forEach(function(r){ZVt(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):dtt(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Cxs(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 Uie={};function Exs(e){if(e.length===0||e.length===1)return e;var t=e.join(".");return Uie[t]||(Uie[t]=Cxs(e)),Uie[t]}function Txs(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2?arguments[2]:void 0,r=e.filter(function(a){return a!=="token"}),s=Exs(r);return s.reduce(function(a,i){return PT(PT({},a),n[i])},t)}function ftt(e){return e.join(" ")}function jxs(e,t){var n=0;return function(r){return n+=1,r.map(function(s,a){return GVt({node:s,stylesheet:e,useInlineStyles:t,key:"code-segment-".concat(n,"-").concat(a)})})}}function GVt(e){var t=e.node,n=e.stylesheet,r=e.style,s=r===void 0?{}:r,a=e.useInlineStyles,i=e.key,l=t.properties,c=t.type,u=t.tagName,d=t.value;if(c==="text")return d;if(u){var f=jxs(n,a),p;if(!a)p=PT(PT({},l),{},{className:ftt(l.className)});else{var h=Object.keys(n).reduce(function(b,x){return x.split(".").forEach(function(S){b.includes(S)||b.push(S)}),b},[]),m=l.className&&l.className.includes("token")?["token"]:[],v=l.className&&m.concat(l.className.filter(function(b){return!h.includes(b)}));p=PT(PT({},l),{},{className:ftt(v)||void 0,style:Txs(l.className,Object.assign({},l.style,s),n)})}var y=f(t.children);return ze.createElement(u,GO({key:i},p),y)}}const Nxs=(function(e,t){var n=e.listLanguages();return n.indexOf(t)!==-1});var Ixs=["language","children","style","customStyle","codeTagProps","useInlineStyles","showLineNumbers","showInlineLineNumbers","startingLineNumber","lineNumberContainerStyle","lineNumberStyle","wrapLines","wrapLongLines","lineProps","renderer","PreTag","CodeTag","code","astGenerator"];function ptt(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function zw(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?ptt(Object(n),!0).forEach(function(r){ZVt(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ptt(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var Axs=/\n/g;function Rxs(e){return e.match(Axs)}function Pxs(e){var t=e.lines,n=e.startingLineNumber,r=e.style;return t.map(function(s,a){var i=a+n;return ze.createElement("span",{key:"line-".concat(a),className:"react-syntax-highlighter-line-number",style:typeof r=="function"?r(i):r},"".concat(i,`
|
|
646
646
|
`))})}function $xs(e){var t=e.codeString,n=e.codeStyle,r=e.containerStyle,s=r===void 0?{float:"left",paddingRight:"10px"}:r,a=e.numberStyle,i=a===void 0?{}:a,l=e.startingLineNumber;return ze.createElement("code",{style:Object.assign({},n,s)},Pxs({lines:t.replace(/\n$/,"").split(`
|
|
647
647
|
`),style:i,startingLineNumber:l}))}function Mxs(e){return"".concat(e.toString().length,".25em")}function QVt(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 YVt(e,t,n){var r={display:"inline-block",minWidth:Mxs(n),paddingRight:"1em",textAlign:"right",userSelect:"none"},s=typeof e=="function"?e(t):e,a=zw(zw({},r),s);return a}function E9(e){var t=e.children,n=e.lineNumber,r=e.lineNumberStyle,s=e.largestLineNumber,a=e.showInlineLineNumbers,i=e.lineProps,l=i===void 0?{}:i,c=e.className,u=c===void 0?[]:c,d=e.showLineNumbers,f=e.wrapLongLines,p=e.wrapLines,h=p===void 0?!1:p,m=h?zw({},typeof l=="function"?l(n):l):{};if(m.className=m.className?[].concat(Zxe(m.className.trim().split(/\s+/)),Zxe(u)):u,n&&a){var v=YVt(r,n,s);t.unshift(QVt(n,v))}return f&d&&(m.style=zw({display:"flex"},m.style)),{type:"element",tagName:"span",properties:m,children:t}}function KVt(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(E9({children:[s],className:Zxe(new Set(t))}));else if(s.children){var a=t.concat(s.properties.className);KVt(s.children,a).forEach(function(i){return n.push(i)})}}return n}function Dxs(e,t,n,r,s,a,i,l,c){var u,d=KVt(e.value),f=[],p=-1,h=0;function m(_,C){var T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return E9({children:_,lineNumber:C,lineNumberStyle:l,largestLineNumber:i,showInlineLineNumbers:s,lineProps:n,className:T,showLineNumbers:r,wrapLongLines:c,wrapLines:t})}function v(_,C){if(r&&C&&s){var T=YVt(l,C,i);_.unshift(QVt(C,T))}return _}function y(_,C){var T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return t||T.length>0?m(_,C,T):v(_,C)}for(var b=function(){var C=d[h],T=C.children[0].value,E=Rxs(T);if(E){var N=T.split(`
|